scip-query 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -1
  3. package/dist/chunk-2GX3TNOW.js +38 -0
  4. package/dist/{chunk-Y4BBVPRK.js → chunk-35TZERMO.js} +2 -2
  5. package/dist/{chunk-PPAT3XUL.js → chunk-43QUXX3E.js} +2 -2
  6. package/dist/{chunk-O27267B6.js → chunk-45XOH33S.js} +2 -2
  7. package/dist/{chunk-SQJ72PQW.js → chunk-4MFMTEJ4.js} +5 -5
  8. package/dist/chunk-4XTPZ5CR.js +9 -0
  9. package/dist/chunk-6JSTKSZH.js +3 -0
  10. package/dist/{chunk-75H6GOND.js → chunk-7ROLM67J.js} +2 -2
  11. package/dist/{chunk-35DURZXI.js → chunk-ABDXTPCT.js} +2 -2
  12. package/dist/{chunk-HYRSGWFX.js → chunk-AV54WZUK.js} +2 -2
  13. package/dist/chunk-AWYKDRYV.js +2 -0
  14. package/dist/{chunk-O56VBJKB.js → chunk-BAMVG4WQ.js} +2 -2
  15. package/dist/{chunk-RPPV6Y4K.js → chunk-BECOMXAL.js} +2 -2
  16. package/dist/{chunk-W3HSUCRG.js → chunk-BJJHBKEC.js} +2 -2
  17. package/dist/{chunk-IZLWLO4X.js → chunk-D5F3IQYP.js} +2 -2
  18. package/dist/{chunk-2TM23JYJ.js → chunk-DDGO34I2.js} +2 -2
  19. package/dist/{chunk-G4IUQW27.js → chunk-DUKRAHV2.js} +2 -2
  20. package/dist/{chunk-MBDBNQBW.js → chunk-EJ65IVPV.js} +2 -2
  21. package/dist/{chunk-MON5XXTG.js → chunk-EMEXMHOP.js} +2 -2
  22. package/dist/{chunk-JYBP5ZIR.js → chunk-FMD46HAG.js} +2 -2
  23. package/dist/{chunk-WENI5ZDR.js → chunk-GTANVH72.js} +2 -2
  24. package/dist/{chunk-FZXN37RN.js → chunk-GWCW25ON.js} +2 -2
  25. package/dist/chunk-GWNE2WJN.js +3 -0
  26. package/dist/{chunk-CSMPXDYE.js → chunk-H4JNB7RT.js} +2 -2
  27. package/dist/{chunk-WGDIA2TU.js → chunk-HOZ3IXZ5.js} +2 -2
  28. package/dist/{chunk-OP5JXGDV.js → chunk-IG6X65MG.js} +2 -2
  29. package/dist/{chunk-KZ2LZBQT.js → chunk-IKMOYFUM.js} +2 -2
  30. package/dist/{chunk-HGO3D2JD.js → chunk-J7IMQRCU.js} +2 -2
  31. package/dist/{chunk-5N5ZC566.js → chunk-K65T4TJS.js} +2 -2
  32. package/dist/{chunk-BTYDBDX5.js → chunk-L2RE5P3X.js} +2 -2
  33. package/dist/{chunk-2DUWNJKE.js → chunk-L2TSLMPT.js} +2 -2
  34. package/dist/{chunk-OC7XDK62.js → chunk-LADYDOS5.js} +2 -2
  35. package/dist/{chunk-Y5BOEWAE.js → chunk-LL5NQB5V.js} +2 -2
  36. package/dist/{chunk-QYBCGCY5.js → chunk-MN54AGZ3.js} +2 -2
  37. package/dist/chunk-MNRKD3WP.js +18 -0
  38. package/dist/chunk-MPBN5DO4.js +2 -0
  39. package/dist/{chunk-IKAJI4SI.js → chunk-NQBMGFFD.js} +2 -2
  40. package/dist/{chunk-LG33DNTZ.js → chunk-NX2YAXVQ.js} +2 -2
  41. package/dist/{chunk-VDHEX6YO.js → chunk-O5A7BTMA.js} +2 -2
  42. package/dist/{chunk-OBPR6E5Z.js → chunk-O5Y3ISO3.js} +2 -2
  43. package/dist/{chunk-WT34AUWL.js → chunk-ODH4FT3P.js} +2 -2
  44. package/dist/{chunk-U3JW5AYG.js → chunk-OINSINYW.js} +2 -2
  45. package/dist/{chunk-FY6RCFDH.js → chunk-OM6JHEW3.js} +2 -2
  46. package/dist/{chunk-DQYG5JHT.js → chunk-OQFPCIXO.js} +2 -2
  47. package/dist/{chunk-BW4VDICR.js → chunk-OSBLECSI.js} +2 -2
  48. package/dist/{chunk-5QSMW5IO.js → chunk-OTTHMUMV.js} +2 -2
  49. package/dist/{chunk-W2I4QAW7.js → chunk-OUXPJ4H5.js} +2 -2
  50. package/dist/{chunk-BBTVIIOI.js → chunk-OWXNDSG3.js} +2 -2
  51. package/dist/{chunk-CKRVVBM6.js → chunk-P4L5QQT5.js} +2 -2
  52. package/dist/{chunk-E5HPTSRD.js → chunk-POGZSZPX.js} +2 -2
  53. package/dist/{chunk-V7MX6YUF.js → chunk-PV3GKBO5.js} +2 -2
  54. package/dist/{chunk-KWMRY4RN.js → chunk-PZV2PGBR.js} +3 -3
  55. package/dist/{chunk-KWQKWY6M.js → chunk-Q4UM4JJP.js} +2 -2
  56. package/dist/{chunk-7H37Z4UO.js → chunk-QPF7CS5W.js} +2 -2
  57. package/dist/chunk-R4VPIS4D.js +10 -0
  58. package/dist/{chunk-623AZLTE.js → chunk-RDX6WWHN.js} +2 -2
  59. package/dist/{chunk-HJYHSTCP.js → chunk-S43DIBME.js} +2 -2
  60. package/dist/chunk-SALRDXWM.js +121 -0
  61. package/dist/{chunk-PA2MQKXD.js → chunk-SUYCF4SX.js} +2 -2
  62. package/dist/{chunk-SSH2NPYS.js → chunk-SW7LKHRU.js} +2 -2
  63. package/dist/{chunk-HZVG4KID.js → chunk-SWJEREML.js} +2 -2
  64. package/dist/{chunk-TR7C5HOC.js → chunk-T4P27T6S.js} +2 -2
  65. package/dist/chunk-VQWDZ34M.js +928 -0
  66. package/dist/chunk-VXDMXZKC.js +5 -0
  67. package/dist/chunk-W3557RPL.js +3 -0
  68. package/dist/chunk-W3SKYOTF.js +2 -0
  69. package/dist/{chunk-UKUISUS6.js → chunk-XEEQX5X3.js} +2 -2
  70. package/dist/{chunk-7Z5UT44B.js → chunk-YMFHC5J2.js} +2 -2
  71. package/dist/cli.js +3 -1528
  72. package/dist/command-descriptors-AQWWJNTT.js +599 -0
  73. package/dist/direct-navigation-K3CTVVBU.js +3 -0
  74. package/dist/index.js +1 -1
  75. package/dist/postinstall.js +1 -1
  76. package/dist/queries/affected.js +1 -1
  77. package/dist/queries/bottlenecks.js +1 -1
  78. package/dist/queries/call-graph.js +1 -1
  79. package/dist/queries/change-surface.js +1 -1
  80. package/dist/queries/cleanup-plan.js +1 -1
  81. package/dist/queries/co-change.d.ts +2 -0
  82. package/dist/queries/co-change.js +1 -1
  83. package/dist/queries/code.js +1 -1
  84. package/dist/queries/complexity-hotspots.js +1 -1
  85. package/dist/queries/complexity.js +1 -1
  86. package/dist/queries/convergence.js +1 -1
  87. package/dist/queries/coupling.js +1 -1
  88. package/dist/queries/dataflow.js +1 -1
  89. package/dist/queries/dead.js +1 -1
  90. package/dist/queries/decorative-checkers.js +1 -1
  91. package/dist/queries/deps.js +1 -1
  92. package/dist/queries/diff-gate.js +1 -1
  93. package/dist/queries/diff-impact.js +1 -1
  94. package/dist/queries/doc-drift.js +1 -1
  95. package/dist/queries/drift.js +1 -1
  96. package/dist/queries/duplicate-bodies.js +1 -1
  97. package/dist/queries/extract-candidates.js +1 -1
  98. package/dist/queries/fan.js +1 -1
  99. package/dist/queries/health.js +1 -1
  100. package/dist/queries/hierarchy.js +1 -1
  101. package/dist/queries/hotspots.js +1 -1
  102. package/dist/queries/imports.js +1 -1
  103. package/dist/queries/incomplete-migration.js +1 -1
  104. package/dist/queries/index.js +1 -1
  105. package/dist/queries/isolated.js +1 -1
  106. package/dist/queries/locality-candidates.js +1 -1
  107. package/dist/queries/members.js +1 -1
  108. package/dist/queries/methods.js +1 -1
  109. package/dist/queries/not-implemented.js +1 -1
  110. package/dist/queries/outline.js +1 -1
  111. package/dist/queries/passthrough-candidates.js +1 -1
  112. package/dist/queries/plan-context.d.ts +2 -0
  113. package/dist/queries/plan-context.js +1 -1
  114. package/dist/queries/recent-duplicates.js +1 -1
  115. package/dist/queries/redundant-reexports.js +1 -1
  116. package/dist/queries/refs.js +1 -1
  117. package/dist/queries/self-audit.js +1 -1
  118. package/dist/queries/similar-signatures.js +1 -1
  119. package/dist/queries/similar.js +1 -1
  120. package/dist/queries/slice.js +1 -1
  121. package/dist/queries/stale-abstractions.js +1 -1
  122. package/dist/queries/surface.js +1 -1
  123. package/dist/queries/symbols.js +1 -1
  124. package/dist/queries/system.js +1 -1
  125. package/dist/queries/test-quality.js +1 -1
  126. package/dist/queries/trace.js +1 -1
  127. package/dist/queries/twin-ab.js +1 -1
  128. package/dist/queries/twin-drift.js +1 -1
  129. package/dist/queries/unused-imports.js +1 -1
  130. package/dist/queries/unused-params.js +1 -1
  131. package/dist/queries/wrapper-candidates.js +1 -1
  132. package/dist/reindex-worker.js +24 -24
  133. package/dist/reindex.js +36 -36
  134. package/dist/runtime.js +1 -1
  135. package/dist/watch-server.js +4 -4
  136. package/docs/COMMAND_REFERENCE.md +4 -1
  137. package/package.json +1 -1
  138. package/skills/_shared/SKILL.md +1 -1
  139. package/skills/scip-api-impact/SKILL.md +5 -1
  140. package/skills/scip-claim-audit/SKILL.md +1 -0
  141. package/skills/scip-cleanup-audit/SKILL.md +4 -0
  142. package/skills/scip-concrete-plan/SKILL.md +129 -48
  143. package/skills/scip-debug/SKILL.md +6 -1
  144. package/skills/scip-explore/SKILL.md +2 -1
  145. package/skills/scip-integrity-audit/SKILL.md +17 -0
  146. package/skills/scip-maintainability/SKILL.md +6 -1
  147. package/skills/scip-query/SKILL.md +3 -0
  148. package/skills/scip-root-cause/SKILL.md +150 -0
  149. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  150. package/skills/scip-tla-model-system/SKILL.md +7 -9
  151. package/skills/scip-verify/SKILL.md +19 -2
  152. package/dist/chunk-2HCWAL42.js +0 -3
  153. package/dist/chunk-3YEBIYXL.js +0 -38
  154. package/dist/chunk-6TJERPN3.js +0 -2
  155. package/dist/chunk-E7BTIEAY.js +0 -2
  156. package/dist/chunk-EUMETOTD.js +0 -21
  157. package/dist/chunk-GRHA5NGF.js +0 -2
  158. package/dist/chunk-IHD2CHMX.js +0 -10
  159. package/dist/chunk-TFWDJDGO.js +0 -2
  160. package/dist/chunk-U267E6YN.js +0 -120
  161. package/dist/chunk-X566NT42.js +0 -9
package/dist/cli.js CHANGED
@@ -1,1530 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{program as Jp}from"commander";import{realpathSync as VM}from"fs";import{fileURLToPath as Mme}from"url";import{availableParallelism as cte}from"os";import{fileURLToPath as Hy}from"url";import{createRequire as h0}from"module";import{existsSync as xi}from"fs";import{basename as HS,dirname as Mt,extname as nr,join as tn,relative as Si,resolve as Ze,sep as y0}from"path";import{createHash as zM}from"crypto";import{existsSync as KM,mkdirSync as JM,readFileSync as YM}from"fs";import{dirname as Qp,join as ES}from"path";import Xp from"better-sqlite3";var IS=[];function Nr(e){e.groups.length>0&&IS.push(e)}function Yp(e,t){let n=new Set(t.groups);for(let r of IS)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function PS(){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 ne(e,t){let{cache:n,ensure:r}=PS(),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 Nr({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function me(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 Nr({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var GM={clearGroups:["whole-project","source-file"]};function Ar(e){return bi(e,GM)}function bi(e,t){let{cache:n,ensure:r}=PS(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Nr({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}var QM="evidence.db";var XM=["source-facts","definition-exclusions","doc-path-tokens","react-component-behavior-profiles"],Zp=new Set(XM),ZM=25e4,e0=512*1024*1024,t0=5e3,Kc=new WeakMap,n0=ne("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),r0=ne("evidence-project-fingerprint",{clearGroups:["whole-project"]}),Zt="evidence-v1",So="version NOT LIKE 'evidence-%'";function Ge(e){return zM("sha256").update(e).digest("hex")}function Ae(e,t,n){return n0.get(e,t,()=>Ge(n))}function Ye(e){return r0.get(e,"current",()=>{try{let t=JSON.parse(YM(ES(Qp(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"&&t.status!=="partial"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return Ge(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n,status:t.status}))}catch(t){return vo("project fingerprint unavailable",t),null}})}function vo(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function xn(e){if(Kc.has(e))return Kc.get(e)??null;let t=null;try{let n=new Xp(ES(Qp(e.config.dbPath),QM));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
3
- CREATE TABLE IF NOT EXISTS file_evidence (
4
- kind TEXT NOT NULL,
5
- relative_path TEXT NOT NULL,
6
- content_hash TEXT NOT NULL,
7
- version TEXT NOT NULL,
8
- payload TEXT NOT NULL,
9
- PRIMARY KEY (kind, relative_path)
10
- );
11
- CREATE TABLE IF NOT EXISTS project_evidence (
12
- kind TEXT NOT NULL,
13
- cache_key TEXT NOT NULL,
14
- project_fingerprint TEXT NOT NULL,
15
- version TEXT NOT NULL,
16
- payload TEXT NOT NULL,
17
- PRIMARY KEY (kind, cache_key)
18
- );
19
- CREATE TABLE IF NOT EXISTS semantic_callees (
20
- relative_path TEXT NOT NULL,
21
- symbol TEXT NOT NULL,
22
- content_hash TEXT NOT NULL,
23
- deps_digest TEXT NOT NULL,
24
- version TEXT NOT NULL,
25
- payload TEXT NOT NULL,
26
- PRIMARY KEY (relative_path, symbol)
27
- );
28
- CREATE TABLE IF NOT EXISTS semantic_references (
29
- relative_path TEXT NOT NULL,
30
- symbol TEXT NOT NULL,
31
- project_fingerprint TEXT NOT NULL,
32
- version TEXT NOT NULL,
33
- payload TEXT NOT NULL,
34
- PRIMARY KEY (relative_path, symbol)
35
- );
36
- CREATE TABLE IF NOT EXISTS finding_outcome_ledger (
37
- check_name TEXT NOT NULL,
38
- finding_id TEXT NOT NULL,
39
- first_seen INTEGER NOT NULL,
40
- last_seen INTEGER NOT NULL,
41
- times_shown INTEGER NOT NULL,
42
- outcome TEXT NOT NULL,
43
- PRIMARY KEY (check_name, finding_id)
44
- );
45
- `),t={evidence:n,shared:i0(e.config.sharedEvidenceDbPath),readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
46
- WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${So}
47
- ORDER BY version DESC
48
- LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readProjectEvidence:n.prepare("SELECT payload FROM project_evidence WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND version = ?"),readLegacyProjectEvidence:n.prepare(`SELECT payload FROM project_evidence
49
- WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND ${So}
50
- ORDER BY version DESC
51
- LIMIT 1`),writeProjectEvidence:n.prepare("INSERT OR REPLACE INTO project_evidence (kind, cache_key, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
52
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
53
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${So}
54
- ORDER BY version DESC
55
- LIMIT 1`),readCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
56
- WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
57
- WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND ${So}
58
- ORDER BY symbol, version DESC`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
59
- (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
60
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
61
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${So}
62
- ORDER BY version DESC
63
- LIMIT 1`),readReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
64
- WHERE relative_path = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
65
- WHERE relative_path = ? AND project_fingerprint = ? AND ${So}
66
- ORDER BY symbol, version DESC`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
67
- (relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE relative_path = ? AND project_fingerprint != ?"),readFindingOutcomeLedger:n.prepare("SELECT check_name, finding_id, first_seen, last_seen, times_shown, outcome FROM finding_outcome_ledger"),deleteFindingOutcomeLedgerForCheck:n.prepare("DELETE FROM finding_outcome_ledger WHERE check_name = ?"),writeFindingOutcomeLedgerRow:n.prepare(`INSERT INTO finding_outcome_ledger
68
- (check_name, finding_id, first_seen, last_seen, times_shown, outcome) VALUES (?, ?, ?, ?, ?, ?)`)}}catch(n){vo("disabled (open failed)",n)}return Kc.set(e,t),t}function Rn(e,t,n){vo(`disabled (${t})`,n),Kc.set(e,null)}function i0(e){if(!e)return null;try{JM(Qp(e),{recursive:!0});let t=new Xp(e);return t.pragma("journal_mode = WAL"),t.pragma("busy_timeout = 250"),t.pragma("synchronous = NORMAL"),t.exec(`
69
- CREATE TABLE IF NOT EXISTS file_evidence (
70
- kind TEXT NOT NULL,
71
- relative_path TEXT NOT NULL,
72
- content_hash TEXT NOT NULL,
73
- version TEXT NOT NULL,
74
- payload TEXT NOT NULL,
75
- last_accessed_at INTEGER NOT NULL,
76
- PRIMARY KEY (kind, relative_path, content_hash, version)
77
- );
78
- `),{evidence:t,readFileEvidence:t.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:t.prepare(`INSERT INTO file_evidence (kind, relative_path, content_hash, version, payload, last_accessed_at)
79
- VALUES (?, ?, ?, ?, ?, ?)
80
- ON CONFLICT(kind, relative_path, content_hash, version)
81
- DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`)}}catch(t){return vo("shared cache disabled (open failed)",t),null}}function em(e,t,n){vo(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function DS(e,t={}){if(!KM(e))return null;let n;try{n=new Xp(e),n.pragma("busy_timeout = 50"),n.pragma("wal_checkpoint(TRUNCATE)");let r=n.prepare("SELECT COUNT(*) AS count FROM file_evidence").get().count,i=t.maxRows??ZM,o=t.budgetBytes??e0,s=Number(n.pragma("page_size",{simple:!0})),a=Number(n.pragma("page_count",{simple:!0})),c=Number(n.pragma("freelist_count",{simple:!0})),l=Math.max(0,a-c)*s,u=r>0&&l>o?Math.min(r,Math.ceil((l-o)/Math.max(1,l/r))):0,d=Math.max(r-i,u);return d>0&&(n.prepare(`DELETE FROM file_evidence WHERE rowid IN (
82
- SELECT rowid FROM file_evidence ORDER BY last_accessed_at ASC, rowid ASC LIMIT ?
83
- )`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return vo("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function TS(e,t,n,r){let i=xn(e);if(!i)return null;try{let o=i.readFileEvidence.get(t,n,r,Zt)??i.readLegacyFileEvidence.get(t,n,r);if(o?.payload!==void 0)return o.payload;if(!Zp.has(t)||!i.shared)return null;try{return i.shared.readFileEvidence.get(t,n,r,Zt)?.payload??null}catch(s){return em(i,"file_evidence read",s),null}}catch(o){return Rn(e,"file_evidence read",o),null}}function LS(e,t,n,r,i){let o=xn(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,Zt,i),Zp.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,Zt,i,Date.now())}catch(s){em(o,"file_evidence write",s)}}catch(s){Rn(e,"file_evidence write",s)}}function FS(e,t){if(t.length===0)return;let n=xn(e);if(n)try{n.evidence.transaction(()=>{for(let i of t)n.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,Zt,i.payload)})();let r=t.filter(i=>Zp.has(i.kind));if(r.length>0&&n.shared)try{n.shared.evidence.transaction(()=>{for(let i of r)n.shared.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,Zt,i.payload,Date.now())})()}catch(i){em(n,"file_evidence batch write",i)}}catch(r){Rn(e,"file_evidence batch write",r)}}function NS(e,t,n,r){let i=xn(e);if(!i)return null;try{return(i.readProjectEvidence.get(t,n,r,Zt)??i.readLegacyProjectEvidence.get(t,n,r))?.payload??null}catch(o){return Rn(e,"project_evidence read",o),null}}function AS(e,t,n,r,i){let o=xn(e);if(o)try{o.writeProjectEvidence.run(t,n,r,Zt,i)}catch(s){Rn(e,"project_evidence write",s)}}function _S(e,t,n,r){let i=xn(e);if(!i)return new Map;try{let o=i.readCalleesForFile.all(t,n,r,Zt),s=i.readLegacyCalleesForFile.all(t,n,r);return $S([...s,...o])}catch(o){return Rn(e,"semantic_callees bulk read",o),new Map}}function MS(e,t,n){let r=xn(e);if(!r)return new Map;try{let i=r.readReferencesForFile.all(t,n,Zt),o=r.readLegacyReferencesForFile.all(t,n);return $S([...o,...i])}catch(i){return Rn(e,"semantic_references bulk read",i),new Map}}function $S(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function tm(e,t){if(t.length===0)return;let n=xn(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.contentHash}`;r.has(o)||(r.add(o),n.dropStaleCallees.run(i.relativePath,i.contentHash)),n.writeCallees.run(i.relativePath,i.symbol,i.contentHash,i.depsDigest,Zt,i.payload)}})()}catch(r){Rn(e,"semantic_callees write",r)}}function OS(e,t){if(t.length===0)return;let n=xn(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.projectFingerprint}`;r.has(o)||(r.add(o),n.dropStaleReferences.run(i.relativePath,i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,Zt,i.payload)}})()}catch(r){Rn(e,"semantic_references write",r)}}function jS(e){let t=xn(e);if(!t)return[];try{return t.readFindingOutcomeLedger.all().map(r=>({check:r.check_name,findingId:r.finding_id,firstSeen:r.first_seen,lastSeen:r.last_seen,timesShown:r.times_shown,outcome:r.outcome}))}catch(n){return Rn(e,"finding_outcome_ledger read",n),[]}}function BS(e,t){let n=xn(e);if(n)try{let r=new Map;for(let i of t){let o=r.get(i.check)??[];o.push(i),r.set(i.check,o)}n.evidence.transaction(()=>{for(let[i,o]of r){n.deleteFindingOutcomeLedgerForCheck.run(i);let s=[...o].sort((a,c)=>c.lastSeen-a.lastSeen).slice(0,t0);for(let a of s)n.writeFindingOutcomeLedgerRow.run(a.check,a.findingId,a.firstSeen,a.lastSeen,a.timesShown,a.outcome)}})()}catch(r){Rn(e,"finding_outcome_ledger write",r)}}function q(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
84
- FROM documents
85
- WHERE 1 = 1
86
- ${e.pathExclusionsFor("documents")}
87
- ${n}
88
- ${r}
89
- 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}import{isAbsolute as o0,relative as s0}from"path";function _r(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Se(e){return e.replace(/\\/g,"/")}function _t(e,t){return _r(e)===_r(t)}function en(e,t){let n=s0(e,t);return n===""||!n.startsWith("..")&&!o0(n)}import{existsSync as rm,readFileSync as im,readdirSync as a0,statSync as c0}from"fs";import{join as xo,relative as l0}from"path";function Ro(e){let t=u0(e)??f0(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of om(e,i)){if(r.has(o))continue;r.add(o);let s=g0(e,o);s&&n.push(s)}return n}function u0(e){let t=xo(e,"pnpm-workspace.yaml");if(!rm(t))return null;try{return d0(im(t,"utf8"))}catch{return null}}function d0(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=p0(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=m0(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function p0(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function m0(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function f0(e){let t=xo(e,"package.json");if(!rm(t))return null;try{let n=JSON.parse(im(t,"utf8"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function om(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=xo(e,t);return nm(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=xo(e,r||".");return nm(o)?a0(o).map(s=>xo(o,s,i)).filter(nm):[]}function nm(e){try{return c0(e).isDirectory()}catch{return!1}}function g0(e,t){let n=xo(t,"package.json");if(!rm(n))return null;try{let r=JSON.parse(im(n,"utf8"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:l0(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var b0=me("indexed-paths",{clearGroups:[]}),S0=me("indexed-path-digest",{clearGroups:[]}),v0=ne("tsconfig-alias-config",{clearGroups:["whole-project"]}),x0=ne("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),R0=h0(import.meta.url),qs;function C0(){if(qs!==void 0)return qs;try{qs=R0("typescript")}catch{qs=null}return qs}var w0=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],k0=me("workspace-packages",{clearGroups:["whole-project"]}),vi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Jc=[".py",".pyi"],$t=[".java",".scala",".kt",".kts"],Yc=[".rs"],Qc=[".rb"],Xc=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Mr=[".cs",".vb"],Zc=[".dart"],Ri=[".php"],Mn=[".clj",".cljs",".cljc"],I0=new Set(vi),sm=new Set(Jc),WS=new Set($t),am=new Set(Yc),cm=new Set(Qc),qS=new Set(Xc),US=new Set(Mr),lm=new Set(Zc),VS=new Set(Ri),GS=new Set(Mn),P0=[{extensions:vi,lookup:I0},{extensions:Jc,lookup:sm},{extensions:$t,lookup:WS},{extensions:Yc,lookup:am},{extensions:Qc,lookup:cm},{extensions:Xc,lookup:qS},{extensions:Mr,lookup:US},{extensions:Zc,lookup:lm},{extensions:Ri,lookup:VS},{extensions:Mn,lookup:GS}];function rr(e,t){return t.has(nr(e).toLowerCase())}function E0(e){return rr(e,sm)}function D0(e){return rr(e,WS)}function T0(e){return rr(e,am)}function L0(e){return rr(e,cm)}function F0(e){return rr(e,qS)}function N0(e){return rr(e,US)}function zS(e){return nr(e).toLowerCase()===".vb"}function A0(e){return rr(e,lm)}function _0(e){return rr(e,VS)}function M0(e){return rr(e,GS)}function um(e){let t=nr(e).toLowerCase();for(let n of P0)if(n.lookup.has(t))return n.extensions;return vi}function $0(e){return D0(e)||N0(e)||_0(e)}function Ot(e,t,n){return E0(t)?Co(e,t,n):T0(t)?ir(e,t,n):L0(t)?el(e,t,n):F0(t)?tl(e,t,n):$0(t)?ze(e,n.replace(/\\/g,"."),um(t)):A0(t)?nl(e,t,n):M0(t)?dm(e,n):O0(e,t,n)}function O0(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return j0(e,t,n)??H0(e,n);let r=Mt(tn(e.config.projectRoot,t)),i=Ze(r,n),o=or(e);for(let s of mm(i)){let a=Se(Si(e.config.projectRoot,s));if(o.has(a)||xi(s))return a}return Se(Si(e.config.projectRoot,i))}function j0(e,t,n){let r=z0(e,t);if(!r)return null;let i=or(e);for(let o of B0(r,n)){let s=Ze(r.baseUrl,o);for(let a of mm(s)){let c=Se(Si(e.config.projectRoot,a));if(i.has(c)||xi(a))return c}}return null}function B0(e,t){let n=[];for(let[r,i]of Object.entries(e.paths)){let o=r.indexOf("*");if(o===-1){if(t!==r)continue;n.push(...i);continue}let s=r.slice(0,o),a=r.slice(o+1);if(!t.startsWith(s)||!t.endsWith(a)||t.length<s.length+a.length)continue;let c=t.slice(s.length,t.length-a.length);for(let l of i)n.push(l.includes("*")?l.replace("*",c):l)}return n}function H0(e,t){let n=q0(W0(e),t);if(!n)return null;let r=or(e);for(let i of U0(n)){let o=Ze(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of mm(o)){let a=Se(Si(e.config.projectRoot,s));if(r.has(a)||xi(s))return a}}return null}function W0(e){return k0.get(e,()=>Ro(e.config.projectRoot))}function q0(e,t){let n=null;for(let r of e){let i=null;t===r.name?i="":t.startsWith(`${r.name}/`)&&(i=t.slice(r.name.length+1)),i!==null&&(!n||r.name.length>n.pkg.name.length)&&(n={pkg:r,subpath:i})}return n}function U0(e){let t=[],n=V0(e.pkg.exports,e.subpath);if(n){let r=G0(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function V0(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return KS(e[n])}function KS(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return null;let t=e;for(let n of["types","import","default","require","node"]){let r=KS(t[n]);if(r)return r}return null}function G0(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function z0(e,t){let n=Se(Mt(t));return x0.get(e,n,()=>K0(e,n))}function K0(e,t){let n=C0();if(!n)return null;let r=Ze(e.config.projectRoot),i=Ze(r,t);for(;i===r||i.startsWith(r+y0);){for(let s of w0){let a=tn(i,s);if(!xi(a))continue;let c=v0.get(e,a,()=>J0(n,a));if(c)return c}let o=Mt(i);if(o===i)break;i=o}return null}function J0(e,t){try{let n=e.readConfigFile(t,e.sys.readFile);if(n.error||!n.config)return null;let r=e.parseJsonConfigFileContent(n.config,e.sys,Mt(t)),i=r.options.paths;return!i||Object.keys(i).length===0?null:{baseUrl:r.options.baseUrl?Ze(Mt(t),r.options.baseUrl):Mt(t),paths:i}}catch{return null}}function Co(e,t,n){let r=or(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Mt(tn(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Mt(c);i=a?Ze(c,a.replace(/\./g,"/")):c}else i=Ze(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Y0(i)){let s=Se(Si(e.config.projectRoot,o));if(r.has(s)||xi(o))return s}return null}function ir(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=Mt(tn(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Ze(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Ze(i,r.slice(6).replace(/::/g,"/")):o=Ze(Mt(i),r.slice(7).replace(/::/g,"/")),pm(e,Q0(o))}function el(e,t,n){let r=Mt(tn(e.config.projectRoot,t)),i=Ze(r,n);return pm(e,X0(i))}function tl(e,t,n){let r=Mt(tn(e.config.projectRoot,t)),i=[Ze(r,n),Ze(e.config.projectRoot,n),Ze(e.config.projectRoot,"include",n),Ze(e.config.projectRoot,"src",n)];return pm(e,i)}function ze(e,t,n){let r=or(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(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>HS(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(nr(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function nl(e,t,n){let r=or(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=Se(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Mt(tn(e.config.projectRoot,t)),o=Ze(i,n);for(let s of Z0(o)){let a=Se(Si(e.config.projectRoot,s));if(r.has(a)||xi(s))return a}return null}function dm(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=or(e);for(let i of Mn){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of Mn){let o=[...r].find(s=>HS(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function Y0(e){let t=nr(e);return sm.has(t)?[e]:[`${e}.py`,`${e}.pyi`,tn(e,"__init__.py"),tn(e,"__init__.pyi")]}function pm(e,t){let n=or(e);for(let r of t){let i=Se(Si(e.config.projectRoot,r));if(n.has(i)||xi(r))return i}return null}function Q0(e){let t=nr(e);return am.has(t)?[e]:[`${e}.rs`,tn(e,"mod.rs")]}function X0(e){let t=nr(e);return cm.has(t)?[e]:[`${e}.rb`,tn(e,"index.rb")]}function Z0(e){let t=nr(e);return lm.has(t)?[e]:[`${e}.dart`,e]}function mm(e){let t=nr(e),n=new Set;if(t){n.add(e);for(let r of vi)n.add(e.slice(0,-t.length)+r)}else for(let r of vi)n.add(`${e}${r}`),n.add(tn(e,`index${r}`));return[...n]}function or(e){return b0.get(e,()=>new Set(q(e,{includeIgnored:!1}).map(Se)))}function fm(e){return S0.get(e,()=>Ge([...or(e)].sort().join(`
90
- `)))}function ee(e){return typeof e=="object"&&e!==null}function X(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}import{appendFileSync as e$,mkdirSync as t$}from"fs";import{createHash as n$,randomUUID as r$}from"crypto";import{dirname as i$}from"path";import{performance as wo}from"perf_hooks";var XS="SCIP_QUERY_PROFILE",ZS="SCIP_QUERY_PROFILE_OUT",ev="SCIP_QUERY_PROFILE_COMMAND",tv="SCIP_QUERY_PROFILE_CACHE_STATE",gm="SCIP_QUERY_PROFILE_RUN_ID",hm="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",ym="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",nv=[XS,ZS,ev,tv,gm,hm,ym],gfe=new Set(nv),JS=new Set,YS=new Map,QS=!1;function re(){let e=process.env[XS];return e==="1"||e==="true"}function o$(){return process.env[ZS]}function il(){return process.env[ev]}function s$(){return process.env[tv]}function ol(){let e=process.env[gm];if(e)return e;if(!re())return;let t=r$();return process.env[gm]=t,t}function sl(){return process.env[hm]}function bm(e){let t=sl();if(t)return t;if(!re())return;let n=ol();if(!n)return;let r=e.projectFingerprint?"published-project":"run-only",i=Us(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[hm]=i,process.env[ym]=r,i}function Us(e){return n$("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function rv(){return Object.fromEntries(nv.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function D(e,t,n){if(!re())return t();let r=wo.now();try{let i=t();return jt({type:"span",name:e,durationMs:Math.round(wo.now()-r),ok:!0,...rl(n)??{}}),i}catch(i){throw jt({type:"span",name:e,durationMs:Math.round(wo.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...rl(n)??{}}),i}}async function Vs(e,t,n){if(!re())return t();let r=wo.now();try{let i=await t();return jt({type:"span",name:e,durationMs:Math.round(wo.now()-r),ok:!0,...rl(n)??{}}),i}catch(i){throw jt({type:"span",name:e,durationMs:Math.round(wo.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...rl(n)??{}}),i}}function jt(e,t=o$()){let n=a$(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:ol(),command:il(),cacheState:s$(),...n,...e},i=`${JSON.stringify(r)}
91
- `;if(t)try{let o=i$(t);JS.has(o)||(t$(o,{recursive:!0}),JS.add(o)),e$(t,i);return}catch(o){QS||(QS=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
92
- `));return}re()&&process.stderr.write(i)}function a$(e){let t=sl()??bm({command:il()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[ym],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=YS.get(o);return s||(s=Us(["profile-subsystem-v1",t,r]),YS.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function rl(e){return typeof e=="function"?e():e}var c$=[wt("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),wt("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),wt("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),wt("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),wt("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),wt("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),wt("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),wt("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),wt("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),wt("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),wt("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),wt("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),wt("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),wt("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),al("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),al("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),al("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),al("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function Ie(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(re()){let c=Ye(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=Us(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return D("evidence-product.file.read",()=>{let c=TS(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){LS(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){FS(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function Ci(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(re()){let c=`${i}\0${r}`;a=t.get(c),a||(a=Us(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return D("evidence-product.project.read",()=>{let c=NS(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){AS(n,e.kind,r,i,e.serialize(o))}}}function pe(e){let t=c$.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function wt(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function al(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}import{readFileSync as l$}from"fs";import{join as u$}from"path";var d$=ne("source-text",{clearGroups:["whole-project","source-file"]}),p$=ne("source-lines",{clearGroups:["whole-project","source-file"]});function _(e,t){let n=t.replace(/\\/g,"/");return d$.get(e,n,()=>{let r=u$(e.config.projectRoot,n);try{return l$(r,"utf-8")}catch(i){if(m$(i))return"";throw i}})}function m$(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Qe(e,t){let n=t.replace(/\\/g,"/");return p$.get(e,n,()=>{let r=_(e,n);return r?r.split(`
93
- `):[]})}var f$=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function Gs(e){let t=f$.exec(e);return t?t[1]??"":null}function cl(e,t,n){return ov(e,t,n).length>0}function iv(e,t,n,r){let i=r.toLowerCase();return ov(e,t,n).some(o=>o.toLowerCase()===i)}function ov(e,t,n){if(n<=0)return[];let r=Qe(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=Gs(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{basename as Yv}from"path";function J(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(e){return e.replace(/'''[\s\S]*?'''/g,$r).replace(/"""[\s\S]*?"""/g,$r).replace(/#.*$/gm,$r).replace(/\/\/.*$/gm,$r).replace(/\/\*[\s\S]*?\*\//g,$r).replace(/`(?:\\[\s\S]|[^`])*`/g,$r).replace(/'(?:\\.|[^'\\\r\n])*'/g,$r).replace(/"(?:\\.|[^"\\\r\n])*"/g,$r)}function Ks(e){return av(e,{maskStrings:!1})}function sv(e){return av(e,{maskStrings:!0})}function av(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
94
- `,r),a=s===-1?i:s;n+=Sm(e,r,a),r=a;continue}if(e[r]==="/"&&e[r+1]==="*"){let s=e.indexOf("*/",r+2),a=s===-1?i:s+2;n+=Sm(e,r,a),r=a;continue}let o=e[r];if(o==="`"||o==="'"||o==='"'){let s=o,a=r+1;for(;a<i;){if(e[a]==="\\"){a+=2;continue}if(e[a]===s){a+=1;break}if(s!=="`"&&e[a]===`
95
- `)break;a+=1}n+=t.maskStrings?Sm(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function Sm(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
96
- `?`
97
- `:" ";return r}function $r(e){return e.replace(/[^\r\n]/g," ")}var Tfe=bi("stripped-lines",{clearGroups:["whole-project","source-file"]});Nr({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{ll=null,zs=""},clearFile:()=>{ll=null,zs=""}});var ll=null,zs="";function g$(e){return ll===e||(ll=e,zs=kt(e)),zs}function Or(e,t,n){let r=g$(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function It(e,t){return new RegExp(`\\b${J(t)}\\b`,"m").test(e)}function ko(e,t){let n=new Set,r=new RegExp(`\\b${J(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 Js(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}import{extname as cv}from"path";var h$={".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",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function K(e){return h$[cv(e).toLowerCase()]??null}function sr(e){return cv(e).toLowerCase()===".vue"}import{createRequire as y$}from"module";var yt=y$(import.meta.url),Ys=null,vm=!1;function lv(){if(vm)return null;if(Ys)return Ys;try{return Ys=yt("tree-sitter"),Ys}catch{return vm=!0,null}}function ul(e){if(e==="clojure")return"reader";let t=lv();if(!t)return"unavailable";let n=uv(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return Io.add(e),"unavailable"}}var xm=new Map,Io=new Set;function uv(e){if(Io.has(e))return null;let t=xm.get(e);if(t)return t;let n;try{switch(e){case"rust":n=yt("tree-sitter-rust");break;case"typescript":n=yt("tree-sitter-typescript").typescript;break;case"tsx":n=yt("tree-sitter-typescript").tsx;break;case"javascript":n=yt("tree-sitter-javascript");break;case"python":n=yt("tree-sitter-python");break;case"java":n=yt("tree-sitter-java");break;case"kotlin":n=yt("tree-sitter-kotlin");break;case"scala":n=yt("tree-sitter-scala");break;case"ruby":n=yt("tree-sitter-ruby");break;case"c":n=yt("tree-sitter-c");break;case"cpp":n=yt("tree-sitter-cpp");break;case"csharp":n=yt("tree-sitter-c-sharp");break;case"php":n=yt("tree-sitter-php").php;break;case"vb":{let r=yt("tree-sitter-vb-dotnet");n=r.language??r;break}case"clojure":return Io.add(e),null}}catch{return Io.add(e),null}return xm.set(e,n),n}var Rm=new Map;function dv(){Ys=null,vm=!1,xm.clear(),Io.clear(),Rm.clear(),v$.clear()}function b$(e){let t=Rm.get(e);if(t)return t;let n=uv(e);if(!n)return null;let r=lv();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Io.add(e),null}return Rm.set(e,i),i}function S$(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Qs(e,t){let n=b$(e);if(!n)return null;try{return S$(n,t)}catch{return null}}var v$=new Map;import{posix as Cm}from"path";import{parse as x$}from"@vue/compiler-sfc";var R$=Ar("vue-sfc-units");function Po(e,t){let n=fv(t),r=_(e,n);return R$.get(e,n,r,()=>wm(e,n,r))}function fv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function C$(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function wi(e){return!e||e.body.length===0?0:e.body.split(`
98
- `).length}function wm(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=x$(n,{filename:t})}catch(s){return r.errors.push(mv(s)),r}r.errors.push(...i.errors.map(mv));let{descriptor:o}=i;return o.template&&(r.template=dl(e,t,"template",o.template)),o.script&&r.scripts.push(pv(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(pv(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>dl(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>dl(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function pv(e,t,n,r){let i=dl(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:C$(i.lang)}}function dl(e,t,n,r){let i=k$(r.attrs),o=typeof i.lang=="string"?i.lang:null,s=typeof i.src=="string"?i.src:typeof r.src=="string"?r.src:void 0;if(s){let c=w$(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:i,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=_(e,c),u=l?Math.max(0,l.split(`
99
- `).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:i,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,r.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:i,lang:o,body:r.content,startLine:a,endLine:Math.max(a,r.loc.end.line-1),errors:[]}}function w$(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=fv(Cm.normalize(Cm.join(Cm.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function k$(e){return{...e}}function mv(e){return e instanceof Error?e.message:String(e)}function pl(e,t,n){let i=wm(e,t,n).scripts.filter(s=>s.astLanguage&&s.body.length>0),o=i[0]?.astLanguage;return o?{body:i.map(s=>`${`
100
- `.repeat(s.startLine)}${s.body}`).join(`
101
- `),startLine:0,language:o}:null}var gv=bi("ast-trees",{clearGroups:["whole-project","source-file"]});function oe(e,t){if(sr(t))return I$(e,t);let n=K(t);if(!n)return null;let r=_(e,t);return r?gv.get(e,t,r,()=>Qs(n,r)):null}function I$(e,t){let n=_(e,t);return n?gv.get(e,t,n,()=>{let r=pl(e,t,n);if(!r)return null;let i=`
102
- `.repeat(r.startLine)+r.body;return Qs(r.language,i)}):null}function Eo(e,t){let n=P$(e,t);if(!n)return null;let r=ki(n);return r?{calleeLeaf:r,memberAccess:E$(n),line:e.startPosition.row}:null}function P$(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 E$(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function ki(e){switch(e.type){case"identifier":case"type_identifier":case"field_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?ki(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?ki(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?ki(t):null}case"super":case"self":case"this":return null;default:return null}}function Xs(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var D$=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function ml(e,t){let n=L$(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:bv(n.functionNode),params:hv(n.functionNode),paramsEndLine:yv(n.functionNode),isLiteralPassthrough:Sv(n.functionNode,t)};if(!T$(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:bv(e),params:hv(e),paramsEndLine:yv(e),isLiteralPassthrough:Sv(e,t)}:null}function vv(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function hv(e){let t=vv(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Xs(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 yv(e){let t=vv(e);return t?t.endPosition.row:e.startPosition.row}function T$(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?D$.has(e):!1}function L$(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 bv(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)Xs(r)||(n+=1);return n}function Sv(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>!Xs(d));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(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!Xs(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let p=d.namedChildren.find(m=>m.type==="identifier");p&&u.push(p.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let p=c[d];if(p.type!=="identifier"||p.text!==u[d])return!1}return!0}var F$=new Set(["identifier","type_identifier","field_identifier"]),N$=new Set(["identifier"]),A$=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),_$=new Set(["rust","python"]),M$=/\{([^{}]*)\}/g,$$=/\b([A-Za-z_][\w]*)\b/g;function xv(e,t){return O$(t).has(e.type)}function Rv(e,t){return _$.has(t)&&e.type==="string_content"}function km(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 O$(e){return e==="rust"?F$:e==="python"?N$:A$}function Cv(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(M$)){let i=r[1]??"";for(let o of i.matchAll($$))o[1]&&t(o[1],n)}}var j$=[/\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],B$=/^#!?\[\s*serde\s*\(/,H$=/^#!?\[\s*schemars\s*\(/,W$=/^#!?\[\s*validate\s*\(/,q$=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function wv(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=ki(r);if(!i||!q$.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 kv(e,t){let n=B$.test(e),r=H$.test(e),i=W$.test(e);if(!(!n&&!r&&!i))for(let o of j$){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 Iv(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(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.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 U$=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),Im=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function Pv(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
103
- `){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=gl(e,a);continue}if(l==='"'){let f=ea(e,a,s);s=f.line,a=f.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let f=o.pop();f&&(f.endLine=s,V$(f,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(f)),a+=1;continue}if(Pm(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!Em(e[a]);)a+=1;let p=e.slice(d,a);if(!p)continue;let m={text:p,line:u};G$(o[o.length-1],m),c(nn(p),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:Q$(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function V$(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=nn(n.text),i=U$.get(n.text);if(i){let s=e.headTokens[1];if(s){let a=nn(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:i})}}if(z$(e,t),!r||Im.has(n.text)||Im.has(r)||r.startsWith(":"))return;let o=Y$(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function G$(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function z$(e,t){let n=nn(e.tokens[0]?.text??"");if(n==="defprotocol"){let r=nn(e.tokens[1]?.text??"");if(!r)return;for(let i of fl(e))Zs(t,r,"protocol",i,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let r=nn(e.tokens[1]?.text??"");if(!r)return;let i=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of fl(e))Zs(t,r,i,s,o);return}if(n==="extend-type"){let r=nn(e.tokens[1]?.text??"");if(!r)return;for(let i of fl(e))Zs(t,r,"extension",i,"extension-method");return}if(n==="extend-protocol"){let r=nn(e.tokens[1]?.text??"");for(let i of fl(e)){r&&Zs(t,r,"extension",i,"extension-method");let o=J$(e,i.startLine);o&&o!==r&&Zs(t,o,"extension",i,"extension-method")}}}function fl(e){return e.children.filter(K$)}function K$(e){if(e.kind!=="(")return!1;let t=nn(e.tokens[0]?.text??"");return!!(t&&!Im.has(t)&&!t.startsWith(":"))}function Zs(e,t,n,r,i){let o=r.tokens[0],s=nn(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:i,startLine:r.startLine,endLine:r.endLine}))}function J$(e,t){let n=null;for(let r=2;r<e.tokens.length;r+=1){let i=e.tokens[r];if(i.line>t)break;let o=nn(i.text);o&&!o.startsWith(":")&&(n=o)}return n}function nn(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function Y$(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),r=nn(t);if(n<=0)return{leaf:r,text:t};let i=t.slice(0,n);return{leaf:r,qualifier:i,text:t}}function gl(e,t){let n=t;for(;n<e.length&&e[n]!==`
104
- `;)n+=1;return n}function ea(e,t,n){let r=t+1,i=n;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
105
- `&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function Pm(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function Em(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function Q$(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var Ev=3,X$=bi("source-facts",{clearGroups:["whole-project","source-file"]}),Dm=Ie({kind:"source-facts",invalidation:pe("source-facts"),serialize:tO,deserialize:nO});function ce(e,t){return Tm(e,t).facts}function Tm(e,t){let n=_(e,t);if(!n)return{facts:null};let r=Z$(e,t,n);return r?X$.get(e,t,n,()=>eO(e,t,r,n)):{facts:null}}function Z$(e,t,n){return sr(t)?pl(e,t,n)?.language??null:K(t)}function eO(e,t,n,r){let i=Ae(e,t,r),o=Dm.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=Pv(r);return Dm.write(e,t,i,c),{facts:c}}let s=oe(e,t);if(!s)return{facts:null,unavailable:{language:n,reason:"parser-unavailable"}};let a=iO(s,n);return Dm.write(e,t,i,a),{facts:a}}function tO(e){let t={version:Ev,language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function nO(e){try{let t=JSON.parse(e);if(t.version!==Ev||t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(r=>r.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:km(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Lm(e,t,n,r){let i=ce(e,t);return i?rO(i,n,r)?.isLiteralPassthrough??!0:!0}function ta(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:ce(e,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine)?.clojureKind==="macro"}function rO(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function iO(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=ml(l,t);u&&n.push(u);let d=Eo(l,t);d&&r.push(d),wv(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&kv(l.text,i),xv(l,t)&&a(l.text,l.startPosition.row),Rv(l,t)&&Cv(l,a);for(let p of l.children)c(p)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:Iv(e,t),identifierLineMap:s,identifiersByLine:km(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Dv=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function Fm(e,t){let n=ce(e,t);return!n||!Dv.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function jr(e,t){let n=ce(e,t);return!n||!Dv.has(n.language)?null:n.callSites}function Nm(e,t){return ce(e,t)?.typeContainerMap??new Map}import{ElementTypes as sO,NodeTypes as Am,parse as aO}from"@vue/compiler-dom";import{parse as wge}from"@vue/compiler-sfc";var oO=new Set(["children","className","data","e","err","error","ev","event","false","id","idx","index","item","key","null","props","res","result","state","style","true","undefined","val","value"]);function hl(e){return e.length<=2||oO.has(e)}function yl(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var cO=Ar("vue-template-facts"),lO=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),uO=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),dO=new Set(["div","span","template"]),pO=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function bl(e,t){let n=t.replace(/\\/g,"/"),r=_(e,n);return cO.get(e,n,r,()=>mO(n,Po(e,n).template))}function mO(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let r;try{r=aO(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Lv(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Lv(e,t,n,r){for(let i of e)if(i.type===Am.ELEMENT)fO(i,t,n,r),Lv(i.children,t,n,r);else if(i.type===Am.INTERPOLATION){r("interpolation");let o=_m(i.content);o&&Fv(o,t,i.loc.start.line,n,r)}}function fO(e,t,n,r){let i=xO(e.tag),o={tag:e.tag,normalized:i,kind:vO(e),startLine:Do(t,e.loc.start.line),endLine:Do(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),r(`component:${i}`)):o.kind==="builtin"?(n.builtinTags.push(o),r(`builtin:${i}`)):(n.nativeTags.push(o),dO.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)gO(s,t,n,r)}function gO(e,t,n,r){if(e.type===Am.ATTRIBUTE){let a=e.value?.content??null,c=Tv("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=yO(e),o=_m(e.exp),s=Tv(hO(e.name),i,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),r(`prop:${i}`);break;case"event":n.events.push(s),r(`event:${i}`);break;case"slot":n.slots.push(s),r(`slot:${i}`);break;case"directive":n.directives.push(s),r(`directive:${i}`);break}o&&Fv(o,t,e.loc.start.line,n,r)}function Tv(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Do(r,i),endLine:Do(r,o)}}function hO(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function yO(e){let t=_m(e.arg);return t||e.name}function _m(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function Fv(e,t,n,r,i){for(let o of bO(e)){let s={name:o,startLine:Do(t,n),endLine:Do(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function bO(e){let t=new Set,n=SO(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];pO.has(o)||hl(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function SO(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function vO(e){let t=e.tag;return e.tagType===sO.COMPONENT?"component":lO.has(t)?"builtin":uO.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function xO(e){return yl(e,/[-_:]/)}function Do(e,t){return e+Math.max(0,t-1)}import{readdirSync as RO}from"fs";import{execFileSync as CO}from"child_process";import{extname as Sl,join as wO}from"path";var Mm=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Nv=[".vue"],Av=[".tsx",".jsx"],_v=[".vue"],kO=[...Av,..._v],IO=new Set(Av),PO=new Set(_v),Mv=new Set(Mm.map(e=>e.toLowerCase())),EO=[...Mv].sort().join(","),vl=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Pt(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Mv,s=i?[...o].sort().join(","):EO,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return DO.get(e,a,()=>{let c=new Set;if(n)for(let l of q(e,{includeIgnored:!1}))o.has(Sl(l).toLowerCase())&&c.add(l);if(r)for(let l of TO(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function xl(e,t={}){let n=!1,r=!1;for(let i of Pt(e,{extensions:kO})){if(t.scope&&!i.includes(t.scope))continue;let o=Sl(i).toLowerCase();if(n||=IO.has(o),r||=PO.has(o),n&&r)break}return{react:n,vue:r}}var DO=ne("source-files",{clearGroups:[]});function TO(e,t){return LO(e,t)??NO(e,t)}function LO(e,t){try{let n=CO("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),r=new Set;for(let i of n.split(`
106
- `)){let o=i.trim();o&&(FO(o)||t.has(Sl(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function FO(e){return e.split("/").some(t=>vl.has(t))}function NO(e,t){let n=new Set,r=i=>{let o=i?wO(e,i):e,s;try{s=RO(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!vl.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Sl(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var AO=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),_O=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),MO=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),$O=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),OO=new Set(["catch","for","function","if","return","switch","while"]);function Cl(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=wi(n),n.external&&(t.externalLineCount+=wi(n),t.externalScriptPaths.push(n.sourcePath));for(let i of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:i});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...WO(n));let r=Qs(n.astLanguage,n.body);r?BO(n,r.rootNode,t):HO(n,t)}return jO(t),t.externalScriptPaths=Ov(t.externalScriptPaths),t}function jO(e){e.composables=To(e,"composable"),e.stores=To(e,"store"),e.reactivity=To(e,"reactivity"),e.lifecycle=To(e,"lifecycle"),e.requests=To(e,"request"),e.macros=To(e,"macro")}function To(e,t){return Ov(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function BO(e,t,n){let r=new Set,i=new Set,o=s=>{let a=ml(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;i.has(l)||(i.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=Eo(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;r.has(l)||(r.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:$v(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function HO(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||OO.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+Rl(e.body,n.index??0),categories:$v(r),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let r=n[1];if(!r)continue;let i=e.startLine+Rl(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let r=n[1];if(!r)continue;let i=e.startLine+Rl(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function WO(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let r=n[1]?.trim(),i=n[2];if(!r||!i)continue;let o=e.startLine+Rl(e.body,n.index??0);for(let s of qO(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function qO(e){let t=[],r=e.split(",").map(s=>s.trim()).filter(Boolean)[0];r&&!r.startsWith("{")&&!r.startsWith("*")&&t.push(r);let i=/\{([^}]*)\}/.exec(e)?.[1];if(i)for(let s of i.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function $v(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),AO.has(e)&&t.push("reactivity"),_O.has(e)&&t.push("lifecycle"),MO.has(e)&&t.push("request"),$O.has(e)&&t.push("macro"),t}function Rl(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function Ov(e){return[...new Set(e)].sort()}var UO=new Set(["in","key","of"]),VO=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),GO=Ar("vue-component-behavior-profiles");function jv(e,t={}){let n=Pt(e,{extensions:[".vue"]}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(i=>$m(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function $m(e,t){let n=t.replace(/\\/g,"/"),r=_(e,n),i=GO.get(e,n,r,()=>zO(e,n,r));return JO(i)}function zO(e,t,n){let r=Po(e,t),i=bl(e,t),o=Cl(r),s=XO(i),a=i.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,y,x)=>x.indexOf(h)===y).sort(),c=i.componentTags.map(h=>h.normalized).filter((h,y,x)=>x.indexOf(h)===y).sort(),l=n?n.split(`
107
- `).length:0,u=wi(r.template),d=o.lineCount,p=r.styles.reduce((h,y)=>h+wi(y),0),m=r.customBlocks.reduce((h,y)=>h+wi(y),0),{lines:f,paths:g}=KO(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:QO(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:p,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:m,delegatedComposableLines:f,delegatedComposablePaths:g}}function KO(e,t,n){let r=new Set;for(let s of n.composables){let a=n.imports.find(l=>l.local===s);if(!a)continue;let c=Ot(e,a.sourcePath,a.source);!c||c===t||r.add(c)}let i=[...r].sort();return{lines:i.reduce((s,a)=>{let c=_(e,a);return s+(c?c.split(`
108
- `).length:0)},0),paths:i}}function JO(e){let t=YO(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function YO(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function QO(e,t,n){let r=new Set;for(let i of t.composables)r.add(`composable:${i}`);for(let i of t.stores)r.add(`store:${i}`);for(let i of t.reactivity)r.add(`reactivity:${i}`);for(let i of t.lifecycle)r.add(`lifecycle:${i}`);for(let i of t.requests)r.add(`request:${i}`);for(let i of t.macros)r.add(`macro:${i}`);for(let i of t.functions){if(VO.has(i.name))continue;r.add(`function:${i.name}`);let o=/^[a-z]+/.exec(i.name)?.[0]??null;o&&o.length>2&&o!==i.name&&r.add(`function-verb:${o}`)}for(let i of e.events)r.add(`template-event:${i.name}`);for(let i of n)r.add(`template-binding:${i}`);return r}function XO(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of ZO(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of Bv(n.value))t.add(r);return[...t].sort()}function ZO(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Bv(t[1]??""):[]}function Bv(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];UO.has(r)||t.push(r)}return t}import{extname as ej}from"path";var tj=[".tsx",".jsx"],Hv=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),nj=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),rj=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),ij=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),oj=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),sj=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),aj=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),cj=Ar("react-component-behavior-profiles"),Wv=Ie({kind:"react-component-behavior-profiles",invalidation:pe("react-component-behavior-profiles"),serialize:pj,deserialize:mj});function Gv(e,t={}){let n=Pt(e,{extensions:tj}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(i=>jm(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function jm(e,t){let n=t.replace(/\\/g,"/"),r=_(e,n);return cj.get(e,n,r,()=>lj(e,n,r)).map(dj)}function lj(e,t,n){let r=Ae(e,t,n),i=Wv.read(e,t,r);if(i)return i;let o=uj(e,t);return Wv.write(e,t,r,o),o}function uj(e,t){let n=gj(t);if(!n)return[];let r=oe(e,t);if(!r)return[];let i=Qe(e,t).length;return hj(r.rootNode,n).filter(s=>s.kind==="hook"||Bm(s.bodyNode)).map(s=>{let a=Cj(s.bodyNode),c=Ej(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:ar(a.componentNames),nativeTags:ar(a.nativeTags),propNames:ar(a.propNames),eventNames:ar(a.eventNames),hookNames:ar(c.hookNames),requestNames:ar(c.requestNames),stateNames:ar(c.stateNames),effectNames:ar(c.effectNames),handlerNames:ar(c.handlerNames)}})}function dj(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function pj(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function mj(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=fj(r);if(!i)return null;n.push(i)}return n}catch{return null}}function fj(e){if(!ee(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:p,eventNames:m,hookNames:f,requestNames:g,stateNames:h,effectNames:y,handlerNames:x}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!wl(i)||!wl(o)||!wl(s)||!wl(a))return null;let R={jsxTokens:X(c),behaviorTokens:X(l),componentNames:X(u),nativeTags:X(d),propNames:X(p),eventNames:X(m),hookNames:X(f),requestNames:X(g),stateNames:X(h),effectNames:X(y),handlerNames:X(x)};return Object.values(R).some(b=>b===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(R.jsxTokens),behaviorTokens:new Set(R.behaviorTokens),componentNames:R.componentNames,nativeTags:R.nativeTags,propNames:R.propNames,eventNames:R.eventNames,hookNames:R.hookNames,requestNames:R.requestNames,stateNames:R.stateNames,effectNames:R.effectNames,handlerNames:R.handlerNames}}function wl(e){return typeof e=="number"&&Number.isFinite(e)}function gj(e){let t=ej(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:K(e)}function hj(e,t){let n=[],r=new Set,i=o=>{let s=yj(o);if(s&&(!xj(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function yj(e){if(e.type==="class_declaration"){let o=Om(e);if(!o||!/^[A-Z]/.test(o))return null;let s=bj(e);return!s||!Sj(e)&&!Bm(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=Om(e);return!o||!qv(o)?null:{name:o,kind:Uv(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=na(t);if(!r||!n||!qv(r))return null;let i=vj(n);return i?{name:r,kind:Uv(r),node:e,bodyNode:i}:null}function bj(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function Sj(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function qv(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Uv(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function vj(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=Rj(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(i=>i.type==="arguments")?.namedChildren.find(i=>i.type==="arrow_function"||i.type==="function_expression")??null}function xj(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function Om(e){return na(e.childForFieldName("name")??e.namedChild(0))}function Rj(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function Bm(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(Bm)}function Cj(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=r=>{r.type==="jsx_opening_element"||r.type==="jsx_self_closing_element"?wj(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?kj(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function wj(e,t){let n=Ij(e),r=!1;if(n){let i=Vv(n),o=i==="Fragment"||i==="React.Fragment";r=Nj(i)&&!o,o?t.tokens.add("jsx:fragment"):r?(t.componentNames.add(i),t.tokens.add(`component:${i}`)):(t.nativeTags.add(i),t.tokens.add(`native:${i}`))}for(let i of e.namedChildren)if(i.type==="jsx_attribute"){let o=Pj(i);if(!o)continue;let s=Vv(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else aj.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(zv(i))}function kj(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(zv(e)),Kv(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of Aj(n))hl(r)||t.tokens.add(`binding:${r}`)}function zv(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function Kv(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(Kv)}function Ij(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function Pj(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function Ej(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},r=i=>{if(i.type==="call_expression"){let o=Eo(i,t);o&&Dj(o.calleeLeaf,n)}else if(i.type==="variable_declarator")Lj(i,n);else if(i.type==="function_declaration"){let o=Om(i);o&&Jv(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function Dj(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Hv.has(e)&&!ij.has(e)&&t.tokens.add(`hook:${e}`)),Hv.has(e)&&t.tokens.add(`react-hook:${e}`),nj.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),rj.has(e)&&t.tokens.add(`state-hook:${e}`),Tj(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function Tj(e){if(oj.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function Lj(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&r?.text.includes("useState")){let o=n.namedChildren.find(a=>na(a)),s=na(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=na(n);i&&Jv(i,t)}function Jv(e,t){let n=Fj(e);!n||!sj.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function Fj(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function Nj(e){return/^[A-Z]/.test(e)||e.includes(".")}function Vv(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function na(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function Aj(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];t.includes(r)||t.push(r)}return t}function ar(e){return[...e].sort()}function rn(e){return{capability:(t,n)=>_j(t,n),reactProfiles:(t={})=>Gv(e,t),reactProfilesForFile:t=>jm(e,t),vueProfiles:(t={})=>jv(e,t),vueProfileForFile:t=>$m(e,t),vueTemplateFacts:t=>bl(e,t),vueScriptFacts:t=>Cl(Po(e,t))}}function _j(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Ii(e,t,n={}){let r=ce(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 Mj=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Et(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 Bt(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function Ke(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Mj.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Cn(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??ze(e,r,um(t)),kind:"named",used:It(n,o),usedMembers:[]}}function qe(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 cr(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 Pi(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Ei(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 on(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=Or(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function sn(e,t,n,r){let i=oe(e,t);if(i){let o=n(i);if(o)return o}return r()}function kl(e,t,n,r){let i=oe(e,t),o=K(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Qv(e,t,n){return sn(e,t,r=>Oj(e,t,r),()=>$j(e,t,n))}function $j(e,t,n){return on(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Yv(o).replace(/\.[^.]+$/,"");return[cr(o,s,tl(e,t,o),It(i,s))]})}function Oj(e,t,n){let r=Ke(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=Yv(s).replace(/\.[^.]+$/,"");i.push(qe(s,a,tl(e,t,s),r))}return i}var jj=new Set([":require",":require-macros",":use"]),qm=String.raw`A-Za-z0-9_$*+!?.<>=-`;function Zv(e,t,n){let r=Yj(n);if(!r)return[];let i=Jj(n,r.start,r.end),o=[];for(let s of r.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=an(s.children[0]);if(a){if(jj.has(a)){for(let c of Wj(s.children.slice(1)))o.push(...Hj(e,c,i));continue}if(a===":import")for(let c of Uj(s.children.slice(1)))o.push(c)}}return o}function Bj(e){return e.type==="list"&&an(e.children[0])==="ns"}function Hj(e,t,n){let r=dm(e,t.namespace),i=t.alias??t.namespace,o=Gj(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||zj(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:r,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:r,kind:"named",used:Kj(n,a),usedMembers:[]});return s}function Wj(e){return e.flatMap(t=>Il(t,null))}function Il(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:Wm(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return e.children.length>0&&an(e.children[0])===null?e.children.flatMap(n=>Il(n,t)):qj(e,t);if(e.type==="list"&&e.children.length>0){let n=an(e.children[0]);return n?!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(r=>Il(r,Wm(t,n))):e.children.flatMap(r=>Il(r,t))}return[]}function qj(e,t){let n=an(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:Wm(t,n),alias:null,refers:[],referAll:!1};for(let i=1;i<e.children.length;i+=1){let o=an(e.children[i]);if(!o?.startsWith(":"))continue;let s=e.children[i+1];if((o===":as"||o===":as-alias")&&s){r.alias=an(s),i+=1;continue}o===":refer"&&s&&(an(s)===":all"?r.referAll=!0:(s.type==="vector"||s.type==="list")&&r.refers.push(...s.children.map(an).filter(Vj)),i+=1)}return[r]}function Uj(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(cr(i,i,null,!0));continue}if(n.type!=="vector")continue;let r=an(n.children[0]);if(r)for(let i of n.children.slice(1)){let o=an(i);o&&t.push(cr(`${r}.${o}`,o,null,!0))}}return t}function Wm(e,t){return e?`${e}.${t}`:t}function an(e){return e?.type==="atom"?e.text:null}function Vj(e){return!!(e&&!e.startsWith(":"))}function Gj(e,t){let n=new Set,r=new RegExp(`${Um()}${J(t)}\\s*/\\s*([${qm}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function zj(e,t){return new RegExp(`${Um()}${J(t)}\\s*/`,"m").test(e)}function Kj(e,t){return new RegExp(`${Um()}${J(t)}(?![${qm}])`,"m").test(e)}function Um(){return`(?<![${qm}])`}function Jj(e,t,n){let r="",i=0;for(;i<e.length;){if(i>=t&&i<n){r+=e[i]===`
109
- `?`
110
- `:" ",i+=1;continue}let o=e[i];if(o===";"){let s=gl(e,i);r+=Xv(e.slice(i,s)),i=s;continue}if(o==='"'){let s=ea(e,i,0).index;r+=Xv(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function Yj(e){let t=0;for(;t<e.length&&(t=Vm(e,t),!(t>=e.length));){let n=Pl(e,t);if(!n){t+=1;continue}if(Bj(n.form))return n.form;t=n.index}return null}function Pl(e,t){let n=Vm(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return Qj(e,n);if(e.startsWith("#_",n)){let i=Pl(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;Pm(e[n]);)n+=1;let r=e[n];return r?r==="("?Hm(e,n,"list",")"):r==="["?Hm(e,n,"vector","]"):r==="{"?Hm(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:ea(e,n,0).index},index:ea(e,n,0).index}:Zj(e,n):null}function Qj(e,t){let n=e.startsWith("#?@",t)?3:2,r=Pl(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?Xj(r.form.children):[],start:t,end:r.index},index:r.index}:null}function Xj(e){let t=[];for(let n=0;n<e.length;n+=2){let r=an(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function Hm(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=Vm(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=Pl(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function Zj(e,t){let n=t;for(;n<e.length&&!Em(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function Vm(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=gl(e,n);continue}break}return n}function Xv(e){return e.replace(/[^\r\n]/g," ")}function ex(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=Or(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:nl(e,t,o),kind:s?"namespace":"side-effect",used:s?It(c,s):!0,usedMembers:s?ko(c,s):[]})}return r}function tx(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:nl(e,t,o)})}return r}function nx(e,t,n){return kl(e,t,{csharp:r=>tB(e,t,r),vb:r=>eB(e,t,r)},()=>{let r=zS(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return on(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,d=u.split(".").pop()??u,p=l?a?.trim()??d:d;return[Cn(e,t,o,u,d,p,ze(e,u,Mr))]})})}function eB(e,t,n){let r=Ke(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(p=>p.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;i.push(qe(u,d,ze(e,l,Mr),r,c?"namespace":"named"))}return i}function tB(e,t,n){let r=Ke(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,d=a?.text??u;i.push(qe(u,d,ze(e,l,Mr),r,a?"namespace":"named"))}return i}var nB=ne("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function rx(e,t){return nB.get(e,t,()=>{let n=new Set,r=_(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 Gm(e,t,n){return sn(e,t,r=>iB(e,t,r),()=>rB(e,t,n))}function rB(e,t,n){return gB(n).flatMap(r=>hB(e,t,r.clause,r.specifier,r.start,r.end,n))}function iB(e,t,n){let r=oB(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...sB(e,t,n,o,r));return i}function oB(e,t,n){let r=Ke(n,new Set(["import_statement"]));if(sr(t))for(let i of rx(e,t))r.add(i);return r}function sB(e,t,n,r,i){let o=dB(r);if(!o)return[];let s=Ot(e,t,o),a=Bt(r,"import_clause");return a?aB(n,a,s,i,pB(r.text)):[Pi("*",s)]}function aB(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(cB(s.text,n,r,i));else if(s.type==="namespace_import"){let a=lB(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...uB(s,n,r,i));return o}function cB(e,t,n,r){return qe("default",e,t,n,"default",{isTypeOnly:r})}function lB(e,t,n,r,i){let s=Bt(t,"identifier")?.text??"";if(!s)return null;let a=fB(e,s);return Ei("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function uB(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(qe(c,l,t,n,"named",{isTypeOnly:r||mB(o.text)}))}return i}function dB(e){let t=Bt(e,"string");if(!t)return null;let n=Bt(t,"string_fragment");return n?n.text:null}function pB(e){return/^\s*import\s+type\b/.test(e)}function mB(e){return/^\s*type\b/.test(e.trim())}function fB(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 gB(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 hB(e,t,n,r,i,o,s){let a=Ot(e,t,r),c=Or(s,i,o);return n?yB(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=ko(c,u.localName);return Ei(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||It(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Pi(u.importedName,u.sourcePath):cr(u.importedName,u.localName??"",u.sourcePath,u.localName?It(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Pi("*",a)]}function yB(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=bB(r),s=[];return i&&s.push(...ix(i,n)),o&&s.push(...ix(o,n)),s}function ix(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?Et(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 bB(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 zm(e,t,n){let r=oe(e,t);return r?wB(e,t,r):SB(e,t,n)}function SB(e,t,n){return[...vB(e,t,n),...xB(e,t,n),...RB(e,t,n)]}function vB(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=Et(s).map(d=>CB(d.trim())).filter(d=>!!d),l=Lo(n,o.index),u=Lo(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Ot(e,t,a),names:c,startLine:l,endLine:u})}return r}function xB(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=Lo(n,o.index),c=Lo(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Ot(e,t,s),names:[],startLine:a,endLine:c})}return r}function RB(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=Lo(n,o.index),c=Lo(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Ot(e,t,s),names:[],startLine:a,endLine:c})}return r}function CB(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 Lo(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function wB(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=kB(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=IB(i,o,s,a);r.push(c)}return r}function kB(e,t,n){let r=Bt(n,"string");if(!r)return;let i=Bt(r,"string_fragment");if(i)return Ot(e,t,i.text)}function IB(e,t,n,r){let i=Bt(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 Bt(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function ox(e,t,n){return kl(e,t,{java:r=>PB(e,t,r),kotlin:r=>EB(e,t,r),scala:r=>DB(e,t,r)},()=>on(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?TB(e,t,o,i):[]}))}function PB(e,t,n){let r=Ke(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(Ei("*",ze(e,l,$t)));continue}let u=l.split(".").pop()??l;i.push(qe(u,u,ze(e,l,$t),r))}return i}function EB(e,t,n){let r=Ke(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(m=>m.type==="identifier");if(!s)continue;let a=o.namedChildren.some(m=>m.type==="wildcard_import"),c=o.namedChildren.find(m=>m.type==="import_alias");if(a){i.push(Ei("*",ze(e,s.text,$t)));continue}let l=s.text,u=l.split(".").pop()??l,p=c?.namedChild(0)?.text??u;i.push(qe(u,p,ze(e,l,$t),r))}return i}function DB(e,t,n){let r=Ke(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(Ei("*",ze(e,c,$t)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[p,m]=d.namedChildren;if(!p)continue;let f=p.text,g=m?.text??f;if(f==="_")continue;i.push(qe(f,g,ze(e,`${c}.${f}`,$t),r))}else if(d.type==="identifier"){let p=d.text;i.push(qe(p,p,ze(e,`${c}.${p}`,$t),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(qe(l,l,ze(e,u&&a.length>1?`${u}.${l}`:c,$t),r))}return i}function TB(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 Et(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),p=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Cn(e,t,r,p,u,d)]})}return[Cn(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function ax(e,t,n){return sn(e,t,r=>LB(e,t,r),()=>on(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Et(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,p=(l??d).trim();return[Cn(e,t,i,u,d,p,ze(e,u.replace(/\\/g,"."),Ri))]}):[]}))}function LB(e,t,n){let r=Ke(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(qe(a,c,ze(e,s.replace(/\\/g,"."),Ri),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:d,qualified:p}=sx(l,c);u&&o(p,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=sx(c,"");l&&o(d,l,u)}}return i}function sx(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 lx(e,t,n){return sn(e,t,r=>FB(e,t,r),()=>AB(n).flatMap(r=>MB(e,t,r,n)))}function FB(e,t,n){let r=Ke(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=cx(s);if(!a)continue;let c=Co(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=NB(s);if(a===null)continue;let c=Co(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 d=cx(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function cx(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 NB(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Bt(e,"import_prefix")?.text??"",n=Bt(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function AB(e){let t=e.split(`
111
- `),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=Js(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let p=t[i];c+=`
112
- ${p}`,l+=1+p.length,u+=Js(p),r+=p.length+1}let d=_B(c);d&&n.push({...d,start:a,end:l})}return n}function _B(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 MB(e,t,n,r){let i=Or(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Et(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),p=u.trim(),m=(d??p.split(".")[0]??p).trim(),f=Co(e,t,p),g=ko(i,m);return[{importedName:p,localName:m,sourcePath:f,kind:"namespace",used:It(i,m)||g.length>0,usedMembers:g}]});let s=n.module?Co(e,t,n.module):null,a=[];for(let c of Et(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),p=(d??u).trim();a.push({importedName:u.trim(),localName:p,sourcePath:s,kind:"named",used:It(i,p),usedMembers:[]})}return a}import{basename as $B}from"path";function ux(e,t,n){return sn(e,t,r=>jB(e,t,r),()=>OB(e,t,n))}function OB(e,t,n){return on(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"?el(e,t,s):null;if(a){let c=dx(s);return[cr(c,c,a,It(i,c))]}return[Pi(s,a)]})}function jB(e,t,n){let r=Ke(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(m=>m.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(m=>m.type==="string_content")?.text;if(!d)continue;let p=a.text==="require_relative"?el(e,t,d):null;if(p){let m=dx(d);i.push(qe(m,m,p,r))}else i.push(Pi(d,p))}return i}function dx(e){return yl($B(e).replace(/\.[^.]+$/,""),/_/)}function px(e,t,n){return sn(e,t,r=>BB(e,t,r),()=>on(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?HB(e,t,o,i):[]}))}function BB(e,t,n){let r=Ke(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 ra(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=ir(e,t,a.qualifiedName)??ir(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(qe(a.importedName,a.localName,c,r))}}return i}function ra(e,t){switch(e.type){case"identifier":case"super":case"crate":{let n=e.text;return[{qualifiedName:Fo(t,n),importedName:n,localName:n}]}case"self":{let n=t.split("::").filter(Boolean).pop()??"self";return[{qualifiedName:t||"self",importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Fo(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=Fo(t,n.text),o=[];for(let s of r.namedChildren)o.push(...ra(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...ra(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=ra(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:Fo(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Fo(e,t){return e?t?`${e}::${t}`:e:t}function HB(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Et(d).flatMap(p=>{let m=p.trim();if(!m)return[];if(m==="self"){let R=u.split("::").filter(Boolean).pop();return R?[Cn(e,t,r,u,R,R)]:[]}let[f,g]=m.split(/\s+as\s+/),h=f?.trim();if(!h)return[];let y=(g??h.split("::").pop()??h).trim(),x=`${u}::${h}`.replace(/::::/g,"::");return[Cn(e,t,r,x,h.split("::").pop()??h,y,ir(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=ir(e,t,a)??ir(e,t,a.split("::").slice(0,-1).join("::"));return[Cn(e,t,r,a,a.split("::").pop()??a,c,l)]}function mx(e,t,n){let r=oe(e,t);if(r)return WB(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(...UB(e,t,s))}return i}function WB(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!qB(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of ra(o,""))s.importedName&&r.push(Km(e,t,s.qualifiedName))}return r}function qB(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function UB(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 Et(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[Km(e,t,l)]})}return[Km(e,t,r)]}function Km(e,t,n){return{specifier:n,sourcePath:ir(e,t,n)??ir(e,t,n.split("::").slice(0,-1).join("::"))}}function Br({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function fx(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 VB={language:"javascript",extensions:vi,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Gm,parseReExports:zm},GB=Br({language:"python",extensions:Jc,imports:"ast-with-regex-fallback",parseImports:lx}),zB=Br({language:"jvm",extensions:$t,imports:"ast-dispatch-with-regex-fallback",parseImports:ox}),KB={language:"rust",extensions:Yc,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:px,parseExports:mx},JB=Br({language:"ruby",extensions:Qc,imports:"ast-with-regex-fallback",parseImports:ux}),YB=Br({language:"c/cpp",extensions:Xc,imports:"ast-with-regex-fallback",parseImports:Qv}),QB=Br({language:"dotnet",extensions:Mr,imports:"ast-dispatch-with-regex-fallback",parseImports:nx}),XB={language:"dart",extensions:Zc,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:ex,parseExports:tx},ZB=Br({language:"php",extensions:Ri,imports:"ast-with-regex-fallback",parseImports:ax}),e1=Br({language:"clojure",extensions:Mn,imports:"regex-only",parseImports:Zv}),gx=[VB,GB,zB,KB,JB,YB,QB,XB,ZB,e1];function El(e){return fx(gx,e)}function hx(e){return gx.find(n=>n.language===e)?.capabilities??null}var Jm={clearGroups:["whole-project","source-file"]},t1=ne("source-imports",Jm),n1=ne("source-exports",Jm),r1=ne("source-reexports",Jm),yx=Ie({kind:"source-imports",invalidation:pe("source-imports"),serialize:i1,deserialize:o1}),bx=Ie({kind:"source-reexports",invalidation:pe("source-reexports"),serialize:s1,deserialize:a1});function Di(e,t){let n=Se(t);return r1.get(e,n,()=>{let r=El(n);if(!r?.parseReExports)return[];let i=_(e,n);if(!i)return[];let o=Ae(e,n,i),s=fm(e),a=bx.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return bx.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function Ce(e,t){let n=Se(t);return t1.get(e,n,()=>{let r=El(n);if(!r)return[];let i=_(e,n);if(!i)return[];let o=Ae(e,n,i),s=fm(e),a=yx.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return yx.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function Dl(e,t){let n=Se(t);return n1.get(e,n,()=>{let r=El(n);if(!r?.parseExports)return[];let i=_(e,n);return i?r.parseExports(e,n,i):[]})}function i1(e){return JSON.stringify(e)}function o1(e){try{let t=JSON.parse(e);return!ee(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function s1(e){return JSON.stringify(e)}function a1(e){try{let t=JSON.parse(e);return!ee(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}var Sx=Ci({kind:"file-dependency-graph",invalidation:pe("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:f1}),c1=ne("file-dep-graph",{clearGroups:["whole-project"]});function ge(e,t,n={}){let r=n.scipEdges??"all-references";return c1.get(e,`${r}:${t??""}`,()=>{let i=new Set(q(e,{includeIgnored:!1})),o=Ye(e),s=d1(t,r),a=0,c=0,l=null,u=!1,d=0,p=0;return D("file-dep-graph.product",()=>{if(o){let h=Sx.read(e,s,o);if(h){u=!0;let y=m1(h);return a=h.sourceFileCount,c=h.sourceEdgeCount,d=h.scipEdgeCount,p=y.size,l=h.sourceImportFingerprint,y}}let m=D("file-dep-graph.source-imports",()=>{let h=l1(e,i,t);return a=h.files.length,c=h.edges.length,l=h.fingerprint,h},()=>({scope:t??null,files:a,edges:c})),f=new Map,g=(h,y)=>b1(e,f,i,h,y);D("file-dep-graph.scip-edges",()=>{for(let h of y1(e,t,r))d+=1,g(h.from_file,h.to_file)},()=>({scope:t??null,edges:d}));for(let h of m.edges)g(h.fromFile,h.toFile);return p=f.size,o&&Sx.write(e,s,o,{sourceImportFingerprint:m.fingerprint,sourceFileCount:m.files.length,sourceEdgeCount:m.edges.length,scipEdgeCount:d,graph:p1(f)}),f},()=>({scope:t??null,available:o!==null,hit:u,files:a,sourceEdges:c,scipEdges:d,graphFiles:p,sourceImportFingerprint:l}))})}function l1(e,t,n){let r=[],i=[];for(let o of t)if(!(n&&!o.includes(n))){r.push(o);for(let s of Ce(e,o))s.sourcePath&&i.push({fromFile:o,toFile:s.sourcePath})}return{files:r,edges:i,fingerprint:u1(r,i)}}function u1(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return Ge(JSON.stringify({files:e,edges:n}))}function d1(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function p1(e){return[...e].map(([t,n])=>[t,[...n]])}function m1(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function f1(e){let t=JSON.parse(e);return g1(t)?t:null}function g1(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(h1)}function h1(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function y1(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],o=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
113
- d1.relative_path AS from_file,
114
- d2.relative_path AS to_file
115
- FROM mentions m
116
- JOIN chunks c ON m.chunk_id = c.id
117
- JOIN documents d1 ON c.document_id = d1.id
118
- JOIN global_symbols gs ON m.symbol_id = gs.id
119
- JOIN (
120
- SELECT m2.symbol_id, c2.document_id
121
- FROM mentions m2
122
- JOIN chunks c2 ON m2.chunk_id = c2.id
123
- WHERE m2.role = 1
124
- GROUP BY m2.symbol_id
125
- ) sym_def ON sym_def.symbol_id = gs.id
126
- JOIN documents d2 ON sym_def.document_id = d2.id
127
- WHERE d1.id != d2.id
128
- ${o}
129
- ${e.pathExclusionsFor("d1","d2")}
130
- ${r}`,...i)}function b1(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)}function cn(e){return{forFile(t,n){return vx(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,vx(e,i,n));return r}}}function vx(e,t,n){let r={file:t},i=n.facts||n.identifiers;if(n.text&&(r.text=_(e,t)),n.lines&&(r.lines=Qe(e,t)),n.ast&&(r.ast=oe(e,t)),n.imports&&(r.imports=Ce(e,t)),n.reexports&&(r.reexports=Di(e,t)),i){let o=Tm(e,t),s=o.facts;n.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),n.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}var S1={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Je(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=v1(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function $n(e){let t=Je(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 v1(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||xx(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&&!xx(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=S1[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function xx(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function P(e){let t=Je(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=x1(i);o&&r.push(o)}return r.join(":")}function x1(e){let t=e.suffix==="namespace"?R1(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function R1(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 M(e){let t=Je(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 $e(e){let t=Je(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function _e(e){return e.endsWith("().")||$e(e)==="method"}function ve(e){let t=$e(e);return t==="method"?!0:t!=="term"?!1:e.endsWith("().")?!0:e.startsWith("rust-analyzer ")&&e.includes("#")?!1:e.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(e):!0}function Hr(e){return $e(e)==="namespace"}var C1=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function et(e){return C1.test(e)}var w1=new Set(["test","tests","_tests"]);function No(e){let t=Je(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&&w1.has(r.name))return!0}return!1}function Rx(e,t){let n=Je(e),r=Je(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 Cx(e,t){let n=Je(e),r=Je(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}import{existsSync as Tl,readFileSync as k1,readdirSync as kx}from"fs";import{join as ia}from"path";var I1={files:new Set,pathPrefixes:[]},Ym=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,P1=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Ix=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],E1=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),D1=4,T1=me("package-surface",{clearGroups:["whole-project"]});function L1(e){return T1.get(e,()=>F1(e.config.projectRoot))}function Ti(e,t){let n=L1(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function F1(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of N1(e))for(let o of A1(r))_1(e,i,o,t,n);return t.size===0&&n.length===0?I1:{files:t,pathPrefixes:n}}function N1(e){let t=[],n=Ex(e,"");return n&&t.push({manifest:n,packageRoot:""}),Px(e,"",t,0),t}function Px(e,t,n,r){if(r>=D1)return;let i=ia(e,t);if(Tl(i))for(let o of kx(i,{withFileTypes:!0})){if(!o.isDirectory()||E1.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=Ex(e,s);a&&n.push({manifest:a,packageRoot:s}),Px(e,s,n,r+1)}}function Ex(e,t){try{let n=k1(ia(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function A1(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 Dx(e.exports,t),t}function Dx(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Dx(n,t)}function _1(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of wx(c))l!==""&&i.push(lr(t,l));return}let a=o.replace(P1,"");for(let c of wx(a)){c===a&&c===o&&r.add(lr(t,o));for(let l of Ix)M1(e,r,t,c+l)}r.add(lr(t,o))}function wx(e){let t=[e];return Ym.test(e)&&(t.push(e.replace(Ym,"src/")),t.push(e.replace(Ym,""))),t}function M1(e,t,n,r){let i=lr(n,r);if(t.add(i),!r.startsWith("src/")||Tl(ia(e,i)))return;let o=Ix.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);$1(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of Tx(e,n,c,`${l}${o}`))t.add(u)}function $1(e,t,n,r,i){let o=lr(n,`${r}/index${i}`);Tl(ia(e,o))&&t.add(o)}function Tx(e,t,n,r){let i=ia(e,t,n);if(!Tl(i))return[];let o=[];for(let s of kx(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Tx(e,t,a,r)):s.isFile()&&s.name===r&&o.push(lr(t,a))}return o}function lr(e,t){return e?`${e}/${t}`:t}import{existsSync as _l,readFileSync as mH,readdirSync as fH}from"fs";import{dirname as gH,join as Ml}from"path";function Li(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.start_char, der.end_line, der.end_char, d.relative_path, gs.display_name, gs.documentation
131
- FROM global_symbols gs
132
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
133
- JOIN documents d ON der.document_id = d.id
134
- WHERE ${t.where}
135
- ${e.pathExclusionsFor("d")}
136
- ${Fx(t.orderBy)}
137
- ${Nx(t.limit)}`,...t.params??[])}function Ao(e,t){return e.all(`SELECT
138
- gs.id,
139
- gs.symbol,
140
- c.document_id,
141
- MIN(c.start_line) AS start_line,
142
- 0 AS start_char,
143
- MAX(c.end_line) AS end_line,
144
- 0 AS end_char,
145
- d.relative_path,
146
- gs.display_name,
147
- gs.documentation
148
- FROM global_symbols gs
149
- JOIN mentions m ON m.symbol_id = gs.id
150
- JOIN chunks c ON m.chunk_id = c.id
151
- JOIN documents d ON c.document_id = d.id
152
- WHERE m.role = 1
153
- AND ${t.where}
154
- ${e.pathExclusionsFor("d")}
155
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
156
- ${Fx(t.orderBy)}
157
- ${Nx(t.limit)}`,...t.params??[])}function Fx(e){return e?`ORDER BY ${e}`:""}function Nx(e){return typeof e=="number"?`LIMIT ${e}`:""}function ur(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 dr(e){if(!e)return null;let t=Lx(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(Lx(r)??r).replace(/\n/g," ")}function Lx(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function O1(e,t={}){if($n(e.symbol)!==null)return t.includeClassMemberFallbacks===!0;let i=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Wr(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!O1(o,{includeClassMemberFallbacks:n.includeClassMemberFallbacks})||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 j1=ne("file-definitions",{clearGroups:["definition-catalog"]}),B1=ne("file-function-like-definitions",{clearGroups:["definition-catalog"]}),Ax=new WeakMap;function se(e,t,n={}){return n.includeClassMemberFallbacks?Qm(e,t,void 0,{includeClassMemberFallbacks:!0}):j1.get(e,t,()=>{let r=Ox(e,t);if(r)return r;let i=Qm(e,t),o=Ye(e),s=cn(e).forFile(t,{text:!0}).text;return o&&s&&$x.write(e,t,Ae(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function H1(e,t){return B1.get(e,t,()=>{let n=Ox(e,t);return n?n.filter(r=>r.isFunctionLike):Qm(e,t,r=>r.isFunctionLike)})}var $x=Ie({kind:"file-definitions",invalidation:pe("file-definitions"),serialize:W1,deserialize:q1});function Ox(e,t){let n=Ye(e);if(!n)return null;let r=cn(e).forFile(t,{text:!0}).text;if(!r)return null;let i=$x.read(e,t,Ae(e,t,r));return i?U1(i,n,t):null}function W1(e){return JSON.stringify(e)}function q1(e){try{let t=JSON.parse(e);return!ee(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function U1(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=V1(i,n);if(!o)return null;r.push(o)}return r}function V1(e,t){return!ee(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.startChar!="number"&&e.startChar!==void 0||typeof e.endLine!="number"||typeof e.endChar!="number"&&e.endChar!==void 0||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,startChar:e.startChar,endLine:e.endLine,endChar:e.endChar,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function Qm(e,t,n,r={}){let i=Wr(G1(e,t),z1(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(jx);return n&&(i=i.filter(n)),Wx(e,t,i)}function G1(e,t){return e.all(`SELECT
158
- gs.id,
159
- gs.symbol,
160
- der.document_id,
161
- der.start_line,
162
- der.start_char,
163
- der.end_line,
164
- der.end_char,
165
- d.relative_path,
166
- gs.display_name,
167
- gs.kind,
168
- gs.documentation,
169
- gs.enclosing_symbol
170
- FROM global_symbols gs
171
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
172
- JOIN documents d ON der.document_id = d.id
173
- WHERE d.relative_path = ?
174
- ${e.symbolNoiseFor("gs")}
175
- ORDER BY der.start_line, der.end_line`,t)}function z1(e,t){return e.all(`SELECT
176
- gs.id,
177
- gs.symbol,
178
- c.document_id,
179
- MIN(c.start_line) AS start_line,
180
- 0 AS start_char,
181
- MAX(c.end_line) AS end_line,
182
- 0 AS end_char,
183
- d.relative_path,
184
- gs.display_name,
185
- gs.kind,
186
- gs.documentation,
187
- gs.enclosing_symbol
188
- FROM global_symbols gs
189
- JOIN mentions m ON m.symbol_id = gs.id
190
- JOIN chunks c ON m.chunk_id = c.id
191
- JOIN documents d ON c.document_id = d.id
192
- WHERE d.relative_path = ?
193
- AND m.role = 1
194
- ${e.symbolNoiseFor("gs")}
195
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
196
- ORDER BY start_line, end_line`,t)}function jx(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:M(e.symbol),parentTypeName:$n(e.symbol),isFunctionLike:ve(e.symbol),isTypeLike:$e(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Ue(e,t={}){return Xm(e,t.scope)}function Xm(e,t){return q(e,{scope:t,includeIgnored:!1}).flatMap(n=>se(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Bx(e,t){return q(e,{scope:t,includeIgnored:!1}).flatMap(n=>H1(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function oa(e,t){let n=_x(K1(e,t.scope,t.sqlPrefilter)),r=_x(J1(e,t.scope,t.sqlPrefilter)),i=new Set([...n.keys(),...r.keys()]),o=[];for(let s of[...i].sort()){if(e.isIgnored(s))continue;let a=Wr(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...Wx(e,s,a.map(jx)))}return o}function K1(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${Hx("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
197
- gs.id,
198
- gs.symbol,
199
- der.document_id,
200
- der.start_line,
201
- der.start_char,
202
- der.end_line,
203
- der.end_char,
204
- d.relative_path,
205
- gs.display_name,
206
- gs.kind,
207
- gs.documentation,
208
- gs.enclosing_symbol
209
- FROM global_symbols gs
210
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
211
- JOIN documents d ON der.document_id = d.id
212
- WHERE 1 = 1
213
- ${e.pathExclusionsFor("d")}
214
- ${r}
215
- ${i}
216
- ${e.symbolNoiseFor("gs")}
217
- ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function J1(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${Hx("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
218
- gs.id,
219
- gs.symbol,
220
- c.document_id,
221
- MIN(c.start_line) AS start_line,
222
- 0 AS start_char,
223
- MAX(c.end_line) AS end_line,
224
- 0 AS end_char,
225
- d.relative_path,
226
- gs.display_name,
227
- gs.kind,
228
- gs.documentation,
229
- gs.enclosing_symbol
230
- FROM global_symbols gs
231
- JOIN mentions m ON m.symbol_id = gs.id
232
- JOIN chunks c ON m.chunk_id = c.id
233
- JOIN documents d ON c.document_id = d.id
234
- WHERE m.role = 1
235
- ${e.pathExclusionsFor("d")}
236
- ${r}
237
- ${i}
238
- ${e.symbolNoiseFor("gs")}
239
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
240
- ORDER BY d.relative_path, start_line, end_line`,...o)}function Y1(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function Hx(e,t){return t==="callable"?Y1(e):Q1(e)}function Q1(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function _x(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function Ll(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>se(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:P(i.symbol),signature:ur(dr(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Zm(e){let t=new Map,n=e.map((r,i)=>({definition:r,index:i,span:r.endLine-r.startLine})).sort((r,i)=>r.span-i.span||r.index-i.index);for(let{definition:r}of n)for(let i=r.startLine;i<=r.endLine;i+=1)t.has(i)||t.set(i,r);return t}function On(e,t){let n=Ax.get(e);return n||(n=Zm(e),Ax.set(e,n)),n.get(t)??null}function Fl(e,t){let n=se(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,startChar:t.start_char??0,endLine:t.end_line,endChar:t.end_char??0,relativePath:t.relative_path}}function Wx(e,t,n){let r=cn(e).forFile(t,{text:!0}).text,i=Fm(e,t);return i?rH(n,i,r):r?X1(n,r):n}function X1(e,t){let n=t.split(/\r?\n/),r=Z1(e,n),i=eH(e,r),o=tH(i,n);return nH(e,o)}function Z1(e,t){let n=e.some(i=>Nl(i.symbol))?uH(t):null,r=new Map;for(let i of e)r.set(i.symbolId,lH(t,n,i));return r}function eH(e,t){return e.filter(n=>Nl(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 tH(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:dH(t,i.definition,i.startLine,s)})}return n}function nH(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function rH(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(!cH(i)||!i.leaf)return Mx(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Mx(i,n);let s=n?iH(i,o,n):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let u=o[l],d=Math.abs(u.startLine-i.startLine);d<c&&(a=u,c=d)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function iH(e,t,n){let r=oH(e.symbol);if(!r)return null;let i=n.split(/\r?\n/),o=new RegExp(`\\b${J(r)}\\b`);for(let s of t){let a=sH(i,s.startLine);if(a&&o.test(a))return s}return null}function oH(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function sH(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return aH(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function aH(e,t,n){let r=[];for(let i=t;i<=n;i+=1){let o=e[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function cH(e){return Nl(e.symbol)?!0:$e(e.symbol)==="term"&&$n(e.symbol)===null}function Mx(e,t){if(!t||!e.leaf||$e(e.symbol)!=="term"||$n(e.symbol)!==null)return e;let n=J(e.leaf),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 lH(e,t,n){if(!Nl(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 uH(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 dH(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=pH(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function pH(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 Nl(e){return e.includes("().")}function Al(e){let t=Je(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}var hH={rootFiles:new Set,sourcePrefixes:[]},yH=new Set([".git",".scipquery","node_modules","target"]),bH=6,SH=me("rust-library-surface",{clearGroups:["whole-project"]});function qx(e,t,n){if(!n.endsWith(".rs")||!RH(vH(e),n))return!1;let r=se(e,n).find(i=>i.symbol===t);return r?CH(Qe(e,n)[r.startLine]??""):!1}function vH(e){return SH.get(e,()=>xH(e.config.projectRoot))}function xH(e){let t=new Set,n=new Set;for(let r of wH(e)){let i=Ml(e,r,"Cargo.toml"),o=mH(i,"utf8"),s=kH(o),a=lr(r,"src/lib.rs"),c=s?lr(r,s):!IH(o)&&_l(Ml(e,a))?a:null;if(!c)continue;t.add(c);let l=gH(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?hH:{rootFiles:t,sourcePrefixes:[...n].sort()}}function RH(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:PH(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function CH(e){return/^\s*pub\s+(?!\()/.test(e)}function wH(e){if(!_l(e))return[];let t=[];return Ux(e,"",t,0),t}function Ux(e,t,n,r){let i=Ml(e,t);if(_l(i)&&(_l(Ml(i,"Cargo.toml"))&&n.push(t),!(r>=bH)))for(let o of fH(i,{withFileTypes:!0})){if(!o.isDirectory()||yH.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;Ux(e,s,n,r+1)}}function kH(e){let t=!1;for(let n of e.split(`
241
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function IH(e){let t=!1;for(let n of e.split(`
242
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function PH(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function fe(e){let t=Se(e);return UH(t)?"test":VH(t)?"worker":GH(t)?"entry":zH(t)?"barrel":"source"}function _o(e){return fe(e)==="barrel"}function Gx(e){return EH.get(e,()=>{let n=q(e,{includeIgnored:!1}).filter(s=>{let a=fe(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=ge(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),fe(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var EH=me("live-barrels",{clearGroups:["whole-project"]});function ef(e,t){return Gx(e).has(Se(t))}function zx(e){let t=Gx(e);return q(e,{includeIgnored:!1}).filter(n=>_o(n)&&!t.has(n)&&!DH(e,n))}function DH(e,t){let n=Se(t),r=cn(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
243
- FROM defn_enclosing_ranges der
244
- JOIN documents d ON d.id = der.document_id
245
- WHERE d.relative_path = ?
246
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function tt(e,t){let n=Se(t),r=fe(t);return r==="entry"||r==="worker"||HH(n)||ef(e,n)}function Oe(e,t,n){let r=Se(n);if(Ti(e,r)||LH(e,t,r)||qx(e,t,r)||BH(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>Se(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(Se(o)))||i.qualifiedVars?.some(o=>KH(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var TH=me("package-surface-reachability",{clearGroups:["whole-project"]});function LH(e,t,n){let r=FH(e).get(n);return r===void 0?!1:r===null||r.has(M(t))}function FH(e){return TH.get(e,()=>{let t=new Map,n=[];for(let r of q(e,{includeIgnored:!1}))Ti(e,r)&&(t.set(r,null),n.push(r));for(;n.length>0;){let r=n.shift(),i=t.get(r);if(i!==void 0)for(let o of Di(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=NH(i,o);s!==void 0&&AH(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function NH(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function AH(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var Kx=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),_H=new Set(["default","generateMetadata","generateStaticParams"]),MH=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),$H=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),OH=new Set(["load","actions","entries",...Kx]),jH=new Set(["default"]);function BH(e,t){let n=M(e);return n===""?!1:Jx(t)?Kx.has(n):Yx(t)?_H.has(n):Qx(t)?MH.has(n):Xx(t)?$H.has(n):Zx(t)?OH.has(n):qH(t)?jH.has(n):!1}function HH(e){return Jx(e)||Yx(e)||Qx(e)||WH(e)||Xx(e)||Zx(e)}function Jx(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Yx(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Qx(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function WH(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function Xx(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Zx(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function qH(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function UH(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 VH(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function GH(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 zH(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 KH(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(Vx(r)+"/")&&e.includes(Vx(i)+".")}function Vx(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function $l(e,t,n,r={}){if(!n)return[];let i=_(e,t);return i?i.indexOf(n)===-1?[]:(pr(e,t).get(n)??[]).filter(s=>!JH(s,r)):[]}function JH(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var YH=ne("file-identifiers",{clearGroups:["whole-project","source-file"]});function eR(e,t){let n=ce(e,t);return n?n.fileIdentifiers:YH.get(e,t,()=>new Set(pr(e,t).keys()))}var QH=ne("file-ident-lines",{clearGroups:["whole-project","source-file"]});function pr(e,t){let n=ce(e,t);return n?n.identifierLineMap:QH.get(e,t,()=>ZH(e,t))}var XH=ne("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function tR(e,t){let n=ce(e,t);return n?n.identifiersByLine:XH.get(e,t,()=>{let r=pr(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 ZH(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=_(e,t);if(!i)return n;let o=kt(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 te(e,t){return Ht(e,t).match}function Ht(e,t){let n=rR(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return sa(e,n);let r=sW(e,t);if(r&&!e.isIgnored(r.relative_path))return sa(e,[r]);let i=eW(e,t);return i.length>0?sa(e,i):iW(e,t)}function eW(e,t){let n=jl(t),r=tf(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return tW(e,i,o,n)}function tW(e,t,n,r){let i=Wr([],[...nW(e,t,n),...rW(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Mo(o,r)>1);return i.sort((o,s)=>Mo(s,r)-Mo(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 nW(e,t,n){return Li(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function rW(e,t,n){return Ao(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function iW(e,t){let n=jl(t),r=pW(t),i=uW(e,r),o=mW(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return sa(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=dW(a,t,n,r);c<=0||s.push({row:a,score:c})}return s.sort((a,c)=>c.score-a.score||a.row.end_line-a.row.start_line-(c.row.end_line-c.row.start_line)||a.row.relative_path.localeCompare(c.row.relative_path)||a.row.symbol.localeCompare(c.row.symbol)),sa(e,s.map(a=>a.row))}function sa(e,t){let n=t.map(i=>Fl(e,i)),r=n[0]??null;return{match:r,candidates:r?oW(n,r):[],total:n.length}}function oW(e,t){let n=new Set([`${t.symbolId}:${t.relativePath}:${t.startLine}`]),r=[];for(let i of e){let o=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!n.has(o)&&(n.add(o),r.push({symbol:i.symbol,shortName:P(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),r.length>=5))break}return r}function sW(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1);return aW(e,r,s,a)??cW(e,r,s,a)}function aW(e,t,n,r){return Li(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 cW(e,t,n,r){return Ao(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 aa(e,t){let n=rR(e,t).find(r=>!e.isIgnored(r.relative_path));return n?Fl(e,n):null}function rR(e,t){let n=Li(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line"}),r=n.length>0?[]:Ao(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line"});return Wr(n,r)}function Ol(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=lW(e,t.symbolId)[0];return n?Fl(e,n):null}function lW(e,t){let n=Li(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Ao(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Wr(n,r)}function uW(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(`
247
- AND `),o=Li(e,{where:i,params:r,limit:200}),s=Ao(e,{where:i,params:r,limit:200});return Wr(o,s)}function dW(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,d=P(e.symbol),p=M(e.symbol),m=e.display_name??"",f=e.symbol.toLowerCase(),g=d.toLowerCase(),h=p.toLowerCase(),y=m.toLowerCase(),x=e.relative_path.toLowerCase(),R=/[/:.]/.test(n),b=tf(n),v=b?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(d===i||d===o)&&(w+=1100),m===s&&(w+=1180),p===s&&(w+=1160),(`${p}()`===i||`${p}()`===o)&&(w+=955),(f===a||f===c)&&(w+=1e3),(g===a||g===c)&&(w+=950),(x===a||x===c)&&(w+=925),(x.endsWith(`/${c}`)||x.endsWith(`/${a}`))&&(w+=875),y===l&&(w+=850),h===l&&(w+=825),(`${h}()`===a||`${h}()`===c)&&(w+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(w+=800),f.includes(c)&&(w+=120),g.includes(c)&&(w+=140),x.includes(c)&&(w+=140),y.includes(c)&&(w+=110),r.every(I=>{let C=I.toLowerCase();return f.includes(C)||g.includes(C)||x.includes(C)||y.includes(C)})&&(w+=100+r.length*15),b&&x.includes(b.path.toLowerCase())&&(w+=360,v&&(h===v||`${h}()`===v||`${h}()`==`${v}()`)&&(w+=700),_e(e.symbol)&&(w+=180)),ve(e.symbol)&&h===l&&(w+=60),!R&&Hr(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function tf(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 jl(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function pW(e){let t=jl(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 mW(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=P(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||Mo(o,n)>1||o.relative_path===r});return i.length===0?[]:(i.sort((o,s)=>Mo(s,n)-Mo(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)}function Mo(e,t){let n=tf(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=M(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:_e(e.symbol)?$n(e.symbol)===null?5:4:$n(e.symbol)===null?3:2:0}function nf(e,t,n=5){let r=nR(t);if(!r)return[];let i=Li(e,{where:"1 = 1",orderBy:"d.relative_path, der.start_line",limit:5e3}),o=new Map;for(let s of i){if(e.isIgnored(s.relative_path))continue;let a=P(s.symbol),c=M(s.symbol),l=s.display_name??c,u=[a,c,l].filter(m=>m.trim().length>0),d=Math.min(...u.map(m=>fW(nR(m),r))),p=o.get(a);(!p||d<p.distance)&&o.set(a,{shortName:a,distance:d})}return[...o.values()].sort((s,a)=>s.distance-a.distance||s.shortName.localeCompare(a.shortName)).slice(0,n).map(s=>s.shortName)}function nR(e){return jl(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function fW(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=0;r<e.length;r++){let i=[r+1];for(let o=0;o<t.length;o++){let s=e[r]===t[o]?0:1;i[o+1]=Math.min(i[o]+1,n[o+1]+1,n[o]+s)}n=i}return n[t.length]}function iR(e,t){return Bl(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
248
- m.symbol_id,
249
- d.relative_path,
250
- COUNT(*) AS ref_count
251
- FROM mentions m
252
- JOIN chunks c ON m.chunk_id = c.id
253
- JOIN documents d ON c.document_id = d.id
254
- WHERE m.role != 1
255
- ${r}
256
- ${e.pathExclusionsFor("d")}
257
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function oR(e,t){return Bl(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
258
- FROM mentions m
259
- JOIN chunks c ON m.chunk_id = c.id
260
- JOIN documents d ON c.document_id = d.id
261
- WHERE m.role != 1
262
- ${r}
263
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function sR(e,t){return Bl(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id
264
- FROM mentions m
265
- WHERE m.role != 1
266
- ${r}`,...n??[])}).filter(n=>n.symbol_id!==null)}function $o(e,t){return Bl(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
267
- c.start_line AS chunk_start, c.end_line AS chunk_end
268
- FROM mentions m
269
- JOIN chunks c ON m.chunk_id = c.id
270
- JOIN documents d ON c.document_id = d.id
271
- WHERE m.role != 1
272
- ${r}
273
- ${e.pathExclusionsFor("d")}
274
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function Bl(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 Hl(e,t){let n=aR(e);return n?t.filter(r=>aR(r.file)===n):t}function Wl(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(_t(a,s.file))return s;return null}return n.length===1?n[0]:null}function aR(e){let t=K(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var gW=me("global-leaf-index",{clearGroups:["whole-project"]});function mr(e){return gW.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
275
- COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
276
- FROM global_symbols gs
277
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
278
- LEFT JOIN documents der_doc ON der_doc.id = der.document_id
279
- LEFT JOIN (
280
- SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
281
- FROM mentions m
282
- JOIN chunks c ON m.chunk_id = c.id
283
- JOIN documents d ON c.document_id = d.id
284
- WHERE m.role = 1
285
- GROUP BY m.symbol_id
286
- ) mention_doc ON mention_doc.symbol_id = gs.id
287
- WHERE 1 = 1
288
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=M(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})}var cR=/[A-Za-z_$][A-Za-z0-9_$]*/g,lR=/^[A-Za-z_$][A-Za-z0-9_$]*$/,hW=512;function ca(e){let t=[],n=!1;for(let r of e)r&&(n=!0,lR.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function ql(e,t){let n=yW(t)?t:ca(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=hW){for(let i of n.candidateNames)if(i){if(lR.test(i)){if(bW(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}cR.lastIndex=0;let r;for(;(r=cR.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function yW(e){return"candidateNames"in e}function bW(e){return new RegExp(`(?<![A-Za-z_$0-9])${J(e)}(?![A-Za-z_$0-9])`)}function uR(e){let t=new Map,n=vW(e),r=new Map;return i=>{let o=SW(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=xW(se(e,i.file)),t.set(i.file,a));let c=RW(a,i);return r.set(o,c),c}}function SW(e){return`${e.file}\0${e.symbol}\0${e.line}`}function vW(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function xW(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function RW(e,t){if(e.definitions.length===0)return t.symbol;let n=kW(t.symbol),r=CW(e.byLeaf,n),i=wW(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function CW(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function wW(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function kW(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function dR(e,t){let r=Ce(e,t).map(i=>PW(t,i));return{usage:r,positions:EW(e,t,r)}}function pR(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?IW(r.usage,i.sourcePaths):r.usage}}}function IW(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function PW(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function EW(e,t,n){let r=oe(e,t);if(!r)return[];let i=DW(r.rootNode),o=new Map;for(let a of i){let c=o.get(of(a.importedName,a.localName));c?c.push(a.position):o.set(of(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(of(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function DW(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Ul(r,""))}return t.filter(n=>n.importedName!=="*")}function Ul(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:rf(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:rf(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Fo(t,n.text);return r.namedChildren.flatMap(o=>Ul(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Ul(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Ul(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:rf(n??e,r)}]}default:return[]}}function rf(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+TW(t)}}function TW(e){return Math.max(0,Math.min(e.length-1,1))}function of(e,t){return`${e}\0${t}`}import{spawnSync as Cf}from"child_process";import{existsSync as wf}from"fs";import{fileURLToPath as Qq}from"url";function qr(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{existsSync as mR,readdirSync as LW}from"fs";import{isAbsolute as FW,join as sf,resolve as NW}from"path";var AW={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",FW(r)?r:NW(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},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",fR(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",fR(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=sf(e,"vendor","bin","scip-php"),r=sf(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",mR(r)?r:mR(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function fr(e){return AW[e]}function fR(e,t){let n;try{n=LW(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return sf(e,i);return null}import{execFileSync as cf}from"child_process";import{existsSync as af,readFileSync as OW}from"fs";import{createRequire as jW}from"module";import{platform as BW}from"os";import{dirname as gR,join as Vl}from"path";import{execFileSync as _W}from"child_process";import{platform as MW}from"os";var $W=MW()==="win32";function jn(e){let t=$W?"where":"which";try{return _W(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var HW=jW(import.meta.url);function lf(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Gl(e){let t=lf(e);return t.length===1?t[0]:t.join(" or ")}function Oo(e){for(let t of lf(e))if(jn(t))return t;return qW(e)}function hR(e){return Oo(e)!==null||WW(e)}function WW(e){return yR(e)!==null}function qW(e){let t=yR(e);if(!t)return null;let r=JSON.parse(OW(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Vl(gR(t),r);for(let i of lf(e)){let o=r[i];if(o)return Vl(gR(t),o)}return null}function yR(e){if(!e.bundledNpmPackage)return null;try{return HW.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function uf(e,t){for(let n of e.projectLocalBinaries??[]){let r=Vl(t,n);if(af(r))return r}return null}function UW(e,t){return uf(e,t)??Oo(e)}function bR(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||df(n,t))return t;let r=SR(n,t);return r?{...t,DOTNET_ROOT:r}:t}function jo(e,t){let n=Gl(e),r=t?UW(e,t):Oo(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=VW(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function zl(e,t){let n=e.installMethods,r=Gl(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(jn(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{cf(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Oo(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 VW(e){if(df(e,process.env))return{runnable:!0};let t=SR(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=vR(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 SR(e,t){for(let n of vR(t))if(df(e,{...t,DOTNET_ROOT:n}))return n;return null}function vR(e){let t=[],n=e.DOTNET_ROOT;if(n&&af(n)&&t.push(n),BW()==="darwin"&&jn("brew"))try{let r=cf("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Vl(r,"libexec");af(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function df(e,t){try{return cf(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}function Bo(e){let t=jo(fr("rust"),e),n=t.runnable;return{available:n,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:n?"rust-analyzer semantic reference queries are enabled.":"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as Mq,mkdtempSync as GR,readFileSync as zR,rmSync as yf}from"fs";import{tmpdir as vf}from"os";import{join as bf}from"path";import{fileURLToPath as ma,pathToFileURL as $q}from"url";import{SHARE_ENV as Oq,Worker as jq}from"worker_threads";function xe(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}}function Ur(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Fi(e,t,n){let r=qr(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as Cq}from"child_process";import{createHash as wq,randomUUID as kq}from"crypto";import{existsSync as jR,mkdirSync as AR,readFileSync as Xl,realpathSync as Iq,rmSync as gf}from"fs";import{tmpdir as Pq}from"os";import{resolve as Bn}from"path";import{mkdirSync as GW,renameSync as zW,writeFileSync as KW}from"fs";import{dirname as JW}from"path";function he(e,t,n={}){GW(JW(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`,i=JSON.stringify(t,null,n.spacing);KW(r,n.trailingNewline?`${i}
289
- `:i),zW(r,e)}import{execFileSync as iq}from"child_process";import{existsSync as YW,readFileSync as QW}from"fs";import{deserializeSCIP as XW,SymbolRole as ZW}from"@c4312/scip";import{existsSync as HSe,readFileSync as WSe}from"fs";import{relative as USe,resolve as VSe,sep as GSe}from"path";import{fileURLToPath as KSe,pathToFileURL as JSe}from"url";function Kl(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var pf=new WeakMap,eq="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function xR(e,t){let n=new Map,r=Jl(),i=t.filter(s=>wR(s,r));if(i.length===0)return n;let o=kR(e);if(!o)return n;for(let s of i){let a=CR(o,s);a!==null&&n.set(s.symbolId,a)}return n}function RR(e,t){if(!wR(t,Jl()))return null;let n=kR(e);return n?CR(n,t):null}function CR(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function wR(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||et(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=$e(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Je(e.symbol);return"kind"in r?!1:!tq(r)}function tq(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function kR(e){if(pf.has(e))return pf.get(e)??null;let t=nq(e);return pf.set(e,t),t}function nq(e){if(!YW(e.config.indexPath))return null;try{let t=XW(QW(e.config.indexPath)),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&ZW.Definition)!==0)continue;let s=rq(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,Kl(i));return{referencesBySymbol:n}}catch{return null}}function rq(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function Jl(){return process.env[eq]==="all"?"all":"safe"}var IR=new Map;function mf(e){let n=Bo(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?oq(e,n):"unavailable"}}function Ni(e){return{...mf(e),scipOccurrenceReferenceMode:Jl()}}function oq(e,t){let n=`${e}\0${t}`,r=IR.get(n);if(r)return r;let i;try{i=iq(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return IR.set(n,i),i}import{createHash as vq}from"crypto";import{execFileSync as sq}from"child_process";import{createHash as PR}from"crypto";import{lstatSync as aq,readdirSync as cq,readFileSync as lq,readlinkSync as uq,realpathSync as ER}from"fs";import{isAbsolute as dq,join as DR,relative as pq,sep as mq}from"path";function Ho(e,t){let n=e.split("/").at(-1)??e;if(LR.has(n)||n===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(n))return"config";if(/\.d\.(?:ts|mts|cts)$/.test(e.toLowerCase()))return"ambient";let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return t.some(i=>(FR[i]??[]).includes(r))?"source":"other"}function ff(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function fq(e){return(yq(e)??bq(e)).filter(t=>t&&!TR(t)).sort()}function Ai(e,t={}){let n=fq(e).filter(i=>!t.language||hq(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=ER(e);return n.map(i=>{let o=DR(e,i);try{if(aq(o).isSymbolicLink()){let a=ER(o),c=pq(r,a);if(c===".."||c.startsWith(`..${mq}`)||dq(c))throw new Error("external symlink");let l=uq(o);return{path:i,size:Buffer.byteLength(l),hash:PR("sha256").update("symlink\0").update(l).digest("hex")}}let s=lq(o);return{path:i,size:s.byteLength,hash:PR("sha256").update(s).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function _i(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:ff(n.typescriptProjects),clojureConfigPath:gq(n.clojureConfigPath),files:Ai(e)}}function gq(e){return e?.trim()||void 0}function hq(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||LR.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(FR[t]??[]).includes(i)}function yq(e){try{return sq("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
290
- `).filter(Boolean)}catch{return null}}function bq(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?DR(e,r):e,o;try{o=cq(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){TR(a)||n.push(a);continue}t.push(a)}}return t}function TR(e){let t=e.split("/");return e==="meta.json"||t.some(n=>Sq.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var Sq=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),LR=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),FR={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};var xq=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function NR(e){let t=Ai(e,{includePath:Rq});return vq("sha256").update(JSON.stringify(t)).digest("hex")}function Rq(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||xq.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}var BR=2,Eq=5e3,Dq=5e3,HR=10,Tq=3e4;function _R(e,t,n,r=VR){let i=r.engineIdentity(e),o={protocolVersion:BR,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:WR(r.environment())};return{key:Ql(Yl(o)),...o}}function la(e,t,n){return e.protocolVersion===BR&&(t-e.heartbeatAtMs<=Eq||e.busyUntilMs!==void 0&&t<=e.busyUntilMs)&&n(e.pid)}function hf(e,t,n){let r;try{r=Ql(Xl(t))}catch{r="missing"}let i=Ql(Yl({projectRoot:Bn(e),serverPath:Bn(t),serverFingerprint:r})).slice(0,20);return Bn(n,`scip-query-rust-session-${i}`)}function MR(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function WR(e){return Object.fromEntries(Object.entries(e).filter(([t])=>UR(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function qR(e,t){let n=t.runtime??_q,r=t.identityRuntime??VR,i=hf(e,t.serverPath,t.tempRoot??Pq()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return Fq(i,t.serverPath,t.semanticWorkerPath,a,c,n)};return{requestSemantic(a,c){let l=_R(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"semantic",identityKey:l.key,workerEnvironment:OR(),request:{...a,readinessDeadlineMs:u,referenceRetryTimeoutMs:Lq(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:MR(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=_R(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:OR(),request:{...a,readinessDeadlineMs:u,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:MR(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function Lq(e,t){return t!==void 0?t:e===void 0?Tq:void 0}function Fq(e,t,n,r,i,o){let s=o.randomId(),a=o.now(),c=Bn(e,"requests"),l=Bn(e,"responses"),u=Bn(c,`${s}.json`),d=Bn(l,`${s}.json`);AR(c,{recursive:!0}),AR(l,{recursive:!0}),he(u,{id:s,request:r});let p=o.now()+i;try{for($R(e,t,n,p,o);o.now()<=p;){if(jR(d)){let f=Nq(Xl(d,"utf8"));if(!f.ok)throw new Error(f.error);return re()&&jt({type:"span",name:"rust.semantic.durable-session.request",durationMs:o.now()-a,ok:!0,session:f.session,kind:r.kind}),f.response}let m=ua(e);(!m||!la(m,o.now(),o.isProcessAlive))&&$R(e,t,n,p,o),o.sleep(HR)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}finally{gf(u,{force:!0}),gf(d,{force:!0})}}function $R(e,t,n,r,i){let o=ua(e);if(o&&la(o,i.now(),i.isProcessAlive))return;gf(Bn(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=Math.min(r,i.now()+Dq);for(;i.now()<=s;){let a=ua(e);if(a&&la(a,i.now(),i.isProcessAlive))return;i.sleep(HR)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function ua(e){try{let t=JSON.parse(Xl(Bn(e,"server.json"),"utf8"));return typeof t.protocolVersion!="number"||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"?null:{protocolVersion:t.protocolVersion,pid:t.pid,heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs}}}catch{return null}}function Nq(e){try{let t=JSON.parse(e);return t.ok===!0&&(t.session==="created"||t.session==="reused"||t.session==="invalidated")&&t.response&&typeof t.response=="object"?{ok:!0,session:t.session,response:t.response}:{ok:!1,error:typeof t.error=="string"?t.error:"helper wrote an invalid response"}}catch(t){return{ok:!1,error:`helper wrote malformed JSON: ${t instanceof Error?t.message:String(t)}`}}}function OR(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>Aq(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function UR(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Aq(e){return UR(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var VR={canonicalProjectRoot(e){try{return Iq(e)}catch{return Bn(e)}},projectFingerprint(e){return NR(e)},engineIdentity:mf,fileFingerprint(e){return Ql(Xl(e))},environment(){return WR(process.env)}},_q={now:Date.now,randomId:kq,isProcessAlive:xe,spawnServer(e,t,n){if(!jR(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);Cq(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Yl(e){return Array.isArray(e)?`[${e.map(Yl).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Yl(n)}`).join(",")}}`:JSON.stringify(e)}function Ql(e){return wq("sha256").update(e).digest("hex")}var KR=15e3,JR=8,QR=5e3,Bq=64,Hq=96,xf=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??Uq(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,references:da(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:Ur(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:da(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:pa(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,callees:Sf(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:pa(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:da(t),callees:pa(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{available:o.available,resolvedBinary:r.resolvedBinary,reason:o.reason,references:Ur(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Sf(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,signatures:YR(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,signatures:Jq(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:YR(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return{available:r.available,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{available:i.available,resolvedBinary:r.resolvedBinary,reason:i.reason,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Zl(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,KR),o=eu(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Zl(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,JR),a=eu(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=fa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),p={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},m=Yq(p);return D("rust.semantic.session.request",()=>this.requester.requestSemantic(p,Fi(m,Rf(i,p.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:m,referenceDefinitions:p.referenceDefinitions?.length,calleeDefinitions:p.calleeDefinitions?.length,signatureDefinitions:p.signatureDefinitions?.length,references:p.includeReferences!==!1,callees:p.includeCallees===!0,signatures:p.includeSignatures===!0,referenceRetryTimeoutMs:p.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,references:da(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:pa(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?{available:o.available&&s.available,resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,reason:o.reason??s.reason,references:Ur(n,o.references),callees:Sf(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:da(n),callees:pa(r)}}requestImportDefinitions(t,n,r){let i=Zl(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,KR),o=Zl(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,JR),s=eu(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=eu(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,QR),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return D("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Fi(r.length,i,o)),()=>({file:n,positions:r.length}))}};function XR(e,t,n={}){return new xf(e,t,n)}function fa(e,t){let n=nC(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=Bq||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=Hq?0:QR}function ZR(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function Wq(e){return ZR(e).transport}function tu(e,t){let n=ZR(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=ma(tC()),i=hf(e,r,vf()),o=ua(i);return o?{...n,state:la(o,Date.now(),xe)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function qq(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,p)=>{let m=Kq(u);r=!0;try{a()}catch{}re()&&jt({type:"span",name:"rust.semantic.durable-session.request",durationMs:p,ok:!1,kind:d,session:"worker-fallback",reason:m})},l=(u,d,p)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return p(s());let m=Date.now();try{return d(e)}catch(f){c(f,u,Date.now()-m)}return p(s())};return{requestSemantic(u,d){return l("semantic",p=>p.requestSemantic(u,d),p=>p.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",p=>p.requestImportDefinitions(u,d),p=>p.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function Uq(e,t,n={worker:()=>Vq(),durable:()=>qR(e,{serverPath:ma(tC()),semanticWorkerPath:ma(eC())})}){return Wq(t)==="durable"?qq(n.durable(),n.worker):n.worker()}function Vq(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(yf(n,{recursive:!0,force:!0}),n=null)},s=()=>{let l=t;t=null,l&&l.terminate(),o()},a=()=>{if(t)return t;let l=e.semanticWorkerPath?$q(e.semanticWorkerPath):eC();if(!Mq(ma(l)))throw new Error(`Rust semantic session worker was not found at ${ma(l)}. Run npm run build before using built semantic Rust queries.`);return n=GR(bf(vf(),"scip-query-rust-session-")),t=new jq(l,e.shareEnvironment?{env:Oq}:void 0),t.unref(),t},c=()=>{let l=n??GR(bf(vf(),"scip-query-rust-session-"));return n=l,bf(l,`${r++}.json`)};return{requestSemantic(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),p=c(),m=new SharedArrayBuffer(4),f=new Int32Array(m);if(d.postMessage({kind:"semantic",request:l,responsePath:p,sharedBuffer:m}),Atomics.wait(f,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let h=Gq(zR(p,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{yf(p,{force:!0})}},requestImportDefinitions(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),p=c(),m=new SharedArrayBuffer(4),f=new Int32Array(m);if(d.postMessage({kind:"import-definitions",request:l,responsePath:p,sharedBuffer:m}),Atomics.wait(f,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic import-definition session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let h=zq(zR(p,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{yf(p,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){o();return}let l=c(),u=new SharedArrayBuffer(4),d=new Int32Array(u);t.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:u}),Atomics.wait(d,0,0,5e3),s()}}}function Gq(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function zq(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function Kq(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function da(e){return new Map(e.map(t=>[t.symbolId,[]]))}function pa(e){return new Map(e.map(t=>[t.symbolId,[]]))}function YR(e){return new Map(e.map(t=>[t.symbolId,null]))}function Sf(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function Jq(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Yq(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function Rf(e,t){return t&&t>0?Math.max(e,t):e}function eC(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function tC(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Zl(e,t){return qr(e)??t}function eu(e,t){return nC(e)??t}function nC(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var kf=15e3,If=8;function sC(e,t={}){let n=t.status??Bo,r=eU(e,n),i=tU(e,n),o=nU(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!Xq(t)?null:XR(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??pR(t.sourceImportUsageResolver??Zq(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,p=t.sourceZeroCalleeOracle,m=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,y=null,x=()=>(h??=n(e),h),R=()=>{let C=x();return C.dependencyAvailable?y??C:C},b=C=>{if(C.length===0)return new Map;let k=ga(C);try{let T=a.referencesForDefinitions(k),F=x();return y={...F,available:T.available,resolvedBinary:T.resolvedBinary??F.resolvedBinary,reason:T.reason??F.reason},T.available?new Map(T.references):Ur(k,T.references)}catch(T){return y={...x(),available:!1,reason:T instanceof Error?T.message:String(T)},Mi(k)}},v=C=>{if(C.length===0)return new Map;let k=ga(C),T=k.filter(rC);if(T.length===0)return $i(k);let F=new Map,V=oC(T,m),ie=[];for(let W of T)g.has(W.symbolId)?F.set(W.symbolId,g.get(W.symbolId)??[]):V.has(W.symbolId)?F.set(W.symbolId,V.get(W.symbolId)??[]):iC(W,p)?F.set(W.symbolId,[]):ie.push(W);if(ie.length===0)return Wo(k,F,void 0);try{let W=c.calleesForDefinitions(ie),be=x();y={...be,available:W.available,resolvedBinary:W.resolvedBinary??be.resolvedBinary,reason:W.reason??be.reason};let Z=Wo(ie,W.callees,d);for(let[Re,ht]of Z)F.set(Re,ht);return Wo(k,F,void 0)}catch(W){return y={...x(),available:!1,reason:W instanceof Error?W.message:String(W)},$i(k)}},w=(C,k)=>{let T=ga(C),F=ga(k),V=F.filter(rC),ie=new Map,W=oC(V,m),be=[];for(let Z of V)W.has(Z.symbolId)?ie.set(Z.symbolId,W.get(Z.symbolId)??[]):iC(Z,p)?ie.set(Z.symbolId,[]):be.push(Z);if(T.length===0&&be.length===0)return{references:Mi(T),callees:Wo(F,ie,void 0)};try{let Z=s?s.referencesAndCalleesForDefinitions(T,be):sU(a,c,{referenceDefinitions:T,calleeDefinitions:be}),Re=x();y={...Re,available:Z.available,resolvedBinary:Z.resolvedBinary??Re.resolvedBinary,reason:Z.reason??Re.reason};let ht=Z.available?new Map(Z.references):Ur(T,Z.references);for(let[Ws,At]of Z.callees)ie.set(Ws,At);let yi=Wo(F,ie,d);for(let[Ws,At]of yi)g.set(Ws,At);return{references:ht,callees:yi}}catch(Z){return y={...x(),available:!1,reason:Z instanceof Error?Z.message:String(Z)},{references:Mi(T),callees:$i(F)}}},I=C=>{if(C.length===0)return new Map;let k=ga(C);try{let T=l.signaturesForDefinitions(k),F=x();return y={...F,available:T.available,resolvedBinary:T.resolvedBinary??F.resolvedBinary,reason:T.reason??F.reason},aC(k,T.signatures)}catch(T){return y={...x(),available:!1,reason:T instanceof Error?T.message:String(T)},nu(k)}};return{language:"rust",availability:R,dispose:()=>{s?.dispose()},importUsage:C=>{let k=f.get(C);if(k)return k;try{let T=u.importUsage(C);return f.set(C,T),T}catch(T){return y={...x(),available:!1,reason:T instanceof Error?T.message:String(T)},[]}},referencesFor:C=>b([C]).get(C.symbolId)??[],referencesForDefinitions:b,referencesAndCalleesForDefinitions:w,calleesFor:C=>v([C]).get(C.symbolId)??[],calleesForDefinitions:v,signatureFor:C=>I([C]).get(C.symbolId)??null}}function Xq(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function Zq(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function ga(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:M(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ve(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function rC(e){return e.isFunctionLike}function iC(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function oC(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function eU(e,t){return{referencesForDefinitions:n=>rU(e,t,n)}}function tU(e,t){return{calleesForDefinitions:n=>iU(e,t,n)}}function nU(e,t){return{signaturesForDefinitions:n=>oU(e,t,n)}}function rU(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Mi(n)};let i=Pf();if(!wf(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Mi(n)};let o=qo(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,kf),s=ru(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,If),c=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=fa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=Cf(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fi(n.length,Rf(o,u.referenceRetryTimeoutMs),a)}),p=Ef(d.stdout);if(p)return{available:p.available,resolvedBinary:r.resolvedBinary,reason:p.reason,references:Ur(n,new Map(p.references),new Set(p.incompleteReferenceSymbolIds??[]))};let m=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,references:Mi(n)}}function iU(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,callees:$i(n)};let i=Pf();if(!wf(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:$i(n)};let o=qo(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,kf),s=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,If),a=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=fa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=Cf(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fi(n.length,o,s)}),d=Ef(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,callees:Wo(n,new Map(d.callees??[]),void 0)};let p=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,callees:$i(n)}}function oU(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,signatures:nu(n)};let i=Pf();if(!wf(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:nu(n)};let o=qo(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,kf),s=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,If),a=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=fa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Cf(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fi(n.length,o,s)}),d=Ef(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:aC(n,new Map(d.signatures??[]))};let p=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,signatures:nu(n)}}function sU(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Mi(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:$i(n.calleeDefinitions)};return{available:r.available&&i.available,resolvedBinary:r.resolvedBinary??i.resolvedBinary,reason:r.reason??i.reason,references:r.references,callees:i.callees}}function Mi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function $i(e){return new Map(e.map(t=>[t.symbolId,[]]))}function nu(e){return new Map(e.map(t=>[t.symbolId,null]))}function Wo(e,t,n){let r=0,i=0;return D("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function aC(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Pf(){return Qq(new URL("./rust-semantic-worker.js",import.meta.url))}function Ef(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.available!="boolean"||!Array.isArray(n.references)?null:{available:n.available,reason:typeof n.reason=="string"?n.reason:void 0,references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0}}catch{return null}}function qo(e,t){return qr(e)??t}function ru(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as aU,readFileSync as cU}from"fs";import{deserializeSCIP as lU,SymbolRole as uU}from"@c4312/scip";var Df=new WeakMap;function lC(e,t){let n=t.filter(dU);if(n.length===0)return new Map;let r=!1,i=0,o=0;return D("rust.scip-occurrence.callees",()=>{let s=fU(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=pU(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function dU(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||et(e.symbol))}function pU(e,t,n){let r=ce(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!mU(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function mU(e,t){let n=cC(e),r=cC(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function cC(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function fU(e){if(Df.has(e))return Df.get(e)??null;let t=gU(e);return Df.set(e,t),t}function gU(e){if(!aU(e.config.indexPath))return null;try{let t=Ue(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=lU(cU(e.config.indexPath)),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&uU.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:et(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var iu=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=hU(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function hU(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as CV}from"crypto";import{existsSync as wV,mkdirSync as UC,readFileSync as kV,rmSync as VC}from"fs";import{dirname as IV,resolve as GC}from"path";import{spawn as PU}from"child_process";import{closeSync as EU,existsSync as DU,mkdirSync as TU,openSync as LU,readFileSync as $f,rmSync as ya,writeFileSync as FU}from"fs";import{dirname as NU,join as Nf,resolve as uu}from"path";import{fileURLToPath as AU}from"url";import{spawnSync as yU}from"child_process";import{createHash as bU}from"crypto";import{existsSync as SU,lstatSync as vU,realpathSync as xU}from"fs";import{dirname as RU,isAbsolute as CU,join as wU,resolve as ou}from"path";var ha={run(e,t){let n=uC(e,t);return n.kind==="success"?n.output:void 0},runResult:uC};function dC(e,t=ha){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?wn(n):void 0}function Wt(e,t=ha){let n=Lf(e,t);if(n.kind!=="worktree")return;let r=n.identity,i=r.projectRoot,o=t.run(i,["rev-parse","--git-common-dir"])?.trim();if(!o)return;let s=wn(au(i,o)),a=Tf(t.run(i,["rev-parse","--verify","HEAD"])),c=Tf(t.run(i,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(i,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{...r,commonDir:s,repositoryId:pC("repository",s),headCommit:a,treeOid:c,clean:l.length===0}}function Lf(e,t=ha){let n=t.runResult(e,["rev-parse","--show-toplevel"]);if(n.kind==="not-repository")return{kind:"non-git"};if(n.kind==="error")return n;let r=n.output.trim();if(!r)return{kind:"error",message:"Git returned an empty worktree root."};let i=wn(r),o=t.run(i,["rev-parse","--absolute-git-dir"])?.trim();if(!o)return{kind:"error",message:"Git did not return an absolute worktree directory."};let s=wn(au(i,o));return{kind:"worktree",identity:{projectRoot:i,gitDir:s,worktreeId:pC("worktree",`${i}\0${s}`)}}}function su(e,t=ha){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:kU(n)}function kU(e){let t=[],n;for(let r of e.split("\0")){if(r===""){n&&t.push(n),n=void 0;continue}let i=r.indexOf(" "),o=i<0?r:r.slice(0,i),s=i<0?"":r.slice(i+1);if(o==="worktree"){n&&t.push(n),n={path:wn(s),detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o==="HEAD"?n.head=s:o==="branch"?n.branch=s:o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="prunable"?n.prunable=!0:o==="locked"&&(n.locked=!0))}return n&&t.push(n),t}function Ff(e,t,n=ha){return Tf(n.run(e,t))}function au(e,t){return CU(t)?t:ou(e,t)}function wn(e){try{return xU(e)}catch{return ou(e)}}function pC(e,t){return bU("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function Tf(e){return e?.trim()||void 0}function uC(e,t){let n=yU("git",["-C",e,...t],{encoding:"utf-8",env:{...process.env,LC_ALL:"C"},maxBuffer:52428800,stdio:["ignore","pipe","pipe"]});if(n.status===0)return{kind:"success",output:n.stdout.trimEnd()};let i=(typeof n.stderr=="string"?n.stderr.trim():"")||n.error?.message||`git exited with status ${n.status??"unknown"}`,o=n.error?.code;return(/not a git repository/i.test(i)||o==="ENOENT"&&SU(ou(e)))&&!IU(e)?{kind:"not-repository"}:{kind:"error",message:i}}function IU(e){if(process.env.GIT_DIR||process.env.GIT_COMMON_DIR)return!0;let t=ou(e);for(;;){try{return vU(wU(t,".git")),!0}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")return!0}let n=RU(t);if(n===t)return!1;t=n}}var _U=4,Sa=5e3,Of="watch.lock",MU="watch-state.json",$U="watch-activity.json",mC=5e3,OU=2e3,hC=10,jU=new Set(["bench","config-validate","hook-context","hook-stop","init","reindex","setup","setup-agent","setup-ci","setup-hooks","uninstall","watch","work-audit"]);function jf(e,t=process.env){return t.SCIP_QUERY_SKIP_WATCH_SERVICE!=="1"&&!e.startsWith("__")&&!jU.has(e)}function du(e){let t=e.env??process.env;if(t.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return{kind:"skipped",reason:"environment"};if(!jf(e.commandName,t))return{kind:"skipped",reason:"excluded-command"};if(e.config.watch?.enabled!==!0)return{kind:"skipped",reason:"disabled"};try{let n=va({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:e.cliVersion,runtime:e.runtime});return{kind:n.disposition,state:n.state}}catch(n){return{kind:"failed",message:n instanceof Error?n.message:String(n)}}}function Hn(e){return{lockPath:Nf(e,Of),statePath:Nf(e,MU),activityPath:Nf(e,$U)}}function yC(e,t){let n=wn(uu(e)),r=Lf(n);if(r.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${r.message}`);return r.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:t}:{projectRoot:n,worktreeKind:"git",worktreeId:r.identity.worktreeId,cliVersion:t}}function Bf(e){return lu(e,yC(e.projectRoot,e.cliVersion))}function lu(e,t){let n=e.runtime??Hf,r=Hn(e.cacheDir),i=Vr(r.statePath),o=Uo(r.lockPath);return{identity:t,classification:WU(i,t,n.now(),n.isProcessAlive),lock:o,lockIsLive:o!==null&&n.isProcessAlive(o.pid),paths:r}}function va(e){let t=e.runtime??Hf,n=yC(e.projectRoot,e.cliVersion),r=lu(e,n),i=_f("ensure",r.classification);if(i.kind==="reuse")return cu(r.paths.activityPath,t.now()),{disposition:"reused",state:i.state};if(i.kind==="replace")Mf(i.state.pid,e,t),ba(r.paths,i.state.pid,t);else if(i.kind==="start"){if(r.lockIsLive){let a=fC(e,n,t,Math.min(e.startupTimeoutMs??1e3,1e3));if(a)return cu(r.paths.activityPath,t.now()),{disposition:"reused",state:a};throw new Error(`scip-query watch is already running for ${uu(e.projectRoot)} (pid ${r.lock?.pid}; lock: ${r.paths.lockPath}) without compatible daemon state. Stop the foreground watcher before starting the service.`)}r.classification.kind==="stale"&&ba(r.paths,r.classification.state.pid,t)}else throw new Error(`Unexpected ensure action: ${i.kind}`);if(r=lu(e,n),i=_f("ensure",r.classification),i.kind==="reuse")return cu(r.paths.activityPath,t.now()),{disposition:"reused",state:i.state};let o=e.serverPath??AU(new URL("./watch-server.js",import.meta.url));t.spawnServer(o,n.projectRoot,e.cliVersion,e.watchOverrides??{});let s=fC(e,n,t,e.startupTimeoutMs??mC);if(!s)throw new Error(`scip-query watch service did not become ready within ${e.startupTimeoutMs??mC}ms.`);return cu(r.paths.activityPath,t.now()),{disposition:"started",state:s}}function pu(e){let t=e.runtime??Hf,n=Hn(e.cacheDir),r=Vr(n.statePath),i=r?t.isProcessAlive(r.pid)?{kind:"live",state:r}:{kind:"stale",state:r,reason:"dead-process"}:{kind:"stopped"},o=_f("stop",i);if(o.kind==="signal-stop")return Mf(o.state.pid,e,t),ba(n,o.state.pid,t),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ba(n,o.state.pid,t),{disposition:"stopped",pid:o.state.pid};let s=Uo(n.lockPath);return o.kind==="already-stopped"&&s&&t.isProcessAlive(s.pid)?(Mf(s.pid,e,t),ba(n,s.pid,t),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function Vr(e){try{return HU(JSON.parse($f(e,"utf8")))}catch{return null}}function cu(e,t=Date.now()){let n=BU(e);he(e,{version:1,at:new Date(t).toISOString(),...n?.refreshRequestedAtMs===void 0?{}:{refreshRequestedAt:new Date(n.refreshRequestedAtMs).toISOString(),...n.refreshDetail?{refreshDetail:n.refreshDetail}:{}}})}function bC(e,t,n=Date.now()){he(e,{version:1,at:new Date(n).toISOString(),refreshRequestedAt:new Date(n).toISOString(),refreshDetail:t})}function BU(e){try{let t=JSON.parse($f(e,"utf8"));return t.version!==1||!Dt(t.at)||t.refreshRequestedAt!==void 0&&!Dt(t.refreshRequestedAt)||t.refreshDetail!==void 0&&typeof t.refreshDetail!="string"?null:{atMs:Date.parse(t.at),...t.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(t.refreshRequestedAt)},...t.refreshDetail===void 0?{}:{refreshDetail:t.refreshDetail}}}catch{return null}}function SC(e,t,n={}){let r=n.pid??process.pid,i=n.isProcessAlive??xe,o=()=>{},s=Uo(e);if(s&&i(s.pid))return{acquired:!1,lockPath:e,message:gC(e,t,s),release:o};s&&ya(e,{force:!0}),TU(NU(e),{recursive:!0});let a;try{a=LU(e,"wx")}catch(u){if(qU(u)==="EEXIST")return{acquired:!1,lockPath:e,message:gC(e,t,Uo(e)),release:o};throw u}let c={version:1,pid:r,projectRoot:uu(t),startedAt:(n.now??(()=>new Date))().toISOString()};FU(a,`${JSON.stringify(c)}
291
- `);let l=!1;return{acquired:!0,lockPath:e,message:"",release:()=>{if(l)return;l=!0,EU(a);let u=Uo(e);u?.pid===c.pid&&u.startedAt===c.startedAt&&ya(e,{force:!0})}}}function Uo(e){try{let t=JSON.parse($f(e,"utf-8"));return t.version!==1||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||!Dt(t.startedAt)?null:t}catch{return null}}function HU(e){if(!e||typeof e!="object")return null;let t=e;return t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!Dt(t.startedAt)||!Dt(t.heartbeatAt)||!Dt(t.lastActivityAt)||!UU(t.watcher)||t.idleDeadlineAt!==void 0&&!Dt(t.idleDeadlineAt)||t.lastError!==void 0&&!VU(t.lastError)||t.lastRefresh!==void 0&&!GU(t.lastRefresh)||t.typescriptSemantic!==void 0&&!zU(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!KU(t.typescriptIndex)?null:t}function WU(e,t,n,r){if(!e)return{kind:"stopped"};if(e.protocolVersion!==_U)return{kind:"incompatible",state:e,reason:"protocol"};if(e.projectRoot!==t.projectRoot)return{kind:"incompatible",state:e,reason:"project"};let i=t.worktreeKind==="git"?t.worktreeId:void 0;if(e.worktreeId!==i)return{kind:"incompatible",state:e,reason:"worktree"};if(e.cliVersion!==t.cliVersion)return{kind:"incompatible",state:e,reason:"cli-version"};if(!r(e.pid))return{kind:"stale",state:e,reason:"dead-process"};let o=Date.parse(e.heartbeatAt);return n-o>Sa?{kind:"stale",state:e,reason:"old-heartbeat"}:{kind:"live",state:e}}function _f(e,t){switch(e){case"status":return{kind:"report",classification:t};case"ensure":switch(t.kind){case"stopped":return{kind:"start"};case"stale":return t.reason==="old-heartbeat"?{kind:"replace",state:t.state}:{kind:"start"};case"live":return{kind:"reuse",state:t.state};case"incompatible":return{kind:"replace",state:t.state};default:return Af(t)}case"stop":switch(t.kind){case"stopped":return{kind:"already-stopped"};case"stale":return t.reason==="old-heartbeat"?{kind:"signal-stop",state:t.state}:{kind:"clean-stale",state:t.state};case"live":case"incompatible":return{kind:"signal-stop",state:t.state};default:return Af(t)}default:return Af(e)}}function fC(e,t,n,r){let i=n.now()+r;for(;n.now()<=i;){let o=lu(e,t).classification;if(o.kind==="live")return o.state;n.sleep(hC)}return null}function Mf(e,t,n){if(!n.isProcessAlive(e))return;n.signalProcess(e);let r=t.stopTimeoutMs??OU,i=n.now()+r;for(;n.now()<=i;){if(!n.isProcessAlive(e))return;n.sleep(hC)}throw new Error(`scip-query watch service pid ${e} did not stop within ${r}ms.`)}function ba(e,t,n){ya(e.statePath,{force:!0}),ya(e.activityPath,{force:!0}),Uo(e.lockPath)?.pid===t&&!n.isProcessAlive(t)&&ya(e.lockPath,{force:!0})}function gC(e,t,n){return`error: scip-query watch is already running for ${uu(t)}${n?` (pid ${n.pid}, started ${n.startedAt}; lock: ${e})`:` (lock: ${e})`}. Stop that watcher before starting another.`}function qU(e){return typeof e=="object"&&e&&"code"in e?e.code:void 0}var Hf={now:Date.now,isProcessAlive:xe,spawnServer(e,t,n,r){if(!DU(e))throw new Error(`Watch service helper was not found at ${e}. Run npm run build first.`);PU(process.execPath,[e,t,n,JSON.stringify(r)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(e){process.kill(e,"SIGTERM")},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Dt(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function UU(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return ln(t.changedFiles)&&ln(t.reindexAt);case"indexing":return ln(t.startedAt);case"cooldown":return ln(t.until)&&typeof t.dirty=="boolean";default:return!1}}function VU(e){if(!e||typeof e!="object")return!1;let t=e;return Dt(t.at)&&typeof t.message=="string"}function GU(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&Dt(t.startedAt)&&Dt(t.completedAt)&&ln(t.durationMs)}function zU(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&ln(t.requests)&&ln(t.sessionsCreated)&&ln(t.sessionsReused)&&ln(t.sessionsRefreshed)&&ln(t.sessionsReplaced)&&ln(t.projectsCreated)&&(t.lastRequestAt===void 0||Dt(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Dt(t.busyUntil))}function KU(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Oi(t.requests)&&Oi(t.sessionsCreated)&&Oi(t.sessionsReplaced)&&Oi(t.initializations)&&Oi(t.programUpdates)&&Oi(t.documentsEmitted)&&Oi(t.documentsRemoved)&&(t.lastRequestAt===void 0||Dt(t.lastRequestAt))&&(t.lastDurationMs===void 0||ln(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Dt(t.busyUntil))}function ln(e){return typeof e=="number"&&Number.isFinite(e)}function Oi(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Af(e){throw new Error(`Unhandled watch service value: ${JSON.stringify(e)}`)}import{performance as ae}from"perf_hooks";function un(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import vC from"path";function JU(e,t){return e.getReferences().map(n=>{let r=n.getNode();return mu(r,t)})}function YU(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function xC(e,t,n,r){let i=[];for(let o of YU(e))for(let s of JU(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 Gr(i)}function RC(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();zr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:mu(a,r),node:a}))}return i}function mu(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:zr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function CC(e,t,n){let r=e.getSourceFile(),i=qf(r,e),o=e.getText(),s=new RegExp(`\\b${J(o)}\\b`,"g"),a=r.getFullText().split(`
292
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return Gr(c.filter(l=>zr(n,vC.join(n,l.file))===t))}function Wf(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 qf(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Gr(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 zr(e,t){let n=vC.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function wC(e,t,n,r){let i=QU(t,r);return i.size===0?new Map:XU(e,n,i)}function QU(e,t){let n=new Map;for(let r of se(e,t)){let i=M(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function XU(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of ZU(e,o)){let a=n.get(s);if(!a)continue;let c=qf(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function ZU(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}var eV=ne("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function kC(e,t,n,r){let i=Gf(e,t),o=Uf(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||M(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return Uf(s,n)}function Vf(e,t,n,r){return Uf(Gf(e,t).get(r)??[],n)}function IC(e,t){let n=new Map;for(let[r,i]of Gf(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Gf(e,t){return eV.get(e,t,()=>{let n=new Map;for(let r of se(e,t)){let i=r.leaf||M(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function Uf(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import zf from"path";var xa=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function bt(e){let t=e.toLowerCase();return xa.some(n=>t.endsWith(n))}function PC(e,t){let n=new Map,r=null,i=null,o=()=>(i??=q(e,{extensions:xa}),i),s=()=>(r??=D("typescript.source-file-index",()=>tV(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>bt(c)?un(n,c,()=>{let l=Ra(zf.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let p=d.get(l)??null;if(p||(p=u.addSourceFileAtPathIfExists(l)??null,p&&d.set(Ra(p.getFilePath()),p)),p)return{project:u,sourceFile:p}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function tV(e,t,n){let r=t.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Ra(o.getFilePath()),o]))}));for(let i of n){let o=Ra(zf.resolve(e,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(Ra(a.getFilePath()),a);break}}}return r}function Ra(e){return zf.resolve(e)}function Kf(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function EC(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as Ca,readFileSync as nV}from"fs";import at from"path";var Jf=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Yf(e,t){let r=t?at.dirname(at.join(e,t)):e,i=at.resolve(e);for(;r.startsWith(i);){for(let s of Jf){let a=at.join(r,s);if(Ca(a))return a}let o=at.dirname(r);if(o===r)break;r=o}for(let o of Jf){let s=at.join(e,o);if(Ca(s))return s}return null}function fu(e){let t=e.config.projectRoot,n=new Set(Qf(t,e.config.semantic?.typescript?.tsconfigs)),r=q(e,{includeIgnored:!1,extensions:xa});for(let i of r){let o=Yf(t,i);o&&n.add(at.resolve(o))}if(n.size===0){let i=Yf(t);i&&n.add(at.resolve(i))}return[...n].filter(i=>!DC(t,i)).sort((i,o)=>i.localeCompare(o))}function Qf(e,t=[]){let n=new Set;for(let r of t){let i=at.isAbsolute(r)?r:at.join(e,r);Ca(i)&&n.add(at.resolve(i))}for(let r of rV(e))for(let i of Jf){let o=at.join(r,i);Ca(o)&&n.add(at.resolve(o))}if(n.size===0){let r=Yf(e);r&&n.add(at.resolve(r))}return[...n].filter(r=>!DC(e,r)).sort((r,i)=>r.localeCompare(i))}function rV(e){let t=at.join(e,"package.json");if(!Ca(t))return[];let n;try{n=JSON.parse(nV(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>om(e,i))}function DC(e,t){let n=at.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 iV}from"module";var TC=iV(import.meta.url),wa,gu;function Xf(){if(wa!==void 0)return wa;try{wa=TC("ts-morph")}catch{wa=null}return wa}function hu(){if(gu)return gu;let e=Xf();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=TC("ts-morph/package.json").version??"unknown"}catch{}return gu=`ts-morph:${t}:typescript:${e.ts.version}`,gu}function LC(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function Kr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function yu(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,oV(o));return r}function AC(e,t,n){let r=NC(e,t),i=NC(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=FC(e,t),c=FC(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function FC(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function _C(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,sV(s));return i}function NC(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function oV(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort(MC)}function sV(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||MC(n.location,r.location))}function MC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var aV=32;function bu(e,t){let n=D("typescript.provider.load",()=>Xf());if(!n)return Kr("ts-morph is not installed");let r=D("typescript.provider.tsconfig-discovery",()=>fu(e));if(r.length===0)return Kr("no tsconfig found");try{let i=D("typescript.provider.project-bundles",()=>LC(n,r),()=>({tsconfigs:r.length}));return cV(e,n,i)}catch(i){return Kr(i instanceof Error?i.message:String(i),r[0],r)}}function cV(e,t,n,r={}){return D("typescript.provider.construct",()=>new eg(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var eg=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ro(t.config.projectRoot),this.sourceFiles=PC(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;compilerCheckerCache=new WeakMap;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 un(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=uV();return D("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return un(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=re(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!OC(u));if(a.length>=aV){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let p=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,p),r.set(d.symbolId,p)}if(s=o.filter(d=>OC(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let p=jC();D("typescript.references-map.file",()=>{let m=this.definitionNodesForFile(u);for(let f of d){i&&(p.cacheMisses+=1);let g=m.get(f.symbolId)??null;i&&(g?p.nodeHits+=1:p.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?p:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:u,definitions:d.length,...BC(p)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let p=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,p),r.set(d.symbolId,p)}}return r}referenceFragmentsForFiles(t){let n=Ue(this.db).filter(o=>bt(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return _C(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=re(),i=jC(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return D("typescript.references-map.inverted-scan",()=>{let c=r?ae.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let y=l.get(h.symbolId)??[];if(y.length>0){let x=o.get(h.symbolId)??[];x.push(...y),o.set(h.symbolId,x)}r&&(i.packageReferenceCount+=y.length)}r&&(i.packageRefsMs+=ae.now()-c);let u=new Map,d=new Map,p=this.hierarchyTargetsForDefinitions(t),m=new Set(t.map(h=>h.leaf).filter(Boolean)),f=r?ae.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let y=this.sourceFiles.sourceFile(h);y&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(y,h,s,a,p,m,u,d,o,r?i:void 0))}r&&(i.scanMs+=ae.now()-f);let g=r?ae.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=ae.now()-g);for(let[h,y]of o){let x=Gr(y);o.set(h,x),r&&(i.referenceCount+=x.length)}},()=>({definitions:t.length,...BC(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),p=t.compilerNode,m=mV(t),f=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!m.has(g.text)){this.tsMorph.ts.forEachChild(g,f);return}let h=this.compilerReferenceSymbol(d,g,u);if(h){let y;a.has(h)?y=a.get(h)??null:(y=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,y)),u&&(y?u.targetHits+=1:u.targetMisses+=1);let x=un(c,h,()=>this.compilerSymbolKeys(h)),R=null,b=null,v=y&&r.has(y.symbolId)?i.get(y.symbolId):void 0;if(v&&(R=Zf(p,g),!$C(v,n,R))){let w=p.getLineAndCharacterOfPosition(g.getStart(p));b={file:n,line:w.line,column:w.character};let I=l.get(v.symbolId)??[];I.push(b),l.set(v.symbolId,I),u&&(u.requestedHits+=1)}for(let w of x)for(let I of o.get(w)?.values()??[]){if(R??=Zf(p,g),$C(I,n,R))continue;if(!b){let k=p.getLineAndCharacterOfPosition(g.getStart(p));b={file:n,line:k.line,column:k.character}}let C=l.get(I.symbolId)??[];C.push(b),l.set(I.symbolId,C),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,f)};f(p)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),p=d.getLineAndCharacterOfPosition(a.name.getStart(d)),m={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let y of this.compilerSymbolLocations(h))f.push(y),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,f);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let y=i.get(h)??new Map;y.set(o.symbolId,m),i.set(h,y)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let p=d.getProperty(r.name);p&&(u=!0,s(d,p,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=zr(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return un(this.calleesCache,t.symbolId,()=>un(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?ae.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=ae.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?ae.now():0,a=xC(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=ae.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return un(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 HC(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${HC(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Ot(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of tg(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let p=o.get(l.localName);p?p.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||dV(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:mu(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?lV(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of RC(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!Wf(c.node)),s=i.some(c=>Wf(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Kf(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Gr(s));return n}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,Gr(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=Kf(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of tg(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=CC(a.identifier,r,this.db.config.projectRoot);l.length>0&&yV(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of EC(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}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?Ot(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))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 d=u.getNameNode().getText(),p=u.getAliasNode()?.getText()??d,m=this.indexedDefinitionByLeaf(c,d);if(!m)continue;let f=r.get(p);f||(f=new Set,r.set(p,f)),f.add(m.symbolId)}}}indexedDefinitionByLeaf(t,n){return un(this.indexedDefinitionLeafCache,t,()=>IC(this.db,t)).get(n)??null}nodeForDefinition(t){return un(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return un(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?wC(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?ae.now():0,s=t.declarations??[];n&&(n.declarationsMs+=ae.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?ae.now():0,l=a.getSourceFile(),u=zr(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=ae.now()-c),!u||this.db.isIgnored(u))continue;let p=n?ae.now():0,m=this.compilerDeclarationName(a),f=r?Vf(this.db,u,d,i)??(m&&m!==i?Vf(this.db,u,d,m):null):kC(this.db,u,d,i);if(n&&(n.indexedLookupMs+=ae.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=re(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,p=r?gV():void 0;return D("typescript.callee-map.file",()=>{let m=r?ae.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(ae.now()-m)),!f)return new Map;let g=r?ae.now():0,h=se(this.db,t).sort((C,k)=>C.startLine-k.startLine||k.endLine-C.endLine);if(r&&(l=Math.round(ae.now()-g)),i=h.length,h.length===0)return new Map;let y=new Map,x=r?ae.now():0,R=this.compilerCheckerForSourceFile(f),b=f.compilerNode;r&&(u=Math.round(ae.now()-x));let v=new Map,w=C=>{if(this.tsMorph.ts.isCallExpression(C)||this.tsMorph.ts.isNewExpression(C)){r&&(o+=1);let k=this.semanticCalleeForCallNode(R,b,h,C,v,n,p);k&&(r&&(s+=1),pV(y,k.callerId,k.target))}this.tsMorph.ts.forEachChild(C,w)},I=r?ae.now():0;w(b),r&&(d=Math.round(ae.now()-I));for(let[C,k]of y)y.set(C,bV(k));return a=y.size,y},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...p?hV(p):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?ae.now():0,l=fV(r,Zf(n,i));if(a&&(a.callerLookupMs+=ae.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),p=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),p=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let m=a?ae.now():0;p=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=ae.now()-m),o.set(d,p)}else a&&(a.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?ae.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=ae.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?ae.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=ae.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function tg(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 lV(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 uV(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function dV(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function pV(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function mV(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of tg(n))r.localName&&t.add(r.localName);return t}function fV(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 Zf(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function $C(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function OC(e){return e.symbol.includes("#")?$e(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function gV(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function hV(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function jC(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function BC(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function yV(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function bV(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 HC(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{createHash as SV}from"crypto";import{readFileSync as vV}from"fs";import{dirname as xV,join as Su}from"path";var vu=2,RV="typescript-semantic";function WC(e){let t=Su(e,RV);return{rootDir:t,requestDir:Su(t,"requests"),responseDir:Su(t,"responses")}}function qC(e){try{let t=JSON.parse(vV(Su(xV(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||typeof t.status!="string"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:SV("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}var PV=12e4,EV=5;function JC(e,t,n={}){let r=new ng(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=bu(e,t),i),c=(d,p,m)=>{if(s)return m();try{return p(r.request(d))}catch{return s=!0,m()}},l=(d,p)=>c({kind:"references",definitions:[...d],...p?.exact?{exact:!0}:{}},m=>KC(m),()=>a().referencesForDefinitions?.(d,p)??new Map(d.map(m=>[m.symbolId,a().referencesFor(m)]))),u=d=>c({kind:"callees",definitions:[...d]},p=>KC(p),()=>a().calleesForDefinitions?.(d)??new Map(d.map(p=>[p.symbolId,a().calleesFor(p)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},LV,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},p=>p,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},p=>TV(p),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},FV,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var ng=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??AV,this.timeoutMs=n.timeoutMs??NV(),this.cacheDir=IV(t.config.dbPath),this.projectRoot=wn(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;request(t){let n=Hn(this.cacheDir),r=WC(this.cacheDir),i=Vr(n.statePath);if(!zC(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=qC(this.db.config.dbPath);if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.randomId(),a=GC(r.requestDir,`${s}.json`),c=GC(r.responseDir,`${s}.json`),l=this.runtime.now()+this.timeoutMs;UC(r.requestDir,{recursive:!0}),UC(r.responseDir,{recursive:!0}),he(a,{protocolVersion:vu,id:s,generation:o,deadlineAtMs:l,profileEnvironment:rv(),request:t});try{for(;this.runtime.now()<=l;){if(wV(c))return DV(kV(c,"utf8"),s,o);let u=Vr(n.statePath);if(!zC(u,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(EV)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}finally{VC(a,{force:!0}),VC(c,{force:!0})}}};function zC(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Sa,i=e?.typescriptSemantic?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptSemantic.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===vu&&n.isProcessAlive(e.pid)&&(r||i)}function DV(e,t,n){let r=JSON.parse(e);if(r.protocolVersion!==vu||r.id!==t||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function KC(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function TV(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function LV(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function FV(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function NV(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:PV}var AV={now:Date.now,randomId:CV,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xe};var YC=new iu;Nr({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>YC.clear(e)});function Vo(e,t){let n=nt(t)??"typescript";return YC.getOrCreate(e,n,()=>n==="rust"?sC(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>dR(e,r)},calleeSymbolResolver:uR(e),sourceZeroCalleeOracle:r=>_V(e,r),scipOccurrenceCalleeOracle:r=>lC(e,r)}):JC(e,t))}function nt(e){return e?K(e)==="rust"?"rust":bt(e)?"typescript":null:"typescript"}function _V(e,t){let n=ce(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}import{existsSync as MV,readFileSync as $V}from"fs";import{resolve as OV}from"path";var jV=/^[A-Za-z_][A-Za-z0-9_]*$/,QC=/\bDefault::default\b/g,BV=/^\.\.\s*Default::default\b/;function XC(e,t){let n=new Map,r=new Map;for(let i of t){let o=rg(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function rg(e,t,n=new Map){let r=WV(t.symbol);if(!r)return null;let i=$o(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${J(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${J(r)}\\s*$`),a=HV(e,t.symbolId),c=[];for(let l of i){let u=qV(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),p=0,m=[],f=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let y=d[g]??"",x=new Set;o.lastIndex=0;let R;for(;R=o.exec(y);)c.push({file:l.relative_path,line:g,column:R.index+R[1].length+r.length+2}),f+=1;for(let b=0;b<y.length;b+=1){let v=BV.exec(y.slice(b));if(v){if(a&&m.includes(p)){let I=b+v[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:I}),x.add(I),f+=1}b+=v[0].length-1;continue}let w=y[b];if(w==="{"){let I=s.test(y.slice(0,b));p+=1,I&&m.push(p);continue}if(w==="}")for(p=Math.max(0,p-1);m.length>0&&m[m.length-1]>p;)m.pop()}for(QC.lastIndex=0;R=QC.exec(y);){let b=R.index+9;if(!x.has(b))return null}}if(f===0)return null}return Kl(c)}function HV(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function WV(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!jV.test(t)?null:t}function qV(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:UV(e,t);return n.set(t,i),i}function UV(e,t){let n=OV(e.config.projectRoot,t);if(!MV(n))return null;try{return $V(n,"utf8")}catch{return null}}import{readFileSync as XV}from"fs";import{dirname as ZV,join as eG}from"path";function xu(e){return!ee(e)||typeof e.version!="number"||X(e.languages)===null||typeof e.pnpmWorkspaces!="boolean"||typeof e.typescriptProjectMode!="string"||X(e.typescriptProjects)===null||e.clojureConfigPath!==void 0&&typeof e.clojureConfigPath!="string"||!Array.isArray(e.files)||!e.files.every(VV)?null:e}function Ru(e,t){let n=new Map((e?.files??[]).map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=new Set([...n.keys(),...r.keys()]),o=[];for(let a of[...i].sort()){let c=n.get(a),l=r.get(a),u=Ho(a,t.languages);!c&&l?o.push({kind:"added",path:a,inputKind:u,after:l}):c&&!l?o.push({kind:"deleted",path:a,inputKind:u,before:c}):c&&l&&(c.hash!==l.hash||c.size!==l.size)&&o.push({kind:"modified",path:a,inputKind:u,before:c,after:l})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),(ZC(e?.files??[])||ZC(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(GV)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!KV(e,t):!0,uncertainty:[...s].sort()}}function ZC(e){return new Set(e.map(t=>t.path)).size!==e.length}function VV(e){return ee(e)&&typeof e.path=="string"&&typeof e.size=="number"&&typeof e.hash=="string"}function GV(e){return e.hash==="unreadable"||e.size<0}function ig(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Cu(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=ig(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),ew(r,i,s)):s.size>0?ew(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:zV(r,t,i),reasons:[]}}function ew(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function zV(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}function KV(e,t){return tw(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&tw(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function tw(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((i,o)=>i===r[o])}function zo(e){let t=wu(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let p=Ho(d.path,["typescript"]);return p==="config"||p==="ambient"}).map(d=>d.path),o=wu([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>nw(r.get(d))),l=Ge(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:wu(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,p){if(!n.has(d))return Go("target-outside-project");if(a)return Go("duplicate-input-path");if(s)return Go("missing-input-fingerprint");if(c)return Go("unreadable-input");let m=[],f,g;if(e.graph===null)m.push("dependency-graph-unavailable"),g="whole-project",f=o;else{let x=YV(d,e.graph,u);if(x.find(b=>!r.has(b)))return Go("missing-input-fingerprint");if(f=wu([...x,...i]),f.some(b=>nw(r.get(b))))return Go("unreadable-input");g="dependency-closure"}let h=f.map(x=>QV(r.get(x)));return{version:1,key:Ge(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:p,projectIdentity:l,inputs:h})),mode:g,inputFiles:f,reasons:m}}}}function JV(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function YV(e,t,n){let r=n.get(e);if(r)return r;let i=JV(e,t);return n.set(e,i),i}function QV(e){return{path:e.path,size:e.size,hash:e.hash}}function nw(e){return e.size<0||e.hash==="unreadable"}function Go(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function wu(e){return[...new Set(e)].sort()}var tG=me("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function Jr(e,t,n){let r=tG.get(e,()=>nG(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function ka(e){return q(e,{includeIgnored:!1}).filter(bt).sort()}function nG(e){try{let t=JSON.parse(XV(eG(ZV(e.config.dbPath),"meta.json"),"utf8")),n=xu(t.fingerprint);return n?{builder:zo({projectFiles:ka(e),snapshot:n,graph:ge(e),engineIdentity:hu()}),identities:new Map}:null}catch{return null}}var og="typescript-reference-fragment-v2",Iu=Ie({kind:"typescript-reference-fragments",invalidation:pe("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:iG});function rw(e,t,n,r=e){let i=ka(e),o=zo({projectFiles:i,snapshot:t,graph:ge(e),engineIdentity:hu()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,og).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return Iu.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function sg(e,t,n){let r=t.filter(o=>bt(o.relativePath));if(r.length===0)return ku("no TypeScript definitions");let i=ku("shadow did not run");return D("typescript.reference-fragments.shadow",()=>{try{let o=Vo(e,r[0].relativePath);if(!o.availability().available||!o.referenceFragmentsForFiles)return i=ku("TypeScript reference fragment provider is unavailable"),i;let s=ka(e),a=new Set(s),c=o.referenceFragmentsForFiles(s),l=yu(r,c),u=AC(r,rG(n,a),l);if(!u.passed)return i={state:"failing",files:s.length,keyedFiles:0,writtenFiles:0,...u},i;let d=[];for(let p of s){let m=Jr(e,p,og);m?.key&&d.push({relativePath:p,contentHash:m.key,value:c.get(p)??[]})}return Iu.writeBatch(e,d),i={state:"passing",files:s.length,keyedFiles:d.length,writtenFiles:d.length,...u},i}catch(o){return i=ku(o instanceof Error?o.message:String(o)),i}},()=>({...i}))}function rG(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function ag(e,t){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let n="fallback",r=0,i=0,o=0,s=0;return D("typescript.reference-fragments.materialize",()=>{try{let a=ka(e);r=a.length;let c=new Map,l=new Map,u=[];for(let m of a){let f=Jr(e,m,og);if(!f?.key)return null;c.set(m,f.key);let g=Iu.read(e,m,f.key);g===null?(o+=1,u.push(m)):(i+=1,l.set(m,g))}if(o===0)return n="hit",{references:yu(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s};let d=Vo(e,t[0].relativePath);if(!d.availability().available||!d.referenceFragmentsForFiles)return null;let p=d.referenceFragmentsForFiles(u);if(u.some(m=>!p.has(m)))return null;s=p.size,Iu.writeBatch(e,u.map(m=>({relativePath:m,contentHash:c.get(m),value:p.get(m)??[]})));for(let[m,f]of p)l.set(m,f);return n="computed",{references:yu(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s}}catch{return null}},()=>({state:n,files:r,cacheHits:i,cacheMisses:o,computedFiles:s}))}function ku(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function iG(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(oG)?null:t}catch{return null}}function oG(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}function Pu(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}var sG="typescript-import-usage-v1",aG="typescript-signatures-v1",cg=me("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),iw=Ci({kind:"semantic-import-usage",invalidation:pe("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:gw}),ow=Ci({kind:"semantic-signatures",invalidation:pe("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:yG}),sw=Ie({kind:"typescript-import-usage",invalidation:pe("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:gw}),aw=Ie({kind:"typescript-signatures",invalidation:pe("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:bG});function St(e){let t=new Map,n=new Set;return{capability:(r,i)=>hw(e,r,i),importUsage:r=>lG(e,r),references:r=>uw(e,r),materializeReferences:(r,i)=>pw(e,r,t,n,i),callerMap:r=>uG(e,r,t,n),calleeMap:r=>fG(e,r),signature:r=>gG(e,r)}}function cG(e,t){if(t.size===0)return;let n=cg.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function lw(e,t){if(!cg.has(e))return{hits:[],misses:[...t]};let n=cg.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Pa(e,t){return St(e).importUsage(t)}function lG(e,t){if(nt(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return D("typescript.import-usage.materialize",()=>{let u=Jr(e,t,sG);if(u?.key){s=1;let p=sw.read(e,t,u.key);if(p)return o="hit",a=1,p;c=1;let m=Wn(e,t);if(!m)return o="unavailable",[];let f=m.importUsage(t);return sw.write(e,t,u.key,f),o="computed",f}l=1;let d=Wn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=fw(e,"semantic-import-usage",t);if(n){let o=iw.read(e,t,n);if(o)return o}let r=Wn(e,t);if(!r)return[];let i=r.importUsage(t);return n&&iw.write(e,t,n,i),i}function Ko(e,t){return St(e).references(t)}function uw(e,t){let n=rg(e,t);if(n)return n;let r=RR(e,t);if(r)return r;let i=Wn(e,t.relativePath);return i?i.referencesFor(t):[]}function Yr(e,t){return St(e).callerMap(t)}function dw(e,t){let n=new Map,r=new Map;for(let i of t){if(nt(i.relativePath)==="typescript"){let o=Wn(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}lg(e,n,i,uw(e,i))}for(let[i,o]of r){let s=ag(e,o),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&re()&&sg(e,o,a);for(let c of o)lg(e,n,c,a.get(c.symbolId)??[])}return n}function uG(e,t,n=new Map,r=new Set){let i=new Map,o=pw(e,t,n,r),s=0;return D("semantic.callers.from-references",()=>{for(let a of t)s+=lg(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function pw(e,t,n,r,i={}){let o=Ye(e),s=[],a=[],c=[],l=0,u=0,d=0,p=0,m=0,f=0,g=0,h=0,y=0,x=0,R=0,b=0,v=[],w=new Map,I=t.filter(k=>nt(k.relativePath)==="typescript"&&!n.has(k.symbolId)&&!r.has(k.symbolId)),C=ag(e,I);if(C){y=I.length,x=C.cacheHits,R=C.cacheMisses,b=C.computedFiles;for(let k of I)n.set(k.symbolId,C.references.get(k.symbolId)??[])}if(D("semantic.references.cache-scan",()=>{for(let[k,T]of Pu(t)){let F=[];for(let W of T)n.has(W.symbolId)?u+=1:r.has(W.symbolId)?h+=1:F.push(W);if(F.length===0){g+=1;continue}let V=dG(e,o,k);if(!V){for(let W of F)nt(W.relativePath)||(l+=1),c.push(W);continue}f+=1;let ie=MS(e,k,V);for(let W of F){let be=ie.get(W.symbol)??null;if(be!==null){let Z=mG(be);if(Z){d+=1,n.set(W.symbolId,Z);continue}p+=1}a.push({definition:W,cacheFingerprint:V})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:p,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){v=[...c,...a.map(k=>k.definition)],w=D("semantic.references.compute-misses",()=>{let k=pG(e,v,i);return m=k.size,k},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:m}));for(let k of v)w.has(k.symbolId)?(n.set(k.symbolId,w.get(k.symbolId)??[]),r.delete(k.symbolId)):r.add(k.symbolId);for(let{definition:k,cacheFingerprint:T}of a)w.has(k.symbolId)&&hw(e,"semantic-references",k.relativePath).available&&s.push({relativePath:k.relativePath,symbol:k.symbol,projectFingerprint:T,payload:JSON.stringify(w.get(k.symbolId)??[])})}return s.length>0&&D("semantic.references.cache-write",()=>OS(e,s),()=>({entries:s.length})),w.size>0&&sg(e,v,w),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:p,computed:m,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:y,fragmentCacheHits:x,fragmentCacheMisses:R,fragmentComputedFiles:b}}function dG(e,t,n){if(!t)return null;let r=nt(n);return r==="typescript"?t:r==="rust"?Ge(JSON.stringify({kind:"semantic-references",language:r,engine:Ni(e.config.projectRoot),projectFingerprint:t})):null}function pG(e,t,n={}){let r=re(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,p=0,m=0;return D("semantic.references.provider-loop",()=>{let f=XC(e,t),g=xR(e,t),h=new Map,y=n.prefetchCallees?new Map:null,x=[];for(let b of t){let v,w=()=>(v??=Wn(e,b.relativePath),v);if(y){let T=w();if(T?.referencesAndCalleesForDefinitions){let F=y.get(T);F?F.push(b):y.set(T,[b]),m+=1}}let I=f.get(b.symbolId);if(I){a+=1,c+=I.length,Ia(i,b.symbolId,I,r,T=>{d+=1,p+=T});continue}let C=g.get(b.symbolId);if(C){l+=1,u+=C.length,Ia(i,b.symbolId,C,r,T=>{d+=1,p+=T});continue}let k=w();if(!k){r&&(s+=1);continue}if(r&&(o+=1),k.referencesForDefinitions){let T=h.get(k);T?T.push(b):h.set(k,[b])}else x.push({provider:k,definition:b})}let R=new Set;if(y)for(let[b,v]of y){if(!b.referencesAndCalleesForDefinitions)continue;let w=h.get(b)??[],I=b.referencesAndCalleesForDefinitions(w,v);R.add(b),cG(e,I.callees);for(let C of w){if(!I.references.has(C.symbolId))continue;let k=I.references.get(C.symbolId)??[];Ia(i,C.symbolId,k,r,T=>{d+=1,p+=T})}}for(let[b,v]of h){if(R.has(b))continue;let w=b.referencesForDefinitions(v);for(let I of v){if(!w.has(I.symbolId))continue;let C=w.get(I.symbolId)??[];Ia(i,I.symbolId,C,r,k=>{d+=1,p+=k})}}for(let{provider:b,definition:v}of x){let w=b.referencesFor(v);Ia(i,v.symbolId,w,r,I=>{d+=1,p+=I})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:m,definitionsWithReferences:d,referenceCount:p,rows:i.size}))}function Ia(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function lg(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function mG(e){try{return JSON.parse(e)}catch{return null}}function Eu(e,t){return St(e).calleeMap(t)}function fG(e,t){let n=re(),r=new Map,i=0,o=0,s=0,a=0;return D("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Wn(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let p=u;if(d.calleesForDefinitions){let m=c.get(d);m?m.push(p):c.set(d,[p])}else l.push({provider:d,definition:p})}for(let[u,d]of c){let p=u.calleesForDefinitions(d);for(let m of d){let f=p.get(m.symbolId)??[];cw(r,m.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let p=u.calleesFor(d);cw(r,d.symbolId,p,n,m=>{s+=1,a+=m})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function cw(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function mw(e,t){return St(e).signature(t)}function gG(e,t){if(nt(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return D("typescript.signature.materialize",()=>{let d=Jr(e,t.relativePath,aG);if(d?.key){a=1;let m=aw.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(m,t.symbol))return s="hit",c=1,m[t.symbol]??null;l=1;let f=Wn(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return aw.write(e,t.relativePath,d.key,{...m,[t.symbol]:g}),s="computed",g}u=1;let p=Wn(e,t.relativePath);return p?(s="direct-fallback",p.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=fw(e,"semantic-signatures",t.relativePath),r=hG(t);if(n){let s=ow.read(e,r,n);if(s)return s.signature}let i=Wn(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&ow.write(e,r,n,{signature:o}),o}function fw(e,t,n){let r=Ye(e);if(!r)return null;let i=nt(n);return i!=="rust"?null:Ge(JSON.stringify({kind:t,language:i,engine:Ni(e.config.projectRoot),projectFingerprint:r}))}function hG(e){return`${e.relativePath}\0${e.symbol}`}function gw(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function yG(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function bG(e){try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;for(let n of Object.values(t))if(n!==null&&typeof n!="string")return null;return t}catch{return null}}function hw(e,t,n){let r=nt(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...Vo(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Wn(e,t){if(!nt(t))return null;let n=Vo(e,t);return n.availability().available?n:null}var SG=ne("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function Du(e,t){let n=_r(t);return SG.get(e,n,()=>vG(e,n))}function vG(e,t){let n=new Map;for(let r of Ce(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&yw(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)yw(n,o,r.sourcePath)}return n}function yw(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Jo(e,t,n){let r=mr(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Ea(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Ea);let o=Du(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>_t(c,u.file));if(l.length>0)return l.map(Ea)}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=>_t(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Ea)}return[]}function bw(e,t,n){let r=Jo(e,t,n);if(r.length>0)return r;let i=mr(e).get(n);return!i||i.length===0?[]:i.map(Ea)}function Sw(e,t,n={}){let r=Ol(e,t);if(!r)return[];let i=M(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=Ko(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 Tu(e,a)}}let o=new Map;for(let s of Pt(e)){let a=_(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Jo(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=$l(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Tu(e,o)}function vw(e,t,n={}){let r=new Map;for(let c of t){if(!c.leaf)continue;let l=r.get(c.leaf)??[];l.push(c),r.set(c.leaf,l)}if(r.size===0)return new Map;let i=new Set(t.map(c=>c.symbolId)),o=new Set(r.keys()),s=ca(o),a=new Map;for(let c of Pt(e)){if(n.skipPath?.(c)||!ql(_(e,c),s))continue;let l=eR(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of Jo(e,c,u)){if(!i.has(d.symbolId)||c===d.relativePath)continue;let p=a.get(d.symbolId);p||(p=new Set,a.set(d.symbolId,p)),p.add(c)}}}return a}function Ea(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Tu(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=se(e,i);for(let a of o){let c=On(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 Da(e,t){let n=IG(e,t);return n?Tu(e,RG(e,n.match,n.identifier)):[]}function qn(e,t,n={}){return xG(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function xG(e,t,n={}){let r=Sw(e,t,{semantic:n.semantic}),i=r.length>0?xw(r,"source-attribution"):xw(Da(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function xw(e,t){return e.map(n=>({...n,provenance:t}))}function RG(e,t,n){let r=new Map;for(let[i,o]of CG(e,t.symbolId))r.set(i,wG(e,i,o,t,n));return r}function CG(e,t){let n=new Map;for(let r of $o(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 wG(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?$l(e,t,i,o):[];return n.flatMap(a=>kG(s,a))}function kG(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function IG(e,t){let n=Ol(e,t);return n?{match:n,identifier:M(n.symbol)||null}:null}import{SymbolInformation_Kind as le}from"@c4312/scip";var Lu=new Map(Object.entries(le).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),Rw=new Map([...Lu.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Un(e){return Lu.get(e)??"Unknown"}function dn(){return[le.Function,le.Method,le.Macro,le.Constructor,le.Getter,le.Setter,le.StaticMethod,le.SingletonMethod,le.AbstractMethod,le.ProtocolMethod,le.TraitMethod]}function Fu(){return[le.Class,le.Interface,le.Struct,le.Trait,le.Type,le.TypeAlias,le.Enum,le.Union,le.Protocol]}function Cw(){return[le.Constant,le.Variable,le.Value,le.Field,le.Property,le.StaticDataMember,le.StaticField,le.StaticProperty,le.StaticVariable,le.EnumMember]}function pn(e,t,n={}){let r=Nu(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>_e(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function kw(e,t,n={}){let r=DG(e)?LG(e,t,{semantic:n.semantic!==!1}):TG(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var PG=me("caller-rows",{clearGroups:["whole-project"]}),EG=2e4;function DG(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>EG}function TG(e){return PG.get(e,()=>{let t=Ue(e),n=Nu(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 d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function LG(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 Da(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?FG(e,t):null;if(s)for(let a of Ko(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=On(se(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function FG(e,t){let n=dn().join(", "),r=Fu().join(", ");return e.get(`SELECT
293
- d.id AS documentId,
294
- gs.id AS symbolId,
295
- gs.symbol,
296
- d.relative_path AS relativePath,
297
- COALESCE(der.start_line, c.start_line) AS startLine,
298
- COALESCE(der.end_line, c.end_line) AS endLine,
299
- COALESCE(gs.display_name, '') AS leaf,
300
- NULL AS parentTypeName,
301
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
302
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
303
- gs.kind AS kind,
304
- gs.documentation AS documentation,
305
- gs.enclosing_symbol AS enclosingSymbol
306
- FROM global_symbols gs
307
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
308
- LEFT JOIN chunks c ON c.document_id = der.document_id
309
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
310
- WHERE gs.id = ?
311
- LIMIT 1`,t.symbolId)??null}function Nu(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)K(u.relativePath)&&jr(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,p]of u){let m=s.get(d);m||(m=[],s.set(d,m));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of p){let h=`${g.symbol}|${g.chunkId}`;f.has(h)||(f.add(h),m.push(g))}}};i.length>0&&c(OG(e,i)),n.semantic!==!1&&c(UG(Iw(e,t)));let l=r?t:o;return l.length>0&&c(WG(e,l)),s}function Iw(e,t){let n=re(),r=new Map,i=lw(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,p=0,m=0;for(let{definition:R,callees:b}of i.hits)d+=1,b.length>0&&(p+=1,m+=b.length,r.set(R.symbolId,b));let f=NG(e,i.hits);if(f.entries.length>0&&D("semantic.callees.prefetch-cache-write",()=>tm(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),D("semantic.callees.cache-scan",()=>{for(let[R,b]of Pu(i.misses)){if(!nt(R)){n&&(a+=b.length);continue}let v=_(e,R);if(!v){n&&(c+=b.length),s.push(...b);continue}let w=Ae(e,R,v),I=Ew(e,R);if(!I){s.push(...b);continue}let C=_S(e,R,w,I);for(let k of b){let T=C.get(k.symbol)??null;if(T!==null){let F=_G(T);if(F){n&&(l+=1),F.length>0&&r.set(k.symbolId,F);continue}n&&(u+=1)}o.push({def:k,contentHash:w,depsDigest:I})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:p,inMemoryCalleeCount:m,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(R=>R.def)],h=0,y=D("semantic.callees.compute-misses",()=>{let R=Eu(e,g);return h=R.size,R},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[R,b]of y)r.set(R,b);let x=o.filter(R=>St(e).capability("semantic-callees",R.def.relativePath).available).map(R=>({relativePath:R.def.relativePath,symbol:R.def.symbol,contentHash:R.contentHash,depsDigest:R.depsDigest,payload:JSON.stringify(y.get(R.def.symbolId)??[])}));return x.length>0?D("semantic.callees.cache-write",()=>tm(e,x),()=>({entries:x.length})):D("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function NG(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!nt(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=_(e,s.relativePath),u=l?Ew(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Ae(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}function Pw(e,t){return Iw(e,t)}var AG="typescript-callees-v1";function Ew(e,t){let n=nt(t);if(n==="typescript")return Jr(e,t,AG)?.key??null;let r=$G(e,t);return n==="rust"?Ge(JSON.stringify({kind:"semantic-callees",language:n,engine:Ni(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function _G(e){try{return JSON.parse(e)}catch{return null}}var MG=ne("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function $G(e,t){return MG.get(e,t,()=>{let r=[...ge(e).get(t)??[]].sort().map(i=>`${i}:${Ae(e,i,_(e,i))}`);return Ge(r.join("|"))})}function OG(e,t){let n=new Map,r=jG(t,n),i=mr(e);for(let[o,s]of r){let a=jr(e,o);if(!a)continue;let c=Zm(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=BG(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function jG(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 BG(e,t,n,r){let i=Hl(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=HG(e,t,i,r.calleeQualifier);return o||Wl(e,t,i,r.memberAccess)}function HG(e,t,n,r){if(!r||K(t)!=="clojure")return null;let o=Ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>_t(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function WG(e,t){if(t.length===0)return new Map;let r=ug(t.map(m=>m.documentId)).flatMap(m=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
312
- FROM mentions m
313
- JOIN chunks c ON m.chunk_id = c.id
314
- WHERE m.role != 1
315
- AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),i=new Map;for(let m of r)i.has(m.document_id)||i.set(m.document_id,[]),i.get(m.document_id).push(m);let s=ug(r.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
316
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
317
- FROM global_symbols gs
318
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
319
- LEFT JOIN (
320
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
321
- FROM mentions m
322
- JOIN chunks c ON m.chunk_id = c.id
323
- WHERE m.role = 1
324
- AND m.symbol_id IN (${m.map(()=>"?").join(",")})
325
- GROUP BY m.symbol_id
326
- ) def_chunk ON def_chunk.symbol_id = gs.id
327
- WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=ug([...t.map(m=>m.documentId),...s.flatMap(m=>m.document_id===null?[]:[m.document_id])]),c=new Map(a.flatMap(m=>e.all(`SELECT id, relative_path FROM documents
328
- WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(f=>[f.id,f.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c,p=qG(t);for(let[m,f]of p){let h=[...i.get(m)??[]].sort((b,v)=>b.start_line-v.start_line||b.end_line-v.end_line),y=[...f].sort((b,v)=>b.startLine-v.startLine||b.endLine-v.endLine),x=new Set,R=0;for(let b of y){for(;R<h.length&&h[R].start_line<=b.endLine;)x.add(h[R]),R+=1;for(let k of x)k.end_line<b.startLine&&x.delete(k);let v=new Set,w=[],I=null,C=()=>{if(I)return I;let k=d.get(b.documentId)??"",T=new Set;if(k){let F=tR(e,k),V=Math.max(0,b.startLine),ie=Math.min(F.length-1,b.endLine);for(let W=V;W<=ie;W+=1)for(let be of F[W])T.add(be)}return I=T,T};for(let k of x){if(k.symbol_id===b.symbolId)continue;let T=l.get(k.symbol_id);if(!T)continue;if(!(k.start_line>=b.startLine&&k.end_line<=b.endLine)){if(!(k.start_line<=b.endLine&&k.end_line>=b.startLine))continue;let W=M(T.symbol);if(!W||!C().has(W))continue}let V=`${T.symbol}|${k.chunk_id}`;v.has(V)||(v.add(V),w.push({...T,chunkId:k.chunk_id,source:"scip-chunk"}))}u.set(b.symbolId,w)}}return u}var ww=500;function ug(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=ww)n.push(t.slice(r,r+ww));return n}function qG(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function UG(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 Dw(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=q(e,{includeIgnored:!1}),o=mr(e),s=t??Ue(e),a=new Set(s.map(l=>l.symbolId)),c=QG(s);if(VG(e,r,i,o,a,c),GG(e,r,s,a),YG(e,r,i,o,a,c),n.semantic!==!1){let l=St(e);ZG(r,l.callerMap(XG(s)))}return r}function VG(e,t,n,r,i,o){for(let s of n){if(!K(s))continue;let a=jr(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=Hl(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Wl(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&dg(t,u.symbolId,s)}}}function GG(e,t,n,r){let i=KG(n);for(let o of zG(e,r))e.isIgnored(o.relative_path)||JG(o,i.get(o.symbol_id))||dg(t,o.symbol_id,o.relative_path)}function zG(e,t){return $o(e,t?[...t]:void 0)}function KG(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 JG(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function YG(e,t,n,r,i,o){for(let s of n){if(K(s)!=="rust")continue;let a=Ii(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&dg(t,u.symbolId,s)}}}function dg(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function QG(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?M(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function XG(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function ZG(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 qt(e,t,n={}){return kw(e,t,n)}function pg(e,t,n={}){return Dw(e,t,n)}function Ta(e,t,n={}){return vw(e,t,n)}function Tw(e,t,n={}){let r=pg(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:gr(r,Ta(e,t))}function gr(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 Lw(e,t,n){let r=t.identifierResolution==="strict"?Jo:bw,i=t.candidateNames?ca(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!K(u)&&!(t.includeVueSfc&&sr(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!ql(_(e,u),i))continue;s+=1;let p=(f,g,h,y)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let x=t.resolveTargets?t.resolveTargets({sourceFile:u,name:f,kind:g,defaultTargets:y}):y();for(let R of x)c+=1,n({sourceFile:u,name:f,target:R,occurrences:h,kind:g})},m=pr(e,u);for(let[f,g]of m)p(f,"identifier",g.length,()=>r(e,u,f));for(let f of Ii(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Jo(e,u,f.name):()=>r(e,u,f.name);p(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&D("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function Q(e){return e.endLine-e.startLine+1}function Fw(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:p=!1,includeSuppressed:m=!1,sortByLocDesc:f=!1}=t,g=[],h=ez(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),y=new Map,x=new Map,R=v=>{let w=y.get(v);if(w!==void 0)return w;let I=tt(e,v);return y.set(v,I),I},b=v=>{let w=x.get(v);if(w!==void 0)return w;let I=fe(v);return x.set(v,I),I};for(let v of h){let w=v.relativePath;if(e.isIgnored(w)||a&&R(w)||!tz(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let I=Q(v);I<i||I>o||c&&nz(w)||l&&Oe(e,v.symbol,w)||p&&et(v.symbol)||b(w)!=="test"&&(No(v.symbol)||!m&&cl(e,w,v.startLine)||g.push(v))}return f?g.sort((v,w)=>Q(w)-Q(v)):g}function ez(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>se(e,r)):t.requireCallableSymbol?oa(e,{scope:t.scope,symbolMatches:_e,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?oa(e,{scope:t.scope,symbolMatches:ve,sqlPrefilter:"function-like"}):Bx(e,t.scope)}function tz(e,t){return t.requireCallableSymbol?_e(e.symbol):t.requireFunctionLikeSymbol?ve(e.symbol):e.isFunctionLike}function nz(e){return(e.split("/").pop()??"").includes("types")}var B=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Xm(this.db,t)}definitionsForFile(t){return se(this.db,t)}productionCallableDefinitions(t={}){return Fw(this.db,t)}calleeMap(t,n={}){return Nu(this.db,t,n)}crossFileCallerMap(t,n={}){return pg(this.db,t,n)}sourceFallbackCallerFiles(t,n={}){return Ta(this.db,t,n)}callerFileMap(t,n={}){return Tw(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 q(this.db,{includeIgnored:!1}))if(K(i)==="rust")for(let{name:o}of Ii(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 ge(this.db,t)}fileKind(t){return fe(t)}hasSuppressionComment(t){return cl(this.db,t.relativePath,t.startLine)}sourceFiles(){return Pt(this.db)}scanSourceReferences(t,n){Lw(this.db,t,n)}callableSignature(t){let n=cn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as rz}from"fs";function Ut(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,...iz(e.config.dbPath)}}function iz(e){try{let t=rz(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function oz(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function mg(e,t){let n=oz(t);return q(e,{like:n,includeIgnored:!1}).filter(r=>sz(t,r)).map(r=>({relativePath:r}))}function sz(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Au(n.split("/"),t.split("/"))}function Au(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Au(r,t)||t.length>0&&Au(e,t.slice(1)):t.length===0||!az(n??"",t[0]??"")?!1:Au(r,t.slice(1))}function az(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=cz(r);return n+="$",new RegExp(n).test(t)}function cz(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{existsSync as lz}from"fs";import{basename as Nw,isAbsolute as uz,join as dz}from"path";function vt(e,t){let n=Aw(e,t,{allowMultiple:!1})[0]?.relativePath;return n||pz(e,t)}function Yo(e,t){return Aw(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function pz(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=uz(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=dz(e.config.projectRoot,r);return lz(i)?r:null}function Aw(e,t,n){let r=_w(t);if(!r)return[];let i=q(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:mz(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=te(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 mz(e,t){let n=_w(e),r=Nw(n),i=Nw(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 _w(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as fz}from"path";function fg(e,t){let n=te(e,t);if(!n)return[];let r=M(n.symbol),o=new B(e).definitionsForFile(n.relativePath).filter(l=>_e(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r)),c=(s.length>0?s:gz(fz(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:M(l.symbol)}));return K(n.relativePath)!=="clojure"?c:yz(c,hz(e,n))}function gz(e){return e.replace(/\.[^.]+$/,"")}function hz(e,t){let n=M(t.symbol);return n?(ce(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function yz(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function gg(e,t,n={}){let r=te(e,t);if(!r)return[];let o=!ve(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=qn(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=bz(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function bz(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Sz(t.symbol);if(n.length===0)return[];let r=[];for(let i of q(e,{extensions:[".rb"],includeIgnored:!1})){let o=_(e,i);if(!o)continue;let s=o.split(`
329
- `);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 Sz(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 La(e,t,n={}){let r=te(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=dr(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:xz(o,i?.display_name??null,r.symbol),source:vz(e,r.relativePath,r.startLine,r.endLine)}],a=qn(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?P(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function vz(e,t,n,r){let i=_(e,t);if(!i)return null;let s=i.split(`
330
- `).slice(n,r+1).join(`
331
- `).trimEnd();return s.length>0?s:null}function xz(e,t,n){let r=ur(e);if(r&&!Rz(r))return r;let i=(t??"").trim();return i?ve(n)&&!i.endsWith("()")?`${i}()`:i:P(n)}function Rz(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Fa(e,t){let n=vt(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
332
- FROM mentions m
333
- JOIN chunks c ON m.chunk_id = c.id
334
- JOIN documents d1 ON c.document_id = d1.id
335
- JOIN global_symbols gs ON m.symbol_id = gs.id
336
- JOIN (
337
- SELECT m2.symbol_id, c2.document_id
338
- FROM mentions m2
339
- JOIN chunks c2 ON m2.chunk_id = c2.id
340
- WHERE m2.role = 1
341
- GROUP BY m2.symbol_id
342
- ) sym_def ON sym_def.symbol_id = gs.id
343
- JOIN documents d2 ON sym_def.document_id = d2.id
344
- WHERE d1.relative_path = ?
345
- AND d2.relative_path <> d1.relative_path
346
- AND ${e.localSymbolPredicate}
347
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Na(e,t){let n=vt(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
348
- FROM mentions m
349
- JOIN chunks c ON m.chunk_id = c.id
350
- JOIN documents d1 ON c.document_id = d1.id
351
- JOIN global_symbols gs ON m.symbol_id = gs.id
352
- JOIN (
353
- SELECT m2.symbol_id, c2.document_id
354
- FROM mentions m2
355
- JOIN chunks c2 ON m2.chunk_id = c2.id
356
- WHERE m2.role = 1
357
- GROUP BY m2.symbol_id
358
- ) sym_def ON sym_def.symbol_id = gs.id
359
- JOIN documents d2 ON sym_def.document_id = d2.id
360
- WHERE d2.relative_path = ?
361
- AND d1.relative_path != ?
362
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Aa(e,t){let n=Yo(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
363
- WHERE relative_path IN (${r})
364
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=Ll(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...p})=>p),c=e.all(`SELECT DISTINCT d2.relative_path
365
- FROM mentions m
366
- JOIN chunks c ON m.chunk_id = c.id
367
- JOIN documents d1 ON c.document_id = d1.id
368
- JOIN global_symbols gs ON m.symbol_id = gs.id
369
- JOIN (
370
- SELECT m2.symbol_id, c2.document_id
371
- FROM mentions m2
372
- JOIN chunks c2 ON m2.chunk_id = c2.id
373
- WHERE m2.role = 1
374
- GROUP BY m2.symbol_id
375
- ) sym_def ON sym_def.symbol_id = gs.id
376
- JOIN documents d2 ON sym_def.document_id = d2.id
377
- WHERE d1.relative_path IN (${r})
378
- AND d2.relative_path NOT IN (${r})
379
- AND ${e.localSymbolPredicate}
380
- ORDER BY d2.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),u=e.all(`SELECT DISTINCT d1.relative_path
381
- FROM mentions m
382
- JOIN chunks c ON m.chunk_id = c.id
383
- JOIN documents d1 ON c.document_id = d1.id
384
- JOIN global_symbols gs ON m.symbol_id = gs.id
385
- JOIN (
386
- SELECT m2.symbol_id, c2.document_id
387
- FROM mentions m2
388
- JOIN chunks c2 ON m2.chunk_id = c2.id
389
- WHERE m2.role = 1
390
- GROUP BY m2.symbol_id
391
- ) sym_def ON sym_def.symbol_id = gs.id
392
- JOIN documents d2 ON sym_def.document_id = d2.id
393
- WHERE d2.relative_path IN (${r})
394
- AND d1.relative_path NOT IN (${r})
395
- ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function _a(e,t){let n=Yo(e,t);return n.length===0?[]:kz([...Cz(e,n),...wz(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Iz)}function Cz(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
396
- FROM mentions m
397
- JOIN chunks c ON m.chunk_id = c.id
398
- JOIN documents d1 ON c.document_id = d1.id
399
- JOIN global_symbols gs ON m.symbol_id = gs.id
400
- WHERE d1.relative_path NOT IN (${n})
401
- AND (
402
- EXISTS (
403
- SELECT 1
404
- FROM defn_enclosing_ranges der
405
- JOIN documents d2 ON der.document_id = d2.id
406
- WHERE der.symbol_id = gs.id
407
- AND d2.relative_path IN (${n})
408
- )
409
- OR EXISTS (
410
- SELECT 1
411
- FROM mentions def_m
412
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
413
- JOIN documents d2 ON def_c.document_id = d2.id
414
- WHERE def_m.symbol_id = gs.id
415
- AND def_m.role = 1
416
- AND d2.relative_path IN (${n})
417
- )
418
- )
419
- AND m.role != 1
420
- AND ${e.localSymbolPredicate}
421
- ${e.pathExclusionsFor("d1")}
422
- ORDER BY d1.relative_path`,...t,...t,...t)}function wz(e,t){let n=new B(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>_e(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function kz(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 Iz(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:P(e.symbol)}}var Ma=new WeakMap,Mw=Ie({kind:"definition-exclusions",invalidation:pe("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:Pz});function Ow(e,t){let n=K(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=_(e,t);if(!i)return[];let o=Ae(e,t,i),s=Mw.read(e,t,o);if(s)return s;let a=n==="rust"?_z(e,t):Lz(e,t);return Mw.write(e,t,o,a),a}function Pz(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(Ez);return n.some(r=>r===null)?null:n}catch{return null}}function Ez(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?zz(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var jw=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),Dz=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,Tz=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function Lz(e,t){let n=_(e,t);if(!n||!Fz(n))return[];let r=oe(e,t);if(!r)return[];let i=Ma.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&jw.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let p=d.namedChild(0)?.text,m=d.namedChild(1);p&&(m?.type==="arrow_function"||m?.type==="function_expression")&&(l=p,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...Bw(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Ma.set(r,a),a}function Fz(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of jw)if(e.includes(n)){t=!0;break}return t&&Dz.test(e)?!0:e.includes("use")&&Tz.test(e)}var Nz=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Az(e){return Nz.test(e)}function Bw(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(Az(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});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 _z(e,t){let n=oe(e,t);if(!n)return[];let r=Ma.get(n);if(r)return r;let i=[],o=Mz(n);return o?(Ma.set(n,o),o):(Hw(n.rootNode,i,!1,!1),i.push(...Bw(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(...Vz(n.rootNode)),Ma.set(n,i),i)}function Mz(e){return Kz(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function Hw(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)",disposition:"implicit-usage"}),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)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?$z(e,t,n,r):r&&Uz(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?Oz(e,t,n):e.type==="mod_item"&&hg(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Hw(s,t,i,o)}function $z(e,t,n,r){let i=hg(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(Ww(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=Wz(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function Oz(e,t,n){let r=hg(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(qz)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(Ww)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function hg(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 jz=new Set(["test","bench","tokio::test","async_std::test"]),Bz=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),Hz=new Set(["allow","warn","deny","forbid","cfg","cfg_attr","doc","inline","cold","must_use","deprecated","repr","derive","automatically_derived","non_exhaustive","path","link","link_section","global_allocator","panic_handler"]);function Wz(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=Gz(e);return t?jz.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:Bz.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:Hz.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function qz(e){return/#\[\s*derive\s*\(/.test(e)}function Ww(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Uz(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Vz(e){let t=Jz(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:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function Gz(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function zz(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function Kz(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 $w=/\bwith\s*=\s*"([^"]+)"/g;function Jz(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){$w.lastIndex=0;let r;for(;(r=$w.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function qw(e){let t=yg(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function yg(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Ow(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Al(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return Yz(c)}}function Yz(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function bg(e,t={}){Yp(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Uw(e,t,n={}){Yp(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Vw(e,t){if(t.isIgnoredPath(e.relativePath))return xt("ignored-file");if(Hr(e.symbol))return xt("module-like-symbol");if(!_u(e.symbol))return xt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&_u(e.enclosingSymbol))return xt("nested-non-callable-value");if(!t.includeTests&&!Qz(e.relativePath))return xt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return xt("excluded-file-region");let n=M(e.symbol);if(n==="<constructor>")return xt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return xt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return xt("python-protocol-member")}return t.isDeclarationOnlyCallable()?xt("declaration-only-callable"):t.isFrameworkContractCallable()?xt("framework-contract-member"):et(e.symbol)?xt("rust-trait-impl-member"):No(e.symbol)?xt("rust-test-module"):!t.includeMembers&&!Xz(e)?xt("member"):e.endLine-e.startLine+1<t.minLoc?xt("below-min-loc"):{accepted:!0}}function Qz(e){return fe(e)!=="test"}function xt(e){return{accepted:!1,rejectionReason:e}}function _u(e){return ve(e)||e.endsWith("().")||e.endsWith(".")}function Xz(e){return _e(e.symbol)||Al(e.symbol).length===0}function Mu(e,t){return Q(e)-Q(t)||e.relativePath.localeCompare(t.relativePath)}function Pe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Qo(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 Gw(){return new Map}function zw(e,t,n){let r=new Map;for(let i of iR(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Ou(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Kw(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of sR(e,t))i.add(o.symbol_id);return i}for(let o of oR(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function Sg(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 $u(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function Jw(e){return e?.occurrences??0}function Ou(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=Qw(e,t,n);o.occurrences+=r,o.sources.add(i)}function Yw(e,t,n,r,i){if(r<=0)return;let o=Qw(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function Qw(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}var Zz=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Xo(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=oe(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:Zz.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var e2=1e3,t2=300;function hr(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=0,d=D("dead.candidates",()=>{let v=Pe(n2(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),p=0,m=o?D("dead.inactive-barrels",()=>{let v=new Set(zx(e));return p=v.size,v},()=>({paths:p})):new Set,f=0,g=a?Gw():D("dead.mention-reference-counts",()=>{let v=zw(e,m,d.map(w=>w.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,y=a?D("dead.mentioned-symbol-ids",()=>{let v=Kw(e,d.map(w=>w.symbolId),m,{conservative:m.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,x=a?d.filter(v=>!y.has(v.symbolId)):d.filter(v=>!$u(g,v.symbolId,v.relativePath));a?D("dead.source-fallback.dead-code-only",()=>l2(e,x,g,{inactiveBarrelPaths:m}),()=>({definitions:x.length,testReferencesIncluded:!0})):D("dead.source-fallback.ast",()=>c2(e,x,g,{inactiveBarrelPaths:m}),()=>({definitions:x.length,testReferencesIncluded:!0}));let R=a?x.filter(v=>!Sg(g,v.symbolId)):x.filter(v=>!$u(g,v.symbolId,v.relativePath));D("dead.caller-map-supplement",()=>f2(e,R,g,{inactiveBarrelPaths:m,includeSemantic:!a&&l}),()=>({definitions:R.length,semantic:!a&&l}));let b=a?x.filter(v=>!Sg(g,v.symbolId)):d;return a2(e,o2(b,g))}function n2(e,t){let n=qw(e),r=[];for(let i of oa(e,{scope:t.scope,symbolMatches:_u,sqlPrefilter:"function-like"}))Vw(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>i2(e,i),isFrameworkContractCallable:()=>Xo(e,i)}).accepted&&r.push(i);return r}var r2=["method_signature","abstract_method_signature","call_signature","construct_signature"];function i2(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=oe(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...r2]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Qe(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
423
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function o2(e,t){return e.map(n=>s2(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 s2(e,t){let n=t.get(e.symbolId)??new Map,r=Jw(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,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function a2(e,t){let n=yg(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(tt(e,u.relative_path)){a++;continue}if(Oe(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),p=d?.disposition==="implicit-usage"?d.reason:void 0,m=p?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";m==="dead-code"?i++:m==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:P(u.symbol),sameFileRefs:u.same_file_refs,kind:m,...p?{implicitUsageReason:p}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function c2(e,t,n,r){if(t.length===0)return;let i=new B(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 q(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(p2(e,c)||Ou(n,c.target.symbolId,c.sourceFile,m2(c),"source-fallback"))})}function l2(e,t,n,r){if(t.length===0)return;let i=new B(e),o=u2(t),s=new Set(i.sourceFiles());for(let u of q(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Du(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:p})=>{let m=o.get(d);return m?d2(u,d,m,()=>l(u),{permissive:p!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Uw(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Xw(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Ou(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function u2(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 d2(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>_t(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>_t(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function p2(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Xw(e,t)}function m2(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Xw(e,t){return t.occurrences>1?!1:Ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function f2(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=e2&&q(e).length>=t2,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||Yw(n,u.symbolId,d,1,"caller-map")};if(o?D("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=qt(e,u,{semantic:!1});for(let p of d)s(u,p.file)}},()=>({definitions:t.length,semantic:!1})):D("dead.caller-map.per-symbol",()=>{for(let u of t){let d=qt(e,u,{semantic:i});if(d.length!==0)for(let p of d)s(u,p.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=D("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!$u(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=dw(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let p of d)s(u,p)}}function vg(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
424
- gs.symbol,
425
- COUNT(*) AS ref_count,
426
- COUNT(DISTINCT ref_d.id) AS file_count,
427
- def_d.relative_path AS defined_in
428
- FROM mentions m
429
- JOIN chunks c ON m.chunk_id = c.id
430
- JOIN documents ref_d ON c.document_id = ref_d.id
431
- JOIN global_symbols gs ON m.symbol_id = gs.id
432
- JOIN (
433
- SELECT m2.symbol_id, c2.document_id
434
- FROM mentions m2
435
- JOIN chunks c2 ON m2.chunk_id = c2.id
436
- WHERE m2.role = 1
437
- GROUP BY m2.symbol_id
438
- ) sym_def ON sym_def.symbol_id = gs.id
439
- JOIN documents def_d ON sym_def.document_id = def_d.id
440
- WHERE m.role != 1
441
- AND def_d.id != ref_d.id
442
- ${e.pathExclusionsFor("def_d")}
443
- ${e.symbolNoiseFor("gs")}
444
- ${i}
445
- GROUP BY gs.id
446
- ORDER BY ref_count DESC
447
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:P(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:g2(e,r,n)}function g2(e,t,n){return Ue(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>h2(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function h2(e,t){let r=qt(e,t,{limit:500}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:P(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath}}function xg(e,t,n={}){return w2(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Rg(e,t){let n=te(e,t),r=b2(e,t);if(r.length>0&&!v2(n))return r;let i=S2(e,t,n);return wg(t)&&i.length>0?i:x2([...r,...i])}function Cg(e,t,n={}){let r=vt(e,t);if(!r)return[];let i=ek(e,r),o=n.semantic===!1?null:Zw(e,r);return(o?y2(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function y2(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function b2(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
448
- FROM mentions m
449
- JOIN chunks c ON m.chunk_id = c.id
450
- JOIN documents d ON c.document_id = d.id
451
- JOIN global_symbols gs ON m.symbol_id = gs.id
452
- WHERE gs.symbol LIKE ?
453
- AND m.role = 2
454
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:P(r.symbol),fromFile:r.importer}))}function S2(e,t,n=te(e,t)){let r=n?.relativePath??null,i=n?M(n.symbol):t.replace(/\(\)$/,""),o=n?Hr(n.symbol):!1,s=new Set;for(let c of q(e,{includeIgnored:!1}))for(let l of Ce(e,c))R2(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=wg(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?P(n.symbol):i),fromFile:c}))}function v2(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||K(e.relativePath)==="clojure"))}function x2(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function R2(e,t,n){return!e.sourcePath||n.targetFile&&Se(e.sourcePath)!==Se(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&E2(t)||e.kind==="namespace"&&C2(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function C2(e,t){let n=t.trim().replace(/\(\)$/,"");return wg(n)?e.importedName===n||e.localName===n:!1}function wg(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function w2(e,t,n={}){let r=vt(e,t);return r?k2(e,r,n)??(n.semantic===!1?null:Zw(e,r))??ek(e,r):null}function k2(e,t,n){let i=e.all(`SELECT DISTINCT
455
- gs.symbol,
456
- def_d.relative_path AS from_file,
457
- imp_d.relative_path AS importer,
458
- EXISTS (
459
- SELECT 1
460
- FROM mentions ref_m
461
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
462
- WHERE ref_m.symbol_id = gs.id
463
- AND ref_m.role != 1
464
- AND ref_c.document_id = imp_d.id
465
- ) AS used
466
- FROM mentions m
467
- JOIN chunks c ON m.chunk_id = c.id
468
- JOIN documents imp_d ON c.document_id = imp_d.id
469
- JOIN global_symbols gs ON m.symbol_id = gs.id
470
- LEFT JOIN (
471
- SELECT m2.symbol_id, c2.document_id
472
- FROM mentions m2
473
- JOIN chunks c2 ON m2.chunk_id = c2.id
474
- WHERE m2.role = 1
475
- GROUP BY m2.symbol_id
476
- ) sym_def ON sym_def.symbol_id = gs.id
477
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
478
- WHERE imp_d.relative_path = ?
479
- AND m.role = 2
480
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Pa(e,t);return i.map(s=>({symbol:s.symbol,shortName:P(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 Zw(e,t){let n=Pa(e,t);return n.length>0?n.map(r=>{let i=tk(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 ek(e,t){let n=I2(t,_(e,t));return Ce(e,t).map(r=>{let i=tk(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||P2(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function I2(e,t){let n=new Set;if(K(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function P2(e,t){if(K(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function tk(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 E2(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function kg(e,t){let n=Yo(e,t),r=Ll(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,d=1/0;for(let p of i)if(p!==l&&p.startLine<=l.startLine&&p.endLine>=l.endLine){if(p.startLine===l.startLine&&p.endLine===l.endLine&&!Cx(p.symbol,l.symbol))continue;let f=p.endLine-p.startLine;f<d&&(d=f,u=p)}u?u.children.push(l):s.push(l)}return s}function Ig(e,t){let n=te(e,t);if(!n)return[];let i=new B(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Rx(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:P(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:$e(o.symbol)??"unknown"}));return K(n.relativePath)!=="clojure"?i:T2(i,D2(e,n))}function D2(e,t){let n=M(t.symbol);if(!n)return[];let r=P(t.symbol);return(ce(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function T2(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function Pg(e,t){let n=te(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
481
- FROM mentions m
482
- JOIN chunks c ON m.chunk_id = c.id
483
- JOIN (
484
- SELECT m2.symbol_id, c2.document_id
485
- FROM mentions m2
486
- JOIN chunks c2 ON m2.chunk_id = c2.id
487
- WHERE m2.role = 1
488
- GROUP BY m2.symbol_id
489
- ) sym_def ON sym_def.symbol_id = m.symbol_id
490
- WHERE m.symbol_id = ?
491
- AND m.role != 1
492
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:P(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function Eg(e,t){let n=vt(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
493
- FROM mentions m
494
- JOIN chunks c ON m.chunk_id = c.id
495
- JOIN documents d ON c.document_id = d.id
496
- JOIN global_symbols gs ON m.symbol_id = gs.id
497
- JOIN (
498
- SELECT m2.symbol_id, c2.document_id
499
- FROM mentions m2
500
- JOIN chunks c2 ON m2.chunk_id = c2.id
501
- WHERE m2.role = 1
502
- GROUP BY m2.symbol_id
503
- ) sym_def ON sym_def.symbol_id = gs.id
504
- JOIN documents def_d ON sym_def.document_id = def_d.id
505
- WHERE d.relative_path = ?
506
- AND m.role != 1
507
- AND def_d.id != d.id
508
- GROUP BY d.id
509
- 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=ge(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Dg(e,t={}){return L2(e,t).map(n=>({name:P(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function L2(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
510
- COUNT(DISTINCT c.document_id) AS file_count,
511
- def_d.relative_path AS defined_in
512
- FROM mentions m
513
- JOIN chunks c ON m.chunk_id = c.id
514
- JOIN global_symbols gs ON m.symbol_id = gs.id
515
- JOIN (
516
- SELECT m2.symbol_id, c2.document_id
517
- FROM mentions m2
518
- JOIN chunks c2 ON m2.chunk_id = c2.id
519
- WHERE m2.role = 1
520
- GROUP BY m2.symbol_id
521
- ) sym_def ON sym_def.symbol_id = gs.id
522
- JOIN documents def_d ON sym_def.document_id = def_d.id
523
- WHERE m.role != 1
524
- AND def_d.id != c.document_id
525
- ${e.pathExclusionsFor("def_d")}
526
- ${e.symbolNoiseFor("gs")}
527
- ${i}
528
- GROUP BY gs.id
529
- HAVING file_count > 1
530
- ORDER BY file_count DESC
531
- LIMIT ?`,...o,n)}function Tg(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
532
- FROM mentions m
533
- JOIN chunks c ON m.chunk_id = c.id
534
- JOIN documents d ON c.document_id = d.id
535
- JOIN global_symbols gs ON m.symbol_id = gs.id
536
- JOIN (
537
- SELECT m2.symbol_id, c2.document_id
538
- FROM mentions m2
539
- JOIN chunks c2 ON m2.chunk_id = c2.id
540
- WHERE m2.role = 1
541
- GROUP BY m2.symbol_id
542
- ) sym_def ON sym_def.symbol_id = gs.id
543
- JOIN documents def_d ON sym_def.document_id = def_d.id
544
- WHERE m.role != 1
545
- AND def_d.id != d.id
546
- ${e.pathExclusionsFor("d")}
547
- ${e.symbolNoiseFor("gs")}
548
- ${i}
549
- GROUP BY d.id
550
- ORDER BY symbol_count DESC
551
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}function Lg(e,t,n){let r=vt(e,t)??t,i=vt(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
552
- FROM global_symbols gs
553
- WHERE (
554
- -- Defined in file1, referenced in file2
555
- EXISTS (
556
- SELECT 1
557
- FROM mentions def_m
558
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
559
- JOIN documents d ON def_c.document_id = d.id
560
- WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
561
- )
562
- AND EXISTS (
563
- SELECT 1 FROM mentions m
564
- JOIN chunks c ON m.chunk_id = c.id
565
- JOIN documents d ON c.document_id = d.id
566
- WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
567
- )
568
- ) OR (
569
- -- Defined in file2, referenced in file1
570
- EXISTS (
571
- SELECT 1
572
- FROM mentions def_m
573
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
574
- JOIN documents d ON def_c.document_id = d.id
575
- WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
576
- )
577
- AND EXISTS (
578
- SELECT 1 FROM mentions m
579
- JOIN chunks c ON m.chunk_id = c.id
580
- JOIN documents d ON c.document_id = d.id
581
- WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
582
- )
583
- )`,r,i,i,r);return{...nk(r,i,o?.shared??0)}}function Fg(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
584
- def_d.relative_path AS file1,
585
- ref_d.relative_path AS file2,
586
- COUNT(DISTINCT gs.id) AS shared
587
- FROM mentions m
588
- JOIN chunks c ON m.chunk_id = c.id
589
- JOIN documents ref_d ON c.document_id = ref_d.id
590
- JOIN global_symbols gs ON m.symbol_id = gs.id
591
- JOIN (
592
- SELECT m2.symbol_id, c2.document_id
593
- FROM mentions m2
594
- JOIN chunks c2 ON m2.chunk_id = c2.id
595
- WHERE m2.role = 1
596
- GROUP BY m2.symbol_id
597
- ) sym_def ON sym_def.symbol_id = gs.id
598
- JOIN documents def_d ON sym_def.document_id = def_d.id
599
- WHERE m.role != 1
600
- AND def_d.id != ref_d.id
601
- ${e.pathExclusionsFor("def_d","ref_d")}
602
- ${i}
603
- GROUP BY def_d.id, ref_d.id
604
- ORDER BY shared DESC
605
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>nk(a.file1,a.file2,a.shared))}function nk(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function $a(e,t={}){return ju(e,t).cycles}function ju(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ge(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(p,m){if(m>r){l=!0;return}if(a.has(p)){let g=c.indexOf(p);if(g!==-1){let h=c.slice(g).concat(p),y=h.indexOf(h.reduce((b,v)=>b<v?b:v)),x=[...h.slice(y,-1),...h.slice(0,y),h[y]],R=x.join(" -> ");d.has(R)||(d.add(R),o.push({path:x,kind:F2(x)}))}return}if(s.has(p))return;s.add(p),a.add(p),c.push(p);let f=i.get(p);if(f)for(let g of f)u(g,m+1);c.pop(),a.delete(p)}let d=new Set;for(let p of i.keys())s.has(p)||u(p,0);return o.sort((p,m)=>p.kind!==m.kind?p.kind==="real"?-1:1:p.path.length-m.path.length),{cycles:o,truncated:l,maxDepth:r}}function F2(e){for(let r of e){let i=fe(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":_o(t)||_o(n)||rk(t,n)||rk(n,t)||ik(t,n)||ik(n,t)||fe(t)==="entry"||fe(n)==="entry"?"module-hierarchy":"real"}function rk(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 ik(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 Ng(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new B(e);return Pe(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>N2(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function N2(e,t,n){let r=[...new Set(qt(e,t,{limit:500,semantic:n}).map(l=>l.file))].sort(),i=new Map;for(let l of pn(e,t,{limit:500,semantic:n})){if(l.file===t.relativePath)continue;let u=`${l.symbol}|${l.file}`;i.has(u)||i.set(u,{symbol:l.symbol,shortName:P(l.symbol),file:l.file})}let o=[...i.values()].sort((l,u)=>l.file.localeCompare(u.file)||l.symbol.localeCompare(u.symbol)),s=r.length,a=o.length,c=s*a;return{symbol:t.symbol,shortName:P(t.symbol),fanIn:s,fanOut:a,callerFiles:r,externalCallees:o,score:c,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${s} incoming file(s) reference this symbol`,`${a} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function ji(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new B(e),s=t.semantic!==!1,a=0,c=D("isolated.candidates",()=>{let w=Pe(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(I=>!Xo(e,I));return a=w.length,w},()=>({definitions:a})),l=0,u=D("isolated.strict-callees",()=>{let v=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=v.size,v},()=>({definitions:c.length,symbols:l})),d=c.filter(v=>!u.has(v.symbolId)),p=0,m=D("isolated.scip-callers",()=>{let v=o.crossFileCallerMap(d,{semantic:!1});return p=v.size,v},()=>({definitions:d.length,symbols:p})),f=new Set(m.keys());for(let v of o.frameworkReferencedSymbolIds(d))f.add(v);let g=d.filter(v=>!f.has(v.symbolId));if(s&&g.length>0){for(let v of Yr(e,g).keys())f.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(v);g=g.filter(v=>!f.has(v.symbolId)).filter(v=>!u.has(v.symbolId))}let h=0,y=D("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:w=>fe(w)==="test"});return h=v.size,v},()=>({definitions:g.length,symbols:h}));for(let v of y.keys())f.add(v);let x=g.filter(v=>!f.has(v.symbolId)),R=0,b=D("isolated.additive-callees",()=>{let v=o.symbolsWithNonSelfCallees(x,{additive:!0,semantic:s});return R=v.size,v},()=>({definitions:x.length,symbols:R}));for(let v of b)u.add(v);return x.filter(v=>!u.has(v.symbolId)).sort((v,w)=>Q(w)-Q(v)||v.relativePath.localeCompare(w.relativePath)||v.startLine-w.startLine).map(v=>({symbol:v.symbol,shortName:P(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:Q(v)}))}import{SymbolInformation_Kind as rt}from"@c4312/scip";var ok=500;function A2(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Rw.get(n);if(r!==void 0)return r;for(let[i,o]of Lu)if(o.toLowerCase().includes(n))return i;return null}function Ag(e,t,n={}){let{scope:r,limit:i=100}=n,o=A2(t);return o===null?[]:_2(e,r).map(a=>({row:a,resolvedKind:ak(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:P(a.symbol),kind:c,kindName:Un(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function _g(e,t={}){let n=M2(e,t.scope);for(let r of $2(e,t.scope)){let i=ak(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:Un(r),count:i}))}function _2(e,t){return Ue(e,{scope:t}).map(O2)}function M2(e,t){let n=new Map;for(let r of sk(q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
606
- FROM defn_enclosing_ranges der
607
- JOIN global_symbols gs ON der.symbol_id = gs.id
608
- JOIN documents d ON der.document_id = d.id
609
- WHERE gs.kind IS NOT NULL
610
- AND gs.kind != 0
611
- AND gs.symbol NOT LIKE '%#'
612
- AND d.relative_path IN (${i})
613
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function $2(e,t){let n=[];for(let r of sk(q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
614
- gs.kind,
615
- gs.documentation,
616
- gs.enclosing_symbol,
617
- d.relative_path,
618
- der.start_line,
619
- der.end_line
620
- FROM defn_enclosing_ranges der
621
- JOIN global_symbols gs ON der.symbol_id = gs.id
622
- JOIN documents d ON der.document_id = d.id
623
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
624
- ${e.symbolNoiseFor("gs")}
625
- AND d.relative_path IN (${i})
626
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function sk(e){let t=[];for(let n=0;n<e.length;n+=ok)t.push(e.slice(n,n+ok));return t}function O2(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 ak(e){return e.kind!==null&&e.kind!==0?j2(e.kind,e.symbol,e.documentation):B2(e.symbol,e.documentation,e.enclosing_symbol)}function j2(e,t,n){let r=(n??"").toLowerCase();if($e(t)==="type"){if(r.includes("type "))return rt.TypeAlias;if(r.includes("interface "))return rt.Interface;if(r.includes("struct "))return rt.Struct;if(r.includes("trait "))return rt.Trait;if(r.includes("class "))return rt.Class}return e}function B2(e,t,n){let r=Je(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=$e(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?rt.TypeAlias:a.includes("interface ")?rt.Interface:a.includes("struct ")?rt.Struct:a.includes("trait ")?rt.Trait:a.includes("class ")?rt.Class:rt.Class:s==="method"?o?.suffix==="type"?rt.Method:rt.Function:s==="namespace"?rt.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?rt.Function:(n?$e(n):o?.suffix??null)==="type"?rt.Field:rt.Variable}function Mg(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ge(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],p=0;for(let b of o.keys()){if(c.has(b))continue;let v=[],w=(o.get(b)??new Set).values();for(c.set(b,p),l.set(b,p),p+=1,d.push(b),u.add(b),v.push({node:b,iter:w,pendingChild:null});v.length>0;){let I=v[v.length-1];if(I.pendingChild!==null){let T=I.pendingChild;I.pendingChild=null,l.set(I.node,Math.min(l.get(I.node),l.get(T)))}let C=I.iter.next();if(C.done){if(l.get(I.node)===c.get(I.node)){let T=[];for(;;){let F=d.pop();if(u.delete(F),T.push(F),s.set(F,a.length),F===I.node)break}a.push(T)}v.pop();continue}let k=C.value;if(c.has(k))u.has(k)&&l.set(I.node,Math.min(l.get(I.node),c.get(k)));else{c.set(k,p),l.set(k,p),p+=1,d.push(k),u.add(k);let T=(o.get(k)??new Set).values();I.pendingChild=k,v.push({node:k,iter:T,pendingChild:null})}}}let m=new Map;for(let b=0;b<a.length;b++)m.set(b,new Set);for(let[b,v]of o){let w=s.get(b);for(let I of v){let C=s.get(I);C!==w&&m.get(w).add(C)}}let f=new Array(a.length),g=new Array(a.length);for(let b=0;b<a.length;b++){let v=[],w=0;for(let I of m.get(b)){let C=g[I];C>w&&(w=C,v=f[I])}f[b]=[b,...v],g[b]=1+w}function h(b){return f[b]}let y=a.map(b=>[...b].sort()),x=new Set,R=[];for(let b=0;b<a.length;b++){let w=h(b).map(k=>y[k]),I=w.map(k=>k[0]);if(w.length<i)continue;let C=I.join(" ");x.has(C)||(x.add(C),R.push(H2(I,w)))}return R.sort((b,v)=>v.depth-b.depth),W2(R).slice(0,n)}function H2(e,t){let n=t.reduce((i,o)=>i+o.length,0),r=t.filter(i=>i.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${n} file(s) are represented; ${r} component(s) contain a dependency cycle`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function W2(e){let t=[];for(let n of e)t.some(r=>q2(n.chain,r.chain))||t.push(n);return t}function q2(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function $g(e,t){let n=te(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
627
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:P(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 d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:P(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Je(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,p=1;d>=0;d--,p++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:p})}return u}function Qr(e,t,n={}){let r=te(e,t);if(!r)return null;let i=n.semantic!==!1,o=qt(e,r,{semantic:i}).filter(a=>ve(a.symbol)).slice(0,50),s=Qo(pn(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:P(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:P(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:P(a.symbol),file:a.file}))}}function mn(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function it(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Xr(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 ck(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function Og(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Zo(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 es(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function lk(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Zo(n),c=[],l=[];for(let p of e){let m=n.get(p)??0;o+=m*m,t.has(p)&&(i+=m*m,m>=a?c.push(p):l.push(p))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let p of t){let m=n.get(p)??0;s+=m*m}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((p,m)=>(n.get(m)??0)-(n.get(p)??0)),{similarity:d,significantShared:c,trivialShared:l}}function uk(e,t,n,r){let i=0,o=r.medianIdf??Zo(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function ts(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=X2(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ve(o.symbol))return[];if(o.callees.size===0)return dk(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=V2(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):dk(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Oa(e,t,n,r={}){let i=te(e,t),o=te(e,n);if(!i||!o)return null;let s=ts(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:P(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:P(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:U2(s)}}function U2(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function V2(e,t,n,r){let i=ns(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=sK(t,i.corpus),s=rK(o,i),a=G2(o,i),c=Zo(a),l=es(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let p=es(d.callees,a),m=gk(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:p});m&&u.push(m)}return u.sort((d,p)=>p.similarity-d.similarity),u}function G2(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Og(n,t.corpus.length+1)}function gk(e,t,n,r){let i=K2(e,t,n,r);if(!J2(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=vk(c,"callees");return{symbolA:e.symbol,shortNameA:P(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:P(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(P),uniqueToA:[...it(e.callees,t.callees)].map(P),uniqueToB:[...it(t.callees,e.callees)].map(P),...l}}function z2(e,t,n,r){let i=r.magnitudeA??es(e.callees,n),o=r.magnitudeB??es(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Zo(n);for(let p of e.callees){if(!t.callees.has(p))continue;let m=n.get(p)??0;s+=m*m,c+=1,m>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function K2(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?lk(e.callees,t.callees,n,{medianIdf:r.medianIdf}):uk(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function J2(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function Bi(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=re(),u=0,d=0,p=0,m=0,f=0,g=0,h=0;return D("similar.all",()=>{let x=ns(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),R=x.corpus;u=R.length;let b=t.focusFiles,v=[],w=0;return D("similar.all.pair-scan",()=>{for(let I=0;I<R.length;I+=1){let C=R[I],k=b?.has(C.file)??!1,T=x.weightedMagnitudes[I],F=new Set;for(let V of C.callees){let ie=x.candidateIndexesByCallee.get(V);if(ie)for(let W of ie)W<=I||b&&!k&&!b.has(R[W].file)||F.add(W)}l&&(p+=F.size,F.size>0&&(d+=1));for(let V of F){let ie=R[V];if(s&&C.file===ie.file){l&&(f+=1);continue}if(hk(C,ie)){l&&(g+=1);continue}l&&(m+=1);let W=gk(C,ie,x.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:x.medianIdf,magnitudeA:T,magnitudeB:x.weightedMagnitudes[V]});W&&(Y2(v,W,r,w),l&&(h+=1),w+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:p,comparedPairs:m,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:v.length})),D("similar.all.sort-project",()=>(v.sort((I,C)=>C.result.similarity-I.result.similarity||I.order-C.order),v.map(I=>I.result)),()=>({topResults:v.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:p,comparedPairs:m,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function Wg(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=re(),l=0,u=0,d=0,p=0,m=0,f=0,g=0;return D("similar.all-count",()=>{let y=ns(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),x=y.corpus;l=x.length;let R=t.focusFiles;return D("similar.all-count.pair-scan",()=>{for(let b=0;b<x.length;b+=1){let v=x[b],w=R?.has(v.file)??!1,I=y.weightedMagnitudes[b],C=new Set;for(let k of v.callees){let T=y.candidateIndexesByCallee.get(k);if(T)for(let F of T)F<=b||R&&!w&&!R.has(x[F].file)||C.add(F)}c&&(d+=C.size,C.size>0&&(u+=1));for(let k of C){let T=x[k];if(o&&v.file===T.file){c&&(m+=1);continue}if(hk(v,T)){c&&(f+=1);continue}c&&(p+=1),z2(v,T,y.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:y.medianIdf,magnitudeA:I,magnitudeB:y.weightedMagnitudes[k]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:p,crossFileSkips:m,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:p,crossFileSkips:m,signatureSkips:f,insertedResults:g}))}function hk(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var yk=Ie({kind:"source-fingerprints",invalidation:pe("source-fingerprints"),serialize:IK,deserialize:kK});function Y2(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var Q2=["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 X2(e,t,n){let r=te(e,t);if(!r||!ve(r.symbol))return null;let i=new B(e),o=pn(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Bu(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var Z2=me("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),eK=me("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function bk(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=Z2.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return D("similar.callee-fingerprints.resolve",()=>{let p=a.get(c);if(l=p!==void 0,p||(p=iK(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,p)),u=p.length,i===void 0)return p;let m=p.filter(f=>f.symbol!==i);return d=p.length-m.length,m},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function tK(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=eK.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return D("similar.callee-index.resolve",()=>{let p=s.get(a);return c=p!==void 0,p||(p=nK(bk(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,p)),l=p.corpus.length,u=p.docFreq.size,d=p.candidateIndexesByCallee.size,p},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function ns(e){return{calleeCorpus:t=>bk(e,t),calleeIndex:t=>tK(e,t),sourceCorpus:(t={})=>kk(e,t),sourceIndex:(t={})=>fk(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?yK(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):hK(t,fk(e,{scanLimit:n.scanLimit}))}}function nK(e){let t=re(),n=0,r=D("similar.callee-index.doc-frequency",()=>{let p=new Map;for(let m of e)for(let f of m.callees)p.set(f,(p.get(f)??0)+1);return n=p.size,p},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=D("similar.callee-index.idf-weights",()=>Og(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=D("similar.callee-index.weighted-magnitudes",()=>e.map(p=>es(p.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=D("similar.callee-index.candidate-buckets",()=>{let p=new Map;for(let m=0;m<e.length;m+=1){let f=e[m];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=p.get(g);h||(h=[],p.set(g,h)),h.push(m),t&&(a+=1)}}return t&&(l=p.size),p},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=D("similar.callee-index.median-idf",()=>Zo(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function rK(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function iK(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=re(),a=new B(e),c=0,l=D("similar.callee-fingerprints.candidates",()=>{let g=Pe(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=D("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),p=0,m=0,f=0;return D("similar.callee-fingerprints.shape",()=>{let g=l.map(x=>({symbol:x.symbol,file:x.relativePath,callees:Bu((d.get(x.symbolId)??[]).map(R=>R.symbol)),paramCount:a.callableSignature(x)?.paramCount??-1})),h=oK(g);s&&(f=h.filter((x,R)=>x.callees.size!==g[R].callees.size).length);let y=h.filter(x=>x.callees.size>=n);return p=y.length,s&&(m=y.reduce((x,R)=>x+R.callees.size,0)),y},()=>({candidateCount:c,fingerprintCount:p,retainedCalleeCount:m,minCallees:n,siblingSaturatedFingerprints:f}))}var Sk=5;function oK(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=Sk);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function sK(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=Sk);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Bu(e){return new Set([...e].filter(t=>!aK(t)))}function aK(e){return Q2.some(t=>e.includes(t))}function dk(e,t,n){let r=dK(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return D("similar.source-shape",()=>{let p=ns(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=p.length;for(let m of p){if(m.symbol===r.symbol||m.tokens.size<3)continue;c+=1;let f=mn(r.tokens,m.tokens);if(f.size<2){l+=1;continue}let g=new Set([...r.tokens,...m.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:P(r.symbol),fileA:r.file,symbolB:m.symbol,shortNameB:P(m.symbol),fileB:m.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...it(r.tokens,m.tokens)].sort(),uniqueToB:[...it(m.tokens,r.tokens)].sort(),...vk([...f],"source-tokens")})}return o.sort((m,f)=>f.similarity-m.similarity||m.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function vk(e,t){let n=e.flatMap(Bg),r=e.flatMap(h=>pk(h,t)),i=jg(n,xk),o=jg(n,Rk),s=jg(r,Hg),a=[...new Set(r.filter(mk))],c=e.filter(h=>{let y=pk(h,t);return y.some(x=>Hg.has(x))&&y.some(mk)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Ck.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,p=i.length+o.length>0,m=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=m?"domain-behavior":d?p?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||m)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:cK(f,g)}}function cK(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function jg(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Bg(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function pk(e,t){if(t==="source-tokens")return Bg(e);let n=M(e);return Bg(n.length>0?n:lK(e))}function lK(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function mk(e){return e.length>3&&!Hg.has(e)&&!xk.has(e)&&!Rk.has(e)&&!Ck.has(e)&&!uK.has(e)}var Hg=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),xk=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Rk=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Ck=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),uK=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function dK(e,t){let n=te(e,t);if(!n||!ve(n.symbol))return null;let r=pK(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function pK(e,t){let n=M(t.symbol),r=RK(e,t.relativePath,t.startLine,t.endLine,n),i=Ek(r,n);return i.size>0?i:null}var mK=me("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),fK=me("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function wk(e){return`${e.scanLimit??""}`}function kk(e,t={}){let n=mK.get(e,()=>new Map),r=wk(t),i=n.get(r);return i||(i=xK(e,t),n.set(r,i)),i}function fk(e,t={}){let n=fK.get(e,()=>new Map),r=wk(t),i=n.get(r);return i||(i=gK(kk(e,t)),n.set(r,i)),i}function gK(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function hK(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function yK(e,t,n){let r=re(),i=new B(e),o=bK(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=D("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of q(e,{includeIgnored:!1})){s+=1;let y=_(e,h);y&&(a+=1,SK(y,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=D("similar.source-shape.target-definitions",()=>{let f=Pe(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),p=0;return D("similar.source-shape.target-fingerprints",()=>{let f=Ik(e,d);return r&&(p=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:p})).filter(f=>f.symbol!==t.symbol)}function bK(e,t){return Math.max(2,Math.ceil(e*t))}function SK(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(vK(r,o)&&(i+=1,i>=n))return!0;return!1}function vK(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function xK(e,t={}){let n=new B(e),{scanLimit:r}=t,i=Pe(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return Ik(e,i)}function Ik(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=_(e,i);if(!s)continue;let a=Ae(e,i,s),c=wK(e,i,a),l=!1,u=null;for(let d of o){let p=CK(d),m=c.get(p),f=m?new Set(m.tokens):null;f||(u??=Qe(e,i),f=Ek(Pk(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(p,{key:p,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&PK(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function RK(e,t,n,r,i){let o=Qe(e,t);return o.length===0?"":Pk(o,n,r,i)}function Pk(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
628
- `);let i=[new RegExp(`\\bdef\\s+${J(r)}\\b`),new RegExp(`\\bfun\\s+${J(r)}\\b`),new RegExp(`\\bfn\\s+${J(r)}\\b`),new RegExp(`\\bfunction\\s+${J(r)}\\b`),new RegExp(`\\b${J(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&DK(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
629
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
630
- `)}function CK(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function wK(e,t,n){return yk.read(e,t,n)??new Map}function kK(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function IK(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function PK(e,t,n,r){yk.write(e,t,n,new Map(r))}function Ek(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=EK(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 EK(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 DK(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Vn(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function Gn(e){let t=Dk(e.profile?.name),n=()=>{let r=[];t=Dk(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of TK(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of LK(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?D(`pairwise-profile:${e.profile.name}`,n,()=>({...FK(e.profile?.metadata),...t})):n()}function TK(e,t){if(e.candidateIndex)return Tk(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function LK(e,t){if(e.candidateIndex)return Tk(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function Tk(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function Dk(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function FK(e){return typeof e=="function"?e():e??{}}function qg(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=NK(e,{scope:i,minDeps:s}),l=Vn(a,u=>u.deps);return Gn({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>_K(u,d,n,c)})}function NK(e,t){let{scope:n,minDeps:r}=t,i=ge(e,n),{universalDeps:o,distinctiveDeps:s}=AK(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 AK(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 _K(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=Xr(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 Zr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&Lk(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)MK(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Lk(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Hu(e,t){if(e.size===0||t.size===0)return 0;let i=mn(e,t).size/Math.min(e.size,t.size)*Math.min(1,Math.min(e.size,t.size)/(.35*Math.max(e.size,t.size)));return Math.max(Xr(e,t),i)}function ei(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Wu(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function ue(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ct(e){return[...e].sort()}function MK(e,t,n,r,i,o){let s=[],a=[];for(let c of e)$K(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function $K(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Lk(e,t,n){return e==="generic"?t:n}function Hi(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=rn(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=Vn(l,d=>d.tokens);return Gn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,p)=>OK(d,p,n),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.componentA.localeCompare(p.componentA)||d.fileB.localeCompare(p.fileB)||d.componentB.localeCompare(p.componentB)})}function OK(e,t,n){let r=mn(e.tokens,t.tokens);if(r.size<6||!jK(r))return null;let i=Xr(e.tokens,t.tokens);if(i<n)return null;let o=ue(r,"component:"),s=ue(r,"native:"),a=ue(r,"prop:"),c=ue(r,"event:"),l=ue(r,"binding:"),u=BK({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:ct(it(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(it(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function jK(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return ei([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function BK(e){return Zr({genericWords:WK,primitiveGroups:[{values:e.sharedNativeTags,reasonPrefix:"shared native tags",bucket:"generic"},{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"}],recommendation:HK})}function HK(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific UI primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var WK=new Set(["actions","app","button","card","children","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function Wi(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=rn(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=Vn(l,d=>d.tokens);return Gn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,p)=>qK(d,p,n,r),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.componentA.localeCompare(p.componentA)||d.fileB.localeCompare(p.fileB)||d.componentB.localeCompare(p.componentB)})}function qK(e,t,n,r){let i=mn(e.tokens,t.tokens);if(i.size<r||!GK(i))return null;let o=Hu(e.tokens,t.tokens);if(o<n)return null;let s=ue(i,"hook:"),a=ue(i,"react-hook:"),c=ue(i,"effect:"),l=ue(i,"state:"),u=ue(i,"request:"),d=ue(i,"handler:"),p=ue(i,"handler-verb:"),m=UK({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:p});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:p,evidenceClass:m.evidenceClass,actionTier:m.actionTier,evidenceClassReasons:m.reasons,recommendation:m.recommendation,uniqueToA:ct(it(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(it(t.tokens,e.tokens)).slice(0,25),reason:zK({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:p}),locA:e.profile.loc,locB:t.profile.loc}}function UK(e){return Zr({genericWords:KK,stripPrefixes:JK,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:VK})}function VK(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function GK(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return ei([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function zK(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var KK=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),JK=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function ja(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return rn(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>YK(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,p)=>p.componentLines-d.componentLines||p.fileLines-d.fileLines||d.file.localeCompare(p.file)).slice(0,s)}function YK(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Wu(e,QK({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=XK(e),c=ZK(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:eJ(c,a),reasons:i,loc:e.loc}}function QK(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function XK(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(p=>p.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(p=>nJ.has(p))>=0,s=n.some(p=>tJ.has(p));if(Fk(r)||Fk(e.name))return"component";let c=rJ.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function Fk(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Nk.has(t.at(-1))?!0:[...Nk].some(n=>e.endsWith(iJ(n)))}function ZK(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function eJ(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var tJ=new Set(["component","components","panel","panels","partial","partials"]),Nk=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),nJ=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),rJ=new Set(["page","route","screen"]);function iJ(e){return e.charAt(0).toUpperCase()+e.slice(1)}function qi(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=oJ(e,{scope:o,minTokens:r,scanLimit:s}),u=Vn(l,d=>d.tokens);return Gn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,p)=>aJ(d,p,n),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.fileB.localeCompare(p.fileB)})}function oJ(e,t){return rn(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:sJ(n)}))}function sJ(e){return e.totalLines}function aJ(e,t,n){let r=mn(e.tokens,t.tokens);if(r.size<6||!cJ(r))return null;let i=Xr(e.tokens,t.tokens);if(i<n)return null;let o=ue(r,"component:"),s=ue(r,"prop:"),a=ue(r,"event:"),c=ue(r,"directive:"),l=ue(r,"slot:"),u=ue(r,"id:"),d=lJ({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:ct(it(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(it(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function cJ(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return ei([{name:"component",count:t},{name:"behavior",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{behavior:3},reason:"shared Vue template structure"}]).pass}function lJ(e){return Zr({genericWords:dJ,primitiveGroups:[{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"},{values:e.sharedDirectives,reasonPrefix:"shared directives",bucket:"generic"},{values:e.sharedSlots,reasonPrefix:"shared slots",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedIdentifiers,label:"shared identifier",fallbackBucket:"generic"}],recommendation:uJ})}function uJ(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific Vue primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var dJ=new Set(["actions","app","button","card","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function Ui(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=rn(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Vn(l,d=>d.tokens);return Gn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,p)=>pJ(d,p,n,r),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.fileB.localeCompare(p.fileB)})}function pJ(e,t,n,r){let i=mn(e.tokens,t.tokens);if(i.size<r||!gJ(i))return null;let o=Hu(e.tokens,t.tokens);if(o<n)return null;let s=ue(i,"composable:"),a=ue(i,"store:"),c=ue(i,"reactivity:"),l=ue(i,"lifecycle:"),u=ue(i,"request:"),d=ue(i,"function:"),p=ue(i,"function-verb:"),m=ue(i,"template-binding:"),f=ue(i,"template-event:"),g=mJ({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:p,sharedBindings:m,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:p,sharedBindings:m,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ct(it(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(it(t.tokens,e.tokens)).slice(0,25),reason:hJ({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:p,sharedBindings:m}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function mJ(e){return Zr({genericWords:yJ,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:fJ})}function fJ(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function gJ(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return ei([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function hJ(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var yJ=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function Ba(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return rn(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>bJ(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,p)=>p.totalLines-d.totalLines||d.file.localeCompare(p.file)).slice(0,s)}function bJ(e,t){let n=Wu(e,SJ(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=vJ(e.file),a=xJ(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:RJ(a,s),reasons:r,loc:c}}function SJ(e){return[{axis:"total",value:t=>t.totalLines+t.delegatedComposableLines,qualifies:(t,n)=>n>=e.minTotalLines,reason:(t,n)=>t.delegatedComposableLines>0?`${n} total line(s) (${t.totalLines} component + ${t.delegatedComposableLines} delegated composable line(s) across ${t.delegatedComposablePaths.length} file(s))`:`${n} total component line(s)`,dominantEligible:!1},{axis:"template",value:t=>t.templateLines,qualifies:(t,n)=>n>=e.minTemplateLines,reason:(t,n)=>`${n} template line(s)`},{axis:"script",value:t=>t.scriptLines-t.externalScriptLines,qualifies:t=>t.scriptLines>=e.minScriptLines,reason:t=>`${t.scriptLines} script line(s)`},{axis:"style",value:t=>t.styleLines,qualifies:(t,n)=>n>=e.minStyleLines,reason:(t,n)=>`${n} style line(s)`},{axis:"external-script",value:t=>t.externalScriptLines,qualifies:(t,n)=>n>=e.minScriptLines},{axis:"custom-block",value:t=>t.customBlockLines,qualifies:()=>!1}]}function vJ(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>CJ.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function xJ(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function RJ(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var CJ=new Set(["landing","page","pages","route","routes","view","views"]);function Ug(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ge(e,i),c=LJ(a,o,s);if(c.length===0)return[];let l=wJ(c);return l.length<2?[]:TJ(PJ(l,n,r),r)}function wJ(e){let t=kJ(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 kJ(e){let{nodeFreq:t,tailFreq:n}=IJ(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 IJ(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 PJ(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=EJ(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 EJ(e,t,n){if(!DJ(e.filtered,t.filtered))return null;let{distance:r,ops:i}=FJ(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:NJ(e.original,t.original),commonSuffix:AJ(e.original,t.original)}}function DJ(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function TJ(e,t){let n=[];for(let r of e)if(n.some(o=>Ak(r.chainA,o.chainA)&&Ak(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function LJ(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;_k(e,o,[o],new Set([o]),t,n,r,500)}return r}function _k(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),_k(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 FJ(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 NJ(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 AJ(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 Ak(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function fn(e){let t=_J(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=Pe(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?D(`candidate-pipeline:${e.profile.name}`,n,()=>({...MJ(e.profile?.metadata),...t})):n()}function _J(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function MJ(e){return typeof e=="function"?e():e??{}}function Vi(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new B(e);return fn({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>$J(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function $J(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=WJ(r,t),o=qJ(r,i);if(o.length<2)return null;let s=UJ(o,i);if(s.length===0)return null;let a=P(e.symbol),c=OJ(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:Q(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function OJ(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=jJ(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function jJ(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=BJ(e);return HJ.has(r)?`caller verb suggests orchestration: ${r}`:null}function BJ(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var HJ=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function WJ(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 qJ(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 UJ(e,t){return e.filter(n=>n.size>=3).map(n=>VJ(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function VJ(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(P),isolation:s}}import{posix as rs}from"path";import{spawnSync as GJ}from"child_process";import{createHash as zJ}from"crypto";import{existsSync as KJ}from"fs";import{dirname as Mk,join as JJ}from"path";import{fileURLToPath as YJ}from"url";var jk=ne("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),$k=Ie({kind:"consumer-file-usage",invalidation:pe("consumer-file-usage"),serialize:sY,deserialize:aY});function yr(e,t){return{forDefinitions(n,r){return QJ(e,t,n,r)}}}function br(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Uu(e,t,n){return Hk(e,t,n).partition}function QJ(e,t,n,r){let i=Bk(n.length),o=re()?Ye(e):null,s=o?XJ(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return D("consumer-evidence.product",()=>{let c=D("consumer-evidence.provenance",()=>ZJ(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=eY(n,c.sources);return D("consumer-evidence.classify",()=>{let d=tY(e,n,c.sources,u);for(let p of n){let m=d.get(p.symbolId)??rY();i.realFiles+=m.partition.realConsumers.length,i.reexportOnlyFiles+=m.partition.barrelConsumers,i.importOnlyFiles+=m.partition.importOnlyConsumers,l.set(p.symbolId,{definition:p,files:m.files,...m.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function XJ(e,t,n){let r=zJ("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function Bk(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function ZJ(e,t,n,r){let i=Bk(n.length),o=new Map;return Vg(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Vg(o,i,"semantic",Yr(e,n)),r.sourceFallback!==!1&&Vg(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function eY(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Vg(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function tY(e,t,n,r){let i=fY(e,t,n,r);return i||nY(e,t,n)}function nY(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,Hk(e,i,[...o.keys()],o))}return r}function Hk(e,t,n,r=new Map){let i=[],o=0,s=0,a=M(t.symbol),c=[];for(let l of n){let u;cY(e,l,t.relativePath,a)?(o++,u="reexport-only"):Gg(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function rY(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Gg(e,t,n){if(!n)return!1;let r=K(t);if(!r)return!1;let i=jk.get(e,t,()=>Wk(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function Wk(e,t,n){let r=cn(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return oY();let o=Ae(e,t,i),s=$k.read(e,t,o);if(s)return s;let a=iY(r.ast,n);return $k.write(e,t,o,a),a}function iY(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function oY(){return{importedLeaves:new Set,usedLeaves:new Set}}function sY(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function aY(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function cY(e,t,n,r){if(!r)return!1;let i=cn(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return qk(o,s,r)}function qk(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var lY="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",uY="SCIP_QUERY_NATIVE_KERNELS_BIN",dY="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",Ok=1e3,pY=5e3,mY=64*1024*1024,qu;function fY(e,t,n,r){let i=process.env[lY]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<xY())return r.nativeReason="below-threshold",null;let o=RY();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=gY(e,t,n),a=GJ(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:pY,maxBuffer:mY});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=yY(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function gY(e,t,n){let r=new Map,i=[];for(let a of t){let c=M(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,p])=>{let m=r.get(d)??new Set;return c&&m.add(c),r.set(d,m),{file:d,sources:[...p]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=K(a);if(l){let d=jk.get(e,a,()=>Wk(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=hY(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function hY(e,t,n){if(n.size===0)return[];let r=cn(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>qk(i,o,s))}function yY(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=bY(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function bY(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(SY)||!vY(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function SY(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function vY(e){return e==="real"||e==="reexport-only"||e==="import-only"}function xY(){let e=process.env[dY];if(!e)return Ok;let t=Number(e);return Number.isFinite(t)&&t>=0?t:Ok}function RY(){if(qu!==void 0)return qu;let e=process.env[uY],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return qu=[...e?[e]:[],...CY().map(r=>JJ(r,"target","release",t))].find(r=>KJ(r))??null,qu}function CY(){let e=new Set,t=Mk(YJ(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=Mk(t);return[...e]}var wY=20,kY=1,IY=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),PY=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),EY=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Yg(e,t={}){let n=Jg(t.limit,wY),r=Jg(t.minConsumers,kY),i=new B(e),o=i.fileDependencyGraph(t.scope),s=KY(q(e,{includeIgnored:!1})),a=QY(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?DY(e,i,t.target):TY(e,t.scope,t.scanLimit)).map(u=>LY(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(zY).slice(0,n)}function DY(e,t,n){let r=AY(e,n);if(r)return[Kk(r)];let i=te(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[_Y(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:P(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function TY(e,t,n){let r=q(e,{scope:t,includeIgnored:!1}),i=Jg(n,r.length);return r.slice(0,i).map(o=>Kk(o))}function LY(e,t,n,r,i,o,s){let a=r.definition?FY(e,t,r.definition,i.semantic):NY(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=kn(rs.dirname(l)),d=$Y(a),p=MY(u),m=Xg([...Uk(u),...d?Uk(d):[]]),f=OY(r.unit,u,d,a),g=jY(f,r.unit,u,d,a,o,s),h=UY(r.unit,c,d,a,u,g.whyNoSuggestedHome),y=VY(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:p,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:m,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:y,recommendation:GY(f,g.suggestedHome,c)}}function FY(e,t,n,r){let i=br(yr(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return Zk(i.get(n.symbolId)??[])}function NY(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return Zk(n)}function AY(e,t){let n=_r(t),r=q(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function _Y(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:P(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Kk(e){return{unit:{kind:"file",file:e,shortName:rs.basename(e)}}}function MY(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:Qg(i)})}return t}function Uk(e){return e==="."?[]:Jk(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Qg(e){return Xg(Jk(e).map(({marker:t})=>t))}function Jk(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=IY.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function $Y(e){if(e.length===0)return null;let t=e.map(r=>kn(rs.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function OY(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":Gk(n,"package")?"package-level-shared":Gk(n,"app")?"app-level-shared":zk(n,["feature","domain","module"])||zk(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function jY(e,t,n,r,i,o,s){let a=BY(e,r);if(a)return ti(a);let c=JY(t.file),l=HY(e,n,c,i,s);if(l)return l;let u=r;if(kn(n)===kn(u))return ti(`${n} is already the nearest common owner for its consumers.`);let d=WY(u,n,c,s);return d||qY(u,n,c,o,s)}function BY(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function HY(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?zg(o):ti("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=kn(rs.dirname(r[0])),s=Xk(t,n,o,i);return s?ti(s):zg(o)}return null}function WY(e,t,n,r){return ZY(e)?Yk(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function qY(e,t,n,r,i){if(e===".")return ti("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Yk(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:ti(`${o} does not exist in the indexed project.`)}function Yk(e,t,n,r,i){if(!Qk(e,n))return ti(i);let o=Xk(t,n,e,r);return o?ti(o):zg(e)}function zg(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function ti(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function UY(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function VY(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function GY(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function zY(e,t){return Vk(t)-Vk(e)||e.candidatePath.localeCompare(t.candidatePath)}function Vk(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function KY(e){let t=new Set(["."]);for(let n of e){let r=kn(rs.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=kn(rs.dirname(r))}return t}function JY(e){let t=Kg(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Qk(e,t){let n=kn(e),r=kn(t);return r==="."||n===r||n.startsWith(`${r}/`)}function YY(e,t,n){let r=Kg(e),i=Kg(t);return(Qk(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Xk(e,t,n,r){return kn(e)===kn(n)||!YY(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function QY(...e){let t=new Set(EY);for(let n of e)for(let r of n??[]){let i=XY(r);i&&t.add(i)}return t}function XY(e){let t=e.trim().toLowerCase();return t===""?null:t}function Gk(e,t){return Qg(e).includes(t)}function zk(e,t){let n=Qg(e);return t.some(r=>n.includes(r))}function ZY(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?PY.has(n):!1}function kn(e){let t=_r(e);return t===""?".":t}function Kg(e){let t=_r(e);return t==="."?[]:t.split("/").filter(Boolean)}function Jg(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Zk(e){return Xg([...e]).sort((t,n)=>t.localeCompare(n))}function Xg(e){return[...new Set(e)]}function Ha(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=te(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 d=[];for(let p of l)for(let m of eQ(e,p,i)){let f=`${m.file}|${m.shortName}`;if(m.symbolId!==null){if(a.has(m.symbolId))continue;a.add(m.symbolId)}else if(c.has(f))continue;c.add(f),s.push({symbol:m.symbol,shortName:m.shortName,file:m.file,depth:u}),m.symbolId!==null&&m.symbolMatch&&d.push(m.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function eQ(e,t,n){let r=qt(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 tQ(e,t,n)){if(i.has(l))continue;let u=se(e,l),d=u.length>0?On(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=aa(e,l.symbol);if(!u){let p=`${l.file}|${l.symbol}`;if(c.has(p))continue;c.add(p),a.push({symbolId:null,symbol:l.symbol,shortName:P(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!nQ(u))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:P(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function tQ(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
631
- FROM mentions m
632
- JOIN chunks c ON m.chunk_id = c.id
633
- JOIN documents consumer_d ON consumer_d.id = c.document_id
634
- WHERE m.symbol_id = ?
635
- AND m.role != 1
636
- AND c.document_id != ?
637
- ${e.pathExclusionsFor("consumer_d")}
638
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function nQ(e){if(e.symbol.startsWith("scip-clojure ")||K(e.relativePath)==="clojure")return!0;let t=$e(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function Wa(e,t,n={}){let r=vt(e,t);if(!r)return null;let i=rQ(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=iQ(e,i.relative_path),c=n.semantic===!1?new Map:Yr(e,a);for(let l of a){let u=oQ(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:P(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:sQ(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function rQ(e,t){return e.get(`SELECT id, relative_path FROM documents
639
- WHERE relative_path = ?
640
- ${e.pathExclusionsFor("documents")}
641
- LIMIT 1`,t)??null}function iQ(e,t){return new B(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function oQ(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
642
- FROM mentions m
643
- JOIN chunks c ON m.chunk_id = c.id
644
- JOIN documents consumer_d ON consumer_d.id = c.document_id
645
- WHERE m.symbol_id = ?
646
- AND m.role != 1
647
- 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 sQ(e){return e>10?"high":e>0?"medium":"low"}function Vu(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new B(e),a=aQ(e,n,r,o),c=new Zg;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(eI(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),p=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),y=new Set;for(let R of d)for(let b of h.get(R.symbolId)??[])p.has(b.symbol)||y.add(b.symbol);let x=[];for(let R of y){p.add(R);let b=tI(e,R);if(!b||e.isIgnored(b.relativePath)||tt(e,b.relativePath)||Oe(e,b.symbol,b.relativePath)||s.fileKind(b.relativePath)==="test"||s.hasSuppressionComment(b))continue;let v=lQ(e,b,c);v.removable?x.push(cQ(b,"cascade")):v.blockingFiles.length>0&&u.push({shortName:P(b.symbol),file:b.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(x.length===0)break;for(let R of x)c.add(R);l.push(eI(e,g,x,c)),d=x.map(R=>R.definition).filter(R=>R!==null)}let m=l.reduce((g,h)=>g+h.loc,0),f=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:m,blocked:u}}function aQ(e,t,n,r){let i=hr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(tt(e,s.relativePath)||Oe(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:tI(e,s.symbol)}));return o}function cQ(e,t){return{symbol:e.symbol,shortName:P(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function tI(e,t){let n=e.get(`SELECT d.relative_path
648
- FROM global_symbols gs
649
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
650
- JOIN documents d ON d.id = der.document_id
651
- WHERE gs.symbol = ?
652
- LIMIT 1`,t);return n?se(e,n.relative_path).find(r=>r.symbol===t)??null:null}function lQ(e,t,n){let r=Da(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 eI(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=se(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 Zg=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{createHash as J8}from"crypto";import{existsSync as Nh}from"fs";import{execFileSync as uQ}from"child_process";var sI=2e3,Gu=50,dQ=64,pQ=8,mQ=3,fQ=2160*60*60,gQ=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,hQ=3,yQ=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,bQ=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function SQ(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=eh(n.config.projectRoot);if(!i)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===i?o.value:(t.invalidate(n),t.get(n,()=>({head:i,value:r(n.config.projectRoot,i)})).value)}}function zu(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=eh(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!s||s.head!==o)&&t.invalidate(n);let a=t.get(n,()=>({head:o,values:new Map}));if(a.values.has(r))return a.values.get(r)??null;let c=i(n.config.projectRoot,o);return a.values.set(r,c),c}}var vQ=zu("git-commit-history");function Tt(e,t={}){let n=t.historyMode??"bounded";return{capability:r=>xQ(e,r),commitHistory:()=>qa(e,n),fileChurn:()=>wQ(e,n),changeAmplification:()=>kQ(e,n),trackedFiles:()=>PQ(e),fileAddRecords:()=>DQ(e,n),coChangePairs:(r={})=>MQ(e,r,n),coChangePairsForFiles:(r,i={})=>cI(e,r,i,n),directionalCoChangePairsForFiles:(r,i={})=>$Q(e,r,i,n)}}function qa(e,t="bounded"){return vQ(e,is(t),(n,r)=>RQ(n,r,t))}function xQ(e,t){let n=eh(e.config.projectRoot);return n?{slot:t,available:!0,head:n}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function eh(e){try{return Vt(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Vt(e,t){return uQ("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function RQ(e,t,n){let r;try{r=Vt(e,["log","--no-merges","--name-only",...Ku(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...ih(r,Gu)}}function CQ(e){return gQ.test(e.subject)}function wQ(e,t){let n=qa(e,t);if(!n)return null;let r=new Map;for(let i of n.commits){let o=CQ(i);for(let s of i.files){let a=r.get(s)??{changes:0,fixChanges:0,lastChangedAt:0};a.changes+=1,o&&(a.fixChanges+=1),i.timestamp>a.lastChangedAt&&(a.lastChangedAt=i.timestamp),r.set(s,a)}}return r}function kQ(e,t){let n=qa(e,t);if(!n||n.commits.length===0)return null;let r=n.commits.map(i=>i.files.length).filter(i=>i>0).sort((i,o)=>i-o);return r.length===0?null:{medianFilesPerCommit:nI(r,.5),p90FilesPerCommit:nI(r,.9),commitsAnalyzed:r.length}}function nI(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var IQ=SQ("git-tracked-files");function PQ(e){return IQ(e,t=>{try{let n=Vt(t,["ls-files"]);return new Set(n.split(`
653
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var EQ=zu("git-file-adds"),rI="__git__/file-adds",iI=Ie({kind:"git-file-adds",invalidation:pe("git-file-adds"),serialize:LQ,deserialize:FQ});function th(e){return Tt(e).fileAddRecords()}function DQ(e,t){let n=is(t);return EQ(e,n,(r,i)=>TQ(e,r,i,t))}function TQ(e,t,n,r){let i=iI.read(e,oI(r),n);if(i)return i;let o=NQ(t,r);return o&&iI.write(e,oI(r),n,o),o}function LQ(e){return JSON.stringify([...e.entries()])}function FQ(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function NQ(e,t){let n;try{n=Vt(e,["log","--no-merges","--find-renames","--name-status",...Ku(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
654
- `),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
655
- `)){let p=AQ(d);if(!p)continue;if(p.status==="R"&&p.from&&p.to){let f=i.get(p.to)??new Set([p.to]);i.set(p.from,f);continue}if(p.status!=="A"||!p.to)continue;let m={commitsAgo:o,addedAt:u};r.set(p.to,m);for(let f of i.get(p.to)??[])r.set(f,m)}}return r}function AQ(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var aI=zu("git-co-change-pairs"),_Q=zu("git-directional-co-change-pairs");function MQ(e,t,n){let r=`all\0${is(n)}\0${nh(t)}`,i=aI(e,r,()=>{let o=qa(e,n);return o?rh(o,t):null});return i&&[...i]}function cI(e,t,n,r){if(t.size===0)return[];let i=`files\0${is(r)}\0${lI(t)}\0${nh(n)}`,o=aI(e,i,()=>{let s=qa(e,r);return s?rh(s,n,t):null});return o&&[...o]}function $Q(e,t,n,r){if(t.size===0)return[];let i=n.maxFilesPerCommit??Gu;if(t.size>dQ)return cI(e,t,n,r);let o=`directional\0${is(r)}\0${lI(t)}\0${nh({...n,maxFilesPerCommit:i})}`,s=_Q(e,o,(a,c)=>{let l=OQ(a,c,t,i,r);return l?rh(l,n,t):null});return s&&[...s]}function nh(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??Gu;return`${t}\0${n}\0${r}`}function lI(e){return[...e].sort().join("\0")}function rh(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Gu}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let p=[...new Set(d.files)].sort();if(p.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let m=HQ(p),f=n===void 0||p.some(g=>n.has(g));for(let g of p)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<p.length;g++)for(let h=g+1;h<p.length;h++){if(n&&!n.has(p[g])&&!n.has(p[h]))continue;let y=`${p[g]}\0${p[h]}`,x=a.get(y)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};x.together+=1,m?x.broadTogether+=1:x.focusedTogether+=1,d.timestamp>x.lastTogetherAt&&(x.lastTogetherAt=d.timestamp),x.timestamps.push(d.timestamp),x.subjects.push(d.subject),a.set(y,x)}}let l=[],u=c-fQ;for(let[d,p]of a){let m=p.together;if(m<r)continue;let[f,g]=d.split("\0"),h=s.get(f)??m,y=s.get(g)??m,x=Math.max(m/h,m/y);if(x<i)continue;let R=p.broadTogether/m,b=p.timestamps.filter(v=>v>=u).length;l.push({fileA:f,fileB:g,together:m,confidence:x,changesA:h,changesB:y,focusedTogether:p.focusedTogether,broadTogether:p.broadTogether,broadCommitRatio:R,lastTogetherAt:p.lastTogetherAt,recentTogether:b,commitScope:qQ(p.broadTogether,m),recency:b>0?"recent":"stale",subjectContext:UQ(p.subjects)})}return l.sort((d,p)=>p.together-d.together||p.confidence-d.confidence||d.fileA.localeCompare(p.fileA)),l}function OQ(e,t,n,r,i){let o;try{o=jQ(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Vt(e,["log","--no-merges","--format=%H",...Ku(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(p=>p.hash)),c=s.split(`
656
- `).map(p=>p.trim()).filter(p=>p!==""&&a.has(p)),l=BQ(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Vt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=ih(u,r);return{head:t,...d,newestAnalyzedAt:l}}function jQ(e,t){return Vt(e,["log","--no-merges","--format=%H%x00%ct",...Ku(t)]).split(`
657
- `).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Ku(e){return e==="full"?[]:["-n",String(uI())]}function uI(){return qr(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??sI}function is(e){return e==="full"?"full":`bounded:${uI()}`}function oI(e){let t=is(e);return t===`bounded:${sI}`?rI:`${rI}:${t}`}function BQ(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Vt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=ih(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function ih(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
658
- `),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
659
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function HQ(e){return e.length>=pQ?!0:WQ(e).size>=mQ}function WQ(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function qQ(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function UQ(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<hQ&&r.push(i);for(let o of VQ(i))t.add(o);for(let o of i.match(yQ)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function VQ(e){let t=new Set,n=bQ.exec(e)?.[1]?.toLowerCase();return n&&t.add(GQ(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function GQ(e){return e==="feat"?"feature":e}import{existsSync as zQ}from"fs";import{join as KQ}from"path";function sh(e){return oh.test(e)}var oh=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|uv\.lock|poetry\.lock|Pipfile\.lock|bun\.lockb?|\.SRCINFO|CHANGELOG(?:\.[a-z]+)?|.*\.(?:map|tsbuildinfo))$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function Gi(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Tt(e,{historyMode:n.historyMode}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,p=ge(e),m=gI(e),f=lh(e,p,m),g=n.includeLinked===!0||l,h=[];for(let y of d){if(oh.test(y.fileA)||oh.test(y.fileB)||!dI(e,y.fileA)||!dI(e,y.fileB)||l&&!y.fileA.includes(t)&&!y.fileB.includes(t)||!l&&(fe(y.fileA)==="test"||fe(y.fileB)==="test"||XQ(y.fileA,y.fileB)||YQ(y.fileA,y.fileB)))continue;let x=f(y.fileA,y.fileB);if(!g&&x)continue;let R=ah(y.fileA,y.fileB),b=ch(y,R,x);if(h.push({...y,structurallyLinked:x,partnerClass:R.partnerClass,partnerClassReasons:R.reasons,...b?{declaredCouplingSuggestion:b}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function dI(e,t){return zQ(KQ(e.config.projectRoot,t))}function ah(e,t){let n=mI(e),r=mI(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=l5(n.tokens,r.tokens).filter(c=>!a5.has(c));return fI(e,t)||a.length>=2?(o(fI(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function ch(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!s5.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${u5(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function lh(e,t=ge(e),n=gI(e)){return(r,i)=>ZQ(t,n,r,i)}var JQ=/(?:^|\/)(?:locales|i18n)\//i;function pI(e){return JQ.test(e)}function YQ(e,t){return pI(e)&&pI(t)?!0:QQ(e,t)}function QQ(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function XQ(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 gI(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function ZQ(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var e5=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,t5=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,n5=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,r5=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,i5=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,o5=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,s5=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),a5=new Set(["src","lib","app","apps","packages","frontend","backend","examples","python","typescript","javascript","test","tests","spec","index","main","utils","util","types","type","config","docs","doc","package","requirements","ts","tsx","js","jsx","mjs","cjs","vue","py","md","mdx","json","yaml","yml","toml","txt"]);function mI(e){let t=e.replace(/\\/g,"/"),n=new Set;return e5.test(t)&&n.add("doc"),t5.test(t)&&n.add("config"),n5.test(t)&&n.add("schema"),r5.test(t)&&n.add("script"),i5.test(t)&&n.add("model"),o5.test(t)&&n.add("view"),fe(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:c5(t)}}function fI(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function c5(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function l5(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function u5(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as In}from"child_process";import{existsSync as d5,readFileSync as p5}from"fs";import{basename as hI}from"path";function Ju(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Ua="Unable to compute git diff.";function os(e,t={}){let n=t.plan??zn(e,t);return n.note?m5(n.note,n.changedFileLines):n.changedFiles.length===0?f5(n.changedFileLines):Qu(n.changedFiles,[Yu(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function zn(e,t={}){let{base:n="HEAD"}=t;try{let r=g5(e.config.projectRoot,n),i=C5(e,r),o=w5(e,h5(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:S5(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Ua}}}function Yu(e,t,n,r=[]){let i=new B(e),o=new Set(n),s=Ju(r),a=[],c=new Map,l=t.flatMap(b=>i.definitionsForFile(b)).filter(O5),u=l.filter(b=>I5(b,s)),d=E5(e,l,u,s),p=L5([...u,...d.definitions]).sort((b,v)=>b.relativePath.localeCompare(v.relativePath)||b.startLine-v.startLine),m=p.map(b=>b.symbolId),f=_5(e,m),g=M5(e,m,n),h=p.filter(b=>(f.get(b.symbolId)??0)===0),y=vI(()=>Yr(e,h)),x=h.filter(b=>(y.get(b.symbolId)?.size??0)===0),R=vI(()=>Ta(e,x));for(let b of p)A5(e,b,o,a,c,y.get(b.symbolId)??new Set,R.get(b.symbolId)??new Set,f.get(b.symbolId)??0,g.get(b.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([b,v])=>({file:b,symbols:[...v].sort()})),attributionNotes:d.notes}}function Qu(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols),i=t.flatMap(s=>s.attributionNotes??[]);for(let s of t)for(let a of s.consumerEntries){let c=n.get(a.file);c||(c=new Set,n.set(a.file,c));for(let l of a.symbols)c.add(l)}let o=$5(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function m5(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function f5(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function g5(e,t){let n=In("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=In("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=In("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return[...new Set([n,r,i].flatMap(o=>o.split(`
660
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function h5(e,t){let n=In("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=In("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return RI([...SI(n),...SI(r)])}function ph(e,t,n){try{return In("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function Va(e,t,n=[]){let r=y5(e,t,n);return i=>(r.has(i)||r.set(i,ph(e,t,i)),r.get(i)??null)}function Ga(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function y5(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
661
- `).join(""),s=In("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return b5(s,r)}catch{for(let o of r)i.set(o,ph(e,t,o));return i}}function b5(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function S5(e,t,n){if(n.length===0)return[];let r=new Map,i=new Set;for(let s of x5(e,t))n.includes(s.to)&&(r.set(s.to,s),i.add(s.from));let o=v5(e,t);if(o.length===0)return[...r.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(r.has(s)||!d5(`${e}/${s}`))continue;let a=o.filter(u=>!i.has(u)).filter(u=>hI(u)===hI(s));if(a.length===0)continue;let c=p5(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:R5(ph(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(r.set(s,l),i.add(l.from))}return[...r.values()].sort((s,a)=>s.to.localeCompare(a.to))}function v5(e,t){let n=In("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=In("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return[...new Set([...bI(n),...bI(r)])]}function x5(e,t){let n=In("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=In("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return[...n.split(`
662
- `),...r.split(`
663
- `)].map(i=>i.trim()).filter(i=>i.startsWith("R")).map(i=>i.split(" ")).filter(i=>i.length>=3).map(([i,o,s])=>({from:o,to:s,similarity:Number(i.slice(1))/100}))}function R5(e,t){let n=new Set(yI(e)),r=new Set(yI(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function yI(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function bI(e){return e.split(`
664
- `).map(t=>t.trim()).filter(t=>t.length>0)}function C5(e,t){let n=xI(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function w5(e,t){let n=xI(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return RI(r)}function xI(e){let t=e.all(`SELECT relative_path FROM documents
665
- ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function SI(e){let t=[],n=null;for(let r of e.split(`
666
- `)){if(r.startsWith("+++ ")){n=k5(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function k5(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function RI(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function I5(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>mh(e.startLine,e.endLine,r.startLine,r.endLine))}function P5(e,t,n){let r=new Map,i=[],o=CI(e),s=F5(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>mh(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=N5(l,a);if(u){let d=c.find(p=>p.startLine>=u.startLine&&p.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(uh(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(p=>p.startLine<=a.startLine).sort((p,m)=>m.startLine-p.startLine||p.endLine-m.endLine)[0];if(d){r.set(d.symbolId,d),i.push(uh(a,"nearest-preceding"));continue}}i.push(uh(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function E5(e,t,n,r){let i=CI(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(p=>mh(p.startLine,p.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...D5(e,c))}return P5(t,o,s)}function D5(e,t){let n=oe(e,t);return n?n.rootNode.namedChildren.filter(T5).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function T5(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function L5(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function CI(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function F5(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function N5(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function uh(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function mh(e,t,n,r){return e<=r&&n<=t}function A5(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!j5(t,l))return;let u=P(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)dh(e,n,i,d,u);for(let d of o)dh(e,n,i,d,u);for(let d of s)dh(e,n,i,d,u)}function vI(e){try{return e()}catch(t){return console.error(`warning: diff-impact enrichment scan failed, continuing without it: ${t instanceof Error?t.message:t}`),new Map}}function _5(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
667
- FROM mentions m
668
- JOIN chunks c ON m.chunk_id = c.id
669
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
670
- AND m.role != 1
671
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function M5(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
672
- FROM mentions m
673
- JOIN chunks c ON m.chunk_id = c.id
674
- JOIN documents ref_d ON c.document_id = ref_d.id
675
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
676
- AND m.role != 1
677
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
678
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function dh(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 $5(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function O5(e){return!(Hr(e.symbol)||e.parentTypeName!==null&&!_e(e.symbol))}function j5(e,t){return _e(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function wI(e){let[t,n]=Xu(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??B5(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??H5(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=Xu(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="drift"){let[o,s]=Xu(n,":"),[a,c]=Xu(s,":");return i({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function B5(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function H5(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function Xu(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as J5,readFileSync as DI}from"fs";function td(e,t){let n=W5(e,t)??q5(e,t)??U5(e,t)??V5(e,t);return G5(e,n,t)}function W5(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=fh(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(fh(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function fh(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function q5(e,t){if(!Zu(e[t]??""))return null;let n=t;for(;n>0&&Zu(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Zu(e[r]??"");)r+=1;return{start:n,end:r}}function Zu(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function U5(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(ed(o)!==null)break;if(gh(o)!==null)return null;n-=1}if(n<0)return null;let r=ed(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=ed(o);if(s!==null){if(s<=r)break;i+=1;continue}if(gh(o)!==null)break;i+=1}return{start:n,end:i}}function ed(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function V5(e,t){let n=e[t]??"";if(II(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&kI(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&kI(e[i]??"");)i+=1;return{start:r,end:i}}function kI(e){return gh(e)===null}function gh(e){return e.trim().length===0?"blank":II(e)?"heading":fh(e)?"fence":Zu(e)?"table":ed(e)!==null?"list":null}function II(e){return/^#{1,6}\s+/.test(e.trim())}function G5(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
679
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function zi(e,t){return t.filter(n=>e.includes(n))}import{readdirSync as z5}from"fs";import{join as PI}from"path";function za(e,t){let n=nd(e),r=nd(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function K5(e){return nd(e).replace(/\/\*\*?$/,"")}function EI(e,t){let n=nd(t),r=K5(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=z5(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;za(n,d)&&o.push(d),i&&u.isDirectory()&&s(PI(a,u.name),d)}};return s(PI(e,r),r),o.sort()}function nd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var Y5=/<!--\s*scip-query:\s*snapshot\s*-->/i;function rd(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>za(i,t)))return!0;let r=_(e,t);return r.length>0&&Y5.test(r)}var Sr={classifyCitation:X5,citationContexts:Z5,citationKindLabel:tX,citationRemediation:nX,referenceTargets:rX,hasLineAnchoredCitation:Q5};function Q5(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function X5(e){let t=e.join(`
680
- `).toLowerCase(),n=[],r=zi(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=zi(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=zi(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function Z5(e,t,n){let r;try{r=DI(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(eX),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(td(r,s))}return o}function eX(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function tX(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function nX(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function rX(e,t,n){let r=Ju(n),i=new Set;for(let o of t)iX(e,o,r.get(o)??[])&&i.add(o);return i}function iX(e,t,n){if(!oX.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!J5(r))return!0;if(n.length===0)return!1;let i=DI(r,"utf-8").split(/\r?\n/),o=sX(i);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((i[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var oX=/\.(?:[cm]?[jt]sx?)$/i;function sX(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&aX(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function aX(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as LI,readFileSync as yh,statSync as cX}from"fs";import{join as ss}from"path";var TI=Ie({kind:"doc-path-evidence",invalidation:pe("doc-path-evidence"),serialize:RX,deserialize:CX}),Ka=/\.(?:md|mdx|rst|txt)$/i;function lX(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var uX=3,dX=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function bh(e,t={}){let{doc:n,limit:r=20,minCoupling:i=uX,includeSnapshotExcluded:o=!1}=t,s=gX(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!NI(e,c)||n!==void 0&&!LI(ss(e.config.projectRoot,c)))continue;let l=rd(e,c);if(l&&!o)continue;let{value:u,estimated:d}=pX(e,c,s.changeTimes.get(c)),p=mX(e,c),m=new Map,{resolved:f,broken:g,citations:h}=bX(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),y=new Map(h.map(R=>[R.file,R]));for(let R of f){if(R===c||Ka.test(R))continue;let b=(s.changeTimes.get(R)??[]).filter(w=>w>u).length;if(b===0)continue;let v=y.get(R);m.set(R,{file:R,evidence:"reference",coChanges:0,changesSinceDocUpdate:b,...hh("reference",p,v?.contexts),citationContexts:v?.contexts,citedLines:v?.lineReferences})}for(let[R,b]of s.coupling.get(c)??[]){if(b<i||!s.tracked.has(R))continue;let v=(s.changeTimes.get(R)??[]).filter(I=>I>u).length;if(v===0)continue;let w=m.get(R);w?(w.evidence="both",w.coChanges=b,Object.assign(w,hh("both",p,w.citationContexts))):m.set(R,{file:R,evidence:"co-change",coChanges:b,changesSinceDocUpdate:v,...hh("co-change",p)})}if(m.size===0&&g.length===0)continue;let x=[...m.values()].sort((R,b)=>b.changesSinceDocUpdate-R.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:x.reduce((R,b)=>R+b.changesSinceDocUpdate,0)+g.length*10,subjects:x.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function pX(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(cX(ss(e.config.projectRoot,t)).mtimeMs/1e3),estimated:!0}}catch{return{value:0,estimated:!1}}}function mX(e,t){let n;try{n=yh(ss(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
681
- ${n}`.toLowerCase(),i=zi(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=zi(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function hh(e,t,n=[]){let r=e==="co-change"||n.length===0?null:Sr.classifyCitation(n);return{actionTier:fX(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function fX(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function gX(e,t){let n=Tt(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(p=>Ka.test(p)),d=l.filter(p=>!Ka.test(p));for(let p of l){a.add(p);let m=o.get(p)??[];m.push(c.timestamp),o.set(p,m)}for(let p of u){let m=s.get(p);m||(m=new Map,s.set(p,m));for(let f of d)m.set(f,(m.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>Ka.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:AI(i)}}function FI(e,t){if(t.size===0)return[];let n=re(),r=0,i=0,o=0,s=0,a=0,c=0;return D("doc-reference.docs-citing-files",()=>{let l=Tt(e).trackedFiles()??new Set;r=l.size;let u=AI(l),d=hX(t,u),p=[];for(let m of l){if(!NI(e,m))continue;n&&(i+=1);let f;try{f=yh(ss(e.config.projectRoot,m),"utf-8")}catch{n&&(o+=1);continue}if(!vX(f,d)){n&&(s+=1);continue}let g=_I(e,m,f);if(!g)continue;n&&(a+=1);let h=yX(g.candidates,t,d,l,u);if(h.size===0)continue;let y=[...new Set([...h.values()].flatMap(v=>[...v]))],x=SX(g.contextsByCandidate,y),R=[...h].map(([v,w])=>({file:v,contexts:id([...w].flatMap(I=>x.get(I)??[])).slice(0,3),lineReferences:od([...w].flatMap(I=>g.lineReferencesByCandidate.get(I)??[]))})).filter(v=>v.contexts.length>0),b=[...h.keys()];if(b.length>0){n&&(c+=1);let v=b.sort();p.push({doc:m,cited:v,citations:R,citedClaims:id(R.flatMap(w=>w.contexts)).slice(0,3)})}}return p},()=>({targets:t.size,trackedFiles:r,livingDocs:i,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function NI(e,t){return Ka.test(t)&&!lX(t)&&LI(ss(e.config.projectRoot,t))}function AI(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 hX(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function yX(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(t.has(s))a=s;else if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function bX(e,t,n,r,i){let o=new Set,s=new Set,a=_I(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,p=new Map,m=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let x=d.get(f)??[];x.push(...h),d.set(f,id(x).slice(0,3))}let y=u.get(g);y&&y.length>0&&p.set(f,od([...p.get(f)??[],...y]))};for(let f of c){if(n.has(f)){o.add(f),m(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),m(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:p.get(f)}))}}function SX(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function _I(e,t,n){let r=n;if(r===void 0)try{r=yh(ss(e.config.projectRoot,t),"utf-8")}catch{return null}let i=Ae(e,t,r),o=TI.read(e,t,i);if(o)return o;let s=xX(r);return TI.write(e,t,i,s),s}function vX(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function xX(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(dX)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,od([...i.get(c)??[],l]));let u=td(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,id(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function RX(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function CX(e){try{let t=JSON.parse(e);if(!ee(t))return null;let n=X(t.candidates),r=kX(t.contextsByCandidate),i=wX(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function wX(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],od(r)])}return t}function kX(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=X(n[1]);if(!r)return null;t.push([n[0],r])}return t}function id(e){let t=[];for(let n of new Set(e))t.some(r=>IX(r,n))||t.push(n);return t}function od(e){return[...new Set(e)].sort((t,n)=>t-n)}function IX(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as PX}from"crypto";var $I=3;function Ki(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=$I,limit:o,scanLimit:s}=t,a=th(e),c=BI(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>HI(e,u,a,i)).filter(u=>u!==null),l=jI(c);return o?l.slice(0,o):l}function Sh(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=$I,scanLimit:s}=n,a=th(e),c=BI(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>HI(e,u,a,o)).filter(u=>u!==null),l=c.find(u=>u.symbol===t);return l?c.filter(u=>u.symbol!==l.symbol&&u.normalizedBody===l.normalizedBody&&u.file!==l.file).sort(WI).map(({normalizedBody:u,...d})=>d):[]}function OI(e){let t=Kn(e);return kt(t).replace(/\s+/g,"")}function jI(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=DX(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(WI).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=MI(i)-MI(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function BI(e,t){let n=Ue(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>Q(r)<=t.maxLoc);return n.sort((r,i)=>Q(i)-Q(r)||r.relativePath.localeCompare(i.relativePath)),Pe(n,t.scanLimit)}function HI(e,t,n,r){let i=vr(e,t);if(!i||EX(i)<r)return null;let o=vh(e,t);return o?{symbol:t.symbol,shortName:P(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:Q(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function vh(e,t){let n=vr(e,t);return n&&OI(n)||null}function vr(e,t){let n=Qe(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
682
- `)}function Kn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function EX(e){return Kn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function DX(e){return PX("sha256").update(e).digest("hex").slice(0,16)}function WI(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function MI(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var TX=new Set(dn());function xh(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=as(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function as(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=NX(e,{scope:n,scanLimit:i});return VI(o,{minSimilarity:r,isDelegatePair:t3(e)}).filter(s=>!s.members.some(a=>iv(e,a.file,a.startLine,"twin")))}function VI(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!XI(l.leaf)&&!UX(l.leaf)&&fe(l.file)!=="test"&&!et(l.symbol)&&!zI(l.symbol)&&!KI(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=D("twin-drift.group-by-leaf",()=>LX(i),()=>({records:i.length})),a=D("twin-drift.cluster-leaf-names",()=>GI([...o.keys()]),()=>({leaves:o.size}));return D("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=FX(u,o,s);if(d.length<2||new Set(d.map(x=>x.file)).size<2)continue;let p=null,m=!1,f=!1,g=new Set;for(let x=0;x<d.length;x+=1)for(let R=x+1;R<d.length;R+=1){let b=d[x],v=d[R];if(b.file===v.file||!KX(b,v)||r?.(b,v,d)||r?.(v,b,d))continue;if(m=!0,g.add(b.symbol),g.add(v.symbol),b.normalizedBody===v.normalizedBody){f=!0;continue}let w=BX(b.tokens,v.tokens);(!p||w>p.similarity)&&(p={a:b,b:v,similarity:w})}if(!m)continue;let h=d.filter(x=>g.has(x.symbol)).sort((x,R)=>x.file.localeCompare(R.file)||x.startLine-R.startLine).map(jX);if(!p){l.push({leaf:UI(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let y=p.similarity>=n?"divergent":"homonym";l.push({leaf:UI(u),relationship:y,maxDivergence:Math.round((1-p.similarity)*1e3)/1e3,members:h,...y==="divergent"?{firstDivergentTokens:HX(p.a.tokens,p.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function LX(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function FX(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function NX(e,t){let n=D("twin-drift.load-definitions",()=>Ue(e,{scope:t.scope}).filter(o=>AX(o)&&!e.isIgnored(o.relativePath)).filter(o=>!_o(o.relativePath)));D("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=Pe(n,t.scanLimit),i=D("twin-drift.select-candidates",()=>_X(r),()=>({scanned:r.length}));return D("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=MX(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function AX(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&TX.has(e.kind):!0:!1}function _X(e){let t=e.filter(o=>o.leaf&&!XI(o.leaf)&&!et(o.symbol)&&!zI(o.symbol)&&!KI(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=GI([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>fe(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function MX(e,t){if(!t.leaf)return null;let n=vr(e,t);if(!n||!_e(t.symbol)&&!$X(n,t.leaf))return null;let r=kt(Kn(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(OX)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:P(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:Q(t),normalizedBody:i,tokens:o,isThinForwarder:YI(r)}}function $X(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var OX=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function jX(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function BX(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function HX(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function GI(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)WX(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function WX(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||qX(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:JX(e.toLowerCase(),t.toLowerCase(),2)}function qX(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function UX(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||VX.has(e.toLowerCase())}var VX=new Set(["main","row"]),GX=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function zI(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var zX=new Set(["default","new","reset"]);function KI(e,t){return e.startsWith("rust-analyzer ")&&zX.has(t.toLowerCase())}function KX(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=qI(e);return[...qI(t)].some(r=>n.has(r))}function qI(e){let t=e.leaf.toLowerCase();return new Set(`${e.file}/${e.shortName}`.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>2&&n!==t&&!GX.has(n)))}function JX(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function JI(e){return YI(kt(Kn(e)))}function YI(e){let t=e.trim();if(!t||YX.test(t))return!1;let n=ZX(t);return n.length===0||n.length>2?!1:XX(n[n.length-1])}var YX=/\b(?:if|else|for|while|switch|try|catch|do)\b/,QX=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function XX(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return QX.test(t)}function ZX(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var e3=3;function t3(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=QI(e,n,r,i,e3,new Set);return t.set(o,a),a}}function QI(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(jr(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(Ce(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>_t(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>_t(l,c.file))&&QI(e,c,n,r,i-1,o))return!0;return!1}function XI(e){return e.startsWith("<")&&e.endsWith(">")}function UI(e){return[...e].sort()[0]}import{readFileSync as n3,readdirSync as r3}from"fs";import{basename as i3,join as Rh}from"path";function o3(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function Ch(e,t){let n=s3(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=p3(e.config.projectRoot,t.mustEqual),i=o3(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function eP(e,t){return t.map(n=>Ch(e,n))}function tP(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>za(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function nP(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function s3(e,t,n){return n.type==="markdown-list"?d3(e,t,n.marker):a3(e,t,n)}function a3(e,t,n){if(!_(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=K(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=oe(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?c3(o,n.identifier):u3(o,n.identifier);return s===null?{ok:!1,reason:`no ${n.type==="object-literal-keys"?"object literal":"string array"} named "${n.identifier}" found in ${t}`}:{ok:!0,keys:s}}function rP(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function c3(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=rP(n);if(i?.type==="object")return l3(i)}return null}function l3(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(iP(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function u3(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=rP(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(iP(s.text));return[...o].sort()}return null}function iP(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function d3(e,t,n){let r=_(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=oP(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:sP(i)}}function oP(e,t){let n=J(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function sP(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function p3(e,t){switch(t.type){case"top-level-dirs":return ZI(Rh(e,t.path));case"file-glob":return[...new Set(EI(e,t.pattern).map(n=>i3(n)))].sort();case"registered-commands":return m3(e);case"builtin-skills":return ZI(Rh(e,"skills"))}}function ZI(e){let t;try{t=r3(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function m3(e){let t;try{t=n3(Rh(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=oP(t,"COMMAND REFERENCE");return n?sP(n):[]}import{existsSync as x8,readFileSync as R8,writeFileSync as C8}from"fs";import{isAbsolute as w8,join as k8}from"path";var je={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import Ja from"path";var aP={analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),domain:new Set([]),instrumentation:new Set([]),"language-parsers":new Set(["core","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(["core","domain","language-parsers","queries","reindex","resolution","semantic","source","storage","symbols","tla"]),semantic:new Set(["core","domain","language-parsers","reindex","resolution","runtime","source","storage","symbols"]),source:new Set(["core","domain","resolution","storage"]),storage:new Set(["analysis","domain","queries","source"]),symbols:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage"]),tla:new Set(["core","domain","queries","source","storage","symbols"])};function Ji(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 wh(e,t){if(e===t)return"ok";let n=cs(e),r=cs(t);return n&&r?!ls(n)||!ls(r)?null:f3(n,r)?"ok":"violation":g3(e,t)}function cP(e,t){let n=cs(Ji(e)),r=cs(Ji(t));return!!n&&!!r&&ls(n)&&ls(r)}function lP(e,t){let n=cs(e),r=cs(t);return!!n&&!!r&&(!ls(n)||!ls(r))}function cs(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function f3(e,t){return t==="instrumentation"||t==="domain"?!0:e==="domain"?!1:aP[e]?.has(t)??!1}function ls(e){return Object.hasOwn(aP,e)}function g3(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 Yi(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new B(e).fileDependencyGraph(n),l=x3([...h3(e,c,{scope:n,semantic:o}),...b3(c),...s?v3(c,r):[]]);return i<=0||l.results.length<=i?l:{...l,results:l.results.slice(0,i),totalResults:l.results.length}}function h3(e,t,n){let r=w3(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(xr(a))continue;let l=r.get(a)??new Set;for(let u of c)xr(u)||l.has(u)||y3(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&P3(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function y3(e,t,n,r){return L3(e,t,n)||F3(e,t,n)||D3(n)||A3(e,t,n)||N3(n)?!0:r.semantic&&T3(e,t,n)}function b3(e){let t=[],n=E3(e);for(let[r,i]of e){if(xr(r))continue;let o=Ji(r);for(let s of i){if(xr(s))continue;let a=Ji(s);if(o===a)continue;let c=wh(o,a),l=c===null&&lP(o,a),u=c?"explicit":l?"unknown-layer":"inferred";if((l?"violation":c??n.get(`${o}->${a}`))==="violation"){let p=u==="explicit"?"direct":"signal";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}/`,actionTier:p,policyBasis:u,evidenceReasons:[`dependency edge exists from ${r} to ${s}`,S3(u,o,a)],recommendation:u==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":u==="unknown-layer"?"Add a layer policy entry before treating this as a boundary violation.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function S3(e,t,n){return e==="explicit"?`explicit layer policy rejects ${t}/ -> ${n}/`:e==="unknown-layer"?`source layer policy has no entry for ${t}/ -> ${n}/`:`rare cross-layer edge ${t}/ -> ${n}/ is inferred as a violation`}function v3(e,t){let n=[];for(let[r,i]of R3(e)){let o=i.filter(a=>!xr(a));if(o.length<t)continue;let s=C3(e,o);for(let a of o)for(let c of e.get(a)??[])xr(c)||(s.get(c)??0)===1&&Ja.dirname(c)!==r&&Ja.dirname(c)!==Ja.dirname(r)&&(cP(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function x3(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 R3(e){let t=new Map;for(let n of e.keys()){let r=Ja.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function C3(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])xr(i)||n.set(i,(n.get(i)??0)+1);return n}function w3(e,t){let n=new Map;return k3(e,n,t),n}function k3(e,t,n){for(let r of I3(e,n))uP(e,t,r.from_file,r.to_file)}function I3(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
683
- FROM mentions m
684
- JOIN chunks c ON m.chunk_id = c.id
685
- JOIN documents d1 ON c.document_id = d1.id
686
- JOIN global_symbols gs ON m.symbol_id = gs.id
687
- JOIN (
688
- SELECT m2.symbol_id, c2.document_id
689
- FROM mentions m2
690
- JOIN chunks c2 ON m2.chunk_id = c2.id
691
- WHERE m2.role = 1
692
- GROUP BY m2.symbol_id
693
- ) sym_def ON sym_def.symbol_id = gs.id
694
- JOIN documents d2 ON sym_def.document_id = d2.id
695
- WHERE d1.id != d2.id
696
- AND m.role != 1
697
- ${e.pathExclusionsFor("d1","d2")}
698
- ${n}`,...r)}function P3(e,t,n={}){new B(e).scanSourceReferences({paths:n.paths??q(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||uP(e,t,i.sourceFile,i.target.relativePath))})}function uP(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 E3(e){let t=new Map;for(let[r,i]of e){if(xr(r))continue;let o=Ji(r);for(let s of i){if(xr(s))continue;let a=Ji(s);if(o===a||wh(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 D3(e){return e.includes("types")||e.endsWith(".d.ts")}function T3(e,t,n){let r=Pa(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function L3(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function F3(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function N3(e){return e.endsWith(".vue")}function A3(e,t,n){let r=Ce(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 xr(e){let t=fe(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||_3(Ja.basename(e)))}function _3(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as dP,extname as pP}from"path";function sd(e,t,n,r,i,o){let s=new Set;$3(e,t,n,r)&&s.add(i);for(let a of o)a.value&&M3(s,a.label,a.value);return[...s].slice(0,6)}function M3(e,t,n){let r=O3(n);t.endsWith("name")&&j3(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=B3.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function $3(e,t,n,r){if(n<=0)return!1;let i=Qe(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(Gs(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function O3(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function j3(e){return e.some(t=>H3.has(t))&&e.some(t=>W3.has(t))}var B3=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),H3=new Set(["can","has","is","should"]),W3=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Qi(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new B(e);return fn({candidates:()=>Y3(e,s,n,r),orderCandidates:Mu,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>q3(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function q3(e,t,n){let r=J3(n);if(r.size!==1||!Lm(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=U3(e,t,i),s=G3(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:P(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:Q(t),forwardsTo:i.symbol,forwardsToShort:P(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:V3(a,o,s)}}function U3(e,t,n){return sd(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:P(t.symbol)},{label:"callee name",value:P(n.symbol)},{label:"passthrough module",value:dP(t.relativePath,pP(t.relativePath))},{label:"callee module",value:dP(n.file,pP(n.file))}])}function V3(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(K3);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function G3(e,t){return Ya(e,t)?Ti(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Oe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function Ya(e,t){let n=Qe(e,t.relativePath);if(n.length===0)return!1;let r=M(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
699
- `),o=J(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:z3(n,r)}function z3(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${J(t)}\\b`);return e.some(r=>n.test(r))}function K3(e){return e.includes("public surface")}function J3(e){let t=e.some(r=>ve(r.symbol))?e.filter(r=>ve(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function Y3(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!ta(e,i))}function Xi(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 B(e),u=l.scopedDefinitions(n),d=c8(l,n),p={high:0,medium:1,low:2};return fn({candidates:()=>Q3(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(m,f)=>Q(f)-Q(m)||m.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:m=>{let f=Z3(m),g=X3(e,l,m,f,{semantic:c}),h=m.filter(y=>{let x=ad(e,y,g,f);return x.realConsumers.length<=1&&!x.transitivelyReachable&&mP(y,x.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:n8(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(m,f)=>{if(f.singletonBackedClassIds.has(m.symbolId))return null;let g=ad(e,m,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!mP(g.definition,g.realConsumers.length,d))return null;let h=e8(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(m,f)=>p[m.confidence]-p[f.confidence]||f.loc-m.loc||m.file.localeCompare(f.file)||m.startLine-f.startLine,limit:o})}function Q3(e,t,n,r){return n.filter(i=>i.isTypeLike&&Q(i)>=r.minLoc).filter(i=>Q(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>fe(i.relativePath)!=="test").filter(i=>!Oe(e,i.symbol,i.relativePath)).filter(i=>!l8(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function kh(e,t,n,r){return br(yr(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function X3(e,t,n,r,i){let o=kh(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=ad(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&Ih(l.relativePath))}),a=i.semantic&&s.length>0?gr(o,kh(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>ad(e,l,a,r).realConsumers.length<=1);return gr(a,kh(e,t,c,{semantic:!1,sourceFallback:!0}))}function Z3(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=M(n.symbol);i&&r.set(i,n)}return t}function ad(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}=Uu(e,t,o),l=u8(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function e8(e,t){let n=gP(e,t.definition.relativePath,t.definition.startLine),r=Ih(t.definition.relativePath)?!0:d8(e,t.definition),{confidence:i,reason:o}=p8(t.realConsumers.length,n,r),s=t8(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:P(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:Q(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function t8(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function n8(e,t,n,r,i){let o=i8(e,r8(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=br(yr(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)s8(e,l,a)&&c.add(u);return c}function r8(e){let t=new Map;for(let n of e){let r=M(n.symbol);r&&t.set(fP(n.relativePath,r),n)}return t}function i8(e,t,n){let r=[];for(let i of n){let o=o8(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function o8(e,t,n){if(gP(e,n.relativePath,n.startLine)!=="class")return null;let r=M(n.symbol);if(!r)return null;let i=a8(e,n.relativePath,r);return i?t.get(fP(n.relativePath,i))??null:null}function s8(e,t,n){let r=M(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Gg(e,o,r))}function fP(e,t){return`${e}\0${t}`}function a8(e,t,n){let r=_(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 c8(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function l8(e){let t=Je(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 Ih(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 mP(e,t,n){return!(Ih(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function u8(e,t,n,r){let i=Nm(e,t.relativePath),o=M(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let p of d)if(p!==t.relativePath&&!e.isIgnored(p))return!0}for(let p of i.get(l)??[])a.push(p)}return!1}function gP(e,t,n){let r=_(e,t);if(!r)return"other";let i=r.split(`
700
- `),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 d8(e,t){let n=_(e,t.relativePath);if(!n)return!1;let r=M(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
701
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function p8(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 us,extname as cd}from"path";function Zi(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new B(e),a=b8(s.fileDependencyGraph(n));return fn({candidates:()=>g8(e,s,n,r),orderCandidates:Mu,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:m8(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>f8(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function m8(e,t,n,r){let i=yr(e,t),o=br(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&D("wrapper.semantic-candidates",()=>{s=n.filter(p=>Ph(e,t,p,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:br(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:gr(o,a),l=new Map(n.map(p=>[p.symbolId,p])),u=new Map;for(let p of n){let m=Ph(e,t,p,c);if(m.length>1||(u.set(p.symbolId,p),m.length!==1))continue;let f=m[0],g=hP(e,p.symbolId,f);if(!g)continue;let h=yP(t,e,f,p.symbol,g);h?.isFunctionLike&&l.has(h.symbolId)&&u.set(h.symbolId,l.get(h.symbolId))}let d=[...u.values()];return d.length===0?c:gr(c,br(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function f8(e,t,n,r){let i=Ph(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=hP(e,n.symbolId,o);if(!s)return null;let a=yP(t,e,o,n.symbol,s);if(a&&No(a.symbol))return null;let{fanIn:c,source:l}=h8(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=v8(e,n,o,a);return{symbol:n.symbol,shortName:P(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:Q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?P(a.symbol):us(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function g8(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!ta(e,i))}function Ph(e,t,n,r){let i=us(n.relativePath,cd(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>us(s,cd(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Uu(e,n,o).realConsumers}function hP(e,t,n){return e.get(`SELECT c.start_line, c.end_line
702
- FROM mentions m
703
- JOIN chunks c ON m.chunk_id = c.id
704
- JOIN documents d ON c.document_id = d.id
705
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
706
- LIMIT 1`,t,n)}function yP(e,t,n,r,i){let o=e.definitionsForFile(n),s=y8(t,n,r,i.start_line,i.end_line);return On(o,s)}function h8(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:S8(t,n),source:"file"}}function y8(e,t,n,r,i){let o=M(n);if(!o)return r;let s=pr(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 b8(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 S8(e,t){let n=e.get(t)??0;if(n>0)return n;let r=us(t,cd(t)),i=0;for(let[o,s]of e)o!==t&&us(o,cd(o))===r&&s>i&&(i=s);return i}function v8(e,t,n,r){return sd(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:P(t.symbol)},{label:"caller name",value:r?.symbol?P(r.symbol):us(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var I8=25e3,P8=2500,E8=2500;function D8(e){let t=Ut(e);return t.symbols>=I8||t.documents>=P8?E8:void 0}var T8=".scipquery-baseline.json";function ld(e,t){return t&&w8(t)?t:k8(e.config.projectRoot,t??T8)}function Eh(e,t={}){let{scope:n}=t,r=D8(e),i=[],o=hr(e,{scope:n,...je.dead,scanLimit:r});for(let s of o.symbols)tt(e,s.relativePath)||Oe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of ji(e,{scope:n,...je.isolated,scanLimit:r}))tt(e,s.relativePath)||Oe(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of $a(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${L8(s.path)}`);for(let s of Bi(e,{scope:n,...je.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Ki(e,{scope:n,...je.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of Vi(e,{scope:n,...je.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Zi(e,{scope:n,...je.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Qi(e,{scope:n,...je.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Xi(e,{scope:n,...je.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Yi(e,{scope:n,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function L8(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 Dh(e,t={}){let n=Eh(e,{scope:t.scope}),r=ld(e,t.path);return C8(r,JSON.stringify({version:1,findings:n},null,2)+`
707
- `),{path:r,findingCount:n.length}}function Qa(e,t={}){let n=ld(e,t.path);if(!x8(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(R8(n,"utf-8")),i=new Set(r.findings??[]),o=Eh(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))}}var F8=5;function Xa(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??zn(e,{base:n}),d={available:u.note!==Ua,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let p=new B(e),m=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(I=>[I.to,I.from])),g=t.baseContentAt??Va(e.config.projectRoot,n,Ga(u)),h=O8(p,m,f,g);if(h.length===0)return d;let y=h.slice(0,s);h.length>s&&(d.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let x=p.calleeMap(y,{semantic:l}),R=y.map(I=>({def:I,callees:Bu((x.get(I.symbolId)??[]).map(C=>C.symbol))})),b=ns(e),v,w=()=>(v??=b.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),v);for(let{def:I,callees:C}of R){let k=P(I.symbol);if(C.size<i){d.skipped.push({helperShortName:k,helperFile:I.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let T=w(),F=$8(C,T);if(F===0){d.skipped.push({helperShortName:k,helperFile:I.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let V=j8(e,I.symbolId);if(V.length===0){d.skipped.push({helperShortName:k,helperFile:I.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let ie=N8({candidateIndex:T,changed:m,helperCallees:C,helperFile:I.relativePath,helperSymbol:I.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:V});ie.length!==0&&(ie.sort((W,be)=>bP(be.migrationScope)-bP(W.migrationScope)||be.containment-W.containment||be.siteCoverage-W.siteCoverage||W.file.localeCompare(be.file)),d.findings.push({helperSymbol:I.symbol,helperShortName:k,helperFile:I.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:F,migratedFiles:V.sort(),leftovers:ie.slice(0,F8)}))}return d.findings.sort((I,C)=>(C.leftovers[0]?.containment??0)-(I.leftovers[0]?.containment??0)||I.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function N8(e){let t=[],n=A8(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=ck(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=_8(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:P(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(P).sort()})}return t}function bP(e){return e==="same-scope"?2:e==="unknown"?1:0}function A8(e,t,n){let r=new Set([...Th(t),...Lh(M(e))]);for(let i of n)for(let o of Th(i))r.add(o);return r}function _8(e,t,n){let r=new Set([...Th(n),...Lh(M(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var M8=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function Th(e){return Lh(e.replace(/\.[^.]+$/,""))}function Lh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!M8.has(t))}function $8(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function O8(e,t,n,r){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(i=>{if(!t.has(i.relativePath))return!1;let o=n.get(i.relativePath)??i.relativePath,s=r(o);return s===null||!new RegExp(`\\b${J(i.leaf)}\\b`).test(s)})}function j8(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
708
- FROM mentions m
709
- JOIN chunks c ON m.chunk_id = c.id
710
- JOIN documents ref_d ON c.document_id = ref_d.id
711
- WHERE m.symbol_id = ?
712
- AND m.role != 1
713
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function Za(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new B(e);return fn({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>B8(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=ce(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=pr(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||H8(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:P(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function B8(e){let t=K(e);return t==="typescript"||t==="tsx"||t==="javascript"}function H8(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as W8,mkdirSync as q8,readdirSync as U8,readFileSync as V8,writeFileSync as G8}from"fs";import{createHash as z8}from"crypto";import{join as ud}from"path";var ec=ud(".scipquery","suppressions");function SP(e){return ud(e,ec)}function K8(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${z8("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function vP(e,t,n=new Date){if(!t.reason||t.reason.trim()==="")throw new Error("suppression requires a non-empty reason");if(!t.id&&!t.check)throw new Error("suppression requires an id or a check");let r=SP(e);q8(r,{recursive:!0});let i=ud(r,K8(t)),o={...t,createdAt:t.createdAt??n.toISOString()};return G8(i,JSON.stringify(o,null,2)+`
714
- `),{path:i}}function xP(e){let t=SP(e);if(!W8(t))return{suppressions:[],warnings:[]};let n=[],r=[];for(let i of U8(t).sort()){if(!i.endsWith(".json"))continue;let o=ud(t,i),s;try{s=JSON.parse(V8(o,"utf-8"))}catch{r.push(`${ec}/${i}: malformed JSON \u2014 ignored`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){r.push(`${ec}/${i}: not a suppression object \u2014 ignored`);continue}let a=s;if(typeof a.reason!="string"||a.reason.trim()===""){r.push(`${ec}/${i}: missing reason \u2014 ignored`);continue}if(!a.id&&!a.check){r.push(`${ec}/${i}: needs an id or a check \u2014 ignored`);continue}n.push(a)}return{suppressions:n,warnings:r}}var pd=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","doc-reference","unused-params","new-dead","baseline"];function eo(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",p=new Set(t.skip??[]),m=zn(e,{base:n}),f=os(e,{base:n,plan:m}),g=f.changedFiles,h=new Set(g),y=new Set(m.changedFileLines),x=new Set([...h,...y]),R=Va(e.config.projectRoot,n,Ga(m,g)),b=R4(e.config.projectRoot,n,m,R),v={base:n,changedFiles:g,changedSymbols:f.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:f.attributionNotes,rootCauseGroups:[],note:f.summary.note};if(g.length===0)return v;let w=(I,C)=>{if(p.has(I)){v.skipped.push({check:I,reason:"skipped via --skip"});return}let k=v.findings.length,T=v.skipped.length,F=v.checksRun.length;D(`diff-gate.check.${I}`,C,()=>({check:I,changedFiles:g.length,changedSymbols:f.changedSymbols.length,findingsAdded:v.findings.length-k,skippedAdded:v.skipped.length-T,checksRunAdded:v.checksRun.length-F}))};return w("echo",()=>Z8(e,f.changedSymbols,h,b,o,a,l,u,v)),w("incomplete-migration",()=>o4(e,n,m,s,l,u,R,v)),w("co-change-partner",()=>s4(e,x,r,i,d,v)),w("twin-partner",()=>a4(e,f.changedSymbols,h,l,v)),w("coverage-contract",()=>c4(e,x,v)),w("doc-reference",()=>m4(e,h,y,m.changedRanges,m.renamedFiles,v)),w("unused-params",()=>y4(e,g,v)),w("new-dead",()=>b4(e,f.changedSymbols,b,v)),c&&w("baseline",()=>w4(e,v)),Q8(v,[...e.config.suppressions??[],...xP(e.config.projectRoot).suppressions]),v.rootCauseGroups=Y8(v.findings),v}function tc(e){return e.checksRun.length===0&&e.note===Ua}function nc(e){return e.filter(t=>!t.advisory)}function Y8(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=PP(i.severity,n.severity),i.actionTier=EP(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||dd(r.severity)-dd(n.severity)||n.groupKey.localeCompare(r.groupKey))}function PP(e,t){return dd(t)>dd(e)?t:e}function dd(e){return e==="error"?2:e==="warning"?1:0}function EP(e,t){return e?t&&RP(t)>RP(e)?t:e:t}function RP(e){return e==="direct"?2:e==="signal"?1:0}function Q8(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>X8(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function X8(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function Rr(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function Z8(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!_e(l.symbol)||r(l))continue;let u=Sh(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(y=>!n.has(y.file)).slice(0,5).map(y=>({otherFile:y.file,otherShort:y.shortName,otherSymbol:y.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${y.loc} LOC)`]}));if(u.length>0){let y=ot("echo",l.symbol,l.file),x=ot("echo",l.symbol,l.file,...u.map(b=>`${b.otherSymbol}|${b.otherFile}`).sort()),R=u[0];Rr(c,{id:y,legacySuppressionIds:x===y?void 0:[x],groupKey:y,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(b=>b.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${R.otherSymbol}`,message:wP(l,u),why:kP(l,u),remediation:IP("direct",l.shortName,R.otherShort)});continue}let d=ts(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),p=[];for(let y of d){let x=y.fileA===l.file?y.fileB:y.fileA,R=y.fileA===l.file?y.shortNameB:y.shortNameA,b=y.fileA===l.file?y.symbolB:y.symbolA;n.has(x)||p.push({otherFile:x,otherShort:R,otherSymbol:b,similarity:y.similarity,similarityBasis:y.similarityBasis??"callees",sharedEvidence:y.sharedCallees})}if(p.length===0)continue;let m=p[0],f=ot("echo",l.symbol,l.file,...p.map(y=>`${y.otherSymbol}|${y.otherFile}`).sort()),g=ot("echo",l.symbol,l.file),h=e4(l,p);Rr(c,{id:g,legacySuppressionIds:f===g?void 0:[f],groupKey:g,actionTier:h,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(p.map(y=>y.otherFile))].sort(),message:wP(l,p),why:kP(l,p),remediation:IP(h,l.shortName,m.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function e4(e,t){return t.some(r=>t4(e.symbol,r))?"direct":"signal"}function t4(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=M(e),r=M(t.otherSymbol);return!n||!r?!1:n===r?!0:i4(t.sharedEvidence)?!1:n4(n,r)}function n4(e,t){let n=CP(e),r=CP(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function CP(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var r4=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function i4(e){return e.length>=3&&e.every(t=>r4.has(t.toLowerCase()))}function wP(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function kP(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function IP(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function o4(e,t,n,r,i,o,s,a){let c=Xa(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(y=>`${y.shortName} (${y.file}, ${Math.round(y.containment*100)}% helper / ${Math.round(y.siteCoverage*100)}% site, ${y.migrationScope})`).join(", "),d=l.leftovers.map(y=>`${y.shortName}: ${y.migrationScope} (${y.migrationScopeReasons[0]})`).join("; "),p=[...l.migratedFiles,...l.leftovers.map(y=>y.file)],m=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(y=>Math.min(y.containment,y.siteCoverage))),f=l.leftovers.some(y=>y.migrationScope==="possible-subtype"),g=ot("incomplete-migration",l.helperSymbol,l.helperFile,p.join("|")),h=ot("incomplete-migration",l.helperSymbol,l.helperFile);Rr(a,{id:h,legacySuppressionIds:g===h?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:m,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:p,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:f?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function s4(e,t,n,r,i,o){let s=Tt(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let p=u?l.fileA:l.fileB,m=u?l.fileB:l.fileA,f=u?l.changesA:l.changesB,g=f>0?l.together/f:0;if(g<r||sh(m)||sh(p)||!Nh(`${e.config.projectRoot}/${m}`))continue;let h=`${p}|${m}`;if(a.has(h))continue;a.add(h);let y=ot("co-change-partner",p,m,String(l.together)),x=ot("co-change-partner",p,m),R=ah(p,m),b=ch({fileA:p,fileB:m,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},R,(c??=lh(e))(p,m)),v=[p,m].sort().join("|");o.findings.push({id:x,legacySuppressionIds:y===x?void 0:[y],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${v}`,confidence:g,file:p,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:v,partnerClass:R.partnerClass,partnerClassReasons:R.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...b?{declaredCouplingSuggestion:b}:{},message:`${p} changed, but ${m} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${p} is in this diff and ${m} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${l4(l)}.`,`Subject context: ${u4(l.subjectContext)}.`,...d4(l),`Partner class: ${R.partnerClass} (${R.reasons.join("; ")}).`],remediation:b?`Update ${m} alongside this change, declare the coupling "${b.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function a4(e,t,n,r,i){i.checksRun.push("twin-partner");let o=as(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!_e(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(f=>f.symbol!==c.symbol&&!n.has(f.file));if(u.length===0)continue;let d=[c.symbol,...u.map(f=>f.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let p=u[0],m=ot("twin-partner",c.symbol,c.file,p.symbol);Rr(i,{id:m,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(f=>f.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${p.shortName} (${p.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${p.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${p.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${p.file} alongside this change, consolidate ${c.shortName}/${p.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function c4(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!tP(i,t))continue;let o=Ch(e,i);if(o.status==="ok")continue;let s=ot("coverage-contract",i.name,i.file);Rr(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:nP(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function l4(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${p4(e.lastTogetherAt)}`}function u4(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function d4(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function p4(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Fh=3;function m4(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=Sr.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of FI(e,s))n.has(l.doc)||rd(e,l.doc)||c.push(f4(e,l,a));for(let l of g4(c))Rr(o,l)}function f4(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:Sr.citationContexts(e,t.doc,t.cited),i=Sr.classifyCitation(r),o=Sr.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!Nh(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=ot("doc-reference",t.doc,t.cited.join("|")),u=ot("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${Sr.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:Sr.citationRemediation(i.citationKind,t.doc)}}function g4(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=Fh?n.push(...i):n.push(h4(r,i));return n}function h4(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Fh).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>PP(u,d.severity),"info"),a=n.reduce((u,d)=>EP(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:ot("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${Fh}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function y4(e,t,n){n.checksRun.push("unused-params");for(let r of Za(e,{files:t,limit:50})){let i=ot("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=ot("unused-params",r.symbol,r.file);Rr(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function b4(e,t,n,r){r.checksRun.push("new-dead");let i=new B(e),o=Ro(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||tt(e,a.file)||Oe(e,a.symbol,a.file)||x4(a.symbol))continue;let c=ot("new-dead",a.symbol,a.file),l=s&&S4(o,a.file)&&v4(e,a.symbol);Rr(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function S4(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function v4(e,t){let n=M(t);return n?(mr(e).get(n)?.length??0)>1:!1}function x4(e){if($e(e)!=="type")return!1;let t=M(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function R4(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??Va(e,t,Ga(n));return s=>{let a=i.get(s.file)??s.file,c=M(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&C4(l,c)}}function C4(e,t){return new RegExp(`\\b${J(t)}\\b`).test(e)}function w4(e,t){if(!Nh(ld(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=Qa(e);for(let r of n.newFindings){let i=wI(r),o=ot("baseline",r);Rr(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function ot(e,...t){return`SQ${J8("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as k4,relative as I4,resolve as P4}from"path";var E4=new Set(dn());function Ah(e,t){return`tests/generated/twin-ab/${DP(e)}-vs-${DP(t)}.test.ts`}function DP(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function _h(e,t,n,r){let i=TP(e,t);if(!i.ok)return i;let o=TP(e,n);if(!o.ok)return o;let s=i.symbol.paramCount===null||o.symbol.paramCount===null?null:i.symbol.paramCount===o.symbol.paramCount,a=T4(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function TP(e,t){let r=Ht(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?E4.has(o):ve(r.symbol)))return{ok:!1,reason:`${t} resolves to ${P(r.symbol)}${o!==null?` with SCIP kind ${Un(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Ya(e,r))return{ok:!1,reason:`${t} (${P(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=ur(dr(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:M(r.symbol)||P(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?D4(c):null}}}function D4(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function LP(e,t,n){let r=k4(t),i=P4(e,n),s=I4(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function T4(e,t,n,r,i){let o=LP(n,r,e.file),s=LP(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
715
- * Generated by 'scip-query twin-ab'. scip-integrity-audit drill 5
716
- * ("cross-examine same-concept twins"): where one concept is computed in
717
- * more than one place, feed both the same input and require the same
718
- * answer. Disagreement between twins means at least one is wrong \u2014
719
- * determine which before consolidating.
720
- *
721
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
722
- * ${e.signature??"(signature unavailable)"}
723
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
724
- * ${t.signature??"(signature unavailable)"}
725
- * ${a}
726
- *
727
- * Fill in the TODO input table below with inputs both twins should agree
728
- * on, then run this file with vitest.
729
- */
730
- import { describe, expect, it } from 'vitest';
731
- import { ${e.shortName} as twinA } from '${o}';
732
- import { ${t.shortName} as twinB } from '${s}';
733
-
734
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
735
- const inputs: any[][] = [
736
- // [/* arg1, arg2, ... */],
737
- ];
738
-
739
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
740
- // the real twins have fixed, non-rest parameter lists, and TS rejects
741
- // spreading a generic args array into those (TS2556) even when the array
742
- // itself is 'any'; casting the callee's signature, not the args, satisfies
743
- // the checker without weakening the twins' real exported types elsewhere.
744
- const callA = twinA as (...callArgs: any[]) => any;
745
- const callB = twinB as (...callArgs: any[]) => any;
746
-
747
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
748
- it.each(inputs)('agrees on input %#', (...args) => {
749
- expect(callA(...args)).toEqual(callB(...args));
750
- });
751
- });
752
- `}var FP={caller:3,"entry-surface":2,rooted:1},L4=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,F4=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,N4=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,A4=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,_4=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function Mh(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new B(e),a=Pe(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let m of a){let f=$4(e,m);f&&c.push(f)}if(c.length===0)return[];let l=H4(e,c,a),u=c.filter(m=>!l.has(m.def.symbol));if(u.length===0)return[];let d=yr(e,s).forDefinitions(u.map(m=>m.def),{semantic:o}),p=[];for(let m of u){let g=d.get(m.def.symbolId)?.realConsumers.length??0,h=M4(e,m.def,g);h&&p.push({symbol:m.def.symbol,shortName:P(m.def.symbol),file:m.def.relativePath,startLine:m.def.startLine,endLine:m.def.endLine,loc:Q(m.def),stubKind:m.stubKind,reachability:h,callerFanIn:g,stubText:m.stubText})}return p.sort((m,f)=>FP[f.reachability]-FP[m.reachability]||f.callerFanIn-m.callerFanIn||m.file.localeCompare(f.file)||m.startLine-f.startLine),r?p.slice(0,r):p}function M4(e,t,n){return n>0?"caller":Oe(e,t.symbol,t.relativePath)?"rooted":tt(e,t.relativePath)?"entry-surface":null}function $4(e,t){let n=vr(e,t);if(!n)return null;let r=Kn(n),i=r.trim();if(i==="")return!B4(n)||!Ya(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Ks(r),s=kt(r),a=O4(o,s);if(a.length!==1)return null;let c=a[0];return j4(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:A4.test(r)&&N4.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function O4(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function j4(e){let t=F4.exec(e.trim());return t?L4.test(t[1]??""):!1}function B4(e){return _4.test(e.trimEnd())}function H4(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=q4(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(p=>u.has(p))&&r.add(a.def.symbol)}return r}var W4=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function q4(e,t){let n=new Map;for(let r of q(e,{includeIgnored:!1})){let i=_(e,r);if(i)for(let o of i.matchAll(W4)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var U4=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,V4=/^(?:is|has)(?:[A-Z].*)?$/,G4=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,$h=/\breturn\b/g,z4=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,K4=/\.(?:addIssue|push)\s*\(/;function Oh(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new B(e),s=Pe(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=Y4(e,c);l&&a.push({symbol:c.symbol,shortName:P(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:Q(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function J4(e){return U4.test(e)?"imperative":V4.test(e)?"predicate":null}function Y4(e,t){let n=J4(t.leaf);if(!n||Xo(e,t))return null;let r=vr(e,t);if(!r||!z4.test(r))return null;let i=ce(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(JI(r)){let s=Z4(e,t);return!s||_P(s.body,AP(s.snippet))||NP(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=Kn(r);return _P(o,AP(r))||NP(o)?null:{nameKind:n,resolvedVia:"direct"}}var Q4=new Set(["if","for","while","switch","catch","function"]);function NP(e){let t=Ks(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!Q4.has(n[1]))return!0;return!1}function AP(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function _P(e,t){let n=Ks(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||G4.test(n)||K4.test(n))return!0;let r=X4(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function X4(e){let t=[];$h.lastIndex=0;let n;for(;n=$h.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),$h.lastIndex=o}return t}function Z4(e,t){let n=pn(e,t,{callableOnly:!0,limit:3}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Ht(e,r[0]).match;if(!o)return null;let s=se(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=vr(e,s);return a?{body:Kn(a),snippet:a,shortName:P(s.symbol)}:null}var e6=60;function Hh(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=e6}=t,s=Pe(Pt(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>fe(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=_(e,u);if(!d)continue;let p=sv(d),m=r6(d);for(let g of a6(p,m))m.add(g);let f=t6(p);for(let g of f){if(g.skip){c.push(f6(e,u,g,o));continue}if(g.kind==="describe")continue;let h=$P(d,g.argsStart),y=p.slice(g.argsStart,g.callEnd),x=d.slice(g.argsStart,g.callEnd);OP(y,m)||a.push({file:u,startLine:rc(d,g.callStart),endLine:rc(d,g.callEnd),title:h,severity:/\bawait\b/.test(y)?"low":"high"});let R=d6(y,x);R&&l.push({file:u,startLine:rc(d,g.callStart),endLine:rc(d,g.callEnd),title:h,echoedValue:R})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var jh=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function t6(e){let t=[];jh.lastIndex=0;let n;for(;n=jh.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=ic(e,a);jh.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function ic(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function rc(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
753
- `&&(n+=1);return n}function $P(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var n6=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),MP=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function r6(e){let t=new Set(["expect","assert"]);MP.lastIndex=0;let n;for(;n=MP.exec(e);){let[,r,i,o,s]=n;if(!(!s||!n6.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function OP(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var i6=/\bfunction\s+(\w+)\s*\(/g,o6=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,s6=60;function a6(e,t){let n=new Set;for(let r of[i6,o6]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=ic(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>s6)continue;let l=c6(e,c),u=e.slice(c+1,l);OP(u,t)&&n.add(o)}}return n}function c6(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var l6=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,Bh=/\bexpect\s*\(/g,u6=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,jP=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function d6(e,t){let n=p6(e,t,l6);if(n.length===0)return null;let r=m6(e,t);for(let i of r)if(n.includes(i))return i;return null}function p6(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=ic(e,o),a=t.slice(o+1,s).trim();jP.test(a)&&r.push(a),n.lastIndex=s+1}return r}function m6(e,t){let n=[];Bh.lastIndex=0;let r;for(;r=Bh.exec(e);){let i=r.index+r[0].length-1,o=ic(e,i),s=e.slice(o+1),a=u6.exec(s);if(Bh.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=ic(e,c),u=t.slice(c+1,l).trim();jP.test(u)&&n.push(u)}return n}function f6(e,t,n,r){let i=_(e,t),o=$P(i,n.argsStart),s=rc(i,n.callStart),a=g6(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function g6(e,t,n){let r=n+1;try{let i=Vt(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var h6=.7,BP=.62,HP=.45;function Wh(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Tt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=k6(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=y6(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>I6(d,s,n)).filter(d=>d!==null);l.sort((d,p)=>(d.kind===p.kind?0:d.kind==="echo"?-1:1)||p.similarity-d.similarity||d.echoFile.localeCompare(p.echoFile)||d.echoSymbol.localeCompare(p.echoSymbol)||d.domain.localeCompare(p.domain));let u=l.slice(0,r).map(P6);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:E6(u)}}function y6(e,t){let n=T6(t.limit),r=[...b6(e,{scope:t.scope,minSimilarity:t.minSimilarity??h6,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=xl(e,{scope:t.scope});return i.react&&r.push(...S6(e,{scope:t.scope,minSimilarity:t.minSimilarity??BP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...v6(e,{scope:t.scope,minSimilarity:t.minSimilarity??HP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...C6(e,{scope:t.scope,minSimilarity:t.minSimilarity??BP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...w6(e,{scope:t.scope,minSimilarity:t.minSimilarity??HP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function b6(e,t){return Bi(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!et(n.symbolA)&&!et(n.symbolB)).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function S6(e,t){return fd(e,t,{query:Hi,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function fd(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:L6(...n.evidenceBuckets(r)),sharedCallees:[]}))}function v6(e,t){return fd(e,t,{query:Wi,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:R6,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}var x6=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function R6(e){return e.sharedHooks.some(t=>!x6.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function C6(e,t){return fd(e,t,{query:qi,domain:"vue-component",basis:"vue-template",symbolA:n=>md(n.fileA),symbolB:n=>md(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function w6(e,t){return fd(e,t,{query:Ui,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>md(n.fileA),symbolB:n=>md(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function k6(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function I6(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function P6(e){let t=WP(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function WP(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function E6(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??WP(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:D6(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function D6(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function T6(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function L6(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function md(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var F6=me("suppression-inventory",{clearGroups:["whole-project"]});function gd(e){return F6.get(e,()=>N6(e))}function N6(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of Pt(e)){let o=_(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Gs(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=A6(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function A6(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as _6}from"fs";import{join as M6}from"path";function oc(e,t,n={}){let r=te(e,t);if(!r)return null;let i=new B(e),o=$6(e,r),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:P(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:j6(e,r.symbolId),fanOut:B6(c,r.relativePath)}}function $6(e,t){let n=oe(e,t.relativePath);if(n){let r=GP(n.rootNode,t.startLine,t.endLine);if(r)return{branches:H6(r),estimateBasis:"ast"}}return{branches:KP(VP(e,t.relativePath,t.startLine,t.endLine),UP(e,t.relativePath)),estimateBasis:"regex-fallback"}}function qP(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=oe(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});W6(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,O6(e,l))}return n}function O6(e,t){return{branches:KP(VP(e,t.relativePath,t.startLine,t.endLine),UP(e,t.relativePath)),estimateBasis:"regex-fallback"}}function UP(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function VP(e,t,n,r){try{return _6(M6(e.config.projectRoot,t),"utf-8").split(`
754
- `).slice(n,r+1).join(`
755
- `)}catch{return""}}function j6(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
756
- FROM mentions m
757
- JOIN chunks c ON m.chunk_id = c.id
758
- JOIN (
759
- SELECT m2.symbol_id, c2.document_id
760
- FROM mentions m2
761
- JOIN chunks c2 ON m2.chunk_id = c2.id
762
- WHERE m2.role = 1
763
- GROUP BY m2.symbol_id
764
- ) sym_def ON sym_def.symbol_id = m.symbol_id
765
- WHERE m.symbol_id = ?
766
- AND m.role != 1
767
- AND sym_def.document_id != c.document_id`,t)?.c??0}function B6(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function H6(e){let t=0;return qh(e,n=>{t+=zP(n)}),t}function W6(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);qh(e,i=>{let o=zP(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function qh(e,t){t(e);for(let n of e.namedChildren)qh(n,t)}function GP(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=GP(r,t,n);if(i)return i}return e}var q6=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function zP(e){return q6.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?U6(e.text):0}function U6(e){return(e.match(/&&|\|\|/g)??[]).length}function KP(e,t){let n=kt(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 sc(e,t,n={}){let r=te(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=qn(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?P(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=V6(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:P(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:P(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)":P(c.symbol),file:c.file}))}}function V6(e,t,n,r){let i=Qo(pn(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Qo(qt(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Qo(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function ds(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=te(e,t);return o?r==="backward"?G6(e,o,i,{semantic:n.semantic!==!1}):z6(e,o,{semantic:n.semantic!==!1}):null}function G6(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=pn(e,l,{semantic:r.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:P(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let p=aa(e,d.symbol);p&&!e.isIgnored(p.relativePath)&&c.push(p)}}s=c}return{symbol:t.symbol,shortName:P(t.symbol),direction:"backward",connectedSymbols:i}}function z6(e,t,n){let r=new Set,i=[],o=new B(e);for(let s of qn(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??On(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=aa(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:P(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:P(t.symbol),direction:"forward",connectedSymbols:i}}function Uh(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!J6(t),a=s?La(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Qr(e,t,{semantic:o}):null,l=s?oc(e,t,{semantic:o}):null,u=s?sc(e,t,{semantic:o}):null,d=s?ds(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,p=s?ds(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,m=s?Ha(e,t,{maxDepth:r,scope:n.scope}):[],f=Wa(e,t,{semantic:o}),g=Fa(e,t),h=Na(e,t),y=Aa(e,t),x=_a(e,t),R={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||p!==null||m.length>0,file:f!==null||g.length>0||h.length>0,module:y.files.length>0||y.symbols.length>0||x.length>0},b=[];!R.symbol&&!R.file&&!R.module&&b.push("No symbol, file, or module matched target.");let v=f?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:R,history:K6(e,v),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:p,affected:m,changeSurface:f,deps:g,rdeps:h,system:y,surface:x,warnings:b}}function K6(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Tt(e).fileChurn();if(!r)return n;let i=Gi(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,subjectContext:o.subjectContext})),suppressionsInFile:gd(e).byFile.get(t)??0}}function J6(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Y6=new Set(dn());function ac(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new B(e);return fn({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:Q6,profile:{name:"complexity-hotspots"},prepare:a=>{let c=Z6(e,a),l=t?.semantic!==!1,u=l?St(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?gr(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:eZ(e,a,c),branchEstimates:qP(e,a)}},evaluate:(a,c)=>X6(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function Q6(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&Y6.has(e.kind):!0}function X6(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;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=new Set,a=new Set;for(let p of o){let m=`${p.symbol}|${p.file}`;s.add(m),p.file!==e.relativePath&&a.add(m)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:P(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function Z6(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
768
- FROM documents
769
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function eZ(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((ce(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}function tZ(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[Be(c.check,c.findingId),c])),s=new Set(t.map(c=>Be(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=Be(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=Be(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function Vh(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,p)=>d.firstSeen-p.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/JP):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var JP=864e5,nZ=50,rZ=.1,iZ=10;function oZ(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function YP(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[Be(s.check,s.findingId),s])),i=t.map(s=>r.get(Be(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/JP)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function QP(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=oZ(e,r,nZ);i.length<iZ||i.filter(a=>a.outcome==="resolved").length/i.length>=rZ||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function Be(e,t){return`${e}\0${t}`}function ps(e){return jS(e).map(t=>({check:t.check,findingId:t.findingId,firstSeen:t.firstSeen,lastSeen:t.lastSeen,timesShown:t.timesShown,outcome:t.outcome}))}function XP(e,t,n,r=Date.now(),i=new Set){let o=ps(e),s=tZ(o,t,n,r,i);return BS(e,s),s}function Cr(e){return e.scoreCount??e.count}function tE(e){let t=lZ(e),{breakdown:n,pressure:r}=uZ(e),i=eE(n,"risk"),o=eE(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Cr(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Cr(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Cr(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null,coverageContractViolations:e.coverageContracts.count},axes:sZ(e),validation:cZ(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function sZ(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:aZ(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function aZ(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:Jn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function cZ(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?Jn(i/r.size):0,c=s>0?Jn(o/s):0,l={};for(let[u,d]of Object.entries(n)){let p=new Set(d);if(p.size===0)continue;let m=0;for(let g of p)m+=t[g]?.fixChanges??0;let f=Jn(m/p.size);l[u]={flaggedFiles:p.size,fixDensity:f,lift:c>0?Jn(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Jn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Jn(e){return Math.round(e*100)/100}function nE(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function hd(e,t="existing shared infrastructure discount"){let n=Cr(e);return Math.abs(n-e.count)<.01?"":` (${nE(n)} score-weighted after ${t})`}function cc(e,t){let n=Cr(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${nE(n)} score-weighted)`}function lZ(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,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} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${hd(e.reactHookCandidates)} \u2014 review whether a common hook would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${hd(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${hd(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,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 literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,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 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,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(", ")} \u2014 verify direct rows and review inferred layer signals against declared ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query diff-gate\` or \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),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 structural link`+hd({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",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 ZP={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","duplicate-bodies-pressure":"hygiene","twin-drift-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function eE(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 uZ(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(I,C,k)=>{C>0&&r.push({axis:I,points:C,detail:k,kind:ZP[I]??"hygiene"})},s=(I,C,k,T,F,V,ie)=>{let W=Math.max(T,1);if(k<=W)return;let be=k/W,Z=Math.min(F,Math.ceil(Math.log2(be)*V));if(Z<=0)return;let Re=ZP[I]??"hygiene";i.push({axis:I,category:C,kind:Re,count:k,threshold:Jn(W),ratio:Jn(be),extraPenalty:Z}),o(I,Z,`${k} ${ie} exceed pressure threshold ${Jn(W)} (${Jn(be)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let p=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(p)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let m=Cr(e.reactHookCandidates),f=m/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),cc(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let y=Cr(e.vueComposableCandidates),x=y/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(x)),cc(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let R=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(R/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let b=Cr(e.wrappers);o("wrappers",Math.min(3,b),cc(e.wrappers,"wrapper candidate(s)"));let v=Cr(e.passthroughs);o("passthroughs",Math.min(3,v),cc(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let w=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(w*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let I=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(I/10)),cc({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:I},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let I=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",I,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",m,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",y,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",b,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",v,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as dZ}from"v8";var pZ=64*1024*1024;function Gh(){let e=globalThis.gc;if(!e)return;let t=dZ();t.heap_size_limit-t.used_heap_size<pZ||e()}var mZ=50,fZ=25e3,gZ=2500,rE=2500,iE=50,hZ=10,ms=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions","coverage-contracts"],yZ={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:vZ(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:xZ(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:RZ(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:CZ(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:kZ(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:IZ(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:PZ(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:EZ(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:DZ(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:TZ(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:LZ(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:FZ(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:wZ(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:NZ(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:AZ(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_Z(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:jZ(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:BZ(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:MZ(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:$Z(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:OZ(e,n)})};function lc(e,t,n={}){return zh(e,[t],n)[0]}function zh(e,t,n={}){return bZ(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>yZ[s](e,n.scope,o,r))})}function bZ(e,t,n){let r=Ut(e),i=HZ(r,t);try{return n(r,i)}finally{bg(e,{semanticProvider:!0}),Gh()}}function Kh(e){return tE(SZ(e))}function SZ(e){let t=Ve(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:Ve(e,"dead").dead,isolated:Ve(e,"isolated").isolated,realCycleCount:Ve(e,"cycles").realCycleCount,similarCount:Ve(e,"similar").similarCount,duplicateBodies:Ve(e,"duplicate-bodies").duplicateBodies,twinDrift:Ve(e,"twin-drift").twinDrift,reactComponentDuplicates:Ve(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Ve(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Ve(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Ve(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Ve(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Ve(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Ve(e,"extract-candidates").extractCount,wrappers:Ve(e,"wrapper-candidates").wrappers,passthroughs:Ve(e,"passthrough-candidates").passthroughs,stale:Ve(e,"stale-abstractions").stale,drift:Ve(e,"drift").drift,complexity:Ve(e,"complexity-hotspots").complexity,gitEvidence:oE(e,"git-evidence")?.gitEvidence??null,suppressions:oE(e,"suppressions")?.suppressions??null,coverageContracts:Ve(e,"coverage-contracts").coverageContracts}}function oE(e,t){return e.find(n=>n.phase===t)}function Ve(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function vZ(e,t,n){return He(e,n,"dead",()=>{let r=hr(e,{scope:t,...je.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return yd(UZ(e,r.symbols))})}function xZ(e,t,n){return He(e,n,"isolated",()=>{let r=ji(e,{scope:t,...je.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return yd(VZ(e,r))})}function RZ(e,t,n){return He(e,n,"cycles",()=>$a(e,{scope:t}).filter(i=>i.kind==="real").length)}function CZ(e,t,n){let r=He(e,n,"similar",()=>Wg(e,{scope:t,...je.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function wZ(e,t,n){return He(e,n,"extract-candidates",()=>Vi(e,{scope:t,...je.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function kZ(e,t,n){return He(e,n,"duplicate-bodies",()=>{let r=Ki(e,{scope:t,...je.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function IZ(e,t,n){return He(e,n,"twin-drift",()=>{let r=as(e,{scope:t,...je.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function PZ(e,t,n){return He(e,n,"react-component-duplicates",()=>{let r=Hi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Jh(r)})}function EZ(e,t,n){return He(e,n,"react-hook-candidates",()=>{let r=Wi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return cE(r,zZ)})}function DZ(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let r=ja(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return GZ(r)})}function TZ(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let r=qi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Jh(r)})}function LZ(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let r=Ui(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return cE(r,KZ)})}function FZ(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let r=Ba(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return yd(r)})}function NZ(e,t,n){return He(e,n,"wrapper-candidates",()=>{let r=Zi(e,{scope:t,...je.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return aE(r,JZ)})}function AZ(e,t,n){return He(e,n,"passthrough-candidates",()=>{let r=Qi(e,{scope:t,...je.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return aE(r,YZ)})}function _Z(e,t,n){return He(e,n,"stale-abstractions",()=>{let r=Xi(e,{scope:t,...je.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),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 MZ(e,t){return He(e,t,"git-evidence",()=>{let n=Tt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Gi(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Yh(o.findings.reduce((a,c)=>a+sE(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:sE(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function $Z(e,t){return He(e,t,"suppressions",()=>{let n=gd(e);return{total:n.total,byCategory:{...n.byCategory}}})}function OZ(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=eP(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function jZ(e,t,n){return He(e,n,"drift",()=>{let r=Yi(e,{scope:t,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,layerViolations:r.layerViolations,direct:o,signal:s}})}function BZ(e,t,n){return He(e,n,"complexity-hotspots",()=>{let r=ac(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>mZ).length}})}function HZ(e,t){let n=e.symbols>=fZ||e.documents>=gZ,r=t?Number.POSITIVE_INFINITY:iE,i=t?Number.POSITIVE_INFINITY:hZ;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:rE,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${rE} symbols and reported their top ${iE} findings. Enable full mode for unbounded candidate counts.`]}}function WZ(e,t){t.releaseCachesBetweenPhases&&(bg(e),Gh())}function He(e,t,n,r){qZ(n);try{return r()}finally{WZ(e,t)}}function qZ(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function UZ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Oe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function VZ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Oe(e,n.symbol,n.relativePath))}function yd(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 aE(e,t){return{...yd(e),scoreCount:Yh(e.reduce((r,i)=>r+t(i),0))}}function GZ(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function Jh(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function cE(e,t){return{...Jh(e),scoreCount:Yh(e.reduce((r,i)=>r+t(i),0))}}function zZ(e){let t=e.sharedHooks.length>0,n=lE({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:uE(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function KZ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=lE({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:uE(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function lE(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!pE.has(dE(t))).length+Math.min(e.functions.length,3)}function uE(e,t,n){let r=[...e,...t,...n].map(dE);return r.length>0&&r.every(i=>pE.has(i))}function dE(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function JZ(e){return e.actionTier==="signal"?.25:1}function YZ(e){return e.actionTier==="signal"?.25:1}function sE(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function Yh(e){return Math.round(e*100)/100}var pE=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function Qh(e,t,n,r={}){let i=Oa(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}import{readFileSync as mE}from"fs";import{extname as QZ,join as fE}from"path";function Xh(e,t,n={}){let{context:r=0}=n,i=XZ(t);if(i)return e9(e,i.filePath,i.startLine,i.endLine,r);let o=te(e,t);return o?ZZ(e,o,r):null}function XZ(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 ZZ(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=fE(e.config.projectRoot,t.relativePath),o;try{o=mE(i,"utf-8")}catch{return null}let s=o.split(`
770
- `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
771
- `);return{symbol:t.symbol,shortName:P(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??gE(t.relativePath),source:l}}function e9(e,t,n,r,i){let o=vt(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=fE(e.config.projectRoot,s.relative_path),c;try{c=mE(a,"utf-8")}catch{return null}let l=c.split(`
772
- `),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),p=l.slice(u,d+1).join(`
773
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??gE(s.relative_path),source:p}}function gE(e){switch(QZ(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 Zh(e,t={}){let{scope:n,limit:r}=t,i=new B(e),o=c9([...t9(e,n),...i9(e,i,n)]);return l9(o),r?o.slice(0,r):o}function t9(e,t){let n=[];for(let r of n9(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||ef(e,r.barrel_path)||_(e,r.barrel_path)&&Dl(e,r.barrel_path).length===0)continue;let i=r9(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:P(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...yE(e,r.barrel_path)})}return n}function n9(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT
774
- barrel_d.id AS barrel_doc_id,
775
- barrel_d.relative_path AS barrel_path,
776
- gs.id AS symbol_id,
777
- gs.symbol AS symbol,
778
- orig_d.id AS original_doc_id,
779
- orig_d.relative_path AS original_path
780
- FROM mentions m
781
- JOIN chunks c ON m.chunk_id = c.id
782
- JOIN documents barrel_d ON c.document_id = barrel_d.id
783
- JOIN global_symbols gs ON m.symbol_id = gs.id
784
- JOIN (
785
- SELECT m2.symbol_id, c2.document_id
786
- FROM mentions m2
787
- JOIN chunks c2 ON m2.chunk_id = c2.id
788
- WHERE m2.role = 1
789
- GROUP BY m2.symbol_id
790
- ) sym_def ON sym_def.symbol_id = gs.id
791
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
792
- WHERE m.role != 1
793
- AND (barrel_d.relative_path LIKE '%/index.ts'
794
- OR barrel_d.relative_path LIKE '%/index.js'
795
- OR barrel_d.relative_path = 'index.ts'
796
- OR barrel_d.relative_path = 'index.js')
797
- AND orig_d.id != barrel_d.id
798
- ${e.pathExclusionsFor("barrel_d","orig_d")}
799
- ${e.symbolNoiseFor("gs")}
800
- -- Only function-level symbols (ending with ().), not module-level
801
- AND gs.symbol LIKE '%().'
802
- ${n}
803
- ORDER BY barrel_d.relative_path, gs.symbol`,...r)}function r9(e,t){return e.get(`SELECT
804
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
805
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
806
- FROM (
807
- SELECT
808
- consumer_d.id AS consumer_doc_id,
809
- MAX(CASE WHEN EXISTS (
810
- SELECT 1
811
- FROM mentions barrel_m
812
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
813
- WHERE barrel_c.document_id = consumer_d.id
814
- AND barrel_m.role != 1
815
- AND barrel_m.symbol_id IN (
816
- SELECT m2.symbol_id
817
- FROM mentions m2
818
- JOIN chunks c2 ON m2.chunk_id = c2.id
819
- WHERE c2.document_id = ?
820
- AND m2.role != 1
821
- )
822
- ) THEN 1 ELSE 0 END) AS uses_barrel
823
- FROM mentions ref_m
824
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
825
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
826
- WHERE ref_m.symbol_id = ?
827
- AND ref_m.role != 1
828
- AND consumer_d.id != ?
829
- AND consumer_d.id != ?
830
- ${e.pathExclusionsFor("consumer_d")}
831
- GROUP BY consumer_d.id
832
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function i9(e,t,n){let r=[];for(let i of o9(e,n))bE(e,i,i)>0||r.push(...s9(e,t,i));return r}function o9(e,t){return q(e,{scope:t,includeIgnored:!1}).filter(n=>Dl(e,n).length>0||Di(e,n).length>0)}function s9(e,t,n){let r=Dl(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hE(e,t,n,o.sourcePath,[a9(o.specifier)])),i=Di(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hE(e,t,n,o.sourcePath,o.kind==="named"&&o.names.length>0?o.names:[o.kind==="star"?`* from ${o.sourcePath}`:`* namespace from ${o.sourcePath}`]));return[...r,...i]}function hE(e,t,n,r,i){let o=t.definitionsForFile(r);return i.map(s=>{let a=o.find(c=>c.leaf===s);return{barrelFile:n,symbol:a?.symbol??`source-reexport:${n}:${s}`,shortName:a?P(a.symbol):s,originalFile:r,barrelConsumers:0,directConsumers:bE(e,r,n),...yE(e,n)}})}function a9(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function yE(e,t){return Ti(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function bE(e,t,n){let r=new Set;for(let i of q(e,{includeIgnored:!1}))if(i!==n)for(let o of Ce(e,i))o.sourcePath===t&&r.add(i);return r.size}function c9(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 l9(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function ry(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new B(e),s=u9(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=d9(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:SE(),callees:SE()},l=[],u=0,d=a==="semantic"?Eu(e,s):new Map,p=a==="source"?f9(e,o,s):null;for(let m of s){let f=bd(m,a==="semantic"?Ko(e,m).map(b=>b.file):[...p?.referencesBySymbolId.get(m.symbolId)??[]]),g=bd(m,a==="semantic"?(d.get(m.symbolId)??[]).map(b=>b.file):[...p?.calleesBySymbolId.get(m.symbolId)??[]]);u+=1;let h=bd(m,qn(e,m).map(b=>b.file)),y=bd(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(b=>b.file)),x=ey(a,"references"),R=ey(a,"callees");vE(c.references,m,"references",h,f,x,l),vE(c.callees,m,"callees",y,g,R,l)}return l.sort((m,f)=>f.cheapOnly.length+f.oracleOnly.length-(m.cheapOnly.length+m.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?ny(u/s.length):0,oracleKind:a,scores:["references","callees"].map(m=>m9(m,c[m],a)),topDisagreements:l.slice(0,i)}}function SE(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function u9(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 d9(e,t){let n=t[0];if(!n)return null;if(ty(e,n))return"source";try{if(St(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>ty(e,r))?"source":null}function bd(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function vE(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:P(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var p9={references:!0,callees:!1};function m9(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=ey(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?ny(t.agreed/t.cheapTotal):null,recall:ny(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function ey(e,t){return e==="semantic"?p9[t]:!1}function ty(e,t){return K(t.relativePath)==="clojure"&&ce(e,t.relativePath)!==null}function f9(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>ty(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(K(c)!=="clojure")continue;let l=ce(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])xE(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(K(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=ce(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])xE(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function xE(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function ny(e){return Math.round(e*1e3)/1e3}var g9=new Set(dn());function iy(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=b9(e,h9(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=v9(c);return i?l.slice(0,i):l}function h9(e,t){let n=Ue(e,{scope:t.scope}).filter(r=>y9(r)&&!e.isIgnored(r.relativePath)).filter(r=>Q(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>Q(i)-Q(r)||r.relativePath.localeCompare(i.relativePath)),Pe(n,t.scanLimit)}function y9(e){return!e.isFunctionLike||et(e.symbol)?!1:e.kind===null||g9.has(e.kind)}function b9(e,t,n){let r=[];for(let s of t){let a=R9(e,s,n);a&&r.push({signature:a,definition:s,fn:S9(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=x9(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?vh(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function S9(e){return{symbol:e.symbol,shortName:P(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:Q(e)}}function v9(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);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 x9(e){return e<=5?"<=5":e<=20?"6-20":">20"}function R9(e,t,n){if(n.semantic){let o=mw(e,t);if(o)return o}let r=C9(t.documentation),i=r?I9(r):null;return i||P9(w9(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function C9(e){return ur(dr(e))}function w9(e,t,n,r,i){let o=_(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=D9(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let p=s[d]?.trim();if(p&&(u=u?`${u} ${p}`:p,k9(u)))return u}if(u&&u.includes("("))return u}return null}function k9(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Js(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function I9(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 P9(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${J(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=E9(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 E9(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 D9(e,t,n,r){let i=J(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 d=l;d<=u;d+=1){let p=e[d]??"";(o.test(p)||s.test(p))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let p=e[d]??"";(o.test(p)||s.test(p))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{existsSync as Ay,statSync as Wee}from"fs";import{join as qee}from"path";import T9 from"better-sqlite3";var L9=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],Gt=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new T9(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
833
- EXISTS (
834
- SELECT 1
835
- FROM defn_enclosing_ranges local_der
836
- JOIN documents local_d ON local_der.document_id = local_d.id
837
- WHERE local_der.symbol_id = gs.id
838
- ${this.pathExclusionsFor("local_d").trimStart()}
839
- )
840
- OR EXISTS (
841
- SELECT 1
842
- FROM mentions local_m
843
- JOIN chunks local_c ON local_m.chunk_id = local_c.id
844
- JOIN documents local_d ON local_c.document_id = local_d.id
845
- WHERE local_m.symbol_id = gs.id
846
- AND local_m.role = 1
847
- ${this.pathExclusionsFor("local_d").trimStart()}
848
- )
849
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>L9.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
850
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import F9 from"ignore";import{readFileSync as N9,existsSync as RE,readdirSync as A9}from"fs";import{dirname as oy,isAbsolute as CE,join as Sd,relative as _9,resolve as M9}from"path";function ni(e){let t=F9();return $9(e,t)||t.add(B9),{isIgnored:r=>sy(t,e,r),filter:r=>r.filter(i=>!sy(t,e,i))}}function $9(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!RE(s)))try{let c=N9(s,"utf-8");t.add(a?O9(c,a):c),n.add(s)}catch{}},i=oy(e),o=0;for(;i!==oy(i)&&o<5&&(r(Sd(i,".gitignore"),""),!RE(Sd(i,".git")));)i=oy(i),o++;return wE(e,"",t,r),n.size>0}function wE(e,t,n,r){let i=t?Sd(e,t):e;r(Sd(i,".gitignore"),t);let o;try{o=A9(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;sy(n,e,`${a}/`)||wE(e,a,n,r)}}function O9(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>j9(r,n)).join(`
851
- `)}function j9(e,t){let n=e.trimStart();if(!n||n.startsWith("#"))return e;let r=e.slice(0,e.length-n.length),i=n.startsWith("!"),o=i?n.slice(1):n;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,u=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${r}${i?"!":""}${u}`}var B9=`
852
- # Dependencies
853
- node_modules/
854
- vendor/
855
- .bundle/
856
-
857
- # Build output
858
- dist/
859
- build/
860
- out/
861
- target/
862
- bin/
863
- obj/
864
-
865
- # Python
866
- __pycache__/
867
- *.pyc
868
- *.pyo
869
- .venv/
870
- venv/
871
- .env/
872
- env/
873
- *.egg-info/
874
-
875
- # Rust
876
- target/
877
-
878
- # Java / Kotlin / Scala
879
- *.class
880
- .gradle/
881
- .mvn/
882
-
883
- # C# / .NET
884
- bin/
885
- obj/
886
- packages/
887
-
888
- # Go
889
- vendor/
890
-
891
- # Dart
892
- .dart_tool/
893
- build/
894
-
895
- # PHP
896
- vendor/
897
-
898
- # IDE / OS
899
- .idea/
900
- .vscode/
901
- *.swp
902
- *.swo
903
- .DS_Store
904
- Thumbs.db
905
-
906
- # Type definitions (often noise in queries)
907
- *.d.ts
908
- `;function sy(e,t,n){let r=H9(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function H9(e,t){if(!t||t===".")return null;if(!CE(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=CE(t)?t:M9(e,t),r=_9(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as W9,writeFileSync as cy,existsSync as wr,mkdirSync as q9,realpathSync as U9}from"fs";import{isAbsolute as kE,join as Lt,relative as IE,resolve as vd}from"path";import{createHash as V9}from"crypto";import{homedir as G9}from"os";var fs=".scipquery.json",DE=250,TE=0,LE=10*6e4,z9={enabled:!1,debounceMs:DE,cooldownMs:TE,gitPollMs:2e3,idleTimeoutMs:LE,autoRefresh:!0,ignore:[]},xd=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],K9=new Set(["languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","coverageContracts","docs"]),J9=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),Y9=new Set(["router"]),Q9=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),X9=new Set(["typescript","rust"]),Z9=new Set(["tsconfigs"]),e7=new Set(["rustAnalyzerPath"]),PE=new Set(xd),t7=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),n7=new Set(["architecturalBoundarySegments"]),r7=new Set(["snapshotPaths"]),i7=new Set(["name","files","reason"]),o7=new Set(["id","check","file","reason","expiresAt","createdAt"]),s7=new Set(["name","file","keys","mustEqual","allowExtra"]),a7=new Set(["type","identifier","marker"]),c7=new Set(["type","path","pattern"]),l7=new Set(["object-literal-keys","string-array","markdown-list"]),u7=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function ut(e){let t=Lt(e,fs);if(!wr(t))return{};try{let n=W9(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${fs} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${fs} at ${t}: ${r}`,{cause:n})}}function gs(e,t={}){let n=[];f7(e,n);let r=new Set(xd);for(let[c,l]of(e.languages??[]).entries())r.has(l)||n.push({level:"error",path:`languages[${c}]`,message:`Unsupported language: ${l}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let i=e.indexer?.typescript;if(i?.projectMode!==void 0&&i.projectMode!=="single"&&i.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),i?.projects!==void 0)if(!Array.isArray(i.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[c,l]of i.projects.entries()){let u=`indexer.typescript.projects[${c}]`;if(typeof l!="string"||l.trim()==="")n.push({level:"error",path:u,message:"Project path must be a non-empty string."});else if(t.projectRoot){let d=vd(t.projectRoot,l),p=IE(t.projectRoot,d);p.startsWith("..")||kE(p)?n.push({level:"error",path:u,message:"Project path must stay inside the project root."}):wr(d)||n.push({level:"warning",path:u,message:`TypeScript project path does not exist: ${l}`})}}i?.projectMode==="workspace"&&i.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let o=e.semantic?.rust;o?.rustAnalyzerPath!==void 0&&(typeof o.rustAnalyzerPath!="string"||o.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let s=e.indexer?.clojure;if(s?.configPath!==void 0){let c="indexer.clojure.configPath";if(typeof s.configPath!="string"||s.configPath.trim()==="")n.push({level:"error",path:c,message:"Config path must be a non-empty string."});else if(t.projectRoot){let l=vd(t.projectRoot,s.configPath),u=IE(t.projectRoot,l);u.startsWith("..")||kE(u)?n.push({level:"error",path:c,message:"Config path must stay inside the project root."}):wr(l)||n.push({level:"warning",path:c,message:`Clojure indexer config path does not exist: ${s.configPath}`})}}if(e.locality!==void 0)if(!ri(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let c=e.locality.architecturalBoundarySegments;if(c!==void 0)if(!Array.isArray(c))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[l,u]of c.entries()){let d=`locality.architecturalBoundarySegments[${l}]`;typeof u!="string"||u.trim()===""?n.push({level:"error",path:d,message:"Boundary segment must be a non-empty string."}):(u.includes("/")||u.includes("\\"))&&n.push({level:"error",path:d,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[c,l]of(e.declaredCouplings??[]).entries()){let u=`declaredCouplings[${c}]`;if((!l.name||l.name.trim()==="")&&n.push({level:"error",path:`${u}.name`,message:"Declared coupling name is required."}),!Array.isArray(l.files)||l.files.length<2)n.push({level:"error",path:`${u}.files`,message:"Declared coupling needs at least two files."});else for(let[d,p]of l.files.entries())!p||p.trim()===""?n.push({level:"error",path:`${u}.files[${d}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!wr(Lt(t.projectRoot,p))&&n.push({level:"warning",path:`${u}.files[${d}]`,message:`Declared coupling file does not exist: ${p}`});l.reason!==void 0&&l.reason.trim()===""&&n.push({level:"error",path:`${u}.reason`,message:"Declared coupling reason cannot be blank."})}let a=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[c,l]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let u=`suppressions[${c}]`;if(!ri(l)){n.push({level:"error",path:u,message:"Suppression must be an object."});continue}if((!l.reason||l.reason.trim()==="")&&n.push({level:"error",path:`${u}.reason`,message:"Suppression reason is required."}),l.id!==void 0&&l.id.trim()===""&&n.push({level:"error",path:`${u}.id`,message:"Suppression id cannot be blank."}),l.check!==void 0&&l.check.trim()===""&&n.push({level:"error",path:`${u}.check`,message:"Suppression check cannot be blank."}),!l.id&&(!l.check||!l.file)?n.push({level:"error",path:u,message:"Suppression must include id or both check and file."}):!l.id&&l.check&&l.file&&n.push({level:"warning",path:u,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),l.file!==void 0&&(l.file.trim()===""?n.push({level:"error",path:`${u}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!wr(Lt(t.projectRoot,l.file))&&n.push({level:"warning",path:`${u}.file`,message:`Suppression file does not exist: ${l.file}`})),l.expiresAt){let d=Date.parse(l.expiresAt);Number.isNaN(d)?n.push({level:"error",path:`${u}.expiresAt`,message:"Must be an ISO date string."}):d<=a.getTime()&&n.push({level:"warning",path:`${u}.expiresAt`,message:"Suppression has expired."})}}return p7(e,n,t),d7(e,n),n}function d7(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function p7(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!ri(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!wr(Lt(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),EE(t,i.keys,`${o}.keys`,l7,"Unknown coverage-contract key extractor type."),EE(t,i.mustEqual,`${o}.mustEqual`,u7,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function EE(e,t,n,r,i){if(!ri(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function Yn(e){return{...z9,...e.watch}}function m7(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return ay(n);if(t?.dbPath)return ay(vd(e,t.dbPath));let r=ys(e);return ay(r)}function hs(){let e=process.env.XDG_CACHE_HOME;return Lt(e||Lt(G9(),".cache"),"scip-query")}function ys(e){let t=vd(e);try{t=U9(t)}catch{}let n=V9("sha256").update(t).digest("hex").slice(0,12);return Lt(hs(),"projects",n)}function uc(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return Lt(hs(),"repositories",e)}function dc(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function zt(e,t){let n=m7(e,t);return{cacheDir:n,dbPath:Lt(n,"index.db"),indexPath:Lt(n,"index.scip"),metaPath:Lt(n,"meta.json")}}function FE(e,t){let n=Lt(e,fs);return wr(n)||cy(n,JSON.stringify({languages:t,watch:{enabled:!0,debounceMs:DE,cooldownMs:TE,gitPollMs:2e3,idleTimeoutMs:LE,autoRefresh:!0}},null,2)+`
909
- `),n}function NE(e,t,n){let r=Lt(e,fs),i={...t,languages:[...n]},o=!wr(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&cy(r,JSON.stringify(i,null,2)+`
910
- `),{configPath:r,config:i,changed:o}}function AE(e,t,n){let r=Lt(e,fs),i={...t,watch:{...t.watch,enabled:n,...n&&t.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}},o=!wr(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&cy(r,JSON.stringify(i,null,2)+`
911
- `),{configPath:r,config:i,changed:o}}function ay(e){return q9(e,{recursive:!0}),e}function f7(e,t){if(!ri(e))return;let n=e;if(lt(t,n,"",K9),lt(t,n.watch,"watch",J9),lt(t,n.hooks,"hooks",Y9),lt(t,n.entryRoots,"entryRoots",Q9),lt(t,n.semantic,"semantic",X9),lt(t,n.semantic?.typescript,"semantic.typescript",Z9),lt(t,n.semantic?.rust,"semantic.rust",e7),lt(t,n.locality,"locality",n7),lt(t,n.docs,"docs",r7),ri(n.indexer)){lt(t,n.indexer,"indexer",PE);for(let[r,i]of Object.entries(n.indexer))PE.has(r)&&lt(t,i,`indexer.${r}`,t7)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())lt(t,i,`declaredCouplings[${r}]`,i7);if(Array.isArray(n.suppressions))for(let[r,i]of n.suppressions.entries())lt(t,i,`suppressions[${r}]`,o7);if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;lt(t,i,o,s7),ri(i)&&(lt(t,i.keys,`${o}.keys`,a7),lt(t,i.mustEqual,`${o}.mustEqual`,c7))}}function lt(e,t,n,r){if(ri(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}function ri(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as zE,readFileSync as N7}from"fs";import{execFileSync as g7}from"child_process";import{existsSync as h7,readdirSync as ME}from"fs";import{extname as $E,join as OE}from"path";var jE=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),y7=[{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:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{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 gn(e){let t=[],n=b7(e),r=R7(e);for(let i of y7){if(S7(e,i.files)){t.push(i.language);continue}if(v7(n,i.globs)){t.push(i.language);continue}w7(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&_E(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&_E(t,"c"),t}function b7(e){try{return ME(e)}catch{return[]}}function S7(e,t){return t?.length?t.some(n=>h7(OE(e,n))):!1}function v7(e,t){return t?.length?e.some(n=>t.some(r=>x7(n,r))):!1}function x7(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 R7(e){let t=C7(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=ME(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=OE(i,s.name);if(s.isDirectory()){jE.has(s.name)||r.push(a);continue}let c=$E(s.name).toLowerCase();c&&n.add(c)}}return n}function C7(e){try{let t=g7("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(`
912
- `)){if(!r||r.split("/").some(o=>jE.has(o)))continue;let i=$E(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function w7(e,t){return t?.length?t.some(n=>e.has(n)):!1}function _E(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as k7}from"crypto";import{copyFileSync as BE,existsSync as ii,linkSync as I7,mkdirSync as HE,readFileSync as UE,readdirSync as WE,renameSync as uy,rmSync as Cd,statSync as P7}from"fs";import{basename as Rd,dirname as pc,join as Ft,relative as qE}from"path";var bs=1,wd=".scipquery-generations";function kd(e){let t=Id(e.outputDb),n=E7(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||ly(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),ly(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),ly(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=Pd(e.metaPath,e.outputDb),i={version:bs,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return he(Ft(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function VE(e){try{let t=JSON.parse(UE(Ft(Id(e),"state.json"),"utf8"));return t.version!==bs||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!L7(t.previousGeneration)||!F7(t.publication)?null:t}catch{return null}}function GE(e,t,n=()=>new Date){if(!ii(e)||!ii(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=VE(e),i={version:bs,currentGeneration:Pd(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return he(Ft(Id(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function hn(e,t=Ft(pc(e),"meta.json")){let n=Ft(Id(e),"state.json");if(!ii(n))return{state:"legacy",statePath:n};let r=VE(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Pd(t,e),o=r.currentGeneration===i,s=r.previousGeneration?ii(Ft(pc(e),r.previousGeneration.databasePath)):!0;return!o||!s?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:s,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Id(e){return Ft(pc(e),wd)}function E7(e,t){if(!ii(e.outputDb))return;let n=Pd(e.metaPath,e.outputDb),r=Ft(t,n),i=Ft(r,Rd(e.outputDb)),o=ii(e.metaPath)?Ft(r,Rd(e.metaPath)):void 0;if(!ii(i)){let s=`${r}.${process.pid}.${Date.now()}.tmp`;Cd(s,{recursive:!0,force:!0}),HE(s,{recursive:!0});let a=Ft(s,Rd(e.outputDb));try{I7(e.outputDb,a)}catch{BE(e.outputDb,a)}o&&BE(e.metaPath,Ft(s,Rd(e.metaPath))),HE(t,{recursive:!0}),uy(s,r)}return D7(t,n),{generationIdentity:n,databasePath:qE(pc(e.outputDb),i),...o?{metadataPath:qE(pc(e.outputDb),o)}:{}}}function D7(e,t){for(let n of WE(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Cd(Ft(e,n.name),{recursive:!0,force:!0});for(let n of WE(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Cd(Ft(e,n.name),{recursive:!0,force:!0})}function Pd(e,t){let n=k7("sha256").update(`sqlite-generation-v${bs}\0`);ii(e)&&n.update(T7(UE(e,"utf8")));let r=P7(t);return n.update(`\0${r.size}`),n.digest("hex")}function T7(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function ly(e,t){Cd(`${t}.tmp-replace`,{force:!0}),uy(e,`${t}.tmp-replace`),uy(`${t}.tmp-replace`,t)}function L7(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function F7(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}function En(e,t,n){let r=new Date().toISOString();if(!zE(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!zE(n.metaPath))return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(N7(n.metaPath,"utf-8")),o=t.languages??gn(e),s=A7(e,o,t),a=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages),l=hn(n.dbPath,n.metaPath),u=l.state==="invalid"||l.state==="drifted",d=c&&!u;return{state:d?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:u?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:d?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function A7(e,t,n){return _i(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}import{createHash as qD,randomUUID as Dy}from"crypto";import{closeSync as UD,constants as Iee,copyFileSync as jD,existsSync as si,lstatSync as Pee,mkdirSync as kr,mkdtempSync as VD,openSync as GD,readdirSync as Eee,readFileSync as Kt,realpathSync as Dee,renameSync as io,rmSync as oi,statSync as Tee,unlinkSync as Iy,writeFileSync as zD}from"fs";import{dirname as KD,join as z,resolve as Tn}from"path";import{setTimeout as Lee}from"timers/promises";import{pathToFileURL as BD}from"url";import{deserializeSCIP as JD}from"@c4312/scip";import Fee from"better-sqlite3";import{createRequire as _7}from"module";var M7=_7(import.meta.url),Fe=$7().version;function $7(){for(let e of["../package.json","../../package.json"])try{return M7(e)}catch{}return{version:"0.0.0"}}import{randomUUID as KE}from"crypto";import{closeSync as JE,mkdirSync as O7,openSync as YE,readFileSync as QE,unlinkSync as XE,writeFileSync as ZE}from"fs";import{dirname as j7,join as B7}from"path";function mc(e,t={}){return to(B7(e,"gc.lock"),t)}function to(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;O7(j7(e),{recursive:!0});do{let s=KE();try{let a=YE(e,"wx");try{let c={version:1,pid:process.pid,token:s,startedAt:new Date(i()).toISOString()};ZE(a,`${JSON.stringify(c)}
913
- `)}finally{JE(a)}return{release:()=>tD(e,s)}}catch(a){if(a.code!=="EEXIST")return null;let c=eD(e);if(c&&(c.pid===void 0||!xe(c.pid))){H7(e,c);continue}if(Date.now()>=o)return null;W7(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function eD(e){try{let t=QE(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function H7(e,t){let n=`${e}.reclaim`,r=KE(),i;try{i=YE(n,"wx")}catch{return!1}try{ZE(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
914
- `)}finally{JE(i)}try{let o=eD(e);return!o||o.raw!==t.raw||o.pid!==void 0&&xe(o.pid)?!1:(XE(e),!0)}catch{return!1}finally{tD(n,r)}}function tD(e,t){try{let n=JSON.parse(QE(e,"utf8"));n.pid===process.pid&&n.token===t&&XE(e)}catch{}}function W7(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import{lstatSync as ree,readdirSync as iee}from"fs";import{join as oee,relative as see,resolve as Sy,sep as aee}from"path";import{createHash as q7}from"crypto";import{existsSync as py,mkdirSync as U7,readFileSync as Ed,readdirSync as T0e,renameSync as V7,rmSync as L0e,writeFileSync as G7}from"fs";import{join as Ss}from"path";import{create as rD,fromBinary as iD,toBinary as z7}from"@bufbuild/protobuf";import{deserializeSCIP as Dd,DocumentSchema as my,IndexSchema as oD,serializeSCIP as sD}from"@c4312/scip";var Td=1,fc="typescript-scip-fragments";function aD(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=no(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=iD(my,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=sD(rD(oD,{documents:n,externalSymbols:[]})),i=Dd(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ld(e){let t=Ss(e,fc);return{rootDir:t,blobDir:Ss(t,"blobs"),generationDir:Ss(t,"generations")}}function K7(e){let t=Dd(e.indexBytes);SD(t.metadata,vD(e)),bD(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=no(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=z7(my,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?ro(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:ro(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(fD(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=gD(e,r);return hD(e.cacheDir,i),i}function cD(e){let t=Ld(e.cacheDir);if(!py(fy(t,e.generationIdentity)))return K7(e);let n=uD({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function lD(e){let t=uD({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=no(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,fD(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=gD(e,[...n.values()]);return hD(e.cacheDir,i),i}function uD(e){let t=Ld(e.cacheDir),n=fy(t,e.generationIdentity),r;try{r=yD(Ed(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=Ss(t.blobDir,`${o.blobHash}.scipdoc`),a=Ed(s);if(a.byteLength!==o.byteLength||ro(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function dD(e){let t=mD(e);return dy(t.baseIndex,t.completeDocuments,"assembled")}function pD(e){let t=mD(e);return J7(t.deletedAffectedPaths),{completeIndexBytes:dy(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:dy(t.baseIndex,t.affectedDocuments,"affected")}}function mD(e){let t=Dd(e.baseIndexBytes);SD(t.metadata,vD(e)),bD(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=no(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=no(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=iD(my,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function dy(e,t,n){let r=sD(rD(oD,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Dd(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function J7(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function fD(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=no(t.relativePath),i=Buffer.from(t.bytes),o=ro(i),s=Ld(e);U7(s.blobDir,{recursive:!0});let a=Ss(s.blobDir,`${o}.scipdoc`);if(py(a)){let c=Ed(a);if(c.byteLength!==i.byteLength||ro(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;G7(c,i),V7(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function gD(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Td,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function hD(e,t){let n=Ld(e),r=fy(n,t.generationIdentity);if(py(r)){let i=yD(Ed(r,"utf8"));if(nD(i)!==nD(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}he(r,t,{spacing:2,trailingNewline:!0})}function nD(e){return ro(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function yD(e){let t=JSON.parse(e);if(t.version!==Td||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(no(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function fy(e,t){return Ss(e.generationDir,Y7(t))}function Y7(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${ro(e)}.json`}function bD(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function SD(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function vD(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function no(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function ro(e){return q7("sha256").update(e).digest("hex")}import{createHash as Q7}from"crypto";import{existsSync as gc,mkdirSync as X7,readFileSync as yc,readdirSync as gy,renameSync as Z7,rmSync as xD,writeFileSync as eee}from"fs";import{join as Dn}from"path";var Fd=1,CD=64*1024*1024,bc="typescript-scip-overlays";function wD(e){let t=PD(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=by(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,tee(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Fd,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return nee(e.cacheDir,i),i}function kD(e){let t=PD(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=yc(Dn(Sc(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||hc(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return dD({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ID(e,t){let n=Sc(e),r=Dn(n,"generations");if(!gc(r))return;let i=new Set(t.map(yy)),o=new Set;for(let a of gy(r).filter(c=>i.has(c))){let c=hy(yc(Dn(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of gy(r))i.has(a)||xD(Dn(r,a),{force:!0});let s=Dn(n,"blobs");if(gc(s))for(let a of gy(s))o.has(a)||xD(Dn(s,a),{force:!0})}function PD(e,t){let n=Dn(Sc(e),"generations",yy(t));if(!gc(n))return null;let r=hy(yc(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function tee(e,t){let n=by(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=hc(r),o=Dn(Sc(e),"blobs");X7(o,{recursive:!0});let s=Dn(o,`${i}.scipdoc`);if(gc(s)){let a=yc(s);if(a.byteLength!==r.byteLength||hc(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;eee(a,r),Z7(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function nee(e,t){let n=Dn(Sc(e),"generations",yy(t.generationIdentity));if(gc(n)){let r=hy(yc(n,"utf8"));if(RD(r)!==RD(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}he(n,t,{spacing:2,trailingNewline:!0})}function hy(e){let t=JSON.parse(e);if(t.version!==Fd||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(by(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Sc(e){return Dn(e,bc)}function yy(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${hc(e)}.json`}function RD(e){return hc(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function by(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function hc(e){return Q7("sha256").update(e).digest("hex")}var vc=1,vy="language-indexes",ED=["index.db","index.scip","meta.json"],DD=[vy,fc,bc];function Nd(e){let t=[];for(let n of ED)cee(e,n),t.push(n);for(let n of DD)TD(e,n,t);return{version:vc,files:t.sort()}}function Ad(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!ED.includes(e)&&!DD.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function Qn(e,t){let n=Ad(t),r=Sy(e),i=Sy(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${aee}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function TD(e,t,n){let r=oee(e,t),i;try{i=iee(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?TD(e,s,n):o.isFile()&&n.push(Ad(s))}}function cee(e,t){let n=Qn(e,t),r;try{r=ree(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(see(Sy(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as Ry,writeFileSync as Cy}from"fs";import{create as xc}from"@bufbuild/protobuf";import{deserializeSCIP as wy,serializeSCIP as ky,DocumentSchema as hee,IndexSchema as ND,MetadataSchema as yee,SymbolInformationSchema as bee}from"@c4312/scip";import{readFileSync as lee,writeFileSync as uee}from"fs";import{create as LD}from"@bufbuild/protobuf";import{deserializeSCIP as dee,DocumentSchema as pee,IndexSchema as mee,serializeSCIP as fee,SymbolRole as gee}from"@c4312/scip";function FD(e){let t;try{t=dee(lee(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=xy(t);return n.removedDefinitionOccurrences>0&&uee(e,Buffer.from(fee(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function xy(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&gee.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(LD(pee,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:LD(mee,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function AD(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=vee(e),n=xee(e.flatMap(i=>i.documents??[])),r=OD(e.flatMap(i=>i.externalSymbols??[]));return xc(ND,{metadata:t,documents:n,externalSymbols:r})}function _D(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>wy(Ry(i))),r=AD(n);return Cy(t,Buffer.from(ky(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function MD(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>wy(Ry(i))),r=xy(AD(n));return Cy(t,Buffer.from(ky(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function See(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return xc(ND,{metadata:xc(yee,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function $D(e,t,n){let r=wy(Ry(e)),i=See(r,t,n);Cy(e,Buffer.from(ky(i)))}function vee(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 xee(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,xc(hee,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Ree([...r.occurrences,...n.occurrences]),symbols:OD([...r.symbols,...n.symbols]),text:wee(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ree(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function OD(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,xc(bee,{symbol:r.symbol,documentation:kee([...r.documentation,...n.documentation]),relationships:Cee([...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 Cee(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 wee(e,t){return e?t?e.length>=t.length?e:t:e:t}function kee(e){return[...new Set(e)]}var Ty=1,HD="SCIP_QUERY_SHARED_CACHE",Py=JSON.stringify({cliVersion:Fe,artifactCatalogVersion:vc,sqliteGenerationStoreVersion:bs,typescriptFragmentStoreVersion:Td,typescriptOverlayStoreVersion:Fd}),YD="manifest.json",QD="shared-cache.json",Ly=[vy,fc,bc];function ai(e,t){if(!e.clean||!e.treeOid)return;let n=kc(JSON.stringify({version:Ty,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Py}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Py,generationId:n,repositoryCacheDir:uc(e.repositoryId)}}function Cs(e,t,n){if(process.env[HD]==="0")return`${HD}=0`;if(!dc(n))return"explicit cache or database override";if(Tn(t)!==Tn(z(ys(e),"index.db")))return"index database is outside the managed worktree cache"}function ws(e,t){if(!dc(t))return;let n=Wt(e);return n?z(uc(n.repositoryId),"evidence.db"):void 0}function Ln(e,t=!0){let n=Fy(e),r;try{r=Nee(Kt(z(n,YD),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=Qn(n,i.path),s=Tee(o);if(!s.isFile()||s.size!==i.size||kc(Kt(o))!==i.sha256)return null}}catch{return null}return r}function _d(e){let t=Ln(e.snapshot);if(t)return t;if(!Rs(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=WD(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Nd(e.sourceCacheDir),i=z(e.snapshot.repositoryCacheDir,"generations");kr(i,{recursive:!0});let o=VD(z(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let p=Qn(e.sourceCacheDir,d),m=Qn(o,d);wc(p,m);let f=Kt(m);s.push({path:d,size:f.byteLength,sha256:kc(f)})}let a=JD(Kt(z(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=Ny(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(WD(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Ty,artifactCatalogVersion:vc,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:a,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((d,p)=>d.path.localeCompare(p.path))};he(z(o,YD),l,{spacing:2,trailingNewline:!0});let u=Fy(e.snapshot);try{if(si(u)&&!Ln(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;io(u,d),oi(d,{recursive:!0,force:!0})}io(o,u)}catch(d){let p=Ln(e.snapshot);if(p)return p;throw d}return l}finally{oi(o,{recursive:!0,force:!0})}}function vs(e){let t=Fy(e.snapshot);kr(e.targetCacheDir,{recursive:!0});let n=to(z(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=VD(z(e.targetCacheDir,".shared-hydrate-")),Bee(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=Qn(t,c.path),u=Qn(r,c.path);wc(l,u);let d=Kt(u);if(d.byteLength!==c.size||kc(d)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=Ny(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&$D(Qn(r,c.path),e.manifest.scipProjectRoot,s);if(!Rs(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=$ee(e.targetCacheDir,r),o=!0,Oee(r,e.targetCacheDir,i),kd({tempOutputScip:z(r,"index.scip"),tempOutputDb:z(r,"index.db"),tempMetaPath:z(r,"meta.json"),outputScip:z(e.targetCacheDir,"index.scip"),outputDb:z(e.targetCacheDir,"index.db"),metaPath:z(e.targetCacheDir,"meta.json"),now:e.now});let a=hn(z(e.targetCacheDir,"index.db"),z(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);xs(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&jee(e.targetCacheDir,i),s}finally{r&&oi(r,{recursive:!0,force:!0}),n.release()}}function XD(e,t,n){let r=Cs(e,n.dbPath,t);if(r)return{kind:"bypassed",reason:r};try{let i=Wt(e);if(!i)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!i.clean)return Ey(i,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let o=t.languages??gn(e),s=_i(e,o,nT(t)),a=ai(i,s);if(!a)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let c=Ln(a);if(c)return vs({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:a.generationId};let l=Aee(a,e);return l?(c=l.manifest,vs({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:a.generationId,sourceProjectRoot:l.sourceProjectRoot}):(Ey(i,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(i){return{kind:"failed",reason:i instanceof Error?i.message:String(i)}}}function ZD(e,t,n){let r=Cs(e,n.dbPath,t);if(r)return{kind:"bypassed",reason:r};try{let i=Wt(e);if(!i)return{kind:"missed",reason:"Git worktree identity is unavailable"};let o=t.languages??gn(e),s=_i(e,o,nT(t)),a=ai(i,s);if(!a)return Ey(i,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let c=Ln(a);if(c)return Rs(n.cacheDir,e,s)?(xs(a,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(vs({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:a.generationId});let l=Md(n.cacheDir);return l?.status!=="complete"||JSON.stringify(l.fingerprint)!==JSON.stringify(s)||JSON.stringify([...l.indexedLanguages??[]].sort())!==JSON.stringify([...o].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Rs(n.cacheDir,e,s)?(_d({snapshot:a,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let u=Wt(e);return(u?ai(u,s):void 0)?.generationId===a.generationId}}),xs(a,n.cacheDir,"built"),{kind:"built",generationId:a.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(i){return{kind:"failed",reason:i instanceof Error?i.message:String(i)}}}async function eT(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,s=z(e.repositoryCacheDir,"locks"),a=z(s,`${e.generationId}.lock`);for(kr(s,{recursive:!0});i()<=o;){if(Ln(e))return{kind:"generation-ready"};let c=Dy();try{let l=GD(a,"wx");try{zD(l,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
915
- `)}finally{UD(l)}return{kind:"owner",release:()=>{try{let u=JSON.parse(Kt(a,"utf8"));u.pid===process.pid&&u.token===c&&Iy(a)}catch{}}}}catch(l){if(l.code!=="EEXIST")return{kind:"timeout"};let u=rT(a);if(u&&(u.pid===void 0||!xe(u.pid))){Mee(a,u);continue}await Lee(r)}}return Ln(e)?{kind:"generation-ready"}:{kind:"timeout"}}function xs(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Cc(i)};return iT(e.repositoryCacheDir,o,!0),o}function Ey(e,t,n,r=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:n,...i?{lastReason:i}:{},lastSeenAt:(r??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:Cc(o)};return iT(uc(e.repositoryId),s,!1),s}function Cc(e){return kc(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Tn(e.projectRoot),localCacheDir:Tn(e.localCacheDir)}))}function tT(e,t,n=void 0){try{let r=JSON.parse(Kt(z(t,QD),"utf8"));if(r.version!==1||typeof r.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(r.repositoryId)||typeof r.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(r.worktreeId))return null;let i=z(uc(r.repositoryId),"worktrees",`${r.worktreeId}.json`),o=JSON.parse(Kt(i,"utf8")),s=Wt(e);if(!s?.clean||!s.treeOid||o.version!==1||o.repositoryId!==r.repositoryId||o.worktreeId!==r.worktreeId||o.repositoryId!==s.repositoryId||o.worktreeId!==s.worktreeId||Tn(o.projectRoot)!==Tn(s.projectRoot)||o.treeOid!==s.treeOid||Tn(o.localCacheDir)!==Tn(t)||o.ownershipChecksum!==Cc(o))return null;let a=Md(t);if(!Hee(a?.fingerprint))return null;let c=ai(s,a.fingerprint);if(!c||o.baseGenerationId!==c.generationId||o.activeGenerationId!==c.generationId||!Rs(t,e,c.fingerprint,!0,!1))return null;let l=(n??(()=>new Date))();if(Number.isFinite(Date.parse(o.lastSeenAt))&&l.getTime()-Date.parse(o.lastSeenAt)<6e4)return o;let u=mc(c.repositoryCacheDir,{waitMs:5e3});if(!u)return null;try{o.lastSeenAt=l.toISOString(),he(i,o,{spacing:2,trailingNewline:!0})}finally{u.release()}return o}catch{return null}}function Nee(e){let t=JSON.parse(e);if(t.version!==Ty||t.artifactCatalogVersion!==vc||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Py||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Ad(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function wc(e,t){kr(KD(t),{recursive:!0});try{jD(e,t,Iee.COPYFILE_FICLONE)}catch{jD(e,t)}}function Aee(e,t){for(let n of su(t)){if(Tn(n.path)===Tn(t))continue;let r=ys(n.path),i=Md(r);if(!(i?.status!=="complete"||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&Rs(r,n.path,e.fingerprint))try{return{manifest:_d({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}),sourceProjectRoot:n.path}}catch{continue}}return null}function _ee(e,t,n){kr(e,{recursive:!0}),he(z(e,QD),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function WD(e){try{let t=Nd(e),n=qD("sha256");for(let r of t.files){let i=Kt(Qn(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function Md(e){try{return JSON.parse(Kt(z(e,"meta.json"),"utf8"))}catch{return}}function nT(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function Fy(e){return z(e.repositoryCacheDir,"generations",e.generationId)}function rT(e){try{let t=Kt(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function Mee(e,t){let n=`${e}.reclaim`,r=Dy(),i;try{i=GD(n,"wx")}catch{return!1}try{zD(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
916
- `)}finally{UD(i)}try{let o=rT(e);return!o||o.raw!==t.raw||o.pid!==void 0&&xe(o.pid)?!1:(Iy(e),!0)}catch{return!1}finally{try{let o=JSON.parse(Kt(n,"utf8"));o.pid===process.pid&&o.token===r&&Iy(n)}catch{}}}function iT(e,t,n){let r=mc(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!si(z(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=z(e,"worktrees");kr(i,{recursive:!0}),he(z(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),_ee(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function $ee(e,t){let n=z(t,".rollback"),r=new Map,i=new Map;kr(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=z(e,a),l=si(c);r.set(a,l),l&&wc(c,z(n,"stable",a))}for(let a of Ly){let c=z(e,a),l=si(c);if(l){let u=Pee(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=z(e,wd),s=si(o);return s&&oT(o,z(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function Oee(e,t,n){for(let r of Ly){let i=z(t,r);if(n.managedDirectories.get(r)){let s=z(n.root,"managed",r);kr(KD(s),{recursive:!0}),io(i,s)}let o=z(e,r);si(o)&&io(o,i)}}function jee(e,t){for(let i of Ly){let o=z(e,i),s=z(t.root,"managed",i);t.managedDirectories.get(i)?si(s)&&(oi(o,{recursive:!0,force:!0}),io(s,o)):oi(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=z(e,i);if(!o){oi(s,{force:!0});continue}let a=`${s}.shared-restore-${Dy()}`;wc(z(t.root,"stable",i),a),oi(s,{force:!0}),io(a,s)}let n=z(e,wd);oi(n,{recursive:!0,force:!0});let r=z(t.root,"sqlite-generations");t.generationStoreExisted&&si(r)&&io(r,n)}function oT(e,t){kr(t,{recursive:!0});for(let n of Eee(e,{withFileTypes:!0})){let r=z(e,n.name),i=z(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?oT(r,i):n.isFile()&&wc(r,i)}}function Bee(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Rs(e,t,n,r=!0,i=!0){try{let o=Md(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return Rc("source validation rejected metadata"),!1;let s=Nd(e),a=hn(z(e,"index.db"),z(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return Rc(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new Fee(z(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=Ny(t),d=(i?s.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=JD(Kt(Qn(e,p))).metadata?.projectRoot;return m!==l&&Rc(`source validation rejected SCIP root for ${p}: ${String(m)}`),m===l});return d||Rc("source validation rejected SCIP project roots"),d}catch(o){return Rc(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Rc(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Ny(e){try{return BD(Dee(e)).href}catch{return BD(Tn(e)).href}}function Hee(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function kc(e){return qD("sha256").update(e).digest("hex")}function Me(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Ir(e=Me()){let t=ut(e),n=zt(e,t),r=process.env.SCIP_QUERY_INDEX_DB;if(r)return{projectRoot:e,config:t,paths:n,dbPath:r,dbPathSource:"env"};if(Ay(n.dbPath))return{projectRoot:e,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured"};let i=qee(e,"index.db");return{projectRoot:e,config:t,paths:n,dbPath:i,dbPathSource:"root-fallback",rootFallbackWarning:zee(i,n.dbPath)}}function ks(e){return Ir(e).dbPath}function $d(e,t,n){return Ay(n.dbPath)&&tT(e,n.cacheDir)?{kind:"local-fresh"}:En(e,t,n).state==="fresh"?ZD(e,t,n):XD(e,t,n)}function sT(e){return!e.startsWith("__")&&!Uee.has(e)}var Uee=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function Vee(){try{return Gee(Me(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function Gee(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s}=Ir(e);if(!Ay(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let a={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:ws(e,n),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,coverageContracts:n.coverageContracts,docs:n.docs},c=ni(e);return new Gt(a,c)}function zee(e,t){let n="unknown time";try{n=Wee(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function Ee(e){let t=Vee();try{return e(t)}finally{t.close()}}function _y(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 My(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 Kee(e)}}function Kee(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawn as Jee,spawnSync as N$e}from"child_process";var Is=class extends Error{constructor(n,r){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r}label;timeoutMs;timedOut=!0};function aT(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Od(e){return new Promise((t,n)=>{let r=e.maxBuffer??10485760,i=Jee(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=e.timeoutMs&&e.timeoutMs>0?setTimeout(()=>d(new Is(e.label,e.timeoutMs)),e.timeoutMs):null,d=p=>{l||(l=!0,u&&clearTimeout(u),i.kill(),n(p))};i.stdout.on("data",p=>{if(a+=p.length,a>r){d(new Error(`${e.label} exceeded stdout buffer limit (${r} bytes).`));return}o.push(p)}),i.stderr.on("data",p=>{if(c+=p.length,c>r){d(new Error(`${e.label} exceeded stderr buffer limit (${r} bytes).`));return}s.push(p)}),i.on("error",d),i.on("close",p=>{if(l)return;l=!0,u&&clearTimeout(u);let m=Buffer.concat(s).toString("utf8").trim();if(p!==0){n(new Error(`${e.label} failed${m?`:
917
- ${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(f){n(new Error(`${e.label} returned invalid JSON: ${f instanceof Error?f.message:f}`))}})})}async function $y(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function cT(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}function Rt(e){return e+1}function dt(e,t){return`${Rt(e)}-${Rt(t)}`}function ye(e,t,n){return`${e}:${dt(t,n)}`}function jd(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var O={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)}};import{spawnSync as Yee}from"child_process";import{existsSync as Qee,mkdirSync as Xee,readFileSync as Zee,renameSync as ete,writeFileSync as tte}from"fs";import{dirname as lT,join as nte}from"path";var Bd=3,rte="health-report-cache.json";function Oy(e,t,n,r=ate()){let i=Ye(e);return i?{version:Bd,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function uT(e,t,n=fT()){let r=pT(e),i=mT(t),o=!1;return D("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFileSync(r,"utf8"));return!ite(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function dT(e,t,n,r=fT()){let i=pT(e),o={version:Bd,keyHash:mT(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(lT(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function pT(e){return nte(lT(e.config.dbPath),rte)}function mT(e){return Ge(JSON.stringify(e))}function ite(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Bd&&typeof t.keyHash=="string"&&ote(t.key)&&typeof t.writtenAt=="string"&&ste(t.report)}function ote(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Bd&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function ste(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorPrecision)}function ate(){return{gitHead(e){let t=Yee("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"});return t.status===0?t.stdout.trim():null}}}function fT(){return{existsSync:Qee,mkdirSync:Xee,readFileSync:Zee,renameSync:ete,writeFileSync:tte,nowIso:()=>new Date().toISOString()}}var Ic="__health-phase",Wd="__diff-impact-batch",lte=10,ute=4,dte=8,pte=25e3,mte=2500,jy=2500,fte=4,gte=12,gT=3e4,yT=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),bT=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),hte=new Set([...bT,"suppressions"]),yte=new Set(["similar","extract-candidates"]),Hd=2,hT=Ci({kind:"health-semantic-prewarm",invalidation:pe("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:bte});function bte(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==Hd||typeof n.definitions!="number"||!Number.isFinite(n.definitions)||typeof n.referenceCacheWrites!="number"||!Number.isFinite(n.referenceCacheWrites)||typeof n.referenceIncomplete!="number"||!Number.isFinite(n.referenceIncomplete)||typeof n.calleeRows!="number"||!Number.isFinite(n.calleeRows)||typeof n.warmedAt!="number"||!Number.isFinite(n.warmedAt)?null:{version:Hd,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Jt(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
918
- `)}function Ste(e){let t=Ut(e);return t.symbols>=pte||t.documents>=mte}function qd(e,t,n,r={}){return Ste(e)?n?(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(r.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${jy} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:jy,semantic:!1,analysisBudget:{scanLimit:jy,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function ST(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var vte={env:process.env,projectFingerprint:Ye,semanticEngineFingerprint:wte,readMarker:(e,t,n)=>hT.read(e,t,n),writeMarker:(e,t,n,r)=>hT.write(e,t,n,r),candidateDefinitions:(e,t)=>new B(e).scopedDefinitions(t.scope).filter(n=>nt(n.relativePath)!==null),materializeReferences:(e,t,n)=>St(e).materializeReferences(t,n),materializeCallees:Pw};function xte(e,t,n=vte){if(t.full!==!0)return ci("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return ci("disabled");let r=ci("error");return D("health.semantic-prewarm",()=>{try{r=Rte(e,t,n)}catch(i){r=ci("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>kte(r))}function Rte(e,t,n){let r=n.projectFingerprint(e);if(!r)return ci("missing-project-fingerprint");let i=Cte(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return ci("cache-hit");let s=[];if(s=D("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return ci("no-semantic-definitions");let a=0,c=D("health.semantic-prewarm.references",()=>{let p=n.materializeReferences(e,s,{prefetchCallees:!0});return a=p.cacheHits+p.cacheWrites+p.inMemoryHits,p},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return ci("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=D("health.semantic-prewarm.callees",()=>{let p=n.materializeCallees(e,s);return u=p.size,p},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(D("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:Hd,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function Cte(e,t){return JSON.stringify({version:Hd,cliVersion:Fe,semanticEngineFingerprint:t,scope:e.scope??null})}function wte(e){return Ge(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Ni(e.config.projectRoot)}))}function ci(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function kte(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}async function Ud(e){let t=Lte(e),n={...e,phaseTimeoutMs:t??null},r=Ee(p=>{let m=Oy(p,n,Fe);if(!m)return null;let f=uT(p,m);return f?(f.detectorPrecision=Vh(ps(p),Date.now()),f):null});if(r)return r;let{applicability:i,overview:o}=Ee(p=>({applicability:Ite(p,e),overview:lc(p,"overview",e)})),s=new Map;s.set("overview",o);let a=ms.filter(p=>p==="overview"?!1:Pte(p,i)?!0:(s.set(p,oo(p)),!1)),c=Ete(a);e.full&&Ee(p=>xte(p,e));let l=await $y(c,Fte(c.length),p=>Dte(p,e,t)),u=[];if(l.flat().forEach(p=>{p.healthPhaseMeta&&u.push(`Health phase "${p.phase}" deferred: ${p.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),s.set(p.phase,p)}),u.length>0){let p=s.get("overview");s.set("overview",{...p,warnings:[...p.warnings,...u]})}let d=Kh(ms.map(p=>s.get(p)));return d.detectorPrecision=Ee(p=>Vh(ps(p),Date.now())),Ee(p=>{let m=Oy(p,n,Fe);m&&dT(p,m,d)}),d}function Ite(e,t){return xl(e,{scope:t.scope})}function Pte(e,t){return yT.has(e)?t.react:bT.has(e)?t.vue:!0}function Ete(e){return cT(e,[yT,hte,yte])}function oo(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function Dte(e,t,n){if(e.length===1)return Tte(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??Hy(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Od({cliPath:i,command:Ic,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof Is))throw s;return e.map(a=>vT(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function Tte(e,t,n){let r=process.argv[1]??Hy(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Od({cliPath:r,command:Ic,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof Is))throw o;return vT(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function Lte(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return gT;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?gT:r===0?void 0:r}function vT(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...oo(e),...r};case"react-hook-candidates":return{...oo(e),...r};case"react-large-component-pressure":return{...oo(e),...r};case"vue-component-duplicates":return{...oo(e),...r};case"vue-composable-candidates":return{...oo(e),...r};case"vue-large-view-pressure":return{...oo(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var Fte=CT({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:fte,defaultMaximum:gte});function xT(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
919
- Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
920
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Xn(e.overview.indexSizeBytes)}
921
- `),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.twinDriftGroups>0&&console.log(` Drifted twins: ${n.twinDriftGroups} group(s)`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${By(n.reactHookCandidatePairs,n.reactHookCandidateScoreCount)} candidate pair(s)`),n.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${n.reactLargeComponentPressureFiles} component(s)`),n.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${n.vueComponentDuplicatePairs} duplicate pair(s)`),n.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${By(n.vueComposableCandidatePairs,n.vueComposableCandidateScoreCount)} candidate pair(s)`),n.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${n.vueLargeViewPressureFiles} file(s)`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${By(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
922
- 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 involved)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
923
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(_te(e),Ate(e),e.scoreBreakdown.length>0){console.log(`
924
- 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(e.warnings&&e.warnings.length>0?`
925
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
926
- No issues found. Codebase is clean.`)}function By(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${Nte(t)} score-weighted)`}function Nte(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Ate(e){if(e.pressure.length!==0){console.log(`
927
- Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function _te(e){let t=e.axes;if(console.log(`
928
- Axes:`),console.log(` Zero-reference candidates: ${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})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function RT(e){let t=Ee(i=>{let o=zn(i,{base:e.base});return o.note?{kind:"complete",result:os(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:os(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=aT(t.plan.changedFiles,lte),r=await $y(n,Mte(n.length),i=>jte(i,e));return Qu(t.plan.changedFiles,r)}var Mte=CT({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:ute,defaultMaximum:dte});function CT(e){return(t,n=process.env,r=cte)=>$te(t,n,r,e)}function $te(e,t,n,r){let i=t[r.envKey],o=Ote(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function Ote(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function jte(e,t){let n=process.argv[1]??Hy(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Od({cliPath:n,command:Wd,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function wT(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}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),O.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
929
- Affected consumer files:`),O.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}var so=_y,L=(e=>parseInt(e,10)),Pr=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),yn=parseFloat,Ps=parseInt;function S(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function Wy(){return S("--json","Output as JSON for programmatic consumption")}function j(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Wy()]}function N(e,t=[]){return{category:e,examples:t}}import{execFileSync as aL,spawn as Qne}from"child_process";import{existsSync as uo,mkdirSync as rb,readFileSync as cL,rmSync as Xne,writeFileSync as ep}from"fs";import{homedir as Zne}from"os";import{dirname as tp,isAbsolute as ere,join as Lc,resolve as tre}from"path";import{execFileSync as xne}from"child_process";import{createRequire as Bte}from"module";var Hte=Bte(import.meta.url);function kT(e,t=[]){let n=Wte(),r=Qf(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 Wte(){try{return Hte.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Es,spawnSync as Ute}from"child_process";import{existsSync as Fn,mkdtempSync as DT,readFileSync as Vte,readdirSync as Gte,rmSync as TT,symlinkSync as zte,writeFileSync as Kte}from"fs";import{tmpdir as LT}from"os";import{join as Nt}from"path";import{spawnSync as qte}from"child_process";function Er(e,t=qte){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}var Jte=3e5,Yte=12;function Vy(e,t,n={}){let r=Gy(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:qy(e),batches:[]};let i=ene(t,r),o=n.timeoutMs??Jte,s=one(e,t),a=qy(e),c=DT(Nt(LT(),"scip-cleanup-verify-")),l=[],u=new Map;try{Es("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),sne(e,c);for(let d of r)u.set(d.label,PT(d,c,o).rawErrors);for(let d of t.batches){NT(c,d);let p=null;for(let m of r){let f=PT(m,c,o),g=Qte(f,u.get(m.label)??[],f.rawErrors);if(g.status==="failed"){let h=g.errors.length>0?g.errors:f.outputTail;p={depth:d.depth,status:"failed",reason:`${m.label}: ${g.reason}`,errors:h.slice(0,Yte)};break}}if(!p)l.push({depth:d.depth,status:"verified"});else{l.push(p);break}}}finally{try{Es("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{TT(c,{recursive:!0,force:!0})}}return{checkers:r.map(d=>d.label),uncoveredFiles:i,baselineErrors:[...u.values()].reduce((d,p)=>d+p.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Qte(e,t,n){let r=Xte(t,n);return r.length>0?{status:"failed",reason:"checker reported new errors",errors:r}:e.ok?{status:"verified",reason:"checker passed",errors:[]}:{status:"failed",reason:`checker exited ${e.exitCode===null?"unknown":String(e.exitCode)} with unparsed output`,errors:[...e.outputTail??[]]}}function Xte(e,t){let n=Zte(e),r=new Map,i=[];for(let o of t){let s=FT(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Zte(e){let t=new Map;for(let n of e){let r=FT(n);t.set(r,(t.get(r)??0)+1)}return t}function ene(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 FT(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var IT=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],tne=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Gy(e){let t=[];if(Fn(Nt(e,"tsconfig.json"))){let n=Nt(e,"node_modules",".bin","tsc");t.push(Fn(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:IT,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:IT,strength:"reference-aware"})}if(Fn(Nt(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>Fn(Nt(e,n)))){let n=nne();n&&t.push(n)}if(tne.some(n=>Fn(Nt(e,n)))){let n=rne(e);n&&t.push(n)}for(let n of ine(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:Nt(e,n,"..","target")}});return t}function nne(){return Er("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--output-format","json","--select","E9,F821,F822","."],coversExtensions:[".py"],strength:"reference-aware"}:Er("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function rne(e){let t=Nt(e,"node_modules",".bin","clj-kondo");return Fn(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Mn],strength:"reference-aware"}:Er("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Mn],strength:"reference-aware"}:Er("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Mn],strength:"reference-aware"}:null}function ine(e){let t=[];if(Fn(Nt(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Gte(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||Fn(Nt(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function one(e,t){let n=new Set(qy(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function qy(e){let t;try{t=Es("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
930
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function sne(e,t){for(let n of["node_modules"]){let r=Nt(e,n),i=Nt(t,n);if(Fn(r)&&!Fn(i))try{zte(r,i,"junction")}catch{}}}function NT(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=Nt(e,r);Fn(o)&&Kte(o,ane(Vte(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function zy(e,t){for(let n of t)NT(e,n)}function AT(e,t){let n=DT(Nt(LT(),"scip-cleanup-patch-"));try{return Es("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),zy(n,t),Es("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Es("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{TT(n,{recursive:!0,force:!0})}}}function Ky(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(r=>r.depth===t.batch);return n?[n]:[]}return[...e.batches]}function Jy(e,t,n={}){let r=[];e.checkers.length===0&&r.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&r.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&r.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let i=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)i.has(o.depth)||r.push(`Batch ${o.depth} is not verified by the detected checker(s).`);return r}function ane(e,t,n={}){let r=e.split(`
931
- `),i=(n.rust===!0?cne(e):kt(e)).split(`
932
- `),o=new Set;for(let s of t){let a=lne(r,s.start),c=dne(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(`
933
- `)}function cne(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 lne(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 une=200;function dne(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>une)break}return n}function PT(e,t,n){let r=Ute(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
934
- ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:ET(i)};let o=pne(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(vne),diagnostics:s,parseBasis:o.parseBasis,outputTail:ET(i)}}function pne(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:mne(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:fne(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=gne(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:hne(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:yne(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:bne(t),parseBasis:"clj-kondo-json"}:{diagnostics:Sne(t),parseBasis:"heuristic"}}function mne(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function fne(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function gne(e){let t=_T(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function hne(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function yne(e){let t=[];for(let n of e.split(`
935
- `)){if(!n.trim().startsWith("{"))continue;let r=Uy(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(d=>!!d&&typeof d=="object"&&d.is_primary===!0),u=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:u&&typeof u=="object"&&typeof u.code=="string"?String(u.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function bne(e){let t=_T(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function Sne(e){return e.split(`
936
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function vne(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function _T(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Uy(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Uy(t.slice(n)):null}function Uy(e){try{return JSON.parse(e)}catch{return null}}function ET(e,t=10){return e.split(`
937
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var OT={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},Rne={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},Cne={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function bn(e,t){let n=t.languages??gn(e),r=n.map(a=>{let c=jo(fr(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=Lne(e,n,t),o=Yy({semantics:i},"typescript"),s=Gy(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:Ane(e)}}function li(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>Ene(e,c,{hasIndexedGraph:Dne(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...wne(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function wne(e){return kne(e).map(t=>{let n=Yy(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Ine(t)} semantic provider`,status:r,evidence:"semantic",reason:Pne(t,n)}})}function kne(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of BT(e))t.add(n.language);return[...t].sort((n,r)=>MT(n)-MT(r))}function MT(e){return e==="typescript"?0:1}function Ine(e){return e==="typescript"?"TypeScript":"Rust"}function Pne(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function Ene(e,t,n){let r=e.indexers.find(u=>u.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=Tne(t,n.runtimeProbe),a=Fne(e,t),c=Nne(e,t),l=c.length===0?"unavailable":c.every(u=>u.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(u=>u.label).join(", "):`No detected checker covers ${OT[t].join(", ")} files.`}}}function Dne(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Tne(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??$T(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=jT(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??$T(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function $T(e){let t=Rne[e];return t?ul(t):jT(e)==="regex-only"?"regex":"unavailable"}function jT(e){let t=Cne[e],n=t?hx(t):null;return n?.imports??n?.exports??n?.reExports??null}function Lne(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...kT(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Bo(e)}),r}function BT(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Yy(e,t){return BT(e).find(n=>n.language===t)}function Fne(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=Yy(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function Nne(e,t){let n=new Set(OT[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function Ane(e){try{return xne("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as _ne,existsSync as Ds,readFileSync as Ts,rmSync as qT,writeFileSync as Xy}from"fs";import{join as co}from"path";var ao="<!-- scip-query:agent-setup:begin -->",Vd="<!-- scip-query:agent-setup:end -->",Qy="# scip-query:agent-setup";function Pc(){if(process.stdin.isTTY)return"";try{return Ts(0,"utf-8")}catch{return""}}function Gd(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Ec(e){let t=nc(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
938
- `)}function zd(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Mne(e,n),t.gitHook&&$ne(e,n),n}function UT(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return WT(e,"AGENTS.md",t,n),WT(e,"CLAUDE.md",t,n),One(e,t,n),n}function Mne(e,t){let n=[ao,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For non-trivial implementation requests: plan first (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",Vd].join(`
939
- `);HT(e,"AGENTS.md",n,t);let r=Ds(co(e,"CLAUDE.md"))?Ts(co(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ao)){t.unchanged.push("CLAUDE.md");return}let i=[ao,"@AGENTS.md",Vd].join(`
940
- `);HT(e,"CLAUDE.md",i,t)}function HT(e,t,n,r){let i=co(e,t),o=Ds(i)?Ts(i,"utf-8"):"",s;if(o.includes(ao)){let a=new RegExp(`${ao}[\\s\\S]*?${Vd}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
941
-
942
- `)}${n}
943
- `:`${n}
944
- `;s===o?r.unchanged.push(t):(Xy(i,s),r.written.push(t))}function WT(e,t,n,r){let i=co(e,t);if(!Ds(i)){r.unchanged.push(t);return}let o=Ts(i,"utf-8");if(!o.includes(ao)){r.unchanged.push(t);return}let s=new RegExp(`${ao}[\\s\\S]*?${Vd}`),a=o.replace(s,"").replace(/\n{3,}/g,`
945
-
946
- `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?qT(i,{force:!0}):Xy(i,`${a}
947
- `))}function $ne(e,t){let n=co(e,".git","hooks");if(!Ds(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=co(n,"pre-commit"),i=["#!/bin/sh",Qy,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
948
- `);if(Ds(r)){let o=Ts(r,"utf-8");if(o.includes(Qy)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}Xy(r,i),_ne(r,493),t.written.push(".git/hooks/pre-commit")}function One(e,t,n){let r=co(e,".git","hooks","pre-commit");if(!Ds(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Ts(r,"utf-8").includes(Qy)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||qT(r,{force:!0})}import{createHash as jne}from"crypto";import{existsSync as Jd,mkdirSync as Bne,readFileSync as Yd,readdirSync as Hne,rmSync as VT,writeFileSync as GT}from"fs";import{join as Dr}from"path";var Qd=Dr(".scipquery","events"),Wne=Dr(".scipquery","ledger"),zT="events.jsonl";function KT(e){return Dr(e,Wne)}function Zy(e){return Dr(KT(e),zT)}function JT(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[Be(l.check,l.findingId),l])),a=[],c=(l,u)=>{let d=n.get(l.findingId),p=u==="resolved"?o.verifiedAgainstByFinding?.get(Be(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:u,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...p?{verifiedAgainstCommit:p}:{},...d?{symbol:d}:{}})};for(let l of t){let u=s.get(Be(l.check,l.findingId));if(!u){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}u.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function YT(e){return eb(e,"HEAD")}function eb(e,t){try{let n=Vt(e,["rev-parse","--verify",`${t}^{commit}`]).trim();return/^[0-9a-f]{40}$/.test(n)?n:null}catch{return null}}function QT(e){try{return Vt(e,["status","--porcelain=v1","--untracked-files=all"]).trim()===""}catch{return!1}}function XT(e,t){let n=Zy(e),r=Jd(n),i=[...r?ZT(n):[],...t];if(i.length>0){let o=Dr(e,Qd);Bne(o,{recursive:!0});for(let s of i)qne(o,s)}r&&Une(e)}function qne(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
949
- `,r=jne("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Dr(e,`${t.ts}-${r}.json`);try{GT(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Yd(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function Une(e){VT(Zy(e));let t=Dr(KT(e),".gitattributes");if(!Jd(t))return;let n=Yd(t,"utf-8").split(`
950
- `).filter(r=>r.trim()!==`${zT} merge=union`).join(`
951
- `).replace(/^\n+|\n+$/g,"");n===""?VT(t):GT(t,`${n}
952
- `)}function Xd(e){let t=[],n=Dr(e,Qd);if(Jd(n))for(let i of Hne(n).sort()){if(!i.endsWith(".json"))continue;let o=eL(Yd(Dr(n,i),"utf-8"));o&&t.push(o)}let r=Zy(e);return Jd(r)&&t.push(...ZT(r)),Vne(t)}function ZT(e){let t=[];for(let n of Yd(e,"utf-8").split(`
953
- `)){let r=eL(n);r&&t.push(r)}return t}function eL(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return zne(t)?t:null}function Vne(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||Kd(n)>Kd(i)||Kd(n)===Kd(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Dc(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function Kd(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var Gne=["caught","resolved","suppressed","reopened"];function zne(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&Gne.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Zd(e,t,n={}){let r=(n.now??Date.now)(),i=Jne(t),o=ps(e),s=e.config.projectRoot,a=(n.headCommit??YT)(s),c=(n.resolveCommit??eb)(s,t.base),l=Kne({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),u=XP(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let d=new Map;for(let m of t.findings)m.symbol&&d.set(m.id,m.symbol);for(let m of t.suppressed)m.finding.symbol&&d.set(m.finding.id,m.finding.symbol);for(let[m,f]of l.replaySymbols)d.set(m,f);let p=JT(o,u,d,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??XT)(s,p),{ledger:u,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(d){return{ledger:u,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${d instanceof Error?d.message:String(d)}`].filter(Boolean).join("; ")}}}function Kne(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(g=>Be(g.check,g.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!tc(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(g=>g.outcome!=="resolved"&&(a.has(g.check)||c)&&!s.has(Be(g.check,g.findingId)));if(lo(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let u;try{u=(e.runtime.readEvents??Xd)(e.projectRoot)}catch(g){for(let h of l)r.add(Be(h.check,h.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${g instanceof Error?g.message:String(g)}`}}let d=new Map;for(let g of u){let h=Be(g.check,g.findingId),y=d.get(h)??[];y.push(g),d.set(h,y)}let p=new Map;for(let g of l){let h=Be(g.check,g.findingId),y=Dc(d.get(h)??[]),x=y?.comparisonBaseCommit??y?.commit;if(lo(`candidate ${h} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!y?.comparisonBaseCommit&&y?.commit&&y.commit===e.commit){n.add(g.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(h);continue}if(x===e.comparisonBaseCommit){n.add(g.check);continue}let R=p.get(x)??[];R.push(g),p.set(x,R)}if(p.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let m=(e.runtime.worktreeIsClean??QT)(e.projectRoot);if(lo(`replay groups=${p.size} clean=${m} callback=${!!e.runtime.replayGate}`),!m||!e.runtime.replayGate){for(let g of p.values())for(let h of g)r.add(Be(h.check,h.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let f=[];for(let[g,h]of p){let y;try{y=e.runtime.replayGate(g),lo(`replay base=${g} checks=${y.checksRun.join(",")} findings=${y.findings.length} suppressed=${y.suppressed.length}`)}catch(b){for(let v of h)r.add(Be(v.check,v.findingId));f.push(`cross-HEAD outcome verification deferred for ${g.slice(0,12)}: ${b instanceof Error?b.message:String(b)}`);continue}let x=new Set(y.checksRun),R=Yne(y);for(let b of h){let v=Be(b.check,b.findingId);if(!x.has(b.check)){r.add(v);continue}n.add(b.check);let w=R.find(k=>k.key===v);if(w){lo(`replay retained exact ${v}`),t.push(w.observed),w.symbol&&o.set(w.observed.findingId,w.symbol);continue}let I=Dc(d.get(v)??[]),C=I?.symbol?R.find(k=>k.check===b.check&&k.symbol===I.symbol):void 0;if(C){lo(`replay moved ${v} -> ${C.key}`),t.push(C.observed),C.symbol&&o.set(C.observed.findingId,C.symbol);continue}i.set(v,g),lo(`replay verified ${v} against ${g}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...f.length>0?{warning:f.join("; ")}:{}}}function lo(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Jne(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function Yne(e){return[...e.findings.map(t=>({key:Be(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:Be(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var lL="SCIP_QUERY_SKIP_HOOK_INSTALL",tb="SCIP_QUERY_STOP_HOOK_MODE",nre="scip-query hook-",rre="scip-query diff-gate --hook",tL="# scip-query:local-hooks:begin",nL="# scip-query:local-hooks:end",Tc=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Ls(e,t={}){let n=uL(),r=t.env??process.env;if(are(r))return n.skipped.push({target:"project agent hooks",reason:`${lL}=1`}),n;let i=fre(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),ore(e,n,t.dryRun),t.remove?(iL(e,Tc[0],n,{dryRun:t.dryRun}),iL(e,Tc[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(rL(e,Tc[0],n,{provider:"codex",commandPrefix:i,force:t.force}),rL(e,Tc[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&ire({homeDir:t.homeDir,result:n}),n)}function ire(e={}){let t=e.result??uL(),n=e.homeDir??Zne();return nb({configPath:Lc(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),nb({configPath:Lc(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function uL(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function rL(e,t,n,r){if(ib(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Lc(e,t.relativePath);lre({provider:r.provider,rootDir:tp(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function iL(e,t,n,r){if(ib(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}ure({configPath:Lc(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function ore(e,t,n=!1){let r=sre(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Tc.filter(u=>!ib(e,u.relativePath));if(i.length===0)return;let o=[tL,...i.map(u=>`/${u.relativePath}`),nL].join(`
954
- `),s=uo(r)?cL(r,"utf-8"):"",a=new RegExp(`${J(tL)}[\\s\\S]*?${J(nL)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
955
-
956
- `:""}${o}
957
- `;!n&&l!==s&&(rb(tp(r),{recursive:!0}),ep(r,l)),t.gitExcluded.push(...i.map(u=>u.label))}function sre(e){try{let t=aL("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?ere(t)?t:tre(e,t):null}catch{return null}}function ib(e,t){try{return aL("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function are(e=process.env){let t=e[lL];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function cre(e=process.env){let t=e[tb]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function lre(e){if(!e.createRoot&&!uo(e.rootDir))return;let t=ob(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=dre(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=uo(e.configPath);rb(tp(e.configPath),{recursive:!0}),ep(e.configPath,`${JSON.stringify(n,null,2)}
958
- `),e.result[r?"updated":"installed"].push(e.label)}function nb(e){if(!uo(e.configPath))return;let t=ob(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=dL(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Xne(e.configPath,{force:!0}):ep(e.configPath,`${JSON.stringify(o,null,2)}
959
- `)),e.result.removed.push(e.label)}function ure(e){let t=e.result.removed.length;if(nb(e),!e.writeDeclinedTombstone)return;let n=ob(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(rb(tp(e.configPath),{recursive:!0}),ep(e.configPath,`${JSON.stringify(r,null,2)}
960
- `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function ob(e,t,n){if(!uo(e))return{};try{let r=JSON.parse(cL(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function dre(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...dL(s),mre(t,o,n)]}return i}function dL(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!pre(n)):[]})).filter(t=>t.hooks.length>0)}function pre(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(nre)||t===rre)}function mre(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function fre(e){let t=Lc(e,"node_modules",".bin","scip-query");return uo(t)?t:"scip-query"}async function pL(){let e=await bre(Pc());e&&console.log(JSON.stringify(e))}function gre(e){if(Gd(e))return;let t=fL(e),n=gL(t);if(!(!n||!uo(n.paths.dbPath)))return Pre(n,r=>{let i={minTogether:6,skip:[]},o=eo(r,i),s=Zd(r,o,{replayGate:a=>eo(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function mL(){let e=gre(Pc());!e||e.findings.length===0||console.log(JSON.stringify(hre(e,cre())))}function hre(e,t="feedback"){let n=Ec(e),r=yre(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
961
-
962
- This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
963
-
964
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${tb}=feedback to ask the agent to continue without a hook error, or ${tb}=block to enforce the gate.`}}function yre(e){return Ec(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function bre(e){let t=fL(e),n=Ire(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=gL(t);if(!r)return;let i=await vre(r,n),o=n==="SessionStart"?Rre(r.projectRoot,r.config,r.paths):Cre(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
965
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var Sre={prepare:$d,ensureService:du,freshness:En,requestRefresh:bC,startOneShot(e){Qne("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function vre(e,t,n=Sre){let r=Yn(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Fe,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(xre(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function xre(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(Hn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Rre(e,t,n){let r=En(e,t,n),i=bn(e,t),s=li(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
966
- `)}function Cre(e,t={},n=process.env){if(kre(t,n)==="off")return"";let r=wre(e);return r?`scip-query routing reminder:
967
- ${r.message}`:""}var oL=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function wre(e){let t=oL.find(i=>i.skillNames.some(o=>sL(e,o)));if(t)return t;let n=0,r=[];for(let i of oL){let o=i.keywords.filter(s=>sL(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function kre(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function sL(e,t){let n=t.trim().split(/\s+/).map(r=>J(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function fL(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Ire(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function gL(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=dC(t);if(n)try{let r=ut(n),i=zt(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function Pre(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:ws(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Gt(n,ni(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as rp,mkdirSync as Nre,symlinkSync as Are,readlinkSync as cb,unlinkSync as lb,readdirSync as xL}from"fs";import{join as Zn,dirname as Ac,resolve as ui,relative as _re,isAbsolute as Mre}from"path";import{homedir as ip,platform as $re}from"os";import{fileURLToPath as RL}from"url";import{execFileSync as hL}from"child_process";import{createRequire as Ere}from"module";import{existsSync as Dre}from"fs";import{platform as Fc,arch as yL}from"os";var bL="v0.8.1",sb="https://github.com/sourcegraph/scip",SL="SCIP_QUERY_SCIP_BIN";function Tre(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[SL];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function Lre(e){let t=Ere(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function np(e=process.env){return Tre({platform:Fc(),arch:yL(),env:e,isOnPath:jn,fileExists:Dre,resolveSidecar:Lre})?.path??null}function Nc(){return np()!==null}function Fre(){let e=Fc(),t=yL(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";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:`${sb}/releases/download/${bL}/${o}`,filename:o}}function ab(){let e=Fre();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Fc()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
968
- `),console.log("Or download manually:")):Fc()==="win32"?(console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(" npm install -g scip-query-scip-windows"),console.log(`Or set ${SL} to a local scip.exe path.
969
- `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
970
- `:` ${sb}/releases/tag/${bL}
971
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function vL(e){if(Fc()==="darwin"&&jn("brew")){e("Installing scip CLI via Homebrew...");try{if(hL("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),jn("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(jn("go")){e("Installing scip CLI via go install...");try{if(hL("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),jn("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: ${sb}/releases`),!1}var Ore=$re()==="win32",op=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function sp(e={}){let t=e.quiet?()=>{}:console.log,n=RL(import.meta.url),r=ui(Ac(n),"..","skills"),i=[Zn(ip(),".claude","skills"),Zn(ip(),".codex","skills"),Zn(ip(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Ac(s);if(!rp(a))continue;Nre(s,{recursive:!0});let c=kL(s);jre(s,r,c,o,t);for(let l of op){let u=Zn(r,l),d=Zn(s,l);if(!rp(u)){o.skipped.push(`${c}/${l}`);continue}if(rp(d)){try{let p=cb(d);if(ui(p)===ui(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}lb(d)}Are(u,d,Ore?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function jre(e,t,n,r,i){let o=new Set(op);for(let s of xL(e)){if(o.has(s))continue;let a=Zn(e,s),c;try{c=ui(Ac(a),cb(a))}catch{continue}wL(c,t)&&(lb(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function CL(e={}){let t=RL(import.meta.url),n=ui(Ac(t),"..","skills"),r=e.homeDir??ip(),i=[Zn(r,".claude","skills"),Zn(r,".codex","skills"),Zn(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!rp(s))continue;let a=kL(s);for(let c of xL(s)){let l=Zn(s,c),u;try{let d=cb(l);u=ui(Ac(l),d)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!wL(u,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{lb(l)}catch(d){o.skipped.push(`${a}/${c} (${d instanceof Error?d.message:String(d)})`)}}}return o}function wL(e,t){let n=_re(ui(t),ui(e));return n===""||!n.startsWith("..")&&!Mre(n)}function kL(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as pA}from"child_process";import{performance as gi}from"perf_hooks";import{existsSync as An,readFileSync as cle,renameSync as lle,rmSync as ule,unlinkSync as dle,writeFileSync as ple}from"fs";import{dirname as Lp,extname as mle,join as go,resolve as fle}from"path";import{execFileSync as jse}from"child_process";import{createHash as Bse}from"crypto";import{closeSync as Hse,copyFileSync as bp,existsSync as Nn,mkdirSync as yp,mkdtempSync as Wse,openSync as qse,readdirSync as Use,readFileSync as Sp,renameSync as YF,rmSync as mi,statSync as Vse,writeFileSync as Gse}from"fs";import{basename as hp,dirname as we,extname as zse,join as mt,resolve as qF}from"path";import{platform as Kse}from"os";import Bre from"better-sqlite3";import{execFileSync as Hre}from"child_process";import{existsSync as Wre,readdirSync as qre,readFileSync as Ure}from"fs";import{extname as ap,join as IL}from"path";function po(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>cp({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function cp(e){let t=new Set((e.extensions??Nv).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Wre(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=ni(e.projectRoot),r=Vre(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Bre(e.dbPath);try{let o=zre(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
972
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let d=0;for(let p of u){if(o.has(p))continue;let m=Ure(IL(e.projectRoot,p),"utf-8"),f=s.run(Kre(p),p,m);d+=Number(f.changes)}return d})(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 Vre(e,t){let n=Gre(e,t);if(n)return n;let r=[],i=o=>{let s=o?IL(e,o):e,a;try{a=qre(s,{withFileTypes:!0})}catch{return}for(let c of a){if(vl.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(ap(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Gre(e,t){try{return Hre("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
973
- `).filter(r=>r&&t.has(ap(r).toLowerCase())).sort()}catch{return null}}function zre(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 Kre(e){return ap(e).toLowerCase()===".vue"?"vue":ap(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Jre}from"crypto";import{appendFileSync as Yre,existsSync as Qre,mkdirSync as Xre,readFileSync as Zre}from"fs";import{dirname as LL,join as PL}from"path";var eie="<global-symbols>";function tie(e){let t=[];for(let n of e.all(`
974
- SELECT relative_path, language, position_encoding, text
975
- FROM documents
976
- `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
977
- SELECT d.relative_path,
978
- c.chunk_index,
979
- c.start_line,
980
- c.end_line,
981
- hex(c.occurrences) AS occurrences_hex
982
- FROM chunks c
983
- JOIN documents d ON d.id = c.document_id
984
- `))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
985
- SELECT d.relative_path,
986
- r.start_line,
987
- r.start_char,
988
- r.end_line,
989
- r.end_char,
990
- g.symbol,
991
- g.display_name,
992
- g.kind,
993
- g.documentation,
994
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
995
- g.enclosing_symbol,
996
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
997
- FROM defn_enclosing_ranges r
998
- JOIN documents d ON d.id = r.document_id
999
- JOIN global_symbols g ON g.id = r.symbol_id
1000
- `))t.push({relativePath:n.relative_path,kind:"definition",values:ub(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
1001
- SELECT d.relative_path,
1002
- c.chunk_index,
1003
- m.role,
1004
- g.symbol,
1005
- g.display_name,
1006
- g.kind,
1007
- g.documentation,
1008
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
1009
- g.enclosing_symbol,
1010
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
1011
- FROM mentions m
1012
- JOIN chunks c ON c.id = m.chunk_id
1013
- JOIN documents d ON d.id = c.document_id
1014
- JOIN global_symbols g ON g.id = m.symbol_id
1015
- `))t.push({relativePath:n.relative_path,kind:"mention",values:ub(n,[n.chunk_index,n.role])});for(let n of e.all(`
1016
- SELECT g.symbol,
1017
- g.display_name,
1018
- g.kind,
1019
- g.documentation,
1020
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
1021
- g.enclosing_symbol,
1022
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
1023
- FROM global_symbols g
1024
- WHERE NOT EXISTS (
1025
- SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
1026
- ) AND NOT EXISTS (
1027
- SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
1028
- )
1029
- `))t.push({relativePath:eie,kind:"global-symbol",values:ub(n)});return nie(t)}function nie(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=Jre("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
1030
- `);n.set(r,o.digest("hex"))}return n}function rie(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function db(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function pb(e,t=iie){let n=t.now();if(!t.databaseExists(e.previousDbPath))return lp(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return lp(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=Ru(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!ig(s).fullProject&&s.changes.every(p=>a.has(p.path)),l=Cu(s,c?t.dependencyGraph(r):new Map,o),u=rie(t.factDigests(r),t.factDigests(i)),d=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(d).toISOString(),durationMs:Math.max(0,d-n),manifest:s,plan:l,comparison:u,evaluation:db(l,u,o.length)}}catch(o){return lp(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{EL(r),EL(i)}}function FL(e,t,n,r=Date.now()){return lp(e,t,r,r,n)}function NL(e){let t=LL(e);return{latestPath:PL(t,"affected-shadow-latest.json"),historyPath:PL(t,"affected-shadow.jsonl")}}function AL(e,t=n=>Zre(n,"utf-8")){let n=NL(e),r;try{r=JSON.parse(t(n.latestPath))}catch(y){let x=lie(y),R=x?"telemetry-missing":cie(y);return di(n,R,x?void 0:y instanceof Error?y.message:String(y))}if(ee(r)&&typeof r.version=="number"&&r.version!==1)return di(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!sie(r))return di(n,"telemetry-malformed");if(r.status==="unavailable")return aie(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:di(n,"telemetry-malformed");if(r.status!=="evaluated")return di(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!ee(r.manifest)||!ee(i)||!ee(o)||!ee(s))return di(n,"telemetry-malformed");let a=i.mode,c=X(i.affectedFiles),l=X(i.reasons),u=X(o.changedFiles),d=X(s.predictedFiles),p=X(s.actualFiles),m=X(s.missingFiles),f=s.recall,g=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||u===null||d===null||p===null||m===null||typeof s.passed!="boolean"||!DL(f)||!DL(g))return di(n,"telemetry-malformed");let h=p.length===0?1:(p.length-m.length)/p.length;return!TL(c,d)||!TL(u,p)||s.passed!==(m.length===0)||Math.abs(f-h)>Number.EPSILON||m.some(y=>!p.includes(y)||d.includes(y))?di(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:f,affectedRatio:g,predictedFiles:d,actualFiles:p,missingFiles:m,fallbackReasons:l}}function _L(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function ML(e,t,n=oie){let r=NL(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function ub(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var iie={now:()=>Date.now(),databaseExists:e=>Qre(e),openDatabase:(e,t,n)=>new Gt({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>q(e),dependencyGraph:e=>ge(e),factDigests:e=>tie(e)},oie={appendHistory:(e,t)=>{Xre(LL(e),{recursive:!0}),Yre(e,`${JSON.stringify(t)}
1031
- `)},writeLatest:(e,t)=>he(e,t,{spacing:2,trailingNewline:!0})};function lp(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function EL(e){try{e?.close()}catch{}}function sie(e){return ee(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function aie(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function DL(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function TL(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function di(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function cie(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function lie(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as uie}from"crypto";import{copyFileSync as die,existsSync as $L,rmSync as OL}from"fs";import{resolve as pie}from"path";import HL from"better-sqlite3";var mie={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},fie={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function WL(e){let t=Date.now(),n=gie(e.affectedFiles);if(hie(e.previousDbPath,e.miniDbPath,e.candidateDbPath),OL(e.candidateDbPath,{force:!0}),!$L(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!$L(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");jL(e.previousDbPath,"previous SQLite generation",!1),jL(e.miniDbPath,"incremental SQLite mini database"),die(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new HL(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),mb(r,"main","candidate SQLite generation"),mb(r,"incremental","incremental SQLite mini database"),yie(r,n),bie(r,n.length);let i=fb(r,"main",!0),o=pi(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Sie(r),vie(r),xie(r),e.onStage?.("after-delete"),Rie(r),e.onStage?.("after-symbol-reconciliation"),Cie(r),e.onStage?.("after-insert"),wie(r),kie(r,n.length,o),e.onStage?.("before-commit")}).immediate(),qL(r,"main","candidate SQLite generation");let c=[...Iie(r)].filter(([l,u])=>i.get(l)!==u).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{OL(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function gie(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function hie(e,t,n){let r=[e,t,n].map(i=>pie(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function jL(e,t,n=!0){let r=new HL(e,{readonly:!0,fileMustExist:!0});try{mb(r,"main",t),n&&qL(r,"main",t)}finally{r.close()}}function mb(e,t,n){for(let[r,i]of Object.entries(mie)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:u})=>({name:a,type:c.toUpperCase(),notnull:l,pk:u}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(fie)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}BL(e,t,"documents",["relative_path"],n),BL(e,t,"global_symbols",["symbol"],n)}function BL(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function qL(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function yie(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function bie(e,t){let n=pi(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=pi(e,`SELECT COUNT(*) AS value
1032
- FROM main.documents d
1033
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
1034
- FROM temp.incremental_affected_paths p
1035
- LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
1036
- WHERE d.id IS NULL
1037
- LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
1038
- FROM incremental.documents d
1039
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1040
- WHERE p.relative_path IS NULL
1041
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Sie(e){e.exec(`
1042
- CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
1043
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
1044
- SELECT g.symbol
1045
- FROM main.defn_enclosing_ranges r
1046
- JOIN main.documents d ON d.id = r.document_id
1047
- JOIN main.global_symbols g ON g.id = r.symbol_id
1048
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
1049
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
1050
- SELECT g.symbol
1051
- FROM main.mentions m
1052
- JOIN main.chunks c ON c.id = m.chunk_id
1053
- JOIN main.documents d ON d.id = c.document_id
1054
- JOIN main.global_symbols g ON g.id = m.symbol_id
1055
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1056
- WHERE m.role = 1;
1057
-
1058
- CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
1059
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
1060
- SELECT g.symbol
1061
- FROM incremental.defn_enclosing_ranges r
1062
- JOIN incremental.global_symbols g ON g.id = r.symbol_id;
1063
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
1064
- SELECT g.symbol
1065
- FROM incremental.mentions m
1066
- JOIN incremental.global_symbols g ON g.id = m.symbol_id
1067
- WHERE m.role = 1;
1068
- `)}function vie(e){let t=e.prepare(`WITH changed_symbols AS (
1069
- SELECT symbol FROM temp.incremental_old_defined_symbols
1070
- UNION
1071
- SELECT symbol FROM temp.incremental_new_defined_symbols
1072
- ), unaffected_definitions AS (
1073
- SELECT g.symbol
1074
- FROM main.defn_enclosing_ranges r
1075
- JOIN main.documents d ON d.id = r.document_id
1076
- JOIN main.global_symbols g ON g.id = r.symbol_id
1077
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1078
- WHERE p.relative_path IS NULL
1079
- UNION
1080
- SELECT g.symbol
1081
- FROM main.mentions m
1082
- JOIN main.chunks c ON c.id = m.chunk_id
1083
- JOIN main.documents d ON d.id = c.document_id
1084
- JOIN main.global_symbols g ON g.id = m.symbol_id
1085
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1086
- WHERE m.role = 1 AND p.relative_path IS NULL
1087
- )
1088
- SELECT u.symbol
1089
- FROM unaffected_definitions u
1090
- JOIN changed_symbols c ON c.symbol = u.symbol
1091
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function xie(e){e.exec(`
1092
- DELETE FROM main.mentions
1093
- WHERE chunk_id IN (
1094
- SELECT c.id
1095
- FROM main.chunks c
1096
- JOIN main.documents d ON d.id = c.document_id
1097
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1098
- );
1099
- DELETE FROM main.chunks
1100
- WHERE document_id IN (
1101
- SELECT d.id
1102
- FROM main.documents d
1103
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1104
- );
1105
- DELETE FROM main.defn_enclosing_ranges
1106
- WHERE document_id IN (
1107
- SELECT d.id
1108
- FROM main.documents d
1109
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
1110
- );
1111
- DELETE FROM main.documents
1112
- WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
1113
- `)}function Rie(e){e.exec(`
1114
- UPDATE main.global_symbols
1115
- SET display_name = NULL,
1116
- kind = NULL,
1117
- documentation = NULL,
1118
- signature = NULL,
1119
- enclosing_symbol = NULL,
1120
- relationships = NULL
1121
- WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
1122
-
1123
- INSERT OR IGNORE INTO main.global_symbols(
1124
- symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
1125
- )
1126
- SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
1127
- FROM incremental.global_symbols;
1128
-
1129
- UPDATE main.global_symbols
1130
- SET display_name = (
1131
- SELECT source.display_name FROM incremental.global_symbols source
1132
- WHERE source.symbol = main.global_symbols.symbol
1133
- ),
1134
- kind = (
1135
- SELECT source.kind FROM incremental.global_symbols source
1136
- WHERE source.symbol = main.global_symbols.symbol
1137
- ),
1138
- documentation = (
1139
- SELECT source.documentation FROM incremental.global_symbols source
1140
- WHERE source.symbol = main.global_symbols.symbol
1141
- ),
1142
- signature = (
1143
- SELECT source.signature FROM incremental.global_symbols source
1144
- WHERE source.symbol = main.global_symbols.symbol
1145
- ),
1146
- enclosing_symbol = (
1147
- SELECT source.enclosing_symbol FROM incremental.global_symbols source
1148
- WHERE source.symbol = main.global_symbols.symbol
1149
- ),
1150
- relationships = (
1151
- SELECT source.relationships FROM incremental.global_symbols source
1152
- WHERE source.symbol = main.global_symbols.symbol
1153
- )
1154
- WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
1155
- `)}function Cie(e){let t=pi(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=pi(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=pi(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
1156
- SELECT id + ?, language, relative_path, position_encoding, text
1157
- FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
1158
- SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
1159
- FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
1160
- SELECT m.chunk_id + ?, target.id, m.role
1161
- FROM incremental.mentions m
1162
- JOIN incremental.global_symbols source ON source.id = m.symbol_id
1163
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
1164
- id, document_id, symbol_id, start_line, start_char, end_line, end_char
1165
- )
1166
- SELECT r.id + ?, r.document_id + ?, target.id,
1167
- r.start_line, r.start_char, r.end_line, r.end_char
1168
- FROM incremental.defn_enclosing_ranges r
1169
- JOIN incremental.global_symbols source ON source.id = r.symbol_id
1170
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function wie(e){e.exec(`
1171
- DELETE FROM main.global_symbols
1172
- WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
1173
- AND NOT EXISTS (
1174
- SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
1175
- );
1176
- `)}function kie(e,t,n){let r=pi(e,"SELECT COUNT(*) AS value FROM main.documents"),i=pi(e,`SELECT COUNT(*) AS value
1177
- FROM main.documents d
1178
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Iie(e){let t=fb(e,"main",!0),n=fb(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function fb(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
1179
- FROM ${t}.documents d
1180
- ${r}
1181
- ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
1182
- FROM ${t}.chunks c
1183
- JOIN ${t}.documents d ON d.id = c.document_id
1184
- ${r}
1185
- ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),s=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
1186
- g.symbol, g.display_name, g.kind, g.documentation,
1187
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
1188
- g.enclosing_symbol,
1189
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
1190
- FROM ${t}.defn_enclosing_ranges r
1191
- JOIN ${t}.documents d ON d.id = r.document_id
1192
- JOIN ${t}.global_symbols g ON g.id = r.symbol_id
1193
- ${r}
1194
- ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
1195
- FROM ${t}.mentions m
1196
- JOIN ${t}.chunks c ON c.id = m.chunk_id
1197
- JOIN ${t}.documents d ON d.id = c.document_id
1198
- JOIN ${t}.global_symbols g ON g.id = m.symbol_id
1199
- ${r}
1200
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[u,d]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let p of d){let m=JSON.stringify([u,p]),f=c.get(p.relative_path)??[];f.push(m),c.set(p.relative_path,f)}let l=new Map;for(let[u,d]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=uie("sha256");for(let m of d.sort())p.update(m).update(`
1201
- `);l.set(u,p.digest("hex"))}return l}function pi(e,t){return e.prepare(t).get().value}import{readFileSync as Pie,writeFileSync as Eie}from"fs";function mo(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function VL(e){let t=e.readFingerprint(),n=Die(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Tie(e.cachePath,e.readFingerprint(),r),r}function Die(e,t){try{let n=JSON.parse(Pie(e,"utf-8"));return UL(n.fingerprint)===UL(t)?{result:n.result}:null}catch{return null}}function Tie(e,t,n){Eie(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
1202
- `)}function UL(e){return JSON.stringify(e)}import{createHash as Lie}from"crypto";import{existsSync as gb,readFileSync as Fie,readdirSync as Nie}from"fs";import{dirname as hb,join as up,relative as Aie,resolve as yb,sep as GL}from"path";function zL(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=QL(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function KL(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],s=r.get(i);if(!o||o.parseFailed){for(let a of e)a!==i&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==i&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=QL(a,e);c&&c!==i&&s.add(c)}}return _ie(e,r)}function JL(e,t,n){let r={};for(let i of e){let o=new Map;for(let s of t.files[i]??[])o.set(s.path,s);for(let s of n[i]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);r[i]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return r}function bb(e){if(e===".")return"root";let t=Lie("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function YL(e,t){let n=yb(e),r={};for(let i of t)r[i]=Mie(n,i);return r}function QL(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function _ie(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function Mie(e,t){let n=t==="."?e:up(e,t),r=$ie(n),i=Oie(n),o=i?jie(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function $ie(e){let t=up(e,"package.json");if(!gb(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Sb(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let s=n.value[o];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.keys(s))i.add(a)}return{name:r,dependencyNames:[...i],failed:!1}}function Oie(e){let t=up(e,"tsconfig.json");if(gb(t))return t;let n;try{n=Nie(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?up(e,n[0]):void 0}function jie(e,t){let n=Sb(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Bie(n.value,e,t),i=XL(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Bie(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=hb(t),o=new Set;for(let s of r){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=ZL(a,i,n);c&&o.add(c)}return[...o]}function XL(e,t,n,r){let i=Hie(t);if(i)return{pathsTargets:Wie(i,hb(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=qie(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Sb(o);return s.ok?XL(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Hie(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Wie(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let s=ZL(o,t,n);s&&r.add(s)}return[...r]}function qie(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=yb(hb(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(GL).includes("node_modules")&&en(n,i)&&gb(i))return i}function ZL(e,t,n){let r=e.replace(/\/?\*+$/,""),i=yb(t,r===""?".":r);if(!en(n,i))return;let s=Aie(n,i).split(GL).join("/");return s===""?".":s}function Uie(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
1203
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Sb(e){try{let t=Fie(e,"utf-8"),n=JSON.parse(Uie(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Vie,readFileSync as Gie,readdirSync as zie,statSync as Kie}from"fs";import pt from"path";var Jie=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function _c(e,t=[]){let n=pt.resolve(e),r=t.flatMap(c=>Qie(n,c));if(r.length>0)return eF(n,tF(r));let i=Yie(n),o=tF(i),s=Zie(n,o)?[n,...o]:o,a=s.length>0?s:[n];return eF(n,a)}function eF(e,t){return[...new Set(t.map(n=>toe(e,n)))].sort((n,r)=>n.localeCompare(r))}function Yie(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=zie(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=pt.join(r,o.name);if(o.isDirectory()){!Jie.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Xie(s)&&t.push(pt.dirname(s))}}return t}function Qie(e,t){let n=t.trim();if(!n)return[];let r=pt.resolve(e,n);if(!en(e,r))return[];try{let i=Kie(r);if(i.isDirectory())return[r];if(i.isFile()&&nF(pt.basename(r)))return[pt.dirname(r)]}catch{return[]}return[]}function Xie(e){if(!nF(pt.basename(e)))return!1;let t=rF(e);return t?pt.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function nF(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function tF(e){let t=[...new Set(e.map(n=>pt.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&noe(n,r)))}function Zie(e,t){if(t.length===0||t.some(r=>pt.resolve(r)===e))return!1;let n=pt.join(e,"tsconfig.json");return Vie(n)&&eoe(n)}function eoe(e){let n=rF(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!pt.extname(r))):!1}function rF(e){try{let t=JSON.parse(Gie(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function toe(e,t){let n=pt.relative(e,t);return n?n.split(pt.sep).join("/"):"."}function noe(e,t){let n=pt.relative(e,t);return!!n&&!n.startsWith("..")&&!pt.isAbsolute(n)}import{createHash as Coe}from"crypto";import{existsSync as xb,readFileSync as hF,statSync as woe,writeFileSync as Rb}from"fs";import{join as koe}from"path";import{readFileSync as iF}from"fs";import{createRequire as roe}from"module";import{dirname as ioe,isAbsolute as sBe,relative as aBe,resolve as cBe,sep as lBe}from"path";var oF=roe(import.meta.url),ooe=1,sF="0.4.0";function vb(){let e=soe();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function soe(){try{let e=oF.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(iF(e,"utf8"));if(t.version!==sF)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${sF}`};let n=ioe(e),r=oF.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(iF(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:aoe(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function aoe(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${ooe}`}import{createHash as coe}from"crypto";import{readFileSync as loe}from"fs";import{dirname as uoe,join as dp}from"path";var pp=2,doe="typescript-index";function aF(e){let t=dp(e,doe);return{rootDir:t,requestDir:dp(t,"requests"),responseDir:dp(t,"responses")}}function cF(e){try{let t=JSON.parse(loe(dp(uoe(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:coe("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as poe}from"crypto";import{existsSync as moe,mkdirSync as lF,readFileSync as foe,rmSync as uF}from"fs";import{resolve as dF}from"path";var goe=12e4,hoe=5,mp=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=wn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??xoe(),this.runtime=n.runtime??Roe}request(t){let n=Hn(this.cacheDir),r=aF(this.cacheDir),i=Vr(n.statePath);if(!pF(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=dF(r.requestDir,`${o}.json`),a=dF(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;lF(r.requestDir,{recursive:!0}),lF(r.responseDir,{recursive:!0}),he(s,{protocolVersion:pp,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(moe(a))return yoe(foe(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Vr(n.statePath);if(!pF(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(hoe)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{uF(s,{force:!0}),uF(a,{force:!0})}}};function pF(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Sa,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===pp&&n.isProcessAlive(e.pid)&&(r||i)}function yoe(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==pp||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let s=boe(o.response,r),a=[...new Set(i)].sort(),c=s.fragments.map(l=>l.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(a))throw new Error("TypeScript index service omitted or added an affected document.");return s}function boe(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Soe)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:voe(o.bytesBase64);return{relativePath:o.relativePath,bytes:s,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Soe(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function voe(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function xoe(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:goe}var Roe={now:Date.now,randomId:poe,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xe};function Ioe(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Ru(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(l=>l.kind!=="modified"||l.inputKind!=="source"||!bt(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Cu(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=Poe([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=mF(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=mF(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=gF(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=gF(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:fF(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:fF(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function Poe(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function yF(e){let t=Date.now();try{if(!xb(e.previousDbPath)||!xb(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=vb();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Gt({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=q(o,{includeIgnored:!1}).filter(bt).sort(),a=ge(o)}finally{o.close()}let c=performance.now()-n,l=Ioe({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?_c(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:xb(koe(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let u=cF(e.previousDbPath);if(!u)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new mp({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:u}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),m=performance.now()-n,f=woe(e.previousShardPath).size>=CD;n=performance.now();let g=f?null:hF(e.previousShardPath),h=f?{completeIndexBytes:null,affectedIndexBytes:aD(p.fragments)}:pD({packageVersion:r.packageVersion,baseIndexBytes:g,fragments:p.fragments}),y=performance.now()-n;n=performance.now(),f?wD({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(cD({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:g,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),lD({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:p.fragments,documentIdentities:l.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),h.completeIndexBytes&&Rb(e.candidateShardPath,h.completeIndexBytes),Rb(e.candidateAffectedScipPath,h.affectedIndexBytes);let R=performance.now()-n,b={scipPath:f?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!f,durationMs:Date.now()-t,cold:p.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(p.fragments.map(v=>[v.relativePath,v.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:p.durationMs,assemblyMs:y,fragmentStoreMs:x,writeMs:R}};return e.onStatus(`Incremental TypeScript index emitted ${b.affectedFiles.length} affected document(s) in ${(b.durationMs/1e3).toFixed(3)}s (${b.cold?"cold":"warm"} service; ${f?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${y.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${R.toFixed(0)}ms).`),b}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function bF(e){let t=vb();if(!t.available)throw new Error(t.reason);let n=kD({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:hF(e.baseShardPath),packageVersion:t.packageVersion});Rb(e.candidateShardPath,n)}function mF(e,t,n){let r=e.files.filter(i=>Ho(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Cb(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function fF(e,t){return Cb(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function gF(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=zo({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),a=new Map;for(let c of i){let l=s.identityFor(c,"typescript-scip-document-v1");if(l.key){a.set(c,l.key);continue}if(o.has(c))return null;a.set(c,Cb(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Cb(e){return Coe("sha256").update(e).digest("hex")}import{execFile as Eoe}from"child_process";import{existsSync as fp,renameSync as kb,rmSync as Ib,statSync as Doe}from"fs";import{cpus as Toe}from"os";import{join as SF}from"path";function Loe(e,t,n){if(!e.defaultOutputPath)return;let r=SF(t,e.defaultOutputPath);n!==r&&fp(r)&&kb(r,n)}function Foe(e,t,n){if(!e.defaultOutputPath)return null;let r=SF(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ib(i,{force:!0}),fp(r)?(kb(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Noe(e){e&&(Ib(e.defaultOutputPath,{force:!0}),e.backupPath&&fp(e.backupPath)&&kb(e.backupPath,e.defaultOutputPath))}function Aoe(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(8,Math.max(1,Toe().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function vF(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=Aoe(o.length,r),c=await Moe(o,a,l=>wb(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(d=>d.skipped)){let d=o.find(p=>p.id===u.id);d&&(n(`Retrying ${d.label} indexer serially after parallel failure...`),l.set(d.id,await wb(d,t,n)))}s.push(...c.map(u=>l.get(u.id)??u))}else s.push(...c);for(let l of i)s.push(await wb(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function wb(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ib(e.scipPath,{force:!0});let r=Foe(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await _oe(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Loe(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
1204
- `)[0]}`,u=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:u}}}finally{Noe(r)}if(!fp(e.scipPath)){let a=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?a:`${e.label}: ${a}`;return n(`Skipping ${e.label}: ${a}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let s;try{s=Doe(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function _oe(e,t,n){return new Promise((r,i)=>{Eoe(e,[...t],n,o=>{o?i(o):r()})})}async function Moe(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 yse from"better-sqlite3";import{existsSync as bse}from"fs";import{dirname as Sse,join as vse,resolve as xse}from"path";import{readFileSync as Ooe,rmSync as joe,statSync as Boe,mkdtempSync as Hoe}from"fs";import{tmpdir as Woe}from"os";import{join as Pb}from"path";import{Worker as qoe}from"worker_threads";function $oe(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Fs(){return{skippedReferences:0,skippedReferenceReasons:$oe(),skippedReferenceSamples:[]}}function gp(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}function xF(e){return e.length>=8&&CF(e.length)>1}function RF(e){let t=CF(e.vueFiles.length),n=Voe(e.vueFiles),r=zoe(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Hoe(Pb(Woe(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=Uoe(),l=Date.now();try{for(let p=0;p<r.length;p++)new qoe(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[p],resultPath:Pb(o,`${p}.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((p,m)=>{let f=JSON.parse(Ooe(Pb(o,`${m}.json`),"utf-8"));if(!f.ok)throw new Error(`Vue reference worker failed: ${f.error}`);return f.result}),d={occurrences:u.flatMap(p=>p.occurrences),...Fs()};for(let p of u)gp(d,p);return d}finally{joe(o,{recursive:!0,force:!0})}}function CF(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function Uoe(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Voe(e){let t=Goe(),n=[];for(let r of e){let i=wF(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 Goe(){return Number.POSITIVE_INFINITY}function zoe(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Koe(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 Koe(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,wF(e.fileName)-e.startOffset)}function wF(e){try{return Boe(e).size}catch{return 1}}import{createRequire as Joe}from"module";import{existsSync as Yoe,readFileSync as Db}from"fs";import{dirname as kF,extname as Qoe,join as IF,relative as Xoe,resolve as Zoe}from"path";import{pathToFileURL as ese}from"url";function tse(e){e.transaction(()=>{e.prepare(`
1205
- DELETE FROM mentions
1206
- WHERE chunk_id IN (
1207
- SELECT c.id
1208
- FROM chunks c
1209
- JOIN documents d ON d.id = c.document_id
1210
- WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
1211
- )
1212
- `).run(),e.prepare(`
1213
- DELETE FROM chunks
1214
- WHERE document_id IN (
1215
- SELECT id
1216
- FROM documents
1217
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
1218
- )
1219
- `).run()})()}function PF(e,t){return e.prepare(`
1220
- SELECT relative_path AS relativePath
1221
- FROM documents
1222
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
1223
- ORDER BY relative_path
1224
- `).all().map(r=>Zoe(t,r.relativePath))}function EF(e,t){let{vueCore:n,ts:r,volarTs:i}=nse(e),{parsed:o,vueOptions:s}=rse(n,r,t),a=kF(t),c=n.createVueLanguagePlugin(r,o.options,s,m=>m),l=ise(n,r,c),u=ose(a,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,l,m=>m,u),p=r.createLanguageService(d);return{ts:r,language:l,languageService:p,fileNames:o.fileNames,configDir:a}}function nse(e){let t=Joe(ese(IF(e,"package.json")).href);return{vueCore:Eb(t,"@vue/language-core",e),ts:Eb(t,"typescript",e),volarTs:Eb(t,"@volar/typescript",e)}}function rse(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,kF(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function ise(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Yoe(o))return;let s=Db(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??dse(o))});return r.current=i,i}function ose(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Eb(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 DF(e,t,n){let r=sse(e);return i=>{if(!i.name)return null;let o=Tr(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.starts.find(d=>d.line===a.line&&d.displayName===i.name);if(l)return l.symbolId;let u=c.containingByLine.get(a.line);return u&&u.displayName===i.name?u.symbolId:ase(c.starts,a.line,2,i.name)}}function sse(e){let t=e.prepare(`
1225
- SELECT
1226
- d.relative_path AS relativePath,
1227
- der.start_line AS startLine,
1228
- der.end_line AS endLine,
1229
- der.symbol_id AS symbolId,
1230
- gs.display_name AS displayName
1231
- FROM defn_enclosing_ranges der
1232
- JOIN documents d ON d.id = der.document_id
1233
- JOIN global_symbols gs ON gs.id = der.symbol_id
1234
- ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
1235
- `).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,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function ase(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function TF(e,t,n){let r=fse(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
1236
- INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
1237
- VALUES (?, ?, ?, ?)
1238
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Tr(t,l),d=jF(r.name,r.version,u);o.run(d,"default",7,`Vue component|${u}`);let p=gse(i,r,t,l);p&&(s++,a.set(l,p))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function LF(e,t,n,r,i){return e.transaction(()=>(tse(e),cse(e,t,n,r),lse(e,i)))()}function cse(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
1239
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
1240
- VALUES (?, ?, ?, ?, X'00')
1241
- `),s=e.prepare(`
1242
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
1243
- VALUES (?, ?, 1)
1244
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Tr(t,a),u=i.get(l);if(!u)continue;let d=o.run(u.id,-1,0,0);s.run(Number(d.lastInsertRowid),c)}}function FF(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(Tb(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function NF(e){let t=new Set,n=[];for(let r of e){let i=AF(r);t.has(i)||(t.add(i),n.push(r))}return n}function AF(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function lse(e,t){let n=mse(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
1245
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
1246
- VALUES (?, ?, ?, ?, X'00')
1247
- `),i=e.prepare(`
1248
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
1249
- VALUES (?, ?, 0)
1250
- `),o=new Set,s=0,a=0;for(let c of t){let l=AF(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let d=r.run(u,a++,c.sourceLine,c.sourceLine),p=i.run(Number(d.lastInsertRowid),c.symbolId);s+=Number(p.changes)}return s}function*_F(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 MF(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Tb(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function use(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 $F(e,t){return Tr(e,t).startsWith("node_modules/")}function Tr(e,t){return Xoe(e,t).replaceAll("\\","/")}function dse(e){switch(Qoe(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 OF(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Db(t,"utf-8"),r={text:n,lineStarts:pse(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:use}}function pse(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function mse(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 fse(e){try{let t=JSON.parse(Db(IF(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 gse(e,t,n,r){let i=Tr(n,r),o=jF(t.name,t.version,i);return e.get(o)?.id??null}function jF(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function HF(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Rse({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Nb(e){return mo(po(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),mo(HF({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Rse(e){let t=xse(e.projectRoot,e.tsconfig);if(!bse(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new yse(e.dbPath);try{let r=PF(n,e.projectRoot),i=vse(Sse(e.dbPath),"augment-vue-meta.json");return VL({cachePath:i,readFingerprint:()=>kse(n,e.projectRoot,e.tsconfig),compute:()=>Cse({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Cse(e){let t=TF(e.db,e.projectRoot,e.vueFiles),n=wse(e,t),r=NF(n.occurrences),i=LF(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Ase(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Nse(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function wse(e,t){if(xF(e.vueFiles))return RF({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Ise({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Pse({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function kse(e,t,n){let r=e.prepare(`
1251
- SELECT
1252
- (SELECT COUNT(*) FROM documents) AS documents,
1253
- (SELECT COUNT(*) FROM global_symbols) AS symbols,
1254
- (SELECT COUNT(*) FROM chunks) AS chunks,
1255
- (SELECT COUNT(*) FROM mentions) AS mentions,
1256
- (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
1257
- (SELECT MAX(id) FROM chunks) AS maxChunkId,
1258
- (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
1259
- `).get();return{version:3,tsconfig:n,files:Ai(t),db:r}}function Ise(e){let t=OF();return{projectRoot:e.projectRoot,context:EF(e.projectRoot,e.configPath),symbolLookup:DF(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Pse(e){let t=[],n=Fs(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Ese(e,i);t.push(...o.occurrences),gp(n,o)}return{occurrences:t,...n}}function Ese(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return BF(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return BF(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Tr(e.projectRoot,t.fileName),a=[..._F(n.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:Mse(a),processedStarts:new Set};return Dse({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function Dse(e){let t=[],n=Fs();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Tse(e.sourceInfo.text,r.start))continue;let i=MF(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!$F(e.projectRoot,u.fileName));if(!s){Lb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Tr(e.projectRoot,s.fileName),c=Lse(e.sourceFile,r.text,a);if(c){Lb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=FF(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Lb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}WF(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),_se(t,e,r,i,a,l)}return{occurrences:t,...n}}function Tse(e,t){let n=e.lastIndexOf(`
1260
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Lse(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function BF(e,t,n){let r=Fs();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Tr(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Lb(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===r).length>=2)return;let s=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,token:i.text,reason:o})}function Fb(e,t){let n=new Map;for(let o of e){let s=n.get(o.sourceFile)??[];s.push(o),n.set(o.sourceFile,s)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let s=!1;for(let a of r){let c=n.get(a)?.[o];if(c&&(i.push(c),s=!0,i.length===t))break}if(!s)break}return i}function Fse(e,t){let n=Fb(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Fb(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Nse(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let s=n.length-i,a=Math.ceil((t-r.length)/s);r.push(...Fb(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function Ase(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Fse(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function _se(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of $se(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(WF(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function WF(e,t,n,r,i,o,s){let a=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:s})}function Mse(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function $se(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=Ose(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function Ose(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Tb(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Ns(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Yse(e),s=Date.now();yp(we(o.outputScip),{recursive:!0}),yp(we(o.outputDb),{recursive:!0});let a=e.languages??gn(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=D("reindex.fingerprint",()=>Dae(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,u;if(e.skipIfUnchanged!==!1&&!Cs(t,o.outputDb)&&qF(o.outputScip)===qF(mt(we(o.outputDb),"index.scip"))){let f=Wt(t);if(l=f?ai(f,c):void 0,l){let g=Ln(l);if(g){if(!Jse(o,c))try{vs({snapshot:l,manifest:g,targetCacheDir:we(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(h){r(`Shared generation attach failed; continuing locally: ${_b(h)}`)}}else{let h=await eT(l);if(h.kind==="owner")u=h.release;else if(h.kind==="generation-ready"){let y=Ln(l);if(y)try{vs({snapshot:l,manifest:y,targetCacheDir:we(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(x){r(`Shared generation attach failed after waiting; continuing locally: ${_b(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let d=to(mt(we(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!d)throw u?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${we(o.outputDb)}.`);let p;try{p=await Vs("reindex.lock",()=>Rae(mt(we(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(f){throw d.release(),u?.(),f}let m=null;try{let f=null,g=D("reindex.reuse-check",()=>(f=Qse({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),f),()=>({languages:a.length,reused:f!==null}));if(g)return UF({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),g;await Vs("reindex.scip-cli-ready",()=>fae(i,r));let h=Zse(o);m=h.runDir;let y,x=await Vs("reindex.fresh",async()=>(y=await eae({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:h,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),y),()=>({languages:a.length,reused:y?.reused,skipped:y?.skipped.length}));return UF({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(f){throw sN(o.metaPath,xp({trigger:e.trigger,result:"failed",start:s,error:f instanceof Error?f.message:String(f)})),f}finally{m&&mi(m,{recursive:!0,force:!0}),p(),d.release(),u?.()}}function UF(e){if(e.snapshot){if(Ln(e.snapshot)){xs(e.snapshot,we(e.paths.outputDb),"local-fresh");return}try{let t=Wt(e.projectRoot),n=t?ai(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}_d({snapshot:e.snapshot,sourceCacheDir:we(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Wt(e.projectRoot);return(r?ai(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),xs(e.snapshot,we(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${_b(t)}`)}}}function Jse(e,t){if(!Nn(e.outputScip)||!Nn(e.outputDb)||!oN(e.metaPath,t))return!1;let n=hn(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function _b(e){return e instanceof Error?e.message:String(e)}function Yse(e){let t=e.outputScip??mt(e.projectRoot,"index.scip"),n=e.outputDb??mt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:mt(we(n),"meta.json")}}function Qse(e){let t=hn(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Nn(e.paths.outputScip)||!Nn(e.paths.outputDb)||!oN(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;mo(po(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=xp({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return sN(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:Xse(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Xse(e,t,n,r){let i=rN(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Mc(i[o]),outputBytes:$c($b(e.outputDb,o)),durationMs:0}))}function Zse(e){let t=Wse(mt(we(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:mt(t,hp(e.outputScip)),tempOutputDb:mt(t,hp(e.outputDb)),tempMetaPath:mt(t,hp(e.metaPath))}}async function eae(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Vs("reindex.language-indexers",async()=>(n=await nae(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:u}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),tae({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let m=D("reindex.publish",()=>dae(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),f=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(g=>g.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:m,shards:c}}let d=D("reindex.publish",()=>uae(e,t,i,o,s,a,l,u),{mode:u?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),p=d.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:d,shards:c}}function tae(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Nn(e.run.paths.outputScip)||!Nn(e.run.paths.outputDb))return!1;let t=hn(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function nae(e,t){let n=aae({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[k,T]of n)T.reused&&(r.push({language:k,scipPath:T.scipPath}),i.add(k));for(let k of i)e.onStatus(`Reusing cached ${k} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=hn(e.paths.outputDb,e.paths.metaPath),a=jc(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),u=o&&!o.reused&&c?yF({projectRoot:e.projectRoot,cacheDir:we(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Oc(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Oc(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Mb(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,d=new Set(u?["typescript"]:[]),p=u?void 0:rae(e,n),{preparedRuns:m,skippedLanguages:f,languageOutputScipPaths:g}=gae({languages:e.languages.filter(k=>!i.has(k)&&!d.has(k)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:p?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),h=p?m.filter(k=>k.language!=="typescript"||p.missedProjectIds.has(k.id)):m,y=await vF(h,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(p){oae(e.paths.outputDb,y);let k=g.typescript??e.tempPaths.tempOutputScip;x=sae({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:k,reusedProjects:p.reusedProjects})}let R=[...y,...x],{indexedOutputs:b}=yae(R,f),v=u?[{language:"typescript",scipPath:u.scipPath}]:[],w=[...r,...v,...b];bae(w,f,e.languages,e.opts.allowPartial,e.onStatus);let I=u?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:u.scipPath,outputScipPath:u.scipPath,durationMs:u.durationMs,command:"watch-service:typescript-index",outputBytes:$c(u.scipPath)??void 0}]:[],C=cae(n,[...y,...I],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:w,skippedLanguages:f,reusedLanguages:[...i],languageFingerprints:lae(n,e.languages),shards:C,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:u??void 0}}function rae(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=_c(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=YL(e.projectRoot,r),o=zL(n.fingerprint.files,r),s=KL(r,i),a=JL(r,o,s),c=jc(e.paths.metaPath),u=iae(c,a,f=>Nn(vp(e.paths.outputDb,f))),d=[...u.entries()].filter(([,f])=>f.reused).map(([f])=>f),p=new Set(d),m=new Set(r.filter(f=>!p.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:a,classification:u,reusedProjects:d,missedProjectIds:m}}function iae(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.typescriptProjectShards?.[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(Lr(s)!==Lr(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function oae(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=vp(e,r);yp(we(i),{recursive:!0}),bp(n.scipPath,i)}}function sae(e){return e.reusedProjects.map((t,n)=>{let r=vp(e.outputDb,t),i=Oc(e.tempOutputScip,"typescript-project-cached",n);return bp(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:$c(i)??void 0}})}function aae(e){let t=jc(e.paths.metaPath),n=rN(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=$b(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!Nn(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(Lr(a)!==Lr(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function cae(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Mc(o.fingerprint),outputBytes:$c(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?Mc(a.fingerprint):o?Mc(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:Mc(o.fingerprint),outputBytes:$c(vp(n.outputDb,i)),durationMs:0});return r}function Mc(e){return Bse("sha256").update(Lr(e)).digest("hex").slice(0,16)}function $c(e){try{return Vse(e).size}catch{return null}}function lae(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function uae(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(VF(e.paths.outputDb,n),l=GF(n,e.tempPaths.tempOutputScip,e.onStatus));let u=Sae({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:a,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:()=>{if(!a||a.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),bF({cacheDir:we(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(R=>R.language==="typescript"?{language:R.language,scipPath:a.candidateScipPath}:R);return VF(e.paths.outputDb,x),l=GF(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(mo(po(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),u.mode==="incremental"&&a){let x=null,R=null;try{x=new Gt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),R=new Gt({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let b=rw(x,e.fingerprint,a.referenceFragmentsByFile,R);e.onStatus(`Cached exact TypeScript reference fragments for ${b} affected document(s).`)}catch(b){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${b instanceof Error?b.message:String(b)}.`)}finally{x?.close(),R?.close()}}let d=Mb(e.paths.metaPath),p=u.mode==="incremental"&&a?xae(a,u.changedDocumentPaths):pb({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:d,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=xp({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(x=>x.language),skipped:[...r]}),f=u.mode==="incremental"&&u.scipCompanion==="deferred",g={...o};f&&delete g.typescript;let{metadata:h,pruneProjects:y}=XF({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:g,typescriptProjectShardContext:s,lastRefresh:m});return h.scipCompanion=f?"deferred":"current",ZF(e.paths.outputDb,y),Ob(e.tempPaths.tempMetaPath,h),kd({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:u.mode==="incremental"&&u.scipCompanion==="deferred",publication:u.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:u.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:u.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:u.patchDurationMs,scipCompanion:u.scipCompanion,...u.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:u.converterDurationMs,scipCompanion:"current",...u.fallbackReason?{fallbackReason:u.fallbackReason}:{}}}),ID(we(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),QF(e.paths.outputDb,p,e.onStatus),m}function dae(e,t,n,r,i,o){let s=Mb(e.paths.metaPath),a=null;try{bp(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(d){a=FL("reused","oracle-error",`Could not snapshot the prior database: ${d instanceof Error?d.message:String(d)}`)}mo(po(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=pb({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:s,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=xp({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(d=>d.language),skipped:[...n]}),{metadata:l,pruneProjects:u}=XF({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return ZF(e.paths.outputDb,u),Ob(e.paths.metaPath,l),GE(e.paths.outputDb,e.paths.metaPath),QF(e.paths.outputDb,a,e.onStatus),c}function Mb(e){return xu(jc(e)?.fingerprint)}function QF(e,t,n){try{ML(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function XF(e){let t=pae({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function pae(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=jc(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function ZF(e,t){let n=iN(e);if(t===null){mi(n,{recursive:!0,force:!0});return}let r;try{r=Use(n)}catch{return}for(let i of mae(r,t))mi(mt(n,i),{force:!0})}function mae(e,t){let n=new Set(t.map(r=>`${bb(r)}.scip`));return e.filter(r=>!n.has(r))}function VF(e,t){for(let n of t){let r=$b(e,n.language);yp(we(r),{recursive:!0}),n.scipPath!==r&&bp(n.scipPath,r)}}async function fae(e,t){if(!np()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
1261
- Install from: https://github.com/sourcegraph/scip/releases`);if(Kse()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!vL(t))throw new Error(`The scip CLI is required but could not be installed.
1262
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function gae(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?Oc(e.tempOutputScip,o,s):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:s})=>[o,s]));for(let{language:o,scipPath:s}of r){let a=hae({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?eN(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function hae(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Ab({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??_c(e.projectRoot,e.typescriptProjects);return t.length===0?[Ab({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Ab({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Oc(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Ab(e){let t=fr(e.language),n=Gl(t),r=uf(t,e.projectRoot);if(!r&&!hR(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...`),!zl(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??Oo(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,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:s,env:bR(t,e.env,i)}}}function yae(e,t){let n=new Map;for(let i of e)if(i.skipped)eN(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,s=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};s.scipPaths.push(i.scipPath),n.set(o,s)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)_D(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&YF(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function eN(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function bae(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
1263
- `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
1264
- `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${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.
1265
- `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
1266
- `))}function GF(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=MD(e.map(o=>o.scipPath),t);return nN(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&YF(e[0].scipPath,t);return!1}function Sae(e){let t;if(vae(e)){let i=mt(e.run.tempPaths.runDir,"typescript-affected.db");try{tN(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();zF(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=WL({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${s.affectedDocumentCount} SQLite document(s) in ${(s.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:s.changedDocumentPaths,patchDurationMs:s.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),mi(i,{force:!0}),mi(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return zF(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function vae(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Nn(e.run.paths.outputDb)||!Nn(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function xae(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(s=>!i.has(s)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:db(e.plan,o,e.projectFileCount)}}function zF(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Nn(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||tN(e,r);let o=np();if(!o)throw new Error("scip CLI is not available");jse(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function tN(e,t){let n=FD(e);nN(n,t)}function nN(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Oc(e,t,n){let r=zse(e)||".scip",i=hp(e,r);return mt(we(e),`${i}.${n+1}.${t}${r}`)}async function Rae(e,t){for(let n=0;n<2;n++){let r=Cae(e,t);if(r)return r;let i=wae(e);if(i&&kae(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await Pae(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${we(e)}; refusing to steal an active lock.`);mi(e,{force:!0});continue}if(i&&!xe(i.pid)){mi(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${we(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${we(e)}.`)}function Cae(e,t){let n;try{n=qse(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return Gse(n,JSON.stringify(r)+`
1267
- `),()=>{try{Hse(n)}finally{mi(e,{force:!0})}}}function wae(e){try{let t=JSON.parse(Sp(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:we(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function kae(e,t){return e?.kind==="manual-cli"&&Iae(t?.trigger)}function Iae(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Pae(e){return KF(e,"SIGTERM"),await JF(e,2e3)?!0:(KF(e,"SIGKILL"),JF(e,1e3))}function KF(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function JF(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!xe(e))return!0;await Eae(50)}return!xe(e)}function Eae(e){return new Promise(t=>setTimeout(t,e))}function Dae(e,t,n){return _i(e,t,n)}function rN(e,t,n){return Object.fromEntries(t.map(r=>{let i=fr(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:ff(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?Tae(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Lae(n),...o,clojureConfigPath:s,files:Ai(e,{language:r,markerFiles:i})}]}))}function Tae(e){return e?.trim()||void 0}function Lae(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function $b(e,t){return mt(we(e),"language-indexes",`${t}.scip`)}function iN(e){return mt(we(e),"language-indexes","typescript-projects")}function vp(e,t){return mt(iN(e),`${bb(t)}.scip`)}function jc(e){try{return JSON.parse(Sp(e,"utf-8"))}catch{return null}}function oN(e,t){try{let n=JSON.parse(Sp(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Lr(n.fingerprint)===Lr(t)&&Lr([...n.indexedLanguages??[]].sort())===Lr(t.languages)}catch{return!1}}function Ob(e,t){he(e,t,{spacing:2,trailingNewline:!0})}function sN(e,t){try{let n=JSON.parse(Sp(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Ob(e,{...n,lastRefresh:t})}catch{}}function xp(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function Lr(e){return JSON.stringify(e)}var jb=864e5;function aN(e,t={}){let r=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,u)=>l.ts-u.ts),i=new Map;for(let l of r){let u=`${l.check}\0${l.findingId}`,d=i.get(u);d||(d={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(u,d)),d.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=Fae(r),a=new Map;for(let l of o){let u=a.get(l.check)??[];u.push(l),a.set(l.check,u)}let c=[];for(let[l,u]of a){let d=0,p=0,m=0,f=0,g=0,h=0,y=[];for(let R of u){m+=R.events.filter(w=>w.event==="reopened").length;let b=R.events[R.events.length-1],v=`${R.check}\0${R.findingId}`;if(b.event==="resolved"&&s.has(v))f+=1;else if(b.event==="resolved"){let w=Dc(R.events.slice(0,-1)),I=w?.comparisonBaseCommit??w?.commit,C=b.comparisonBaseCommit??b.commit;I&&(C===I||b.verifiedAgainstCommit===I)?(d+=1,y.push((b.ts-R.caughtAt)/jb)):g+=1}else b.event==="suppressed"?p+=1:h+=1}let x=d+p;c.push({check:l,caught:u.length,fixed:d,suppressed:p,reopened:m,moved:f,unverified:g,open:h,precision:x>0?d/x:null,medianDaysToFix:y.length>0?Nae(y):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,u)=>l.check.localeCompare(u.check))}}function Fae(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function cN(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*jb:jb;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function Nae(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{fork as Aae}from"child_process";import{statSync as _ae}from"fs";import{isAbsolute as Mae,join as $ae,relative as Oae}from"path";import{watch as jae}from"chokidar";import Bae from"ignore";var Rp=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Yn(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=ni(t.projectRoot),this.extraIgnore=Bae(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=jae(this.projectRoot,{ignoreInitial:!0,ignored:(n,r)=>this.isIgnoredWatchPath(n,r?.isDirectory()??!1)});t.on("all",(n,r)=>{this.stopped||this.handleFileChange(r)}),t.on("error",n=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}),this.fsWatchers.push(t)}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=lN(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=Mae(t)?t:$ae(this.projectRoot,t);return Oae(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=lN(this.pendingTrigger,t),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 n=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(n).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,r)=>{let i=Date.now(),o=ut(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=zt(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,u=Aae(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});u.on("exit",d=>{d===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${d}`))}),u.on("error",r)})}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)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=Ff(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=au(this.projectRoot,t),r={head:Ff(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=_ae(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function lN(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as cce}from"fs";import{existsSync as dN,mkdirSync as pN,readFileSync as mN,writeFileSync as fN}from"fs";import{homedir as Hae}from"os";import{dirname as gN,isAbsolute as Wae,join as Bb,relative as uN,resolve as qae}from"path";function hN(e,t={}){let n=t.dossierDir?qae(e.projectRoot,t.dossierDir):Bb(e.projectRoot,"docs","scip-query"),r={markdownPath:Bb(n,"health-dossier.md"),jsonPath:Bb(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Xae({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return Jae(r.markdownPath,Uae(i),r),Yae(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Uae(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Wb(e.health)}`,"","## Items That Need Attention","",...Vae(e),"","## Blocked Or Unavailable Checks","",...Gae(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...zae(e),"","## JSON","",`Machine-readable report: \`${Kae(e)}\``,""].join(`
1268
- `)}`}function Vae(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function Gae(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function zae(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",r=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${r})`})}function Wb(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Kae(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Jae(e,t,n){if(pN(gN(e),{recursive:!0}),(dN(e)?mN(e,"utf-8"):null)===t){n.unchanged.push(e);return}fN(e,t),n.written.push(e)}function Yae(e,t,n){pN(gN(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
1269
- `,i=dN(e)?mN(e,"utf-8"):null;if(i&&Qae(i,r)){n.unchanged.push(e);return}fN(e,r),n.written.push(e)}function Qae(e,t){try{let n=JSON.parse(e),r=JSON.parse(t);return delete n.generatedAt,delete r.generatedAt,JSON.stringify(n)===JSON.stringify(r)}catch{return e===t}}function Xae(e,t){return Hb(e,t)}function Hb(e,t){return typeof e=="string"?Zae(e,t):Array.isArray(e)?e.map(n=>Hb(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Hb(r,t)])):e}function Zae(e,t){if(e===t)return".";if(!Wae(e))return e;let n=uN(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=uN(Hae(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as ece}from"child_process";import{readFileSync as bN}from"fs";import{dirname as yN,join as tce,resolve as nce}from"path";import{fileURLToPath as rce}from"url";var Cp={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function ice(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of Cp[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function qb(e){return[...new Set(e.filter(t=>Cp[t]!==void 0))].sort()}function SN(e,t={}){let n=t.runtime??ace,r=t.packageRoot??oce(),i=qb(e),o=i.filter(d=>n.probe(Cp[d].ast)),s=i.filter(d=>!o.includes(d));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=sce(r),c=ice(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let u=i.filter(d=>n.probe(Cp[d].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:u,unavailable:i.filter(d=>!u.includes(d)),attempted:!0,...l.error?{error:l.error}:{}}}function oce(){let e=yN(rce(import.meta.url));for(;;){let t=tce(e,"package.json");try{if(JSON.parse(bN(t,"utf8")).name==="scip-query")return e}catch{}let n=yN(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function sce(e){return JSON.parse(bN(nce(e,"package.json"),"utf8")).optionalDependencies??{}}var ace={probe:e=>ul(e)==="ast",resetProbe:dv,install:(e,t)=>{let n=ece(process.env.npm_execpath?process.execPath:"npm",[...process.env.npm_execpath?[process.env.npm_execpath]:[],"install","--no-save","--no-package-lock","--include=optional",...t],{cwd:e,encoding:"utf8"});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function RN(e){let t=[];e.watchEnabled||t.push({id:"enable-automatic-refresh",scope:"repository",label:"Enable automatic incremental indexing",recommended:!0,requiresConsent:!0,reason:"A demand-started project service keeps indexes current and exits after a clean idle period.",command:"scip-query setup"}),e.files.agentsMd||e.files.claudeMd?t.push({id:"update-agent-guidance",scope:"repository",label:"Update project agent guidance",recommended:!0,requiresConsent:!0,reason:"Existing AGENTS.md or CLAUDE.md guidance can be updated in place.",command:"scip-query setup-agent"}):t.push({id:"create-agent-guidance",scope:"repository",label:"Create project agent guidance",recommended:!1,requiresConsent:!0,reason:"No AGENTS.md or CLAUDE.md file exists, so setup should ask before creating one.",command:"scip-query setup-agent"}),(!e.files.codexHooks||!e.files.claudeSettings)&&t.push({id:"install-project-hooks",scope:"checkout",label:"Install project agent hooks",recommended:!0,requiresConsent:!0,reason:"Project hooks help agents check freshness and route through scip-query before editing.",command:"scip-query setup-hooks"});let n=e.readiness.indexers.filter(r=>!r.runnable);return n.length>0&&t.push({id:"install-indexers",scope:"user",label:"Install missing language indexers",recommended:!0,requiresConsent:!0,reason:`${n.length} detected language indexer(s) are not runnable.`,command:"scip-query setup"}),{actions:t}}async function CN(e={}){let t=[],n=Ir(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?NE(r,n.config,e.languages):null,c=a?.config??n.config,l=gs(c,{projectRoot:r}),u=l.filter(G=>G.level==="error"),d=null,p=null;if(u.length===0&&c.watch?.enabled!==s)try{d=AE(r,c,s)}catch(G){p=As(G)}let m=d?.config??c,f=Nc();de(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:p!==null?"failed":u.length>0||!s?"skipped":"ok",message:p??(u.length>0?"Skipped because the existing project config has validation errors.":s?d?.changed?"Enabled demand-started automatic incremental indexing for this project.":"Demand-started automatic incremental indexing is already enabled.":"Automatic incremental indexing remains explicitly disabled for this project."),...d?{details:[d.configPath]}:{}}),de(t,{id:"scip-cli",label:"scip CLI",status:f?"ok":"warn",message:f?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let g=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:sp({quiet:!0});de(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":g.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${g.installed.length} installed, ${g.alreadyLinked.length} already linked, ${g.pruned.length} pruned, ${g.skipped.length} skipped.`,details:[...g.pruned.map(G=>`Pruned ${G}`),...g.skipped.map(G=>`Skipped ${G}`)]});let h=d?gs(m,{projectRoot:r}):l,y=h.filter(G=>G.level==="error");de(t,{id:"config",label:"Project config",status:y.length>0?"failed":h.length>0?"warn":"ok",message:h.length===0?"Config OK.":`${h.length} diagnostic(s), ${y.length} error(s).`,details:h.map(G=>`${G.level.toUpperCase()} ${G.path}: ${G.message}`)});let x=bn(r,m);de(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(G=>!G.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(G=>`${G.runnable?"OK":G.installed?"WARN":"MISSING"} ${G.language}: ${G.binaryLabel}${G.note?` - ${G.note}`:""}`)});let R=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:SN(x.languages);de(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":R.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":R.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${R.availableAfter.length}/${R.supportedLanguages.length} selected language parser(s) available${R.installed.length>0?`; installed ${R.installed.join(", ")}`:""}.`,details:[...R.unavailable.length>0?[`Unavailable: ${R.unavailable.join(", ")}`]:[],...R.error?[R.error]:[]]});let b=e.installIndexers??!0,v=b?Sce(r,x,t):[];b||de(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let w=bn(r,m),I=await lce({projectRoot:r,paths:i,config:m,readiness:w,configHasErrors:y.length>0,steps:t,onStatus:e.onStatus}),C=I.reindexResult,k=I.freshness,T=Yn(m),F=uce({projectRoot:r,cacheDir:i.cacheDir,watchConfig:T,readiness:w,configHasErrors:y.length>0,reindexResult:C,postReindexFreshness:k,steps:t}),V=bn(r,m),ie=li(V),W=En(r,m,i);de(t,{id:"capabilities",label:"Capability matrix",status:kce(ie),message:Ice(ie)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let be=e.runHealth===!1?Rce(t):await xce(i.dbPath,t),Z=V.languages.includes("rust")?tu(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;de(t,{id:"rust-semantic-session",label:"Rust semantic session",status:Z===null?"skipped":Z.valid?"ok":"failed",message:Z===null?"Skipped because Rust was not detected.":`${Z.transport}/${Z.state} selected from ${Z.source}; ${Z.fallback} fallback; opt out with ${Z.optOut}.`});let Re=null;try{e.noHooks?de(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(Re=Ls(r),de(t,{id:"project-hooks",label:"Project agent hooks",status:Re.skipped.length>0?"warn":"ok",message:`${Re.installed.length} installed, ${Re.updated.length} updated, ${Re.unchanged.length} already configured, ${Re.removed.length} hook config(s) cleaned up, ${Re.skipped.length} skipped.`,details:[...Re.gitExcluded.map(G=>`Checkout-local Git exclude: ${G}`),...Re.removed.map(G=>`Removed ${G}`),...Re.skipped.map(G=>`Skipped ${G.target}: ${G.reason}`),...Re.warnings]}))}catch(G){de(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:As(G)})}let ht=null;try{e.noAgentGuidance?de(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(ht=zd(r,{gitHook:e.gitHook}),de(t,{id:"agent-guidance",label:"Project agent guidance",status:ht.skipped.length>0?"warn":"ok",message:`${ht.written.length} written, ${ht.unchanged.length} already wired, ${ht.skipped.length} skipped.`,details:ht.skipped.map(G=>`Skipped ${G.target}: ${G.reason}`)}))}catch(G){de(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:As(G)})}let yi=dce({reindexResult:C,readiness:V,capabilities:ie,freshness:W,health:be,hooksResult:Re,agentResult:ht,watchConfig:T,watchService:F,rustSemanticSession:Z,steps:t});de(t,{id:"smoke-tests",label:"Setup smoke tests",status:pce(yi),message:mce(yi),details:yi.map(G=>`${G.command}: ${G.status} - ${G.evidence}`)});let Ws={repository:[...a?.changed?[a.configPath]:[],...d?.changed?[d.configPath]:[],...ht?.written.filter(G=>!G.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...Re?.installed??[],...Re?.updated??[],...Re?.gitExcluded??[],...ht?.written.filter(G=>G.startsWith(".git/hooks/"))??[]])],user:[...g.installed,...R.installed,...v.filter(G=>G.attempted).map(G=>`${G.binaryLabel} installer`)]},At={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:f,languages:V.languages,steps:t,skills:g,astParsers:R,initialReadiness:x,indexerRemediation:v,readiness:V,capabilities:ie,freshness:W,reindex:C,automaticRefreshConfig:d,watchService:F,rustSemanticSession:Z,health:be,smokeTests:yi,healthDossier:null,hooks:Re,setupAgent:ht,changeScopes:Ws,filesWritten:ht?.written??[],verdict:Vb(t,V)};if(e.runHealth===!1)return de(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),At.verdict=Vb(t,V),At;let _n=hN(At,{dossierDir:e.dossierDir});return At.healthDossier=_n,At.changeScopes.repository.push(..._n.written),At.filesWritten=[...At.filesWritten,..._n.written],de(t,{id:"health-dossier",label:"Health dossier",status:_n.status==="failed"?"failed":"ok",message:_n.status==="failed"?_n.error:`${_n.written.length} written, ${_n.unchanged.length} unchanged.`,details:[_n.markdownPath,_n.jsonPath]}),At.verdict=Vb(t,V),At}async function lce(e){if(e.readiness.languages.length===0||e.configHasErrors)return de(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,r=null;try{let i=0,o=!1;for(let s=0;s<2;s+=1){if(n=await Ns({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),i+=n.durationMs,o||=!n.reused,r=En(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&r.state==="stale"){t.push(`Index inputs changed during the first build (${r.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");de(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(i/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(i){de(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:As(i),details:t})}return{reindexResult:n,freshness:r}}function uce(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return de(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=va({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Fe,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let r=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return de(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${r}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return de(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:As(n)}),null}}function wN(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Wb(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),Ub("Repository records (commit)",e.changeScopes.repository),Ub("Checkout preferences (do not commit)",e.changeScopes.checkout),Ub("User environment",e.changeScopes.user),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",r=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${r})`),t.recovery&&console.log(` ${t.recovery}`)}}}function Ub(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function dce(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),r=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:fce(e.steps),evidence:gce(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?hce(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:vN(e.readiness,e.freshness),evidence:xN(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:vN(e.readiness,e.freshness),evidence:xN(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:yce(e.capabilities),evidence:bce(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":r?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:r?.message??"Project agent guidance was not written."}]}function pce(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function mce(e){let t=e.filter(i=>i.status==="pass").length,n=e.filter(i=>i.status==="unavailable").length,r=e.filter(i=>i.status==="fail").length;return`${t} passed, ${n} unavailable, ${r} failed.`}function fce(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function gce(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function hce(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(r=>r.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function vN(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function xN(e,t){if(!e.gitAvailable)return"Git is not available for this project.";let n=t.lastRefresh?` Last refresh: ${t.lastRefresh.result} by ${t.lastRefresh.trigger.kind} at ${t.lastRefresh.completedAt}.`:"";return`Git is available and index freshness is ${t.state}: ${t.reason}${n}`}function yce(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function bce(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(i=>i.cleanupVerification.status==="available").length,n=e.matrix.filter(i=>i.cleanupVerification.status==="partial").length,r=e.matrix.filter(i=>i.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${r} unavailable cleanup-verification row(s).`}function Sce(e,t,n){let r=[];if(t.languages.length===0)return de(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),r;for(let s of t.indexers){if(s.runnable)continue;let a=fr(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=zl(a,p=>c.push(p)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let d=vce(jo(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return de(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),r;let i=r.filter(s=>!s.after.runnable),o=r.filter(s=>s.attempted);return de(n,{id:"indexer-remediation",label:"Indexer remediation",status:i.length>0?"warn":"ok",message:i.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${i.length} indexer(s) still blocked.`,details:r.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),r}function vce(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function xce(e,t){if(!cce(e)){let n="Skipped because no SQLite index database exists yet.";return de(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Gb(n)}try{let n=await Ud({full:!0,json:!0});return de(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Cce(n)}catch(n){let r=As(n);return de(t,{id:"health",label:"Health audit",status:"failed",message:r}),Gb(r)}}function Rce(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return de(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Gb(t)}function Cce(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(wce),warnings:e.warnings??[]}}function wce(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-cleanup-audit to confirm this signal; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}}function Gb(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Vb(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function kce(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function Ice(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function de(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function As(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Pce}from"readline";function Ece(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Dce(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let r=n[e.cursor]?.id;if(!r)return e;let i=new Set(e.selected);return i.has(r)?i.delete(r):i.add(r),{...e,selected:i}}async function kN(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=Ece(e);Pce(t);let i=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
1270
- `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
1271
-
1272
- `),e.forEach((a,c)=>{let l=c===r.cursor?"\u203A":" ",u=r.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${u} ${a.label} [${a.scope}]\x1B[K
1273
- `)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(u,d)=>{if(d.ctrl&&d.name==="c"){l(),a(new Error("Setup cancelled."));return}if(d.name==="return"||d.name==="enter"){l(),n.write(`
1274
- `),s(r.selected);return}let p=d.name==="up"?"up":d.name==="down"?"down":d.name==="space"?"toggle":null;p&&(r=Dce(r,p,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as IN,mkdirSync as Tce,writeFileSync as Lce}from"fs";import{dirname as Fce,join as PN}from"path";function EN(e,t={}){let n=PN(e,".github","workflows","scip-query.yml"),r=Nce({hasNpmProject:IN(PN(e,"package.json"))});return IN(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(Tce(Fce(n),{recursive:!0}),Lce(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function Nce(e){let t=`scip-query@${Fe}`;return`name: scip-query
1275
-
1276
- # Generated by scip-query setup-ci.
1277
- # Install the language indexers your repository needs before the reindex step
1278
- # if they are not already provided by your dependency install.
1279
-
1280
- on:
1281
- pull_request:
1282
-
1283
- jobs:
1284
- diff-gate:
1285
- runs-on: ubuntu-latest
1286
- steps:
1287
- - uses: actions/checkout@v4
1288
- with:
1289
- fetch-depth: 0
1290
- - uses: actions/setup-node@v4
1291
- with:
1292
- node-version: 22
1293
- - uses: actions/cache@v4
1294
- with:
1295
- path: ~/.cache/scip-query
1296
- key: scip-query-\${{ runner.os }}-\${{ hashFiles('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock', 'go.sum', 'poetry.lock', 'uv.lock') }}
1297
- ${e.hasNpmProject?` - run: npm ci
1298
- `:[" # TODO: install this repository's dependencies before indexing."," # This project did not have a package.json when the workflow was generated."].join(`
1299
- `)+`
1300
- `} - run: npx ${t} reindex
1301
- - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
1302
- `}import{existsSync as Ace}from"fs";import{join as wp}from"path";function DN(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=CL({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=_ce(e.projectRoot,{dryRun:e.dryRun})),s}function _ce(e,t={}){return{hooks:Ls(e,{remove:!0,dryRun:t.dryRun}),agentSetup:UT(e,{dryRun:t.dryRun}),left:Mce(e)}}function Mce(e){return[[".scipquery.json",wp(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",wp(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",wp(e,".scipquery","ledger")],["docs/scip-query/",wp(e,"docs","scip-query")]].filter(([,t])=>Ace(t)).map(([t])=>t)}import{existsSync as NN,lstatSync as kp,readFileSync as Yb,readdirSync as AN,realpathSync as TN,rmSync as Bc,statSync as _N}from"fs";import{join as st,resolve as fo,sep as LN}from"path";var $ce=3600*1e3,Oce=2*1024*1024*1024,jce=300*1e3;function Bce(e){let t=e.leases.filter(a=>a.managed&&!a.live&&!a.busy),n=MN(e.leases,e.locks),r={};for(let a of e.generations)n.has(a.generationId)||(r[a.generationId]=a.unreferencedAt??e.nowMs);let i=e.generations.filter(a=>!n.has(a.generationId)).sort((a,c)=>r[a.generationId]-r[c.generationId]||a.generationId.localeCompare(c.generationId)),o=new Set;for(let a of i)e.nowMs-r[a.generationId]>=e.policy.generationTtlMs&&o.add(a.generationId);let s=e.generations.filter(a=>!o.has(a.generationId)).reduce((a,c)=>a+c.size,0);for(let a of i){if(s<=e.policy.budgetBytes)break;o.has(a.generationId)||(o.add(a.generationId),s-=a.size)}for(let a of o)delete r[a];return{deleteWorktrees:t,deleteGenerations:e.generations.filter(a=>o.has(a.generationId)),deleteLocks:e.locks.filter(a=>!a.live),deleteTemporaries:e.temporaries.filter(a=>!a.live),protectedGenerationIds:[...n].sort(),unreferencedSince:r}}function MN(e,t){let n=new Set(e.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of t)r.live&&n.add(r.generationId);return n}function $N(e,t,n={}){if(!dc())return{kind:"disabled"};let r=Wt(e);if(!r)return{kind:"unavailable"};let i=st(hs(),"repositories",r.repositoryId);if(!NN(i))return{kind:"unavailable"};let o=(n.now??Date.now)(),s=st(i,"gc-state.json"),a=WN(s);if(!n.force&&a&&o-Date.parse(a.lastSweepAt)<jce)return{kind:"throttled",sweptAt:a.lastSweepAt};let c=mc(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=jN(e,i,r.repositoryId,a?.unreferencedSince??{}),u=Bce({nowMs:o,...l,policy:{generationTtlMs:n.policy?.generationTtlMs??$ce,budgetBytes:n.policy?.budgetBytes??Oce}}),d=0,p=0;for(let g of u.deleteWorktrees){if(!BN(g.lease))continue;let h=to(st(g.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(Kb(g.lease,!0))continue;try{pu({projectRoot:g.lease.projectRoot,cacheDir:g.lease.localCacheDir,cliVersion:t})}catch{continue}if(Kb(g.lease,!0))continue;Bc(g.lease.localCacheDir,{recursive:!0,force:!0}),Bc(g.leasePath,{force:!0}),p+=1}finally{h.release()}}for(let g of u.deleteLocks)Bc(g.path,{force:!0});for(let g of u.deleteTemporaries)Bc(g.path,{recursive:!0,force:!0});for(let g of u.deleteGenerations)Bc(g.path,{recursive:!0,force:!0}),d+=g.size;DS(st(i,"evidence.db"));let m={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:u.deleteGenerations.length,deletedBytes:d,protectedGenerations:u.protectedGenerationIds.length},f={version:1,lastSweepAt:m.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:m};return he(s,f,{spacing:2,trailingNewline:!0}),m}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function ON(e,t,n){let r=Cs(e,n.dbPath,t);if(r)return{state:"bypassed",reason:r,localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let i=Wt(e);if(!i)return{state:"unavailable",reason:"Git worktree identity is unavailable",localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let o=st(hs(),"repositories",i.repositoryId),s=HN(st(o,"worktrees",`${i.worktreeId}.json`)),a=WN(st(o,"gc-state.json")),c=jN(e,o,i.repositoryId,a?.unreferencedSince??{}),l=MN(c.leases,c.locks),u=c.generations.filter(f=>!l.has(f.generationId)),d=c.generations.reduce((f,g)=>f+g.size,0),p=ws(e,t),m=0;return p&&(m=Hce(p)),{state:"managed",repositoryId:i.repositoryId,worktreeId:i.worktreeId,localCacheDir:n.cacheDir,...s?{baseGenerationId:s.baseGenerationId,activeGenerationId:s.activeGenerationId,lastAction:s.lastAction,reason:s.lastReason,lastSeenAt:s.lastSeenAt}:{},generations:c.generations.length,generationBytes:d,protectedGenerations:c.generations.filter(f=>l.has(f.generationId)).length,unreferencedGenerations:u.length,unreferencedBytes:u.reduce((f,g)=>f+g.size,0),temporaryGenerations:c.temporaries.length,sharedEvidence:{path:p,exists:m>0,bytes:m},cleanup:a?.lastResult}}function Hce(e){return[e,`${e}-wal`,`${e}-shm`].reduce((t,n)=>{try{return t+_N(n).size}catch{return t}},0)}function jN(e,t,n,r){let i=new Set(su(e).map(l=>fo(l.path))),o=[];for(let l of zb(st(t,"worktrees"))){if(!l.endsWith(".json"))continue;let u=st(t,"worktrees",l),d=HN(u);if(!d)continue;let p=fo(d.projectRoot);o.push({leasePath:u,lease:d,managed:d.repositoryId===n&&BN(d),live:i.has(p)||NN(p),busy:Kb(d)})}let s=[];for(let l of zb(st(t,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(l);if(!u)continue;let d=st(t,"locks",l),p=Jb(d),m=p!==void 0&&xe(p),f=u[1];s.push({generationId:f,path:d,live:m})}let a=[],c=[];for(let l of zb(st(t,"generations"))){let u=/^\.tmp-(\d+)-/.exec(l);if(u){let m=st(t,"generations",l),f=Number(u[1]);try{c.push({path:m,size:FN(m),live:Number.isSafeInteger(f)&&xe(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let d=st(t,"generations",l),p;try{p=kp(d)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||a.push({generationId:l,path:d,size:FN(d),...r[l]===void 0?{}:{unreferencedAt:r[l]}})}return{leases:o,generations:a,locks:s,temporaries:c}}function BN(e){if(e.ownershipChecksum!==Cc(e)||fo(e.localCacheDir)!==fo(ys(e.projectRoot)))return!1;let t=fo(hs()),n=fo(st(t,"projects")),r=fo(e.localCacheDir);if(!r.startsWith(`${n}${LN}`))return!1;try{let i=kp(t),o=kp(n),s=kp(r);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink())return!1;let a=TN(n);return TN(r).startsWith(`${a}${LN}`)}catch{return!1}}function Kb(e,t=!1){for(let r of t?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Jb(st(e.localCacheDir,r));if(i!==void 0&&xe(i))return!0}let n=Jb(Hn(e.localCacheDir).lockPath);return n!==void 0&&xe(n)}function HN(e){try{let t=JSON.parse(Yb(e,"utf8"));return t.version!==1||typeof t.repositoryId!="string"||typeof t.worktreeId!="string"||typeof t.projectRoot!="string"||t.treeOid!==void 0&&typeof t.treeOid!="string"||typeof t.localCacheDir!="string"||t.baseGenerationId!==void 0&&typeof t.baseGenerationId!="string"||t.activeGenerationId!==void 0&&typeof t.activeGenerationId!="string"||typeof t.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(t.ownershipChecksum)||typeof t.lastAction!="string"||t.lastReason!==void 0&&typeof t.lastReason!="string"||typeof t.lastSeenAt!="string"?null:t}catch{return null}}function Jb(e){try{let t=JSON.parse(Yb(e,"utf8"));return typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0?t.pid:void 0}catch{return}}function WN(e){try{let t=JSON.parse(Yb(e,"utf8"));return t.version!==1||typeof t.lastSweepAt!="string"||!Number.isFinite(Date.parse(t.lastSweepAt))||!t.unreferencedSince||typeof t.unreferencedSince!="object"||!t.lastResult?null:t}catch{return null}}function zb(e){try{return AN(e)}catch{return[]}}function FN(e){let t=0,n=[e];for(;n.length>0;){let r=n.pop();for(let i of AN(r,{withFileTypes:!0})){let o=st(r,i.name);i.isDirectory()?n.push(o):i.isFile()&&(t+=_N(o).size)}}return t}import{existsSync as Wce,readFileSync as qce}from"fs";import{createRequire as Uce}from"module";import Pp from"path";import{performance as Ip}from"perf_hooks";var Vce=Uce(import.meta.url),Hc;function zN(e){let t=Gce();if(!t)return Kr("typescript is not installed");let n=fu(e);if(n.length===0)return Kr("no tsconfig found");try{return new Qb(e.config.projectRoot,t,n.map(r=>zce(t,r)))}catch(r){return Kr(r instanceof Error?r.message:String(r),n[0],n)}}function KN(e,t,n){let r=Ip.now(),i=qN(t,e),o=Ip.now()-r,s=Ip.now(),a=qN(n,e),c=Ip.now()-s,l=[],u=0,d=0,p=0,m=0,f=0;for(let g of e){let h=i.get(g.symbolId)??[],y=a.get(g.symbolId)??[];d+=h.length,p+=y.length;let x=UN(h),R=UN(y),b=VN(h,R),v=VN(y,x);if(b.length===0&&v.length===0){u+=1;continue}m+=b.length,f+=v.length,l.push({symbol:g.symbol,missing:b,extra:v})}return{slot:"semantic-references",definitions:e.length,matches:u,mismatchCount:l.length,missingReferenceCount:m,extraReferenceCount:f,baselineReferenceCount:d,candidateReferenceCount:p,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var Qb=class{constructor(t,n,r){this.projectRoot=t;this.ts=n;this.bundles=r}projectRoot;ts;bundles;language="typescript";referencesCache=new Map;availability(){return{available:!0,tsconfigPath:this.bundles[0]?.tsconfigPath,tsconfigPaths:this.bundles.map(t=>t.tsconfigPath)}}importUsage(t){return[]}referencesFor(t){let n=this.referencesCache.get(t.symbolId);if(n)return n;let r=this.computeReferences(t);return this.referencesCache.set(t.symbolId,r),r}referencesForDefinitions(t){let n=new Map;for(let r of t)n.set(r.symbolId,this.referencesFor(r));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=Pp.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=Jce(this.ts,i,t);if(o===null)return[];let s=r.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let u=Yce(this.ts,r.service,this.projectRoot,l);u&&(u.file===t.relativePath&&u.line>=t.startLine&&u.line<=t.endLine||a.push(u))}return Gr(a)}bundleForFile(t){let n=YN(t);return this.bundles.find(r=>r.files.has(n))??null}};function Gce(){if(Hc!==void 0)return Hc;try{Hc=Vce("typescript")}catch{Hc=null}return Hc}function zce(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(GN(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,Pp.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>GN(e,s)).join(`
1303
- `));let i=new Set(r.fileNames.map(YN)),o=e.createLanguageService(Kce(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Kce(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?Pp.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Wce(n))return e.ScriptSnapshot.fromString(qce(n,"utf8"))},getScriptVersion:()=>"0",readDirectory:e.sys.readDirectory,readFile:e.sys.readFile,fileExists:e.sys.fileExists,directoryExists:e.sys.directoryExists,realpath:e.sys.realpath,useCaseSensitiveFileNames:()=>e.sys.useCaseSensitiveFileNames}}function Jce(e,t,n){let r=t.text.split(`
1304
- `),i=Math.max(0,n.startLine),o=Math.min(r.length-1,Math.max(n.endLine,n.startLine));for(let s=i;s<=o;s+=1){let a=r[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function Yce(e,t,n,r){let i=zr(n,r.fileName);if(!i)return null;let o=t.getProgram()?.getSourceFile(r.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,r.textSpan.start);return{file:i,line:s.line,column:s.character}}function qN(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function UN(e){return new Set(e.map(JN))}function VN(e,t){return e.filter(n=>!t.has(JN(n)))}function JN(e){return`${e.file}:${e.line}:${e.column}`}function YN(e){return Pp.resolve(e).replace(/\\/g,"/")}function GN(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
1305
- `)}import{readFileSync as Qce}from"fs";function QN(e){let t=[];for(let[n,r]of Qce(e,"utf8").split(`
1306
- `).entries()){let i=r.trim();if(!i)continue;let o;try{o=JSON.parse(i)}catch(s){throw new Error(`${e}:${n+1}: invalid profile JSON: ${s instanceof Error?s.message:String(s)}`,{cause:s})}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e}:${n+1}: profile event must be a JSON object`);t.push(o)}return t}function XN(e,t={}){let n=new Map,r=new Map,i=new Map,o=new Set,s=new Set,a=new Set,c=new Set,l=0,u=0,d=0;for(let[h,y]of e.entries()){let x=Sn(y.name)??Sn(y.phase),R=ile(y.durationMs),b=Sn(y.runId);x&&R!==null&&(l+=1,s.add(x),b&&o.add(b),Xce(i,y,x,R),Zce(r,y,x,R,b),Sn(y.subsystemWorkIdentity)&&c.add(x));let v=Sn(y.workIdentity);if(!v)continue;u+=1,x&&a.add(x);let w=rle(y.workOutcome);if(!x||R===null||!w){d+=1;continue}let I=b??`unknown-run-${h}`,C=JSON.stringify([x,v]),k=n.get(C)??{spanName:x,workIdentity:v,observations:[]};k.observations.push({runId:I,command:Sn(y.command)??"unknown",durationMs:R,outcome:w}),n.set(C,k)}let p=[...n.values()].map(nle).filter(h=>h!==null).sort((h,y)=>y.estimatedAvoidableMs-h.estimatedAvoidableMs||y.repeatComputations-h.repeatComputations||h.spanName.localeCompare(y.spanName)||h.workIdentity.localeCompare(y.workIdentity)),m=[...r.values()].map(ele).filter(h=>h!==null).sort((h,y)=>y.laterRunMs-h.laterRunMs||y.laterRunEvents-h.laterRunEvents||h.spanName.localeCompare(y.spanName)),f=[...i.values()].map(tle).sort((h,y)=>y.totalDurationMs-h.totalDurationMs||h.subsystem.localeCompare(y.subsystem)),g=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:u,unclassifiedInstrumentedEvents:d,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:f.reduce((h,y)=>h+y.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:p.length,largestOpportunityMs:p[0]?.estimatedAvoidableMs??0,rows:p.slice(0,g),repeatedWorkloads:m.length,largestRepeatedWorkloadMs:m[0]?.laterRunMs??0,workloadRows:m.slice(0,g),subsystemCoverage:f}}function ZN(e,t){let n=["scip-query work-audit",`Profile: ${t}`,`Profile events: ${e.profileEvents}; spans: ${e.spanEvents}; distinct span names: ${e.distinctSpanNames}; runs: ${e.runCount}`,`Subsystem identity coverage: ${e.workloadIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.workloadIdentifiedEvents}/${e.spanEvents} events`,`Exact identity coverage: ${e.exactIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.instrumentedEvents}/${e.spanEvents} events`,`Repeated work groups: ${e.repeatedGroups}; largest measured opportunity: ${e.largestOpportunityMs}ms`,""];if(e.rows.length===0)n.push("No exact repeated computations were found in work-identified profile events."),e.instrumentedEvents===0&&n.push("This profile predates exact work identities or its spans have not been instrumented yet.");else{n.push("Exact repeated computations:"),n.push("avoidableMs withinRunMs crossRunMs repeats runs span workIdentity commands");for(let r of e.rows)n.push([r.estimatedAvoidableMs,r.withinRunAvoidableMs,r.crossRunRecomputeMs,r.repeatComputations,r.runCount,r.spanName,r.workIdentity,r.commands.join(", ")].join(" "))}if(n.push("",`Repeated subsystem workloads: ${e.repeatedWorkloads}`),e.workloadRows.length===0)n.push("No named subsystem workload was observed in more than one run.");else{n.push("laterRunMs firstRunMs laterEvents runs subsystem span subsystemWorkIdentity commands");for(let r of e.workloadRows)n.push([r.laterRunMs,r.firstRunMs,r.laterRunEvents,r.runCount,r.subsystem,r.spanName,r.subsystemWorkIdentity,r.commands.join(", ")].join(" "))}return n.push("","Rows are independent measurements; nested spans can overlap and must not be summed."),n.push("Within-run time is direct duplication. Cross-run time is a durable-cache opportunity that still needs safe invalidation."),n.push("Subsystem workload time is an aggregate observation against the same command/project inputs, not proven avoidable time."),`${n.join(`
1307
- `)}
1308
- `}function Xce(e,t,n,r){let i=Sn(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(i)??{subsystem:i,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=r,o.spanNames.add(n),Sn(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),Sn(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function Zce(e,t,n,r,i){let o=Sn(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=Sn(t.subsystem)??n.split(/[.:]/,1)[0]??n,a=JSON.stringify([n,o]),c=e.get(a)??{subsystem:s,spanName:n,subsystemWorkIdentity:o,observations:[]};c.observations.push({runId:i,command:Sn(t.command)??"unknown",durationMs:r}),e.set(a,c)}function ele(e){let t=new Map;for(let o of e.observations){let s=t.get(o.runId)??[];s.push(o),t.set(o.runId,s)}let n=[...t.values()];if(n.length<2)return null;let r=n[0],i=n.slice(1).flat();return{subsystem:e.subsystem,spanName:e.spanName,subsystemWorkIdentity:e.subsystemWorkIdentity,commands:[...new Set(e.observations.map(o=>o.command))].sort(),runCount:n.length,totalEvents:e.observations.length,firstRunEvents:r.length,laterRunEvents:i.length,totalDurationMs:_s(e.observations.map(o=>o.durationMs)),firstRunMs:_s(r.map(o=>o.durationMs)),laterRunMs:_s(i.map(o=>o.durationMs))}}function tle(e){return{subsystem:e.subsystem,events:e.events,totalDurationMs:e.totalDurationMs,spanNames:[...e.spanNames].sort(),workloadIdentifiedEvents:e.workloadIdentifiedEvents,workloadIdentifiedSpanNames:e.workloadIdentifiedSpanNames.size,exactIdentifiedEvents:e.exactIdentifiedEvents,exactIdentifiedSpanNames:e.exactIdentifiedSpanNames.size}}function nle(e){let t=e.observations.filter(a=>a.outcome==="computed");if(t.length<2)return null;let n=new Map;for(let a of t){let c=n.get(a.runId)??[];c.push(a),n.set(a.runId,c)}let r=[...n.values()],i=_s(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=_s(r.slice(1).map(a=>a[0]?.durationMs??0)),s=[...new Set(e.observations.map(a=>a.command))].sort();return{spanName:e.spanName,workIdentity:e.workIdentity,commands:s,computations:t.length,runCount:r.length,repeatComputations:t.length-1,withinRunRepeats:t.length-r.length,crossRunRecomputes:Math.max(0,r.length-1),totalComputeMs:_s(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:Ep(e.observations,"cache-hit"),cacheMisses:Ep(e.observations,"cache-miss"),reused:Ep(e.observations,"reused"),skipped:Ep(e.observations,"skipped")}}function rle(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function Ep(e,t){return e.filter(n=>n.outcome===t).length}function ile(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Sn(e){return typeof e=="string"&&e.length>0?e:null}function _s(e){return e.reduce((t,n)=>t+n,0)}var eA={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function tA(e,t){let n=ole(t);return{...e,warnings:[...e.warnings??[],eA.note,...n],capabilities:t,scoreInterpretation:eA}}function ole(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(r=>/syntax only/i.test(r.reason)?`${r.label}=partial (syntax only)`:r.status==="available"?null:`${r.label}=${r.status}`).filter(r=>r!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}var nA=Symbol("option-value-source"),rA=new Map;function iA(e){rA=new Map(e)}function We(e){return(...t)=>{let{args:n,opts:r}=eS(t);Ee(i=>e({db:i,args:n,opts:r}))}}function Ne(e,t){return We(n=>{let r=qd(n.db,e,E(n.opts,"full"),{quiet:E(n.opts,"json")});t({...n,budget:r})})}function oA(e){return We(t=>$s(t,e,{kind:"list"}))}function sA(e){return We(t=>$s(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function aA(e){return We(t=>$s(t,e,{kind:"grouped",key:e.key}))}function fi(e){return We(t=>Zb(t,e))}function cA(e){return fi({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>O.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function vn(e,t){return Ne(e,n=>Zb(n,{...t,commandName:t.commandName??e}))}function lA(e,t){return vn(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>O.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function Yt(e,t){return Ne(e,n=>$s(n,{...t,commandName:e},{kind:"list"}))}function Dp(e,t){return Ne(e,n=>$s(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Tp(e,t){return Ne(e,n=>$s(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function U(e,t){return String(e[t])}function ke(e,t){let n=e[t];return typeof n=="string"?n:void 0}function A(e,t){let n=e[t];return typeof n=="string"?n:void 0}function De(e,t){let n=e[t];return typeof n=="number"?n:void 0}function E(e,t){return!!e[t]}function Ms(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function $(e,t,n){return De(e,t)??n}function Y(e,t,n){let r=De(e,t),i=r!==void 0&&Xb(e,t)!=="default";if(E(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.MAX_SAFE_INTEGER}return r??n}function Xb(e,t){return e[nA]?.(t)}function $s(e,t,n){Zb(e,{commandName:t.commandName,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"?O.list(r,o=>t.format(o,i)):n.kind==="table"?O.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):O.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,before:t.before,after:t.after})}function Zb(e,t){let n=t.query(e);if(E(e.opts,"json")){H(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n,{analysisBudget:sle(e)});return}let r=t.emptyMessage?.(n,e);if(r){O.empty(r);return}t.heuristicLabel&&Jt(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function sle(e){return e.budget?.analysisBudget}function H(e,t,n,r,i={}){let o=e?rA.get(e):void 0;console.log(JSON.stringify({command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:ale(t),options:n,result:r},null,2))}function ale(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function eS(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:Te(t)}}function Te(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,nA,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var gle=new Set(xd),hle=18e4,mA=100*1024*1024,yle=new Set(Mm),ble=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Sle=[["health","--json"],["dead","--json","--full"],["isolated","--json","--full"],["similar","--json","--full"],["similar-files","--json","--full"],["recent-duplicates","--json","--full"],["doc-drift","--json","--full"],["unused-params","--json","--full"],["wrapper-candidates","--json","--full"],["passthrough-candidates","--json","--full"],["stale-abstractions","--json","--full"],["incomplete-migration","--json","--full"],["cleanup-plan","--verify","--json"],["complexity-hotspots","--json","--full"]];function vle(e){return e.filter(t=>gle.has(t))}async function fA(e){let t=Te(e),n=Me(),r=ut(n),i=zt(n,r),o=E(t,"json");try{let s=vle(Ms(t,"language")),a=await Ns({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:E(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!E(t,"force"),allowPartial:E(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:De(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){H("reindex",[],t,a);return}console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}function gA(){let e=Me(),t=ks(e);try{let n=cp({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 hA(e){let t=Te(e),n=Me(),r=ks(n);try{let i=Nb({projectRoot:n,dbPath:r,tsconfig:A(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}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function yA(e){let t=Te(e);Ee(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=zn(n,{base:A(t,"base")}),o=Yu(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function bA(e){let t=Te(e);try{let n=await RT({base:A(t,"base")});if(E(t,"json")){H("diff-impact",[],t,n);return}wT(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function SA(e,t){let n=Te(t),r=String(e).split(",").filter(i=>i.length>0);Ee(i=>{let o=[];for(let c of r)ms.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:A(n,"scope"),full:E(n,"full")},a=o.length===1?lc(i,o[0],s):zh(i,o,s);console.log(JSON.stringify(a))})}async function vA(e){let t=Te(e);if(E(t,"writeBaseline")||E(t,"baseline")){Ale(t);return}try{let n=await Ud({scope:A(t,"scope"),full:E(t,"full"),json:E(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Ir(),s=li(bn(r,i),{hasIndexedGraph:An(o)}),a=tA(n,s);if(E(t,"json")){H("health",[],t,a);return}xT(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function xA(e){let t=Te(e),n=Me(),r=De(t,"timeoutMs")??hle,i=E(t,"progress"),o=E(t,"profile"),s=A(t,"profileOut"),a={projectRoot:n,...Tle(n),index:tS(An(ks(n))),commands:[]};E(t,"coldIndex")&&(Os(i,"cold index started"),a.coldIndex=await xle(n),Os(i,`cold index finished ${a.coldIndex.durationMs}ms`),jt({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),Os(i,"warm index started"),a.warmIndex=await kle(n),Os(i,`warm index finished ${a.warmIndex.durationMs}ms`),jt({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=tS(An(ks(n))));for(let c of Ile(t))a.commands.push(Ele(n,c,r,{progress:i,profile:o,profileOut:s}));if(E(t,"json")){H("bench",[],t,a);return}Lle(a)}function RA(e,t){let n=Te(t),r=fle(String(e)),i=XN(QN(r),{top:De(n,"top")??20});if(E(n,"json")){H("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(ZN(i,r))}function CA(e){let t=Te(e);Ee(n=>{let r=n.config.projectRoot,i=A(t,"scope")??null,o=E(t,"full"),s=De(t,"limit")??200,a=Math.max(0,De(t,"maxMismatches")??10),c=Ue(n).filter(R=>bt(R.relativePath)).filter(R=>!n.isIgnored(R.relativePath)).sort(Nle),l=i?c.filter(R=>R.relativePath.includes(i)):c,u=o?l:l.slice(0,s),d=gi.now(),p=bu(n),m=Number((gi.now()-d).toFixed(3)),f=gi.now(),g=zN(n),h=Number((gi.now()-f).toFixed(3)),y=KN(u,p,g),x={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:u.length},baseline:{provider:"ts-morph",createMs:m,availability:p.availability()},candidate:{provider:"tsserver",createMs:h,availability:g.availability()},comparison:{...y,mismatches:y.mismatches.slice(0,a)}};if(E(t,"json")){H("typescript-semantic-compare",[],t,x);return}Fle(x)})}async function xle(e){let t=ut(e),n=zt(e,t),r=Lp(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Rle(r);let o=Cle(r,i);try{let s=await wA(()=>Ns({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return uA(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...kA(e)}}catch(s){throw uA(r,i,o,"restore-backup"),s}}var nS={existsSync:An,readFileSync:cle,writeFileSync:ple,renameSync:lle,rmSync:ule,unlinkSync:dle};function rS(e){return go(Lp(e),"bench-restore.json")}function Rle(e,t=nS){let n=rS(e);if(!t.existsSync(n))return!1;let r=wle(t.readFileSync(n,"utf8"));return r&&!t.existsSync(r.originalPath)&&t.existsSync(r.backupPath)&&t.renameSync(r.backupPath,r.originalPath),t.unlinkSync(n),!0}function Cle(e,t,n=nS){return n.existsSync(e)?(n.writeFileSync(rS(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function uA(e,t,n,r,i=nS){n&&r==="restore-backup"&&!i.existsSync(e)&&i.existsSync(t)?i.renameSync(t,e):n&&r==="discard-backup"&&i.rmSync(t,{recursive:!0,force:!0});let o=rS(e);i.existsSync(o)&&i.unlinkSync(o)}function wle(e){try{let t=JSON.parse(e);return typeof t.originalPath=="string"&&typeof t.backupPath=="string"?{originalPath:t.originalPath,backupPath:t.backupPath}:null}catch{return null}}async function kle(e){let t=ut(e),n=zt(e,t),r=await wA(()=>Ns({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...kA(e)}}async function wA(e){let t=gi.now(),n=await e();return{durationMs:Math.round(gi.now()-t),value:n}}function kA(e){return An(ks(e))?Ee(t=>{let n=Ut(t);return{files:n.documents,symbols:n.symbols}}):{}}function Ile(e){let t=Ms(e,"command");return t.length>0?t.map(Ple).filter(n=>n.length>0):[...ble.map(n=>[...n]),...E(e,"includeHeavy")?Sle.map(n=>[...n]):[]]}function Ple(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function Ele(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Os(r.progress,`${i} started`),jt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=gi.now(),s={...r.profile?Dle(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=pA(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:mA,timeout:n}),c=Math.round(gi.now()-o),l={command:i,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.code==="ETIMEDOUT"||a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...r.profileOut?{profilePath:r.profileOut}:{}};return Os(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),jt({type:"bench-command-finish",command:i,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},r.profileOut),l}function Os(e,t){e&&process.stderr.write(`[bench] ${t}
1309
- `)}function Dle(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function Tle(e){let t=pA("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:mA});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
1310
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>yle.has(mle(r).toLowerCase())).length}}function Lle(e){console.log("scip-query bench"),console.log(`Project: ${e.projectRoot}`),console.log(`Repo files: ${e.repoFiles??"unknown"}; source-like files: ${e.sourceFiles??"unknown"}`),e.index&&console.log(`Index: ${e.index.files} files, ${e.index.symbols} symbols, ${Xn(e.index.indexSizeBytes)}`),e.coldIndex&&dA("Cold index",e.coldIndex),e.warmIndex&&dA("Warm index",e.warmIndex),console.log(`
1311
- Commands:`);for(let t of[...e.commands].sort((n,r)=>r.durationMs-n.durationMs)){let n=t.timedOut?"timeout":t.exitCode===0?"ok":`exit ${t.exitCode??t.signal??"unknown"}`;console.log(` ${String(t.durationMs).padStart(7)}ms ${n.padEnd(10)} ${String(t.stdoutBytes).padStart(8)}B out ${t.command}`)}}function dA(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function Fle(e){if(console.log("TypeScript semantic provider comparison"),console.log(`Project: ${e.projectRoot}`),console.log(`Definitions: ${e.selection.comparedDefinitions}/${e.selection.scopedDefinitions} compared`+(e.selection.scope?`, scope ${e.selection.scope}`:"")),console.log(`ts-morph: create ${e.baseline.createMs}ms, refs ${e.comparison.baselineMs}ms, refs ${e.comparison.baselineReferenceCount}`),console.log(`tsserver: create ${e.candidate.createMs}ms, refs ${e.comparison.candidateMs}ms, refs ${e.comparison.candidateReferenceCount}`),console.log(`Matches: ${e.comparison.matches}; mismatches: ${e.comparison.mismatchCount}; missing refs: ${e.comparison.missingReferenceCount}; extra refs: ${e.comparison.extraReferenceCount}`),e.comparison.mismatches.length!==0){console.log(`
1312
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function Nle(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function Ale(e){let t=A(e,"scope");Ee(n=>{if(E(e,"writeBaseline")){let i=Dh(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Qa(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 IA(){let e=sp(),t=e.installed.length+e.alreadyLinked.length;console.log(`
1313
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function PA(e){let t=Te(e),n=Me(),r=Ls(n,{shared:E(t,"shared"),remove:E(t,"remove"),force:E(t,"force")});if(E(t,"json")){H("setup-hooks",[],t,r);return}for(let o of r.installed)console.log(` done: ${o}`);for(let o of r.updated)console.log(` update: ${o}`);for(let o of r.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of r.removed)console.log(` remove: ${o}`);for(let o of r.gitExcluded)console.log(` local: ${o} (excluded through .git/info/exclude)`);for(let o of r.warnings)console.log(` warning: ${o}`);for(let o of r.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);r.installed.length+r.updated.length+r.unchanged.length>0?(console.log(`
1314
- Checkout-local scip-query hooks are configured for this clone and must not be committed.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
1315
- No project-local hook config was written.`)}function EA(){let e=!1;Nc()?console.log("scip CLI: installed"):(ab(),e=!0);let t=Me(),n=ut(t),r=bn(t,n);if(r.languages.length===0){console.log(`
1316
- No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
1317
- Detected languages: ${r.languages.join(", ")}`),console.log(`
1318
- Indexer readiness:`);for(let o of r.indexers){let s=o.runnable?" OK":o.installed?" WARN":" MISSING",a=o.resolvedBinary?` (${o.resolvedBinary})`:"";console.log(`${s} ${o.language}: ${o.binaryLabel}${a}`),o.note&&console.log(` ${o.note}`),!o.installed&&o.installUrl&&console.log(` install: ${o.installUrl}`),o.runnable||(e=!0)}let i=GA(r);i.length>0&&console.log(`
1319
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${Ule(o)}${zA(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function DA(e){LA(e,"capabilities")}function TA(e){E(Te(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),LA(e,"capability-matrix")}function LA(e,t){let n=Te(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Ir(),a=bn(r,i),c=En(r,i,o),l=li(a,{hasIndexedGraph:An(s)&&c.state!=="missing"});if(E(n,"json")){H(t,[],n,l);return}iS(l)}function FA(){let e=Me(),t=gn(e),n=FE(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function NA(e){let t=Te(e),n=Me(),r=ut(n),i=gs(r,{projectRoot:n});if(E(t,"json"))H("config-validate",[],t,{diagnostics:i});else if(i.length===0)console.log("Config OK.");else for(let o of i)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);i.some(o=>o.level==="error")&&(process.exitCode=1)}function AA(e,t){let n=Te(t),r=A(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=vP(Me(),{id:String(e),check:A(n,"check"),file:A(n,"file"),reason:r,expiresAt:A(n,"expiresAt")});if(E(n,"json")){H("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function _A(e){let t=Te(e),n=Date.now(),r=A(t,"since"),i;if(r){let h=cN(r,n);if(h===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=h}let o=Me(),s=Xd(o),a=aN(s,{sinceMs:i,check:A(t,"check")});if(E(t,"json")){H("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${go(Qd,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=a.checks.map(h=>[h.check,String(h.caught),String(h.fixed),String(h.suppressed),String(h.open),String(h.moved),String(h.unverified),h.precision===null?"-":`${Math.round(h.precision*100)}%`,h.medianDaysToFix===null?"-":h.medianDaysToFix.toFixed(1)]),u=c.map((h,y)=>Math.max(h.length,...l.map(x=>x[y].length))),d=h=>h.map((y,x)=>y.padEnd(u[x])).join(" ");console.log(d(c));for(let h of l)console.log(d(h));let p=a.checks.reduce((h,y)=>h+y.fixed,0),m=a.checks.reduce((h,y)=>h+y.suppressed,0),f=a.checks.reduce((h,y)=>h+y.unverified,0),g=p+m;g>0?console.log(`
1320
- ${p} finding(s) verified fixed against a stable comparison base, ${m} suppressed, ${f} disappeared without comparable evidence \u2014 overall precision ${Math.round(p/g*100)}%.`):f>0&&console.log(`
1321
- ${f} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function MA(e){let t=Te(e),{report:n,hasIndexerProblems:r,hasErrors:i}=$A("doctor");E(t,"json")?H("doctor",[],t,n):Ble(n,r),process.exitCode=i?1:0}function $A(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Ir(),o=gs(n,{projectRoot:t}),s=bn(t,n),a=En(t,n,r),c=An(i),l=li(s,{hasIndexedGraph:c&&a.state!=="missing"}),u=ON(t,n,r),d=s.indexers.some(f=>!f.runnable),p=o.some(f=>f.level==="error")||d||a.state==="missing"||a.state==="stale",m=o.some(f=>f.level==="error")||d||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:u,ok:!p},hasIndexerProblems:d,hasErrors:m}}function OA(e){let t=Te(e),n=Me(),r=zd(n,{gitHook:E(t,"gitHook")});for(let i of r.written)console.log(` done: ${i}`);for(let i of r.unchanged)console.log(` ok: ${i} (already wired)`);for(let i of r.skipped)console.log(` skip: ${i.target} \u2014 ${i.reason}`);console.log(`
1322
- Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}async function jA(e){let t=Te(e);try{let n={gitHook:E(t,"gitHook"),noHooks:E(t,"noHooks")||t.hooks===!1,dossierDir:A(t,"dossierDir"),runHealth:E(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...E(t,"yes")?{automaticRefresh:!0}:{}},r=E(t,"json"),i=!r&&!E(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(E(t,"guided")||i)&&(n=await _le(n,{json:E(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await CN(n);E(t,"json")?H("setup",[],t,o):wN(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function _le(e,t){let{projectRoot:n,config:r}=Ir(),i=bn(n,r),o=RN({files:Mle(n),watchEnabled:Yn(r).enabled,readiness:i}),s=i.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=qb(i.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,u=l?await kN([...s,...a]):new Set([...$le(o.actions),...s.map(f=>f.id)]);l&&Ole(o.actions,u);let d=u.has("create-agent-guidance")||u.has("update-agent-guidance"),p=o.actions.some(f=>f.id==="enable-automatic-refresh"),m=o.actions.some(f=>f.id==="install-indexers");return{...e,...p?{automaticRefresh:u.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(f=>f.id==="install-project-hooks")&&!u.has("install-project-hooks"),noAgentGuidance:!d,...m?{installIndexers:u.has("install-indexers")}:{},languages:i.languages.filter(f=>u.has(`language:${f}`)),installSkills:u.has("install-agent-skills"),installAstParsers:u.has("install-ast-parsers"),runHealth:u.has("run-health-analysis")}}function Mle(e){return{agentsMd:An(go(e,"AGENTS.md")),claudeMd:An(go(e,"CLAUDE.md")),codexHooks:An(go(e,".codex","hooks.json")),claudeSettings:An(go(e,".claude","settings.local.json"))}}function $le(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function Ole(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let r=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${r.length>0?r.join(", "):"none"}`)}}function BA(e){let t=Te(e),n=Me(),r=EN(n,{force:E(t,"force"),dryRun:E(t,"dryRun")});if(E(t,"dryRun")){console.log(r.content);return}if(r.skipped){console.log(`skip: ${r.path} \u2014 ${r.reason}`);return}console.log(`done: ${r.path}`)}function HA(e){let t=Te(e);if(E(t,"global")&&E(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=DN({projectRoot:Me(),global:E(t,"global"),project:E(t,"project"),dryRun:E(t,"dryRun")});if(E(t,"json")){H("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function WA(e){let t=Te(e),n=Me(),r=ut(n),i=De(t,"debounce"),o=De(t,"cooldown"),s=De(t,"gitPoll"),a=De(t,"idleTimeout"),c=E(t,"daemon"),l=E(t,"status"),u=E(t,"stop"),d=E(t,"json"),p=[c,l,u].filter(Boolean).length;if(p>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(d&&p===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let m=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,b,v])=>b!==void 0&&(!Number.isInteger(b)||(v?Number(b)<0:Number(b)<=0)));if(m){console.error(`error: ${m[0]} requires ${m[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let f={...i===void 0?{}:{debounceMs:i},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};i&&((r.watch??={}).debounceMs=i),o!==void 0&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s),a!==void 0&&((r.watch??={}).idleTimeoutMs=a);let g=Yn(r);r.watch=g;let h=zt(n,r),y={projectRoot:n,cacheDir:h.cacheDir,cliVersion:Fe,watchOverrides:f};if(l){let b=qA(Bf(y),g.enabled);d?H("watch",[],t,b):UA(b);return}if(u){try{let b=pu(y);d?H("watch",[],t,b):console.log(b.disposition==="stopped"?`Stopped watch service${b.pid?` (pid ${b.pid})`:""}.`:"Watch service is already stopped.")}catch(b){console.error(`error: ${b instanceof Error?b.message:String(b)}`),process.exitCode=1}return}if(!g.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(c){try{let b=va(y);d?H("watch",[],t,b):console.log(`${b.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${b.state.pid}).`)}catch(b){console.error(`error: ${b instanceof Error?b.message:String(b)}`),process.exitCode=1}return}let x=SC(go(Lp(h.dbPath),Of),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let R=new Rp({projectRoot:n,config:r,languages:r.languages,onStatus:b=>{process.stdout.write(`\r\x1B[K${My(b)}`)},onReindexComplete:b=>{console.log(`
1323
- Reindex complete in ${(b/1e3).toFixed(1)}s`)},onError:b=>{console.error(`
1324
- Watch error: ${b.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${g.debounceMs}ms | Cooldown: ${g.cooldownMs}ms | Git poll: ${g.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
1325
- `),R.start(),process.on("SIGINT",()=>{R.stop(),x.release(),console.log(`
1326
- Stopped.`),process.exit(0)}),process.once("exit",x.release)}function qA(e,t=!0){let{classification:n}=e;switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt}:{enabled:t,state:"stopped",mode:"none"};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return jle(n)}}function UA(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${My(e.watcher)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function jle(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function VA(e){let t=Te(e),{report:n}=$A("status"),r=Yn(ut(n.projectRoot)).enabled,i=qA(Bf({projectRoot:n.projectRoot,cacheDir:Lp(n.configuredDbPath),cliVersion:Fe}),r),o=AL(n.dbPath),s=hn(n.dbPath,n.freshness.metaPath),a=tu(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(E(t,"json")){H("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:tS(n.exists)});return}Hle(n,{affectedSetShadow:o,capabilities:E(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function Ble(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(r=>!r.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),iS(e.capabilities)}function Hle(e,t){console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`);for(let n of GA(e.readiness)){let r=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",i=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${i.padEnd(9)}${r}${zA(n)}`),n.reason&&console.log(`${n.language} note: ${n.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${Vle(e.freshness.lastRefresh)}`),UA(t.watchService),Wle(e.sharedCache),console.log(`Rust sess: ${t.rustSemanticSession.transport}/${t.rustSemanticSession.state} (${t.rustSemanticSession.source}; worker fallback; opt out with ${t.rustSemanticSession.optOut})`),t.rustSemanticSession.valid||console.log("Rust note: invalid durable-session value; using worker fallback"),qle(t.sqliteGeneration),console.log(`Shadow: ${_L(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),Gle(e.exists),t.capabilities&&(console.log(""),iS(e.capabilities))}function Wle(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.activeGenerationId?.slice(0,12)??"none",n=e.lastAction??"none";console.log(`Shared: ${n}, active ${t}, ${e.generations} generation(s), ${Xn(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Xn(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${Xn(e.cleanup.deletedBytes??0)} removed`)}function qle(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",r=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(i=>i!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${r})`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function GA(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ule(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function zA(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function Vle(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",r=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${r}`}function tS(e){if(e)return Ee(t=>{let n=Ut(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function Gle(e){e&&Ee(t=>{let n=Ut(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Xn(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function iS(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
1327
- Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function Wc(e){return{...e,options:j(e.options)}}function er({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=Wc(a);return{...c,renderShape:"list",handler:oA({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function Fp({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let u=Wc(l);return{...u,renderShape:"table",handler:sA({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function KA({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=Wc(c);return{...l,renderShape:"grouped-by-file",handler:aA({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function JA({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=Wc(a);return{...c,renderShape:"sectioned-report",handler:cA({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function Np({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=Wc(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:lA(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as wue,mkdirSync as kue,writeFileSync as Iue}from"fs";import{dirname as Pue,relative as Eue}from"path";import{existsSync as Fr,readdirSync as Xle,readFileSync as ho}from"fs";import{basename as Zle,dirname as n_,isAbsolute as r_,join as eue,relative as tue,resolve as qc,sep as nue}from"path";import{spawnSync as Kle}from"child_process";import{dirname as Jle}from"path";function QA(e){let n=(e.spawnSync??Kle)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:Jle(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function XA(e){let t=Qle(e),n=new Map,r=new Map,i=[],o=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?r.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(i.push(a),o.set(a.uid,a));let s=[];for(let a of i){let c=ZA(a.block,n,r,o,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:i.map(a=>a.uniquename).sort(),actions:s}}var Yle=8;function Qle(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let r of e.matchAll(n)){let i=r.index,o=e.indexOf("</entry>",i),s=e.slice(i,o<0?e.length:o),a=oS(s,"uniquename"),c=oS(s,"kind"),l=oS(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:YA(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:YA(l),block:s})}return t}function ZA(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],u="read";for(let[,d,p]of l){if(d==="BuiltInKindRef"){let m=n.get(p)??"";m==="'"?u="write-next":m==="UNCHANGED"?u="unchanged-run":u==="unchanged-run"&&m==="$Tuple"||u!=="write-next"&&(u="read");continue}if(d==="OpDeclNodeRef"){let m=t.get(p);if(!m)continue;u==="write-next"?(c.add(m),u="read"):u==="unchanged-run"||a.add(m);continue}if(d==="UserDefinedOpKindRef"){u==="unchanged-run"&&(u="read");let m=r.get(p);if(m&&s<Yle&&!o.has(m.uid)&&m.filename===i){let f=ZA(m.block,t,n,r,i,new Set([...o,m.uid]),s+1);for(let g of f.reads)a.add(g);for(let g of f.writes)c.add(g)}continue}u==="unchanged-run"&&(u="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function oS(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function YA(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var i_=["update","insert","delete"],o_=["select","query","findFirst","findMany"],sS=new Set([...i_,...o_]);function aS(e){let t=e.methods&&e.methods.length>0?e.methods:[...sS],n=new Set(i_),r=new Set(o_);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var rue=/^(.*)@L(\d+)-L(\d+)$/;function cS(e){let t=e.match(rue);if(!t)return{ref:e};let n=t[1],r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return n?r<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:i<r?{error:`codeRef "${e}" line window end (L${i}) is before its start (L${r})`}:{ref:n,window:{startLine:r,endLine:i}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var iue=new Set(["auto","sany","tlc","apalache","none"]),_p=/^[A-Za-z_][A-Za-z0-9_]*$/;function s_(e){return iue.has(e)}function Mp(e,t){let n=[],r=Qt(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Fr(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(ho(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=oue(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:n_(r)},errors:n}:{errors:n}}function Qt(e,t){if(!t)return null;let n=r_(t)?qc(t):qc(e,t);return en(e,n)?n:null}function a_(e,t,n){if(!n)return null;if(r_(n)){let s=qc(n);return en(e,s)?s:null}let r=qc(e,n);if(en(e,r)&&Fr(r))return r;let i=qc(t,n);if(en(e,i)&&Fr(i))return i;let o=en(e,r)?r:i;return en(e,o)?o:null}function c_(e,t){let n=Qt(e,t);if(!n||!Fr(n))return null;let r=ho(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:Sue(r),operators:vue(r),actions:[]}}function l_(e,t,n){let r=Qt(e,t);if(!r||!Fr(r))return null;let i=ho(r,"utf8"),o=XA(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function lS(e,t){let n=Qt(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Fr(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(ho(n,"utf8")),i=Array.isArray(r)?r:ee(r)&&Array.isArray(r.steps)?r.steps:null;if(!i)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of i.entries()){if(!ee(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:ee(c.before)?c.before:void 0,after:ee(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(r){let i=r instanceof Error?r.message:String(r);return{steps:[],errors:[`trace file is not valid JSON: ${i}`]}}}function uS(e,t){let n=new Set,r=[];for(let i of t){let o=Qt(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function oue(e,t){if(!ee(e))return t.push("map file must contain a JSON object"),null;let n=due(e.variables,t);uue(n,t);let r=yue(e.actions,n,t),i=sue(e.init,t);cue(i,r,t);let o={module:t_(e.module,"module",t),config:t_(e.config,"config",t),scope:X(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:X(e.invariants)??[],traces:X(e.traces)??[],unmappedWriteScope:lue(e.unmappedWriteScope,t)};return Rue(e.scope,t),t.length===0?o:null}function sue(e,t){if(e===void 0)return;if(!ee(e)){t.push("init must be an object when present");return}let n=X(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=aue(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function aue(e,t){if(e===void 0)return;if(!ee(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function cue(e,t,n){if(!e)return;let r=new Set(e.codeRefs),i=new Set;for(let o of Object.values(t))for(let s of o.code)r.has(s)&&i.add(s);i.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...i].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function lue(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function uue(e,t){Ap(e,t,"alias",n=>n.aliases),Ap(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Ap(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Ap(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=aS(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Ap(e,t,n,r){let i=new Map;for(let[o,s]of Object.entries(e))for(let a of r(s)){let c=i.get(a);c?c.push(o):i.set(a,[o])}for(let[o,s]of i)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${o}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function due(e,t){if(!ee(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[r,i]of Object.entries(e)){if(!_p.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!ee(i)){t.push(`variables.${r} must be an object`);continue}let o=d_(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=X(i.aliases)??[],a=mue(i.resource,r,t),c=fue(i.statements,r,t),l=gue(i.ormCalls,r,t),u=hue(i.waive,r,t),d=pue(i.selfAlias,r,t),p=d?[...new Set([r,...s])]:[...new Set(s)];d===!1&&p.length===0&&!a&&!c&&!l&&!u&&t.push(`variables.${r}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${r} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${r}.waive with a reason`),n[r]={code:o,aliases:p,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...u?{waive:u}:{},...d===!1?{selfAlias:!1}:{}}}return n}function pue(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function mue(e,t,n){if(e===void 0)return;if(!ee(e)){n.push(`variables.${t}.resource must be an object when present`);return}let r=typeof e.path=="string"?e.path.trim():"";if(!r){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:r}}function fue(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!ee(i)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof i.pattern=="string"?i.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${o}].pattern must be a non-empty string`);return}try{new RegExp(s)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${o}].pattern is not a valid regular expression: ${c}`);return}r.push({pattern:s})}),r.length>0?r:void 0}function gue(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!ee(i)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof i.table=="string"?i.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(i.methods===void 0){r.push({table:s});return}let a=X(i.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!sS.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...sS].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function hue(e,t,n){if(e===void 0)return;if(!ee(e)){n.push(`variables.${t}.waive must be an object when present`);return}let r=typeof e.reason=="string"?e.reason.trim():"";if(!r){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:r}}function yue(e,t,n){if(!ee(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let r=new Set(Object.keys(t)),i={};for(let[o,s]of Object.entries(e)){if(!_p.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!ee(s)){n.push(`actions.${o} must be an object`);continue}let a=d_(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let p of a){let m=cS(p);"error"in m&&n.push(`actions.${o}.code: ${m.error}`)}let c=X(s.reads)??[],l=X(s.writes)??[],u=X(s.calls)??[];for(let p of[...c,...l])r.has(p)||n.push(`actions.${o} references unknown variable: ${p}`);let d=bue(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:u,...d?{waive:d}:{}}}return i}function bue(e,t,n,r,i,o,s){if(ee(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${o}.waive.reason must be a non-empty string`);let c=X(e.reads)??[],l=X(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),e_(o,"reads",c,i,s),e_(o,"writes",l,i,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${o}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(r)],reason:"legacy allowUnknown",legacy:!0}}function e_(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function Sue(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let r=n[1]??"";for(let i of r.split(",")){let o=i.trim();_p.test(o)&&t.add(o)}}return[...t].sort()}function vue(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var xue=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function u_(e){if(!e||!Fr(e))return[];let t=ho(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(xue.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&_p.test(i)&&n.add(i)}return[...n].sort()}function t_(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function d_(e){return typeof e=="string"?[e]:X(e)}function Rue(e,t){e!==void 0&&(X(e)||t.push("scope must be an array of strings when present"))}function $p(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Cue=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function p_(e,t){if(!Fr(t))return{status:"none"};let r=ho(t,"utf8").match(Cue)?.[1],i=tue(e,t).split(nue).join("/"),o=Zle(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(u=>!!u)),a=n_(t);if(!Fr(a))return{status:"none"};let c=[];for(let u of Xle(a)){if(!u.endsWith(".scip-tla.json"))continue;let d=eue(a,u),p;try{p=JSON.parse(ho(d,"utf8"))}catch{continue}ee(p)&&typeof p.module=="string"&&s.has(p.module)&&c.push(d)}c.sort();let l=r??i;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function Op(e,t,n,r,i={count:e.length,loc:r}){let o=i.count===e.length&&i.loc===r?`${e.length}, ${r} LOC`:`${e.length} of ${i.count}, ${r} of ${i.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let u=s.get(l.relativePath)??[];u.push(l),s.set(l.relativePath,u)}let a=[...s.entries()].map(([l,u])=>({file:l,bucket:u,totalLoc:u.reduce((d,p)=>d+p.loc,0)})).sort((l,u)=>u.totalLoc-l.totalLoc||l.file.localeCompare(u.file)),c=!0;for(let{file:l,bucket:u}of a){c||console.log(""),c=!1,console.log(` ${l}`),u.sort((d,p)=>d.startLine-p.startLine);for(let d of u){let p=d.implicitUsageReason?` [implicit usage: ${d.implicitUsageReason}]`:"";console.log(` ${dt(d.startLine,d.endLine)} (${d.loc} LOC) ${d.shortName}${p}`)}}}var dS=20,m_=Ne("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:ke(t,0)||void 0,minLoc:$(n,"minLoc",1),includeTests:E(n,"includeTests"),skipBarrels:E(n,"skipBarrels"),includeMembers:E(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=hr(e,i),s=o.symbols.filter(F=>F.kind==="dead-code"),a=o.symbols.filter(F=>F.kind==="file-internal"),c=o.symbols.filter(F=>F.kind==="implicit-usage"),l=!E(n,"onlyInternal"),u=!E(n,"onlyDead"),d=!E(n,"onlyDead")&&!E(n,"onlyInternal"),p=l?s:[],m=u?a:[],f=d?c:[],g=p.reduce((F,V)=>F+V.loc,0),h=m.reduce((F,V)=>F+V.loc,0),y=f.reduce((F,V)=>F+V.loc,0),x=E(n,"full"),R=x?p:p.slice(0,dS),b=x?m:m.slice(0,dS),v=x?f:f.slice(0,dS),w=R.reduce((F,V)=>F+V.loc,0),I=b.reduce((F,V)=>F+V.loc,0),C=v.reduce((F,V)=>F+V.loc,0),k={total:p.length+m.length+f.length,deadCode:p.length,fileInternal:m.length,implicitUsage:f.length,loc:g+h+y};if(E(n,"json")){H("dead",t,n,{...o,shown:{deadCode:p,fileInternal:m,implicitUsage:f},shownCounts:k,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:r.analysisBudget});return}if(p.length===0&&m.length===0&&f.length===0){O.empty("No matching dead-code symbols found.");return}p.length>0&&(Op(R,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
1328
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,w,{count:p.length,loc:g}),!x&&p.length>R.length&&console.log(`
1329
- Showing top ${R.length} by LOC. Re-run with --full for the remaining ${p.length-R.length}.`)),m.length>0&&(p.length>0&&console.log(""),Op(b,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
1330
- single-use helper, an abstraction-in-progress, or a callback registered
1331
- through a framework path that static analysis cannot trace (signal
1332
- handlers, event listeners, dependency injection). NOT necessarily dead \u2014
1333
- review case by case.`,I,{count:m.length,loc:h}),!x&&m.length>b.length&&console.log(`
1334
- Showing top ${b.length} by LOC. Re-run with --full for the remaining ${m.length-b.length}.`)),f.length>0&&((p.length>0||m.length>0)&&console.log(""),Op(v,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
1335
- consumer that the static reference graph cannot trace. Investigation
1336
- signals only \u2014 not deletion candidates and not counted as dead code.`,C,{count:f.length,loc:y}),!x&&f.length>v.length&&console.log(`
1337
- Showing top ${v.length} by LOC. Re-run with --full for the remaining ${f.length-v.length}.`));let T=[];l&&T.push(`${p.length} dead code (${g} LOC)`),u&&T.push(`${m.length} file-internal (${h} LOC)`),d&&T.push(`${f.length} implicit usage (${y} LOC)`),console.log(`
1338
- \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: ${p.length+m.length+f.length} symbols \u2014 ${T.join(" + ")}`)}),f_=Yt("unused-imports",{query:({db:e,args:t,budget:n})=>Cg(e,U(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
1339
- ${e.length} unused import(s)`)}),g_=Tp("isolated",{query:({db:e,opts:t,budget:n})=>ji(e,{scope:A(t,"scope"),minLoc:$(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${dt(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
1340
- ${e.length} isolated symbol(s)`)}),h_=Ne("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Vi(e,{scope:A(n,"scope"),minLoc:$(n,"minLoc",10),minCallees:$(n,"minCallees",6),limit:Y(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(E(n,"json")){H("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return O.empty("No extraction candidates found.");Jt("extraction candidates");for(let o of i){console.log(`
1341
- ${ye(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
1342
- ${i.length} extraction candidate(s) found.`)}),y_=Ne("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Yg(e,{target:ke(t,0)||void 0,scope:A(n,"scope"),minConsumers:$(n,"minConsumers",1),limit:Y(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(E(n,"json")){H("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return O.empty("No locality candidates found.");Jt("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?ye(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
1343
- ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
1344
- ${i.length} locality candidate(s) found.`)}),b_=Yt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Zi(e,{scope:A(t,"scope"),maxLoc:$(t,"maxLoc",15),limit:Y(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
1345
- Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
1346
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
1347
- ${e.length} wrapper candidate(s).`)}),S_=Yt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Qi(e,{scope:A(t,"scope"),maxLoc:$(t,"maxLoc",15),limit:Y(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
1348
- Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
1349
- Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
1350
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
1351
- Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
1352
- ${e.length} passthrough candidate(s).`)}),v_=Yt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Xi(e,{scope:A(t,"scope"),minLoc:$(t,"minLoc",3),limit:Y(t,"limit",30),includeLowConfidence:E(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
1353
- ${e.reason}
1354
- Kind: ${e.stalenessKind}; tier: ${e.actionTier}
1355
- Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
1356
- ${e.length} stale abstraction(s).`)}),x_=Dp("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>ac(e,{scope:A(t,"scope"),minLoc:$(t,"minLoc",10),limit:Y(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]}),R_=vn("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(E(n,"plan")){let o=ke(t,0),s=ke(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Oa(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=ke(t,0);return i?{mode:"target",rows:ts(e,i,{minSimilarity:$(n,"minSimilarity",.4),limit:Y(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Bi(e,{minSimilarity:$(n,"minSimilarity",.4),limit:Y(n,"limit",20),scope:A(n,"scope"),minCallees:$(n,"minCallees",4),crossFileOnly:E(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";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==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
1357
- ${Math.round(t.similarity*100)}% ${n}
1358
- `),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
1359
- `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
1360
- Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
1361
- Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
1362
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){O.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=[`
1363
- ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
1364
- `)});return}O.list(e.rows,t=>`
1365
- ${Math.round(t.similarity*100)}% similar:
1366
- A: ${t.shortNameA} (${t.fileA})
1367
- B: ${t.shortNameB} (${t.fileB})
1368
- Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
1369
- Recommendation: ${t.recommendation}
1370
- `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
1371
- `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
1372
- ${e.rows.length} similar pair(s) found.`)}}),C_=fi({commandName:"similar-files",query:({db:e,args:t,opts:n})=>qg(e,{minSimilarity:$(n,"minSimilarity",.5),limit:Y(n,"limit",20),scope:A(n,"scope"),minDeps:De(n,"minDeps"),filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{O.list(e,t=>{let n=[`
1373
- ${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(`
1374
- `)}),console.log(`
1375
- ${e.length} similar pair(s) found.`)}}),w_=fi({commandName:"similar-chains",query:({db:e,opts:t})=>Ug(e,{minSimilarity:$(t,"minSimilarity",.5),limit:Y(t,"limit",15),scope:A(t,"scope"),minChainLength:$(t,"minLength",3),maxChainLength:$(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(`
1376
- \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(`
1377
- ${e.length} similar chain pair(s) found.`)}}),k_=vn("drift",{query:({db:e,args:t,opts:n,budget:r})=>Yi(e,{scope:ke(t,0),minDeviation:$(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:E(n,"patterns"),limit:Y(n,"limit",50)}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),O.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
1378
- `)},t=>t.file),console.log(`
1379
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),I_=vn("convergence",{query:({db:e,args:t,budget:n})=>Qh(e,U(t,0),U(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
1380
- ${Math.round(e.similarity*100)}% callee overlap
1381
- `),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)
1382
- `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
1383
- Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
1384
- Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
1385
- Strategy: ${e.consolidationStrategy}`)}}}),P_=Yt("similar-signatures",{query:({db:e,opts:t,budget:n})=>iy(e,{scope:A(t,"scope"),minLoc:$(t,"minLoc",3),maxShapeFrequency:$(t,"maxShapeFrequency",12),limit:Y(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
1386
- Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${ye(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
1387
- `);return`${n}
1388
- ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
1389
- ${e.length} group(s) found.`)}),E_=Yt("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>Ki(e,{scope:A(t,"scope"),maxLoc:$(t,"maxLoc",15),minLoc:$(t,"minLoc",3),limit:Y(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
1390
- Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${ye(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
1391
- `);return`${t}
1392
- ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
1393
- ${e.length} group(s) found.`)}),D_=Yt("twin-drift",{query:({db:e,opts:t,budget:n})=>xh(e,{scope:A(t,"scope"),minSimilarity:$(t,"minSimilarity",.3),includeHomonyms:E(t,"includeHomonyms"),limit:Y(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
1394
- ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${ye(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
1395
- `),r=e.firstDivergentTokens?`
1396
- first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
1397
- ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
1398
- ${e.length} group(s) found.`)}),T_=Yt("not-implemented",{query:({db:e,opts:t,budget:n})=>Mh(e,{scope:A(t,"scope"),limit:Y(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
1399
- ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
1400
- ${e.length} reachable placeholder stub(s).`)}),L_=Yt("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Oh(e,{scope:A(t,"scope"),limit:Y(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
1401
- ${e.length} decorative checker candidate(s).`)}),F_=Ne("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=Hh(e,{scope:A(n,"scope"),limit:Y(n,"limit",30),scanLimit:r.scanLimit,rotDays:De(n,"rotDays")});if(E(n,"json")){H("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Jt("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){O.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
1402
- ASSERTION-FREE (${i.assertionFree.length})`),O.list(i.assertionFree,s=>` ${ye(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
1403
- SKIPPED (${i.skipped.length})`),O.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
1404
- MOCK-ECHO (${i.mockEcho.length})`),O.list(i.mockEcho,s=>` ${ye(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
1405
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),N_=fi({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=U(t,0),i=U(t,1),o=A(n,"out")??Ah(r,i),s=Qt(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=_h(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=Eue(e.config.projectRoot,s);if(!E(n,"force")&&wue(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return kue(Pue(s),{recursive:!0}),Iue(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
1406
- Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${ye(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${ye(e.b.file,e.b.startLine,e.b.startLine)})`);let t=e.signatureCompatible===null?"unknown":e.signatureCompatible?"compatible":"MISMATCH";console.log(` Signature compatibility: ${t}`),console.log(`
1407
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),A_=Ne("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Vu(e,{scope:A(n,"scope"),minLoc:$(n,"minLoc",1),maxDepth:$(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Me(),s=E(n,"patch"),a=E(n,"json"),c=E(n,"verify")||s;if(s&&!E(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){H("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return O.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Ky(i),u=c?Vy(o,i):void 0;if(a){H("cleanup-plan",t,n,{result:i,verification:u},{analysisBudget:r.analysisBudget});return}if(s){let d=Jy(u,l);if(d.length>0){for(let m of d)console.error(`error: ${m}`);process.exitCode=1;return}let p=AT(o,l);if(p.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(p);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
1408
- `);for(let d of i.batches){let p=d.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${d.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${d.depth}: dead once batch ${d.depth-1} lands (cascade, ${d.loc} LOC) \u2500\u2500`;console.log(p);for(let m of d.entries)console.log(` ${m.file}:${m.startLine+1}-${m.endLine+1} ${m.shortName} (${m.loc} LOC)`);d.filesEmptied.length>0&&console.log(` -> empties: ${d.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let d of i.blocked)console.log(` ${d.shortName} (${d.file}) blocked by ${d.blockingFiles.join(", ")}`)}if(u){if(console.log(`
1409
- Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let m of u.checkers)console.log(` Checker: ${m}`);if(u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`),u.dirtyWorkingTree.length>0){let m=u.dirtyWorkingTree.slice(0,5),f=u.dirtyWorkingTree.length-m.length;console.log(` WARNING: verification ran at HEAD; ${u.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${m.join(", ")}${f>0?`, ... ${f} more`:""}`)}let d=Due(u.checkers),p=Tue(u.checkers);for(let m of u.batches)if(m.status==="verified")console.log(` Batch ${m.depth}: VERIFIED (${d})${p}`);else{console.log(` Batch ${m.depth}: FAILED${m.reason?` (${m.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let f of m.errors??[])console.log(` ${f}`)}}}),__=Ne("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!E(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=E(t,"all"),i=De(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Vu(e,{scope:A(t,"scope"),minLoc:$(t,"minLoc",1),maxDepth:$(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){O.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Ky(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=Me(),c=Vy(a,o),l=Jy(c,s,{allowDirty:E(t,"forceDirty")});if(l.length>0){for(let p of l)console.error(`error: ${p}`);process.exitCode=1;return}zy(a,s);let u=s.reduce((p,m)=>p+m.entries.length,0),d=s.reduce((p,m)=>p+m.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)});function Due(e){return e.join(", ")}function Tue(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var M_=Ne("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=E(n,"full"),o=Wh(e,{windowCommits:$(n,"window",100),minSimilarity:De(n,"minSimilarity"),limit:Y(n,"limit",30),scope:A(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(E(n,"json")){H("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return O.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return O.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Jt("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
1410
- `);let s=o.rootCauseGroups?.filter(a=>a.count>1)??[];if(s.length>0){console.log(`Root-cause groups (${s.length}):`);for(let a of s)console.log(` ${a.count} pair(s) ${a.kind.toUpperCase()} ${a.domain} ${Math.round(a.maxSimilarity*100)}% max`),a.establishedFile&&a.establishedSymbol&&console.log(` established: ${a.establishedFile} ${a.establishedSymbol}`),console.log(` files: ${a.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${a.recommendation}`);console.log("")}for(let a of o.findings){let c=a.sharedEvidence.slice(0,16).join(", ");a.kind==="echo"?(console.log(` ${Math.round(a.similarity*100)}% ECHO ${a.domain} ${a.echoFile} ${a.echoSymbol} (added ${a.echoAgeCommits} commits ago)`),console.log(` duplicates established ${a.establishedFile} ${a.establishedSymbol}`)):(console.log(` ${Math.round(a.similarity*100)}% TWIN ${a.domain} ${a.echoFile} ${a.echoSymbol}`),console.log(` and ${a.establishedFile} ${a.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${a.basis}`),c.length>0&&console.log(` shared: ${c}`)}console.log(`
1411
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),$_=We(({db:e,args:t,opts:n})=>{let r=E(n,"full"),i=bh(e,{doc:t[0]===void 0?void 0:U(t,0),limit:Y(n,"limit",20),minCoupling:$(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(E(n,"json")){H("doc-drift",t,n,i);return}if(!i.available)return O.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return O.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Jt("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
1412
- `);for(let o of i.findings){let s=o.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=o.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${o.staleness} ${o.doc}${s}${a}`);for(let c of o.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of o.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let u=c.docIntentReasons[0];u&&console.log(` intent: ${u}`);let d=c.citationContexts?.[0];d&&console.log(` cited claim: ${jd(d)}`)}}console.log(`
1413
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),O_=Yt("unused-params",{query:({db:e,opts:t,budget:n})=>Za(e,{scope:A(t,"scope"),limit:Y(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName}
1414
- trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params -- type-safe to remove at the signature; check call sites for side-effectful arguments)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
1415
- ${e.length} function(s) with trailing unused parameters.`)});var j_=vn("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Hi(e,{minSimilarity:$(n,"minSimilarity",.62),minTokens:$(n,"minTokens",8),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{O.list(e,t=>{let n=[`
1416
- ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
1417
- `)}),console.log(`
1418
- ${e.length} duplicated React component pair(s) found.`)}}),B_=vn("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Wi(e,{minSimilarity:$(n,"minSimilarity",.45),minSharedBehaviors:$(n,"minSharedBehaviors",6),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{O.list(e,t=>{let n=[`
1419
- ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
1420
- `)}),console.log(`
1421
- ${e.length} React hook candidate pair(s) found.`)}}),H_=vn("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>ja(e,{minComponentLines:$(n,"minComponentLines",300),minFileLines:$(n,"minFileLines",800),minJsxTokens:$(n,"minJsxTokens",80),minBehaviorTokens:$(n,"minBehaviorTokens",40),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{O.list(e,t=>[`
1422
- ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
1423
- `)),console.log(`
1424
- ${e.length} large React component(s) found.`)}}),W_=vn("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>qi(e,{minSimilarity:$(n,"minSimilarity",.62),minTokens:$(n,"minTokens",8),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{O.list(e,t=>{let n=[`
1425
- ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
1426
- `)}),console.log(`
1427
- ${e.length} duplicated Vue component pair(s) found.`)}}),q_=vn("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Ui(e,{minSimilarity:$(n,"minSimilarity",.45),minSharedBehaviors:$(n,"minSharedBehaviors",6),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{O.list(e,t=>{let n=[`
1428
- ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
1429
- `)}),console.log(`
1430
- ${e.length} Vue composable candidate pair(s) found.`)}}),U_=vn("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ba(e,{minTotalLines:E(n,"reviewThresholds")&&Xb(n,"minTotalLines")==="default"?300:$(n,"minTotalLines",800),minTemplateLines:$(n,"minTemplateLines",300),minScriptLines:$(n,"minScriptLines",300),minStyleLines:$(n,"minStyleLines",500),limit:Y(n,"limit",20),scope:A(n,"scope"),scanLimit:r.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{O.list(e,t=>{let n=[`
1431
- ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
1432
- `)}),console.log(`
1433
- ${e.length} large Vue view pressure file(s) found.`)}});function Ct(e){return{docs:N("Cleanup"),...e}}function Xe({heuristicLabel:e,...t}){return Ct({...t,heuristic:{label:e}})}var jp=[Ct({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:j([S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Maximum findings",L,30),S("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:N("Cleanup",["scip-query unused-params -s src/services"]),handler:O_}),Ct({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Only include symbols >= N lines",L,1),S("--max-depth <n>","Maximum cascade depth",L,5),S("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),S("--patch","With --verify, print the compiler-verified deletion patch to stdout"),S("--json","Output as JSON for programmatic consumption"),S("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:N("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:A_}),Ct({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Only include symbols >= N lines",L,1),S("--max-depth <n>","Maximum cascade depth",L,5),S("--verified","Required: verify the selected cleanup batch before applying it"),S("--batch <n>","Apply one batch depth",L),S("--all","Apply every compiler-verified batch in the plan"),S("--force-dirty","Allow applying when plan files already have working-tree edits"),S("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:N("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:__}),Ct({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:j([S("--window <n>",'How many commits back counts as "recent"',L,100),S("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",yn),S("-n, --limit <n>","Maximum findings",L,30),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:N("Cleanup",["scip-query recent-duplicates --window 50"]),handler:M_}),Ct({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:j([S("-n, --limit <n>","Maximum docs to report",L,20),S("--min-coupling <n>","Minimum historical co-changes to track a subject",L,3),S("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:N("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:$_}),Ct({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:j([S("--min-loc <n>","Only show symbols >= N lines",L,1),S("--include-tests","Include definitions from test files (test references always count)"),S("--skip-barrels","Ignore refs from barrel re-export files"),S("--include-members","Include class members"),S("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),S("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:N("Cleanup",["scip-query dead --min-loc 10"]),handler:m_}),Ct({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:j([S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:f_}),Ct({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Minimum lines of code",L,3),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:g_}),Xe({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:j([S("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",yn,.4),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--min-callees <n>","Minimum callees to consider",L,4),S("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),S("--plan","Render a consolidation preview for two symbols"),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:R_}),Xe({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:j([S("--min-similarity <n>","Minimum Jaccard similarity (0-1)",yn,.5),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--min-deps <n>","Minimum dependencies to consider",L),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:C_}),Xe({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:j([S("--min-similarity <n>","Minimum JSX structure similarity (0-1)",yn,.62),S("--min-tokens <n>","Minimum structural tokens to consider",L,8),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:j_}),Xe({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:j([S("--min-similarity <n>","Minimum behavior similarity (0-1)",yn,.45),S("--min-shared-behaviors <n>","Minimum shared behavior tokens",L,6),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:B_}),Xe({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:j([S("--min-component-lines <n>","Minimum component lines",L,300),S("--min-file-lines <n>","Minimum file lines",L,800),S("--min-jsx-tokens <n>","Minimum JSX structure tokens",L,80),S("--min-behavior-tokens <n>","Minimum behavior tokens",L,40),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:H_}),Xe({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:j([S("--min-similarity <n>","Minimum template similarity (0-1)",yn,.62),S("--min-tokens <n>","Minimum structural tokens to consider",L,8),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:W_}),Xe({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:j([S("--min-similarity <n>","Minimum behavior similarity (0-1)",yn,.45),S("--min-shared-behaviors <n>","Minimum shared behavior tokens",L,6),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:q_}),Xe({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:j([S("--min-total-lines <n>","Minimum total component lines",L,800),S("--min-template-lines <n>","Minimum template lines",L,300),S("--min-script-lines <n>","Minimum script lines",L,300),S("--min-style-lines <n>","Minimum style lines",L,500),S("--review-thresholds","Use lower review thresholds without changing health scoring"),S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:U_}),Xe({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:j([S("--min-similarity <n>","Minimum chain similarity (0-1)",yn,.5),S("-n, --limit <n>","Number of results",L,15),S("-s, --scope <path>","Limit to files matching path"),S("--min-length <n>","Minimum chain length",L,3),S("--max-length <n>","Maximum chain length",L,8),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:w_}),Xe({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Minimum function LOC",L,10),S("--min-callees <n>","Minimum callees to analyze",L,6),S("-n, --limit <n>","Number of results",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:h_}),Xe({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:j([S("-s, --scope <path>","Limit scan mode to files matching path"),S("--min-consumers <n>","Minimum consumers in scan mode",L,1),S("-n, --limit <n>","Number of results",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:N("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:y_}),Xe({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports and layer violations by default; pass --patterns for pattern deviations too",options:j([S("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Pr,5),S("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),S("-n, --limit <n>","Number of results",L,50),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:k_}),Xe({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--max-loc <n>","Maximum LOC for candidates",L,15),S("-n, --limit <n>","Number of results",L,30),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:b_}),Xe({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--max-loc <n>","Maximum LOC for candidates",L,15),S("-n, --limit <n>","Number of results",L,30),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:S_}),Xe({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Minimum LOC",L,3),S("-n, --limit <n>","Number of results",L,30),S("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:v_}),Xe({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Minimum LOC",L,10),S("-n, --limit <n>","Number of results",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:x_}),Ct({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:j([S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:I_}),KA({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Number of results",L,30),S("--full","Run unbounded analysis on large indexes")],docs:N("Cleanup"),query:({db:e,opts:t})=>Zh(e,{scope:A(t,"scope"),limit:Y(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
1434
- barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
1435
- Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
1436
- Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
1437
- ${e.length} redundant re-export(s).`)}),Ct({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--max-loc <n>","Maximum LOC per function body",L,15),S("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",L,3),S("-n, --limit <n>","Number of groups",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:E_}),Ct({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",yn,.3),S("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),S("-n, --limit <n>","Number of groups",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:D_}),Xe({id:"not-implemented",command:"not-implemented",description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:j([S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Number of results",L,30),S("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:N("Cleanup",["scip-query not-implemented -s src/services"]),handler:T_}),Xe({id:"decorative-checkers",command:"decorative-checkers",description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:j([S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Number of results",L,30),S("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:N("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:L_}),Ct({id:"test-quality",command:"test-quality",description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:j([S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Maximum findings per sub-check",L,30),S("--rot-days <n>","Skips older than this many days are reported as rot",L,60),S("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:N("Cleanup",["scip-query test-quality -s tests/queries"]),handler:F_}),Ct({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-integrity-audit drill 5) \u2014 a ready-to-fill vitest file, not an auto-executor",options:j([S("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),S("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:N("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:N_}),Ct({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--min-loc <n>","Minimum LOC per function",L,3),S("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",L,12),S("-n, --limit <n>","Number of groups",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:P_})];var Lue=We(({db:e,args:t,opts:n})=>{let r=Ut(e);if(E(n,"json")){H("stats",t,n,r);return}console.log(`Documents: ${r.documents}`),console.log(`Symbols: ${r.symbols}`),console.log(`Definitions: ${r.definitions}`),console.log(`References: ${r.references}`),console.log(`Index size: ${Xn(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),V_=[{id:"stats",command:"stats",description:"Show index statistics",options:[Wy()],renderShape:"custom",docs:N("Core"),handler:Lue}];function ft(e,t){let n=Ht(e,t),r=Nue(n);for(let i of r)console.log(i)}function gt(e,t,n="No results found for resolved symbol."){return Ht(e,t).match?n:Fue(t,nf(e,t,5))}function Xt(e,t,n,r){return{...js(e,t),[r]:n}}function js(e,t){let n=Ht(e,t);return n.match?{matched:!0,resolved:{symbol:n.match.symbol,shortName:P(n.match.symbol),relativePath:n.match.relativePath},otherMatches:n.candidates.map(r=>({shortName:r.shortName,relativePath:r.relativePath,startLine:r.startLine})),totalMatches:n.total}:{matched:!1,suggestions:nf(e,t,5)}}function Fue(e,t){let n=`No definition matched '${e}'.`;return t.length>0?`${n} Suggestions: ${t.join(", ")}`:n}function Nue(e){if(!e.match||e.total<=1)return[];let t=e.match,n=Math.max(0,e.total-1),r=[`Resolved: ${P(t.symbol)} (${t.relativePath}) -- ${n} other definition(s) share this name; qualify as <dir/leaf> to target another.`],i=e.candidates.slice(0,3);return i.length>0&&r.push(`Alternates: ${i.map(o=>`${o.shortName} (${o.relativePath}:${Rt(o.startLine)})`).join("; ")}`),r.push(""),r}var Aue=Dp("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ng(e,{limit:Y(t,"limit",20),scope:A(t,"scope"),minFanIn:$(t,"minFanIn",2),minFanOut:$(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),_ue=We(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=Y(n,"limit",30);if(r){let c=Pg(e,r);if(E(n,"json")){H("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return O.empty(`No fan-in for ${r}.`);O.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Dg(e,{limit:i,scope:A(n,"scope")});if(E(n,"json")){H("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));O.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Mue=We(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=Y(n,"limit",30);if(r){let s=Eg(e,r);if(E(n,"json")){H("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return O.empty(`No fan-out for ${r}.`);O.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Tg(e,{limit:i,scope:A(n,"scope")});if(E(n,"json")){H("fan-out",t,n,{mode:"top",rows:o});return}O.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),$ue=We(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=ke(t,1),o=Y(n,"limit",20);if(r&&i){let a=Lg(e,r,i);if(E(n,"json")){H("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=Fg(e,{limit:o,scope:A(n,"scope")});if(E(n,"json")){H("coupling",t,n,{mode:"top",rows:s});return}O.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),Oue=fi({commandName:"cycles",query:({db:e,opts:t})=>ju(e,{scope:A(t,"scope"),maxDepth:$(t,"maxDepth",10)}),emptyMessage:e=>e.cycles.length===0?e.truncated?`No circular dependencies found. Search truncated at depth ${e.maxDepth}; deeper cycles may exist.`:"No circular dependencies found.":void 0,toJson:e=>e,render:e=>{let t=e.cycles.filter(r=>r.kind==="real"),n=e.cycles.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
1438
- 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(`
1439
- ${t.length} real cycle(s) found.`),e.truncated&&console.log(`(search truncated at depth ${e.maxDepth} \u2014 deeper cycles may exist)`),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.)`)}}),jue=fi({commandName:"deep-chains",query:({db:e,opts:t})=>Mg(e,{limit:Y(t,"limit",10),scope:A(t,"scope"),minDepth:$(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(`
1440
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let r=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${r}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),G_=[Fp({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[S("-n, --limit <n>","Number of results",L,30),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")],docs:N("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>vg(e,{limit:Y(t,"limit",30),scope:A(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",options:j([S("-n, --limit <n>","Number of results for top mode",L,30),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:N("Graph"),handler:_ue},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:j([S("-n, --limit <n>","Number of results for top mode",L,30),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:N("Graph"),handler:Mue},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:j([S("-n, --limit <n>","Number of results for top mode",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:N("Graph"),handler:$ue},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:j([S("-s, --scope <path>","Limit to files matching path"),S("--max-depth <n>","Bound DFS search depth",L,10)]),renderShape:"custom",docs:N("Graph"),handler:Oue},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:j([S("-n, --limit <n>","Number of results",L,20),S("-s, --scope <path>","Limit to files matching path"),S("--min-fan-in <n>","Minimum fan-in",L,2),S("--min-fan-out <n>","Minimum fan-out",L,2),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:N("Graph"),handler:Aue},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:j([S("-n, --limit <n>","Number of chains to show",L,10),S("-s, --scope <path>","Limit to files matching path"),S("--min-depth <n>","Minimum chain depth",L,3),S("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:N("Graph"),handler:jue},Np({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[S("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:N("Graph"),query:({db:e,args:t,budget:n})=>Qr(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:gt(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(ft(t,String(n[0])),console.log(`Symbol: ${e.shortName}
1441
- `))},toJson:(e,{db:t,args:n})=>Xt(t,String(n[0]),e,"callGraph"),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 Bue=Ne("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=U(t,0),o=oc(e,i,{semantic:r.semantic});if(E(n,"json")){H("complexity",t,n,Xt(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return O.empty(gt(e,i,"Symbol not found."));ft(e,i),console.log(`${ye(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
1442
- `),console.log(` LOC: ${o.loc}`),console.log(` Branches: ${o.branches}`),console.log(` Cyclomatic estimate: ${o.cyclomaticEstimate}`),console.log(` Callees: ${o.calleeCount}`),console.log(` Fan-in: ${o.fanIn}`),console.log(` Fan-out: ${o.fanOut}`)}),Hue=We(({db:e,args:t,opts:n})=>{let r=ry(e,{samples:$(n,"samples",50),scope:A(n,"scope")});if(E(n,"json")){H("self-audit",t,n,r);return}if(!r.available)return O.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
1443
- `),console.log(`Agreement with ${i} (file-level):`);for(let o of r.scores){let s=o.precision===null?`unverified ${o.unverified} (oracle partial \u2014 no precision claim)`:`precision ${o.precision}`;console.log(` ${o.question.padEnd(11)} ${s} recall ${o.recall} (${o.comparedSymbols} compared, ${o.skippedOraclePartial} skipped: oracle-partial)`)}if(r.topDisagreements.length>0){console.log(`
1444
- Top disagreements (debugging targets):`);for(let o of r.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),z_=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:j([S("--samples <n>","Number of symbols to sample",L,50),S("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:N("Health",["scip-query self-audit --samples 100"]),handler:Hue},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:j([S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:N("Health"),handler:Bue}];var Wue=We(({db:e,args:t,opts:n})=>{let r=U(t,0),i=Ha(e,r,{maxDepth:$(n,"maxDepth",5),scope:A(n,"scope")});if(E(n,"json")){H("affected",t,n,Xt(e,r,i,"affected"));return}if(i.length===0)return O.empty(gt(e,r,"No affected symbols found."));ft(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
1445
- \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
1446
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),que=Ne("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:U(t,0),o=E(n,"full"),s=Gi(e,i,{minTogether:$(n,"minTogether",4),limit:Y(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(E(n,"json")){H("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return O.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return O.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Jt("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
1447
- `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
1448
- `),i&&s.findings.some(a=>a.structurallyLinked||a.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
1449
- `);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,u=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${u}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${Uue(a.lastTogetherAt)}`),console.log(` subjects: ${Vue(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
1450
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Uue(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Vue(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var Gue=Ne("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Wa(e,U(t,0),{semantic:r.semantic});if(E(n,"json")){H("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return O.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
1451
- `),O.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${dt(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),zue=Ne("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=Xa(e,{base:A(n,"base"),minContainment:$(n,"minContainment",.7),maxHelpers:De(n,"maxHelpers"),limit:Y(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(E(n,"json")){H("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return O.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return O.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
1452
- No incomplete migrations detected.`);return}Jt("incomplete migration candidates");for(let o of i.findings){console.log(`
1453
- ${o.helperShortName} (${o.helperFile})`),console.log(` helper shape: ${o.helperShape} (${o.specificHelperCalleeCount}/${o.helperCalleeCount} specific callees)`),console.log(` wired into: ${o.migratedFiles.join(", ")}`);for(let s of o.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
1454
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function Kue(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!pd.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${pd.join(", ")}`),process.exit(1)),t}var Jue=We(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Gd(Pc()))return;let r=E(t,"full"),i=qd(e,"diff-gate",r,{quiet:n||E(t,"json")}),o={base:A(t,"base"),minTogether:$(t,"minTogether",6),maxEchoChecks:De(t,"maxEchoChecks"),maxHelpers:De(t,"maxHelpers"),includeBaseline:E(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:Kue(t.skip)},s=eo(e,o),a=nc(s.findings),c=tc(s),l=Zd(e,s,{replayGate:m=>eo(e,{...o,base:m})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&E(t,"json")){H("diff-gate",[],t,{exitCode:a.length>0||c?1:0,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:m,observed:f,now:g}=l;if(c){console.error("diff gate FAILED CLOSED: could not compute the git diff (diff too large, bad --base, or git error) - zero checks ran. Investigate with: scip-query diff-gate"),process.exitCode=2;return}if(a.length===0)return;let h=YP(m,f,g),y=QP(m,s.checksRun),x=ST(i.analysisBudget),R=[...h?[h]:[],Ec(s),...y,...x?[x]:[]];console.error(R.join(`
1455
- `)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(s.changedFiles.length===0)return O.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let u=s.attributionNotes.filter(m=>m.method==="unattributed");if(u.length>0)for(let m of[...new Set(u.map(f=>f.file))]){let f=u.filter(g=>g.file===m).length;console.log(`note: ${f} changed line-range(s) in ${m} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
1456
- `);for(let m of s.skipped)console.log(` skipped ${m.check}: ${m.reason}`);if(s.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}Jt("diff gate candidates");let d=s.rootCauseGroups?.filter(m=>m.count>1)??[];if(d.length>0){console.log(`Root-cause groups (${d.length}):`);for(let m of d){console.log(` [${m.check}] ${m.count} finding(s), ${m.severity}${m.actionTier?`, tier: ${m.actionTier}`:""}`),(m.sourceAnalyzer||m.rootCauseKey)&&console.log(` source: ${m.sourceAnalyzer??m.check}${m.rootCauseKey?` root cause: ${m.rootCauseKey}`:""}`);let f=[...new Set([...m.files,...m.relatedFiles])].slice(0,6);f.length>0&&console.log(` files: ${f.join(", ")}`),console.log(` -> ${m.remediation}`)}console.log("")}for(let m of s.findings){if(console.log(` [${m.check}]${m.advisory?" (advisory)":""} ${m.message}`),m.partnerClass){console.log(` partner class: ${m.partnerClass}`);for(let f of m.partnerClassReasons??[])console.log(` reason: ${f}`)}m.citationKind&&console.log(` citation kind: ${m.citationKind}${m.actionTier?` (tier: ${m.actionTier})`:""}`);for(let f of m.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${jd(f)}`);m.declaredCouplingSuggestion&&console.log(` declare coupling: ${m.declaredCouplingSuggestion.name} (${m.declaredCouplingSuggestion.reason})`),console.log(` -> ${m.remediation}`)}if(a.length===0){console.log(`
1457
- PASS (advisory only): ${s.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let p=s.findings.length-a.length;console.log(`
1458
- FAIL: ${a.length} finding(s)${p>0?` (+${p} advisory)`:""}, ${s.rootCauseGroups?.length??s.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),K_=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:j([S("--max-depth <n>","Maximum traversal depth",L,5),S("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:N("Impact"),handler:Wue},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:j([S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:N("Impact"),handler:Gue},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, unedited twin partners (advisory), uncited doc updates, unused params, new dead symbols; exit 1 on blocking findings",options:[S("--base <ref>","Git ref to diff against (default: HEAD)"),S("--min-together <n>","Minimum historical co-changes for the partner check",L,6),S("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",L),S("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",L),S("--baseline","Also run the full health-baseline ratchet"),S("--full","Run unbounded semantic and git-history analysis on large indexes"),S("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, doc-reference, unused-params, new-dead, baseline",so,[]),S("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),S("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:N("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:Jue},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:j([S("--base <ref>","Git ref to diff against (default: HEAD)"),S("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",yn,.7),S("--max-helpers <n>","Maximum new helpers to score (default: all)",L),S("-n, --limit <n>","Maximum findings to report",L,20),S("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:N("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:zue},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:j([S("--min-together <n>","Minimum commits where both files changed",L,4),S("-n, --limit <n>","Maximum pairs to report",L,30),S("--all","Include pairs that already have a dependency edge"),S("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:N("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:que}];function Yue(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${ye(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
1459
- `).map((s,a)=>` ${Rt(i.startLine+a)} ${s}`).join(`
1460
- `))}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 ${Rt(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var Que=We(({db:e,args:t,opts:n})=>{let r=U(t,0),i=E(n,"signatures"),o=kg(e,r);if(E(n,"json")){H("outline",t,n,o);return}if(o.length===0)return O.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=i&&l.signature?` - ${Xue(l.signature)}`:"";console.log(`${u}${dt(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function Xue(e){return e.length>120?`${e.slice(0,117)}...`:e}var Zue=Yt("imports",{query:({db:e,args:t,budget:n})=>xg(e,U(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)."}),ede=Tp("refs",{query:({db:e,args:t,budget:n})=>gg(e,U(t,0),{semantic:n.semantic}),format:e=>` line ${Rt(e.line)}`,before:(e,{db:t,args:n})=>ft(t,U(n,0)),emptyMessage:({db:e,args:t})=>gt(e,U(t,0),"No references found."),toJson:(e,{db:t,args:n})=>Xt(t,U(n,0),e,"references")}),tde=We(({db:e,args:t,opts:n})=>{let r=U(t,0),i=Xh(e,r,{context:$(n,"context",0)});if(E(n,"json")){H("code",t,n,Xt(e,r,i,"code"));return}if(!i)return O.empty(gt(e,r,"Symbol found, but source was unreadable."));ft(e,r),console.log(`${ye(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
1461
- `);let o=i.source.split(`
1462
- `);for(let s=0;s<o.length;s++)console.log(` ${String(Rt(i.startLine+s)).padStart(4)} ${o[s]}`)}),nde=Ne("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=U(t,0),o=sc(e,i,{semantic:r.semantic});if(E(n,"json")){H("dataflow",t,n,Xt(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return O.empty(gt(e,i,"No dataflow found."));if(ft(e,i),console.log(`${o.shortName} (${o.relativePath})
1463
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${Rt(s.line)}`)}if(o.usageSites.length>0){console.log(`
1464
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${Rt(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
1465
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of o.producers)console.log(` ${s.file} ${s.shortName}`)}if(o.consumers.length>0){console.log(`
1466
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),rde=Ne("slice",({db:e,args:t,opts:n,budget:r})=>{let i=U(t,0),o=E(n,"forward")?"forward":"backward",s=ds(e,i,{direction:o,maxDepth:$(n,"depth",3),semantic:r.semantic});if(E(n,"json")){H("slice",t,n,Xt(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return O.empty(gt(e,i,"No slice found."));if(ft(e,i),console.log(`${s.direction} slice of ${s.shortName}
1467
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}O.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
1468
- ${a.relationship}`),console.log(`
1469
- ${s.connectedSymbols.length} connected symbol(s).`)}),J_=[er({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:N("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>mg(e,U(t,0)),format:e=>e.relativePath}),er({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:N("Navigation"),query:({db:e,args:t})=>fg(e,U(t,0)),format:e=>` ${dt(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[S("--full","Run unbounded semantic analysis on large indexes"),S("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:N("Navigation",["scip-query refs login"]),handler:ede},Np({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[S("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:N("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>La(e,U(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?gt(t,U(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>ft(t,U(n,0)),toJson:(e,{db:t,args:n})=>({...js(t,U(n,0)),...e}),sections:Yue}),er({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:N("Navigation"),query:({db:e,args:t})=>Fa(e,U(t,0)),format:e=>e.relativePath}),er({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:N("Navigation"),query:({db:e,args:t})=>Na(e,U(t,0)),format:e=>e.relativePath}),JA({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:N("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Aa(e,U(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${dt(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}`)}]}),er({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:N("Navigation"),query:({db:e,args:t})=>_a(e,U(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[S("--full","Run unbounded semantic analysis on large indexes"),S("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:N("Navigation"),handler:Zue},er({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:N("Navigation"),query:({db:e,args:t})=>Rg(e,U(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:j([S("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:N("Navigation"),handler:Que},er({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:N("Navigation"),query:({db:e,args:t})=>Ig(e,U(t,0)),format:e=>` ${dt(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>ft(t,U(n,0)),emptyMessage:({db:e,args:t})=>gt(e,U(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Xt(t,U(n,0),e,"members")}),er({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[S("-s, --scope <path>","Limit to files matching path"),S("-n, --limit <n>","Number of results",L,100),S("--full","Run unbounded analysis on large indexes")],docs:N("Navigation"),query:({db:e,args:t,opts:n})=>Ag(e,U(t,0),{scope:A(n,"scope"),limit:Y(n,"limit",100)}),format:e=>` ${ye(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${U(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
1470
- ${e.length} symbol(s)`)}),Fp({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[S("-s, --scope <path>","Limit to files matching path")],docs:N("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>_g(e,{scope:A(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),er({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:N("Navigation"),query:({db:e,args:t})=>$g(e,U(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>ft(t,U(n,0)),emptyMessage:({db:e,args:t})=>gt(e,U(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Xt(t,U(n,0),e,"hierarchy")}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:j([S("-C, --context <n>","Extra lines of context above/below",L,0)]),renderShape:"custom",docs:N("Navigation"),handler:tde},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:j([S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:N("Navigation"),handler:nde},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:j([S("--forward","Forward slice (what does this affect). Default is backward."),S("--depth <n>","Max transitive depth for backward slice",L,3),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:N("Navigation"),handler:rde}];var ide=Ne("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=Y(n,"limit",20),o=Uh(e,U(t,0),{semantic:r.semantic,impactDepth:$(n,"impactDepth",3),sliceDepth:$(n,"sliceDepth",3),scope:A(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(E(n,"json")){H("plan-context",t,n,{...js(e,U(t,0)),...o},{analysisBudget:r.analysisBudget});return}return O.empty(gt(e,U(t,0)))}if(E(n,"json")){H("plan-context",t,n,o.matched.symbol?{...js(e,U(t,0)),...o}:o,{analysisBudget:r.analysisBudget});return}o.matched.symbol&&ft(e,U(t,0));let s=[{title:"TARGET",rows:ode(o)},{title:"DEFINITIONS",rows:sde(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:ade(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:cde(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:lde(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:ude(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:dde(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:pde(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:mde(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:fde(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:gde(o),skipIfEmpty:!0}];O.sectionedReport(s)}),Y_=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:j([S("--impact-depth <n>","Maximum affected traversal depth",L,3),S("--slice-depth <n>","Maximum backward slice depth",L,3),S("-s, --scope <path>","Limit downstream impact to files matching path"),S("-n, --limit <n>","Rows per section",L,20),S("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:N("Planning",["scip-query plan-context parseSymbol"]),handler:ide}];function ode(e){return[`Target: ${e.target}`,`Matched: symbol=${pS(e.matched.symbol)} file=${pS(e.matched.file)} module=${pS(e.matched.module)}`]}function sde(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${ye(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
1471
- `).map((o,s)=>` ${String(Rt(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${dt(r.startLine,r.endLine)} ${r.shortName}`)),hi(n,t).rows}function ade(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Rt(r.line)} in ${r.enclosingShort}`);return yo(hi(n,t))}function cde(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 yo(hi([...n,...r],t))}function lde(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}:${Rt(o.line)} in ${o.enclosingShort}`);return yo(hi([...n,...r,...i],t))}function ude(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 yo(hi(n,t))}function dde(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${dt(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return yo(hi(n,t))}function pde(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 yo(hi(n,t))}function mde(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` ${dt(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${ye(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),yo(hi(n,t))}function fde(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 gde(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 hi(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function yo(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function pS(e){return e?"yes":"no"}import{existsSync as zc}from"fs";import{existsSync as wde,mkdtempSync as kde,rmSync as Ide}from"fs";import{tmpdir as Pde}from"os";import{dirname as fS,join as gS}from"path";import{performance as eM}from"perf_hooks";import{spawnSync as Ede}from"child_process";import{createHash as hde}from"crypto";import{existsSync as yde,mkdirSync as bde,readFileSync as Sde,renameSync as vde,writeFileSync as xde}from"fs";import{homedir as Rde}from"os";import{dirname as Cde,join as mS}from"path";function Q_(e){return hde("sha256").update(e).digest("hex")}function X_(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?mS(t.XDG_CACHE_HOME,"scip-query"):mS(Rde(),".cache","scip-query"));return mS(n,e)}async function Z_(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(yde(t)){let l=Q_(Sde(t));if(l===r)return{status:"cached",path:t,sha256:l}}let o=await(e.fetchImpl??fetch)(n);if(!o.ok)throw new Error(`failed to download ${n}: HTTP ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),a=Q_(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);bde(Cde(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return xde(c,s),vde(c,t),{status:"downloaded",path:t,sha256:a}}var Dde=12e4,rM="v1.8.0",Tde=`https://github.com/tlaplus/tlaplus/releases/download/${rM}/tla2tools.jar`,Lde="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Hp(e){let t=e.spawn??Ede,n=Fde(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let r=e.timeoutMs??Dde,i=eM.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Ide(l,{recursive:!0,force:!0})}let s=Math.round(eM.now()-i),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=r,c=a?"timed-out":o.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:o.status,signal:o.signal,timedOut:a,diagnostics:Nde(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Fde(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&Er(tM(e),t)){let o=tM(e);return Er(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:fS(e.specPath)}:Bp("apalache",`Apalache binary is not available: ${o}`)}let r=hS(e),i=Er("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Bp(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Bp(n==="sany"?"sany":"tlc","java is not available on PATH");let o=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(o==="sany")return{checker:o,command:["java","-cp",r,"tla2sany.SANY",e.specPath],cwd:fS(e.specPath)};let s=e.metaDir??kde(gS(Pde(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:fS(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Bp("none",`unknown checker mode: ${n}`)}function tM(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function hS(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,iM(t),gS(e.projectRoot,"tla2tools.jar"),gS(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>wde(r))??null}function iM(e=process.env){return X_("tla2tools.jar",e)}async function oM(e={}){let t=e.cachePath??iM(e.env),n=e.expectedSha256??Lde,r=e.version??rM,i=e.url??Tde;return{...await Z_({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Nde(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let r=[...nM(n),...nM(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function nM(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Bp(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Ade}from"crypto";import{readFileSync as aM}from"fs";import{join as cM}from"path";var lM=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),uM=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),dM=new Set(["readFileSync","existsSync","statSync"]),_de=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Mde=/^\s*SELECT\b/i;function pM(e){return _de.test(e)?"write":Mde.test(e)?"read":null}var $de=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Ode(e,t){let n=e.match($de);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${J(t)}\\b`).test(r)}function mM(e,t,n,r=[],i=[]){let o=[],s=Hde(e,t,o),a=s.aliases,c=Wde(t),l=qde(t),u=Ude(t),d=zde(e,t,o),p=Jde(e,t,o);n&&Yde(t,n,i,o);let m=new Map((n?.actions??[]).map(x=>[x.name,x])),f=new Set(d.flatMap(x=>x.referents.map(R=>R.match?.symbol).filter(Boolean))),g=new Set((p?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),h=Qde(e,t,d,a,c,l,u,f,g,o,m),y=epe(e,d,a,c,l,u,o,m);return npe(e,d,o),rpe(t,r,o),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:bS(d.flatMap(x=>x.referents))+bS(s.referents)+bS(p?.referents??[]),staticWrites:h,staticReads:y,waivers:Cpe(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:jde(o)}}function jde(e){let t=new Map;for(let n of e){let r=`${n.category}:${n.modelElement??"-"}`,i=t.get(r);i||(i={groupKey:r,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=Bde(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Wp(r.severity)-Wp(n.severity)||n.groupKey.localeCompare(r.groupKey))}function Bde(e,t){return Wp(t)>Wp(e)?t:e}function Wp(e){return e==="error"?2:e==="warning"?1:0}function Hde(e,t,n){let r=[],i=[];for(let[o,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let u=Vp(e,l,n,o);i.push(u);let d=u.match;if(!d){c||n.push(Le("missing-referent","error","compiler-symbol",{modelElement:o,codeRef:l,message:`TLA+ variable ${o} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${o}.code to a live symbol, or remove the variable from the model mapping.`}));continue}ype(e,o,l,d,n,c),s.aliases.length===0&&a.add(M(d.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:Rpe(r),referents:i}}function Wde(e){let t=[];for(let[n,r]of Object.entries(e.variables))r.resource&&t.push({variable:n,path:r.resource.path});return t}function qde(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.statements??[])t.push({variable:n,pattern:i.pattern,regex:new RegExp(i.pattern)});return t}function Ude(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=aS(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function Vde(e,t,n,r,i,o){return fM(e,t,(s,a,c)=>bo(e,s,a,c,n,r,i,o))}function Gde(e,t,n,r,i,o){return fM(e,t,(s,a,c)=>Up(e,s,a,c,n,r,i,o))}function fM(e,t,n){let r=Qr(e,t,{semantic:!1});if(!r)return[];let i=[],o=new Set;for(let s of r.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=Ht(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))i.push({...c,via:s.shortName})}return i}function zde(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=cS(s),c="error"in a?s:a.ref,u=Vp(e,c,n,r).match;return u?(bpe(e,r,s,u,n),"error"in a||!a.window?{ref:s,match:u}:Kde(a.window,u)?(n.push(Le("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:u.relativePath,startLine:u.startLine,endLine:u.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${P(u.symbol)}'s actual span L${u.startLine+1}-L${u.endLine+1} in ${u.relativePath}.`,why:[`${s} resolves to ${P(u.symbol)} at ${u.relativePath}:${u.startLine+1}-${u.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${r}.code to fall within L${u.startLine+1}-L${u.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:u,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(Le("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:s,message:`TLA+ action ${r} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${r}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:r,mapping:i,referents:o}})}function Kde(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Jde(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Vp(e,s,n,"Init"),c=a.match;return c?Spe(e,s,c,n,i):i||n.push(Le("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:r,referents:o}}function Yde(e,t,n,r){let i=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))i.has(a)||r.push(Le("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))o.has(a)||r.push(Le("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(sM({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:r,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),sM({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:r,file:t.path}))}for(let a of e.invariants)s.has(a)||r.push(Le("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function sM(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),r=e.isWaived??(()=>!1);for(let i of t)n.has(i)||r(i)||e.findings.push(Le(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${i} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${i} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let i of n)t.has(i)||r(i)||e.findings.push(Le(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${i}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${i}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Qde(e,t,n,r,i,o,s,a,c,l,u){let d=[];for(let m of n){let f=[];for(let g of m.referents){if(!g.match)continue;let h=g.window??{startLine:g.match.startLine,endLine:g.match.endLine},y=bo(e,g.match.relativePath,h.startLine,h.endLine,r,i,o,s);f.push(...y),d.push(...y);let x=new Set(m.mapping.writes),R=Vde(e,g.match.symbol,r,i,o,s).filter(b=>x.has(b.variable));f.push(...R),d.push(...R)}Zde(m,f,l,u.get(m.name))}let p=t.unmappedWriteScope==="actions"?[]:fpe(e,t);for(let m of p)for(let f of bo(e,m,0,Number.POSITIVE_INFINITY,r,i,o,s))d.push(f),Xde(f)&&(f.enclosingSymbol&&(a.has(f.enclosingSymbol)||c.has(f.enclosingSymbol))||l.push(Le("unmapped-write","error","static-action",{modelElement:f.variable,codeRef:f.enclosingSymbol??`${f.file}:${f.line+1}`,file:f.file,startLine:f.line,endLine:f.line,message:`Modeled variable ${f.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${f.target} at ${f.file}:${f.line+1}.`,f.enclosingShort?`The write is inside ${f.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${f.variable} from the modeled slice if it is intentionally out of scope.`})));return xS(d)}function Xde(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function Zde(e,t,n,r){let i=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(r?.writes??[]);for(let a of t)r&&!s.has(a.variable)&&!Vc(e,"write",a.variable)&&n.push(Le("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${qp(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${r.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Vc(e,"write",a.variable)&&n.push(Le("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${qp(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of i)!o.has(a)&&!Vc(e,"write",a)&&n.push(Le("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function epe(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let u=[];for(let d of l.referents){if(!d.match)continue;let p=d.window??{startLine:d.match.startLine,endLine:d.match.endLine},m=Up(e,d.match.relativePath,p.startLine,p.endLine,n,r,i,o);u.push(...m),c.push(...m);let f=new Set(l.mapping.reads),g=Gde(e,d.match.symbol,n,r,i,o).filter(h=>f.has(h.variable));u.push(...g),c.push(...g)}tpe(l,u,s,a.get(l.name))}return RS(c)}function tpe(e,t,n,r){let i=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(r?.reads??[]);for(let a of t)r&&!s.has(a.variable)&&n.push(Le("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${qp(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${r.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Vc(e,"read",a.variable)&&n.push(Le("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${qp(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of i)!o.has(a)&&!Vc(e,"read",a)&&n.push(Le("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function npe(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Vp(e,s,n,r.name));for(let s of i)s.match||n.push(Le("missing-referent","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,message:`actions.${r.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${r.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(i.map(s=>s.match?.symbol).filter(Boolean));for(let s of r.referents){if(!s.match)continue;let a=Qr(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(Le("missing-call","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${r.name} no longer calls ${P(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${r.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function rpe(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(Le("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} uses action ${i.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${i.action} to the mapping, or fix the trace action name.`}));continue}let s=xpe(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(Le("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} changed ${c}, but action ${i.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${i.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function bo(e,t,n,r,i,o=[],s=[],a=[]){let c=ipe(e,t,n,r,i,o,s,a);return c||ppe(e,t,n,r,i,o,s,a)}function Up(e,t,n,r,i,o=[],s=[],a=[]){let c=ope(e,t,n,r,i,o,s,a);return c||mpe(e,t,n,r,i,o,s,a)}function ipe(e,t,n,r,i,o=[],s=[],a=[]){let c=oe(e,t);if(!c)return null;let l=[],u=d=>{if(!(d.startPosition.row>r||d.endPosition.row<n)){spe(e,t,d,i,l),gM(e,t,d,o,"write",l),hM(e,t,d,s,"write",l),yM(e,t,d,a,"write",l);for(let p of d.children)u(p)}};return u(c.rootNode),xS(l)}function ope(e,t,n,r,i,o=[],s=[],a=[]){let c=oe(e,t);if(!c)return null;let l=[],u=d=>{if(!(d.startPosition.row>r||d.endPosition.row<n)){lpe(e,t,d,i,l),gM(e,t,d,o,"read",l),hM(e,t,d,s,"read",l),yM(e,t,d,a,"read",l);for(let p of d.children)u(p)}};return u(c.rootNode),RS(l)}function spe(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&Uc(e,t,o,"assignment",r,i);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&Uc(e,t,o,"object-field",r,i);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&Uc(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&Uc(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!SM(o))return;Uc(e,t,o,"mutation-call",r,i)}}}function gM(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?SS(s):null;if(!a||!(i==="write"?uM:dM).has(a))return;let u=n.childForFieldName("arguments")?.namedChild(0);if(!u)return;let d=u.text;for(let p of r){if(!d.includes(p.path))continue;let m=tr(e,t,n.startPosition.row);o.push({variable:p.variable,alias:p.path,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"resource",enclosingSymbol:m?.symbol,enclosingShort:m?P(m.symbol):void 0})}}function SS(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function hM(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=ape(a);if(c!==null&&pM(c)===i)for(let l of r){if(!l.regex.test(c))continue;let u=tr(e,t,n.startPosition.row),d=n.childForFieldName("function")??n.namedChild(0),p=(d&&SS(d))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${p}(${cpe(c)})`,kind:"statement",enclosingSymbol:u?.symbol,enclosingShort:u?P(u.symbol):void 0})}}}function ape(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function cpe(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function yM(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?SS(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let u=l.text.trim();for(let d of r){if(!bM(d,a,u,i))continue;let p=tr(e,t,n.startPosition.row);o.push({variable:d.variable,alias:d.table,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"orm-call",enclosingSymbol:p?.symbol,enclosingShort:p?P(p.symbol):void 0})}}function bM(e,t,n,r){return n!==e.table?!1:r==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function lpe(e,t,n,r,i){if(!(!upe(n)||dpe(n)))for(let o of r){if(n.text!==o.alias)continue;let s=tr(e,t,n.startPosition.row);i.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?P(s.symbol):void 0})}}function upe(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function dpe(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&yS(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&yS(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&SM(n)&&yS(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function yS(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function SM(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&lM.has(t.text))}function Uc(e,t,n,r,i,o){for(let s of i){if(!vpe(s.alias,n.text))continue;let a=tr(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:r,enclosingSymbol:a?.symbol,enclosingShort:a?P(a.symbol):void 0})}}function ppe(e,t,n,r,i,o=[],s=[],a=[]){let l=aM(cM(e.config.projectRoot,t),"utf8").split(/\r?\n/),u=[],d=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let p=Math.max(0,n);p<=d;p+=1){let m=l[p]??"";for(let f of i){if(Ode(m,f.alias))continue;let g=J(f.alias);if(!new RegExp(`(?:\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${g}\\b\\s*\\.\\s*(?:${[...lM].join("|")})\\s*\\(|\\b${g}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(m))continue;let y=tr(e,t,p);u.push({variable:f.variable,alias:f.alias,file:t,line:p,target:m.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?P(y.symbol):void 0})}vM(e,t,p,m,o,uM,u),xM(e,t,p,m,s,"write",u),RM(e,t,p,m,a,"write",u)}return xS(u)}function mpe(e,t,n,r,i,o=[],s=[],a=[]){let l=aM(cM(e.config.projectRoot,t),"utf8").split(/\r?\n/),u=[],d=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let p=Math.max(0,n);p<=d;p+=1){let m=l[p]??"";for(let f of i){let g=J(f.alias);if(!new RegExp(`\\b${g}\\b`).test(m)||new RegExp(`\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(m))continue;let h=tr(e,t,p);u.push({variable:f.variable,alias:f.alias,file:t,line:p,target:m.trim(),kind:"source-scan",enclosingSymbol:h?.symbol,enclosingShort:h?P(h.symbol):void 0})}vM(e,t,p,m,o,dM,u),xM(e,t,p,m,s,"read",u),RM(e,t,p,m,a,"read",u)}return RS(u)}function vM(e,t,n,r,i,o,s){if(i.length!==0)for(let a of o){let c=r.indexOf(`${a}(`);if(c===-1)continue;let l=r.slice(c+a.length);for(let u of i){if(!l.includes(u.path))continue;let d=tr(e,t,n);s.push({variable:u.variable,alias:u.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:d?.symbol,enclosingShort:d?P(d.symbol):void 0})}}}function xM(e,t,n,r,i,o,s){if(i.length!==0&&pM(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=tr(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:r.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?P(c.symbol):void 0})}}function RM(e,t,n,r,i,o,s){if(i.length!==0)for(let a of r.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let u of i){if(!bM(u,c,l,o))continue;let d=tr(e,t,n);s.push({variable:u.variable,alias:u.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:d?.symbol,enclosingShort:d?P(d.symbol):void 0})}}}function fpe(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(i=>i.relative_path).filter(i=>n.some(o=>i.includes(o)))}function Vp(e,t,n,r){let i=Ht(e,t),o=i.match??(t.includes("#")?Ht(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!gpe(t)&&n.push(Le("ambiguous-referent","warning","compiler-symbol",{modelElement:r,codeRef:t,file:i.match.relativePath,startLine:i.match.startLine,endLine:i.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${P(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,hpe(i.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:o}}function gpe(e){return/[/#:]/.test(e)}function hpe(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function ype(e,t,n,r,i,o=!1){let s=vS(e,r);if(s===null||wpe.has(s)||o)return;let a=CS.has(s);i.push(Le("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Un(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${P(r.symbol)} with SCIP kind ${Un(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function bpe(e,t,n,r,i){let o=vS(e,r);o===null||CM.has(o)||CS.has(o)&&i.push(Le("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${P(r.symbol)} with SCIP kind ${Un(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function Spe(e,t,n,r,i){let o=vS(e,n);o===null||CM.has(o)||i||CS.has(o)&&r.push(Le("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${P(n.symbol)} with SCIP kind ${Un(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function vS(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function tr(e,t,n){return se(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function vpe(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${J(e)}([^A-Za-z0-9_$]|$)`).test(t)}function xpe(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function xS(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function RS(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function Rpe(e){let t=new Set;return e.filter(n=>{let r=`${n.variable}:${n.alias}`;return t.has(r)?!1:(t.add(r),!0)})}function bS(e){return e.filter(t=>t.match).length}function qp(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Vc(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function Cpe(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var CS=new Set(Fu()),CM=new Set(dn()),wpe=new Set(Cw());function Le(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Ade("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as kpe}from"fs";import{basename as Ipe,join as wM}from"path";var wS=/^[A-Za-z_][A-Za-z0-9_]*$/;function kM(e,t,n={}){let r=[],i=se(e,t,{includeClassMemberFallbacks:!0});if(i.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=kpe(wM(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=C=>C.symbol.trimEnd().endsWith("()."),c=i.filter(C=>!a(C)&&!C.isTypeLike&&C.parentTypeName===null&&wS.test(C.leaf)),l=c.map(C=>({variable:C.leaf,alias:C.leaf})),u=l.length>0?bo(e,t,0,Number.POSITIVE_INFINITY,l):[],d=new Set(u.map(C=>C.variable)),p=c.filter(C=>d.has(C.leaf)?!0:Dpe(s,C)),m=null,f;if(p.length>0)f=i.filter(C=>a(C)&&C.parentTypeName===null);else{if(m=Ppe(e,t,i,a),!m){let C=i.some(k=>!a(k)&&!k.isTypeLike&&k.parentTypeName!==null&&wS.test(k.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(C?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}p=m.fields,f=m.methods,r.push(`state scoped to class ${m.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let g=p.map(C=>Tpe(C,s,t,r,m?.className)),h=g.map(C=>({variable:C.name,alias:C.leaf})),y=[],x=new Set;for(let C of f){let k=bo(e,t,C.startLine,C.endLine,h);if(k.length===0)continue;let T=Up(e,t,C.startLine,C.endLine,h),F=Ape(IM(C.leaf),x);y.push({name:F,leaf:C.leaf,codeRef:Epe(t,C,m?.className),startLine:C.startLine,writes:[...new Set(k.map(V=>V.variable))].sort(),reads:[...new Set(T.map(V=>V.variable))].sort()})}y.length===0&&r.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let R=n.moduleName??_pe(t),b=n.specDir??wM("specs",R),v=Mpe(R,g,y,t),w=$pe(),I=Ope(R,b,t,g,y);return{moduleName:R,file:t,variables:g,actions:y,warnings:r,spec:v,cfg:w,map:I}}function Ppe(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!wS.test(s.leaf))continue;let a=i.get(s.parentTypeName);a?a.push(s):i.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of i){let c=n.filter(p=>r(p)&&p.parentTypeName===s),l=a.map(p=>({variable:p.leaf,alias:p.leaf})),u=new Set;for(let p of c)for(let m of bo(e,t,p.startLine,p.endLine,l))u.add(m.variable);let d=a.filter(p=>u.has(p.leaf));d.length!==0&&(!o||d.length>o.fields.length)&&(o={className:s,fields:d,methods:c})}return o}function Epe(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function Dpe(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function Tpe(e,t,n,r,i){let o=Lpe(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=Fpe(e.leaf,o);return a||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:i?`${n}/${i}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function Lpe(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function Fpe(e,t){let r=t.match(new RegExp(`\\b${jpe(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=Npe(r);l?(s=`{${l.map(u=>`"${u}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(r)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(r)||/^(Array|ReadonlyArray)</.test(r))&&(a="sequence",s=null)}let c=null;if(o){let l=o.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(o)?c=o.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(o)?c=o.match(/^-?\d+/)[0]:/^\[\s*\]/.test(o)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function Npe(e){let t=e.split("|").map(r=>r.trim());if(t.length<2)return null;let n=[];for(let r of t){let i=r.match(/^['"]([^'"]*)['"]$/);if(!i)return null;n.push(i[1])}return n}function IM(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function Ape(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function _pe(e){let n=Ipe(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return IM(n||"Model")}function Mpe(e,t,n,r){let i=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${r}'.`),o.push("\\* Draft evidence tier: state from the static write scan, domains from"),o.push("\\* declared types, actions from top-level callables that write state."),o.push("\\* Review every TODO before trusting a green model-check run."),o.push("EXTENDS Naturals, Sequences, TLC"),o.push(""),o.push(`VARIABLES ${i.join(", ")}`),o.push(""),o.push(`vars == <<${i.join(", ")}>>`),o.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';o.push(`${s.name}Domain == ${a}`)}o.push(""),o.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;o.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}o.push("");for(let s of n){let a=i.filter(c=>!s.writes.includes(c));o.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),o.push(`${s.name} ==`),o.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let u=t.find(d=>d.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${u} \\* TODO: tighten to the concrete transition`)}a.length>0&&o.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),o.push("")}if(o.push("Next =="),n.length===0)o.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())o.push(` \\/ ${a.name}`);o.push(""),o.push("Spec == Init /\\ [][Next]_vars"),o.push(""),o.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?o.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):o.push(` /\\ ${s.name} \\in ${s.name}Domain`);return o.push("===="),o.push(""),o.join(`
1472
- `)}function $pe(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
1473
- `)}function Ope(e,t,n,r,i){let o={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(r.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(o,null,2)}
1474
- `}function jpe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PM(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?te(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:Bpe(n),wiring:r,variables:n}}function Bpe(e){return`/**
1475
- * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
1476
- *
1477
- * Usage inside a mapped action (record the model-visible slice around the
1478
- * mutation):
1479
- *
1480
- * import { tlaRecord } from './scip-tla-recorder.js';
1481
- * export function enqueue(job: string) {
1482
- * const before = snapshot();
1483
- * queue.push(job);
1484
- * tlaRecord('Enqueue', before, snapshot());
1485
- * }
1486
- *
1487
- * where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
1488
- * each field with the real runtime value, e.g.
1489
- * const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
1490
- *
1491
- * Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
1492
- * wiring is safe to leave in place. The output is a JSON array compatible
1493
- * with 'scip-query tla trace-check --trace <path>'.
1494
- */
1495
- import { readFileSync, writeFileSync } from 'node:fs';
1496
-
1497
- interface TlaTraceStep {
1498
- action: string;
1499
- before: Record<string, unknown>;
1500
- after: Record<string, unknown>;
1501
- }
1502
-
1503
- const tracePath = process.env['SCIP_TLA_TRACE'];
1504
-
1505
- export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
1506
- if (!tracePath) return;
1507
- let steps: TlaTraceStep[] = [];
1508
- try {
1509
- steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
1510
- if (!Array.isArray(steps)) steps = [];
1511
- } catch {
1512
- steps = [];
1513
- }
1514
- steps.push({ action, before, after });
1515
- writeFileSync(tracePath, JSON.stringify(steps, null, 2));
1516
- }
1517
- `}import{copyFileSync as Hpe,mkdtempSync as Wpe,readdirSync as qpe,rmSync as Upe,writeFileSync as EM}from"fs";import{tmpdir as Vpe}from"os";import{basename as Gpe,dirname as zpe,join as Gc}from"path";function Gp(e,t){let n=new Map;for(let r of t)n.set(r.action,(n.get(r.action)??0)+1);return e.map(r=>({action:r,stepsObserved:n.get(r)??0}))}function Kpe(e,t,n,r="Next"){if(n.length===0)return{error:"trace has no steps"};let i=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=g=>{let h={};for(let[y,x]of Object.entries(g)){if(!t.includes(y))continue;let R=Ype(x);R!==void 0&&(h[y]=R)}return h};s.push(c(a));for(let g of n){if(g.before)for(let[h,y]of Object.entries(g.before))h in a||(a[h]=y);Object.assign(a,g.after??{}),s.push(c(a))}let l=t.filter(g=>s.every(h=>g in h)),u=t.filter(g=>!l.includes(g));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};u.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${u.join(", ")} \u2014 divergence in these variables is NOT checked.`);let d=`${e}Trace`,p=s.map(g=>` [${l.map(h=>`${h} |-> ${TM(g[h])}`).join(", ")}]`).join(`,
1518
- `),m=[`---- MODULE ${d} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${r}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",p,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(g=>` /\\ ${g} = TraceStates[1].${g}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${r}`,...l.map(g=>` /\\ ${g}' = TraceStates[traceIdx + 1].${g}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
1519
- `),f=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
1520
- `);return{moduleName:d,moduleText:m,cfgText:f,variables:l,skippedVariables:u,states:s.length,warnings:i}}function DM(e){let t=e.mappedActions??[],n=Kpe(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Gp(t,[])};let r=Wpe(Gc(Vpe(),"scip-tla-trace-"));try{let i=zpe(e.specPath);for(let u of qpe(i))u.endsWith(".tla")&&Hpe(Gc(i,u),Gc(r,u));let o=Gc(r,`${n.moduleName}.tla`),s=Gc(r,`${n.moduleName}.cfg`);EM(o,n.moduleText),EM(s,n.cfgText);let a=Hp({...e.toolOptions,specPath:o,configPath:s,checker:"tlc"});if(a.status==="skipped")return{status:"unavailable",states:n.states,detail:a.diagnostics[0]?.message??"model checker unavailable",checker:a,generation:n,actionCoverage:Gp(t,[])};if(a.status==="passed")return{status:"accepted",states:n.states,detail:`TLC accepted all ${n.states} pinned states under ${e.baseModuleName}!${e.nextOperator??"Next"}.`,checker:a,generation:n,actionCoverage:Gp(t,e.steps)};let c=Jpe(a.stdout,e.steps),l=c?e.steps.slice(0,c.divergedStep.index):[];return{status:"diverged",states:n.states,...c??{},detail:c?`trace diverges entering state ${c.divergedAtState+1} (step ${c.divergedStep.index}: ${c.divergedStep.action}) \u2014 the model's ${e.nextOperator??"Next"} relation does not accept the recorded transition.`:"TLC rejected the trace but the divergent step could not be parsed from its output; see checker stdout.",checker:a,generation:n,actionCoverage:Gp(t,l)}}finally{Upe(r,{recursive:!0,force:!0})}}function Jpe(e,t){let n=null;for(let o of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(o[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let r=n-1,i=t[r];return{divergedAtState:n,divergedStep:{index:r,action:i?.action??"unknown"}}}function Ype(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isInteger(e))return e;if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n=="string"||typeof n=="boolean")t.push(n);else if(typeof n=="number"&&Number.isInteger(n))t.push(n);else return;return t}}function TM(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>TM(t)).join(", ")}>>`}function LM(e){return Gpe(e).replace(/\.tla$/i,"")}import{mkdirSync as NM,writeFileSync as AM}from"fs";import{dirname as Qpe,join as Bs}from"path";var Xpe=async(...e)=>{let{args:t,opts:n}=eS(e),r=U(t,0);if(r==="fetch-tools"){let o=await oM();if(E(n,"json")){H("tla",t,n,o);return}console.log(`tla2tools.jar ${o.status}: ${o.path}`),console.log(`Version: ${o.version}`),console.log(`SHA-256: ${o.sha256}`);return}if(r==="scaffold"){let o=ke(t,1);if(!o)throw new Error("tla scaffold requires a target source file");Ee(s=>Zpe(s,t,n,o));return}if(r==="instrument"){let o=ke(t,1);Ee(s=>eme(s,t,n,o));return}if(r==="trace-check"){let o=ke(t,1);if(!o)throw new Error("tla trace-check requires a spec path");Ee(s=>tme(s,t,n,o));return}if(r!=="verify")throw new Error(`unknown tla operation: ${r}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let i=ke(t,1);if(!i)throw new Error("tla verify requires a spec path");Ee(o=>ime(o,t,n,i))};function Zpe(e,t,n,r){let i=e.config.projectRoot,o=kM(e,r,{moduleName:A(n,"moduleName"),specDir:A(n,"out")}),s=A(n,"out")??Bs("specs",o.moduleName),a=Qt(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=E(n,"force"),l=[{path:Bs(a,`${o.moduleName}.tla`),body:o.spec},{path:Bs(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Bs(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let u of l)if(!c&&zc(u.path))throw new Error(`refusing to overwrite ${u.path} (pass --force to replace scaffold output)`);NM(a,{recursive:!0});for(let u of l)AM(u.path,u.body);if(E(n,"json")){H("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:r,written:l.map(u=>u.path),variables:o.variables,actions:o.actions,warnings:o.warnings});return}console.log(`Scaffolded ${o.moduleName} from ${r} (draft \u2014 review every TODO):`);for(let u of l)console.log(` wrote ${u.path}`);console.log(`Variables (${o.variables.length}): ${o.variables.map(u=>`${u.name}${u.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${o.actions.length}): ${o.actions.map(u=>`${u.name}(writes: ${u.writes.join(",")||"-"})`).join("; ")}`);for(let u of o.warnings)console.log(`WARNING: ${u}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${Bs(s,`${o.moduleName}.tla`)}'.`)}function eme(e,t,n,r){let i=e.config.projectRoot,o=A(n,"map")??(r?$p(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Mp(i,o);if(!s.loaded)throw new Error(s.errors.join(`
1521
- `));let{contract:a,mapDir:c}=s.loaded,l=PM(e,a),u=A(n,"out")??Bs(c,"scip-tla-recorder.ts"),d=Qt(i,u);if(!d)throw new Error(`instrument output escapes the project root: ${u}`);if(!E(n,"force")&&zc(d))throw new Error(`refusing to overwrite ${d} (pass --force to replace the recorder)`);if(NM(Qpe(d),{recursive:!0}),AM(d,l.recorderSource),E(n,"json")){H("tla",t,n,{operation:"instrument",recorder:d,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${d}`),console.log("Wire tlaRecord(...) into each mapped action (1 line per action), then run your tests with"),console.log("SCIP_TLA_TRACE=<trace.json> set, and check the result with 'scip-query tla trace-check'."),console.log("Wiring sites:");for(let p of l.wiring){let m=p.file?`${p.file}:${p.line}`:`UNRESOLVED (${p.codeRef})`;console.log(` - ${p.action} -> ${m} writes: ${p.writes.join(", ")||"-"}`)}}function tme(e,t,n,r){let i=e.config.projectRoot,o=Qt(i,r);if(!o||!zc(o))throw new Error(`TLA+ spec not found: ${r}`);let s=A(n,"map")??$p(r),a=Mp(i,s);if(!a.loaded)throw new Error(a.errors.join(`
1522
- `));let{contract:c}=a.loaded,l=Ms(n,"trace"),d=uS(i,[...c.traces,...l]).flatMap(f=>lS(i,f).steps);if(d.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let p=DM({specPath:o,baseModuleName:LM(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:d,nextOperator:A(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:A(n,"tlaTools"),timeoutMs:De(n,"timeoutMs")}}),m=p.status==="accepted"||p.status==="unavailable"&&E(n,"allowUnknown")?0:1;if(E(n,"json")){H("tla",t,n,{operation:"trace-check",...p,exitCode:m}),process.exitCode=m;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${d.length} step(s) -> ${p.states} pinned state(s)`),p.generation){console.log(`Pinned variables: ${p.generation.variables.join(", ")}`);for(let f of p.generation.warnings)console.log(`WARNING: ${f}`)}console.log(`${p.status.toUpperCase()}: ${p.detail}`),E(n,"coverage")&&nme(p.actionCoverage),process.exitCode=m}function nme(e){if(e.length===0)return;let t=e.filter(r=>r.stepsObserved>0),n=e.filter(r=>r.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let r of t)console.log(` - ${r.action}: ${r.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(r=>r.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function rme(e,t,n,r){let i=A(r,"map");if(i)return{mapArg:i};let o=$p(t),s=Qt(e,o);if(s&&zc(s))return{mapArg:o};let a=p_(e,n);if(a.status==="ambiguous")throw new Error(`multiple *.scip-tla.json files declare module "${a.moduleName}": ${a.candidates.join(", ")} \u2014 pass --map to disambiguate`);return a.status==="found"?{mapArg:a.mapPath,mappingDiscoveredBy:"module-field"}:{mapArg:o}}function ime(e,t,n,r){let i=e.config.projectRoot,o=Qt(i,r);if(!o||!zc(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=rme(i,r,o,n),c=Mp(i,s);if(!c.loaded)throw new Error(c.errors.join(`
1523
- `));let{contract:l,mapPath:u,mapDir:d}=c.loaded,p=A(n,"config")??l.config,m=a_(i,d,p),f=sme(A(n,"checker")??"auto"),g=A(n,"tlaTools"),h=ome(i,r,o,g)??c_(i,r),y=u_(m),x=Ms(n,"trace"),b=uS(i,[...l.traces,...x]).map(F=>({tracePath:F,...lS(i,F)})),v=b.flatMap(F=>F.steps),w=new Set(x),I=b.filter(F=>w.has(F.tracePath)).flatMap(F=>F.errors),C=mM(e,l,h,v,y);for(let F of[...c.errors,...I])C.findings.push({id:`TLA-CONTRACT-${C.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:F,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun scip-query tla verify."});let k=Hp({projectRoot:i,specPath:o,configPath:m??void 0,checker:f,tlaToolsJar:g,apalacheBin:A(n,"apalache"),length:$(n,"length",10),timeoutMs:De(n,"timeoutMs")});k.status==="skipped"&&f!=="none"&&C.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:k.diagnostics.map(F=>F.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'scip-query tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let T={operation:"verify",specPath:o,mapPath:u,...a?{mappingDiscoveredBy:a}:{},...m?{configPath:m}:{},checker:k,conformance:C,exitCode:ame(k,C,E(n,"allowUnknown"))};if(E(n,"json")){H("tla",t,n,T),process.exitCode=T.exitCode;return}cme(T,E(n,"full")),process.exitCode=T.exitCode}function ome(e,t,n,r){let i=hS({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=QA({specPath:n,jarPath:i});return o?l_(e,t,o):null}var _M=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",options:j([S("--map <file>","scip-query TLA mapping JSON file"),S("--config <file>","TLA+ checker config file"),S("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),S("--tla-tools <jar>","Path to tla2tools.jar"),S("--apalache <binary>","Path to apalache-mc binary"),S("--length <n>","Bounded checker length for Apalache",L,10),S("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",Pr),S("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",so,[]),S("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),S("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),S("--allow-unknown","Exit zero when only unknown findings remain"),S("--out <path>","Output directory (scaffold) or file (instrument)"),S("--module-name <name>","Module name for scaffolded specs"),S("--force","Overwrite existing scaffold/instrument output"),S("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:N("Formal Models",["scip-query tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","scip-query tla scaffold src/queue/store.ts","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","scip-query tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","scip-query tla verify specs/Queue.tla --timeout-ms 300000","scip-query tla verify specs/Queue.tla --full","scip-query tla fetch-tools"]),handler:Xpe}];function sme(e){if(!s_(e))throw new Error(`unknown checker mode: ${e}`);return e}function ame(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(r=>r.severity==="error")||!n&&t.findings.some(r=>r.evidence==="unknown")?1:0}var FM=3;function cme(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let o of e.checker.diagnostics)console.log(` [${o.severity}] ${o.message}`);let n=e.conformance.findings.filter(o=>o.severity==="error"),r=e.conformance.findings.filter(o=>o.evidence==="unknown"),i=ume(e);console.log(`
1524
- Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${i}`);for(let o of dme(e))console.log(`WARNING: ${o}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let o of e.conformance.waivers){let s=o.legacy?" legacy":"",a=o.action?`${o.action} ${o.kind}`:`variable ${o.kind}`;console.log(` - ${a} ${o.variable}:${s} ${o.reason}`)}}if(e.conformance.findings.length===0){console.log(e.conformance.waivers.length===0?`PASS: model, mapping, and checked code evidence agree (model parsed by: ${e.conformance.modelParse}).`:`PASS: model checker and unwaived conformance checks passed (model parsed by: ${e.conformance.modelParse}); see waived facts above.`);return}if(console.log(`Findings: ${n.length} error(s), ${r.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let o of e.conformance.findings)MM(o);return}lme(e.conformance)}function lme(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
1525
- Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
1526
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,FM)){let o=t.get(i);o&&MM(o)}let r=n.count-FM;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function ume(e){let t=`${e.checker.checker} ${e.checker.status==="passed"?"PASS":e.checker.status.toUpperCase()}`,n=e.conformance.waivers.filter(s=>s.kind==="write").length,r=e.conformance.waivers.filter(s=>s.kind==="read").length,i=e.conformance.waivers.filter(s=>s.kind==="referent").length,o=e.conformance.findings.filter(s=>s.category==="missing-call").length;return[`checker: ${t}`,`model parsed by: ${e.conformance.modelParse}`,`writes: ${e.conformance.staticWrites.length} verified, ${n} waived`,`reads: ${e.conformance.staticReads.length} verified, ${r} waived`,`calls: ${o===0?"checked":`${o} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...i>0?[`referents: ${i} waived`]:[]].join(" | ")}function dme(e){let t=[],n=e.conformance.waivers.filter(i=>i.kind==="write").length,r=e.conformance.waivers.filter(i=>i.kind==="read").length;return n>0&&e.conformance.staticWrites.length===0&&t.push("NOTHING PROVEN ABOUT WRITES: every write fact found in this run was waived or unobserved."),r>0&&e.conformance.staticReads.length===0&&t.push("NOTHING PROVEN ABOUT READS: every read fact found in this run was waived or unobserved."),t}function MM(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${ye(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
1527
- [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var $M=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],pme=[V_,J_,G_,jp,K_,Y_,_M,z_],OM=pme.flat(),mme=new Map(OM.map(e=>[e.id,e]));for(let e of OM)if(!$M.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Hs=$M.map(e=>fme(e));function fme(e){let t=mme.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var gme=Hs.slice(0,kS("plan-context")),hme=Hs.slice(zp("drift"),kS("self-audit")),yme=Hs.slice(zp("convergence"),kS("slice")),bme=Hs.slice(zp("redundant-reexports")),jM=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[S("-l, --language <lang>","Index only this language (can be repeated)",so,[]),S("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),S("--force","Rebuild even if source inputs are unchanged"),S("--allow-partial","Write an incomplete index when one or more detected languages fail"),S("--indexer-concurrency <n>","Number of language indexers to run at once",Pr),S("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:N("Indexing",["scip-query reindex"]),handler:fA},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:N("Indexing"),handler:gA},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[S("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:N("Indexing"),handler:hA},...gme,{id:Wd,command:Wd,description:"Internal diff-impact batch worker",hidden:!0,options:[S("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:yA},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:j([S("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:N("Impact"),handler:bA},...hme,{id:Ic,command:Ic,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:SA},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[S("-s, --scope <path>","Limit to files matching path"),S("--full","Run unbounded candidate analyses on large indexes"),S("--json","Output as JSON for programmatic consumption"),S("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),S("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:N("Health",["scip-query health --json","scip-query health --baseline"]),handler:vA},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[S("--json","Output as JSON for programmatic consumption"),S("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),S("--include-heavy","Include expensive full-detector commands in the command matrix"),S("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",so,[]),S("--timeout-ms <n>","Per-command timeout in milliseconds",Pr,18e4),S("--progress","Print benchmark command start/finish progress to stderr"),S("--profile","Enable low-overhead phase profiling in benchmarked commands"),S("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:N("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:xA},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[S("--top <n>","Maximum repeated-work groups to show",Pr,20),S("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:N("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:RA},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[S("-s, --scope <path>","Limit compared definitions to files matching path"),S("--limit <n>","Maximum definitions to compare unless --full is set",Pr),S("--max-mismatches <n>","Maximum mismatch details to include in output",Ps),S("--full","Compare every indexed TypeScript-like definition"),S("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:CA},...yme,{id:"install-skills",command:"install-skills",description:`Install skills (${op.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:N("Maintenance"),handler:IA},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[S("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),S("--remove","Remove managed project hooks and remember the opt-out"),S("--force","Reinstall hooks even after a previous --remove opt-out"),S("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:N("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:PA},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:pL},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:mL},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:N("Maintenance"),handler:EA},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[S("--matrix","Render the project capability matrix (default output)"),S("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:N("Maintenance"),handler:DA},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[S("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:N("Maintenance"),handler:TA},...bme,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:N("Maintenance"),handler:FA},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[S("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:N("Maintenance",["scip-query config-validate"]),handler:NA},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:j([S("--reason <text>","Required human reason for accepting the finding"),S("--check <check>","Optional detector/check name to narrow the suppression"),S("--file <path>","Optional file path to narrow the suppression"),S("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:N("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:AA},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:j([S("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),S("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:N("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:_A},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[S("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:N("Maintenance"),handler:MA},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:j([S("--guided","Open the interactive checklist (the default in a terminal)"),S("--yes","Accept recommended setup defaults without prompting"),S("--git-hook","Also install a git pre-commit hook that runs diff-gate"),S("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),S("--no-skills","Skip user-level agent skill installation"),S("--no-parsers","Skip Tree-sitter AST parser installation and repair"),S("--no-health","Skip the optional full health audit and dossier"),S("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:N("Maintenance",["scip-query setup","scip-query setup --json"]),handler:jA},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[S("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:N("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:OA},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[S("--force","Overwrite an existing workflow"),S("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:N("Maintenance",["scip-query setup-ci"]),handler:BA},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:j([S("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),S("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),S("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:N("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:HA},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:j([S("--daemon","Ensure the demand-started background service is running"),S("--status","Show background/foreground watcher state"),S("--stop","Stop the watcher or background service for this project"),S("--debounce <ms>","Ms to wait after last change (default: 250)",Ps),S("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",Ps),S("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Ps),S("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",Ps)]),renderShape:"custom",docs:N("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:WA},{id:"status",command:"status",description:"Show index status for this project",options:[S("--json","Output as JSON for programmatic consumption"),S("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:N("Maintenance"),handler:VA}];function zp(e){let t=Hs.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function kS(e){return zp(e)+1}function BM(e){return e.evidence?e.evidence:Sme.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var Sme=new Set(["diff-gate","health","plan-context","co-change"]);function HM(e,t){return iA(new Map(t.map(n=>[n.id,BM(n)]))),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(async(...i)=>{try{await n.handler(...i)}catch(o){vme(o)}}),{descriptor:n,command:r}})}function vme(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as xme,mkdirSync as Rme,readFileSync as Cme,writeFileSync as wme}from"fs";import{homedir as kme}from"os";import{join as Kp}from"path";var Ime=1440*60*1e3,qM="update-check.json",Pme="https://registry.npmjs.org/scip-query/latest";async function UM(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER||e.commandName&&Eme(e.commandName))return;let n=e.cacheDir??Lme(t),r=e.now??Date.now(),i=e.currentVersion??Fe,o=Fme(n),s=o&&r-o.checkedAt<Ime?o.latestVersion:await Nme(n,e.fetchLatestVersion??_me,r);if(!s||!Tme(s,i))return;(e.writeNotice??(c=>console.error(c)))(Dme(i,s))}function Eme(e){return e==="hook-context"||e==="hook-stop"}function Dme(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
1528
- `)}function Tme(e,t){let n=WM(e),r=WM(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 Lme(e){let t=e.XDG_CACHE_HOME||Kp(kme(),".cache");return Kp(t,"scip-query")}function Fme(e){let t=Kp(e,qM);if(!xme(t))return null;try{let n=JSON.parse(Cme(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 Nme(e,t,n){let r;try{r=await t()}catch{r=null}return Ame(e,{checkedAt:n,latestVersion:r}),r}function Ame(e,t){try{Rme(e,{recursive:!0}),wme(Kp(e,qM),`${JSON.stringify(t,null,2)}
1529
- `)}catch{}}async function _me(){let e=await fetch(Pme,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function WM(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Jp.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Fe);HM(Jp,jM);Jp.hook("preAction",async(e,t)=>{$me();let n=t.name();await UM({commandName:n});let r=sT(n),i=jf(n);if(!r&&!i)return;let o=Me(),s=ut(o),a=zt(o,s);if(r){let l=$d(o,s,a);l.kind==="failed"&&process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${l.reason}`)}if($N(o,Fe),!i)return;let c=du({commandName:n,projectRoot:o,cacheDir:a.cacheDir,cliVersion:Fe,config:s});c.kind==="failed"&&console.error(`warning: scip-query watch service did not start: ${c.message}`)});function $me(){if(ol(),!re()||sl())return;let e=null;try{e=Ee(t=>Ye(t))}catch{}bm({command:il()??`scip-query ${process.argv.slice(2).join(" ")}`,toolVersion:Fe,projectFingerprint:e})}Ome()&&await Jp.parseAsync();function Ome(){if(!process.argv[1])return!1;let e=Mme(import.meta.url);try{return VM(e)===VM(process.argv[1])}catch{return e===process.argv[1]}}export{Jp as program,Jt as renderHeuristicNotice};
2
+ import{a as g}from"./chunk-W3557RPL.js";import{Fc as a,Z as A,a as E,ad as V,bd as f,cd as I,ea as P,ed as U,fa as x,fd as _,ga as S,gd as j,h as v,i as D,ia as k,j as w,k as N,l as b,rd as W,yd as T}from"./chunk-VQWDZ34M.js";import{program as m}from"commander";import{realpathSync as F}from"fs";import{fileURLToPath as de}from"url";var H=new Set(["code","outline","refs"]);function B(e){return e!==void 0&&H.has(e)}async function R(e){if(B(e)){let{directNavigationQueryCommandDescriptors:t}=await import("./direct-navigation-K3CTVVBU.js"),o=t.find(r=>r.id===e);if(!o)throw new Error(`Direct navigation command descriptor is unavailable: ${e}`);return[o]}let{commandDescriptors:n}=await import("./command-descriptors-AQWWJNTT.js");return n}function O(e){return e.evidence?e.evidence:J.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var J=new Set(["diff-gate","health","plan-context","co-change"]);function M(e,n){return T(new Map(n.map(t=>[t.id,O(t)]))),n.map(t=>{let o=t.hidden?e.command(t.command,{hidden:!0}):e.command(t.command);o.description(t.description);for(let r of t.arguments??[])o.argument(r.name);for(let r of t.options??[])r.parser&&Object.hasOwn(r,"defaultValue")?o.option(r.flags,r.description,r.parser,r.defaultValue):r.parser?o.option(r.flags,r.description,r.parser):Object.hasOwn(r,"defaultValue")?o.option(r.flags,r.description,r.defaultValue):o.option(r.flags,r.description);return o.action(async(...r)=>{try{await t.handler(...r)}catch(i){z(i)}}),{descriptor:t,command:o}})}function z(e){let n=e instanceof Error?e.message:String(e);console.error(`error: ${n}`),process.exitCode=1}import{existsSync as K,mkdirSync as Q,readFileSync as X,writeFileSync as Y}from"fs";import{homedir as Z}from"os";import{join as p}from"path";var ee=1440*60*1e3,L="update-check.json",ne="https://registry.npmjs.org/scip-query/latest";async function h(e={}){let n=e.env??process.env;if(n.SCIP_QUERY_UPDATE_CHECK==="0"||n.NO_UPDATE_NOTIFIER||e.commandName&&te(e.commandName))return;let t=e.cacheDir??ie(n),o=e.now??Date.now(),r=e.currentVersion??a,i=ae(t),c=i&&o-i.checkedAt<ee?i.latestVersion:await ce(t,e.fetchLatestVersion??me,o);if(!c||!oe(c,r))return;(e.writeNotice??(s=>console.error(s)))(re(r,c))}function te(e){return e==="hook-context"||e==="hook-stop"}function re(e,n){return[`scip-query update available: ${e} -> ${n}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
3
+ `)}function oe(e,n){let t=$(e),o=$(n);if(!t||!o)return e!==n;for(let r=0;r<t.length;r++){let i=t[r]-o[r];if(i>0)return!0;if(i<0)return!1}return!1}function ie(e){let n=e.XDG_CACHE_HOME||p(Z(),".cache");return p(n,"scip-query")}function ae(e){let n=p(e,L);if(!K(n))return null;try{let t=JSON.parse(X(n,"utf8"));return typeof t.checkedAt=="number"&&(typeof t.latestVersion=="string"||t.latestVersion===null)?{checkedAt:t.checkedAt,latestVersion:t.latestVersion}:null}catch{return null}}async function ce(e,n,t){let o;try{o=await n()}catch{o=null}return se(e,{checkedAt:t,latestVersion:o}),o}function se(e,n){try{Q(e,{recursive:!0}),Y(p(e,L),`${JSON.stringify(n,null,2)}
4
+ `)}catch{}}async function me(){let e=await fetch(ne,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let n=await e.json();return typeof n.version=="string"?n.version:null}function $(e){let n=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}m.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(a);var pe=await R(q()?process.argv[2]:void 0);M(m,pe);m.hook("preAction",async(e,n)=>{let t=n.name(),o=_(t),r=x(t);if(!o&&!r){G(),await h({commandName:t});return}let i=V(),c=A(i),l=I(i,c);f(l),G(),await h({commandName:t});let{config:s,paths:u}=l,C;if(r&&s.watch?.enabled===!0)try{C=P(k({projectRoot:i,cacheDir:u.cacheDir,cliVersion:a,gitContext:c}))}catch{}if(o){let y=U(i,s,u,{gitContext:c,watcherGeneration:C});y.kind==="failed"&&process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${y.reason}`)}if(!r){g(i,a);return}let d=S({commandName:t,projectRoot:i,cacheDir:u.cacheDir,cliVersion:a,config:s,gitContext:c});d.kind==="failed"&&console.error(`warning: scip-query watch service did not start: ${d.message}`),(d.kind==="failed"||d.kind==="skipped")&&g(i,a)});m.hook("postAction",()=>f(void 0));function G(){if(w(),!v()||N())return;let e=null;try{e=j(n=>E(n))}catch{}b({command:D()??`scip-query ${process.argv.slice(2).join(" ")}`,toolVersion:a,projectFingerprint:e})}q()&&await m.parseAsync();function q(){if(!process.argv[1])return!1;let e=de(import.meta.url);try{return F(e)===F(process.argv[1])}catch{return e===process.argv[1]}}export{m as program,W as renderHeuristicNotice};
1530
5
  //# sourceMappingURL=cli.js.map