scip-query 0.17.0 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +19 -0
- package/dist/{chunk-ZMD4O5UP.js → chunk-2A7LUMZP.js} +2 -2
- package/dist/{chunk-VCOAUTSI.js → chunk-4H7T7FIM.js} +2 -2
- package/dist/{chunk-LC57FSPX.js → chunk-4QBRVI7D.js} +2 -2
- package/dist/chunk-4XTPZ5CR.js +9 -0
- package/dist/chunk-6AITNECC.js +928 -0
- package/dist/chunk-6JSTKSZH.js +3 -0
- package/dist/{chunk-A4KRWTXD.js → chunk-7LERNHDG.js} +2 -2
- package/dist/{chunk-75H6GOND.js → chunk-7ROLM67J.js} +2 -2
- package/dist/{chunk-EPDV3SQD.js → chunk-7VR5TNOI.js} +2 -2
- package/dist/chunk-A2GX3PYV.js +5 -0
- package/dist/{chunk-KYUYAWKA.js → chunk-APCXCRED.js} +2 -2
- package/dist/{chunk-H4SMB657.js → chunk-ATC4MEVA.js} +2 -2
- package/dist/chunk-AWYKDRYV.js +2 -0
- package/dist/{chunk-PYOZHG6A.js → chunk-AY44MGWS.js} +2 -2
- package/dist/{chunk-7MT6UM4D.js → chunk-BEGHYHOQ.js} +2 -2
- package/dist/{chunk-JJAH2VLD.js → chunk-BPMBOZAN.js} +2 -2
- package/dist/{chunk-3EBDPBBU.js → chunk-C7MBQSIC.js} +2 -2
- package/dist/{chunk-KAOWSWEX.js → chunk-CHJ3QROR.js} +2 -2
- package/dist/{chunk-VT2KFEPG.js → chunk-CVWX24IY.js} +2 -2
- package/dist/chunk-DJI446FQ.js +18 -0
- package/dist/{chunk-6G3GQWTK.js → chunk-ELLPMCWA.js} +2 -2
- package/dist/{chunk-42YU6TEB.js → chunk-FVLZB54V.js} +2 -2
- package/dist/{chunk-VPVAQRHM.js → chunk-G6DDSHMD.js} +2 -2
- package/dist/{chunk-OP5JXGDV.js → chunk-IG6X65MG.js} +2 -2
- package/dist/{chunk-KZ2LZBQT.js → chunk-IKMOYFUM.js} +2 -2
- package/dist/{chunk-Y3DG4J6A.js → chunk-IS7DZ7TB.js} +2 -2
- package/dist/{chunk-HGO3D2JD.js → chunk-J7IMQRCU.js} +2 -2
- package/dist/{chunk-J4HK7PQS.js → chunk-K4XL4HOK.js} +2 -2
- package/dist/{chunk-5ODF4JGH.js → chunk-K53GNKY3.js} +2 -2
- package/dist/{chunk-5N5ZC566.js → chunk-K65T4TJS.js} +2 -2
- package/dist/{chunk-YD7GGLGE.js → chunk-KA7RMBVU.js} +2 -2
- package/dist/{chunk-7CHIAMKS.js → chunk-KJOKTZUE.js} +2 -2
- package/dist/chunk-KSD6IWF4.js +38 -0
- package/dist/{chunk-OQRMCT2N.js → chunk-LEKXKHIQ.js} +5 -5
- package/dist/{chunk-KTZACYL6.js → chunk-LFPQFRCX.js} +2 -2
- package/dist/{chunk-Y5BOEWAE.js → chunk-LL5NQB5V.js} +2 -2
- package/dist/{chunk-MVFNACWB.js → chunk-MBVHEPHQ.js} +2 -2
- package/dist/{chunk-KO2TFDIP.js → chunk-MFIA6EIT.js} +2 -2
- package/dist/{chunk-PVXSHZLW.js → chunk-N3JH45WR.js} +2 -2
- package/dist/{chunk-QNCVN5EH.js → chunk-NJD4C5G5.js} +3 -3
- package/dist/{chunk-JUADXGUH.js → chunk-NJTIAQY7.js} +2 -2
- package/dist/{chunk-LG33DNTZ.js → chunk-NX2YAXVQ.js} +2 -2
- package/dist/{chunk-VDHEX6YO.js → chunk-O5A7BTMA.js} +2 -2
- package/dist/{chunk-JYBF5CPE.js → chunk-O7NA5FCA.js} +2 -2
- package/dist/{chunk-U3JW5AYG.js → chunk-OINSINYW.js} +2 -2
- package/dist/{chunk-JVTMRIKU.js → chunk-OQFA2SUQ.js} +2 -2
- package/dist/{chunk-DQYG5JHT.js → chunk-OQFPCIXO.js} +2 -2
- package/dist/{chunk-ABRWGVC6.js → chunk-P6FOIU7O.js} +2 -2
- package/dist/{chunk-NJBARXRO.js → chunk-PQD7P6WB.js} +2 -2
- package/dist/{chunk-OP5RO2CF.js → chunk-Q4GKL4CC.js} +2 -2
- package/dist/{chunk-TL2IXVGH.js → chunk-ROMKXEUM.js} +2 -2
- package/dist/{chunk-CYDOV3AQ.js → chunk-RUV4KHWA.js} +2 -2
- package/dist/{chunk-34RCSYMZ.js → chunk-S22ICAWV.js} +2 -2
- package/dist/chunk-SALRDXWM.js +121 -0
- package/dist/chunk-SON6DQNK.js +7 -0
- package/dist/{chunk-SREWDA7Q.js → chunk-SSGACGAD.js} +2 -2
- package/dist/{chunk-PA2MQKXD.js → chunk-SUYCF4SX.js} +2 -2
- package/dist/chunk-SXDXR5FH.js +2 -0
- package/dist/{chunk-TR7C5HOC.js → chunk-T4P27T6S.js} +2 -2
- package/dist/{chunk-BBBZB5WY.js → chunk-U4G4UYLB.js} +2 -2
- package/dist/{chunk-IK2NG76R.js → chunk-W7FNZKX5.js} +2 -2
- package/dist/chunk-WD3PAQJT.js +10 -0
- package/dist/{chunk-AQ34B63A.js → chunk-XLJORP6N.js} +2 -2
- package/dist/chunk-XTF6ELXT.js +3 -0
- package/dist/{chunk-7Z5UT44B.js → chunk-YMFHC5J2.js} +2 -2
- package/dist/{chunk-WH65EY7U.js → chunk-YYYERNQL.js} +2 -2
- package/dist/chunk-Z4MCFCGX.js +3 -0
- package/dist/cli.js +3 -1528
- package/dist/command-descriptors-7UUURHWT.js +599 -0
- package/dist/direct-navigation-CVCFER5G.js +3 -0
- package/dist/index.js +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -0
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -0
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +22 -22
- package/dist/reindex.js +36 -36
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.js +1 -1
- package/dist/watch-server.js +4 -4
- package/docs/COMMAND_REFERENCE.md +3 -0
- package/package.json +2 -1
- package/skills/scip-tla-model-system/SKILL.md +10 -8
- package/dist/chunk-2HCWAL42.js +0 -3
- package/dist/chunk-GRHA5NGF.js +0 -2
- package/dist/chunk-HV4N3UBV.js +0 -10
- package/dist/chunk-KLFCCRI7.js +0 -21
- package/dist/chunk-L7UITWFE.js +0 -120
- package/dist/chunk-QVZSWLLZ.js +0 -2
- package/dist/chunk-RSZ4KX4B.js +0 -7
- package/dist/chunk-RZEVUYMG.js +0 -2
- package/dist/chunk-TCOWAGR2.js +0 -38
- package/dist/chunk-X566NT42.js +0 -9
package/dist/cli.js
CHANGED
|
@@ -1,1530 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
|
|
4
|
-
|
|
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:e0(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 e0(e){if(!e)return null;try{VM(Jp(e),{recursive:!0});let t=new Yp(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 Xp(e,t,n){vo(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function ES(e,t={}){if(!UM(e))return null;let n;try{n=new Yp(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??JM,o=t.budgetBytes??YM,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 DS(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(!Qp.has(t)||!i.shared)return null;try{return i.shared.readFileEvidence.get(t,n,r,Zt)?.payload??null}catch(s){return Xp(i,"file_evidence read",s),null}}catch(o){return Rn(e,"file_evidence read",o),null}}function TS(e,t,n,r,i){let o=xn(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,Zt,i),Qp.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,Zt,i,Date.now())}catch(s){Xp(o,"file_evidence write",s)}}catch(s){Rn(e,"file_evidence write",s)}}function LS(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=>Qp.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){Xp(n,"file_evidence batch write",i)}}catch(r){Rn(e,"file_evidence batch write",r)}}function FS(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 NS(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 AS(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 MS([...s,...o])}catch(o){return Rn(e,"semantic_callees bulk read",o),new Map}}function _S(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 MS([...o,...i])}catch(i){return Rn(e,"semantic_references bulk read",i),new Map}}function MS(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function Zp(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 $S(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 OS(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 jS(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,QM);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 t0,relative as n0}from"path";function Ar(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Se(e){return e.replace(/\\/g,"/")}function _t(e,t){return Ar(e)===Ar(t)}function en(e,t){let n=n0(e,t);return n===""||!n.startsWith("..")&&!t0(n)}import{existsSync as tm,readFileSync as nm,readdirSync as r0,statSync as i0}from"fs";import{join as xo,relative as o0}from"path";function Ro(e){let t=s0(e)??u0(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of rm(e,i)){if(r.has(o))continue;r.add(o);let s=d0(e,o);s&&n.push(s)}return n}function s0(e){let t=xo(e,"pnpm-workspace.yaml");if(!tm(t))return null;try{return a0(nm(t,"utf8"))}catch{return null}}function a0(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=c0(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=l0(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function c0(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function l0(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function u0(e){let t=xo(e,"package.json");if(!tm(t))return null;try{let n=JSON.parse(nm(t,"utf8"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function rm(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=xo(e,t);return em(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=xo(e,r||".");return em(o)?r0(o).map(s=>xo(o,s,i)).filter(em):[]}function em(e){try{return i0(e).isDirectory()}catch{return!1}}function d0(e,t){let n=xo(t,"package.json");if(!tm(n))return null;try{let r=JSON.parse(nm(n,"utf8"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:o0(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var f0=me("indexed-paths",{clearGroups:[]}),g0=me("indexed-path-digest",{clearGroups:[]}),h0=ne("tsconfig-alias-config",{clearGroups:["whole-project"]}),y0=ne("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),b0=p0(import.meta.url),Ws;function S0(){if(Ws!==void 0)return Ws;try{Ws=b0("typescript")}catch{Ws=null}return Ws}var v0=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],x0=me("workspace-packages",{clearGroups:["whole-project"]}),bi=[".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"],_r=[".cs",".vb"],Zc=[".dart"],vi=[".php"],_n=[".clj",".cljs",".cljc"],R0=new Set(bi),im=new Set(Jc),HS=new Set($t),om=new Set(Yc),sm=new Set(Qc),WS=new Set(Xc),qS=new Set(_r),am=new Set(Zc),US=new Set(vi),VS=new Set(_n),C0=[{extensions:bi,lookup:R0},{extensions:Jc,lookup:im},{extensions:$t,lookup:HS},{extensions:Yc,lookup:om},{extensions:Qc,lookup:sm},{extensions:Xc,lookup:WS},{extensions:_r,lookup:qS},{extensions:Zc,lookup:am},{extensions:vi,lookup:US},{extensions:_n,lookup:VS}];function tr(e,t){return t.has(er(e).toLowerCase())}function w0(e){return tr(e,im)}function k0(e){return tr(e,HS)}function I0(e){return tr(e,om)}function P0(e){return tr(e,sm)}function E0(e){return tr(e,WS)}function D0(e){return tr(e,qS)}function GS(e){return er(e).toLowerCase()===".vb"}function T0(e){return tr(e,am)}function L0(e){return tr(e,US)}function F0(e){return tr(e,VS)}function cm(e){let t=er(e).toLowerCase();for(let n of C0)if(n.lookup.has(t))return n.extensions;return bi}function N0(e){return k0(e)||D0(e)||L0(e)}function Ot(e,t,n){return w0(t)?Co(e,t,n):I0(t)?nr(e,t,n):P0(t)?el(e,t,n):E0(t)?tl(e,t,n):N0(t)?ze(e,n.replace(/\\/g,"."),cm(t)):T0(t)?nl(e,t,n):F0(t)?lm(e,n):A0(e,t,n)}function A0(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return _0(e,t,n)??$0(e,n);let r=Mt(tn(e.config.projectRoot,t)),i=Ze(r,n),o=rr(e);for(let s of dm(i)){let a=Se(yi(e.config.projectRoot,s));if(o.has(a)||Si(s))return a}return Se(yi(e.config.projectRoot,i))}function _0(e,t,n){let r=q0(e,t);if(!r)return null;let i=rr(e);for(let o of M0(r,n)){let s=Ze(r.baseUrl,o);for(let a of dm(s)){let c=Se(yi(e.config.projectRoot,a));if(i.has(c)||Si(a))return c}}return null}function M0(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 $0(e,t){let n=j0(O0(e),t);if(!n)return null;let r=rr(e);for(let i of B0(n)){let o=Ze(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of dm(o)){let a=Se(yi(e.config.projectRoot,s));if(r.has(a)||Si(s))return a}}return null}function O0(e){return x0.get(e,()=>Ro(e.config.projectRoot))}function j0(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 B0(e){let t=[],n=H0(e.pkg.exports,e.subpath);if(n){let r=W0(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function H0(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return zS(e[n])}function zS(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=zS(t[n]);if(r)return r}return null}function W0(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function q0(e,t){let n=Se(Mt(t));return y0.get(e,n,()=>U0(e,n))}function U0(e,t){let n=S0();if(!n)return null;let r=Ze(e.config.projectRoot),i=Ze(r,t);for(;i===r||i.startsWith(r+m0);){for(let s of v0){let a=tn(i,s);if(!Si(a))continue;let c=h0.get(e,a,()=>V0(n,a));if(c)return c}let o=Mt(i);if(o===i)break;i=o}return null}function V0(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=rr(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 G0(i)){let s=Se(yi(e.config.projectRoot,o));if(r.has(s)||Si(o))return s}return null}function nr(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,"/")),um(e,z0(o))}function el(e,t,n){let r=Mt(tn(e.config.projectRoot,t)),i=Ze(r,n);return um(e,K0(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 um(e,i)}function ze(e,t,n){let r=rr(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=>BS(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(er(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=rr(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 J0(o)){let a=Se(yi(e.config.projectRoot,s));if(r.has(a)||Si(s))return a}return null}function lm(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=rr(e);for(let i of _n){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of _n){let o=[...r].find(s=>BS(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function G0(e){let t=er(e);return im.has(t)?[e]:[`${e}.py`,`${e}.pyi`,tn(e,"__init__.py"),tn(e,"__init__.pyi")]}function um(e,t){let n=rr(e);for(let r of t){let i=Se(yi(e.config.projectRoot,r));if(n.has(i)||Si(r))return i}return null}function z0(e){let t=er(e);return om.has(t)?[e]:[`${e}.rs`,tn(e,"mod.rs")]}function K0(e){let t=er(e);return sm.has(t)?[e]:[`${e}.rb`,tn(e,"index.rb")]}function J0(e){let t=er(e);return am.has(t)?[e]:[`${e}.dart`,e]}function dm(e){let t=er(e),n=new Set;if(t){n.add(e);for(let r of bi)n.add(e.slice(0,-t.length)+r)}else for(let r of bi)n.add(`${e}${r}`),n.add(tn(e,`index${r}`));return[...n]}function rr(e){return f0.get(e,()=>new Set(q(e,{includeIgnored:!1}).map(Se)))}function pm(e){return g0.get(e,()=>Ge([...rr(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 Y0,mkdirSync as Q0}from"fs";import{createHash as X0,randomUUID as Z0}from"crypto";import{dirname as e$}from"path";import{performance as wo}from"perf_hooks";var QS="SCIP_QUERY_PROFILE",XS="SCIP_QUERY_PROFILE_OUT",ZS="SCIP_QUERY_PROFILE_COMMAND",ev="SCIP_QUERY_PROFILE_CACHE_STATE",mm="SCIP_QUERY_PROFILE_RUN_ID",fm="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",gm="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",tv=[QS,XS,ZS,ev,mm,fm,gm],ofe=new Set(tv),KS=new Set,JS=new Map,YS=!1;function re(){let e=process.env[QS];return e==="1"||e==="true"}function t$(){return process.env[XS]}function il(){return process.env[ZS]}function n$(){return process.env[ev]}function ol(){let e=process.env[mm];if(e)return e;if(!re())return;let t=Z0();return process.env[mm]=t,t}function sl(){return process.env[fm]}function hm(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=qs(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[fm]=i,process.env[gm]=r,i}function qs(e){return X0("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function nv(){return Object.fromEntries(tv.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 Us(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=t$()){let n=r$(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:ol(),command:il(),cacheState:n$(),...n,...e},i=`${JSON.stringify(r)}
|
|
91
|
-
`;if(t)try{let o=e$(t);KS.has(o)||(Q0(o,{recursive:!0}),KS.add(o)),Y0(t,i);return}catch(o){YS||(YS=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
|
|
92
|
-
`));return}re()&&process.stderr.write(i)}function r$(e){let t=sl()??hm({command:il()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[gm],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=JS.get(o);return s||(s=qs(["profile-subsystem-v1",t,r]),JS.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function rl(e){return typeof e=="function"?e():e}var i$=[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=qs(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return D("evidence-product.file.read",()=>{let c=DS(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){TS(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){LS(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function xi(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=qs(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return D("evidence-product.project.read",()=>{let c=FS(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){NS(n,e.kind,r,i,e.serialize(o))}}}function pe(e){let t=i$.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 o$}from"fs";import{join as s$}from"path";var a$=ne("source-text",{clearGroups:["whole-project","source-file"]}),c$=ne("source-lines",{clearGroups:["whole-project","source-file"]});function _(e,t){let n=t.replace(/\\/g,"/");return a$.get(e,n,()=>{let r=s$(e.config.projectRoot,n);try{return o$(r,"utf-8")}catch(i){if(l$(i))return"";throw i}})}function l$(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 c$.get(e,n,()=>{let r=_(e,n);return r?r.split(`
|
|
93
|
-
`):[]})}var u$=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function Vs(e){let t=u$.exec(e);return t?t[1]??"":null}function cl(e,t,n){return iv(e,t,n).length>0}function rv(e,t,n,r){let i=r.toLowerCase();return iv(e,t,n).some(o=>o.toLowerCase()===i)}function iv(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=Vs(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 Jv}from"path";function J(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(e){return e.replace(/'''[\s\S]*?'''/g,Mr).replace(/"""[\s\S]*?"""/g,Mr).replace(/#.*$/gm,Mr).replace(/\/\/.*$/gm,Mr).replace(/\/\*[\s\S]*?\*\//g,Mr).replace(/`(?:\\[\s\S]|[^`])*`/g,Mr).replace(/'(?:\\.|[^'\\\r\n])*'/g,Mr).replace(/"(?:\\.|[^"\\\r\n])*"/g,Mr)}function zs(e){return sv(e,{maskStrings:!1})}function ov(e){return sv(e,{maskStrings:!0})}function sv(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+=ym(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+=ym(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?ym(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function ym(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
|
|
96
|
-
`?`
|
|
97
|
-
`:" ";return r}function Mr(e){return e.replace(/[^\r\n]/g," ")}var vfe=hi("stripped-lines",{clearGroups:["whole-project","source-file"]});Fr({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{ll=null,Gs=""},clearFile:()=>{ll=null,Gs=""}});var ll=null,Gs="";function d$(e){return ll===e||(ll=e,Gs=kt(e)),Gs}function $r(e,t,n){let r=d$(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 Ks(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}import{extname as av}from"path";var p$={".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 p$[av(e).toLowerCase()]??null}function ir(e){return av(e).toLowerCase()===".vue"}import{createRequire as m$}from"module";var yt=m$(import.meta.url),Js=null,bm=!1;function cv(){if(bm)return null;if(Js)return Js;try{return Js=yt("tree-sitter"),Js}catch{return bm=!0,null}}function ul(e){if(e==="clojure")return"reader";let t=cv();if(!t)return"unavailable";let n=lv(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return Io.add(e),"unavailable"}}var Sm=new Map,Io=new Set;function lv(e){if(Io.has(e))return null;let t=Sm.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 Sm.set(e,n),n}var vm=new Map;function uv(){Js=null,bm=!1,Sm.clear(),Io.clear(),vm.clear(),h$.clear()}function f$(e){let t=vm.get(e);if(t)return t;let n=lv(e);if(!n)return null;let r=cv();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Io.add(e),null}return vm.set(e,i),i}function g$(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Ys(e,t){let n=f$(e);if(!n)return null;try{return g$(n,t)}catch{return null}}var h$=new Map;import{posix as xm}from"path";import{parse as y$}from"@vue/compiler-sfc";var b$=Nr("vue-sfc-units");function Po(e,t){let n=mv(t),r=_(e,n);return b$.get(e,n,r,()=>Rm(e,n,r))}function mv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function S$(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Ri(e){return!e||e.body.length===0?0:e.body.split(`
|
|
98
|
-
`).length}function Rm(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=y$(n,{filename:t})}catch(s){return r.errors.push(pv(s)),r}r.errors.push(...i.errors.map(pv));let{descriptor:o}=i;return o.template&&(r.template=dl(e,t,"template",o.template)),o.script&&r.scripts.push(dv(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(dv(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 dv(e,t,n,r){let i=dl(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:S$(i.lang)}}function dl(e,t,n,r){let i=x$(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=v$(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 v$(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=mv(xm.normalize(xm.join(xm.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function x$(e){return{...e}}function pv(e){return e instanceof Error?e.message:String(e)}function pl(e,t,n){let i=Rm(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 fv=hi("ast-trees",{clearGroups:["whole-project","source-file"]});function oe(e,t){if(ir(t))return R$(e,t);let n=K(t);if(!n)return null;let r=_(e,t);return r?fv.get(e,t,r,()=>Ys(n,r)):null}function R$(e,t){let n=_(e,t);return n?fv.get(e,t,n,()=>{let r=pl(e,t,n);if(!r)return null;let i=`
|
|
102
|
-
`.repeat(r.startLine)+r.body;return Ys(r.language,i)}):null}function Eo(e,t){let n=C$(e,t);if(!n)return null;let r=Ci(n);return r?{calleeLeaf:r,memberAccess:w$(n),line:e.startPosition.row}:null}function C$(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 w$(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Ci(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?Ci(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?Ci(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Ci(t):null}case"super":case"self":case"this":return null;default:return null}}function Qs(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var k$=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function ml(e,t){let n=P$(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:yv(n.functionNode),params:gv(n.functionNode),paramsEndLine:hv(n.functionNode),isLiteralPassthrough:bv(n.functionNode,t)};if(!I$(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:yv(e),params:gv(e),paramsEndLine:hv(e),isLiteralPassthrough:bv(e,t)}:null}function Sv(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function gv(e){let t=Sv(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Qs(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 hv(e){let t=Sv(e);return t?t.endPosition.row:e.startPosition.row}function I$(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?k$.has(e):!1}function P$(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 yv(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)Qs(r)||(n+=1);return n}function bv(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=>!Qs(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=>!Qs(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 E$=new Set(["identifier","type_identifier","field_identifier"]),D$=new Set(["identifier"]),T$=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),L$=new Set(["rust","python"]),F$=/\{([^{}]*)\}/g,N$=/\b([A-Za-z_][\w]*)\b/g;function vv(e,t){return A$(t).has(e.type)}function xv(e,t){return L$.has(t)&&e.type==="string_content"}function Cm(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 A$(e){return e==="rust"?E$:e==="python"?D$:T$}function Rv(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(F$)){let i=r[1]??"";for(let o of i.matchAll(N$))o[1]&&t(o[1],n)}}var _$=[/\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],M$=/^#!?\[\s*serde\s*\(/,$$=/^#!?\[\s*schemars\s*\(/,O$=/^#!?\[\s*validate\s*\(/,j$=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Cv(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=Ci(r);if(!i||!j$.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 wv(e,t){let n=M$.test(e),r=$$.test(e),i=O$.test(e);if(!(!n&&!r&&!i))for(let o of _$){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 kv(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 B$=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),wm=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 Iv(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=Zs(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,H$(f,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(f)),a+=1;continue}if(km(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!Im(e[a]);)a+=1;let p=e.slice(d,a);if(!p)continue;let m={text:p,line:u};W$(o[o.length-1],m),c(nn(p),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:z$(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function H$(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=nn(n.text),i=B$.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(q$(e,t),!r||wm.has(n.text)||wm.has(r)||r.startsWith(":"))return;let o=G$(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function W$(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function q$(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))Xs(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))Xs(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))Xs(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&&Xs(t,r,"extension",i,"extension-method");let o=V$(e,i.startLine);o&&o!==r&&Xs(t,o,"extension",i,"extension-method")}}}function fl(e){return e.children.filter(U$)}function U$(e){if(e.kind!=="(")return!1;let t=nn(e.tokens[0]?.text??"");return!!(t&&!wm.has(t)&&!t.startsWith(":"))}function Xs(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 V$(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 G$(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 Zs(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 km(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function Im(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function z$(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 Pv=3,K$=hi("source-facts",{clearGroups:["whole-project","source-file"]}),Pm=Ie({kind:"source-facts",invalidation:pe("source-facts"),serialize:Q$,deserialize:X$});function ce(e,t){return Em(e,t).facts}function Em(e,t){let n=_(e,t);if(!n)return{facts:null};let r=J$(e,t,n);return r?K$.get(e,t,n,()=>Y$(e,t,r,n)):{facts:null}}function J$(e,t,n){return ir(t)?pl(e,t,n)?.language??null:K(t)}function Y$(e,t,n,r){let i=Ae(e,t,r),o=Pm.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=Iv(r);return Pm.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=eO(s,n);return Pm.write(e,t,i,a),{facts:a}}function Q$(e){let t={version:Pv,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 X$(e){try{let t=JSON.parse(e);if(t.version!==Pv||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:Cm(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Dm(e,t,n,r){let i=ce(e,t);return i?Z$(i,n,r)?.isLiteralPassthrough??!0:!0}function ea(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 Z$(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function eO(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),Cv(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&wv(l.text,i),vv(l,t)&&a(l.text,l.startPosition.row),xv(l,t)&&Rv(l,a);for(let p of l.children)c(p)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:kv(e,t),identifierLineMap:s,identifiersByLine:Cm(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Ev=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function Tm(e,t){let n=ce(e,t);return!n||!Ev.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Or(e,t){let n=ce(e,t);return!n||!Ev.has(n.language)?null:n.callSites}function Lm(e,t){return ce(e,t)?.typeContainerMap??new Map}import{ElementTypes as nO,NodeTypes as Fm,parse as rO}from"@vue/compiler-dom";import{parse as fge}from"@vue/compiler-sfc";var tO=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||tO.has(e)}function yl(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var iO=Nr("vue-template-facts"),oO=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),sO=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"]),aO=new Set(["div","span","template"]),cO=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 iO.get(e,n,r,()=>lO(n,Po(e,n).template))}function lO(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=rO(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Tv(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Tv(e,t,n,r){for(let i of e)if(i.type===Fm.ELEMENT)uO(i,t,n,r),Tv(i.children,t,n,r);else if(i.type===Fm.INTERPOLATION){r("interpolation");let o=Nm(i.content);o&&Lv(o,t,i.loc.start.line,n,r)}}function uO(e,t,n,r){let i=yO(e.tag),o={tag:e.tag,normalized:i,kind:hO(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),aO.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)dO(s,t,n,r)}function dO(e,t,n,r){if(e.type===Fm.ATTRIBUTE){let a=e.value?.content??null,c=Dv("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=mO(e),o=Nm(e.exp),s=Dv(pO(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&&Lv(o,t,e.loc.start.line,n,r)}function Dv(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Do(r,i),endLine:Do(r,o)}}function pO(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function mO(e){let t=Nm(e.arg);return t||e.name}function Nm(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function Lv(e,t,n,r,i){for(let o of fO(e)){let s={name:o,startLine:Do(t,n),endLine:Do(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function fO(e){let t=new Set,n=gO(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];cO.has(o)||hl(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function gO(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 hO(e){let t=e.tag;return e.tagType===nO.COMPONENT?"component":oO.has(t)?"builtin":sO.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function yO(e){return yl(e,/[-_:]/)}function Do(e,t){return e+Math.max(0,t-1)}import{readdirSync as bO}from"fs";import{execFileSync as SO}from"child_process";import{extname as Sl,join as vO}from"path";var Am=[".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"],Fv=[".vue"],Nv=[".tsx",".jsx"],Av=[".vue"],xO=[...Nv,...Av],RO=new Set(Nv),CO=new Set(Av),_v=new Set(Am.map(e=>e.toLowerCase())),wO=[..._v].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):_v,s=i?[...o].sort().join(","):wO,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return kO.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 IO(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:xO})){if(t.scope&&!i.includes(t.scope))continue;let o=Sl(i).toLowerCase();if(n||=RO.has(o),r||=CO.has(o),n&&r)break}return{react:n,vue:r}}var kO=ne("source-files",{clearGroups:[]});function IO(e,t){return PO(e,t)??DO(e,t)}function PO(e,t){try{let n=SO("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&&(EO(o)||t.has(Sl(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function EO(e){return e.split("/").some(t=>vl.has(t))}function DO(e,t){let n=new Set,r=i=>{let o=i?vO(e,i):e,s;try{s=bO(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 TO=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),LO=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),FO=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),NO=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),AO=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+=Ri(n),n.external&&(t.externalLineCount+=Ri(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(...OO(n));let r=Ys(n.astLanguage,n.body);r?MO(n,r.rootNode,t):$O(n,t)}return _O(t),t.externalScriptPaths=$v(t.externalScriptPaths),t}function _O(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 $v(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function MO(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:Mv(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function $O(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||AO.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+Rl(e.body,n.index??0),categories:Mv(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 OO(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 jO(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function jO(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 Mv(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),TO.has(e)&&t.push("reactivity"),LO.has(e)&&t.push("lifecycle"),FO.has(e)&&t.push("request"),NO.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 $v(e){return[...new Set(e)].sort()}var BO=new Set(["in","key","of"]),HO=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),WO=Nr("vue-component-behavior-profiles");function Ov(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=WO.get(e,n,r,()=>qO(e,n,r));return VO(i)}function qO(e,t,n){let r=Po(e,t),i=bl(e,t),o=Cl(r),s=KO(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=Ri(r.template),d=o.lineCount,p=r.styles.reduce((h,y)=>h+Ri(y),0),m=r.customBlocks.reduce((h,y)=>h+Ri(y),0),{lines:f,paths:g}=UO(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:zO(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 UO(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 VO(e){let t=GO(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 GO(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 zO(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(HO.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 KO(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of JO(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of jv(n.value))t.add(r);return[...t].sort()}function JO(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?jv(t[1]??""):[]}function jv(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];BO.has(r)||t.push(r)}return t}import{extname as YO}from"path";var QO=[".tsx",".jsx"],Bv=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),XO=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),ZO=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),ej=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),tj=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),nj=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),rj=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),ij=Nr("react-component-behavior-profiles"),Hv=Ie({kind:"react-component-behavior-profiles",invalidation:pe("react-component-behavior-profiles"),serialize:cj,deserialize:lj});function Vv(e,t={}){let n=Pt(e,{extensions:QO}).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=>$m(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function $m(e,t){let n=t.replace(/\\/g,"/"),r=_(e,n);return ij.get(e,n,r,()=>oj(e,n,r)).map(aj)}function oj(e,t,n){let r=Ae(e,t,n),i=Hv.read(e,t,r);if(i)return i;let o=sj(e,t);return Hv.write(e,t,r,o),o}function sj(e,t){let n=dj(t);if(!n)return[];let r=oe(e,t);if(!r)return[];let i=Qe(e,t).length;return pj(r.rootNode,n).filter(s=>s.kind==="hook"||Om(s.bodyNode)).map(s=>{let a=Sj(s.bodyNode),c=wj(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:or(a.componentNames),nativeTags:or(a.nativeTags),propNames:or(a.propNames),eventNames:or(a.eventNames),hookNames:or(c.hookNames),requestNames:or(c.requestNames),stateNames:or(c.stateNames),effectNames:or(c.effectNames),handlerNames:or(c.handlerNames)}})}function aj(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 cj(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function lj(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=uj(r);if(!i)return null;n.push(i)}return n}catch{return null}}function uj(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 dj(e){let t=YO(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:K(e)}function pj(e,t){let n=[],r=new Set,i=o=>{let s=mj(o);if(s&&(!yj(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 mj(e){if(e.type==="class_declaration"){let o=Mm(e);if(!o||!/^[A-Z]/.test(o))return null;let s=fj(e);return!s||!gj(e)&&!Om(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=Mm(e);return!o||!Wv(o)?null:{name:o,kind:qv(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=ta(t);if(!r||!n||!Wv(r))return null;let i=hj(n);return i?{name:r,kind:qv(r),node:e,bodyNode:i}:null}function fj(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 gj(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function Wv(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function qv(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function hj(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=bj(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 yj(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 Mm(e){return ta(e.childForFieldName("name")??e.namedChild(0))}function bj(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function Om(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(Om)}function Sj(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"?vj(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?xj(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function vj(e,t){let n=Rj(e),r=!1;if(n){let i=Uv(n),o=i==="Fragment"||i==="React.Fragment";r=Dj(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=Cj(i);if(!o)continue;let s=Uv(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 rj.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(Gv(i))}function xj(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(Gv(e)),zv(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of Tj(n))hl(r)||t.tokens.add(`binding:${r}`)}function Gv(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 zv(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(zv)}function Rj(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 Cj(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 wj(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&&kj(o.calleeLeaf,n)}else if(i.type==="variable_declarator")Pj(i,n);else if(i.type==="function_declaration"){let o=Mm(i);o&&Kv(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function kj(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Bv.has(e)&&!ej.has(e)&&t.tokens.add(`hook:${e}`)),Bv.has(e)&&t.tokens.add(`react-hook:${e}`),XO.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),ZO.has(e)&&t.tokens.add(`state-hook:${e}`),Ij(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function Ij(e){if(tj.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function Pj(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=>ta(a)),s=ta(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=ta(n);i&&Kv(i,t)}function Kv(e,t){let n=Ej(e);!n||!nj.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function Ej(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 Dj(e){return/^[A-Z]/.test(e)||e.includes(".")}function Uv(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function ta(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 Tj(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 or(e){return[...e].sort()}function rn(e){return{capability:(t,n)=>Lj(t,n),reactProfiles:(t={})=>Vv(e,t),reactProfilesForFile:t=>$m(e,t),vueProfiles:(t={})=>Ov(e,t),vueProfileForFile:t=>_m(e,t),vueTemplateFacts:t=>bl(e,t),vueScriptFacts:t=>Cl(Po(e,t))}}function Lj(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 wi(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 Fj=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&&Fj.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,cm(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 sr(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 ki(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Ii(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=$r(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 Yv(e,t,n){return sn(e,t,r=>Aj(e,t,r),()=>Nj(e,t,n))}function Nj(e,t,n){return on(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Jv(o).replace(/\.[^.]+$/,"");return[sr(o,s,tl(e,t,o),It(i,s))]})}function Aj(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=Jv(s).replace(/\.[^.]+$/,"");i.push(qe(s,a,tl(e,t,s),r))}return i}var _j=new Set([":require",":require-macros",":use"]),Hm=String.raw`A-Za-z0-9_$*+!?.<>=-`;function Xv(e,t,n){let r=Gj(n);if(!r)return[];let i=Vj(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(_j.has(a)){for(let c of Oj(s.children.slice(1)))o.push(...$j(e,c,i));continue}if(a===":import")for(let c of Bj(s.children.slice(1)))o.push(c)}}return o}function Mj(e){return e.type==="list"&&an(e.children[0])==="ns"}function $j(e,t,n){let r=lm(e,t.namespace),i=t.alias??t.namespace,o=Wj(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||qj(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:Uj(n,a),usedMembers:[]});return s}function Oj(e){return e.flatMap(t=>Il(t,null))}function Il(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:Bm(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)):jj(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,Bm(t,n))):e.children.flatMap(r=>Il(r,t))}return[]}function jj(e,t){let n=an(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:Bm(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(Hj)),i+=1)}return[r]}function Bj(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(sr(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(sr(`${r}.${o}`,o,null,!0))}}return t}function Bm(e,t){return e?`${e}.${t}`:t}function an(e){return e?.type==="atom"?e.text:null}function Hj(e){return!!(e&&!e.startsWith(":"))}function Wj(e,t){let n=new Set,r=new RegExp(`${Wm()}${J(t)}\\s*/\\s*([${Hm}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function qj(e,t){return new RegExp(`${Wm()}${J(t)}\\s*/`,"m").test(e)}function Uj(e,t){return new RegExp(`${Wm()}${J(t)}(?![${Hm}])`,"m").test(e)}function Wm(){return`(?<![${Hm}])`}function Vj(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+=Qv(e.slice(i,s)),i=s;continue}if(o==='"'){let s=Zs(e,i,0).index;r+=Qv(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function Gj(e){let t=0;for(;t<e.length&&(t=qm(e,t),!(t>=e.length));){let n=Pl(e,t);if(!n){t+=1;continue}if(Mj(n.form))return n.form;t=n.index}return null}function Pl(e,t){let n=qm(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return zj(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(;km(e[n]);)n+=1;let r=e[n];return r?r==="("?jm(e,n,"list",")"):r==="["?jm(e,n,"vector","]"):r==="{"?jm(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:Zs(e,n,0).index},index:Zs(e,n,0).index}:Jj(e,n):null}function zj(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"?Kj(r.form.children):[],start:t,end:r.index},index:r.index}:null}function Kj(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 jm(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=qm(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 Jj(e,t){let n=t;for(;n<e.length&&!Im(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function qm(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 Qv(e){return e.replace(/[^\r\n]/g," ")}function Zv(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=$r(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 ex(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 tx(e,t,n){return kl(e,t,{csharp:r=>Qj(e,t,r),vb:r=>Yj(e,t,r)},()=>{let r=GS(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,_r))]})})}function Yj(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,_r),r,c?"namespace":"named"))}return i}function Qj(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,_r),r,a?"namespace":"named"))}return i}var Xj=ne("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function nx(e,t){return Xj.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 Um(e,t,n){return sn(e,t,r=>eB(e,t,r),()=>Zj(e,t,n))}function Zj(e,t,n){return dB(n).flatMap(r=>pB(e,t,r.clause,r.specifier,r.start,r.end,n))}function eB(e,t,n){let r=tB(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...nB(e,t,n,o,r));return i}function tB(e,t,n){let r=Ke(n,new Set(["import_statement"]));if(ir(t))for(let i of nx(e,t))r.add(i);return r}function nB(e,t,n,r,i){let o=aB(r);if(!o)return[];let s=Ot(e,t,o),a=Bt(r,"import_clause");return a?rB(n,a,s,i,cB(r.text)):[ki("*",s)]}function rB(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(iB(s.text,n,r,i));else if(s.type==="namespace_import"){let a=oB(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...sB(s,n,r,i));return o}function iB(e,t,n,r){return qe("default",e,t,n,"default",{isTypeOnly:r})}function oB(e,t,n,r,i){let s=Bt(t,"identifier")?.text??"";if(!s)return null;let a=uB(e,s);return Ii("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function sB(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||lB(o.text)}))}return i}function aB(e){let t=Bt(e,"string");if(!t)return null;let n=Bt(t,"string_fragment");return n?n.text:null}function cB(e){return/^\s*import\s+type\b/.test(e)}function lB(e){return/^\s*type\b/.test(e.trim())}function uB(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 dB(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 pB(e,t,n,r,i,o,s){let a=Ot(e,t,r),c=$r(s,i,o);return n?mB(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=ko(c,u.localName);return Ii(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"?ki(u.importedName,u.sourcePath):sr(u.importedName,u.localName??"",u.sourcePath,u.localName?It(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[ki("*",a)]}function mB(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=fB(r),s=[];return i&&s.push(...rx(i,n)),o&&s.push(...rx(o,n)),s}function rx(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 fB(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 Vm(e,t,n){let r=oe(e,t);return r?vB(e,t,r):gB(e,t,n)}function gB(e,t,n){return[...hB(e,t,n),...yB(e,t,n),...bB(e,t,n)]}function hB(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=>SB(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 yB(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 bB(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 SB(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 vB(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=xB(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=RB(i,o,s,a);r.push(c)}return r}function xB(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 RB(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 ix(e,t,n){return kl(e,t,{java:r=>CB(e,t,r),kotlin:r=>wB(e,t,r),scala:r=>kB(e,t,r)},()=>on(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?IB(e,t,o,i):[]}))}function CB(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(Ii("*",ze(e,l,$t)));continue}let u=l.split(".").pop()??l;i.push(qe(u,u,ze(e,l,$t),r))}return i}function wB(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(Ii("*",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 kB(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(Ii("*",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 IB(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 sx(e,t,n){return sn(e,t,r=>PB(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,"."),vi))]}):[]}))}function PB(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,"."),vi),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}=ox(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}=ox(c,"");l&&o(d,l,u)}}return i}function ox(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 cx(e,t,n){return sn(e,t,r=>EB(e,t,r),()=>TB(n).flatMap(r=>FB(e,t,r,n)))}function EB(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=ax(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=DB(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=ax(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function ax(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 DB(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 TB(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=Ks(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let p=t[i];c+=`
|
|
112
|
-
${p}`,l+=1+p.length,u+=Ks(p),r+=p.length+1}let d=LB(c);d&&n.push({...d,start:a,end:l})}return n}function LB(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 FB(e,t,n,r){let i=$r(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 NB}from"path";function lx(e,t,n){return sn(e,t,r=>_B(e,t,r),()=>AB(e,t,n))}function AB(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=ux(s);return[sr(c,c,a,It(i,c))]}return[ki(s,a)]})}function _B(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=ux(d);i.push(qe(m,m,p,r))}else i.push(ki(d,p))}return i}function ux(e){return yl(NB(e).replace(/\.[^.]+$/,""),/_/)}function dx(e,t,n){return sn(e,t,r=>MB(e,t,r),()=>on(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?$B(e,t,o,i):[]}))}function MB(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 na(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=nr(e,t,a.qualifiedName)??nr(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(qe(a.importedName,a.localName,c,r))}}return i}function na(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(...na(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...na(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=na(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 $B(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,nr(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=nr(e,t,a)??nr(e,t,a.split("::").slice(0,-1).join("::"));return[Cn(e,t,r,a,a.split("::").pop()??a,c,l)]}function px(e,t,n){let r=oe(e,t);if(r)return OB(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(...BB(e,t,s))}return i}function OB(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!jB(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of na(o,""))s.importedName&&r.push(Gm(e,t,s.qualifiedName))}return r}function jB(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function BB(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[Gm(e,t,l)]})}return[Gm(e,t,r)]}function Gm(e,t,n){return{specifier:n,sourcePath:nr(e,t,n)??nr(e,t,n.split("::").slice(0,-1).join("::"))}}function jr({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function mx(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 HB={language:"javascript",extensions:bi,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Um,parseReExports:Vm},WB=jr({language:"python",extensions:Jc,imports:"ast-with-regex-fallback",parseImports:cx}),qB=jr({language:"jvm",extensions:$t,imports:"ast-dispatch-with-regex-fallback",parseImports:ix}),UB={language:"rust",extensions:Yc,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:dx,parseExports:px},VB=jr({language:"ruby",extensions:Qc,imports:"ast-with-regex-fallback",parseImports:lx}),GB=jr({language:"c/cpp",extensions:Xc,imports:"ast-with-regex-fallback",parseImports:Yv}),zB=jr({language:"dotnet",extensions:_r,imports:"ast-dispatch-with-regex-fallback",parseImports:tx}),KB={language:"dart",extensions:Zc,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Zv,parseExports:ex},JB=jr({language:"php",extensions:vi,imports:"ast-with-regex-fallback",parseImports:sx}),YB=jr({language:"clojure",extensions:_n,imports:"regex-only",parseImports:Xv}),fx=[HB,WB,qB,UB,VB,GB,zB,KB,JB,YB];function El(e){return mx(fx,e)}function gx(e){return fx.find(n=>n.language===e)?.capabilities??null}var zm={clearGroups:["whole-project","source-file"]},QB=ne("source-imports",zm),XB=ne("source-exports",zm),ZB=ne("source-reexports",zm),hx=Ie({kind:"source-imports",invalidation:pe("source-imports"),serialize:e1,deserialize:t1}),yx=Ie({kind:"source-reexports",invalidation:pe("source-reexports"),serialize:n1,deserialize:r1});function Pi(e,t){let n=Se(t);return ZB.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=pm(e),a=yx.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return yx.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function Ce(e,t){let n=Se(t);return QB.get(e,n,()=>{let r=El(n);if(!r)return[];let i=_(e,n);if(!i)return[];let o=Ae(e,n,i),s=pm(e),a=hx.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return hx.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function Dl(e,t){let n=Se(t);return XB.get(e,n,()=>{let r=El(n);if(!r?.parseExports)return[];let i=_(e,n);return i?r.parseExports(e,n,i):[]})}function e1(e){return JSON.stringify(e)}function t1(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 n1(e){return JSON.stringify(e)}function r1(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 bx=xi({kind:"file-dependency-graph",invalidation:pe("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:u1}),i1=ne("file-dep-graph",{clearGroups:["whole-project"]});function ge(e,t,n={}){let r=n.scipEdges??"all-references";return i1.get(e,`${r}:${t??""}`,()=>{let i=new Set(q(e,{includeIgnored:!1})),o=Ye(e),s=a1(t,r),a=0,c=0,l=null,u=!1,d=0,p=0;return D("file-dep-graph.product",()=>{if(o){let h=bx.read(e,s,o);if(h){u=!0;let y=l1(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=o1(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)=>f1(e,f,i,h,y);D("file-dep-graph.scip-edges",()=>{for(let h of m1(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&&bx.write(e,s,o,{sourceImportFingerprint:m.fingerprint,sourceFileCount:m.files.length,sourceEdgeCount:m.edges.length,scipEdgeCount:d,graph:c1(f)}),f},()=>({scope:t??null,available:o!==null,hit:u,files:a,sourceEdges:c,scipEdges:d,graphFiles:p,sourceImportFingerprint:l}))})}function o1(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:s1(r,i)}}function s1(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return Ge(JSON.stringify({files:e,edges:n}))}function a1(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function c1(e){return[...e].map(([t,n])=>[t,[...n]])}function l1(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function u1(e){let t=JSON.parse(e);return d1(t)?t:null}function d1(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(p1)}function p1(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function m1(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 f1(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 Sx(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,Sx(e,i,n));return r}}}function Sx(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=Pi(e,t)),i){let o=Em(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 g1={"/":"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=h1(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Mn(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 h1(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||vx(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&&!vx(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=g1[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function vx(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=y1(i);o&&r.push(o)}return r.join(":")}function y1(e){let t=e.suffix==="namespace"?b1(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function b1(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 Br(e){return $e(e)==="namespace"}var S1=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function et(e){return S1.test(e)}var v1=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&&v1.has(r.name))return!0}return!1}function xx(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 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)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 x1,readdirSync as wx}from"fs";import{join as ra}from"path";var R1={files:new Set,pathPrefixes:[]},Km=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,C1=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,kx=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],w1=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),k1=4,I1=me("package-surface",{clearGroups:["whole-project"]});function P1(e){return I1.get(e,()=>E1(e.config.projectRoot))}function Ei(e,t){let n=P1(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function E1(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of D1(e))for(let o of T1(r))L1(e,i,o,t,n);return t.size===0&&n.length===0?R1:{files:t,pathPrefixes:n}}function D1(e){let t=[],n=Px(e,"");return n&&t.push({manifest:n,packageRoot:""}),Ix(e,"",t,0),t}function Ix(e,t,n,r){if(r>=k1)return;let i=ra(e,t);if(Tl(i))for(let o of wx(i,{withFileTypes:!0})){if(!o.isDirectory()||w1.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=Px(e,s);a&&n.push({manifest:a,packageRoot:s}),Ix(e,s,n,r+1)}}function Px(e,t){try{let n=x1(ra(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function T1(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 Ex(e.exports,t),t}function Ex(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Ex(n,t)}function L1(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 Cx(c))l!==""&&i.push(ar(t,l));return}let a=o.replace(C1,"");for(let c of Cx(a)){c===a&&c===o&&r.add(ar(t,o));for(let l of kx)F1(e,r,t,c+l)}r.add(ar(t,o))}function Cx(e){let t=[e];return Km.test(e)&&(t.push(e.replace(Km,"src/")),t.push(e.replace(Km,""))),t}function F1(e,t,n,r){let i=ar(n,r);if(t.add(i),!r.startsWith("src/")||Tl(ra(e,i)))return;let o=kx.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);N1(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 Dx(e,n,c,`${l}${o}`))t.add(u)}function N1(e,t,n,r,i){let o=ar(n,`${r}/index${i}`);Tl(ra(e,o))&&t.add(o)}function Dx(e,t,n,r){let i=ra(e,t,n);if(!Tl(i))return[];let o=[];for(let s of wx(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Dx(e,t,a,r)):s.isFile()&&s.name===r&&o.push(ar(t,a))}return o}function ar(e,t){return e?`${e}/${t}`:t}import{existsSync as _l,readFileSync as lH,readdirSync as uH}from"fs";import{dirname as dH,join as Ml}from"path";function Di(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
|
-
${Lx(t.orderBy)}
|
|
137
|
-
${Fx(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
|
-
${Lx(t.orderBy)}
|
|
157
|
-
${Fx(t.limit)}`,...t.params??[])}function Lx(e){return e?`ORDER BY ${e}`:""}function Fx(e){return typeof e=="number"?`LIMIT ${e}`:""}function cr(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 lr(e){if(!e)return null;let t=Tx(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(Tx(r)??r).replace(/\n/g," ")}function Tx(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function A1(e,t={}){if(Mn(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 Hr(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!A1(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 _1=ne("file-definitions",{clearGroups:["definition-catalog"]}),M1=ne("file-function-like-definitions",{clearGroups:["definition-catalog"]}),Nx=new WeakMap;function se(e,t,n={}){return n.includeClassMemberFallbacks?Jm(e,t,void 0,{includeClassMemberFallbacks:!0}):_1.get(e,t,()=>{let r=$x(e,t);if(r)return r;let i=Jm(e,t),o=Ye(e),s=cn(e).forFile(t,{text:!0}).text;return o&&s&&Mx.write(e,t,Ae(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function $1(e,t){return M1.get(e,t,()=>{let n=$x(e,t);return n?n.filter(r=>r.isFunctionLike):Jm(e,t,r=>r.isFunctionLike)})}var Mx=Ie({kind:"file-definitions",invalidation:pe("file-definitions"),serialize:O1,deserialize:j1});function $x(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=Mx.read(e,t,Ae(e,t,r));return i?B1(i,n,t):null}function O1(e){return JSON.stringify(e)}function j1(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 B1(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=H1(i,n);if(!o)return null;r.push(o)}return r}function H1(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 Jm(e,t,n,r={}){let i=Hr(W1(e,t),q1(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(Ox);return n&&(i=i.filter(n)),Hx(e,t,i)}function W1(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 q1(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 Ox(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:Mn(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 Ym(e,t.scope)}function Ym(e,t){return q(e,{scope:t,includeIgnored:!1}).flatMap(n=>se(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function jx(e,t){return q(e,{scope:t,includeIgnored:!1}).flatMap(n=>$1(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function ia(e,t){let n=Ax(U1(e,t.scope,t.sqlPrefilter)),r=Ax(V1(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=Hr(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...Hx(e,s,a.map(Ox)))}return o}function U1(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${Bx("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 V1(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${Bx("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 G1(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function Bx(e,t){return t==="callable"?G1(e):z1(e)}function z1(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function Ax(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:cr(lr(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Qm(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 $n(e,t){let n=Nx.get(e);return n||(n=Qm(e),Nx.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 Hx(e,t,n){let r=cn(e).forFile(t,{text:!0}).text,i=Tm(e,t);return i?Z1(n,i,r):r?K1(n,r):n}function K1(e,t){let n=t.split(/\r?\n/),r=J1(e,n),i=Y1(e,r),o=Q1(i,n);return X1(e,o)}function J1(e,t){let n=e.some(i=>Nl(i.symbol))?sH(t):null,r=new Map;for(let i of e)r.set(i.symbolId,oH(t,n,i));return r}function Y1(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 Q1(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:aH(t,i.definition,i.startLine,s)})}return n}function X1(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function Z1(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(!iH(i)||!i.leaf)return _x(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return _x(i,n);let s=n?eH(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 eH(e,t,n){let r=tH(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=nH(i,s.startLine);if(a&&o.test(a))return s}return null}function tH(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function nH(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return rH(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function rH(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 iH(e){return Nl(e.symbol)?!0:$e(e.symbol)==="term"&&Mn(e.symbol)===null}function _x(e,t){if(!t||!e.leaf||$e(e.symbol)!=="term"||Mn(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 oH(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 sH(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 aH(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=cH(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 cH(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 pH={rootFiles:new Set,sourcePrefixes:[]},mH=new Set([".git",".scipquery","node_modules","target"]),fH=6,gH=me("rust-library-surface",{clearGroups:["whole-project"]});function Wx(e,t,n){if(!n.endsWith(".rs")||!bH(hH(e),n))return!1;let r=se(e,n).find(i=>i.symbol===t);return r?SH(Qe(e,n)[r.startLine]??""):!1}function hH(e){return gH.get(e,()=>yH(e.config.projectRoot))}function yH(e){let t=new Set,n=new Set;for(let r of vH(e)){let i=Ml(e,r,"Cargo.toml"),o=lH(i,"utf8"),s=xH(o),a=ar(r,"src/lib.rs"),c=s?ar(r,s):!RH(o)&&_l(Ml(e,a))?a:null;if(!c)continue;t.add(c);let l=dH(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?pH:{rootFiles:t,sourcePrefixes:[...n].sort()}}function bH(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:CH(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function SH(e){return/^\s*pub\s+(?!\()/.test(e)}function vH(e){if(!_l(e))return[];let t=[];return qx(e,"",t,0),t}function qx(e,t,n,r){let i=Ml(e,t);if(_l(i)&&(_l(Ml(i,"Cargo.toml"))&&n.push(t),!(r>=fH)))for(let o of uH(i,{withFileTypes:!0})){if(!o.isDirectory()||mH.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;qx(e,s,n,r+1)}}function xH(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 RH(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 CH(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function fe(e){let t=Se(e);return BH(t)?"test":HH(t)?"worker":WH(t)?"entry":qH(t)?"barrel":"source"}function _o(e){return fe(e)==="barrel"}function Vx(e){return wH.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 wH=me("live-barrels",{clearGroups:["whole-project"]});function Xm(e,t){return Vx(e).has(Se(t))}function Gx(e){let t=Vx(e);return q(e,{includeIgnored:!1}).filter(n=>_o(n)&&!t.has(n)&&!kH(e,n))}function kH(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"||$H(n)||Xm(e,n)}function Oe(e,t,n){let r=Se(n);if(Ei(e,r)||PH(e,t,r)||Wx(e,t,r)||MH(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=>UH(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var IH=me("package-surface-reachability",{clearGroups:["whole-project"]});function PH(e,t,n){let r=EH(e).get(n);return r===void 0?!1:r===null||r.has(M(t))}function EH(e){return IH.get(e,()=>{let t=new Map,n=[];for(let r of q(e,{includeIgnored:!1}))Ei(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 Pi(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=DH(i,o);s!==void 0&&TH(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function DH(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 TH(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 zx=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),LH=new Set(["default","generateMetadata","generateStaticParams"]),FH=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),NH=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),AH=new Set(["load","actions","entries",...zx]),_H=new Set(["default"]);function MH(e,t){let n=M(e);return n===""?!1:Kx(t)?zx.has(n):Jx(t)?LH.has(n):Yx(t)?FH.has(n):Qx(t)?NH.has(n):Xx(t)?AH.has(n):jH(t)?_H.has(n):!1}function $H(e){return Kx(e)||Jx(e)||Yx(e)||OH(e)||Qx(e)||Xx(e)}function Kx(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Jx(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Yx(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function OH(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 Qx(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Xx(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function jH(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function BH(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 HH(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function WH(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 qH(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 UH(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(Ux(r)+"/")&&e.includes(Ux(i)+".")}function Ux(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?[]:(ur(e,t).get(n)??[]).filter(s=>!VH(s,r)):[]}function VH(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var GH=ne("file-identifiers",{clearGroups:["whole-project","source-file"]});function Zx(e,t){let n=ce(e,t);return n?n.fileIdentifiers:GH.get(e,t,()=>new Set(ur(e,t).keys()))}var zH=ne("file-ident-lines",{clearGroups:["whole-project","source-file"]});function ur(e,t){let n=ce(e,t);return n?n.identifierLineMap:zH.get(e,t,()=>JH(e,t))}var KH=ne("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function eR(e,t){let n=ce(e,t);return n?n.identifiersByLine:KH.get(e,t,()=>{let r=ur(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 JH(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=nR(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return oa(e,n);let r=nW(e,t);if(r&&!e.isIgnored(r.relative_path))return oa(e,[r]);let i=YH(e,t);return i.length>0?oa(e,i):eW(e,t)}function YH(e,t){let n=jl(t),r=Zm(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return QH(e,i,o,n)}function QH(e,t,n,r){let i=Hr([],[...XH(e,t,n),...ZH(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 XH(e,t,n){return Di(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function ZH(e,t,n){return Ao(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function eW(e,t){let n=jl(t),r=cW(t),i=sW(e,r),o=lW(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return oa(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=aW(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)),oa(e,s.map(a=>a.row))}function oa(e,t){let n=t.map(i=>Fl(e,i)),r=n[0]??null;return{match:r,candidates:r?tW(n,r):[],total:n.length}}function tW(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 nW(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 rW(e,r,s,a)??iW(e,r,s,a)}function rW(e,t,n,r){return Di(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 iW(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 sa(e,t){let n=nR(e,t).find(r=>!e.isIgnored(r.relative_path));return n?Fl(e,n):null}function nR(e,t){let n=Di(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 Hr(n,r)}function Ol(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=oW(e,t.symbolId)[0];return n?Fl(e,n):null}function oW(e,t){let n=Di(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 Hr(n,r)}function sW(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=Di(e,{where:i,params:r,limit:200}),s=Ao(e,{where:i,params:r,limit:200});return Hr(o,s)}function aW(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=Zm(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&&Br(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Zm(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 cW(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 lW(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=Zm(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)?Mn(e.symbol)===null?5:4:Mn(e.symbol)===null?3:2:0}function ef(e,t,n=5){let r=tR(t);if(!r)return[];let i=Di(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=>uW(tR(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 tR(e){return jl(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function uW(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 rR(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 iR(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 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
|
|
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=sR(e);return n?t.filter(r=>sR(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 sR(e){let t=K(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var dW=me("global-leaf-index",{clearGroups:["whole-project"]});function dr(e){return dW.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 aR=/[A-Za-z_$][A-Za-z0-9_$]*/g,cR=/^[A-Za-z_$][A-Za-z0-9_$]*$/,pW=512;function aa(e){let t=[],n=!1;for(let r of e)r&&(n=!0,cR.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function ql(e,t){let n=mW(t)?t:aa(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=pW){for(let i of n.candidateNames)if(i){if(cR.test(i)){if(fW(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}aR.lastIndex=0;let r;for(;(r=aR.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 mW(e){return"candidateNames"in e}function fW(e){return new RegExp(`(?<![A-Za-z_$0-9])${J(e)}(?![A-Za-z_$0-9])`)}function lR(e){let t=new Map,n=hW(e),r=new Map;return i=>{let o=gW(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=yW(se(e,i.file)),t.set(i.file,a));let c=bW(a,i);return r.set(o,c),c}}function gW(e){return`${e.file}\0${e.symbol}\0${e.line}`}function hW(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function yW(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 bW(e,t){if(e.definitions.length===0)return t.symbol;let n=xW(t.symbol),r=SW(e.byLeaf,n),i=vW(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 SW(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 vW(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 xW(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function uR(e,t){let r=Ce(e,t).map(i=>CW(t,i));return{usage:r,positions:wW(e,t,r)}}function dR(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?RW(r.usage,i.sourcePaths):r.usage}}}function RW(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function CW(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 wW(e,t,n){let r=oe(e,t);if(!r)return[];let i=kW(r.rootNode),o=new Map;for(let a of i){let c=o.get(nf(a.importedName,a.localName));c?c.push(a.position):o.set(nf(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(nf(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function kW(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:tf(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:tf(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:tf(n??e,r)}]}default:return[]}}function tf(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+IW(t)}}function IW(e){return Math.max(0,Math.min(e.length-1,1))}function nf(e,t){return`${e}\0${t}`}import{spawnSync as xf}from"child_process";import{existsSync as Rf}from"fs";import{fileURLToPath as zq}from"url";function Wr(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{existsSync as pR,readdirSync as PW}from"fs";import{isAbsolute as EW,join as rf,resolve as DW}from"path";var TW={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",EW(r)?r:DW(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",mR(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",mR(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=rf(e,"vendor","bin","scip-php"),r=rf(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",pR(r)?r:pR(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function pr(e){return TW[e]}function mR(e,t){let n;try{n=PW(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return rf(e,i);return null}import{execFileSync as sf}from"child_process";import{existsSync as of,readFileSync as AW}from"fs";import{createRequire as _W}from"module";import{platform as MW}from"os";import{dirname as fR,join as Vl}from"path";import{execFileSync as LW}from"child_process";import{platform as FW}from"os";var NW=FW()==="win32";function On(e){let t=NW?"where":"which";try{return LW(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var $W=_W(import.meta.url);function af(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Gl(e){let t=af(e);return t.length===1?t[0]:t.join(" or ")}function Oo(e){for(let t of af(e))if(On(t))return t;return jW(e)}function gR(e){return Oo(e)!==null||OW(e)}function OW(e){return hR(e)!==null}function jW(e){let t=hR(e);if(!t)return null;let r=JSON.parse(AW(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Vl(fR(t),r);for(let i of af(e)){let o=r[i];if(o)return Vl(fR(t),o)}return null}function hR(e){if(!e.bundledNpmPackage)return null;try{return $W.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function cf(e,t){for(let n of e.projectLocalBinaries??[]){let r=Vl(t,n);if(of(r))return r}return null}function BW(e,t){return cf(e,t)??Oo(e)}function yR(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||lf(n,t))return t;let r=bR(n,t);return r?{...t,DOTNET_ROOT:r}:t}function jo(e,t){let n=Gl(e),r=t?BW(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=HW(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(On(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{sf(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 HW(e){if(lf(e,process.env))return{runnable:!0};let t=bR(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=SR(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 bR(e,t){for(let n of SR(t))if(lf(e,{...t,DOTNET_ROOT:n}))return n;return null}function SR(e){let t=[],n=e.DOTNET_ROOT;if(n&&of(n)&&t.push(n),MW()==="darwin"&&On("brew"))try{let r=sf("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Vl(r,"libexec");of(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function lf(e,t){try{return sf(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}function Bo(e){let t=jo(pr("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 Fq,mkdtempSync as VR,readFileSync as GR,rmSync as gf}from"fs";import{tmpdir as bf}from"os";import{join as hf}from"path";import{fileURLToPath as pa,pathToFileURL as Nq}from"url";import{SHARE_ENV as Aq,Worker as _q}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 qr(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 Ti(e,t,n){let r=Wr(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 Sq}from"child_process";import{createHash as vq,randomUUID as xq}from"crypto";import{existsSync as OR,mkdirSync as NR,readFileSync as Xl,realpathSync as Rq,rmSync as mf}from"fs";import{tmpdir as Cq}from"os";import{resolve as jn}from"path";import{mkdirSync as WW,renameSync as qW,writeFileSync as UW}from"fs";import{dirname as VW}from"path";function he(e,t,n={}){WW(VW(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`,i=JSON.stringify(t,null,n.spacing);UW(r,n.trailingNewline?`${i}
|
|
289
|
-
`:i),qW(r,e)}import{execFileSync as eq}from"child_process";import{existsSync as GW,readFileSync as zW}from"fs";import{deserializeSCIP as KW,SymbolRole as JW}from"@c4312/scip";import{existsSync as LSe,readFileSync as FSe}from"fs";import{relative as ASe,resolve as _Se,sep as MSe}from"path";import{fileURLToPath as OSe,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 uf=new WeakMap,YW="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function vR(e,t){let n=new Map,r=Jl(),i=t.filter(s=>CR(s,r));if(i.length===0)return n;let o=wR(e);if(!o)return n;for(let s of i){let a=RR(o,s);a!==null&&n.set(s.symbolId,a)}return n}function xR(e,t){if(!CR(t,Jl()))return null;let n=wR(e);return n?RR(n,t):null}function RR(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function CR(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:!QW(r)}function QW(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function wR(e){if(uf.has(e))return uf.get(e)??null;let t=XW(e);return uf.set(e,t),t}function XW(e){if(!GW(e.config.indexPath))return null;try{let t=KW(zW(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&JW.Definition)!==0)continue;let s=ZW(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 ZW(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[YW]==="all"?"all":"safe"}var kR=new Map;function df(e){let n=Bo(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?tq(e,n):"unavailable"}}function Li(e){return{...df(e),scipOccurrenceReferenceMode:Jl()}}function tq(e,t){let n=`${e}\0${t}`,r=kR.get(n);if(r)return r;let i;try{i=eq(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return kR.set(n,i),i}import{createHash as hq}from"crypto";import{execFileSync as nq}from"child_process";import{createHash as IR}from"crypto";import{lstatSync as rq,readdirSync as iq,readFileSync as oq,readlinkSync as sq,realpathSync as PR}from"fs";import{isAbsolute as aq,join as ER,relative as cq,sep as lq}from"path";function Ho(e,t){let n=e.split("/").at(-1)??e;if(TR.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=>(LR[i]??[]).includes(r))?"source":"other"}function pf(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function uq(e){return(mq(e)??fq(e)).filter(t=>t&&!DR(t)).sort()}function Fi(e,t={}){let n=uq(e).filter(i=>!t.language||pq(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=PR(e);return n.map(i=>{let o=ER(e,i);try{if(rq(o).isSymbolicLink()){let a=PR(o),c=cq(r,a);if(c===".."||c.startsWith(`..${lq}`)||aq(c))throw new Error("external symlink");let l=sq(o);return{path:i,size:Buffer.byteLength(l),hash:IR("sha256").update("symlink\0").update(l).digest("hex")}}let s=oq(o);return{path:i,size:s.byteLength,hash:IR("sha256").update(s).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function Ni(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:pf(n.typescriptProjects),clojureConfigPath:dq(n.clojureConfigPath),files:Fi(e)}}function dq(e){return e?.trim()||void 0}function pq(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||TR.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(LR[t]??[]).includes(i)}function mq(e){try{return nq("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 fq(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?ER(e,r):e,o;try{o=iq(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){DR(a)||n.push(a);continue}t.push(a)}}return t}function DR(e){let t=e.split("/");return e==="meta.json"||t.some(n=>gq.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var gq=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),TR=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"]),LR={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 yq=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function FR(e){let t=Fi(e,{includePath:bq});return hq("sha256").update(JSON.stringify(t)).digest("hex")}function bq(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||yq.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}var jR=2,wq=5e3,kq=5e3,BR=10,Iq=3e4;function AR(e,t,n,r=UR){let i=r.engineIdentity(e),o={protocolVersion:jR,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:HR(r.environment())};return{key:Ql(Yl(o)),...o}}function ca(e,t,n){return e.protocolVersion===jR&&(t-e.heartbeatAtMs<=wq||e.busyUntilMs!==void 0&&t<=e.busyUntilMs)&&n(e.pid)}function ff(e,t,n){let r;try{r=Ql(Xl(t))}catch{r="missing"}let i=Ql(Yl({projectRoot:jn(e),serverPath:jn(t),serverFingerprint:r})).slice(0,20);return jn(n,`scip-query-rust-session-${i}`)}function _R(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function HR(e){return Object.fromEntries(Object.entries(e).filter(([t])=>qR(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function WR(e,t){let n=t.runtime??Lq,r=t.identityRuntime??UR,i=ff(e,t.serverPath,t.tempRoot??Cq()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return Eq(i,t.serverPath,t.semanticWorkerPath,a,c,n)};return{requestSemantic(a,c){let l=AR(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"semantic",identityKey:l.key,workerEnvironment:$R(),request:{...a,readinessDeadlineMs:u,referenceRetryTimeoutMs:Pq(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:_R(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=AR(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:$R(),request:{...a,readinessDeadlineMs:u,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:_R(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function Pq(e,t){return t!==void 0?t:e===void 0?Iq:void 0}function Eq(e,t,n,r,i,o){let s=o.randomId(),a=o.now(),c=jn(e,"requests"),l=jn(e,"responses"),u=jn(c,`${s}.json`),d=jn(l,`${s}.json`);NR(c,{recursive:!0}),NR(l,{recursive:!0}),he(u,{id:s,request:r});let p=o.now()+i;try{for(MR(e,t,n,p,o);o.now()<=p;){if(OR(d)){let f=Dq(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=la(e);(!m||!ca(m,o.now(),o.isProcessAlive))&&MR(e,t,n,p,o),o.sleep(BR)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}finally{mf(u,{force:!0}),mf(d,{force:!0})}}function MR(e,t,n,r,i){let o=la(e);if(o&&ca(o,i.now(),i.isProcessAlive))return;mf(jn(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=Math.min(r,i.now()+kq);for(;i.now()<=s;){let a=la(e);if(a&&ca(a,i.now(),i.isProcessAlive))return;i.sleep(BR)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function la(e){try{let t=JSON.parse(Xl(jn(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 Dq(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 $R(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>Tq(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function qR(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Tq(e){return qR(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 UR={canonicalProjectRoot(e){try{return Rq(e)}catch{return jn(e)}},projectFingerprint(e){return FR(e)},engineIdentity:df,fileFingerprint(e){return Ql(Xl(e))},environment(){return HR(process.env)}},Lq={now:Date.now,randomId:xq,isProcessAlive:xe,spawnServer(e,t,n){if(!OR(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);Sq(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 vq("sha256").update(e).digest("hex")}var zR=15e3,KR=8,YR=5e3,Mq=64,$q=96,Sf=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??Bq(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:ua(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:qr(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:ua(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:da(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,callees:yf(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:da(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:ua(t),callees:da(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:qr(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:yf(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:JR(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:Vq(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:JR(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,zR),o=eu(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Zl(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,KR),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=ma(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=Gq(p);return D("rust.semantic.session.request",()=>this.requester.requestSemantic(p,Ti(m,vf(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:ua(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:da(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:qr(n,o.references),callees:yf(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:ua(n),callees:da(r)}}requestImportDefinitions(t,n,r){let i=Zl(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,zR),o=Zl(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,KR),s=eu(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=eu(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,YR),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,Ti(r.length,i,o)),()=>({file:n,positions:r.length}))}};function QR(e,t,n={}){return new Sf(e,t,n)}function ma(e,t){let n=tC(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=Mq||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=$q?0:YR}function XR(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 Oq(e){return XR(e).transport}function tu(e,t){let n=XR(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=pa(eC()),i=ff(e,r,bf()),o=la(i);return o?{...n,state:ca(o,Date.now(),xe)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function jq(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=Uq(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 Bq(e,t,n={worker:()=>Hq(),durable:()=>WR(e,{serverPath:pa(eC()),semanticWorkerPath:pa(ZR())})}){return Oq(t)==="durable"?jq(n.durable(),n.worker):n.worker()}function Hq(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(gf(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?Nq(e.semanticWorkerPath):ZR();if(!Fq(pa(l)))throw new Error(`Rust semantic session worker was not found at ${pa(l)}. Run npm run build before using built semantic Rust queries.`);return n=VR(hf(bf(),"scip-query-rust-session-")),t=new _q(l,e.shareEnvironment?{env:Aq}:void 0),t.unref(),t},c=()=>{let l=n??VR(hf(bf(),"scip-query-rust-session-"));return n=l,hf(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=Wq(GR(p,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{gf(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=qq(GR(p,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{gf(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 Wq(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 qq(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 Uq(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 ua(e){return new Map(e.map(t=>[t.symbolId,[]]))}function da(e){return new Map(e.map(t=>[t.symbolId,[]]))}function JR(e){return new Map(e.map(t=>[t.symbolId,null]))}function yf(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function Vq(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Gq(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 vf(e,t){return t&&t>0?Math.max(e,t):e}function ZR(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function eC(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Zl(e,t){return Wr(e)??t}function eu(e,t){return tC(e)??t}function tC(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Cf=15e3,wf=8;function oC(e,t={}){let n=t.status??Bo,r=Yq(e,n),i=Qq(e,n),o=Xq(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!Kq(t)?null:QR(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??dR(t.sourceImportUsageResolver??Jq(),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=fa(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):qr(k,T.references)}catch(T){return y={...x(),available:!1,reason:T instanceof Error?T.message:String(T)},Ai(k)}},v=C=>{if(C.length===0)return new Map;let k=fa(C),T=k.filter(nC);if(T.length===0)return _i(k);let F=new Map,V=iC(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)??[]):rC(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=fa(C),F=fa(k),V=F.filter(nC),ie=new Map,W=iC(V,m),be=[];for(let Z of V)W.has(Z.symbolId)?ie.set(Z.symbolId,W.get(Z.symbolId)??[]):rC(Z,p)?ie.set(Z.symbolId,[]):be.push(Z);if(T.length===0&&be.length===0)return{references:Ai(T),callees:Wo(F,ie,void 0)};try{let Z=s?s.referencesAndCalleesForDefinitions(T,be):nU(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):qr(T,Z.references);for(let[Hs,At]of Z.callees)ie.set(Hs,At);let gi=Wo(F,ie,d);for(let[Hs,At]of gi)g.set(Hs,At);return{references:ht,callees:gi}}catch(Z){return y={...x(),available:!1,reason:Z instanceof Error?Z.message:String(Z)},{references:Ai(T),callees:_i(F)}}},I=C=>{if(C.length===0)return new Map;let k=fa(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},sC(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 Kq(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function Jq(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function fa(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 nC(e){return e.isFunctionLike}function rC(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function iC(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function Yq(e,t){return{referencesForDefinitions:n=>Zq(e,t,n)}}function Qq(e,t){return{calleesForDefinitions:n=>eU(e,t,n)}}function Xq(e,t){return{signaturesForDefinitions:n=>tU(e,t,n)}}function Zq(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Ai(n)};let i=kf();if(!Rf(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:Ai(n)};let o=qo(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Cf),s=ru(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,wf),c=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=ma(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=xf(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ti(n.length,vf(o,u.referenceRetryTimeoutMs),a)}),p=If(d.stdout);if(p)return{available:p.available,resolvedBinary:r.resolvedBinary,reason:p.reason,references:qr(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:Ai(n)}}function eU(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=kf();if(!Rf(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,Cf),s=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,wf),a=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=ma(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=xf(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ti(n.length,o,s)}),d=If(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 tU(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=kf();if(!Rf(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,Cf),s=qo(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,wf),a=ru(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=ma(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=xf(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ti(n.length,o,s)}),d=If(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:sC(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 nU(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Ai(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 Ai(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 sC(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function kf(){return zq(new URL("./rust-semantic-worker.js",import.meta.url))}function If(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 Wr(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 rU,readFileSync as iU}from"fs";import{deserializeSCIP as oU,SymbolRole as sU}from"@c4312/scip";var Pf=new WeakMap;function cC(e,t){let n=t.filter(aU);if(n.length===0)return new Map;let r=!1,i=0,o=0;return D("rust.scip-occurrence.callees",()=>{let s=uU(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=cU(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 aU(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||et(e.symbol))}function cU(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)||!lU(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 lU(e,t){let n=aC(e),r=aC(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function aC(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 uU(e){if(Pf.has(e))return Pf.get(e)??null;let t=dU(e);return Pf.set(e,t),t}function dU(e){if(!rU(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=oU(iU(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&sU.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=pU(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 pU(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as lV}from"crypto";import{existsSync as uV,mkdirSync as jC,readFileSync as dV,rmSync as BC}from"fs";import{dirname as pV,resolve as Yf}from"path";import{spawn as mU}from"child_process";import{closeSync as fU,existsSync as gU,mkdirSync as hU,openSync as yU,readFileSync as Ff,rmSync as ga,writeFileSync as bU}from"fs";import{dirname as SU,join as Ef,resolve as ba}from"path";import{fileURLToPath as vU}from"url";var xU=3,Sa=5e3,Nf="watch.lock",RU="watch-state.json",CU="watch-activity.json",lC=5e3,wU=2e3,pC=10,kU=new Set(["bench","config-validate","hook-context","hook-stop","init","reindex","setup","setup-agent","setup-ci","setup-hooks","uninstall","watch","work-audit"]);function Af(e,t=process.env){return t.SCIP_QUERY_SKIP_WATCH_SERVICE!=="1"&&!e.startsWith("__")&&!kU.has(e)}function su(e){let t=e.env??process.env;if(t.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return{kind:"skipped",reason:"environment"};if(!Af(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 mr(e){return{lockPath:Ef(e,Nf),statePath:Ef(e,RU),activityPath:Ef(e,CU)}}function $i(e){let t=e.runtime??_f,n=mr(e.cacheDir),r=Oi(n.statePath),i=ha(n.lockPath);return{classification:EU(r,{projectRoot:ba(e.projectRoot),cliVersion:e.cliVersion},t.now(),t.isProcessAlive),lock:i,lockIsLive:i!==null&&t.isProcessAlive(i.pid),paths:n}}function va(e){let t=e.runtime??_f,n=$i(e),r=Tf("ensure",n.classification);if(r.kind==="reuse")return ou(n.paths.activityPath,t.now()),{disposition:"reused",state:r.state};if(r.kind==="replace")Lf(r.state.pid,e,t),ya(n.paths,r.state.pid,t);else if(r.kind==="start"){if(n.lockIsLive){let s=uC(e,t,Math.min(e.startupTimeoutMs??1e3,1e3));if(s)return ou(n.paths.activityPath,t.now()),{disposition:"reused",state:s};throw new Error(`scip-query watch is already running for ${ba(e.projectRoot)} (pid ${n.lock?.pid}; lock: ${n.paths.lockPath}) without compatible daemon state. Stop the foreground watcher before starting the service.`)}n.classification.kind==="stale"&&ya(n.paths,n.classification.state.pid,t)}else throw new Error(`Unexpected ensure action: ${r.kind}`);if(n=$i(e),r=Tf("ensure",n.classification),r.kind==="reuse")return ou(n.paths.activityPath,t.now()),{disposition:"reused",state:r.state};let i=e.serverPath??vU(new URL("./watch-server.js",import.meta.url));t.spawnServer(i,ba(e.projectRoot),e.cliVersion,e.watchOverrides??{});let o=uC(e,t,e.startupTimeoutMs??lC);if(!o)throw new Error(`scip-query watch service did not become ready within ${e.startupTimeoutMs??lC}ms.`);return ou(n.paths.activityPath,t.now()),{disposition:"started",state:o}}function au(e){let t=e.runtime??_f,n=$i(e),r=Tf("stop",n.classification);return r.kind==="signal-stop"?(Lf(r.state.pid,e,t),ya(n.paths,r.state.pid,t),{disposition:"stopped",pid:r.state.pid}):r.kind==="clean-stale"?(ya(n.paths,r.state.pid,t),{disposition:"stopped",pid:r.state.pid}):r.kind==="already-stopped"&&n.lockIsLive&&n.lock?(Lf(n.lock.pid,e,t),ya(n.paths,n.lock.pid,t),{disposition:"stopped",pid:n.lock.pid}):{disposition:"already-stopped"}}function Oi(e){try{return PU(JSON.parse(Ff(e,"utf8")))}catch{return null}}function ou(e,t=Date.now()){let n=IU(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 mC(e,t,n=Date.now()){he(e,{version:1,at:new Date(n).toISOString(),refreshRequestedAt:new Date(n).toISOString(),refreshDetail:t})}function IU(e){try{let t=JSON.parse(Ff(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 fC(e,t,n={}){let r=n.pid??process.pid,i=n.isProcessAlive??xe,o=()=>{},s=ha(e);if(s&&i(s.pid))return{acquired:!1,lockPath:e,message:dC(e,t,s),release:o};s&&ga(e,{force:!0}),hU(SU(e),{recursive:!0});let a;try{a=yU(e,"wx")}catch(u){if(DU(u)==="EEXIST")return{acquired:!1,lockPath:e,message:dC(e,t,ha(e)),release:o};throw u}let c={version:1,pid:r,projectRoot:ba(t),startedAt:(n.now??(()=>new Date))().toISOString()};bU(a,`${JSON.stringify(c)}
|
|
291
|
-
`);let l=!1;return{acquired:!0,lockPath:e,message:"",release:()=>{if(l)return;l=!0,fU(a);let u=ha(e);u?.pid===c.pid&&u.startedAt===c.startedAt&&ga(e,{force:!0})}}}function ha(e){try{let t=JSON.parse(Ff(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 PU(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"||typeof t.cliVersion!="string"||!Dt(t.startedAt)||!Dt(t.heartbeatAt)||!Dt(t.lastActivityAt)||!TU(t.watcher)||t.idleDeadlineAt!==void 0&&!Dt(t.idleDeadlineAt)||t.lastError!==void 0&&!LU(t.lastError)||t.lastRefresh!==void 0&&!FU(t.lastRefresh)||t.typescriptSemantic!==void 0&&!NU(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!AU(t.typescriptIndex)?null:t}function EU(e,t,n,r){if(!e)return{kind:"stopped"};if(e.protocolVersion!==xU)return{kind:"incompatible",state:e,reason:"protocol"};if(e.projectRoot!==t.projectRoot)return{kind:"incompatible",state:e,reason:"project"};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 i=Date.parse(e.heartbeatAt);return n-i>Sa?{kind:"stale",state:e,reason:"old-heartbeat"}:{kind:"live",state:e}}function Tf(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 Df(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 Df(t)}default:return Df(e)}}function uC(e,t,n){let r=t.now()+n;for(;t.now()<=r;){let i=$i(e).classification;if(i.kind==="live")return i.state;t.sleep(pC)}return null}function Lf(e,t,n){if(!n.isProcessAlive(e))return;n.signalProcess(e);let r=t.stopTimeoutMs??wU,i=n.now()+r;for(;n.now()<=i;){if(!n.isProcessAlive(e))return;n.sleep(pC)}throw new Error(`scip-query watch service pid ${e} did not stop within ${r}ms.`)}function ya(e,t,n){ga(e.statePath,{force:!0}),ga(e.activityPath,{force:!0}),ha(e.lockPath)?.pid===t&&!n.isProcessAlive(t)&&ga(e.lockPath,{force:!0})}function dC(e,t,n){return`error: scip-query watch is already running for ${ba(t)}${n?` (pid ${n.pid}, started ${n.startedAt}; lock: ${e})`:` (lock: ${e})`}. Stop that watcher before starting another.`}function DU(e){return typeof e=="object"&&e&&"code"in e?e.code:void 0}var _f={now:Date.now,isProcessAlive:xe,spawnServer(e,t,n,r){if(!gU(e))throw new Error(`Watch service helper was not found at ${e}. Run npm run build first.`);mU(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 TU(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 LU(e){if(!e||typeof e!="object")return!1;let t=e;return Dt(t.at)&&typeof t.message=="string"}function FU(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 NU(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 AU(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")&&Mi(t.requests)&&Mi(t.sessionsCreated)&&Mi(t.sessionsReplaced)&&Mi(t.initializations)&&Mi(t.programUpdates)&&Mi(t.documentsEmitted)&&Mi(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 Mi(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Df(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 gC from"path";function _U(e,t){return e.getReferences().map(n=>{let r=n.getNode();return cu(r,t)})}function MU(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function hC(e,t,n,r){let i=[];for(let o of MU(e))for(let s of _U(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 Ur(i)}function yC(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Vr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:cu(a,r),node:a}))}return i}function cu(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Vr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function bC(e,t,n){let r=e.getSourceFile(),i=$f(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 Ur(c.filter(l=>Vr(n,gC.join(n,l.file))===t))}function Mf(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 $f(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ur(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 Vr(e,t){let n=gC.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function SC(e,t,n,r){let i=$U(t,r);return i.size===0?new Map:OU(e,n,i)}function $U(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 OU(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of jU(e,o)){let a=n.get(s);if(!a)continue;let c=$f(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 jU(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 BU=ne("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function vC(e,t,n,r){let i=Bf(e,t),o=Of(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 Of(s,n)}function jf(e,t,n,r){return Of(Bf(e,t).get(r)??[],n)}function xC(e,t){let n=new Map;for(let[r,i]of Bf(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Bf(e,t){return BU.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 Of(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 Hf 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 RC(e,t){let n=new Map,r=null,i=null,o=()=>(i??=q(e,{extensions:xa}),i),s=()=>(r??=D("typescript.source-file-index",()=>HU(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>bt(c)?un(n,c,()=>{let l=Ra(Hf.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 HU(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(Hf.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 Hf.resolve(e)}function Wf(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function CC(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 WU}from"fs";import at from"path";var qf=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Uf(e,t){let r=t?at.dirname(at.join(e,t)):e,i=at.resolve(e);for(;r.startsWith(i);){for(let s of qf){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 qf){let s=at.join(e,o);if(Ca(s))return s}return null}function lu(e){let t=e.config.projectRoot,n=new Set(Vf(t,e.config.semantic?.typescript?.tsconfigs)),r=q(e,{includeIgnored:!1,extensions:xa});for(let i of r){let o=Uf(t,i);o&&n.add(at.resolve(o))}if(n.size===0){let i=Uf(t);i&&n.add(at.resolve(i))}return[...n].filter(i=>!wC(t,i)).sort((i,o)=>i.localeCompare(o))}function Vf(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 qU(e))for(let i of qf){let o=at.join(r,i);Ca(o)&&n.add(at.resolve(o))}if(n.size===0){let r=Uf(e);r&&n.add(at.resolve(r))}return[...n].filter(r=>!wC(e,r)).sort((r,i)=>r.localeCompare(i))}function qU(e){let t=at.join(e,"package.json");if(!Ca(t))return[];let n;try{n=JSON.parse(WU(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>rm(e,i))}function wC(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 UU}from"module";var kC=UU(import.meta.url),wa,uu;function Gf(){if(wa!==void 0)return wa;try{wa=kC("ts-morph")}catch{wa=null}return wa}function du(){if(uu)return uu;let e=Gf();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=kC("ts-morph/package.json").version??"unknown"}catch{}return uu=`ts-morph:${t}:typescript:${e.ts.version}`,uu}function IC(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function Gr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function pu(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,VU(o));return r}function DC(e,t,n){let r=EC(e,t),i=EC(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=PC(e,t),c=PC(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 PC(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 TC(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,GU(s));return i}function EC(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 VU(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(LC)}function GU(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)||LC(n.location,r.location))}function LC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var zU=32;function mu(e,t){let n=D("typescript.provider.load",()=>Gf());if(!n)return Gr("ts-morph is not installed");let r=D("typescript.provider.tsconfig-discovery",()=>lu(e));if(r.length===0)return Gr("no tsconfig found");try{let i=D("typescript.provider.project-bundles",()=>IC(n,r),()=>({tsconfigs:r.length}));return KU(e,n,i)}catch(i){return Gr(i instanceof Error?i.message:String(i),r[0],r)}}function KU(e,t,n,r={}){return D("typescript.provider.construct",()=>new Kf(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Kf=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ro(t.config.projectRoot),this.sourceFiles=RC(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;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=YU();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=>!NC(u));if(a.length>=zU){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=>NC(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=AC();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,..._C(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 TC(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=re(),i=AC(),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=Ur(y);o.set(h,x),r&&(i.referenceCount+=x.length)}},()=>({definitions:t.length,..._C(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),p=t.compilerNode,m=ZU(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),!FC(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),FC(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=Vr(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=hC(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 MC(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${MC(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 Jf(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||QU(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:cu(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?JU(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 yC(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=>!Mf(c.node)),s=i.some(c=>Mf(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=Wf(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,Ur(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,Ur(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=Wf(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Jf(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=bC(a.identifier,r,this.db.config.projectRoot);l.length>0&&rV(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 CC(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,()=>xC(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?SC(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=Vr(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?jf(this.db,u,d,i)??(m&&m!==i?jf(this.db,u,d,m):null):vC(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?tV():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),XU(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,iV(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?nV(p):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?ae.now():0,l=eV(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 Jf(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 JU(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 YU(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function QU(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function XU(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function ZU(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Jf(n))r.localName&&t.add(r.localName);return t}function eV(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 FC(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function NC(e){return e.symbol.includes("#")?$e(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function tV(){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 nV(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 AC(){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 _C(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function rV(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function iV(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 MC(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{createHash as oV}from"crypto";import{readFileSync as sV}from"fs";import{dirname as aV,join as fu}from"path";var gu=2,cV="typescript-semantic";function $C(e){let t=fu(e,cV);return{rootDir:t,requestDir:fu(t,"requests"),responseDir:fu(t,"responses")}}function OC(e){try{let t=JSON.parse(sV(fu(aV(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||typeof t.status!="string"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:oV("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 mV=12e4,fV=5;function qC(e,t,n={}){let r=new Qf(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=mu(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=>WC(m),()=>a().referencesForDefinitions?.(d,p)??new Map(d.map(m=>[m.symbolId,a().referencesFor(m)]))),u=d=>c({kind:"callees",definitions:[...d]},p=>WC(p),()=>a().calleesForDefinitions?.(d)??new Map(d.map(p=>[p.symbolId,a().calleesFor(p)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},yV,()=>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=>hV(p),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},bV,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Qf=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??vV,this.timeoutMs=n.timeoutMs??SV(),this.cacheDir=pV(t.config.dbPath)}db;runtime;timeoutMs;cacheDir;request(t){let n=mr(this.cacheDir),r=$C(this.cacheDir),i=Oi(n.statePath);if(!HC(i,this.db.config.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=OC(this.db.config.dbPath);if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.randomId(),a=Yf(r.requestDir,`${s}.json`),c=Yf(r.responseDir,`${s}.json`),l=this.runtime.now()+this.timeoutMs;jC(r.requestDir,{recursive:!0}),jC(r.responseDir,{recursive:!0}),he(a,{protocolVersion:gu,id:s,generation:o,deadlineAtMs:l,profileEnvironment:nv(),request:t});try{for(;this.runtime.now()<=l;){if(uV(c))return gV(dV(c,"utf8"),s,o);let u=Oi(n.statePath);if(!HC(u,this.db.config.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(fV)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}finally{BC(a,{force:!0}),BC(c,{force:!0})}}};function HC(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===Yf(t)&&e.typescriptSemantic?.protocolVersion===gu&&n.isProcessAlive(e.pid)&&(r||i)}function gV(e,t,n){let r=JSON.parse(e);if(r.protocolVersion!==gu||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 WC(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function hV(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function yV(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function bV(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function SV(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:mV}var vV={now:Date.now,randomId:lV,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xe};var UC=new iu;Fr({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>UC.clear(e)});function Uo(e,t){let n=nt(t)??"typescript";return UC.getOrCreate(e,n,()=>n==="rust"?oC(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>uR(e,r)},calleeSymbolResolver:lR(e),sourceZeroCalleeOracle:r=>xV(e,r),scipOccurrenceCalleeOracle:r=>cC(e,r)}):qC(e,t))}function nt(e){return e?K(e)==="rust"?"rust":bt(e)?"typescript":null:"typescript"}function xV(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 RV,readFileSync as CV}from"fs";import{resolve as wV}from"path";var kV=/^[A-Za-z_][A-Za-z0-9_]*$/,VC=/\bDefault::default\b/g,IV=/^\.\.\s*Default::default\b/;function GC(e,t){let n=new Map,r=new Map;for(let i of t){let o=Xf(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Xf(e,t,n=new Map){let r=EV(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=PV(e,t.symbolId),c=[];for(let l of i){let u=DV(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=IV.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(VC.lastIndex=0;R=VC.exec(y);){let b=R.index+9;if(!x.has(b))return null}}if(f===0)return null}return Kl(c)}function PV(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function EV(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!kV.test(t)?null:t}function DV(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:TV(e,t);return n.set(t,i),i}function TV(e,t){let n=wV(e.config.projectRoot,t);if(!RV(n))return null;try{return CV(n,"utf8")}catch{return null}}import{readFileSync as OV}from"fs";import{dirname as jV,join as BV}from"path";function hu(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(LV)?null:e}function yu(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(FV)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!AV(e,t):!0,uncertainty:[...s].sort()}}function zC(e){return new Set(e.map(t=>t.path)).size!==e.length}function LV(e){return ee(e)&&typeof e.path=="string"&&typeof e.size=="number"&&typeof e.hash=="string"}function FV(e){return e.hash==="unreadable"||e.size<0}function Zf(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 bu(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=Zf(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"),KC(r,i,s)):s.size>0?KC(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:NV(r,t,i),reasons:[]}}function KC(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function NV(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 AV(e,t){return JC(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&JC(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function JC(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 Go(e){let t=Su(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=Su([...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=>YC(r.get(d))),l=Ge(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:Su(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,p){if(!n.has(d))return Vo("target-outside-project");if(a)return Vo("duplicate-input-path");if(s)return Vo("missing-input-fingerprint");if(c)return Vo("unreadable-input");let m=[],f,g;if(e.graph===null)m.push("dependency-graph-unavailable"),g="whole-project",f=o;else{let x=MV(d,e.graph,u);if(x.find(b=>!r.has(b)))return Vo("missing-input-fingerprint");if(f=Su([...x,...i]),f.some(b=>YC(r.get(b))))return Vo("unreadable-input");g="dependency-closure"}let h=f.map(x=>$V(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 _V(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 MV(e,t,n){let r=n.get(e);if(r)return r;let i=_V(e,t);return n.set(e,i),i}function $V(e){return{path:e.path,size:e.size,hash:e.hash}}function YC(e){return e.size<0||e.hash==="unreadable"}function Vo(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function Su(e){return[...new Set(e)].sort()}var HV=me("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function zr(e,t,n){let r=HV.get(e,()=>WV(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 WV(e){try{let t=JSON.parse(OV(BV(jV(e.config.dbPath),"meta.json"),"utf8")),n=hu(t.fingerprint);return n?{builder:Go({projectFiles:ka(e),snapshot:n,graph:ge(e),engineIdentity:du()}),identities:new Map}:null}catch{return null}}var eg="typescript-reference-fragment-v2",xu=Ie({kind:"typescript-reference-fragments",invalidation:pe("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:UV});function QC(e,t,n,r=e){let i=ka(e),o=Go({projectFiles:i,snapshot:t,graph:ge(e),engineIdentity:du()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,eg).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return xu.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function tg(e,t,n){let r=t.filter(o=>bt(o.relativePath));if(r.length===0)return vu("no TypeScript definitions");let i=vu("shadow did not run");return D("typescript.reference-fragments.shadow",()=>{try{let o=Uo(e,r[0].relativePath);if(!o.availability().available||!o.referenceFragmentsForFiles)return i=vu("TypeScript reference fragment provider is unavailable"),i;let s=ka(e),a=new Set(s),c=o.referenceFragmentsForFiles(s),l=pu(r,c),u=DC(r,qV(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=zr(e,p,eg);m?.key&&d.push({relativePath:p,contentHash:m.key,value:c.get(p)??[]})}return xu.writeBatch(e,d),i={state:"passing",files:s.length,keyedFiles:d.length,writtenFiles:d.length,...u},i}catch(o){return i=vu(o instanceof Error?o.message:String(o)),i}},()=>({...i}))}function qV(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function ng(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=zr(e,m,eg);if(!f?.key)return null;c.set(m,f.key);let g=xu.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:pu(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s};let d=Uo(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,xu.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:pu(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s}}catch{return null}},()=>({state:n,files:r,cacheHits:i,cacheMisses:o,computedFiles:s}))}function vu(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function UV(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(VV)?null:t}catch{return null}}function VV(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 Ru(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 GV="typescript-import-usage-v1",zV="typescript-signatures-v1",rg=me("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),XC=xi({kind:"semantic-import-usage",invalidation:pe("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:lw}),ZC=xi({kind:"semantic-signatures",invalidation:pe("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:rG}),ew=Ie({kind:"typescript-import-usage",invalidation:pe("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:lw}),tw=Ie({kind:"typescript-signatures",invalidation:pe("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:iG});function St(e){let t=new Map,n=new Set;return{capability:(r,i)=>uw(e,r,i),importUsage:r=>JV(e,r),references:r=>iw(e,r),materializeReferences:(r,i)=>sw(e,r,t,n,i),callerMap:r=>YV(e,r,t,n),calleeMap:r=>eG(e,r),signature:r=>tG(e,r)}}function KV(e,t){if(t.size===0)return;let n=rg.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function rw(e,t){if(!rg.has(e))return{hits:[],misses:[...t]};let n=rg.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 JV(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=zr(e,t,GV);if(u?.key){s=1;let p=ew.read(e,t,u.key);if(p)return o="hit",a=1,p;c=1;let m=Bn(e,t);if(!m)return o="unavailable",[];let f=m.importUsage(t);return ew.write(e,t,u.key,f),o="computed",f}l=1;let d=Bn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=cw(e,"semantic-import-usage",t);if(n){let o=XC.read(e,t,n);if(o)return o}let r=Bn(e,t);if(!r)return[];let i=r.importUsage(t);return n&&XC.write(e,t,n,i),i}function zo(e,t){return St(e).references(t)}function iw(e,t){let n=Xf(e,t);if(n)return n;let r=xR(e,t);if(r)return r;let i=Bn(e,t.relativePath);return i?i.referencesFor(t):[]}function Kr(e,t){return St(e).callerMap(t)}function ow(e,t){let n=new Map,r=new Map;for(let i of t){if(nt(i.relativePath)==="typescript"){let o=Bn(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}ig(e,n,i,iw(e,i))}for(let[i,o]of r){let s=ng(e,o),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&re()&&tg(e,o,a);for(let c of o)ig(e,n,c,a.get(c.symbolId)??[])}return n}function YV(e,t,n=new Map,r=new Set){let i=new Map,o=sw(e,t,n,r),s=0;return D("semantic.callers.from-references",()=>{for(let a of t)s+=ig(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 sw(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=ng(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 Ru(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=QV(e,o,k);if(!V){for(let W of F)nt(W.relativePath)||(l+=1),c.push(W);continue}f+=1;let ie=_S(e,k,V);for(let W of F){let be=ie.get(W.symbol)??null;if(be!==null){let Z=ZV(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=XV(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)&&uw(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",()=>$S(e,s),()=>({entries:s.length})),w.size>0&&tg(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 QV(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:Li(e.config.projectRoot),projectFingerprint:t})):null}function XV(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=GC(e,t),g=vR(e,t),h=new Map,y=n.prefetchCallees?new Map:null,x=[];for(let b of t){let v,w=()=>(v??=Bn(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),KV(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 ig(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 ZV(e){try{return JSON.parse(e)}catch{return null}}function Cu(e,t){return St(e).calleeMap(t)}function eG(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=Bn(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)??[];nw(r,m.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let p=u.calleesFor(d);nw(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 nw(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function aw(e,t){return St(e).signature(t)}function tG(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=zr(e,t.relativePath,zV);if(d?.key){a=1;let m=tw.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=Bn(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return tw.write(e,t.relativePath,d.key,{...m,[t.symbol]:g}),s="computed",g}u=1;let p=Bn(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=cw(e,"semantic-signatures",t.relativePath),r=nG(t);if(n){let s=ZC.read(e,r,n);if(s)return s.signature}let i=Bn(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&ZC.write(e,r,n,{signature:o}),o}function cw(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:Li(e.config.projectRoot),projectFingerprint:r}))}function nG(e){return`${e.relativePath}\0${e.symbol}`}function lw(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function rG(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 iG(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 uw(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,...Uo(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Bn(e,t){if(!nt(t))return null;let n=Uo(e,t);return n.availability().available?n:null}var oG=ne("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function wu(e,t){let n=Ar(t);return oG.get(e,n,()=>sG(e,n))}function sG(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&&dw(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)dw(n,o,r.sourcePath)}return n}function dw(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Ko(e,t,n){let r=dr(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=wu(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 pw(e,t,n){let r=Ko(e,t,n);if(r.length>0)return r;let i=dr(e).get(n);return!i||i.length===0?[]:i.map(Ea)}function mw(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=zo(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 ku(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&&!Ko(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 ku(e,o)}function fw(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=aa(o),a=new Map;for(let c of Pt(e)){if(n.skipPath?.(c)||!ql(_(e,c),s))continue;let l=Zx(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of Ko(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 ku(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=$n(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=pG(e,t);return n?ku(e,cG(e,n.match,n.identifier)):[]}function Hn(e,t,n={}){return aG(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function aG(e,t,n={}){let r=mw(e,t,{semantic:n.semantic}),i=r.length>0?gw(r,"source-attribution"):gw(Da(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function gw(e,t){return e.map(n=>({...n,provenance:t}))}function cG(e,t,n){let r=new Map;for(let[i,o]of lG(e,t.symbolId))r.set(i,uG(e,i,o,t,n));return r}function lG(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 uG(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=>dG(s,a))}function dG(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function pG(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 Iu=new Map(Object.entries(le).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),hw=new Map([...Iu.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Wn(e){return Iu.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 Pu(){return[le.Class,le.Interface,le.Struct,le.Trait,le.Type,le.TypeAlias,le.Enum,le.Union,le.Protocol]}function yw(){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=Eu(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 Sw(e,t,n={}){let r=gG(e)?yG(e,t,{semantic:n.semantic!==!1}):hG(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var mG=me("caller-rows",{clearGroups:["whole-project"]}),fG=2e4;function gG(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>fG}function hG(e){return mG.get(e,()=>{let t=Ue(e),n=Eu(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 yG(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?bG(e,t):null;if(s)for(let a of zo(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=$n(se(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function bG(e,t){let n=dn().join(", "),r=Pu().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 Eu(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)&&Or(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(wG(e,i)),n.semantic!==!1&&c(TG(vw(e,t)));let l=r?t:o;return l.length>0&&c(EG(e,l)),s}function vw(e,t){let n=re(),r=new Map,i=rw(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=SG(e,i.hits);if(f.entries.length>0&&D("semantic.callees.prefetch-cache-write",()=>Zp(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),D("semantic.callees.cache-scan",()=>{for(let[R,b]of Ru(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=Rw(e,R);if(!I){s.push(...b);continue}let C=AS(e,R,w,I);for(let k of b){let T=C.get(k.symbol)??null;if(T!==null){let F=xG(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=Cu(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",()=>Zp(e,x),()=>({entries:x.length})):D("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function SG(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?Rw(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 xw(e,t){return vw(e,t)}var vG="typescript-callees-v1";function Rw(e,t){let n=nt(t);if(n==="typescript")return zr(e,t,vG)?.key??null;let r=CG(e,t);return n==="rust"?Ge(JSON.stringify({kind:"semantic-callees",language:n,engine:Li(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function xG(e){try{return JSON.parse(e)}catch{return null}}var RG=ne("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function CG(e,t){return RG.get(e,t,()=>{let r=[...ge(e).get(t)??[]].sort().map(i=>`${i}:${Ae(e,i,_(e,i))}`);return Ge(r.join("|"))})}function wG(e,t){let n=new Map,r=kG(t,n),i=dr(e);for(let[o,s]of r){let a=Or(e,o);if(!a)continue;let c=Qm(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=IG(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 kG(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 IG(e,t,n,r){let i=Hl(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=PG(e,t,i,r.calleeQualifier);return o||Wl(e,t,i,r.memberAccess)}function PG(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 EG(e,t){if(t.length===0)return new Map;let r=og(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=og(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=og([...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=DG(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=eR(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 bw=500;function og(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=bw)n.push(t.slice(r,r+bw));return n}function DG(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 TG(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 Cw(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=q(e,{includeIgnored:!1}),o=dr(e),s=t??Ue(e),a=new Set(s.map(l=>l.symbolId)),c=$G(s);if(LG(e,r,i,o,a,c),FG(e,r,s,a),MG(e,r,i,o,a,c),n.semantic!==!1){let l=St(e);jG(r,l.callerMap(OG(s)))}return r}function LG(e,t,n,r,i,o){for(let s of n){if(!K(s))continue;let a=Or(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&&sg(t,u.symbolId,s)}}}function FG(e,t,n,r){let i=AG(n);for(let o of NG(e,r))e.isIgnored(o.relative_path)||_G(o,i.get(o.symbol_id))||sg(t,o.symbol_id,o.relative_path)}function NG(e,t){return $o(e,t?[...t]:void 0)}function AG(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 _G(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function MG(e,t,n,r,i,o){for(let s of n){if(K(s)!=="rust")continue;let a=wi(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&&sg(t,u.symbolId,s)}}}function sg(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function $G(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 OG(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function jG(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 Wt(e,t,n={}){return Sw(e,t,n)}function ag(e,t,n={}){return Cw(e,t,n)}function Ta(e,t,n={}){return fw(e,t,n)}function ww(e,t,n={}){let r=ag(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:fr(r,Ta(e,t))}function fr(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 kw(e,t,n){let r=t.identifierResolution==="strict"?Ko:pw,i=t.candidateNames?aa(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&&ir(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=ur(e,u);for(let[f,g]of m)p(f,"identifier",g.length,()=>r(e,u,f));for(let f of wi(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Ko(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 Iw(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=BG(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)||!HG(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let I=Q(v);I<i||I>o||c&&WG(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 BG(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?ia(e,{scope:t.scope,symbolMatches:_e,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?ia(e,{scope:t.scope,symbolMatches:ve,sqlPrefilter:"function-like"}):jx(e,t.scope)}function HG(e,t){return t.requireCallableSymbol?_e(e.symbol):t.requireFunctionLikeSymbol?ve(e.symbol):e.isFunctionLike}function WG(e){return(e.split("/").pop()??"").includes("types")}var B=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ym(this.db,t)}definitionsForFile(t){return se(this.db,t)}productionCallableDefinitions(t={}){return Iw(this.db,t)}calleeMap(t,n={}){return Eu(this.db,t,n)}crossFileCallerMap(t,n={}){return ag(this.db,t,n)}sourceFallbackCallerFiles(t,n={}){return Ta(this.db,t,n)}callerFileMap(t,n={}){return ww(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 wi(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){kw(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 qG}from"fs";function qt(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,...UG(e.config.dbPath)}}function UG(e){try{let t=qG(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function VG(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function cg(e,t){let n=VG(t);return q(e,{like:n,includeIgnored:!1}).filter(r=>GG(t,r)).map(r=>({relativePath:r}))}function GG(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Du(n.split("/"),t.split("/"))}function Du(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Du(r,t)||t.length>0&&Du(e,t.slice(1)):t.length===0||!zG(n??"",t[0]??"")?!1:Du(r,t.slice(1))}function zG(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=KG(r);return n+="$",new RegExp(n).test(t)}function KG(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{existsSync as JG}from"fs";import{basename as Pw,isAbsolute as YG,join as QG}from"path";function vt(e,t){let n=Ew(e,t,{allowMultiple:!1})[0]?.relativePath;return n||XG(e,t)}function Jo(e,t){return Ew(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function XG(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=YG(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=QG(e.config.projectRoot,r);return JG(i)?r:null}function Ew(e,t,n){let r=Dw(t);if(!r)return[];let i=q(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:ZG(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 ZG(e,t){let n=Dw(e),r=Pw(n),i=Pw(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 Dw(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as ez}from"path";function lg(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:tz(ez(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:rz(c,nz(e,n))}function tz(e){return e.replace(/\.[^.]+$/,"")}function nz(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 rz(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 ug(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=Hn(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=iz(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 iz(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=oz(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 oz(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=lr(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:az(o,i?.display_name??null,r.symbol),source:sz(e,r.relativePath,r.startLine,r.endLine)}],a=Hn(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 sz(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 az(e,t,n){let r=cr(e);if(r&&!cz(r))return r;let i=(t??"").trim();return i?ve(n)&&!i.endsWith("()")?`${i}()`:i:P(n)}function cz(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=Jo(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=Jo(e,t);return n.length===0?[]:dz([...lz(e,n),...uz(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(pz)}function lz(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 uz(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 dz(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 pz(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:P(e.symbol)}}var Ma=new WeakMap,Tw=Ie({kind:"definition-exclusions",invalidation:pe("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:mz});function Fw(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=Tw.read(e,t,o);if(s)return s;let a=n==="rust"?xz(e,t):yz(e,t);return Tw.write(e,t,o,a),a}function mz(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(fz);return n.some(r=>r===null)?null:n}catch{return null}}function fz(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?Nz(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 Nw=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),gz=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,hz=/\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 yz(e,t){let n=_(e,t);if(!n||!bz(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&&Nw.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(...Aw(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 bz(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of Nw)if(e.includes(n)){t=!0;break}return t&&gz.test(e)?!0:e.includes("use")&&hz.test(e)}var Sz=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function vz(e){return Sz.test(e)}function Aw(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(vz(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 xz(e,t){let n=oe(e,t);if(!n)return[];let r=Ma.get(n);if(r)return r;let i=[],o=Rz(n);return o?(Ma.set(n,o),o):(_w(n.rootNode,i,!1,!1),i.push(...Aw(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(...Lz(n.rootNode)),Ma.set(n,i),i)}function Rz(e){return Az(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function _w(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"?Cz(e,t,n,r):r&&Tz(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"?wz(e,t,n):e.type==="mod_item"&&dg(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)_w(s,t,i,o)}function Cz(e,t,n,r){let i=dg(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(Mw(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=Ez(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function wz(e,t,n){let r=dg(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Dz)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(Mw)&&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 dg(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 kz=new Set(["test","bench","tokio::test","async_std::test"]),Iz=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),Pz=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 Ez(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=Fz(e);return t?kz.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:Iz.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:Pz.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function Dz(e){return/#\[\s*derive\s*\(/.test(e)}function Mw(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Tz(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Lz(e){let t=_z(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 Fz(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 Nz(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 Az(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 Lw=/\bwith\s*=\s*"([^"]+)"/g;function _z(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){Lw.lastIndex=0;let r;for(;(r=Lw.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function $w(e){let t=pg(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function pg(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Fw(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 Mz(c)}}function Mz(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 mg(e,t={}){Kp(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ow(e,t,n={}){Kp(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function jw(e,t){if(t.isIgnoredPath(e.relativePath))return xt("ignored-file");if(Br(e.symbol))return xt("module-like-symbol");if(!Tu(e.symbol))return xt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Tu(e.enclosingSymbol))return xt("nested-non-callable-value");if(!t.includeTests&&!$z(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&&!Oz(e)?xt("member"):e.endLine-e.startLine+1<t.minLoc?xt("below-min-loc"):{accepted:!0}}function $z(e){return fe(e)!=="test"}function xt(e){return{accepted:!1,rejectionReason:e}}function Tu(e){return ve(e)||e.endsWith("().")||e.endsWith(".")}function Oz(e){return _e(e.symbol)||Al(e.symbol).length===0}function Lu(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 Yo(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 Bw(){return new Map}function Hw(e,t,n){let r=new Map;for(let i of rR(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Nu(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Ww(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of oR(e,t))i.add(o.symbol_id);return i}for(let o of iR(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function fg(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 Fu(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 qw(e){return e?.occurrences??0}function Nu(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=Vw(e,t,n);o.occurrences+=r,o.sources.add(i)}function Uw(e,t,n,r,i){if(r<=0)return;let o=Vw(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function Vw(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 jz=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Qo(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:jz.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var Bz=1e3,Hz=300;function gr(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(Wz(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(Gx(e));return p=v.size,v},()=>({paths:p})):new Set,f=0,g=a?Bw():D("dead.mention-reference-counts",()=>{let v=Hw(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=Ww(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=>!Fu(g,v.symbolId,v.relativePath));a?D("dead.source-fallback.dead-code-only",()=>Jz(e,x,g,{inactiveBarrelPaths:m}),()=>({definitions:x.length,testReferencesIncluded:!0})):D("dead.source-fallback.ast",()=>Kz(e,x,g,{inactiveBarrelPaths:m}),()=>({definitions:x.length,testReferencesIncluded:!0}));let R=a?x.filter(v=>!fg(g,v.symbolId)):x.filter(v=>!Fu(g,v.symbolId,v.relativePath));D("dead.caller-map-supplement",()=>e2(e,R,g,{inactiveBarrelPaths:m,includeSemantic:!a&&l}),()=>({definitions:R.length,semantic:!a&&l}));let b=a?x.filter(v=>!fg(g,v.symbolId)):d;return zz(e,Vz(b,g))}function Wz(e,t){let n=$w(e),r=[];for(let i of ia(e,{scope:t.scope,symbolMatches:Tu,sqlPrefilter:"function-like"}))jw(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>Uz(e,i),isFrameworkContractCallable:()=>Qo(e,i)}).accepted&&r.push(i);return r}var qz=["method_signature","abstract_method_signature","call_signature","construct_signature"];function Uz(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([...qz]).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 Vz(e,t){return e.map(n=>Gz(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 Gz(e,t){let n=t.get(e.symbolId)??new Map,r=qw(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 zz(e,t){let n=pg(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 Kz(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)&&(Xz(e,c)||Nu(n,c.target.symbolId,c.sourceFile,Zz(c),"source-fallback"))})}function Jz(e,t,n,r){if(t.length===0)return;let i=new B(e),o=Yz(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=wu(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?Qz(u,d,m,()=>l(u),{permissive:p!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ow(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Gw(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Nu(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function Yz(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 Qz(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 Xz(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Gw(e,t)}function Zz(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Gw(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 e2(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=Bz&&q(e).length>=Hz,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||Uw(n,u.symbolId,d,1,"caller-map")};if(o?D("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Wt(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=Wt(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=>!Fu(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=ow(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let p of d)s(u,p)}}function gg(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:t2(e,r,n)}function t2(e,t,n){return Ue(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>n2(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function n2(e,t){let r=Wt(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 hg(e,t,n={}){return u2(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function yg(e,t){let n=te(e,t),r=i2(e,t);if(r.length>0&&!s2(n))return r;let i=o2(e,t,n);return Sg(t)&&i.length>0?i:a2([...r,...i])}function bg(e,t,n={}){let r=vt(e,t);if(!r)return[];let i=Kw(e,r),o=n.semantic===!1?null:zw(e,r);return(o?r2(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function r2(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 i2(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 o2(e,t,n=te(e,t)){let r=n?.relativePath??null,i=n?M(n.symbol):t.replace(/\(\)$/,""),o=n?Br(n.symbol):!1,s=new Set;for(let c of q(e,{includeIgnored:!1}))for(let l of Ce(e,c))c2(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Sg(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?P(n.symbol):i),fromFile:c}))}function s2(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||K(e.relativePath)==="clojure"))}function a2(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 c2(e,t,n){return!e.sourcePath||n.targetFile&&Se(e.sourcePath)!==Se(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&f2(t)||e.kind==="namespace"&&l2(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function l2(e,t){let n=t.trim().replace(/\(\)$/,"");return Sg(n)?e.importedName===n||e.localName===n:!1}function Sg(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function u2(e,t,n={}){let r=vt(e,t);return r?d2(e,r,n)??(n.semantic===!1?null:zw(e,r))??Kw(e,r):null}function d2(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=Jw(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 Kw(e,t){let n=p2(t,_(e,t));return Ce(e,t).map(r=>{let i=Jw(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||m2(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 p2(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 m2(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 Jw(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 f2(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function vg(e,t){let n=Jo(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&&!Rx(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 xg(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=>xx(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:h2(i,g2(e,n))}function g2(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 h2(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 Rg(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 Cg(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 wg(e,t={}){return y2(e,t).map(n=>({name:P(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function y2(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 kg(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 Ig(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{...Yw(r,i,o?.shared??0)}}function Pg(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=>Yw(a.file1,a.file2,a.shared))}function Yw(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 Au(e,t).cycles}function Au(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:b2(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 b2(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)||Qw(t,n)||Qw(n,t)||Xw(t,n)||Xw(n,t)||fe(t)==="entry"||fe(n)==="entry"?"module-hierarchy":"real"}function Qw(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 Xw(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 Eg(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=>S2(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 S2(e,t,n){let r=[...new Set(Wt(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=>!Qo(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 Kr(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 Zw=500;function v2(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=hw.get(n);if(r!==void 0)return r;for(let[i,o]of Iu)if(o.toLowerCase().includes(n))return i;return null}function Dg(e,t,n={}){let{scope:r,limit:i=100}=n,o=v2(t);return o===null?[]:x2(e,r).map(a=>({row:a,resolvedKind:tk(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:P(a.symbol),kind:c,kindName:Wn(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Tg(e,t={}){let n=R2(e,t.scope);for(let r of C2(e,t.scope)){let i=tk(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:Wn(r),count:i}))}function x2(e,t){return Ue(e,{scope:t}).map(w2)}function R2(e,t){let n=new Map;for(let r of ek(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 C2(e,t){let n=[];for(let r of ek(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 ek(e){let t=[];for(let n=0;n<e.length;n+=Zw)t.push(e.slice(n,n+Zw));return t}function w2(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 tk(e){return e.kind!==null&&e.kind!==0?k2(e.kind,e.symbol,e.documentation):I2(e.symbol,e.documentation,e.enclosing_symbol)}function k2(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 I2(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 Lg(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(P2(I,w)))}return R.sort((b,v)=>v.depth-b.depth),E2(R).slice(0,n)}function P2(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 E2(e){let t=[];for(let n of e)t.some(r=>D2(n.chain,r.chain))||t.push(n);return t}function D2(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 Fg(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 Jr(e,t,n={}){let r=te(e,t);if(!r)return null;let i=n.semantic!==!1,o=Wt(e,r,{semantic:i}).filter(a=>ve(a.symbol)).slice(0,50),s=Yo(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 Yr(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 nk(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 Ng(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 Xo(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 Zo(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function rk(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Xo(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 ik(e,t,n,r){let i=0,o=r.medianIdf??Xo(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 es(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=O2(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ve(o.symbol))return[];if(o.callees.size===0)return ok(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=L2(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):ok(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=es(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:T2(s)}}function T2(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 L2(e,t,n,r){let i=ts(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=G2(t,i.corpus),s=q2(o,i),a=F2(o,i),c=Xo(a),l=Zo(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let p=Zo(d.callees,a),m=lk(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 F2(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Ng(n,t.corpus.length+1)}function lk(e,t,n,r){let i=A2(e,t,n,r);if(!_2(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=fk(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 N2(e,t,n,r){let i=r.magnitudeA??Zo(e.callees,n),o=r.magnitudeB??Zo(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Xo(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 A2(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?rk(e.callees,t.callees,n,{medianIdf:r.medianIdf}):ik(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function _2(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=ts(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(uk(C,ie)){l&&(g+=1);continue}l&&(m+=1);let W=lk(C,ie,x.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:x.medianIdf,magnitudeA:T,magnitudeB:x.weightedMagnitudes[V]});W&&(M2(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 $g(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=ts(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(uk(v,T)){c&&(f+=1);continue}c&&(p+=1),N2(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 uk(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 dk=Ie({kind:"source-fingerprints",invalidation:pe("source-fingerprints"),serialize:pK,deserialize:dK});function M2(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 $2=["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 O2(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:_u(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var j2=me("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),B2=me("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function pk(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=j2.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=U2(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 H2(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=B2.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=W2(pk(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 ts(e){return{calleeCorpus:t=>pk(e,t),calleeIndex:t=>H2(e,t),sourceCorpus:(t={})=>Sk(e,t),sourceIndex:(t={})=>ck(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?rK(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):nK(t,ck(e,{scanLimit:n.scanLimit}))}}function W2(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",()=>Ng(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=D("similar.callee-index.weighted-magnitudes",()=>e.map(p=>Zo(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",()=>Xo(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function q2(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 U2(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:_u((d.get(x.symbolId)??[]).map(R=>R.symbol)),paramCount:a.callableSignature(x)?.paramCount??-1})),h=V2(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 mk=5;function V2(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)>=mk);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 G2(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>=mk);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 _u(e){return new Set([...e].filter(t=>!z2(t)))}function z2(e){return $2.some(t=>e.includes(t))}function ok(e,t,n){let r=Q2(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=ts(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(),...fk([...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 fk(e,t){let n=e.flatMap(_g),r=e.flatMap(h=>sk(h,t)),i=Ag(n,gk),o=Ag(n,hk),s=Ag(r,Mg),a=[...new Set(r.filter(ak))],c=e.filter(h=>{let y=sk(h,t);return y.some(x=>Mg.has(x))&&y.some(ak)}).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=>yk.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:K2(f,g)}}function K2(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 Ag(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function _g(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function sk(e,t){if(t==="source-tokens")return _g(e);let n=M(e);return _g(n.length>0?n:J2(e))}function J2(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 ak(e){return e.length>3&&!Mg.has(e)&&!gk.has(e)&&!hk.has(e)&&!yk.has(e)&&!Y2.has(e)}var Mg=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),gk=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),hk=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"]),yk=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Y2=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 Q2(e,t){let n=te(e,t);if(!n||!ve(n.symbol))return null;let r=X2(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function X2(e,t){let n=M(t.symbol),r=cK(e,t.relativePath,t.startLine,t.endLine,n),i=Rk(r,n);return i.size>0?i:null}var Z2=me("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),eK=me("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function bk(e){return`${e.scanLimit??""}`}function Sk(e,t={}){let n=Z2.get(e,()=>new Map),r=bk(t),i=n.get(r);return i||(i=aK(e,t),n.set(r,i)),i}function ck(e,t={}){let n=eK.get(e,()=>new Map),r=bk(t),i=n.get(r);return i||(i=tK(Sk(e,t)),n.set(r,i)),i}function tK(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 nK(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 rK(e,t,n){let r=re(),i=new B(e),o=iK(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,oK(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=vk(e,d);return r&&(p=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:p})).filter(f=>f.symbol!==t.symbol)}function iK(e,t){return Math.max(2,Math.ceil(e*t))}function oK(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(sK(r,o)&&(i+=1,i>=n))return!0;return!1}function sK(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function aK(e,t={}){let n=new B(e),{scanLimit:r}=t,i=Pe(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return vk(e,i)}function vk(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=uK(e,i,a),l=!1,u=null;for(let d of o){let p=lK(d),m=c.get(p),f=m?new Set(m.tokens):null;f||(u??=Qe(e,i),f=Rk(xk(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&&mK(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function cK(e,t,n,r,i){let o=Qe(e,t);return o.length===0?"":xk(o,n,r,i)}function xk(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&&gK(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 lK(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function uK(e,t,n){return dk.read(e,t,n)??new Map}function dK(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 pK(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function mK(e,t,n,r){dk.write(e,t,n,new Map(r))}function Rk(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=fK(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 fK(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 gK(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function qn(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 Un(e){let t=Ck(e.profile?.name),n=()=>{let r=[];t=Ck(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 hK(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 yK(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,()=>({...bK(e.profile?.metadata),...t})):n()}function hK(e,t){if(e.candidateIndex)return wk(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function yK(e,t){if(e.candidateIndex)return wk(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function wk(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 Ck(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 bK(e){return typeof e=="function"?e():e??{}}function Og(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=SK(e,{scope:i,minDeps:s}),l=qn(a,u=>u.deps);return Un({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>xK(u,d,n,c)})}function SK(e,t){let{scope:n,minDeps:r}=t,i=ge(e,n),{universalDeps:o,distinctiveDeps:s}=vK(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 vK(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 xK(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=Yr(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 Qr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&kk(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)RK(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,kk(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 Mu(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(Yr(e,t),i)}function Xr(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 $u(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 RK(e,t,n,r,i,o){let s=[],a=[];for(let c of e)CK(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 CK(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 kk(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=qn(l,d=>d.tokens);return Un({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,p)=>wK(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 wK(e,t,n){let r=mn(e.tokens,t.tokens);if(r.size<6||!kK(r))return null;let i=Yr(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=IK({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 kK(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 Xr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function IK(e){return Qr({genericWords:EK,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:PK})}function PK(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 EK=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=qn(l,d=>d.tokens);return Un({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,p)=>DK(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 DK(e,t,n,r){let i=mn(e.tokens,t.tokens);if(i.size<r||!FK(i))return null;let o=Mu(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=TK({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:NK({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:p}),locA:e.profile.loc,locB:t.profile.loc}}function TK(e){return Qr({genericWords:AK,stripPrefixes:_K,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:LK})}function LK(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 FK(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 Xr([{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 NK(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 AK=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"]),_K=[/^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=>MK(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 MK(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=$u(e,$K({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=OK(e),c=jK(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:BK(c,a),reasons:i,loc:e.loc}}function $K(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 OK(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=>WK.has(p))>=0,s=n.some(p=>HK.has(p));if(Ik(r)||Ik(e.name))return"component";let c=qK.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 Ik(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Pk.has(t.at(-1))?!0:[...Pk].some(n=>e.endsWith(UK(n)))}function jK(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 BK(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 HK=new Set(["component","components","panel","panels","partial","partials"]),Pk=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"]),WK=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),qK=new Set(["page","route","screen"]);function UK(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=VK(e,{scope:o,minTokens:r,scanLimit:s}),u=qn(l,d=>d.tokens);return Un({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,p)=>zK(d,p,n),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.fileB.localeCompare(p.fileB)})}function VK(e,t){return rn(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:GK(n)}))}function GK(e){return e.totalLines}function zK(e,t,n){let r=mn(e.tokens,t.tokens);if(r.size<6||!KK(r))return null;let i=Yr(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=JK({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 KK(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 Xr([{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 JK(e){return Qr({genericWords:QK,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:YK})}function YK(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 QK=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=qn(l,d=>d.tokens);return Un({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,p)=>XK(d,p,n,r),sort:(d,p)=>p.similarity-d.similarity||d.fileA.localeCompare(p.fileA)||d.fileB.localeCompare(p.fileB)})}function XK(e,t,n,r){let i=mn(e.tokens,t.tokens);if(i.size<r||!tJ(i))return null;let o=Mu(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=ZK({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:nJ({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:p,sharedBindings:m}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function ZK(e){return Qr({genericWords:rJ,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:eJ})}function eJ(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 tJ(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 Xr([{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 nJ(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 rJ=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=>iJ(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 iJ(e,t){let n=$u(e,oJ(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=sJ(e.file),a=aJ(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:cJ(a,s),reasons:r,loc:c}}function oJ(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 sJ(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>lJ.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function aJ(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 cJ(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 lJ=new Set(["landing","page","pages","route","routes","view","views"]);function jg(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ge(e,i),c=yJ(a,o,s);if(c.length===0)return[];let l=uJ(c);return l.length<2?[]:hJ(mJ(l,n,r),r)}function uJ(e){let t=dJ(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 dJ(e){let{nodeFreq:t,tailFreq:n}=pJ(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 pJ(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 mJ(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=fJ(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 fJ(e,t,n){if(!gJ(e.filtered,t.filtered))return null;let{distance:r,ops:i}=bJ(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:SJ(e.original,t.original),commonSuffix:vJ(e.original,t.original)}}function gJ(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function hJ(e,t){let n=[];for(let r of e)if(n.some(o=>Ek(r.chainA,o.chainA)&&Ek(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function yJ(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Dk(e,o,[o],new Set([o]),t,n,r,500)}return r}function Dk(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),Dk(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 bJ(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 SJ(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 vJ(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 Ek(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=xJ(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,()=>({...RJ(e.profile?.metadata),...t})):n()}function xJ(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function RJ(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)=>CJ(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function CJ(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=EJ(r,t),o=DJ(r,i);if(o.length<2)return null;let s=TJ(o,i);if(s.length===0)return null;let a=P(e.symbol),c=wJ(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 wJ(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=kJ(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 kJ(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=IJ(e);return PJ.has(r)?`caller verb suggests orchestration: ${r}`:null}function IJ(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 PJ=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function EJ(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 DJ(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 TJ(e,t){return e.filter(n=>n.size>=3).map(n=>LJ(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function LJ(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 ns}from"path";import{spawnSync as FJ}from"child_process";import{createHash as NJ}from"crypto";import{existsSync as AJ}from"fs";import{dirname as Tk,join as _J}from"path";import{fileURLToPath as MJ}from"url";var Nk=ne("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),Lk=Ie({kind:"consumer-file-usage",invalidation:pe("consumer-file-usage"),serialize:GJ,deserialize:zJ});function hr(e,t){return{forDefinitions(n,r){return $J(e,t,n,r)}}}function yr(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 ju(e,t,n){return _k(e,t,n).partition}function $J(e,t,n,r){let i=Ak(n.length),o=re()?Ye(e):null,s=o?OJ(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return D("consumer-evidence.product",()=>{let c=D("consumer-evidence.provenance",()=>jJ(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=BJ(n,c.sources);return D("consumer-evidence.classify",()=>{let d=HJ(e,n,c.sources,u);for(let p of n){let m=d.get(p.symbolId)??qJ();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 OJ(e,t,n){let r=NJ("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 Ak(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function jJ(e,t,n,r){let i=Ak(n.length),o=new Map;return Bg(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Bg(o,i,"semantic",Kr(e,n)),r.sourceFallback!==!1&&Bg(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function BJ(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Bg(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 HJ(e,t,n,r){let i=eY(e,t,n,r);return i||WJ(e,t,n)}function WJ(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,_k(e,i,[...o.keys()],o))}return r}function _k(e,t,n,r=new Map){let i=[],o=0,s=0,a=M(t.symbol),c=[];for(let l of n){let u;KJ(e,l,t.relativePath,a)?(o++,u="reexport-only"):Hg(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 qJ(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Hg(e,t,n){if(!n)return!1;let r=K(t);if(!r)return!1;let i=Nk.get(e,t,()=>Mk(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function Mk(e,t,n){let r=cn(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return VJ();let o=Ae(e,t,i),s=Lk.read(e,t,o);if(s)return s;let a=UJ(r.ast,n);return Lk.write(e,t,o,a),a}function UJ(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 VJ(){return{importedLeaves:new Set,usedLeaves:new Set}}function GJ(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function zJ(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 KJ(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 $k(o,s,r)}function $k(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 JJ="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",YJ="SCIP_QUERY_NATIVE_KERNELS_BIN",QJ="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",Fk=1e3,XJ=5e3,ZJ=64*1024*1024,Ou;function eY(e,t,n,r){let i=process.env[JJ]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<aY())return r.nativeReason="below-threshold",null;let o=cY();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=tY(e,t,n),a=FJ(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:XJ,maxBuffer:ZJ});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=rY(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function tY(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=Nk.get(e,a,()=>Mk(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=nY(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function nY(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=>$k(i,o,s))}function rY(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=iY(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 iY(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(oY)||!sY(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 oY(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function sY(e){return e==="real"||e==="reexport-only"||e==="import-only"}function aY(){let e=process.env[QJ];if(!e)return Fk;let t=Number(e);return Number.isFinite(t)&&t>=0?t:Fk}function cY(){if(Ou!==void 0)return Ou;let e=process.env[YJ],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Ou=[...e?[e]:[],...lY().map(r=>_J(r,"target","release",t))].find(r=>AJ(r))??null,Ou}function lY(){let e=new Set,t=Tk(MJ(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=Tk(t);return[...e]}var uY=20,dY=1,pY=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"]]),mY=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),fY=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 Vg(e,t={}){let n=Ug(t.limit,uY),r=Ug(t.minConsumers,dY),i=new B(e),o=i.fileDependencyGraph(t.scope),s=AY(q(e,{includeIgnored:!1})),a=$Y(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?gY(e,i,t.target):hY(e,t.scope,t.scanLimit)).map(u=>yY(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(NY).slice(0,n)}function gY(e,t,n){let r=vY(e,n);if(r)return[Wk(r)];let i=te(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[xY(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:P(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function hY(e,t,n){let r=q(e,{scope:t,includeIgnored:!1}),i=Ug(n,r.length);return r.slice(0,i).map(o=>Wk(o))}function yY(e,t,n,r,i,o,s){let a=r.definition?bY(e,t,r.definition,i.semantic):SY(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=wn(ns.dirname(l)),d=CY(a),p=RY(u),m=zg([...Ok(u),...d?Ok(d):[]]),f=wY(r.unit,u,d,a),g=kY(f,r.unit,u,d,a,o,s),h=TY(r.unit,c,d,a,u,g.whyNoSuggestedHome),y=LY(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:FY(f,g.suggestedHome,c)}}function bY(e,t,n,r){let i=yr(hr(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return zk(i.get(n.symbolId)??[])}function SY(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return zk(n)}function vY(e,t){let n=Ar(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 xY(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:P(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Wk(e){return{unit:{kind:"file",file:e,shortName:ns.basename(e)}}}function RY(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:Gg(i)})}return t}function Ok(e){return e==="."?[]:qk(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Gg(e){return zg(qk(e).map(({marker:t})=>t))}function qk(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=pY.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function CY(e){if(e.length===0)return null;let t=e.map(r=>wn(ns.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 wY(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":Bk(n,"package")?"package-level-shared":Bk(n,"app")?"app-level-shared":Hk(n,["feature","domain","module"])||Hk(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function kY(e,t,n,r,i,o,s){let a=IY(e,r);if(a)return Zr(a);let c=_Y(t.file),l=PY(e,n,c,i,s);if(l)return l;let u=r;if(wn(n)===wn(u))return Zr(`${n} is already the nearest common owner for its consumers.`);let d=EY(u,n,c,s);return d||DY(u,n,c,o,s)}function IY(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 PY(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Wg(o):Zr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=wn(ns.dirname(r[0])),s=Gk(t,n,o,i);return s?Zr(s):Wg(o)}return null}function EY(e,t,n,r){return jY(e)?Uk(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function DY(e,t,n,r,i){if(e===".")return Zr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Uk(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Zr(`${o} does not exist in the indexed project.`)}function Uk(e,t,n,r,i){if(!Vk(e,n))return Zr(i);let o=Gk(t,n,e,r);return o?Zr(o):Wg(e)}function Wg(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Zr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function TY(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 LY(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 FY(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 NY(e,t){return jk(t)-jk(e)||e.candidatePath.localeCompare(t.candidatePath)}function jk(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 AY(e){let t=new Set(["."]);for(let n of e){let r=wn(ns.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=wn(ns.dirname(r))}return t}function _Y(e){let t=qg(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Vk(e,t){let n=wn(e),r=wn(t);return r==="."||n===r||n.startsWith(`${r}/`)}function MY(e,t,n){let r=qg(e),i=qg(t);return(Vk(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Gk(e,t,n,r){return wn(e)===wn(n)||!MY(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function $Y(...e){let t=new Set(fY);for(let n of e)for(let r of n??[]){let i=OY(r);i&&t.add(i)}return t}function OY(e){let t=e.trim().toLowerCase();return t===""?null:t}function Bk(e,t){return Gg(e).includes(t)}function Hk(e,t){let n=Gg(e);return t.some(r=>n.includes(r))}function jY(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?mY.has(n):!1}function wn(e){let t=Ar(e);return t===""?".":t}function qg(e){let t=Ar(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ug(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function zk(e){return zg([...e]).sort((t,n)=>t.localeCompare(n))}function zg(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 BY(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 BY(e,t,n){let r=Wt(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 HY(e,t,n)){if(i.has(l))continue;let u=se(e,l),d=u.length>0?$n(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=sa(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)||!WY(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 HY(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 WY(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=qY(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=UY(e,i.relative_path),c=n.semantic===!1?new Map:Kr(e,a);for(let l of a){let u=VY(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:GY(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function qY(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 UY(e,t){return new B(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function VY(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 GY(e){return e>10?"high":e>0?"medium":"low"}function Bu(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new B(e),a=zY(e,n,r,o),c=new Kg;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(Kk(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=Jk(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=JY(e,b,c);v.removable?x.push(KY(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(Kk(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 zY(e,t,n,r){let i=gr(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:Jk(e,s.symbol)}));return o}function KY(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 Jk(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 JY(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 Kk(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 Kg=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 _8}from"crypto";import{existsSync as Eh}from"fs";import{execFileSync as YY}from"child_process";var eI=2e3,Hu=50,QY=64,XY=8,ZY=3,eQ=2160*60*60,tQ=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,nQ=3,rQ=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,iQ=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function oQ(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=Jg(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 Wu(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=Jg(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 sQ=Wu("git-commit-history");function Tt(e,t={}){let n=t.historyMode??"bounded";return{capability:r=>aQ(e,r),commitHistory:()=>qa(e,n),fileChurn:()=>uQ(e,n),changeAmplification:()=>dQ(e,n),trackedFiles:()=>mQ(e),fileAddRecords:()=>gQ(e,n),coChangePairs:(r={})=>RQ(e,r,n),coChangePairsForFiles:(r,i={})=>nI(e,r,i,n),directionalCoChangePairsForFiles:(r,i={})=>CQ(e,r,i,n)}}function qa(e,t="bounded"){return sQ(e,rs(t),(n,r)=>cQ(n,r,t))}function aQ(e,t){let n=Jg(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 Jg(e){try{return Ut(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Ut(e,t){return YY("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function cQ(e,t,n){let r;try{r=Ut(e,["log","--no-merges","--name-only",...qu(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Zg(r,Hu)}}function lQ(e){return tQ.test(e.subject)}function uQ(e,t){let n=qa(e,t);if(!n)return null;let r=new Map;for(let i of n.commits){let o=lQ(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 dQ(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:Yk(r,.5),p90FilesPerCommit:Yk(r,.9),commitsAnalyzed:r.length}}function Yk(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var pQ=oQ("git-tracked-files");function mQ(e){return pQ(e,t=>{try{let n=Ut(t,["ls-files"]);return new Set(n.split(`
|
|
653
|
-
`).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var fQ=Wu("git-file-adds"),Qk="__git__/file-adds",Xk=Ie({kind:"git-file-adds",invalidation:pe("git-file-adds"),serialize:yQ,deserialize:bQ});function Yg(e){return Tt(e).fileAddRecords()}function gQ(e,t){let n=rs(t);return fQ(e,n,(r,i)=>hQ(e,r,i,t))}function hQ(e,t,n,r){let i=Xk.read(e,Zk(r),n);if(i)return i;let o=SQ(t,r);return o&&Xk.write(e,Zk(r),n,o),o}function yQ(e){return JSON.stringify([...e.entries()])}function bQ(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 SQ(e,t){let n;try{n=Ut(e,["log","--no-merges","--find-renames","--name-status",...qu(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=vQ(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 vQ(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 tI=Wu("git-co-change-pairs"),xQ=Wu("git-directional-co-change-pairs");function RQ(e,t,n){let r=`all\0${rs(n)}\0${Qg(t)}`,i=tI(e,r,()=>{let o=qa(e,n);return o?Xg(o,t):null});return i&&[...i]}function nI(e,t,n,r){if(t.size===0)return[];let i=`files\0${rs(r)}\0${rI(t)}\0${Qg(n)}`,o=tI(e,i,()=>{let s=qa(e,r);return s?Xg(s,n,t):null});return o&&[...o]}function CQ(e,t,n,r){if(t.size===0)return[];let i=n.maxFilesPerCommit??Hu;if(t.size>QY)return nI(e,t,n,r);let o=`directional\0${rs(r)}\0${rI(t)}\0${Qg({...n,maxFilesPerCommit:i})}`,s=xQ(e,o,(a,c)=>{let l=wQ(a,c,t,i,r);return l?Xg(l,n,t):null});return s&&[...s]}function Qg(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??Hu;return`${t}\0${n}\0${r}`}function rI(e){return[...e].sort().join("\0")}function Xg(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Hu}=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=PQ(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-eQ;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:DQ(p.broadTogether,m),recency:b>0?"recent":"stale",subjectContext:TQ(p.subjects)})}return l.sort((d,p)=>p.together-d.together||p.confidence-d.confidence||d.fileA.localeCompare(p.fileA)),l}function wQ(e,t,n,r,i){let o;try{o=kQ(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Ut(e,["log","--no-merges","--format=%H",...qu(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=IQ(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Ut(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Zg(u,r);return{head:t,...d,newestAnalyzedAt:l}}function kQ(e,t){return Ut(e,["log","--no-merges","--format=%H%x00%ct",...qu(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 qu(e){return e==="full"?[]:["-n",String(iI())]}function iI(){return Wr(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??eI}function rs(e){return e==="full"?"full":`bounded:${iI()}`}function Zk(e){let t=rs(e);return t===`bounded:${eI}`?Qk:`${Qk}:${t}`}function IQ(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Ut(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=Zg(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Zg(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 PQ(e){return e.length>=XY?!0:EQ(e).size>=ZY}function EQ(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 DQ(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function TQ(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<nQ&&r.push(i);for(let o of LQ(i))t.add(o);for(let o of i.match(rQ)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function LQ(e){let t=new Set,n=iQ.exec(e)?.[1]?.toLowerCase();return n&&t.add(FQ(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 FQ(e){return e==="feat"?"feature":e}import{existsSync as NQ}from"fs";import{join as AQ}from"path";function th(e){return eh.test(e)}var eh=/(?:^|\/)(?: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=lI(e),f=ih(e,p,m),g=n.includeLinked===!0||l,h=[];for(let y of d){if(eh.test(y.fileA)||eh.test(y.fileB)||!oI(e,y.fileA)||!oI(e,y.fileB)||l&&!y.fileA.includes(t)&&!y.fileB.includes(t)||!l&&(fe(y.fileA)==="test"||fe(y.fileB)==="test"||OQ(y.fileA,y.fileB)||MQ(y.fileA,y.fileB)))continue;let x=f(y.fileA,y.fileB);if(!g&&x)continue;let R=nh(y.fileA,y.fileB),b=rh(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 oI(e,t){return NQ(AQ(e.config.projectRoot,t))}function nh(e,t){let n=aI(e),r=aI(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=JQ(n.tokens,r.tokens).filter(c=>!zQ.has(c));return cI(e,t)||a.length>=2?(o(cI(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 rh(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!GQ.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${YQ(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 ih(e,t=ge(e),n=lI(e)){return(r,i)=>jQ(t,n,r,i)}var _Q=/(?:^|\/)(?:locales|i18n)\//i;function sI(e){return _Q.test(e)}function MQ(e,t){return sI(e)&&sI(t)?!0:$Q(e,t)}function $Q(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 OQ(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 lI(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function jQ(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 BQ=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,HQ=/(?:^|\/)(?:\.[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,WQ=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,qQ=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,UQ=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,VQ=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,GQ=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),zQ=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 aI(e){let t=e.replace(/\\/g,"/"),n=new Set;return BQ.test(t)&&n.add("doc"),HQ.test(t)&&n.add("config"),WQ.test(t)&&n.add("schema"),qQ.test(t)&&n.add("script"),UQ.test(t)&&n.add("model"),VQ.test(t)&&n.add("view"),fe(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:KQ(t)}}function cI(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 KQ(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 JQ(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function YQ(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as kn}from"child_process";import{existsSync as QQ,readFileSync as XQ}from"fs";import{basename as uI}from"path";function Uu(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 is(e,t={}){let n=t.plan??Vn(e,t);return n.note?ZQ(n.note,n.changedFileLines):n.changedFiles.length===0?e5(n.changedFileLines):Gu(n.changedFiles,[Vu(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Vn(e,t={}){let{base:n="HEAD"}=t;try{let r=t5(e.config.projectRoot,n),i=l5(e,r),o=u5(e,n5(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:o5(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Ua}}}function Vu(e,t,n,r=[]){let i=new B(e),o=new Set(n),s=Uu(r),a=[],c=new Map,l=t.flatMap(b=>i.definitionsForFile(b)).filter(w5),u=l.filter(b=>p5(b,s)),d=f5(e,l,u,s),p=y5([...u,...d.definitions]).sort((b,v)=>b.relativePath.localeCompare(v.relativePath)||b.startLine-v.startLine),m=p.map(b=>b.symbolId),f=x5(e,m),g=R5(e,m,n),h=p.filter(b=>(f.get(b.symbolId)??0)===0),y=fI(()=>Kr(e,h)),x=h.filter(b=>(y.get(b.symbolId)?.size??0)===0),R=fI(()=>Ta(e,x));for(let b of p)v5(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 Gu(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=C5(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function ZQ(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function e5(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 t5(e,t){let n=kn("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=kn("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=kn("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 n5(e,t){let n=kn("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=kn("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return hI([...mI(n),...mI(r)])}function ah(e,t,n){try{return kn("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=r5(e,t,n);return i=>(r.has(i)||r.set(i,ah(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 r5(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=kn("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return i5(s,r)}catch{for(let o of r)i.set(o,ah(e,t,o));return i}}function i5(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 o5(e,t,n){if(n.length===0)return[];let r=new Map,i=new Set;for(let s of a5(e,t))n.includes(s.to)&&(r.set(s.to,s),i.add(s.from));let o=s5(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)||!QQ(`${e}/${s}`))continue;let a=o.filter(u=>!i.has(u)).filter(u=>uI(u)===uI(s));if(a.length===0)continue;let c=XQ(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:c5(ah(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 s5(e,t){let n=kn("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=kn("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024});return[...new Set([...pI(n),...pI(r)])]}function a5(e,t){let n=kn("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=kn("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 c5(e,t){let n=new Set(dI(e)),r=new Set(dI(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 dI(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function pI(e){return e.split(`
|
|
664
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}function l5(e,t){let n=gI(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function u5(e,t){let n=gI(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return hI(r)}function gI(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 mI(e){let t=[],n=null;for(let r of e.split(`
|
|
666
|
-
`)){if(r.startsWith("+++ ")){n=d5(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 d5(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function hI(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 p5(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>ch(e.startLine,e.endLine,r.startLine,r.endLine))}function m5(e,t,n){let r=new Map,i=[],o=yI(e),s=b5(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>ch(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=S5(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(oh(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(oh(a,"nearest-preceding"));continue}}i.push(oh(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function f5(e,t,n,r){let i=yI(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=>ch(p.startLine,p.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...g5(e,c))}return m5(t,o,s)}function g5(e,t){let n=oe(e,t);return n?n.rootNode.namedChildren.filter(h5).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function h5(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function y5(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function yI(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 b5(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 S5(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 oh(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function ch(e,t,n,r){return e<=r&&n<=t}function v5(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!k5(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)sh(e,n,i,d,u);for(let d of o)sh(e,n,i,d,u);for(let d of s)sh(e,n,i,d,u)}function fI(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 x5(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 R5(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 sh(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 C5(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function w5(e){return!(Br(e.symbol)||e.parentTypeName!==null&&!_e(e.symbol))}function k5(e,t){return _e(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function bI(e){let[t,n]=zu(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??I5(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??P5(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]=zu(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]=zu(n,":"),[a,c]=zu(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 I5(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 P5(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 zu(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as _5,readFileSync as CI}from"fs";function Yu(e,t){let n=E5(e,t)??D5(e,t)??T5(e,t)??L5(e,t);return F5(e,n,t)}function E5(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=lh(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(lh(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function lh(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function D5(e,t){if(!Ku(e[t]??""))return null;let n=t;for(;n>0&&Ku(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Ku(e[r]??"");)r+=1;return{start:n,end:r}}function Ku(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function T5(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Ju(o)!==null)break;if(uh(o)!==null)return null;n-=1}if(n<0)return null;let r=Ju(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=Ju(o);if(s!==null){if(s<=r)break;i+=1;continue}if(uh(o)!==null)break;i+=1}return{start:n,end:i}}function Ju(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function L5(e,t){let n=e[t]??"";if(vI(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&SI(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&SI(e[i]??"");)i+=1;return{start:r,end:i}}function SI(e){return uh(e)===null}function uh(e){return e.trim().length===0?"blank":vI(e)?"heading":lh(e)?"fence":Ku(e)?"table":Ju(e)!==null?"list":null}function vI(e){return/^#{1,6}\s+/.test(e.trim())}function F5(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 N5}from"fs";import{join as xI}from"path";function za(e,t){let n=Qu(e),r=Qu(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 A5(e){return Qu(e).replace(/\/\*\*?$/,"")}function RI(e,t){let n=Qu(t),r=A5(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=N5(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(xI(a,u.name),d)}};return s(xI(e,r),r),o.sort()}function Qu(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var M5=/<!--\s*scip-query:\s*snapshot\s*-->/i;function Xu(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>za(i,t)))return!0;let r=_(e,t);return r.length>0&&M5.test(r)}var br={classifyCitation:O5,citationContexts:j5,citationKindLabel:H5,citationRemediation:W5,referenceTargets:q5,hasLineAnchoredCitation:$5};function $5(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function O5(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 j5(e,t,n){let r;try{r=CI(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(B5),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(Yu(r,s))}return o}function B5(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 H5(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 W5(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 q5(e,t,n){let r=Uu(n),i=new Set;for(let o of t)U5(e,o,r.get(o)??[])&&i.add(o);return i}function U5(e,t,n){if(!V5.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!_5(r))return!0;if(n.length===0)return!1;let i=CI(r,"utf-8").split(/\r?\n/),o=G5(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 V5=/\.(?:[cm]?[jt]sx?)$/i;function G5(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&z5(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function z5(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as kI,readFileSync as ph,statSync as K5}from"fs";import{join as os}from"path";var wI=Ie({kind:"doc-path-evidence",invalidation:pe("doc-path-evidence"),serialize:cX,deserialize:lX}),Ka=/\.(?:md|mdx|rst|txt)$/i;function J5(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Y5=3,Q5=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function mh(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Y5,includeSnapshotExcluded:o=!1}=t,s=tX(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&&!PI(e,c)||n!==void 0&&!kI(os(e.config.projectRoot,c)))continue;let l=Xu(e,c);if(l&&!o)continue;let{value:u,estimated:d}=X5(e,c,s.changeTimes.get(c)),p=Z5(e,c),m=new Map,{resolved:f,broken:g,citations:h}=iX(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,...dh("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,dh("both",p,w.citationContexts))):m.set(R,{file:R,evidence:"co-change",coChanges:b,changesSinceDocUpdate:v,...dh("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 X5(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(K5(os(e.config.projectRoot,t)).mtimeMs/1e3),estimated:!0}}catch{return{value:0,estimated:!1}}}function Z5(e,t){let n;try{n=ph(os(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 dh(e,t,n=[]){let r=e==="co-change"||n.length===0?null:br.classifyCitation(n);return{actionTier:eX(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function eX(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function tX(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:EI(i)}}function II(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=EI(l),d=nX(t,u),p=[];for(let m of l){if(!PI(e,m))continue;n&&(i+=1);let f;try{f=ph(os(e.config.projectRoot,m),"utf-8")}catch{n&&(o+=1);continue}if(!sX(f,d)){n&&(s+=1);continue}let g=DI(e,m,f);if(!g)continue;n&&(a+=1);let h=rX(g.candidates,t,d,l,u);if(h.size===0)continue;let y=[...new Set([...h.values()].flatMap(v=>[...v]))],x=oX(g.contextsByCandidate,y),R=[...h].map(([v,w])=>({file:v,contexts:Zu([...w].flatMap(I=>x.get(I)??[])).slice(0,3),lineReferences:ed([...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:Zu(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 PI(e,t){return Ka.test(t)&&!J5(t)&&kI(os(e.config.projectRoot,t))}function EI(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 nX(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 rX(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 iX(e,t,n,r,i){let o=new Set,s=new Set,a=DI(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,Zu(x).slice(0,3))}let y=u.get(g);y&&y.length>0&&p.set(f,ed([...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 oX(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 DI(e,t,n){let r=n;if(r===void 0)try{r=ph(os(e.config.projectRoot,t),"utf-8")}catch{return null}let i=Ae(e,t,r),o=wI.read(e,t,i);if(o)return o;let s=aX(r);return wI.write(e,t,i,s),s}function sX(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function aX(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(Q5)){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,ed([...i.get(c)??[],l]));let u=Yu(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,Zu(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function cX(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function lX(e){try{let t=JSON.parse(e);if(!ee(t))return null;let n=X(t.candidates),r=dX(t.contextsByCandidate),i=uX(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function uX(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],ed(r)])}return t}function dX(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 Zu(e){let t=[];for(let n of new Set(e))t.some(r=>pX(r,n))||t.push(n);return t}function ed(e){return[...new Set(e)].sort((t,n)=>t-n)}function pX(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 mX}from"crypto";var LI=3;function Ki(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=LI,limit:o,scanLimit:s}=t,a=Yg(e),c=AI(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>_I(e,u,a,i)).filter(u=>u!==null),l=NI(c);return o?l.slice(0,o):l}function fh(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=LI,scanLimit:s}=n,a=Yg(e),c=AI(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>_I(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(MI).map(({normalizedBody:u,...d})=>d):[]}function FI(e){let t=Gn(e);return kt(t).replace(/\s+/g,"")}function NI(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=gX(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(MI).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=TI(i)-TI(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function AI(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 _I(e,t,n,r){let i=Sr(e,t);if(!i||fX(i)<r)return null;let o=gh(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 gh(e,t){let n=Sr(e,t);return n&&FI(n)||null}function Sr(e,t){let n=Qe(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
682
|
-
`)}function Gn(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 fX(e){return Gn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function gX(e){return mX("sha256").update(e).digest("hex").slice(0,16)}function MI(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function TI(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var hX=new Set(dn());function hh(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=ss(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function ss(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=SX(e,{scope:n,scanLimit:i});return jI(o,{minSimilarity:r,isDelegatePair:HX(e)}).filter(s=>!s.members.some(a=>rv(e,a.file,a.startLine,"twin")))}function jI(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!GI(l.leaf)&&!TX(l.leaf)&&fe(l.file)!=="test"&&!et(l.symbol)&&!HI(l.symbol)&&!WI(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=D("twin-drift.group-by-leaf",()=>yX(i),()=>({records:i.length})),a=D("twin-drift.cluster-leaf-names",()=>BI([...o.keys()]),()=>({leaves:o.size}));return D("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=bX(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||!AX(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=IX(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(kX);if(!p){l.push({leaf:OI(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let y=p.similarity>=n?"divergent":"homonym";l.push({leaf:OI(u),relationship:y,maxDivergence:Math.round((1-p.similarity)*1e3)/1e3,members:h,...y==="divergent"?{firstDivergentTokens:PX(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 yX(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 bX(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 SX(e,t){let n=D("twin-drift.load-definitions",()=>Ue(e,{scope:t.scope}).filter(o=>vX(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",()=>xX(r),()=>({scanned:r.length}));return D("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=RX(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function vX(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&hX.has(e.kind):!0:!1}function xX(e){let t=e.filter(o=>o.leaf&&!GI(o.leaf)&&!et(o.symbol)&&!HI(o.symbol)&&!WI(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=BI([...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 RX(e,t){if(!t.leaf)return null;let n=Sr(e,t);if(!n||!_e(t.symbol)&&!CX(n,t.leaf))return null;let r=kt(Gn(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(wX)??[];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:UI(r)}}function CX(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 wX=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function kX(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function IX(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 PX(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 BI(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)EX(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 EX(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||DX(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:_X(e.toLowerCase(),t.toLowerCase(),2)}function DX(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function TX(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||LX.has(e.toLowerCase())}var LX=new Set(["main","row"]),FX=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function HI(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var NX=new Set(["default","new","reset"]);function WI(e,t){return e.startsWith("rust-analyzer ")&&NX.has(t.toLowerCase())}function AX(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=$I(e);return[...$I(t)].some(r=>n.has(r))}function $I(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&&!FX.has(n)))}function _X(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 qI(e){return UI(kt(Gn(e)))}function UI(e){let t=e.trim();if(!t||MX.test(t))return!1;let n=jX(t);return n.length===0||n.length>2?!1:OX(n[n.length-1])}var MX=/\b(?:if|else|for|while|switch|try|catch|do)\b/,$X=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function OX(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return $X.test(t)}function jX(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 BX=3;function HX(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=VI(e,n,r,i,BX,new Set);return t.set(o,a),a}}function VI(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(Or(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))&&VI(e,c,n,r,i-1,o))return!0;return!1}function GI(e){return e.startsWith("<")&&e.endsWith(">")}function OI(e){return[...e].sort()[0]}import{readFileSync as WX,readdirSync as qX}from"fs";import{basename as UX,join as yh}from"path";function VX(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 bh(e,t){let n=GX(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=XX(e.config.projectRoot,t.mustEqual),i=VX(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 KI(e,t){return t.map(n=>bh(e,n))}function JI(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 YI(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 GX(e,t,n){return n.type==="markdown-list"?QX(e,t,n.marker):zX(e,t,n)}function zX(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"?KX(o,n.identifier):YX(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 QI(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function KX(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=QI(n);if(i?.type==="object")return JX(i)}return null}function JX(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(XI(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function YX(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=QI(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(XI(s.text));return[...o].sort()}return null}function XI(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function QX(e,t,n){let r=_(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=ZI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:eP(i)}}function ZI(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 eP(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 XX(e,t){switch(t.type){case"top-level-dirs":return zI(yh(e,t.path));case"file-glob":return[...new Set(RI(e,t.pattern).map(n=>UX(n)))].sort();case"registered-commands":return ZX(e);case"builtin-skills":return zI(yh(e,"skills"))}}function zI(e){let t;try{t=qX(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function ZX(e){let t;try{t=WX(yh(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=ZI(t,"COMMAND REFERENCE");return n?eP(n):[]}import{existsSync as a8,readFileSync as c8,writeFileSync as l8}from"fs";import{isAbsolute as u8,join as d8}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 tP={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 Sh(e,t){if(e===t)return"ok";let n=as(e),r=as(t);return n&&r?!cs(n)||!cs(r)?null:e3(n,r)?"ok":"violation":t3(e,t)}function nP(e,t){let n=as(Ji(e)),r=as(Ji(t));return!!n&&!!r&&cs(n)&&cs(r)}function rP(e,t){let n=as(e),r=as(t);return!!n&&!!r&&(!cs(n)||!cs(r))}function as(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function e3(e,t){return t==="instrumentation"||t==="domain"?!0:e==="domain"?!1:tP[e]?.has(t)??!1}function cs(e){return Object.hasOwn(tP,e)}function t3(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=a3([...n3(e,c,{scope:n,semantic:o}),...i3(c),...s?s3(c,r):[]]);return i<=0||l.results.length<=i?l:{...l,results:l.results.slice(0,i),totalResults:l.results.length}}function n3(e,t,n){let r=u3(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(vr(a))continue;let l=r.get(a)??new Set;for(let u of c)vr(u)||l.has(u)||r3(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&m3(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 r3(e,t,n,r){return y3(e,t,n)||b3(e,t,n)||g3(n)||v3(e,t,n)||S3(n)?!0:r.semantic&&h3(e,t,n)}function i3(e){let t=[],n=f3(e);for(let[r,i]of e){if(vr(r))continue;let o=Ji(r);for(let s of i){if(vr(s))continue;let a=Ji(s);if(o===a)continue;let c=Sh(o,a),l=c===null&&rP(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}`,o3(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 o3(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 s3(e,t){let n=[];for(let[r,i]of c3(e)){let o=i.filter(a=>!vr(a));if(o.length<t)continue;let s=l3(e,o);for(let a of o)for(let c of e.get(a)??[])vr(c)||(s.get(c)??0)===1&&Ja.dirname(c)!==r&&Ja.dirname(c)!==Ja.dirname(r)&&(nP(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 a3(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 c3(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 l3(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])vr(i)||n.set(i,(n.get(i)??0)+1);return n}function u3(e,t){let n=new Map;return d3(e,n,t),n}function d3(e,t,n){for(let r of p3(e,n))iP(e,t,r.from_file,r.to_file)}function p3(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 m3(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)||iP(e,t,i.sourceFile,i.target.relativePath))})}function iP(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 f3(e){let t=new Map;for(let[r,i]of e){if(vr(r))continue;let o=Ji(r);for(let s of i){if(vr(s))continue;let a=Ji(s);if(o===a||Sh(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 g3(e){return e.includes("types")||e.endsWith(".d.ts")}function h3(e,t,n){let r=Pa(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function y3(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function b3(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function S3(e){return e.endsWith(".vue")}function v3(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 vr(e){let t=fe(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||x3(Ja.basename(e)))}function x3(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 oP,extname as sP}from"path";function td(e,t,n,r,i,o){let s=new Set;C3(e,t,n,r)&&s.add(i);for(let a of o)a.value&&R3(s,a.label,a.value);return[...s].slice(0,6)}function R3(e,t,n){let r=w3(n);t.endsWith("name")&&k3(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=I3.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function C3(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(Vs(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function w3(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 k3(e){return e.some(t=>P3.has(t))&&e.some(t=>E3.has(t))}var I3=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"]]),P3=new Set(["can","has","is","should"]),E3=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:()=>M3(e,s,n,r),orderCandidates:Lu,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>D3(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function D3(e,t,n){let r=_3(n);if(r.size!==1||!Dm(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=T3(e,t,i),s=F3(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:L3(a,o,s)}}function T3(e,t,n){return td(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:oP(t.relativePath,sP(t.relativePath))},{label:"callee module",value:oP(n.file,sP(n.file))}])}function L3(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(A3);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 F3(e,t){return Ya(e,t)?Ei(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:N3(n,r)}function N3(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 A3(e){return e.includes("public surface")}function _3(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 M3(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!ea(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=K3(l,n),p={high:0,medium:1,low:2};return fn({candidates:()=>$3(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=j3(m),g=O3(e,l,m,f,{semantic:c}),h=m.filter(y=>{let x=nd(e,y,g,f);return x.realConsumers.length<=1&&!x.transitivelyReachable&&aP(y,x.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:W3(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(m,f)=>{if(f.singletonBackedClassIds.has(m.symbolId))return null;let g=nd(e,m,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!aP(g.definition,g.realConsumers.length,d))return null;let h=B3(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 $3(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=>!J3(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function vh(e,t,n,r){return yr(hr(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function O3(e,t,n,r,i){let o=vh(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=nd(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&xh(l.relativePath))}),a=i.semantic&&s.length>0?fr(o,vh(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>nd(e,l,a,r).realConsumers.length<=1);return fr(a,vh(e,t,c,{semantic:!1,sourceFallback:!0}))}function j3(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 nd(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}=ju(e,t,o),l=Y3(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function B3(e,t){let n=lP(e,t.definition.relativePath,t.definition.startLine),r=xh(t.definition.relativePath)?!0:Q3(e,t.definition),{confidence:i,reason:o}=X3(t.realConsumers.length,n,r),s=H3(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 H3(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 W3(e,t,n,r,i){let o=U3(e,q3(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=yr(hr(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)G3(e,l,a)&&c.add(u);return c}function q3(e){let t=new Map;for(let n of e){let r=M(n.symbol);r&&t.set(cP(n.relativePath,r),n)}return t}function U3(e,t,n){let r=[];for(let i of n){let o=V3(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function V3(e,t,n){if(lP(e,n.relativePath,n.startLine)!=="class")return null;let r=M(n.symbol);if(!r)return null;let i=z3(e,n.relativePath,r);return i?t.get(cP(n.relativePath,i))??null:null}function G3(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)&&!Hg(e,o,r))}function cP(e,t){return`${e}\0${t}`}function z3(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 K3(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function J3(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 xh(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 aP(e,t,n){return!(xh(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function Y3(e,t,n,r){let i=Lm(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 lP(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 Q3(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 X3(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 ls,extname as rd}from"path";function Zi(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new B(e),a=i8(s.fileDependencyGraph(n));return fn({candidates:()=>t8(e,s,n,r),orderCandidates:Lu,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:Z3(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>e8(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function Z3(e,t,n,r){let i=hr(e,t),o=yr(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&D("wrapper.semantic-candidates",()=>{s=n.filter(p=>Rh(e,t,p,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:yr(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:fr(o,a),l=new Map(n.map(p=>[p.symbolId,p])),u=new Map;for(let p of n){let m=Rh(e,t,p,c);if(m.length>1||(u.set(p.symbolId,p),m.length!==1))continue;let f=m[0],g=uP(e,p.symbolId,f);if(!g)continue;let h=dP(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:fr(c,yr(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function e8(e,t,n,r){let i=Rh(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=uP(e,n.symbolId,o);if(!s)return null;let a=dP(t,e,o,n.symbol,s);if(a&&No(a.symbol))return null;let{fanIn:c,source:l}=n8(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=s8(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):ls(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function t8(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!ea(e,i))}function Rh(e,t,n,r){let i=ls(n.relativePath,rd(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ls(s,rd(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ju(e,n,o).realConsumers}function uP(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 dP(e,t,n,r,i){let o=e.definitionsForFile(n),s=r8(t,n,r,i.start_line,i.end_line);return $n(o,s)}function n8(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:o8(t,n),source:"file"}}function r8(e,t,n,r,i){let o=M(n);if(!o)return r;let s=ur(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 i8(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 o8(e,t){let n=e.get(t)??0;if(n>0)return n;let r=ls(t,rd(t)),i=0;for(let[o,s]of e)o!==t&&ls(o,rd(o))===r&&s>i&&(i=s);return i}function s8(e,t,n,r){return td(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):ls(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var p8=25e3,m8=2500,f8=2500;function g8(e){let t=qt(e);return t.symbols>=p8||t.documents>=m8?f8:void 0}var h8=".scipquery-baseline.json";function id(e,t){return t&&u8(t)?t:d8(e.config.projectRoot,t??h8)}function Ch(e,t={}){let{scope:n}=t,r=g8(e),i=[],o=gr(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:${y8(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 y8(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 wh(e,t={}){let n=Ch(e,{scope:t.scope}),r=id(e,t.path);return l8(r,JSON.stringify({version:1,findings:n},null,2)+`
|
|
707
|
-
`),{path:r,findingCount:n.length}}function Qa(e,t={}){let n=id(e,t.path);if(!a8(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(c8(n,"utf-8")),i=new Set(r.findings??[]),o=Ch(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 b8=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??Vn(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=w8(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:_u((x.get(I.symbolId)??[]).map(C=>C.symbol))})),b=ts(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=C8(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=k8(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=S8({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)=>pP(be.migrationScope)-pP(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,b8)}))}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 S8(e){let t=[],n=v8(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=nk(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=x8(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 pP(e){return e==="same-scope"?2:e==="unknown"?1:0}function v8(e,t,n){let r=new Set([...kh(t),...Ih(M(e))]);for(let i of n)for(let o of kh(i))r.add(o);return r}function x8(e,t,n){let r=new Set([...kh(n),...Ih(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 R8=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 kh(e){return Ih(e.replace(/\.[^.]+$/,""))}function Ih(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!R8.has(t))}function C8(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function w8(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 k8(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=>I8(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=ur(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("_")||P8(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 I8(e){let t=K(e);return t==="typescript"||t==="tsx"||t==="javascript"}function P8(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as E8,mkdirSync as D8,readdirSync as T8,readFileSync as L8,writeFileSync as F8}from"fs";import{createHash as N8}from"crypto";import{join as od}from"path";var ec=od(".scipquery","suppressions");function mP(e){return od(e,ec)}function A8(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${N8("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function fP(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=mP(e);D8(r,{recursive:!0});let i=od(r,A8(t)),o={...t,createdAt:t.createdAt??n.toISOString()};return F8(i,JSON.stringify(o,null,2)+`
|
|
714
|
-
`),{path:i}}function gP(e){let t=mP(e);if(!E8(t))return{suppressions:[],warnings:[]};let n=[],r=[];for(let i of T8(t).sort()){if(!i.endsWith(".json"))continue;let o=od(t,i),s;try{s=JSON.parse(L8(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 ad=["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=Vn(e,{base:n}),f=is(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=c4(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",()=>j8(e,f.changedSymbols,h,b,o,a,l,u,v)),w("incomplete-migration",()=>V8(e,n,m,s,l,u,R,v)),w("co-change-partner",()=>G8(e,x,r,i,d,v)),w("twin-partner",()=>z8(e,f.changedSymbols,h,l,v)),w("coverage-contract",()=>K8(e,x,v)),w("doc-reference",()=>Z8(e,h,y,m.changedRanges,m.renamedFiles,v)),w("unused-params",()=>r4(e,g,v)),w("new-dead",()=>i4(e,f.changedSymbols,b,v)),c&&w("baseline",()=>u4(e,v)),$8(v,[...e.config.suppressions??[],...gP(e.config.projectRoot).suppressions]),v.rootCauseGroups=M8(v.findings),v}function tc(e){return e.checksRun.length===0&&e.note===Ua}function nc(e){return e.filter(t=>!t.advisory)}function M8(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=xP(i.severity,n.severity),i.actionTier=RP(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||sd(r.severity)-sd(n.severity)||n.groupKey.localeCompare(r.groupKey))}function xP(e,t){return sd(t)>sd(e)?t:e}function sd(e){return e==="error"?2:e==="warning"?1:0}function RP(e,t){return e?t&&hP(t)>hP(e)?t:e:t}function hP(e){return e==="direct"?2:e==="signal"?1:0}function $8(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>O8(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function O8(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 xr(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function j8(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=fh(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];xr(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:bP(l,u),why:SP(l,u),remediation:vP("direct",l.shortName,R.otherShort)});continue}let d=es(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=B8(l,p);xr(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:bP(l,p),why:SP(l,p),remediation:vP(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 B8(e,t){return t.some(r=>H8(e.symbol,r))?"direct":"signal"}function H8(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:U8(t.sharedEvidence)?!1:W8(n,r)}function W8(e,t){let n=yP(e),r=yP(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 yP(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 q8=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function U8(e){return e.length>=3&&e.every(t=>q8.has(t.toLowerCase()))}function bP(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 SP(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 vP(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 V8(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);xr(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 G8(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||th(m)||th(p)||!Eh(`${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=nh(p,m),b=rh({fileA:p,fileB:m,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},R,(c??=ih(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: ${J8(l)}.`,`Subject context: ${Y8(l.subjectContext)}.`,...Q8(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 z8(e,t,n,r,i){i.checksRun.push("twin-partner");let o=ss(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);xr(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 K8(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!JI(i,t))continue;let o=bh(e,i);if(o.status==="ok")continue;let s=ot("coverage-contract",i.name,i.file);xr(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:YI(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 J8(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${X8(e.lastTogetherAt)}`}function Y8(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 Q8(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 X8(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Ph=3;function Z8(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=br.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of II(e,s))n.has(l.doc)||Xu(e,l.doc)||c.push(e4(e,l,a));for(let l of t4(c))xr(o,l)}function e4(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:br.citationContexts(e,t.doc,t.cited),i=br.classifyCitation(r),o=br.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!Eh(`${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 ${br.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:br.citationRemediation(i.citationKind,t.doc)}}function t4(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<=Ph?n.push(...i):n.push(n4(r,i));return n}function n4(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Ph).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)=>xP(u,d.severity),"info"),a=n.reduce((u,d)=>RP(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 (${Ph}) \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 r4(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);xr(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 i4(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)||a4(a.symbol))continue;let c=ot("new-dead",a.symbol,a.file),l=s&&o4(o,a.file)&&s4(e,a.symbol);xr(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 o4(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function s4(e,t){let n=M(t);return n?(dr(e).get(n)?.length??0)>1:!1}function a4(e){if($e(e)!=="type")return!1;let t=M(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function c4(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&&l4(l,c)}}function l4(e,t){return new RegExp(`\\b${J(t)}\\b`).test(e)}function u4(e,t){if(!Eh(id(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=bI(r),o=ot("baseline",r);xr(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${_8("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as d4,relative as p4,resolve as m4}from"path";var f4=new Set(dn());function Dh(e,t){return`tests/generated/twin-ab/${CP(e)}-vs-${CP(t)}.test.ts`}function CP(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function Th(e,t,n,r){let i=wP(e,t);if(!i.ok)return i;let o=wP(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=h4(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function wP(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?f4.has(o):ve(r.symbol)))return{ok:!1,reason:`${t} resolves to ${P(r.symbol)}${o!==null?` with SCIP kind ${Wn(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=cr(lr(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?g4(c):null}}}function g4(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 kP(e,t,n){let r=d4(t),i=m4(e,n),s=p4(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function h4(e,t,n,r,i){let o=kP(n,r,e.file),s=kP(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 IP={caller:3,"entry-surface":2,rooted:1},y4=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,b4=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,S4=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,v4=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,x4=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function Lh(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=C4(e,m);f&&c.push(f)}if(c.length===0)return[];let l=P4(e,c,a),u=c.filter(m=>!l.has(m.def.symbol));if(u.length===0)return[];let d=hr(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=R4(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)=>IP[f.reachability]-IP[m.reachability]||f.callerFanIn-m.callerFanIn||m.file.localeCompare(f.file)||m.startLine-f.startLine),r?p.slice(0,r):p}function R4(e,t,n){return n>0?"caller":Oe(e,t.symbol,t.relativePath)?"rooted":tt(e,t.relativePath)?"entry-surface":null}function C4(e,t){let n=Sr(e,t);if(!n)return null;let r=Gn(n),i=r.trim();if(i==="")return!I4(n)||!Ya(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=zs(r),s=kt(r),a=w4(o,s);if(a.length!==1)return null;let c=a[0];return k4(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:v4.test(r)&&S4.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function w4(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 k4(e){let t=b4.exec(e.trim());return t?y4.test(t[1]??""):!1}function I4(e){return x4.test(e.trimEnd())}function P4(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=D4(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 E4=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function D4(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(E4)){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 T4=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,L4=/^(?:is|has)(?:[A-Z].*)?$/,F4=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Fh=/\breturn\b/g,N4=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,A4=/\.(?:addIssue|push)\s*\(/;function Nh(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=M4(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 _4(e){return T4.test(e)?"imperative":L4.test(e)?"predicate":null}function M4(e,t){let n=_4(t.leaf);if(!n||Qo(e,t))return null;let r=Sr(e,t);if(!r||!N4.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(qI(r)){let s=j4(e,t);return!s||DP(s.body,EP(s.snippet))||PP(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=Gn(r);return DP(o,EP(r))||PP(o)?null:{nameKind:n,resolvedVia:"direct"}}var $4=new Set(["if","for","while","switch","catch","function"]);function PP(e){let t=zs(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!$4.has(n[1]))return!0;return!1}function EP(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function DP(e,t){let n=zs(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||F4.test(n)||A4.test(n))return!0;let r=O4(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 O4(e){let t=[];Fh.lastIndex=0;let n;for(;n=Fh.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()),Fh.lastIndex=o}return t}function j4(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=Sr(e,s);return a?{body:Gn(a),snippet:a,shortName:P(s.symbol)}:null}var B4=60;function Mh(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=B4}=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=ov(d),m=q4(d);for(let g of z4(p,m))m.add(g);let f=H4(p);for(let g of f){if(g.skip){c.push(e6(e,u,g,o));continue}if(g.kind==="describe")continue;let h=LP(d,g.argsStart),y=p.slice(g.argsStart,g.callEnd),x=d.slice(g.argsStart,g.callEnd);FP(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=Q4(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 Ah=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function H4(e){let t=[];Ah.lastIndex=0;let n;for(;n=Ah.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);Ah.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 LP(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var W4=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),TP=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function q4(e){let t=new Set(["expect","assert"]);TP.lastIndex=0;let n;for(;n=TP.exec(e);){let[,r,i,o,s]=n;if(!(!s||!W4.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 FP(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 U4=/\bfunction\s+(\w+)\s*\(/g,V4=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,G4=60;function z4(e,t){let n=new Set;for(let r of[U4,V4]){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>G4)continue;let l=K4(e,c),u=e.slice(c+1,l);FP(u,t)&&n.add(o)}}return n}function K4(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 J4=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,_h=/\bexpect\s*\(/g,Y4=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,NP=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function Q4(e,t){let n=X4(e,t,J4);if(n.length===0)return null;let r=Z4(e,t);for(let i of r)if(n.includes(i))return i;return null}function X4(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();NP.test(a)&&r.push(a),n.lastIndex=s+1}return r}function Z4(e,t){let n=[];_h.lastIndex=0;let r;for(;r=_h.exec(e);){let i=r.index+r[0].length-1,o=ic(e,i),s=e.slice(o+1),a=Y4.exec(s);if(_h.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=ic(e,c),u=t.slice(c+1,l).trim();NP.test(u)&&n.push(u)}return n}function e6(e,t,n,r){let i=_(e,t),o=LP(i,n.argsStart),s=rc(i,n.callStart),a=t6(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 t6(e,t,n){let r=n+1;try{let i=Ut(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 n6=.7,AP=.62,_P=.45;function $h(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=d6(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=r6(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>p6(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(m6);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:f6(u)}}function r6(e,t){let n=h6(t.limit),r=[...i6(e,{scope:t.scope,minSimilarity:t.minSimilarity??n6,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=xl(e,{scope:t.scope});return i.react&&r.push(...o6(e,{scope:t.scope,minSimilarity:t.minSimilarity??AP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...s6(e,{scope:t.scope,minSimilarity:t.minSimilarity??_P,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...l6(e,{scope:t.scope,minSimilarity:t.minSimilarity??AP,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...u6(e,{scope:t.scope,minSimilarity:t.minSimilarity??_P,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function i6(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 o6(e,t){return ld(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 ld(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:y6(...n.evidenceBuckets(r)),sharedCallees:[]}))}function s6(e,t){return ld(e,t,{query:Wi,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:c6,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 a6=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function c6(e){return e.sharedHooks.some(t=>!a6.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function l6(e,t){return ld(e,t,{query:qi,domain:"vue-component",basis:"vue-template",symbolA:n=>cd(n.fileA),symbolB:n=>cd(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function u6(e,t){return ld(e,t,{query:Ui,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>cd(n.fileA),symbolB:n=>cd(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 d6(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function p6(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 m6(e){let t=MP(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function MP(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function f6(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??MP(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:g6(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 g6(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 h6(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function y6(...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 cd(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var b6=me("suppression-inventory",{clearGroups:["whole-project"]});function ud(e){return b6.get(e,()=>S6(e))}function S6(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=Vs(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=v6(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function v6(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as x6}from"fs";import{join as R6}from"path";function oc(e,t,n={}){let r=te(e,t);if(!r)return null;let i=new B(e),o=C6(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:k6(e,r.symbolId),fanOut:I6(c,r.relativePath)}}function C6(e,t){let n=oe(e,t.relativePath);if(n){let r=BP(n.rootNode,t.startLine,t.endLine);if(r)return{branches:P6(r),estimateBasis:"ast"}}return{branches:WP(jP(e,t.relativePath,t.startLine,t.endLine),OP(e,t.relativePath)),estimateBasis:"regex-fallback"}}function $P(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"});E6(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,w6(e,l))}return n}function w6(e,t){return{branches:WP(jP(e,t.relativePath,t.startLine,t.endLine),OP(e,t.relativePath)),estimateBasis:"regex-fallback"}}function OP(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function jP(e,t,n,r){try{return x6(R6(e.config.projectRoot,t),"utf-8").split(`
|
|
754
|
-
`).slice(n,r+1).join(`
|
|
755
|
-
`)}catch{return""}}function k6(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 I6(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function P6(e){let t=0;return Oh(e,n=>{t+=HP(n)}),t}function E6(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Oh(e,i=>{let o=HP(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 Oh(e,t){t(e);for(let n of e.namedChildren)Oh(n,t)}function BP(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=BP(r,t,n);if(i)return i}return e}var D6=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 HP(e){return D6.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?T6(e.text):0}function T6(e){return(e.match(/&&|\|\|/g)??[]).length}function WP(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=Hn(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}=L6(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 L6(e,t,n,r){let i=Yo(pn(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Yo(Wt(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Yo(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function us(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=te(e,t);return o?r==="backward"?F6(e,o,i,{semantic:n.semantic!==!1}):N6(e,o,{semantic:n.semantic!==!1}):null}function F6(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=sa(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 N6(e,t,n){let r=new Set,i=[],o=new B(e);for(let s of Hn(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??$n(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=sa(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 jh(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!_6(t),a=s?La(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Jr(e,t,{semantic:o}):null,l=s?oc(e,t,{semantic:o}):null,u=s?sc(e,t,{semantic:o}):null,d=s?us(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,p=s?us(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:A6(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 A6(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:ud(e).byFile.get(t)??0}}function _6(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var M6=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:$6,profile:{name:"complexity-hotspots"},prepare:a=>{let c=j6(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?fr(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:B6(e,a,c),branchEstimates:$P(e,a)}},evaluate:(a,c)=>O6(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function $6(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&M6.has(e.kind):!0}function O6(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 j6(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 B6(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 H6(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 Bh(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)/qP):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var qP=864e5,W6=50,q6=.1,U6=10;function V6(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function UP(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)/qP)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function VP(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=V6(e,r,W6);i.length<U6||i.filter(a=>a.outcome==="resolved").length/i.length>=q6||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 ds(e){return OS(e).map(t=>({check:t.check,findingId:t.findingId,firstSeen:t.firstSeen,lastSeen:t.lastSeen,timesShown:t.timesShown,outcome:t.outcome}))}function GP(e,t,n,r=Date.now(),i=new Set){let o=ds(e),s=H6(o,t,n,r,i);return jS(e,s),s}function Rr(e){return e.scoreCount??e.count}function JP(e){let t=J6(e),{breakdown:n,pressure:r}=Y6(e),i=KP(n,"risk"),o=KP(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:Rr(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Rr(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Rr(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:G6(e),validation:K6(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function G6(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:z6(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 z6(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:zn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function K6(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?zn(i/r.size):0,c=s>0?zn(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=zn(m/p.size);l[u]={flaggedFiles:p.size,fixDensity:f,lift:c>0?zn(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?zn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function zn(e){return Math.round(e*100)/100}function YP(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function dd(e,t="existing shared infrastructure discount"){let n=Rr(e);return Math.abs(n-e.count)<.01?"":` (${YP(n)} score-weighted after ${t})`}function cc(e,t){let n=Rr(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${YP(n)} score-weighted)`}function J6(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${dd(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${dd(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${dd(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`+dd({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 KP(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 Y6(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:zn(W),ratio:zn(be),extraPenalty:Z}),o(I,Z,`${k} ${ie} exceed pressure threshold ${zn(W)} (${zn(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=Rr(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=Rr(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=Rr(e.wrappers);o("wrappers",Math.min(3,b),cc(e.wrappers,"wrapper candidate(s)"));let v=Rr(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 Q6}from"v8";var X6=64*1024*1024;function Hh(){let e=globalThis.gc;if(!e)return;let t=Q6();t.heap_size_limit-t.used_heap_size<X6||e()}var Z6=50,eZ=25e3,tZ=2500,QP=2500,XP=50,nZ=10,ps=["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"],rZ={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:sZ(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:aZ(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:cZ(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:lZ(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:dZ(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:pZ(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:mZ(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:fZ(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:gZ(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:hZ(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:yZ(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:bZ(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:uZ(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:SZ(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:vZ(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:xZ(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:kZ(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:IZ(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:RZ(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:CZ(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:wZ(e,n)})};function lc(e,t,n={}){return Wh(e,[t],n)[0]}function Wh(e,t,n={}){return iZ(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>rZ[s](e,n.scope,o,r))})}function iZ(e,t,n){let r=qt(e),i=PZ(r,t);try{return n(r,i)}finally{mg(e,{semanticProvider:!0}),Hh()}}function qh(e){return JP(oZ(e))}function oZ(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:ZP(e,"git-evidence")?.gitEvidence??null,suppressions:ZP(e,"suppressions")?.suppressions??null,coverageContracts:Ve(e,"coverage-contracts").coverageContracts}}function ZP(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 sZ(e,t,n){return He(e,n,"dead",()=>{let r=gr(e,{scope:t,...je.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return pd(TZ(e,r.symbols))})}function aZ(e,t,n){return He(e,n,"isolated",()=>{let r=ji(e,{scope:t,...je.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return pd(LZ(e,r))})}function cZ(e,t,n){return He(e,n,"cycles",()=>$a(e,{scope:t}).filter(i=>i.kind==="real").length)}function lZ(e,t,n){let r=He(e,n,"similar",()=>$g(e,{scope:t,...je.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function uZ(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 dZ(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 pZ(e,t,n){return He(e,n,"twin-drift",()=>{let r=ss(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 mZ(e,t,n){return He(e,n,"react-component-duplicates",()=>{let r=Hi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Uh(r)})}function fZ(e,t,n){return He(e,n,"react-hook-candidates",()=>{let r=Wi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return nE(r,NZ)})}function gZ(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let r=ja(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return FZ(r)})}function hZ(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let r=qi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Uh(r)})}function yZ(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let r=Ui(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return nE(r,AZ)})}function bZ(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let r=Ba(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return pd(r)})}function SZ(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 tE(r,_Z)})}function vZ(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 tE(r,MZ)})}function xZ(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 RZ(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:Vh(o.findings.reduce((a,c)=>a+eE(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:eE(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function CZ(e,t){return He(e,t,"suppressions",()=>{let n=ud(e);return{total:n.total,byCategory:{...n.byCategory}}})}function wZ(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=KI(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function kZ(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 IZ(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>Z6).length}})}function PZ(e,t){let n=e.symbols>=eZ||e.documents>=tZ,r=t?Number.POSITIVE_INFINITY:XP,i=t?Number.POSITIVE_INFINITY:nZ;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:QP,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${QP} symbols and reported their top ${XP} findings. Enable full mode for unbounded candidate counts.`]}}function EZ(e,t){t.releaseCachesBetweenPhases&&(mg(e),Hh())}function He(e,t,n,r){DZ(n);try{return r()}finally{EZ(e,t)}}function DZ(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function TZ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Oe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function LZ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Oe(e,n.symbol,n.relativePath))}function pd(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 tE(e,t){return{...pd(e),scoreCount:Vh(e.reduce((r,i)=>r+t(i),0))}}function FZ(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 Uh(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 nE(e,t){return{...Uh(e),scoreCount:Vh(e.reduce((r,i)=>r+t(i),0))}}function NZ(e){let t=e.sharedHooks.length>0,n=rE({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:iE(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function AZ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=rE({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:iE(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function rE(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!sE.has(oE(t))).length+Math.min(e.functions.length,3)}function iE(e,t,n){let r=[...e,...t,...n].map(oE);return r.length>0&&r.every(i=>sE.has(i))}function oE(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function _Z(e){return e.actionTier==="signal"?.25:1}function MZ(e){return e.actionTier==="signal"?.25:1}function eE(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 Vh(e){return Math.round(e*100)/100}var sE=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 Gh(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 aE}from"fs";import{extname as $Z,join as cE}from"path";function zh(e,t,n={}){let{context:r=0}=n,i=OZ(t);if(i)return BZ(e,i.filePath,i.startLine,i.endLine,r);let o=te(e,t);return o?jZ(e,o,r):null}function OZ(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 jZ(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=cE(e.config.projectRoot,t.relativePath),o;try{o=aE(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??lE(t.relativePath),source:l}}function BZ(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=cE(e.config.projectRoot,s.relative_path),c;try{c=aE(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??lE(s.relative_path),source:p}}function lE(e){switch($Z(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 Kh(e,t={}){let{scope:n,limit:r}=t,i=new B(e),o=KZ([...HZ(e,n),...UZ(e,i,n)]);return JZ(o),r?o.slice(0,r):o}function HZ(e,t){let n=[];for(let r of WZ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Xm(e,r.barrel_path)||_(e,r.barrel_path)&&Dl(e,r.barrel_path).length===0)continue;let i=qZ(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,...dE(e,r.barrel_path)})}return n}function WZ(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 qZ(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 UZ(e,t,n){let r=[];for(let i of VZ(e,n))pE(e,i,i)>0||r.push(...GZ(e,t,i));return r}function VZ(e,t){return q(e,{scope:t,includeIgnored:!1}).filter(n=>Dl(e,n).length>0||Pi(e,n).length>0)}function GZ(e,t,n){let r=Dl(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>uE(e,t,n,o.sourcePath,[zZ(o.specifier)])),i=Pi(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>uE(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 uE(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:pE(e,r,n),...dE(e,n)}})}function zZ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function dE(e,t){return Ei(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function pE(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 KZ(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 JZ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Xh(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new B(e),s=YZ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=QZ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:mE(),callees:mE()},l=[],u=0,d=a==="semantic"?Cu(e,s):new Map,p=a==="source"?e9(e,o,s):null;for(let m of s){let f=md(m,a==="semantic"?zo(e,m).map(b=>b.file):[...p?.referencesBySymbolId.get(m.symbolId)??[]]),g=md(m,a==="semantic"?(d.get(m.symbolId)??[]).map(b=>b.file):[...p?.calleesBySymbolId.get(m.symbolId)??[]]);u+=1;let h=md(m,Hn(e,m).map(b=>b.file)),y=md(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(b=>b.file)),x=Jh(a,"references"),R=Jh(a,"callees");fE(c.references,m,"references",h,f,x,l),fE(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?Qh(u/s.length):0,oracleKind:a,scores:["references","callees"].map(m=>ZZ(m,c[m],a)),topDisagreements:l.slice(0,i)}}function mE(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function YZ(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 QZ(e,t){let n=t[0];if(!n)return null;if(Yh(e,n))return"source";try{if(St(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Yh(e,r))?"source":null}function md(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function fE(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 XZ={references:!0,callees:!1};function ZZ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=Jh(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Qh(t.agreed/t.cheapTotal):null,recall:Qh(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function Jh(e,t){return e==="semantic"?XZ[t]:!1}function Yh(e,t){return K(t.relativePath)==="clojure"&&ce(e,t.relativePath)!==null}function e9(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Yh(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)??[])gE(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)??[])gE(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function gE(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Qh(e){return Math.round(e*1e3)/1e3}var t9=new Set(dn());function Zh(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=i9(e,n9(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=s9(c);return i?l.slice(0,i):l}function n9(e,t){let n=Ue(e,{scope:t.scope}).filter(r=>r9(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 r9(e){return!e.isFunctionLike||et(e.symbol)?!1:e.kind===null||t9.has(e.kind)}function i9(e,t,n){let r=[];for(let s of t){let a=c9(e,s,n);a&&r.push({signature:a,definition:s,fn:o9(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=a9(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?gh(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 o9(e){return{symbol:e.symbol,shortName:P(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:Q(e)}}function s9(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 a9(e){return e<=5?"<=5":e<=20?"6-20":">20"}function c9(e,t,n){if(n.semantic){let o=aw(e,t);if(o)return o}let r=l9(t.documentation),i=r?p9(r):null;return i||m9(u9(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function l9(e){return cr(lr(e))}function u9(e,t,n,r,i){let o=_(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=g9(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,d9(u)))return u}if(u&&u.includes("("))return u}return null}function d9(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Ks(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function p9(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 m9(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=f9(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 f9(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 g9(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 Fy,statSync as Nee}from"fs";import{join as Aee}from"path";import h9 from"better-sqlite3";var y9=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],Vt=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new h9(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=>y9.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 b9 from"ignore";import{readFileSync as S9,existsSync as hE,readdirSync as v9}from"fs";import{dirname as ey,isAbsolute as yE,join as fd,relative as x9,resolve as R9}from"path";function ei(e){let t=b9();return C9(e,t)||t.add(I9),{isIgnored:r=>ty(t,e,r),filter:r=>r.filter(i=>!ty(t,e,i))}}function C9(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!hE(s)))try{let c=S9(s,"utf-8");t.add(a?w9(c,a):c),n.add(s)}catch{}},i=ey(e),o=0;for(;i!==ey(i)&&o<5&&(r(fd(i,".gitignore"),""),!hE(fd(i,".git")));)i=ey(i),o++;return bE(e,"",t,r),n.size>0}function bE(e,t,n,r){let i=t?fd(e,t):e;r(fd(i,".gitignore"),t);let o;try{o=v9(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;ty(n,e,`${a}/`)||bE(e,a,n,r)}}function w9(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>k9(r,n)).join(`
|
|
851
|
-
`)}function k9(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 I9=`
|
|
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 ty(e,t,n){let r=P9(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function P9(e,t){if(!t||t===".")return null;if(!yE(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=yE(t)?t:R9(e,t),r=x9(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as E9,writeFileSync as ry,existsSync as Cr,mkdirSync as D9,realpathSync as T9}from"fs";import{isAbsolute as SE,join as Lt,relative as vE,resolve as gd}from"path";import{createHash as L9}from"crypto";import{homedir as F9}from"os";var ms=".scipquery.json",CE=250,wE=0,kE=10*6e4,N9={enabled:!1,debounceMs:CE,cooldownMs:wE,gitPollMs:2e3,idleTimeoutMs:kE,autoRefresh:!0,ignore:[]},hd=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],A9=new Set(["languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","coverageContracts","docs"]),_9=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),M9=new Set(["router"]),$9=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),O9=new Set(["typescript","rust"]),j9=new Set(["tsconfigs"]),B9=new Set(["rustAnalyzerPath"]),xE=new Set(hd),H9=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),W9=new Set(["architecturalBoundarySegments"]),q9=new Set(["snapshotPaths"]),U9=new Set(["name","files","reason"]),V9=new Set(["id","check","file","reason","expiresAt","createdAt"]),G9=new Set(["name","file","keys","mustEqual","allowExtra"]),z9=new Set(["type","identifier","marker"]),K9=new Set(["type","path","pattern"]),J9=new Set(["object-literal-keys","string-array","markdown-list"]),Y9=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function ut(e){let t=Lt(e,ms);if(!Cr(t))return{};try{let n=E9(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 ${ms} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${ms} at ${t}: ${r}`,{cause:n})}}function fs(e,t={}){let n=[];e7(e,n);let r=new Set(hd);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=gd(t.projectRoot,l),p=vE(t.projectRoot,d);p.startsWith("..")||SE(p)?n.push({level:"error",path:u,message:"Project path must stay inside the project root."}):Cr(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=gd(t.projectRoot,s.configPath),u=vE(t.projectRoot,l);u.startsWith("..")||SE(u)?n.push({level:"error",path:c,message:"Config path must stay inside the project root."}):Cr(l)||n.push({level:"warning",path:c,message:`Clojure indexer config path does not exist: ${s.configPath}`})}}if(e.locality!==void 0)if(!ti(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&&!Cr(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(!ti(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&&!Cr(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 X9(e,n,t),Q9(e,n),n}function Q9(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 X9(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(!ti(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&&!Cr(Lt(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),RE(t,i.keys,`${o}.keys`,J9,"Unknown coverage-contract key extractor type."),RE(t,i.mustEqual,`${o}.mustEqual`,Y9,"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 RE(e,t,n,r,i){if(!ti(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 Kn(e){return{...N9,...e.watch}}function Z9(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return ny(n);if(t?.dbPath)return ny(gd(e,t.dbPath));let r=hs(e);return ny(r)}function gs(){let e=process.env.XDG_CACHE_HOME;return Lt(e||Lt(F9(),".cache"),"scip-query")}function hs(e){let t=gd(e);try{t=T9(t)}catch{}let n=L9("sha256").update(t).digest("hex").slice(0,12);return Lt(gs(),"projects",n)}function uc(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return Lt(gs(),"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 Gt(e,t){let n=Z9(e,t);return{cacheDir:n,dbPath:Lt(n,"index.db"),indexPath:Lt(n,"index.scip"),metaPath:Lt(n,"meta.json")}}function IE(e,t){let n=Lt(e,ms);return Cr(n)||ry(n,JSON.stringify({languages:t,watch:{enabled:!0,debounceMs:CE,cooldownMs:wE,gitPollMs:2e3,idleTimeoutMs:kE,autoRefresh:!0}},null,2)+`
|
|
909
|
-
`),n}function PE(e,t,n){let r=Lt(e,ms),i={...t,languages:[...n]},o=!Cr(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&ry(r,JSON.stringify(i,null,2)+`
|
|
910
|
-
`),{configPath:r,config:i,changed:o}}function EE(e,t,n){let r=Lt(e,ms),i={...t,watch:{...t.watch,enabled:n,...n&&t.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}},o=!Cr(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&ry(r,JSON.stringify(i,null,2)+`
|
|
911
|
-
`),{configPath:r,config:i,changed:o}}function ny(e){return D9(e,{recursive:!0}),e}function e7(e,t){if(!ti(e))return;let n=e;if(lt(t,n,"",A9),lt(t,n.watch,"watch",_9),lt(t,n.hooks,"hooks",M9),lt(t,n.entryRoots,"entryRoots",$9),lt(t,n.semantic,"semantic",O9),lt(t,n.semantic?.typescript,"semantic.typescript",j9),lt(t,n.semantic?.rust,"semantic.rust",B9),lt(t,n.locality,"locality",W9),lt(t,n.docs,"docs",q9),ti(n.indexer)){lt(t,n.indexer,"indexer",xE);for(let[r,i]of Object.entries(n.indexer))xE.has(r)&<(t,i,`indexer.${r}`,H9)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())lt(t,i,`declaredCouplings[${r}]`,U9);if(Array.isArray(n.suppressions))for(let[r,i]of n.suppressions.entries())lt(t,i,`suppressions[${r}]`,V9);if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;lt(t,i,o,G9),ti(i)&&(lt(t,i.keys,`${o}.keys`,z9),lt(t,i.mustEqual,`${o}.mustEqual`,K9))}}function lt(e,t,n,r){if(ti(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 ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as HE,readFileSync as S7}from"fs";import{execFileSync as t7}from"child_process";import{existsSync as n7,readdirSync as TE}from"fs";import{extname as LE,join as FE}from"path";var NE=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),r7=[{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=i7(e),r=c7(e);for(let i of r7){if(o7(e,i.files)){t.push(i.language);continue}if(s7(n,i.globs)){t.push(i.language);continue}u7(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&DE(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&DE(t,"c"),t}function i7(e){try{return TE(e)}catch{return[]}}function o7(e,t){return t?.length?t.some(n=>n7(FE(e,n))):!1}function s7(e,t){return t?.length?e.some(n=>t.some(r=>a7(n,r))):!1}function a7(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 c7(e){let t=l7(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=TE(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=FE(i,s.name);if(s.isDirectory()){NE.has(s.name)||r.push(a);continue}let c=LE(s.name).toLowerCase();c&&n.add(c)}}return n}function l7(e){try{let t=t7("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=>NE.has(o)))continue;let i=LE(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function u7(e,t){return t?.length?t.some(n=>e.has(n)):!1}function DE(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as d7}from"crypto";import{copyFileSync as AE,existsSync as ni,linkSync as p7,mkdirSync as _E,readFileSync as OE,readdirSync as ME,renameSync as oy,rmSync as bd,statSync as m7}from"fs";import{basename as yd,dirname as pc,join as Ft,relative as $E}from"path";var ys=1,Sd=".scipquery-generations";function vd(e){let t=xd(e.outputDb),n=f7(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||iy(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),iy(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),iy(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=Rd(e.metaPath,e.outputDb),i={version:ys,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 jE(e){try{let t=JSON.parse(OE(Ft(xd(e),"state.json"),"utf8"));return t.version!==ys||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!y7(t.previousGeneration)||!b7(t.publication)?null:t}catch{return null}}function BE(e,t,n=()=>new Date){if(!ni(e)||!ni(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=jE(e),i={version:ys,currentGeneration:Rd(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return he(Ft(xd(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function hn(e,t=Ft(pc(e),"meta.json")){let n=Ft(xd(e),"state.json");if(!ni(n))return{state:"legacy",statePath:n};let r=jE(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Rd(t,e),o=r.currentGeneration===i,s=r.previousGeneration?ni(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 xd(e){return Ft(pc(e),Sd)}function f7(e,t){if(!ni(e.outputDb))return;let n=Rd(e.metaPath,e.outputDb),r=Ft(t,n),i=Ft(r,yd(e.outputDb)),o=ni(e.metaPath)?Ft(r,yd(e.metaPath)):void 0;if(!ni(i)){let s=`${r}.${process.pid}.${Date.now()}.tmp`;bd(s,{recursive:!0,force:!0}),_E(s,{recursive:!0});let a=Ft(s,yd(e.outputDb));try{p7(e.outputDb,a)}catch{AE(e.outputDb,a)}o&&AE(e.metaPath,Ft(s,yd(e.metaPath))),_E(t,{recursive:!0}),oy(s,r)}return g7(t,n),{generationIdentity:n,databasePath:$E(pc(e.outputDb),i),...o?{metadataPath:$E(pc(e.outputDb),o)}:{}}}function g7(e,t){for(let n of ME(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||bd(Ft(e,n.name),{recursive:!0,force:!0});for(let n of ME(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&bd(Ft(e,n.name),{recursive:!0,force:!0})}function Rd(e,t){let n=d7("sha256").update(`sqlite-generation-v${ys}\0`);ni(e)&&n.update(h7(OE(e,"utf8")));let r=m7(t);return n.update(`\0${r.size}`),n.digest("hex")}function h7(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 iy(e,t){bd(`${t}.tmp-replace`,{force:!0}),oy(e,`${t}.tmp-replace`),oy(`${t}.tmp-replace`,t)}function y7(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 b7(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 Pn(e,t,n){let r=new Date().toISOString();if(!HE(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!HE(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(S7(n.metaPath,"utf-8")),o=t.languages??gn(e),s=v7(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 v7(e,t,n){return Ni(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 BD,randomUUID as Py}from"crypto";import{closeSync as HD,constants as yee,copyFileSync as MD,existsSync as ii,lstatSync as bee,mkdirSync as wr,mkdtempSync as WD,openSync as qD,readdirSync as See,readFileSync as Kt,realpathSync as vee,renameSync as io,rmSync as ri,statSync as xee,unlinkSync as wy,writeFileSync as UD}from"fs";import{dirname as VD,join as z,resolve as Dn}from"path";import{setTimeout as Ree}from"timers/promises";import{pathToFileURL as $D}from"url";import{deserializeSCIP as GD}from"@c4312/scip";import Cee from"better-sqlite3";import{createRequire as x7}from"module";var R7=x7(import.meta.url),Fe=C7().version;function C7(){for(let e of["../package.json","../../package.json"])try{return R7(e)}catch{}return{version:"0.0.0"}}import{randomUUID as WE}from"crypto";import{closeSync as qE,mkdirSync as w7,openSync as UE,readFileSync as VE,unlinkSync as GE,writeFileSync as zE}from"fs";import{dirname as k7,join as I7}from"path";function mc(e,t={}){return to(I7(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;w7(k7(e),{recursive:!0});do{let s=WE();try{let a=UE(e,"wx");try{let c={version:1,pid:process.pid,token:s,startedAt:new Date(i()).toISOString()};zE(a,`${JSON.stringify(c)}
|
|
913
|
-
`)}finally{qE(a)}return{release:()=>JE(e,s)}}catch(a){if(a.code!=="EEXIST")return null;let c=KE(e);if(c&&(c.pid===void 0||!xe(c.pid))){P7(e,c);continue}if(Date.now()>=o)return null;E7(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function KE(e){try{let t=VE(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 P7(e,t){let n=`${e}.reclaim`,r=WE(),i;try{i=UE(n,"wx")}catch{return!1}try{zE(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
914
|
-
`)}finally{qE(i)}try{let o=KE(e);return!o||o.raw!==t.raw||o.pid!==void 0&&xe(o.pid)?!1:(GE(e),!0)}catch{return!1}finally{JE(n,r)}}function JE(e,t){try{let n=JSON.parse(VE(e,"utf8"));n.pid===process.pid&&n.token===t&&GE(e)}catch{}}function E7(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import{execFileSync as D7}from"child_process";import{createHash as T7}from"crypto";import{realpathSync as L7}from"fs";import{isAbsolute as F7,resolve as XE}from"path";var wd={run(e,t){try{return D7("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}}};function ay(e,t=wd){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?Cd(n):void 0}function zt(e,t=wd){let n=ay(e,t);if(!n)return;let r=t.run(n,["rev-parse","--absolute-git-dir"])?.trim(),i=t.run(n,["rev-parse","--git-common-dir"])?.trim();if(!r||!i)return;let o=Cd(YE(n,r)),s=Cd(YE(n,i)),a=sy(t.run(n,["rev-parse","--verify","HEAD"])),c=sy(t.run(n,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(n,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{projectRoot:n,gitDir:o,commonDir:s,repositoryId:QE("repository",s),worktreeId:QE("worktree",`${n}\0${o}`),headCommit:a,treeOid:c,clean:l.length===0}}function kd(e,t=wd){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:N7(n)}function N7(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:Cd(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 cy(e,t,n=wd){return sy(n.run(e,t))}function YE(e,t){return F7(t)?t:XE(e,t)}function Cd(e){try{return L7(e)}catch{return XE(e)}}function QE(e,t){return T7("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function sy(e){return e?.trim()||void 0}import{lstatSync as K7,readdirSync as J7}from"fs";import{join as Y7,relative as Q7,resolve as yy,sep as X7}from"path";import{createHash as A7}from"crypto";import{existsSync as uy,mkdirSync as _7,readFileSync as Id,readdirSync as b0e,renameSync as M7,rmSync as S0e,writeFileSync as $7}from"fs";import{join as bs}from"path";import{create as eD,fromBinary as tD,toBinary as O7}from"@bufbuild/protobuf";import{deserializeSCIP as Pd,DocumentSchema as dy,IndexSchema as nD,serializeSCIP as rD}from"@c4312/scip";var Ed=1,fc="typescript-scip-fragments";function iD(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=tD(dy,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=rD(eD(nD,{documents:n,externalSymbols:[]})),i=Pd(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Dd(e){let t=bs(e,fc);return{rootDir:t,blobDir:bs(t,"blobs"),generationDir:bs(t,"generations")}}function j7(e){let t=Pd(e.indexBytes);hD(t.metadata,yD(e)),gD(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=O7(dy,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(dD(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=pD(e,r);return mD(e.cacheDir,i),i}function oD(e){let t=Dd(e.cacheDir);if(!uy(py(t,e.generationIdentity)))return j7(e);let n=aD({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 sD(e){let t=aD({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,dD(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=pD(e,[...n.values()]);return mD(e.cacheDir,i),i}function aD(e){let t=Dd(e.cacheDir),n=py(t,e.generationIdentity),r;try{r=fD(Id(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=bs(t.blobDir,`${o.blobHash}.scipdoc`),a=Id(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 cD(e){let t=uD(e);return ly(t.baseIndex,t.completeDocuments,"assembled")}function lD(e){let t=uD(e);return B7(t.deletedAffectedPaths),{completeIndexBytes:ly(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:ly(t.baseIndex,t.affectedDocuments,"affected")}}function uD(e){let t=Pd(e.baseIndexBytes);hD(t.metadata,yD(e)),gD(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=tD(dy,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 ly(e,t,n){let r=rD(eD(nD,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Pd(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function B7(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function dD(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=Dd(e);_7(s.blobDir,{recursive:!0});let a=bs(s.blobDir,`${o}.scipdoc`);if(uy(a)){let c=Id(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`;$7(c,i),M7(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function pD(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:Ed,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function mD(e,t){let n=Dd(e),r=py(n,t.generationIdentity);if(uy(r)){let i=fD(Id(r,"utf8"));if(ZE(i)!==ZE(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}he(r,t,{spacing:2,trailingNewline:!0})}function ZE(e){return ro(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function fD(e){let t=JSON.parse(e);if(t.version!==Ed||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 py(e,t){return bs(e.generationDir,H7(t))}function H7(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${ro(e)}.json`}function gD(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function hD(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 yD(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 A7("sha256").update(e).digest("hex")}import{createHash as W7}from"crypto";import{existsSync as gc,mkdirSync as q7,readFileSync as yc,readdirSync as my,renameSync as U7,rmSync as bD,writeFileSync as V7}from"fs";import{join as En}from"path";var Td=1,vD=64*1024*1024,bc="typescript-scip-overlays";function xD(e){let t=wD(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=hy(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,G7(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Td,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 z7(e.cacheDir,i),i}function RD(e){let t=wD(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(En(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 cD({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function CD(e,t){let n=Sc(e),r=En(n,"generations");if(!gc(r))return;let i=new Set(t.map(gy)),o=new Set;for(let a of my(r).filter(c=>i.has(c))){let c=fy(yc(En(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of my(r))i.has(a)||bD(En(r,a),{force:!0});let s=En(n,"blobs");if(gc(s))for(let a of my(s))o.has(a)||bD(En(s,a),{force:!0})}function wD(e,t){let n=En(Sc(e),"generations",gy(t));if(!gc(n))return null;let r=fy(yc(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function G7(e,t){let n=hy(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=hc(r),o=En(Sc(e),"blobs");q7(o,{recursive:!0});let s=En(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`;V7(a,r),U7(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function z7(e,t){let n=En(Sc(e),"generations",gy(t.generationIdentity));if(gc(n)){let r=fy(yc(n,"utf8"));if(SD(r)!==SD(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}he(n,t,{spacing:2,trailingNewline:!0})}function fy(e){let t=JSON.parse(e);if(t.version!==Td||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(hy(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Sc(e){return En(e,bc)}function gy(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${hc(e)}.json`}function SD(e){return hc(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function hy(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 W7("sha256").update(e).digest("hex")}var vc=1,by="language-indexes",kD=["index.db","index.scip","meta.json"],ID=[by,fc,bc];function Ld(e){let t=[];for(let n of kD)Z7(e,n),t.push(n);for(let n of ID)PD(e,n,t);return{version:vc,files:t.sort()}}function Fd(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(!kD.includes(e)&&!ID.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function Jn(e,t){let n=Fd(t),r=yy(e),i=yy(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${X7}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function PD(e,t,n){let r=Y7(e,t),i;try{i=J7(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()?PD(e,s,n):o.isFile()&&n.push(Fd(s))}}function Z7(e,t){let n=Jn(e,t),r;try{r=K7(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(Q7(yy(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as vy,writeFileSync as xy}from"fs";import{create as xc}from"@bufbuild/protobuf";import{deserializeSCIP as Ry,serializeSCIP as Cy,DocumentSchema as aee,IndexSchema as TD,MetadataSchema as cee,SymbolInformationSchema as lee}from"@c4312/scip";import{readFileSync as eee,writeFileSync as tee}from"fs";import{create as ED}from"@bufbuild/protobuf";import{deserializeSCIP as nee,DocumentSchema as ree,IndexSchema as iee,serializeSCIP as oee,SymbolRole as see}from"@c4312/scip";function DD(e){let t;try{t=nee(eee(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Sy(t);return n.removedDefinitionOccurrences>0&&tee(e,Buffer.from(oee(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Sy(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&see.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ED(ree,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ED(iee,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function LD(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=dee(e),n=pee(e.flatMap(i=>i.documents??[])),r=_D(e.flatMap(i=>i.externalSymbols??[]));return xc(TD,{metadata:t,documents:n,externalSymbols:r})}function FD(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Ry(vy(i))),r=LD(n);return xy(t,Buffer.from(Cy(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ND(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Ry(vy(i))),r=Sy(LD(n));return xy(t,Buffer.from(Cy(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function uee(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(TD,{metadata:xc(cee,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function AD(e,t,n){let r=Ry(vy(e)),i=uee(r,t,n);xy(e,Buffer.from(Cy(i)))}function dee(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 pee(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(aee,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:mee([...r.occurrences,...n.occurrences]),symbols:_D([...r.symbols,...n.symbols]),text:gee(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function mee(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 _D(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(lee,{symbol:r.symbol,documentation:hee([...r.documentation,...n.documentation]),relationships:fee([...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 fee(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 gee(e,t){return e?t?e.length>=t.length?e:t:e:t}function hee(e){return[...new Set(e)]}var Ey=1,OD="SCIP_QUERY_SHARED_CACHE",ky=JSON.stringify({cliVersion:Fe,artifactCatalogVersion:vc,sqliteGenerationStoreVersion:ys,typescriptFragmentStoreVersion:Ed,typescriptOverlayStoreVersion:Td}),zD="manifest.json",KD="shared-cache.json",Dy=[by,fc,bc];function oi(e,t){if(!e.clean||!e.treeOid)return;let n=kc(JSON.stringify({version:Ey,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:ky}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:ky,generationId:n,repositoryCacheDir:uc(e.repositoryId)}}function Rs(e,t,n){if(process.env[OD]==="0")return`${OD}=0`;if(!dc(n))return"explicit cache or database override";if(Dn(t)!==Dn(z(hs(e),"index.db")))return"index database is outside the managed worktree cache"}function Cs(e,t){if(!dc(t))return;let n=zt(e);return n?z(uc(n.repositoryId),"evidence.db"):void 0}function Tn(e,t=!0){let n=Ty(e),r;try{r=wee(Kt(z(n,zD),"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=Jn(n,i.path),s=xee(o);if(!s.isFile()||s.size!==i.size||kc(Kt(o))!==i.sha256)return null}}catch{return null}return r}function Nd(e){let t=Tn(e.snapshot);if(t)return t;if(!xs(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=jD(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Ld(e.sourceCacheDir),i=z(e.snapshot.repositoryCacheDir,"generations");wr(i,{recursive:!0});let o=WD(z(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let p=Jn(e.sourceCacheDir,d),m=Jn(o,d);wc(p,m);let f=Kt(m);s.push({path:d,size:f.byteLength,sha256:kc(f)})}let a=GD(Kt(z(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=Ly(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(jD(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Ey,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,zD),l,{spacing:2,trailingNewline:!0});let u=Ty(e.snapshot);try{if(ii(u)&&!Tn(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;io(u,d),ri(d,{recursive:!0,force:!0})}io(o,u)}catch(d){let p=Tn(e.snapshot);if(p)return p;throw d}return l}finally{ri(o,{recursive:!0,force:!0})}}function Ss(e){let t=Ty(e.snapshot);wr(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=WD(z(e.targetCacheDir,".shared-hydrate-")),Lee(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=Jn(t,c.path),u=Jn(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=Ly(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&AD(Jn(r,c.path),e.manifest.scipProjectRoot,s);if(!xs(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Eee(e.targetCacheDir,r),o=!0,Dee(r,e.targetCacheDir,i),vd({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}`);vs(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&Tee(e.targetCacheDir,i),s}finally{r&&ri(r,{recursive:!0,force:!0}),n.release()}}function JD(e,t,n){let r=Rs(e,n.dbPath,t);if(r)return{kind:"bypassed",reason:r};try{let i=zt(e);if(!i)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!i.clean)return Iy(i,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let o=t.languages??gn(e),s=Ni(e,o,ZD(t)),a=oi(i,s);if(!a)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let c=Tn(a);if(c)return Ss({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:a.generationId};let l=kee(a,e);return l?(c=l.manifest,Ss({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:a.generationId,sourceProjectRoot:l.sourceProjectRoot}):(Iy(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 YD(e,t,n){let r=Rs(e,n.dbPath,t);if(r)return{kind:"bypassed",reason:r};try{let i=zt(e);if(!i)return{kind:"missed",reason:"Git worktree identity is unavailable"};let o=t.languages??gn(e),s=Ni(e,o,ZD(t)),a=oi(i,s);if(!a)return Iy(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=Tn(a);if(c)return xs(n.cacheDir,e,s)?(vs(a,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(Ss({snapshot:a,manifest:c,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:a.generationId});let l=Ad(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"}:xs(n.cacheDir,e,s)?(Nd({snapshot:a,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let u=zt(e);return(u?oi(u,s):void 0)?.generationId===a.generationId}}),vs(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 QD(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(wr(s,{recursive:!0});i()<=o;){if(Tn(e))return{kind:"generation-ready"};let c=Py();try{let l=qD(a,"wx");try{UD(l,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
|
|
915
|
-
`)}finally{HD(l)}return{kind:"owner",release:()=>{try{let u=JSON.parse(Kt(a,"utf8"));u.pid===process.pid&&u.token===c&&wy(a)}catch{}}}}catch(l){if(l.code!=="EEXIST")return{kind:"timeout"};let u=eT(a);if(u&&(u.pid===void 0||!xe(u.pid))){Pee(a,u);continue}await Ree(r)}}return Tn(e)?{kind:"generation-ready"}:{kind:"timeout"}}function vs(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 tT(e.repositoryCacheDir,o,!0),o}function Iy(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 tT(uc(e.repositoryId),s,!1),s}function Cc(e){return kc(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Dn(e.projectRoot),localCacheDir:Dn(e.localCacheDir)}))}function XD(e,t,n=void 0){try{let r=JSON.parse(Kt(z(t,KD),"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=zt(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||Dn(o.projectRoot)!==Dn(s.projectRoot)||o.treeOid!==s.treeOid||Dn(o.localCacheDir)!==Dn(t)||o.ownershipChecksum!==Cc(o))return null;let a=Ad(t);if(!Fee(a?.fingerprint))return null;let c=oi(s,a.fingerprint);if(!c||o.baseGenerationId!==c.generationId||o.activeGenerationId!==c.generationId||!xs(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 wee(e){let t=JSON.parse(e);if(t.version!==Ey||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!==ky||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(Fd(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){wr(VD(t),{recursive:!0});try{MD(e,t,yee.COPYFILE_FICLONE)}catch{MD(e,t)}}function kee(e,t){for(let n of kd(t)){if(Dn(n.path)===Dn(t))continue;let r=hs(n.path),i=Ad(r);if(!(i?.status!=="complete"||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&xs(r,n.path,e.fingerprint))try{return{manifest:Nd({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}),sourceProjectRoot:n.path}}catch{continue}}return null}function Iee(e,t,n){wr(e,{recursive:!0}),he(z(e,KD),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function jD(e){try{let t=Ld(e),n=BD("sha256");for(let r of t.files){let i=Kt(Jn(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 Ad(e){try{return JSON.parse(Kt(z(e,"meta.json"),"utf8"))}catch{return}}function ZD(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function Ty(e){return z(e.repositoryCacheDir,"generations",e.generationId)}function eT(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 Pee(e,t){let n=`${e}.reclaim`,r=Py(),i;try{i=qD(n,"wx")}catch{return!1}try{UD(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
916
|
-
`)}finally{HD(i)}try{let o=eT(e);return!o||o.raw!==t.raw||o.pid!==void 0&&xe(o.pid)?!1:(wy(e),!0)}catch{return!1}finally{try{let o=JSON.parse(Kt(n,"utf8"));o.pid===process.pid&&o.token===r&&wy(n)}catch{}}}function tT(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||!ii(z(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=z(e,"worktrees");wr(i,{recursive:!0}),he(z(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Iee(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Eee(e,t){let n=z(t,".rollback"),r=new Map,i=new Map;wr(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=z(e,a),l=ii(c);r.set(a,l),l&&wc(c,z(n,"stable",a))}for(let a of Dy){let c=z(e,a),l=ii(c);if(l){let u=bee(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,Sd),s=ii(o);return s&&nT(o,z(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function Dee(e,t,n){for(let r of Dy){let i=z(t,r);if(n.managedDirectories.get(r)){let s=z(n.root,"managed",r);wr(VD(s),{recursive:!0}),io(i,s)}let o=z(e,r);ii(o)&&io(o,i)}}function Tee(e,t){for(let i of Dy){let o=z(e,i),s=z(t.root,"managed",i);t.managedDirectories.get(i)?ii(s)&&(ri(o,{recursive:!0,force:!0}),io(s,o)):ri(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=z(e,i);if(!o){ri(s,{force:!0});continue}let a=`${s}.shared-restore-${Py()}`;wc(z(t.root,"stable",i),a),ri(s,{force:!0}),io(a,s)}let n=z(e,Sd);ri(n,{recursive:!0,force:!0});let r=z(t.root,"sqlite-generations");t.generationStoreExisted&&ii(r)&&io(r,n)}function nT(e,t){wr(t,{recursive:!0});for(let n of See(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()?nT(r,i):n.isFile()&&wc(r,i)}}function Lee(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 xs(e,t,n,r=!0,i=!0){try{let o=Ad(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=Ld(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 Cee(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=Ly(t),d=(i?s.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=GD(Kt(Jn(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 Ly(e){try{return $D(vee(e)).href}catch{return $D(Dn(e)).href}}function Fee(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 BD("sha256").update(e).digest("hex")}function Me(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function kr(e=Me()){let t=ut(e),n=Gt(e,t),r=process.env.SCIP_QUERY_INDEX_DB;if(r)return{projectRoot:e,config:t,paths:n,dbPath:r,dbPathSource:"env"};if(Fy(n.dbPath))return{projectRoot:e,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured"};let i=Aee(e,"index.db");return{projectRoot:e,config:t,paths:n,dbPath:i,dbPathSource:"root-fallback",rootFallbackWarning:Oee(i,n.dbPath)}}function ws(e){return kr(e).dbPath}function _d(e,t,n){return Fy(n.dbPath)&&XD(e,n.cacheDir)?{kind:"local-fresh"}:Pn(e,t,n).state==="fresh"?YD(e,t,n):JD(e,t,n)}function rT(e){return!e.startsWith("__")&&!_ee.has(e)}var _ee=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function Mee(){try{return $ee(Me(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function $ee(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s}=kr(e);if(!Fy(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:Cs(e,n),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,coverageContracts:n.coverageContracts,docs:n.docs},c=ei(e);return new Vt(a,c)}function Oee(e,t){let n="unknown time";try{n=Nee(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=Mee();try{return e(t)}finally{t.close()}}function Ny(e,t){return t.concat([e])}function Yn(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 Ay(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 jee(e)}}function jee(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawn as Bee,spawnSync as x$e}from"child_process";var ks=class extends Error{constructor(n,r){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r}label;timeoutMs;timedOut=!0};function iT(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Md(e){return new Promise((t,n)=>{let r=e.maxBuffer??10485760,i=Bee(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 ks(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 oT(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 $d(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 Hee}from"child_process";import{existsSync as Wee,mkdirSync as qee,readFileSync as Uee,renameSync as Vee,writeFileSync as Gee}from"fs";import{dirname as sT,join as zee}from"path";var Od=3,Kee="health-report-cache.json";function My(e,t,n,r=Xee()){let i=Ye(e);return i?{version:Od,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function aT(e,t,n=dT()){let r=lT(e),i=uT(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!Jee(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function cT(e,t,n,r=dT()){let i=lT(e),o={version:Od,keyHash:uT(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(sT(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function lT(e){return zee(sT(e.config.dbPath),Kee)}function uT(e){return Ge(JSON.stringify(e))}function Jee(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Od&&typeof t.keyHash=="string"&&Yee(t.key)&&typeof t.writtenAt=="string"&&Qee(t.report)}function Yee(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Od&&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 Qee(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 Xee(){return{gitHead(e){let t=Hee("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"});return t.status===0?t.stdout.trim():null}}}function dT(){return{existsSync:Wee,mkdirSync:qee,readFileSync:Uee,renameSync:Vee,writeFileSync:Gee,nowIso:()=>new Date().toISOString()}}var Ic="__health-phase",Bd="__diff-impact-batch",ete=10,tte=4,nte=8,rte=25e3,ite=2500,$y=2500,ote=4,ste=12,pT=3e4,fT=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),gT=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),ate=new Set([...gT,"suppressions"]),cte=new Set(["similar","extract-candidates"]),jd=2,mT=xi({kind:"health-semantic-prewarm",invalidation:pe("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:lte});function lte(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==jd||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:jd,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 ute(e){let t=qt(e);return t.symbols>=rte||t.documents>=ite}function Hd(e,t,n,r={}){return ute(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 ${$y} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:$y,semantic:!1,analysisBudget:{scanLimit:$y,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function hT(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var dte={env:process.env,projectFingerprint:Ye,semanticEngineFingerprint:gte,readMarker:(e,t,n)=>mT.read(e,t,n),writeMarker:(e,t,n,r)=>mT.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:xw};function pte(e,t,n=dte){if(t.full!==!0)return si("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return si("disabled");let r=si("error");return D("health.semantic-prewarm",()=>{try{r=mte(e,t,n)}catch(i){r=si("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>hte(r))}function mte(e,t,n){let r=n.projectFingerprint(e);if(!r)return si("missing-project-fingerprint");let i=fte(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return si("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 si("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 si("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:jd,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 fte(e,t){return JSON.stringify({version:jd,cliVersion:Fe,semanticEngineFingerprint:t,scope:e.scope??null})}function gte(e){return Ge(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Li(e.config.projectRoot)}))}function si(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function hte(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 Wd(e){let t=Rte(e),n={...e,phaseTimeoutMs:t??null},r=Ee(p=>{let m=My(p,n,Fe);if(!m)return null;let f=aT(p,m);return f?(f.detectorPrecision=Bh(ds(p),Date.now()),f):null});if(r)return r;let{applicability:i,overview:o}=Ee(p=>({applicability:yte(p,e),overview:lc(p,"overview",e)})),s=new Map;s.set("overview",o);let a=ps.filter(p=>p==="overview"?!1:bte(p,i)?!0:(s.set(p,oo(p)),!1)),c=Ste(a);e.full&&Ee(p=>pte(p,e));let l=await _y(c,Cte(c.length),p=>vte(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=qh(ps.map(p=>s.get(p)));return d.detectorPrecision=Ee(p=>Bh(ds(p),Date.now())),Ee(p=>{let m=My(p,n,Fe);m&&cT(p,m,d)}),d}function yte(e,t){return xl(e,{scope:t.scope})}function bte(e,t){return fT.has(e)?t.react:gT.has(e)?t.vue:!0}function Ste(e){return oT(e,[fT,ate,cte])}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 vte(e,t,n){if(e.length===1)return xte(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??jy(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Md({cliPath:i,command:Ic,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof ks))throw s;return e.map(a=>yT(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function xte(e,t,n){let r=process.argv[1]??jy(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Md({cliPath:r,command:Ic,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof ks))throw o;return yT(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function Rte(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return pT;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?pT:r===0?void 0:r}function yT(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 Cte=vT({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:ote,defaultMaximum:ste});function bT(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 | ${Yn(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: ${Oy(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: ${Oy(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: ${Oy(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(Ite(e),kte(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 Oy(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${wte(t)} score-weighted)`}function wte(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function kte(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 Ite(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 ST(e){let t=Ee(i=>{let o=Vn(i,{base:e.base});return o.note?{kind:"complete",result:is(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:is(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=iT(t.plan.changedFiles,ete),r=await _y(n,Pte(n.length),i=>Tte(i,e));return Gu(t.plan.changedFiles,r)}var Pte=vT({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:tte,defaultMaximum:nte});function vT(e){return(t,n=process.env,r=Zee)=>Ete(t,n,r,e)}function Ete(e,t,n,r){let i=t[r.envKey],o=Dte(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function Dte(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 Tte(e,t){let n=process.argv[1]??jy(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Md({cliPath:n,command:Bd,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function xT(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=Ny,L=(e=>parseInt(e,10)),Ir=(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,Is=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 By(){return S("--json","Output as JSON for programmatic consumption")}function j(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,By()]}function N(e,t=[]){return{category:e,examples:t}}import{execFileSync as iL,spawn as Wne}from"child_process";import{existsSync as uo,mkdirSync as tb,readFileSync as oL,rmSync as qne,writeFileSync as Xd}from"fs";import{homedir as Une}from"os";import{dirname as Zd,isAbsolute as Vne,join as Lc,resolve as Gne}from"path";import{execFileSync as pne}from"child_process";import{createRequire as Lte}from"module";var Fte=Lte(import.meta.url);function RT(e,t=[]){let n=Nte(),r=Vf(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 Nte(){try{return Fte.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Ps,spawnSync as _te}from"child_process";import{existsSync as Ln,mkdtempSync as IT,readFileSync as Mte,readdirSync as $te,rmSync as PT,symlinkSync as Ote,writeFileSync as jte}from"fs";import{tmpdir as ET}from"os";import{join as Nt}from"path";import{spawnSync as Ate}from"child_process";function Pr(e,t=Ate){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}var Bte=3e5,Hte=12;function qy(e,t,n={}){let r=Uy(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Hy(e),batches:[]};let i=Vte(t,r),o=n.timeoutMs??Bte,s=Yte(e,t),a=Hy(e),c=IT(Nt(ET(),"scip-cleanup-verify-")),l=[],u=new Map;try{Ps("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Qte(e,c);for(let d of r)u.set(d.label,wT(d,c,o).rawErrors);for(let d of t.batches){TT(c,d);let p=null;for(let m of r){let f=wT(m,c,o),g=Wte(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,Hte)};break}}if(!p)l.push({depth:d.depth,status:"verified"});else{l.push(p);break}}}finally{try{Ps("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{PT(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 Wte(e,t,n){let r=qte(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 qte(e,t){let n=Ute(e),r=new Map,i=[];for(let o of t){let s=DT(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Ute(e){let t=new Map;for(let n of e){let r=DT(n);t.set(r,(t.get(r)??0)+1)}return t}function Vte(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 DT(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var CT=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Gte=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Uy(e){let t=[];if(Ln(Nt(e,"tsconfig.json"))){let n=Nt(e,"node_modules",".bin","tsc");t.push(Ln(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:CT,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:CT,strength:"reference-aware"})}if(Ln(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=>Ln(Nt(e,n)))){let n=zte();n&&t.push(n)}if(Gte.some(n=>Ln(Nt(e,n)))){let n=Kte(e);n&&t.push(n)}for(let n of Jte(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 zte(){return Pr("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"}:Pr("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Kte(e){let t=Nt(e,"node_modules",".bin","clj-kondo");return Ln(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[..._n],strength:"reference-aware"}:Pr("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[..._n],strength:"reference-aware"}:Pr("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[..._n],strength:"reference-aware"}:null}function Jte(e){let t=[];if(Ln(Nt(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=$te(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||Ln(Nt(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Yte(e,t){let n=new Set(Hy(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Hy(e){let t;try{t=Ps("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 Qte(e,t){for(let n of["node_modules"]){let r=Nt(e,n),i=Nt(t,n);if(Ln(r)&&!Ln(i))try{Ote(r,i,"junction")}catch{}}}function TT(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);Ln(o)&&jte(o,Xte(Mte(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Vy(e,t){for(let n of t)TT(e,n)}function LT(e,t){let n=IT(Nt(ET(),"scip-cleanup-patch-"));try{return Ps("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Vy(n,t),Ps("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Ps("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{PT(n,{recursive:!0,force:!0})}}}function Gy(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 zy(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 Xte(e,t,n={}){let r=e.split(`
|
|
931
|
-
`),i=(n.rust===!0?Zte(e):kt(e)).split(`
|
|
932
|
-
`),o=new Set;for(let s of t){let a=ene(r,s.start),c=nne(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 Zte(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 ene(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 tne=200;function nne(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>tne)break}return n}function wT(e,t,n){let r=_te(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:kT(i)};let o=rne(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(dne),diagnostics:s,parseBasis:o.parseBasis,outputTail:kT(i)}}function rne(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:ine(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:one(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=sne(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:ane(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:cne(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:lne(t),parseBasis:"clj-kondo-json"}:{diagnostics:une(t),parseBasis:"heuristic"}}function ine(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 one(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 sne(e){let t=FT(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 ane(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 cne(e){let t=[];for(let n of e.split(`
|
|
935
|
-
`)){if(!n.trim().startsWith("{"))continue;let r=Wy(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 lne(e){let t=FT(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 une(e){return e.split(`
|
|
936
|
-
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function dne(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 FT(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Wy(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Wy(t.slice(n)):null}function Wy(e){try{return JSON.parse(e)}catch{return null}}function kT(e,t=10){return e.split(`
|
|
937
|
-
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var _T={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"]},mne={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"},fne={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(pr(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=Rne(e,n,t),o=Ky({semantics:i},"typescript"),s=Uy(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:kne(e)}}function ai(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=>Sne(e,c,{hasIndexedGraph:vne(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.`},...gne(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 gne(e){return hne(e).map(t=>{let n=Ky(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${yne(t)} semantic provider`,status:r,evidence:"semantic",reason:bne(t,n)}})}function hne(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of $T(e))t.add(n.language);return[...t].sort((n,r)=>NT(n)-NT(r))}function NT(e){return e==="typescript"?0:1}function yne(e){return e==="typescript"?"TypeScript":"Rust"}function bne(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 Sne(e,t,n){let r=e.indexers.find(u=>u.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=xne(t,n.runtimeProbe),a=Cne(e,t),c=wne(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 ${_T[t].join(", ")} files.`}}}function vne(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function xne(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)??AT(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=MT(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)??AT(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 AT(e){let t=mne[e];return t?ul(t):MT(e)==="regex-only"?"regex":"unavailable"}function MT(e){let t=fne[e],n=t?gx(t):null;return n?.imports??n?.exports??n?.reExports??null}function Rne(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...RT(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Bo(e)}),r}function $T(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ky(e,t){return $T(e).find(n=>n.language===t)}function Cne(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=Ky(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 wne(e,t){let n=new Set(_T[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function kne(e){try{return pne("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as Ine,existsSync as Es,readFileSync as Ds,rmSync as BT,writeFileSync as Yy}from"fs";import{join as co}from"path";var ao="<!-- scip-query:agent-setup:begin -->",qd="<!-- scip-query:agent-setup:end -->",Jy="# scip-query:agent-setup";function Pc(){if(process.stdin.isTTY)return"";try{return Ds(0,"utf-8")}catch{return""}}function Ud(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 Vd(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Pne(e,n),t.gitHook&&Ene(e,n),n}function HT(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return jT(e,"AGENTS.md",t,n),jT(e,"CLAUDE.md",t,n),Dne(e,t,n),n}function Pne(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.",qd].join(`
|
|
939
|
-
`);OT(e,"AGENTS.md",n,t);let r=Es(co(e,"CLAUDE.md"))?Ds(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",qd].join(`
|
|
940
|
-
`);OT(e,"CLAUDE.md",i,t)}function OT(e,t,n,r){let i=co(e,t),o=Es(i)?Ds(i,"utf-8"):"",s;if(o.includes(ao)){let a=new RegExp(`${ao}[\\s\\S]*?${qd}`);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):(Yy(i,s),r.written.push(t))}function jT(e,t,n,r){let i=co(e,t);if(!Es(i)){r.unchanged.push(t);return}let o=Ds(i,"utf-8");if(!o.includes(ao)){r.unchanged.push(t);return}let s=new RegExp(`${ao}[\\s\\S]*?${qd}`),a=o.replace(s,"").replace(/\n{3,}/g,`
|
|
945
|
-
|
|
946
|
-
`).trim();r.removed.push(t),!n.dryRun&&(a.length===0?BT(i,{force:!0}):Yy(i,`${a}
|
|
947
|
-
`))}function Ene(e,t){let n=co(e,".git","hooks");if(!Es(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",Jy,"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(Es(r)){let o=Ds(r,"utf-8");if(o.includes(Jy)){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}}Yy(r,i),Ine(r,493),t.written.push(".git/hooks/pre-commit")}function Dne(e,t,n){let r=co(e,".git","hooks","pre-commit");if(!Es(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Ds(r,"utf-8").includes(Jy)){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||BT(r,{force:!0})}import{createHash as Tne}from"crypto";import{existsSync as zd,mkdirSync as Lne,readFileSync as Kd,readdirSync as Fne,rmSync as WT,writeFileSync as qT}from"fs";import{join as Er}from"path";var Jd=Er(".scipquery","events"),Nne=Er(".scipquery","ledger"),UT="events.jsonl";function VT(e){return Er(e,Nne)}function Qy(e){return Er(VT(e),UT)}function GT(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 zT(e){return Xy(e,"HEAD")}function Xy(e,t){try{let n=Ut(e,["rev-parse","--verify",`${t}^{commit}`]).trim();return/^[0-9a-f]{40}$/.test(n)?n:null}catch{return null}}function KT(e){try{return Ut(e,["status","--porcelain=v1","--untracked-files=all"]).trim()===""}catch{return!1}}function JT(e,t){let n=Qy(e),r=zd(n),i=[...r?YT(n):[],...t];if(i.length>0){let o=Er(e,Jd);Lne(o,{recursive:!0});for(let s of i)Ane(o,s)}r&&_ne(e)}function Ane(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=Tne("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Er(e,`${t.ts}-${r}.json`);try{qT(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Kd(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function _ne(e){WT(Qy(e));let t=Er(VT(e),".gitattributes");if(!zd(t))return;let n=Kd(t,"utf-8").split(`
|
|
950
|
-
`).filter(r=>r.trim()!==`${UT} merge=union`).join(`
|
|
951
|
-
`).replace(/^\n+|\n+$/g,"");n===""?WT(t):qT(t,`${n}
|
|
952
|
-
`)}function Yd(e){let t=[],n=Er(e,Jd);if(zd(n))for(let i of Fne(n).sort()){if(!i.endsWith(".json"))continue;let o=QT(Kd(Er(n,i),"utf-8"));o&&t.push(o)}let r=Qy(e);return zd(r)&&t.push(...YT(r)),Mne(t)}function YT(e){let t=[];for(let n of Kd(e,"utf-8").split(`
|
|
953
|
-
`)){let r=QT(n);r&&t.push(r)}return t}function QT(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return One(t)?t:null}function Mne(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||Gd(n)>Gd(i)||Gd(n)===Gd(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 Gd(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var $ne=["caught","resolved","suppressed","reopened"];function One(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"&&$ne.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 Qd(e,t,n={}){let r=(n.now??Date.now)(),i=Bne(t),o=ds(e),s=e.config.projectRoot,a=(n.headCommit??zT)(s),c=(n.resolveCommit??Xy)(s,t.base),l=jne({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),u=GP(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=GT(o,u,d,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??JT)(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 jne(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??Yd)(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??KT)(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=Hne(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 Bne(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 Hne(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 sL="SCIP_QUERY_SKIP_HOOK_INSTALL",Zy="SCIP_QUERY_STOP_HOOK_MODE",zne="scip-query hook-",Kne="scip-query diff-gate --hook",XT="# scip-query:local-hooks:begin",ZT="# 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 Ts(e,t={}){let n=aL(),r=t.env??process.env;if(Xne(r))return n.skipped.push({target:"project agent hooks",reason:`${sL}=1`}),n;let i=ore(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Yne(e,n,t.dryRun),t.remove?(tL(e,Tc[0],n,{dryRun:t.dryRun}),tL(e,Tc[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(eL(e,Tc[0],n,{provider:"codex",commandPrefix:i,force:t.force}),eL(e,Tc[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Jne({homeDir:t.homeDir,result:n}),n)}function Jne(e={}){let t=e.result??aL(),n=e.homeDir??Une();return eb({configPath:Lc(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),eb({configPath:Lc(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function aL(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function eL(e,t,n,r){if(nb(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);ere({provider:r.provider,rootDir:Zd(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function tL(e,t,n,r){if(nb(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}tre({configPath:Lc(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Yne(e,t,n=!1){let r=Qne(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=>!nb(e,u.relativePath));if(i.length===0)return;let o=[XT,...i.map(u=>`/${u.relativePath}`),ZT].join(`
|
|
954
|
-
`),s=uo(r)?oL(r,"utf-8"):"",a=new RegExp(`${J(XT)}[\\s\\S]*?${J(ZT)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
|
|
955
|
-
|
|
956
|
-
`:""}${o}
|
|
957
|
-
`;!n&&l!==s&&(tb(Zd(r),{recursive:!0}),Xd(r,l)),t.gitExcluded.push(...i.map(u=>u.label))}function Qne(e){try{let t=iL("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Vne(t)?t:Gne(e,t):null}catch{return null}}function nb(e,t){try{return iL("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Xne(e=process.env){let t=e[sL];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Zne(e=process.env){let t=e[Zy]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function ere(e){if(!e.createRoot&&!uo(e.rootDir))return;let t=rb(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=nre(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=uo(e.configPath);tb(Zd(e.configPath),{recursive:!0}),Xd(e.configPath,`${JSON.stringify(n,null,2)}
|
|
958
|
-
`),e.result[r?"updated":"installed"].push(e.label)}function eb(e){if(!uo(e.configPath))return;let t=rb(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=cL(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?qne(e.configPath,{force:!0}):Xd(e.configPath,`${JSON.stringify(o,null,2)}
|
|
959
|
-
`)),e.result.removed.push(e.label)}function tre(e){let t=e.result.removed.length;if(eb(e),!e.writeDeclinedTombstone)return;let n=rb(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(tb(Zd(e.configPath),{recursive:!0}),Xd(e.configPath,`${JSON.stringify(r,null,2)}
|
|
960
|
-
`)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function rb(e,t,n){if(!uo(e))return{};try{let r=JSON.parse(oL(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 nre(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]=[...cL(s),ire(t,o,n)]}return i}function cL(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!rre(n)):[]})).filter(t=>t.hooks.length>0)}function rre(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(zne)||t===Kne)}function ire(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 ore(e){let t=Lc(e,"node_modules",".bin","scip-query");return uo(t)?t:"scip-query"}async function lL(){let e=await lre(Pc());e&&console.log(JSON.stringify(e))}function sre(e){if(Ud(e))return;let t=dL(e),n=pL(t);if(!(!n||!uo(n.paths.dbPath)))return bre(n,r=>{let i={minTogether:6,skip:[]},o=eo(r,i),s=Qd(r,o,{replayGate:a=>eo(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function uL(){let e=sre(Pc());!e||e.findings.length===0||console.log(JSON.stringify(are(e,Zne())))}function are(e,t="feedback"){let n=Ec(e),r=cre(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 ${Zy}=feedback to ask the agent to continue without a hook error, or ${Zy}=block to enforce the gate.`}}function cre(e){return Ec(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function lre(e){let t=dL(e),n=yre(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=pL(t);if(!r)return;let i=await dre(r,n),o=n==="SessionStart"?mre(r.projectRoot,r.config,r.paths):fre(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
|
|
965
|
-
`);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var ure={prepare:_d,ensureService:su,freshness:Pn,requestRefresh:mC,startOneShot(e){Wne("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function dre(e,t,n=ure){let r=Kn(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}).`:(pre(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 pre(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(mr(n).activityPath,`agent hook observed ${t} index while service was idle`)}function mre(e,t,n){let r=Pn(e,t,n),i=bn(e,t),s=ai(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 fre(e,t={},n=process.env){if(hre(t,n)==="off")return"";let r=gre(e);return r?`scip-query routing reminder:
|
|
967
|
-
${r.message}`:""}var nL=[{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 gre(e){let t=nL.find(i=>i.skillNames.some(o=>rL(e,o)));if(t)return t;let n=0,r=[];for(let i of nL){let o=i.keywords.filter(s=>rL(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function hre(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function rL(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 dL(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function yre(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function pL(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=ay(t);if(n)try{let r=ut(n),i=Gt(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function bre(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:Cs(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 Vt(n,ei(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as tp,mkdirSync as wre,symlinkSync as kre,readlinkSync as sb,unlinkSync as ab,readdirSync as bL}from"fs";import{join as Qn,dirname as Ac,resolve as ci,relative as Ire,isAbsolute as Pre}from"path";import{homedir as np,platform as Ere}from"os";import{fileURLToPath as SL}from"url";import{execFileSync as mL}from"child_process";import{createRequire as Sre}from"module";import{existsSync as vre}from"fs";import{platform as Fc,arch as fL}from"os";var gL="v0.8.1",ib="https://github.com/sourcegraph/scip",hL="SCIP_QUERY_SCIP_BIN";function xre(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[hL];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 Rre(e){let t=Sre(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 ep(e=process.env){return xre({platform:Fc(),arch:fL(),env:e,isOnPath:On,fileExists:vre,resolveSidecar:Rre})?.path??null}function Nc(){return ep()!==null}function Cre(){let e=Fc(),t=fL(),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:`${ib}/releases/download/${gL}/${o}`,filename:o}}function ob(){let e=Cre();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 ${hL} to a local scip.exe path.
|
|
969
|
-
`),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
970
|
-
`:` ${ib}/releases/tag/${gL}
|
|
971
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function yL(e){if(Fc()==="darwin"&&On("brew")){e("Installing scip CLI via Homebrew...");try{if(mL("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),On("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(On("go")){e("Installing scip CLI via go install...");try{if(mL("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),On("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: ${ib}/releases`),!1}var Dre=Ere()==="win32",rp=["_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 ip(e={}){let t=e.quiet?()=>{}:console.log,n=SL(import.meta.url),r=ci(Ac(n),"..","skills"),i=[Qn(np(),".claude","skills"),Qn(np(),".codex","skills"),Qn(np(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Ac(s);if(!tp(a))continue;wre(s,{recursive:!0});let c=RL(s);Tre(s,r,c,o,t);for(let l of rp){let u=Qn(r,l),d=Qn(s,l);if(!tp(u)){o.skipped.push(`${c}/${l}`);continue}if(tp(d)){try{let p=sb(d);if(ci(p)===ci(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}ab(d)}kre(u,d,Dre?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Tre(e,t,n,r,i){let o=new Set(rp);for(let s of bL(e)){if(o.has(s))continue;let a=Qn(e,s),c;try{c=ci(Ac(a),sb(a))}catch{continue}xL(c,t)&&(ab(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function vL(e={}){let t=SL(import.meta.url),n=ci(Ac(t),"..","skills"),r=e.homeDir??np(),i=[Qn(r,".claude","skills"),Qn(r,".codex","skills"),Qn(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!tp(s))continue;let a=RL(s);for(let c of bL(s)){let l=Qn(s,c),u;try{let d=sb(l);u=ci(Ac(l),d)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!xL(u,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{ab(l)}catch(d){o.skipped.push(`${a}/${c} (${d instanceof Error?d.message:String(d)})`)}}}return o}function xL(e,t){let n=Ire(ci(t),ci(e));return n===""||!n.startsWith("..")&&!Pre(n)}function RL(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as cA}from"child_process";import{performance as mi}from"perf_hooks";import{existsSync as Nn,readFileSync as Xce,renameSync as Zce,rmSync as ele,unlinkSync as tle,writeFileSync as nle}from"fs";import{dirname as Dp,extname as rle,join as go,resolve as ile}from"path";import{execFileSync as Tse}from"child_process";import{createHash as Lse}from"crypto";import{closeSync as Fse,copyFileSync as hp,existsSync as Fn,mkdirSync as gp,mkdtempSync as Nse,openSync as Ase,readdirSync as _se,readFileSync as yp,renameSync as GF,rmSync as di,statSync as Mse,writeFileSync as $se}from"fs";import{basename as fp,dirname as we,extname as Ose,join as mt,resolve as jF}from"path";import{platform as jse}from"os";import Lre from"better-sqlite3";import{execFileSync as Fre}from"child_process";import{existsSync as Nre,readdirSync as Are,readFileSync as _re}from"fs";import{extname as op,join as CL}from"path";function po(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>sp({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function sp(e){let t=new Set((e.extensions??Fv).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Nre(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=ei(e.projectRoot),r=Mre(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Lre(e.dbPath);try{let o=Ore(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=_re(CL(e.projectRoot,p),"utf-8"),f=s.run(jre(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 Mre(e,t){let n=$re(e,t);if(n)return n;let r=[],i=o=>{let s=o?CL(e,o):e,a;try{a=Are(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(op(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function $re(e,t){try{return Fre("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
973
|
-
`).filter(r=>r&&t.has(op(r).toLowerCase())).sort()}catch{return null}}function Ore(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 jre(e){return op(e).toLowerCase()===".vue"?"vue":op(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Bre}from"crypto";import{appendFileSync as Hre,existsSync as Wre,mkdirSync as qre,readFileSync as Ure}from"fs";import{dirname as EL,join as wL}from"path";var Vre="<global-symbols>";function Gre(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:cb(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:cb(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:Vre,kind:"global-symbol",values:cb(n)});return zre(t)}function zre(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=Bre("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 Kre(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 lb(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 ub(e,t=Jre){let n=t.now();if(!t.databaseExists(e.previousDbPath))return ap(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return ap(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=yu(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!Zf(s).fullProject&&s.changes.every(p=>a.has(p.path)),l=bu(s,c?t.dependencyGraph(r):new Map,o),u=Kre(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:lb(l,u,o.length)}}catch(o){return ap(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{kL(r),kL(i)}}function DL(e,t,n,r=Date.now()){return ap(e,t,r,r,n)}function TL(e){let t=EL(e);return{latestPath:wL(t,"affected-shadow-latest.json"),historyPath:wL(t,"affected-shadow.jsonl")}}function LL(e,t=n=>Ure(n,"utf-8")){let n=TL(e),r;try{r=JSON.parse(t(n.latestPath))}catch(y){let x=eie(y),R=x?"telemetry-missing":Zre(y);return li(n,R,x?void 0:y instanceof Error?y.message:String(y))}if(ee(r)&&typeof r.version=="number"&&r.version!==1)return li(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Qre(r))return li(n,"telemetry-malformed");if(r.status==="unavailable")return Xre(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:li(n,"telemetry-malformed");if(r.status!=="evaluated")return li(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!ee(r.manifest)||!ee(i)||!ee(o)||!ee(s))return li(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"||!IL(f)||!IL(g))return li(n,"telemetry-malformed");let h=p.length===0?1:(p.length-m.length)/p.length;return!PL(c,d)||!PL(u,p)||s.passed!==(m.length===0)||Math.abs(f-h)>Number.EPSILON||m.some(y=>!p.includes(y)||d.includes(y))?li(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 FL(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 NL(e,t,n=Yre){let r=TL(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function cb(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 Jre={now:()=>Date.now(),databaseExists:e=>Wre(e),openDatabase:(e,t,n)=>new Vt({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>q(e),dependencyGraph:e=>ge(e),factDigests:e=>Gre(e)},Yre={appendHistory:(e,t)=>{qre(EL(e),{recursive:!0}),Hre(e,`${JSON.stringify(t)}
|
|
1031
|
-
`)},writeLatest:(e,t)=>he(e,t,{spacing:2,trailingNewline:!0})};function ap(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 kL(e){try{e?.close()}catch{}}function Qre(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 Xre(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function IL(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function PL(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function li(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Zre(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function eie(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as tie}from"crypto";import{copyFileSync as nie,existsSync as AL,rmSync as _L}from"fs";import{resolve as rie}from"path";import OL from"better-sqlite3";var iie={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}]},oie={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 jL(e){let t=Date.now(),n=sie(e.affectedFiles);if(aie(e.previousDbPath,e.miniDbPath,e.candidateDbPath),_L(e.candidateDbPath,{force:!0}),!AL(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!AL(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ML(e.previousDbPath,"previous SQLite generation",!1),ML(e.miniDbPath,"incremental SQLite mini database"),nie(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new OL(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),db(r,"main","candidate SQLite generation"),db(r,"incremental","incremental SQLite mini database"),cie(r,n),lie(r,n.length);let i=pb(r,"main",!0),o=ui(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{uie(r),die(r),pie(r),e.onStage?.("after-delete"),mie(r),e.onStage?.("after-symbol-reconciliation"),fie(r),e.onStage?.("after-insert"),gie(r),hie(r,n.length,o),e.onStage?.("before-commit")}).immediate(),BL(r,"main","candidate SQLite generation");let c=[...yie(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{_L(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function sie(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 aie(e,t,n){let r=[e,t,n].map(i=>rie(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ML(e,t,n=!0){let r=new OL(e,{readonly:!0,fileMustExist:!0});try{db(r,"main",t),n&&BL(r,"main",t)}finally{r.close()}}function db(e,t,n){for(let[r,i]of Object.entries(iie)){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(oie)){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}`)}$L(e,t,"documents",["relative_path"],n),$L(e,t,"global_symbols",["symbol"],n)}function $L(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 BL(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 cie(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 lie(e,t){let n=ui(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=ui(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 uie(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 die(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 pie(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 mie(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 fie(e){let t=ui(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=ui(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=ui(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 gie(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 hie(e,t,n){let r=ui(e,"SELECT COUNT(*) AS value FROM main.documents"),i=ui(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 yie(e){let t=pb(e,"main",!0),n=pb(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 pb(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=tie("sha256");for(let m of d.sort())p.update(m).update(`
|
|
1201
|
-
`);l.set(u,p.digest("hex"))}return l}function ui(e,t){return e.prepare(t).get().value}import{readFileSync as bie,writeFileSync as Sie}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 WL(e){let t=e.readFingerprint(),n=vie(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return xie(e.cachePath,e.readFingerprint(),r),r}function vie(e,t){try{let n=JSON.parse(bie(e,"utf-8"));return HL(n.fingerprint)===HL(t)?{result:n.result}:null}catch{return null}}function xie(e,t,n){Sie(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
1202
|
-
`)}function HL(e){return JSON.stringify(e)}import{createHash as Rie}from"crypto";import{existsSync as mb,readFileSync as Cie,readdirSync as wie}from"fs";import{dirname as fb,join as cp,relative as kie,resolve as gb,sep as qL}from"path";function UL(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=KL(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function VL(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=KL(a,e);c&&c!==i&&s.add(c)}}return Iie(e,r)}function GL(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 hb(e){if(e===".")return"root";let t=Rie("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function zL(e,t){let n=gb(e),r={};for(let i of t)r[i]=Pie(n,i);return r}function KL(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 Iie(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 Pie(e,t){let n=t==="."?e:cp(e,t),r=Eie(n),i=Die(n),o=i?Tie(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 Eie(e){let t=cp(e,"package.json");if(!mb(t))return{name:void 0,dependencyNames:[],failed:!1};let n=yb(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 Die(e){let t=cp(e,"tsconfig.json");if(mb(t))return t;let n;try{n=wie(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?cp(e,n[0]):void 0}function Tie(e,t){let n=yb(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Lie(n.value,e,t),i=JL(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Lie(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=fb(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=YL(a,i,n);c&&o.add(c)}return[...o]}function JL(e,t,n,r){let i=Fie(t);if(i)return{pathsTargets:Nie(i,fb(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Aie(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=yb(o);return s.ok?JL(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Fie(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 Nie(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=YL(o,t,n);s&&r.add(s)}return[...r]}function Aie(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=gb(fb(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(qL).includes("node_modules")&&en(n,i)&&mb(i))return i}function YL(e,t,n){let r=e.replace(/\/?\*+$/,""),i=gb(t,r===""?".":r);if(!en(n,i))return;let s=kie(n,i).split(qL).join("/");return s===""?".":s}function _ie(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 yb(e){try{let t=Cie(e,"utf-8"),n=JSON.parse(_ie(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Mie,readFileSync as $ie,readdirSync as Oie,statSync as jie}from"fs";import pt from"path";var Bie=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=>Wie(n,c));if(r.length>0)return QL(n,XL(r));let i=Hie(n),o=XL(i),s=Uie(n,o)?[n,...o]:o,a=s.length>0?s:[n];return QL(n,a)}function QL(e,t){return[...new Set(t.map(n=>Gie(e,n)))].sort((n,r)=>n.localeCompare(r))}function Hie(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Oie(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=pt.join(r,o.name);if(o.isDirectory()){!Bie.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&qie(s)&&t.push(pt.dirname(s))}}return t}function Wie(e,t){let n=t.trim();if(!n)return[];let r=pt.resolve(e,n);if(!en(e,r))return[];try{let i=jie(r);if(i.isDirectory())return[r];if(i.isFile()&&ZL(pt.basename(r)))return[pt.dirname(r)]}catch{return[]}return[]}function qie(e){if(!ZL(pt.basename(e)))return!1;let t=eF(e);return t?pt.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ZL(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function XL(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&&zie(n,r)))}function Uie(e,t){if(t.length===0||t.some(r=>pt.resolve(r)===e))return!1;let n=pt.join(e,"tsconfig.json");return Mie(n)&&Vie(n)}function Vie(e){let n=eF(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 eF(e){try{let t=JSON.parse($ie(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Gie(e,t){let n=pt.relative(e,t);return n?n.split(pt.sep).join("/"):"."}function zie(e,t){let n=pt.relative(e,t);return!!n&&!n.startsWith("..")&&!pt.isAbsolute(n)}import{createHash as foe}from"crypto";import{existsSync as vb,readFileSync as pF,statSync as goe,writeFileSync as xb}from"fs";import{join as hoe}from"path";import{readFileSync as tF}from"fs";import{createRequire as Kie}from"module";import{dirname as Jie,isAbsolute as Kje,relative as Jje,resolve as Yje,sep as Qje}from"path";var nF=Kie(import.meta.url),Yie=1,rF="0.4.0";function bb(){let e=Qie();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Qie(){try{let e=nF.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(tF(e,"utf8"));if(t.version!==rF)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${rF}`};let n=Jie(e),r=nF.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(tF(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:Xie(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Xie(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Yie}`}import{createHash as Zie}from"crypto";import{readFileSync as eoe}from"fs";import{dirname as toe,join as lp}from"path";var up=2,noe="typescript-index";function iF(e){let t=lp(e,noe);return{rootDir:t,requestDir:lp(t,"requests"),responseDir:lp(t,"responses")}}function oF(e){try{let t=JSON.parse(eoe(lp(toe(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Zie("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 roe}from"crypto";import{existsSync as ioe,mkdirSync as sF,readFileSync as ooe,rmSync as aF}from"fs";import{resolve as Sb}from"path";var soe=12e4,aoe=5,dp=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Sb(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??poe(),this.runtime=n.runtime??moe}request(t){let n=mr(this.cacheDir),r=iF(this.cacheDir),i=Oi(n.statePath);if(!cF(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=Sb(r.requestDir,`${o}.json`),a=Sb(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;sF(r.requestDir,{recursive:!0}),sF(r.responseDir,{recursive:!0}),he(s,{protocolVersion:up,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(ioe(a))return coe(ooe(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Oi(n.statePath);if(!cF(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(aoe)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{aF(s,{force:!0}),aF(a,{force:!0})}}};function cF(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===up&&n.isProcessAlive(e.pid)&&(r||i)}function coe(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==up||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=loe(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 loe(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(uoe)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:doe(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 uoe(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 doe(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function poe(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:soe}var moe={now:Date.now,randomId:roe,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xe};function yoe(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=yu(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=bu(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=boe([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=lF(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=lF(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=dF(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=dF(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:uF(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:uF(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 boe(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 mF(e){let t=Date.now();try{if(!vb(e.previousDbPath)||!vb(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=bb();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Vt({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=yoe({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:vb(hoe(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let u=oF(e.previousDbPath);if(!u)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new dp({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=goe(e.previousShardPath).size>=vD;n=performance.now();let g=f?null:pF(e.previousShardPath),h=f?{completeIndexBytes:null,affectedIndexBytes:iD(p.fragments)}:lD({packageVersion:r.packageVersion,baseIndexBytes:g,fragments:p.fragments}),y=performance.now()-n;n=performance.now(),f?xD({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(oD({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:g,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),sD({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&&xb(e.candidateShardPath,h.completeIndexBytes),xb(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 fF(e){let t=bb();if(!t.available)throw new Error(t.reason);let n=RD({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:pF(e.baseShardPath),packageVersion:t.packageVersion});xb(e.candidateShardPath,n)}function lF(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 Rb(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function uF(e,t){return Rb(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function dF(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=Go({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,Rb(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Rb(e){return foe("sha256").update(e).digest("hex")}import{execFile as Soe}from"child_process";import{existsSync as pp,renameSync as wb,rmSync as kb,statSync as voe}from"fs";import{cpus as xoe}from"os";import{join as gF}from"path";function Roe(e,t,n){if(!e.defaultOutputPath)return;let r=gF(t,e.defaultOutputPath);n!==r&&pp(r)&&wb(r,n)}function Coe(e,t,n){if(!e.defaultOutputPath)return null;let r=gF(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return kb(i,{force:!0}),pp(r)?(wb(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function woe(e){e&&(kb(e.defaultOutputPath,{force:!0}),e.backupPath&&pp(e.backupPath)&&wb(e.backupPath,e.defaultOutputPath))}function koe(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,xoe().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function hF(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=koe(o.length,r),c=await Poe(o,a,l=>Cb(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 Cb(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 Cb(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function Cb(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),kb(e.scipPath,{force:!0});let r=Coe(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await Ioe(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Roe(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{woe(r)}if(!pp(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=voe(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 Ioe(e,t,n){return new Promise((r,i)=>{Soe(e,[...t],n,o=>{o?i(o):r()})})}async function Poe(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 cse from"better-sqlite3";import{existsSync as lse}from"fs";import{dirname as use,join as dse,resolve as pse}from"path";import{readFileSync as Doe,rmSync as Toe,statSync as Loe,mkdtempSync as Foe}from"fs";import{tmpdir as Noe}from"os";import{join as Ib}from"path";import{Worker as Aoe}from"worker_threads";function Eoe(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Ls(){return{skippedReferences:0,skippedReferenceReasons:Eoe(),skippedReferenceSamples:[]}}function mp(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 yF(e){return e.length>=8&&SF(e.length)>1}function bF(e){let t=SF(e.vueFiles.length),n=Moe(e.vueFiles),r=Ooe(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Foe(Ib(Noe(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=_oe(),l=Date.now();try{for(let p=0;p<r.length;p++)new Aoe(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[p],resultPath:Ib(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(Doe(Ib(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),...Ls()};for(let p of u)mp(d,p);return d}finally{Toe(o,{recursive:!0,force:!0})}}function SF(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 _oe(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Moe(e){let t=$oe(),n=[];for(let r of e){let i=vF(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 $oe(){return Number.POSITIVE_INFINITY}function Ooe(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:joe(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 joe(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,vF(e.fileName)-e.startOffset)}function vF(e){try{return Loe(e).size}catch{return 1}}import{createRequire as Boe}from"module";import{existsSync as Hoe,readFileSync as Eb}from"fs";import{dirname as xF,extname as Woe,join as RF,relative as qoe,resolve as Uoe}from"path";import{pathToFileURL as Voe}from"url";function Goe(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 CF(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=>Uoe(t,r.relativePath))}function wF(e,t){let{vueCore:n,ts:r,volarTs:i}=zoe(e),{parsed:o,vueOptions:s}=Koe(n,r,t),a=xF(t),c=n.createVueLanguagePlugin(r,o.options,s,m=>m),l=Joe(n,r,c),u=Yoe(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 zoe(e){let t=Boe(Voe(RF(e,"package.json")).href);return{vueCore:Pb(t,"@vue/language-core",e),ts:Pb(t,"typescript",e),volarTs:Pb(t,"@volar/typescript",e)}}function Koe(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,xF(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Joe(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Hoe(o))return;let s=Eb(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??nse(o))});return r.current=i,i}function Yoe(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Pb(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 kF(e,t,n){let r=Qoe(e);return i=>{if(!i.name)return null;let o=Dr(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:Xoe(c.starts,a.line,2,i.name)}}function Qoe(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 Xoe(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 IF(e,t,n){let r=ose(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=Dr(t,l),d=_F(r.name,r.version,u);o.run(d,"default",7,`Vue component|${u}`);let p=sse(i,r,t,l);p&&(s++,a.set(l,p))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function PF(e,t,n,r,i){return e.transaction(()=>(Goe(e),Zoe(e,t,n,r),ese(e,i)))()}function Zoe(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=Dr(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 EF(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(Db(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function DF(e){let t=new Set,n=[];for(let r of e){let i=TF(r);t.has(i)||(t.add(i),n.push(r))}return n}function TF(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function ese(e,t){let n=ise(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=TF(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*LF(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 FF(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Db(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function tse(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 NF(e,t){return Dr(e,t).startsWith("node_modules/")}function Dr(e,t){return qoe(e,t).replaceAll("\\","/")}function nse(e){switch(Woe(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 AF(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Eb(t,"utf-8"),r={text:n,lineStarts:rse(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:tse}}function rse(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ise(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 ose(e){try{let t=JSON.parse(Eb(RF(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 sse(e,t,n,r){let i=Dr(n,r),o=_F(t.name,t.version,i);return e.get(o)?.id??null}function _F(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function $F(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>mse({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Fb(e){return mo(po(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),mo($F({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function mse(e){let t=pse(e.projectRoot,e.tsconfig);if(!lse(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new cse(e.dbPath);try{let r=CF(n,e.projectRoot),i=dse(use(e.dbPath),"augment-vue-meta.json");return WL({cachePath:i,readFingerprint:()=>hse(n,e.projectRoot,e.tsconfig),compute:()=>fse({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 fse(e){let t=IF(e.db,e.projectRoot,e.vueFiles),n=gse(e,t),r=DF(n.occurrences),i=PF(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:kse(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:wse(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function gse(e,t){if(yF(e.vueFiles))return bF({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=yse({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return bse({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function hse(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:Fi(t),db:r}}function yse(e){let t=AF();return{projectRoot:e.projectRoot,context:wF(e.projectRoot,e.configPath),symbolLookup:kF(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function bse(e){let t=[],n=Ls(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Sse(e,i);t.push(...o.occurrences),mp(n,o)}return{occurrences:t,...n}}function Sse(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return MF(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 MF(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Dr(e.projectRoot,t.fileName),a=[...LF(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:Pse(a),processedStarts:new Set};return vse({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function vse(e){let t=[],n=Ls();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||xse(e.sourceInfo.text,r.start))continue;let i=FF(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!NF(e.projectRoot,u.fileName));if(!s){Tb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Dr(e.projectRoot,s.fileName),c=Rse(e.sourceFile,r.text,a);if(c){Tb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=EF(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Tb(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}OF(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),Ise(t,e,r,i,a,l)}return{occurrences:t,...n}}function xse(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 Rse(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function MF(e,t,n){let r=Ls();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Dr(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Tb(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 Lb(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 Cse(e,t){let n=Lb(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=Lb(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function wse(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(...Lb(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function kse(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Cse(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Ise(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of Ese(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&&(OF(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function OF(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 Pse(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Ese(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=Dse(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function Dse(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Db(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Fs(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Hse(e),s=Date.now();gp(we(o.outputScip),{recursive:!0}),gp(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",()=>vae(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,u;if(e.skipIfUnchanged!==!1&&!Rs(t,o.outputDb)&&jF(o.outputScip)===jF(mt(we(o.outputDb),"index.scip"))){let f=zt(t);if(l=f?oi(f,c):void 0,l){let g=Tn(l);if(g){if(!Bse(o,c))try{Ss({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: ${Ab(h)}`)}}else{let h=await QD(l);if(h.kind==="owner")u=h.release;else if(h.kind==="generation-ready"){let y=Tn(l);if(y)try{Ss({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: ${Ab(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 Us("reindex.lock",()=>mae(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=Wse({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),f),()=>({languages:a.length,reused:f!==null}));if(g)return BF({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),g;await Us("reindex.scip-cli-ready",()=>oae(i,r));let h=Use(o);m=h.runDir;let y,x=await Us("reindex.fresh",async()=>(y=await Vse({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 BF({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(f){throw nN(o.metaPath,Sp({trigger:e.trigger,result:"failed",start:s,error:f instanceof Error?f.message:String(f)})),f}finally{m&&di(m,{recursive:!0,force:!0}),p(),d.release(),u?.()}}function BF(e){if(e.snapshot){if(Tn(e.snapshot)){vs(e.snapshot,we(e.paths.outputDb),"local-fresh");return}try{let t=zt(e.projectRoot),n=t?oi(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}Nd({snapshot:e.snapshot,sourceCacheDir:we(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=zt(e.projectRoot);return(r?oi(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),vs(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: ${Ab(t)}`)}}}function Bse(e,t){if(!Fn(e.outputScip)||!Fn(e.outputDb)||!tN(e.metaPath,t))return!1;let n=hn(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ab(e){return e instanceof Error?e.message:String(e)}function Hse(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 Wse(e){let t=hn(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Fn(e.paths.outputScip)||!Fn(e.paths.outputDb)||!tN(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=Sp({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return nN(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:qse(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function qse(e,t,n,r){let i=ZF(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Mc(i[o]),outputBytes:$c(Mb(e.outputDb,o)),durationMs:0}))}function Use(e){let t=Nse(mt(we(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:mt(t,fp(e.outputScip)),tempOutputDb:mt(t,fp(e.outputDb)),tempMetaPath:mt(t,fp(e.metaPath))}}async function Vse(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Us("reindex.language-indexers",async()=>(n=await zse(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(", ")}`),Gse({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let m=D("reindex.publish",()=>nae(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",()=>tae(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 Gse(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Fn(e.run.paths.outputScip)||!Fn(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 zse(e,t){let n=Xse({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?mF({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:_b(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,d=new Set(u?["typescript"]:[]),p=u?void 0:Kse(e,n),{preparedRuns:m,skippedLanguages:f,languageOutputScipPaths:g}=sae({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 hF(h,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(p){Yse(e.paths.outputDb,y);let k=g.typescript??e.tempPaths.tempOutputScip;x=Qse({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:k,reusedProjects:p.reusedProjects})}let R=[...y,...x],{indexedOutputs:b}=cae(R,f),v=u?[{language:"typescript",scipPath:u.scipPath}]:[],w=[...r,...v,...b];lae(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=Zse(n,[...y,...I],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:w,skippedLanguages:f,reusedLanguages:[...i],languageFingerprints:eae(n,e.languages),shards:C,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:u??void 0}}function Kse(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=zL(e.projectRoot,r),o=UL(n.fingerprint.files,r),s=VL(r,i),a=GL(r,o,s),c=jc(e.paths.metaPath),u=Jse(c,a,f=>Fn(bp(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 Jse(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(Tr(s)!==Tr(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 Yse(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=bp(e,r);gp(we(i),{recursive:!0}),hp(n.scipPath,i)}}function Qse(e){return e.reusedProjects.map((t,n)=>{let r=bp(e.outputDb,t),i=Oc(e.tempOutputScip,"typescript-project-cached",n);return hp(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 Xse(e){let t=jc(e.paths.metaPath),n=ZF(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Mb(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(!Fn(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(Tr(a)!==Tr(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 Zse(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(bp(n.outputDb,i)),durationMs:0});return r}function Mc(e){return Lse("sha256").update(Tr(e)).digest("hex").slice(0,16)}function $c(e){try{return Mse(e).size}catch{return null}}function eae(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function tae(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(HF(e.paths.outputDb,n),l=WF(n,e.tempPaths.tempOutputScip,e.onStatus));let u=uae({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..."),fF({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 HF(e.paths.outputDb,x),l=WF(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 Vt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),R=new Vt({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let b=QC(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=_b(e.paths.metaPath),p=u.mode==="incremental"&&a?pae(a,u.changedDocumentPaths):ub({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=Sp({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}=KF({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:g,typescriptProjectShardContext:s,lastRefresh:m});return h.scipCompanion=f?"deferred":"current",JF(e.paths.outputDb,y),$b(e.tempPaths.tempMetaPath,h),vd({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}:{}}}),CD(we(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),zF(e.paths.outputDb,p,e.onStatus),m}function nae(e,t,n,r,i,o){let s=_b(e.paths.metaPath),a=null;try{hp(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(d){a=DL("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??=ub({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=Sp({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(d=>d.language),skipped:[...n]}),{metadata:l,pruneProjects:u}=KF({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return JF(e.paths.outputDb,u),$b(e.paths.metaPath,l),BE(e.paths.outputDb,e.paths.metaPath),zF(e.paths.outputDb,a,e.onStatus),c}function _b(e){return hu(jc(e)?.fingerprint)}function zF(e,t,n){try{NL(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 KF(e){let t=rae({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 rae(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 JF(e,t){let n=eN(e);if(t===null){di(n,{recursive:!0,force:!0});return}let r;try{r=_se(n)}catch{return}for(let i of iae(r,t))di(mt(n,i),{force:!0})}function iae(e,t){let n=new Set(t.map(r=>`${hb(r)}.scip`));return e.filter(r=>!n.has(r))}function HF(e,t){for(let n of t){let r=Mb(e,n.language);gp(we(r),{recursive:!0}),n.scipPath!==r&&hp(n.scipPath,r)}}async function oae(e,t){if(!ep()){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(jse()==="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..."),!yL(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 sae(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=aae({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?YF(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function aae(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Nb({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??_c(e.projectRoot,e.typescriptProjects);return t.length===0?[Nb({...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)=>Nb({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Oc(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Nb(e){let t=pr(e.language),n=Gl(t),r=cf(t,e.projectRoot);if(!r&&!gR(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:yR(t,e.env,i)}}}function cae(e,t){let n=new Map;for(let i of e)if(i.skipped)YF(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)FD(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&GF(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function YF(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 lae(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 WF(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ND(e.map(o=>o.scipPath),t);return XF(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&GF(e[0].scipPath,t);return!1}function uae(e){let t;if(dae(e)){let i=mt(e.run.tempPaths.runDir,"typescript-affected.db");try{QF(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();qF(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=jL({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),di(i,{force:!0}),di(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 qF(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function dae(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Fn(e.run.paths.outputDb)||!Fn(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 pae(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:lb(e.plan,o,e.projectFileCount)}}function qF(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Fn(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||QF(e,r);let o=ep();if(!o)throw new Error("scip CLI is not available");Tse(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 QF(e,t){let n=DD(e);XF(n,t)}function XF(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=Ose(e)||".scip",i=fp(e,r);return mt(we(e),`${i}.${n+1}.${t}${r}`)}async function mae(e,t){for(let n=0;n<2;n++){let r=fae(e,t);if(r)return r;let i=gae(e);if(i&&hae(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await bae(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.`);di(e,{force:!0});continue}if(i&&!xe(i.pid)){di(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 fae(e,t){let n;try{n=Ase(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 $se(n,JSON.stringify(r)+`
|
|
1267
|
-
`),()=>{try{Fse(n)}finally{di(e,{force:!0})}}}function gae(e){try{let t=JSON.parse(yp(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 hae(e,t){return e?.kind==="manual-cli"&&yae(t?.trigger)}function yae(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function bae(e){return UF(e,"SIGTERM"),await VF(e,2e3)?!0:(UF(e,"SIGKILL"),VF(e,1e3))}function UF(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function VF(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!xe(e))return!0;await Sae(50)}return!xe(e)}function Sae(e){return new Promise(t=>setTimeout(t,e))}function vae(e,t,n){return Ni(e,t,n)}function ZF(e,t,n){return Object.fromEntries(t.map(r=>{let i=pr(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:pf(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?xae(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Rae(n),...o,clojureConfigPath:s,files:Fi(e,{language:r,markerFiles:i})}]}))}function xae(e){return e?.trim()||void 0}function Rae(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Mb(e,t){return mt(we(e),"language-indexes",`${t}.scip`)}function eN(e){return mt(we(e),"language-indexes","typescript-projects")}function bp(e,t){return mt(eN(e),`${hb(t)}.scip`)}function jc(e){try{return JSON.parse(yp(e,"utf-8"))}catch{return null}}function tN(e,t){try{let n=JSON.parse(yp(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Tr(n.fingerprint)===Tr(t)&&Tr([...n.indexedLanguages??[]].sort())===Tr(t.languages)}catch{return!1}}function $b(e,t){he(e,t,{spacing:2,trailingNewline:!0})}function nN(e,t){try{let n=JSON.parse(yp(e,"utf-8"));if(n.version!==2&&n.version!==3)return;$b(e,{...n,lastRefresh:t})}catch{}}function Sp(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 Tr(e){return JSON.stringify(e)}var Ob=864e5;function rN(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=Cae(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)/Ob)):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?wae(y):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,u)=>l.check.localeCompare(u.check))}}function Cae(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 iN(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Ob:Ob;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function wae(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 kae}from"child_process";import{statSync as Iae,watch as Pae}from"fs";import{join as Eae,relative as Dae}from"path";import Tae from"ignore";var vp=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=Kn(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=ei(t.projectRoot),this.extraIgnore=Tae(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=Pae(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=oN(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}handleFileChange(t){let n=Dae(this.projectRoot,Eae(this.projectRoot,t));n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:n})}scheduleReindex(t){if(this.pendingTrigger=oN(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=Gt(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,u=kae(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=cy(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n={head:cy(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let r=Iae(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function oN(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 Xae}from"fs";import{existsSync as aN,mkdirSync as cN,readFileSync as lN,writeFileSync as uN}from"fs";import{homedir as Lae}from"os";import{dirname as dN,isAbsolute as Fae,join as jb,relative as sN,resolve as Nae}from"path";function pN(e,t={}){let n=t.dossierDir?Nae(e.projectRoot,t.dossierDir):jb(e.projectRoot,"docs","scip-query"),r={markdownPath:jb(n,"health-dossier.md"),jsonPath:jb(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Wae({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return jae(r.markdownPath,Aae(i),r),Bae(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Aae(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Hb(e.health)}`,"","## Items That Need Attention","",..._ae(e),"","## Blocked Or Unavailable Checks","",...Mae(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","",...$ae(e),"","## JSON","",`Machine-readable report: \`${Oae(e)}\``,""].join(`
|
|
1268
|
-
`)}`}function _ae(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 Mae(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 $ae(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 Hb(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Oae(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function jae(e,t,n){if(cN(dN(e),{recursive:!0}),(aN(e)?lN(e,"utf-8"):null)===t){n.unchanged.push(e);return}uN(e,t),n.written.push(e)}function Bae(e,t,n){cN(dN(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
|
|
1269
|
-
`,i=aN(e)?lN(e,"utf-8"):null;if(i&&Hae(i,r)){n.unchanged.push(e);return}uN(e,r),n.written.push(e)}function Hae(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 Wae(e,t){return Bb(e,t)}function Bb(e,t){return typeof e=="string"?qae(e,t):Array.isArray(e)?e.map(n=>Bb(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Bb(r,t)])):e}function qae(e,t){if(e===t)return".";if(!Fae(e))return e;let n=sN(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=sN(Lae(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Uae}from"child_process";import{readFileSync as fN}from"fs";import{dirname as mN,join as Vae,resolve as Gae}from"path";import{fileURLToPath as zae}from"url";var xp={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 Kae(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of xp[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Wb(e){return[...new Set(e.filter(t=>xp[t]!==void 0))].sort()}function gN(e,t={}){let n=t.runtime??Qae,r=t.packageRoot??Jae(),i=Wb(e),o=i.filter(d=>n.probe(xp[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=Yae(r),c=Kae(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let u=i.filter(d=>n.probe(xp[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 Jae(){let e=mN(zae(import.meta.url));for(;;){let t=Vae(e,"package.json");try{if(JSON.parse(fN(t,"utf8")).name==="scip-query")return e}catch{}let n=mN(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Yae(e){return JSON.parse(fN(Gae(e,"package.json"),"utf8")).optionalDependencies??{}}var Qae={probe:e=>ul(e)==="ast",resetProbe:uv,install:(e,t)=>{let n=Uae(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 bN(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 SN(e={}){let t=[],n=kr(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?PE(r,n.config,e.languages):null,c=a?.config??n.config,l=fs(c,{projectRoot:r}),u=l.filter(G=>G.level==="error"),d=null,p=null;if(u.length===0&&c.watch?.enabled!==s)try{d=EE(r,c,s)}catch(G){p=Ns(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:[]}:ip({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?fs(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}:gN(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?lce(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 Zae({projectRoot:r,paths:i,config:m,readiness:w,configHasErrors:y.length>0,steps:t,onStatus:e.onStatus}),C=I.reindexResult,k=I.freshness,T=Kn(m),F=ece({projectRoot:r,cacheDir:i.cacheDir,watchConfig:T,readiness:w,configHasErrors:y.length>0,reindexResult:C,postReindexFreshness:k,steps:t}),V=bn(r,m),ie=ai(V),W=Pn(r,m,i);de(t,{id:"capabilities",label:"Capability matrix",status:gce(ie),message:hce(ie)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let be=e.runHealth===!1?pce(t):await dce(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=Ts(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:Ns(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=Vd(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:Ns(G)})}let gi=tce({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:nce(gi),message:rce(gi),details:gi.map(G=>`${G.command}: ${G.status} - ${G.evidence}`)});let Hs={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:gi,healthDossier:null,hooks:Re,setupAgent:ht,changeScopes:Hs,filesWritten:ht?.written??[],verdict:Ub(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=Ub(t,V),At;let An=pN(At,{dossierDir:e.dossierDir});return At.healthDossier=An,At.changeScopes.repository.push(...An.written),At.filesWritten=[...At.filesWritten,...An.written],de(t,{id:"health-dossier",label:"Health dossier",status:An.status==="failed"?"failed":"ok",message:An.status==="failed"?An.error:`${An.written.length} written, ${An.unchanged.length} unchanged.`,details:[An.markdownPath,An.jsonPath]}),At.verdict=Ub(t,V),At}async function Zae(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 Fs({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=Pn(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:Ns(i),details:t})}return{reindexResult:n,freshness:r}}function ece(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:Ns(n)}),null}}function vN(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Hb(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:"),qb("Repository records (commit)",e.changeScopes.repository),qb("Checkout preferences (do not commit)",e.changeScopes.checkout),qb("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 qb(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function tce(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:ice(e.steps),evidence:oce(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?sce(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:hN(e.readiness,e.freshness),evidence:yN(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:hN(e.readiness,e.freshness),evidence:yN(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:ace(e.capabilities),evidence:cce(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 nce(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function rce(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 ice(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function oce(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function sce(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 hN(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function yN(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 ace(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function cce(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 lce(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=pr(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=uce(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 uce(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function dce(e,t){if(!Xae(e)){let n="Skipped because no SQLite index database exists yet.";return de(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Vb(n)}try{let n=await Wd({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).`}),mce(n)}catch(n){let r=Ns(n);return de(t,{id:"health",label:"Health audit",status:"failed",message:r}),Vb(r)}}function pce(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}),Vb(t)}function mce(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(fce),warnings:e.warnings??[]}}function fce(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 Vb(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ub(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 gce(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 hce(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 Ns(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as yce}from"readline";function bce(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Sce(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 xN(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=bce(e);yce(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=Sce(r,p,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as RN,mkdirSync as vce,writeFileSync as xce}from"fs";import{dirname as Rce,join as CN}from"path";function wN(e,t={}){let n=CN(e,".github","workflows","scip-query.yml"),r=Cce({hasNpmProject:RN(CN(e,"package.json"))});return RN(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(vce(Rce(n),{recursive:!0}),xce(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function Cce(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 wce}from"fs";import{join as Rp}from"path";function kN(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=vL({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=kce(e.projectRoot,{dryRun:e.dryRun})),s}function kce(e,t={}){return{hooks:Ts(e,{remove:!0,dryRun:t.dryRun}),agentSetup:HT(e,{dryRun:t.dryRun}),left:Ice(e)}}function Ice(e){return[[".scipquery.json",Rp(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",Rp(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",Rp(e,".scipquery","ledger")],["docs/scip-query/",Rp(e,"docs","scip-query")]].filter(([,t])=>wce(t)).map(([t])=>t)}import{existsSync as DN,lstatSync as Cp,readFileSync as Jb,readdirSync as TN,realpathSync as IN,rmSync as Bc,statSync as LN}from"fs";import{join as st,resolve as fo,sep as PN}from"path";var Pce=3600*1e3,Ece=2*1024*1024*1024,Dce=300*1e3;function Tce(e){let t=e.leases.filter(a=>a.managed&&!a.live&&!a.busy),n=FN(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 FN(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 NN(e,t,n={}){if(!dc())return{kind:"disabled"};let r=zt(e);if(!r)return{kind:"unavailable"};let i=st(gs(),"repositories",r.repositoryId);if(!DN(i))return{kind:"unavailable"};let o=(n.now??Date.now)(),s=st(i,"gc-state.json"),a=ON(s);if(!n.force&&a&&o-Date.parse(a.lastSweepAt)<Dce)return{kind:"throttled",sweptAt:a.lastSweepAt};let c=mc(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=_N(e,i,r.repositoryId,a?.unreferencedSince??{}),u=Tce({nowMs:o,...l,policy:{generationTtlMs:n.policy?.generationTtlMs??Pce,budgetBytes:n.policy?.budgetBytes??Ece}}),d=0,p=0;for(let g of u.deleteWorktrees){if(!MN(g.lease))continue;let h=to(st(g.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(zb(g.lease,!0))continue;try{au({projectRoot:g.lease.projectRoot,cacheDir:g.lease.localCacheDir,cliVersion:t})}catch{continue}if(zb(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;ES(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 AN(e,t,n){let r=Rs(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=zt(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(gs(),"repositories",i.repositoryId),s=$N(st(o,"worktrees",`${i.worktreeId}.json`)),a=ON(st(o,"gc-state.json")),c=_N(e,o,i.repositoryId,a?.unreferencedSince??{}),l=FN(c.leases,c.locks),u=c.generations.filter(f=>!l.has(f.generationId)),d=c.generations.reduce((f,g)=>f+g.size,0),p=Cs(e,t),m=0;return p&&(m=Lce(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 Lce(e){return[e,`${e}-wal`,`${e}-shm`].reduce((t,n)=>{try{return t+LN(n).size}catch{return t}},0)}function _N(e,t,n,r){let i=new Set(kd(e).map(l=>fo(l.path))),o=[];for(let l of Gb(st(t,"worktrees"))){if(!l.endsWith(".json"))continue;let u=st(t,"worktrees",l),d=$N(u);if(!d)continue;let p=fo(d.projectRoot);o.push({leasePath:u,lease:d,managed:d.repositoryId===n&&MN(d),live:i.has(p)||DN(p),busy:zb(d)})}let s=[];for(let l of Gb(st(t,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(l);if(!u)continue;let d=st(t,"locks",l),p=Kb(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 Gb(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:EN(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=Cp(d)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||a.push({generationId:l,path:d,size:EN(d),...r[l]===void 0?{}:{unreferencedAt:r[l]}})}return{leases:o,generations:a,locks:s,temporaries:c}}function MN(e){if(e.ownershipChecksum!==Cc(e)||fo(e.localCacheDir)!==fo(hs(e.projectRoot)))return!1;let t=fo(gs()),n=fo(st(t,"projects")),r=fo(e.localCacheDir);if(!r.startsWith(`${n}${PN}`))return!1;try{let i=Cp(t),o=Cp(n),s=Cp(r);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink())return!1;let a=IN(n);return IN(r).startsWith(`${a}${PN}`)}catch{return!1}}function zb(e,t=!1){for(let r of t?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Kb(st(e.localCacheDir,r));if(i!==void 0&&xe(i))return!0}let n=Kb(mr(e.localCacheDir).lockPath);return n!==void 0&&xe(n)}function $N(e){try{let t=JSON.parse(Jb(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 Kb(e){try{let t=JSON.parse(Jb(e,"utf8"));return typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0?t.pid:void 0}catch{return}}function ON(e){try{let t=JSON.parse(Jb(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 Gb(e){try{return TN(e)}catch{return[]}}function EN(e){let t=0,n=[e];for(;n.length>0;){let r=n.pop();for(let i of TN(r,{withFileTypes:!0})){let o=st(r,i.name);i.isDirectory()?n.push(o):i.isFile()&&(t+=LN(o).size)}}return t}import{existsSync as Fce,readFileSync as Nce}from"fs";import{createRequire as Ace}from"module";import kp from"path";import{performance as wp}from"perf_hooks";var _ce=Ace(import.meta.url),Hc;function qN(e){let t=Mce();if(!t)return Gr("typescript is not installed");let n=lu(e);if(n.length===0)return Gr("no tsconfig found");try{return new Yb(e.config.projectRoot,t,n.map(r=>$ce(t,r)))}catch(r){return Gr(r instanceof Error?r.message:String(r),n[0],n)}}function UN(e,t,n){let r=wp.now(),i=jN(t,e),o=wp.now()-r,s=wp.now(),a=jN(n,e),c=wp.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=BN(h),R=BN(y),b=HN(h,R),v=HN(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 Yb=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=kp.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=Bce(this.ts,r.service,this.projectRoot,l);u&&(u.file===t.relativePath&&u.line>=t.startLine&&u.line<=t.endLine||a.push(u))}return Ur(a)}bundleForFile(t){let n=GN(t);return this.bundles.find(r=>r.files.has(n))??null}};function Mce(){if(Hc!==void 0)return Hc;try{Hc=_ce("typescript")}catch{Hc=null}return Hc}function $ce(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(WN(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,kp.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>WN(e,s)).join(`
|
|
1303
|
-
`));let i=new Set(r.fileNames.map(GN)),o=e.createLanguageService(Oce(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Oce(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?kp.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Fce(n))return e.ScriptSnapshot.fromString(Nce(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 Bce(e,t,n,r){let i=Vr(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 jN(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function BN(e){return new Set(e.map(VN))}function HN(e,t){return e.filter(n=>!t.has(VN(n)))}function VN(e){return`${e.file}:${e.line}:${e.column}`}function GN(e){return kp.resolve(e).replace(/\\/g,"/")}function WN(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
|
|
1305
|
-
`)}import{readFileSync as Hce}from"fs";function zN(e){let t=[];for(let[n,r]of Hce(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 KN(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=Kce(y.durationMs),b=Sn(y.runId);x&&R!==null&&(l+=1,s.add(x),b&&o.add(b),Wce(i,y,x,R),qce(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=zce(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(Gce).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(Uce).filter(h=>h!==null).sort((h,y)=>y.laterRunMs-h.laterRunMs||y.laterRunEvents-h.laterRunEvents||h.spanName.localeCompare(y.spanName)),f=[...i.values()].map(Vce).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 JN(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 Wce(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 qce(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 Uce(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:As(e.observations.map(o=>o.durationMs)),firstRunMs:As(r.map(o=>o.durationMs)),laterRunMs:As(i.map(o=>o.durationMs))}}function Vce(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 Gce(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=As(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=As(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:As(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:Ip(e.observations,"cache-hit"),cacheMisses:Ip(e.observations,"cache-miss"),reused:Ip(e.observations,"reused"),skipped:Ip(e.observations,"skipped")}}function zce(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function Ip(e,t){return e.filter(n=>n.outcome===t).length}function Kce(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 As(e){return e.reduce((t,n)=>t+n,0)}var YN={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 QN(e,t){let n=Jce(t);return{...e,warnings:[...e.warnings??[],YN.note,...n],capabilities:t,scoreInterpretation:YN}}function Jce(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 XN=Symbol("option-value-source"),ZN=new Map;function eA(e){ZN=new Map(e)}function We(e){return(...t)=>{let{args:n,opts:r}=Zb(t);Ee(i=>e({db:i,args:n,opts:r}))}}function Ne(e,t){return We(n=>{let r=Hd(n.db,e,E(n.opts,"full"),{quiet:E(n.opts,"json")});t({...n,budget:r})})}function tA(e){return We(t=>Ms(t,e,{kind:"list"}))}function nA(e){return We(t=>Ms(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function rA(e){return We(t=>Ms(t,e,{kind:"grouped",key:e.key}))}function pi(e){return We(t=>Xb(t,e))}function iA(e){return pi({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=>Xb(n,{...t,commandName:t.commandName??e}))}function oA(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=>Ms(n,{...t,commandName:e},{kind:"list"}))}function Pp(e,t){return Ne(e,n=>Ms(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Ep(e,t){return Ne(e,n=>Ms(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 _s(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&&Qb(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 Qb(e,t){return e[XN]?.(t)}function Ms(e,t,n){Xb(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 Xb(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:Yce(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 Yce(e){return e.budget?.analysisBudget}function H(e,t,n,r,i={}){let o=e?ZN.get(e):void 0;console.log(JSON.stringify({command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:Qce(t),options:n,result:r},null,2))}function Qce(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function Zb(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,XN,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var ole=new Set(hd),sle=18e4,lA=100*1024*1024,ale=new Set(Am),cle=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],lle=[["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 ule(e){return e.filter(t=>ole.has(t))}async function uA(e){let t=Te(e),n=Me(),r=ut(n),i=Gt(n,r),o=E(t,"json");try{let s=ule(_s(t,"language")),a=await Fs({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 dA(){let e=Me(),t=ws(e);try{let n=sp({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 pA(e){let t=Te(e),n=Me(),r=ws(n);try{let i=Fb({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 mA(e){let t=Te(e);Ee(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Vn(n,{base:A(t,"base")}),o=Vu(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function fA(e){let t=Te(e);try{let n=await ST({base:A(t,"base")});if(E(t,"json")){H("diff-impact",[],t,n);return}xT(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function gA(e,t){let n=Te(t),r=String(e).split(",").filter(i=>i.length>0);Ee(i=>{let o=[];for(let c of r)ps.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):Wh(i,o,s);console.log(JSON.stringify(a))})}async function hA(e){let t=Te(e);if(E(t,"writeBaseline")||E(t,"baseline")){wle(t);return}try{let n=await Wd({scope:A(t,"scope"),full:E(t,"full"),json:E(t,"json")}),{projectRoot:r,config:i,dbPath:o}=kr(),s=ai(bn(r,i),{hasIndexedGraph:Nn(o)}),a=QN(n,s);if(E(t,"json")){H("health",[],t,a);return}bT(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function yA(e){let t=Te(e),n=Me(),r=De(t,"timeoutMs")??sle,i=E(t,"progress"),o=E(t,"profile"),s=A(t,"profileOut"),a={projectRoot:n,...vle(n),index:eS(Nn(ws(n))),commands:[]};E(t,"coldIndex")&&($s(i,"cold index started"),a.coldIndex=await dle(n),$s(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),$s(i,"warm index started"),a.warmIndex=await gle(n),$s(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=eS(Nn(ws(n))));for(let c of hle(t))a.commands.push(ble(n,c,r,{progress:i,profile:o,profileOut:s}));if(E(t,"json")){H("bench",[],t,a);return}xle(a)}function bA(e,t){let n=Te(t),r=ile(String(e)),i=KN(zN(r),{top:De(n,"top")??20});if(E(n,"json")){H("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(JN(i,r))}function SA(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(Cle),l=i?c.filter(R=>R.relativePath.includes(i)):c,u=o?l:l.slice(0,s),d=mi.now(),p=mu(n),m=Number((mi.now()-d).toFixed(3)),f=mi.now(),g=qN(n),h=Number((mi.now()-f).toFixed(3)),y=UN(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}Rle(x)})}async function dle(e){let t=ut(e),n=Gt(e,t),r=Dp(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;ple(r);let o=mle(r,i);try{let s=await vA(()=>Fs({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 sA(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...xA(e)}}catch(s){throw sA(r,i,o,"restore-backup"),s}}var tS={existsSync:Nn,readFileSync:Xce,writeFileSync:nle,renameSync:Zce,rmSync:ele,unlinkSync:tle};function nS(e){return go(Dp(e),"bench-restore.json")}function ple(e,t=tS){let n=nS(e);if(!t.existsSync(n))return!1;let r=fle(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 mle(e,t,n=tS){return n.existsSync(e)?(n.writeFileSync(nS(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function sA(e,t,n,r,i=tS){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=nS(e);i.existsSync(o)&&i.unlinkSync(o)}function fle(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 gle(e){let t=ut(e),n=Gt(e,t),r=await vA(()=>Fs({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,...xA(e)}}async function vA(e){let t=mi.now(),n=await e();return{durationMs:Math.round(mi.now()-t),value:n}}function xA(e){return Nn(ws(e))?Ee(t=>{let n=qt(t);return{files:n.documents,symbols:n.symbols}}):{}}function hle(e){let t=_s(e,"command");return t.length>0?t.map(yle).filter(n=>n.length>0):[...cle.map(n=>[...n]),...E(e,"includeHeavy")?lle.map(n=>[...n]):[]]}function yle(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function ble(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;$s(r.progress,`${i} started`),jt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=mi.now(),s={...r.profile?Sle(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=cA(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:lA,timeout:n}),c=Math.round(mi.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 $s(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 $s(e,t){e&&process.stderr.write(`[bench] ${t}
|
|
1309
|
-
`)}function Sle(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function vle(e){let t=cA("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:lA});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=>ale.has(rle(r).toLowerCase())).length}}function xle(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, ${Yn(e.index.indexSizeBytes)}`),e.coldIndex&&aA("Cold index",e.coldIndex),e.warmIndex&&aA("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 aA(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function Rle(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 Cle(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function wle(e){let t=A(e,"scope");Ee(n=>{if(E(e,"writeBaseline")){let i=wh(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 RA(){let e=ip(),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 CA(e){let t=Te(e),n=Me(),r=Ts(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 wA(){let e=!1;Nc()?console.log("scip CLI: installed"):(ob(),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=WA(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}: ${Ale(o)}${qA(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function kA(e){PA(e,"capabilities")}function IA(e){E(Te(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),PA(e,"capability-matrix")}function PA(e,t){let n=Te(e),{projectRoot:r,config:i,paths:o,dbPath:s}=kr(),a=bn(r,i),c=Pn(r,i,o),l=ai(a,{hasIndexedGraph:Nn(s)&&c.state!=="missing"});if(E(n,"json")){H(t,[],n,l);return}rS(l)}function EA(){let e=Me(),t=gn(e),n=IE(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function DA(e){let t=Te(e),n=Me(),r=ut(n),i=fs(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 TA(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=fP(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 LA(e){let t=Te(e),n=Date.now(),r=A(t,"since"),i;if(r){let h=iN(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=Yd(o),a=rN(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(Jd,"*.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 FA(e){let t=Te(e),{report:n,hasIndexerProblems:r,hasErrors:i}=NA("doctor");E(t,"json")?H("doctor",[],t,n):Tle(n,r),process.exitCode=i?1:0}function NA(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=kr(),o=fs(n,{projectRoot:t}),s=bn(t,n),a=Pn(t,n,r),c=Nn(i),l=ai(s,{hasIndexedGraph:c&&a.state!=="missing"}),u=AN(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 AA(e){let t=Te(e),n=Me(),r=Vd(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 _A(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 kle(n,{json:E(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await SN(n);E(t,"json")?H("setup",[],t,o):vN(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function kle(e,t){let{projectRoot:n,config:r}=kr(),i=bn(n,r),o=bN({files:Ile(n),watchEnabled:Kn(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=Wb(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 xN([...s,...a]):new Set([...Ple(o.actions),...s.map(f=>f.id)]);l&&Ele(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 Ile(e){return{agentsMd:Nn(go(e,"AGENTS.md")),claudeMd:Nn(go(e,"CLAUDE.md")),codexHooks:Nn(go(e,".codex","hooks.json")),claudeSettings:Nn(go(e,".claude","settings.local.json"))}}function Ple(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function Ele(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 MA(e){let t=Te(e),n=Me(),r=wN(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 $A(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=kN({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 OA(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=Kn(r);r.watch=g;let h=Gt(n,r),y={projectRoot:n,cacheDir:h.cacheDir,cliVersion:Fe,watchOverrides:f};if(l){let b=jA($i(y),g.enabled);d?H("watch",[],t,b):BA(b);return}if(u){try{let b=au(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=fC(go(Dp(h.dbPath),Nf),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let R=new vp({projectRoot:n,config:r,languages:r.languages,onStatus:b=>{process.stdout.write(`\r\x1B[K${Ay(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 jA(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,startedAt:e.lock.startedAt}:{enabled:t,state:"stopped",mode:"none"};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,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,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 Dle(n)}}function BA(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}`),"watcher"in e&&e.watcher&&console.log(`Watcher: ${Ay(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 Dle(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function HA(e){let t=Te(e),{report:n}=NA("status"),r=Kn(ut(n.projectRoot)).enabled,i=jA($i({projectRoot:n.projectRoot,cacheDir:Dp(n.configuredDbPath),cliVersion:Fe}),r),o=LL(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:eS(n.exists)});return}Lle(n,{affectedSetShadow:o,capabilities:E(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function Tle(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})`:""}`),rS(e.capabilities)}function Lle(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 WA(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}${qA(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: ${_le(e.freshness.lastRefresh)}`),BA(t.watchService),Fle(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"),Nle(t.sqliteGeneration),console.log(`Shadow: ${FL(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),Mle(e.exists),t.capabilities&&(console.log(""),rS(e.capabilities))}function Fle(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), ${Yn(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Yn(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), ${Yn(e.cleanup.deletedBytes??0)} removed`)}function Nle(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 WA(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ale(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function qA(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function _le(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 eS(e){if(e)return Ee(t=>{let n=qt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function Mle(e){e&&Ee(t=>{let n=qt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Yn(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function rS(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 Xn({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=Wc(a);return{...c,renderShape:"list",handler:tA({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function Tp({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:nA({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function UA({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:rA({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function VA({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:iA({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function Lp({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:oA(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as fue,mkdirSync as gue,writeFileSync as hue}from"fs";import{dirname as yue,relative as bue}from"path";import{existsSync as Lr,readdirSync as Wle,readFileSync as ho}from"fs";import{basename as qle,dirname as XA,isAbsolute as ZA,join as Ule,relative as Vle,resolve as qc,sep as Gle}from"path";import{spawnSync as Ole}from"child_process";import{dirname as jle}from"path";function zA(e){let n=(e.spawnSync??Ole)("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 KA(e){let t=Hle(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=JA(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 Ble=8;function Hle(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=iS(s,"uniquename"),c=iS(s,"kind"),l=iS(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:GA(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:GA(l),block:s})}return t}function JA(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<Ble&&!o.has(m.uid)&&m.filename===i){let f=JA(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 iS(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function GA(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var e_=["update","insert","delete"],t_=["select","query","findFirst","findMany"],oS=new Set([...e_,...t_]);function sS(e){let t=e.methods&&e.methods.length>0?e.methods:[...oS],n=new Set(e_),r=new Set(t_);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var zle=/^(.*)@L(\d+)-L(\d+)$/;function aS(e){let t=e.match(zle);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 Kle=new Set(["auto","sany","tlc","apalache","none"]),Np=/^[A-Za-z_][A-Za-z0-9_]*$/;function n_(e){return Kle.has(e)}function Ap(e,t){let n=[],r=Qt(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Lr(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=Jle(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:XA(r)},errors:n}:{errors:n}}function Qt(e,t){if(!t)return null;let n=ZA(t)?qc(t):qc(e,t);return en(e,n)?n:null}function r_(e,t,n){if(!n)return null;if(ZA(n)){let s=qc(n);return en(e,s)?s:null}let r=qc(e,n);if(en(e,r)&&Lr(r))return r;let i=qc(t,n);if(en(e,i)&&Lr(i))return i;let o=en(e,r)?r:i;return en(e,o)?o:null}function i_(e,t){let n=Qt(e,t);if(!n||!Lr(n))return null;let r=ho(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:lue(r),operators:uue(r),actions:[]}}function o_(e,t,n){let r=Qt(e,t);if(!r||!Lr(r))return null;let i=ho(r,"utf8"),o=KA(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function cS(e,t){let n=Qt(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Lr(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 lS(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 Jle(e,t){if(!ee(e))return t.push("map file must contain a JSON object"),null;let n=tue(e.variables,t);eue(n,t);let r=aue(e.actions,n,t),i=Yle(e.init,t);Xle(i,r,t);let o={module:QA(e.module,"module",t),config:QA(e.config,"config",t),scope:X(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:X(e.invariants)??[],traces:X(e.traces)??[],unmappedWriteScope:Zle(e.unmappedWriteScope,t)};return pue(e.scope,t),t.length===0?o:null}function Yle(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=Qle(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function Qle(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 Xle(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 Zle(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 eue(e,t){Fp(e,t,"alias",n=>n.aliases),Fp(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Fp(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Fp(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=sS(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Fp(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 tue(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(!Np.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!ee(i)){t.push(`variables.${r} must be an object`);continue}let o=a_(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=rue(i.resource,r,t),c=iue(i.statements,r,t),l=oue(i.ormCalls,r,t),u=sue(i.waive,r,t),d=nue(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 nue(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 rue(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 iue(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 oue(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=>!oS.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...oS].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function sue(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 aue(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(!Np.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!ee(s)){n.push(`actions.${o} must be an object`);continue}let a=a_(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=aS(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=cue(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 cue(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`),YA(o,"reads",c,i,s),YA(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 YA(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function lue(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();Np.test(o)&&t.add(o)}}return[...t].sort()}function uue(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 due=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function s_(e){if(!e||!Lr(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(due.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Np.test(i)&&n.add(i)}return[...n].sort()}function QA(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function a_(e){return typeof e=="string"?[e]:X(e)}function pue(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 mue=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function c_(e,t){if(!Lr(t))return{status:"none"};let r=ho(t,"utf8").match(mue)?.[1],i=Vle(e,t).split(Gle).join("/"),o=qle(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(u=>!!u)),a=XA(t);if(!Lr(a))return{status:"none"};let c=[];for(let u of Wle(a)){if(!u.endsWith(".scip-tla.json"))continue;let d=Ule(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 Mp(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 uS=20,l_=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=gr(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,uS),b=x?m:m.slice(0,uS),v=x?f:f.slice(0,uS),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&&(Mp(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(""),Mp(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(""),Mp(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(" + ")}`)}),u_=Yt("unused-imports",{query:({db:e,args:t,budget:n})=>bg(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)`)}),d_=Ep("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)`)}),p_=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.`)}),m_=Ne("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Vg(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.`)}),f_=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).`)}),g_=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).`)}),h_=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).`)}),y_=Pp("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]}),b_=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:es(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.`)}}),S_=pi({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Og(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.`)}}),v_=pi({commandName:"similar-chains",query:({db:e,opts:t})=>jg(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.`)}}),x_=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)`:""}`)}}),R_=vn("convergence",{query:({db:e,args:t,budget:n})=>Gh(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}`)}}}),C_=Yt("similar-signatures",{query:({db:e,opts:t,budget:n})=>Zh(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.`)}),w_=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.`)}),k_=Yt("twin-drift",{query:({db:e,opts:t,budget:n})=>hh(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.`)}),I_=Yt("not-implemented",{query:({db:e,opts:t,budget:n})=>Lh(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).`)}),P_=Yt("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Nh(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).`)}),E_=Ne("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=Mh(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.`)}),D_=pi({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=U(t,0),i=U(t,1),o=A(n,"out")??Dh(r,i),s=Qt(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=Th(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=bue(e.config.projectRoot,s);if(!E(n,"force")&&fue(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return gue(yue(s),{recursive:!0}),hue(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}),T_=Ne("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Bu(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=Gy(i),u=c?qy(o,i):void 0;if(a){H("cleanup-plan",t,n,{result:i,verification:u},{analysisBudget:r.analysisBudget});return}if(s){let d=zy(u,l);if(d.length>0){for(let m of d)console.error(`error: ${m}`);process.exitCode=1;return}let p=LT(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=Sue(u.checkers),p=vue(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}`)}}}),L_=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=Bu(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=Gy(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=qy(a,o),l=zy(c,s,{allowDirty:E(t,"forceDirty")});if(l.length>0){for(let p of l)console.error(`error: ${p}`);process.exitCode=1;return}Vy(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 Sue(e){return e.join(", ")}function vue(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var F_=Ne("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=E(n,"full"),o=$h(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.`)}),N_=We(({db:e,args:t,opts:n})=>{let r=E(n,"full"),i=mh(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: ${$d(d)}`)}}console.log(`
|
|
1413
|
-
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),A_=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 __=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.`)}}),M_=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.`)}}),$_=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.`)}}),O_=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.`)}}),j_=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.`)}}),B_=vn("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ba(e,{minTotalLines:E(n,"reviewThresholds")&&Qb(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 $p=[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:A_}),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:T_}),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:L_}),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:F_}),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:N_}),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:l_}),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:u_}),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:d_}),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:b_}),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:S_}),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:__}),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:M_}),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:$_}),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:O_}),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:j_}),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:B_}),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:v_}),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:p_}),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:m_}),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",Ir,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:x_}),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:f_}),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:g_}),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:h_}),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:y_}),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:R_}),UA({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})=>Kh(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:w_}),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:k_}),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:I_}),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:P_}),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:E_}),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:D_}),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:C_})];var xue=We(({db:e,args:t,opts:n})=>{let r=qt(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: ${Yn(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),H_=[{id:"stats",command:"stats",description:"Show index statistics",options:[By()],renderShape:"custom",docs:N("Core"),handler:xue}];function ft(e,t){let n=Ht(e,t),r=Cue(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:Rue(t,ef(e,t,5))}function Xt(e,t,n,r){return{...Os(e,t),[r]:n}}function Os(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:ef(e,t,5)}}function Rue(e,t){let n=`No definition matched '${e}'.`;return t.length>0?`${n} Suggestions: ${t.join(", ")}`:n}function Cue(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 wue=Pp("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Eg(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."}),kue=We(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=Y(n,"limit",30);if(r){let c=Rg(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=wg(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}]`:""}`))}),Iue=We(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=Y(n,"limit",30);if(r){let s=Cg(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=kg(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}`))}),Pue=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=Ig(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=Pg(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}`))}),Eue=pi({commandName:"cycles",query:({db:e,opts:t})=>Au(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.)`)}}),Due=pi({commandName:"deep-chains",query:({db:e,opts:t})=>Lg(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("; ")}`)}}}),W_=[Tp({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})=>gg(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:kue},{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:Iue},{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:Pue},{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:Eue},{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:wue},{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:Due},Lp({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})=>Jr(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 Tue=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}`)}),Lue=We(({db:e,args:t,opts:n})=>{let r=Xh(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(", ")}`)}}),q_=[{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:Lue},{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:Tue}];var Fue=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.`)}),Nue=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 ${Aue(a.lastTogetherAt)}`),console.log(` subjects: ${_ue(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 Aue(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function _ue(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 Mue=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}`})}),$ue=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 Oue(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!ad.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${ad.join(", ")}`),process.exit(1)),t}var jue=We(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Ud(Pc()))return;let r=E(t,"full"),i=Hd(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:Oue(t.skip)},s=eo(e,o),a=nc(s.findings),c=tc(s),l=Qd(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=UP(m,f,g),y=VP(m,s.checksRun),x=hT(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: ${$d(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}),U_=[{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:Fue},{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:Mue},{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:$ue},{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:Nue}];function Bue(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 Hue=We(({db:e,args:t,opts:n})=>{let r=U(t,0),i=E(n,"signatures"),o=vg(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?` - ${Wue(l.signature)}`:"";console.log(`${u}${dt(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function Wue(e){return e.length>120?`${e.slice(0,117)}...`:e}var que=Yt("imports",{query:({db:e,args:t,budget:n})=>hg(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)."}),Uue=Ep("refs",{query:({db:e,args:t,budget:n})=>ug(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")}),Vue=We(({db:e,args:t,opts:n})=>{let r=U(t,0),i=zh(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]}`)}),Gue=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}`)}}),zue=Ne("slice",({db:e,args:t,opts:n,budget:r})=>{let i=U(t,0),o=E(n,"forward")?"forward":"backward",s=us(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).`)}),V_=[Xn({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:N("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>cg(e,U(t,0)),format:e=>e.relativePath}),Xn({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:N("Navigation"),query:({db:e,args:t})=>lg(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:Uue},Lp({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})=>({...Os(t,U(n,0)),...e}),sections:Bue}),Xn({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}),Xn({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}),VA({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}`)}]}),Xn({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:que},Xn({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:N("Navigation"),query:({db:e,args:t})=>yg(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:Hue},Xn({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:N("Navigation"),query:({db:e,args:t})=>xg(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")}),Xn({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})=>Dg(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)`)}),Tp({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})=>Tg(e,{scope:A(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Xn({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})=>Fg(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:Vue},{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:Gue},{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:zue}];var Kue=Ne("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=Y(n,"limit",20),o=jh(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,{...Os(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?{...Os(e,U(t,0)),...o}:o,{analysisBudget:r.analysisBudget});return}o.matched.symbol&&ft(e,U(t,0));let s=[{title:"TARGET",rows:Jue(o)},{title:"DEFINITIONS",rows:Yue(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:Que(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Xue(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Zue(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:ede(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:tde(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:nde(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:rde(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:ide(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:ode(o),skipIfEmpty:!0}];O.sectionedReport(s)}),G_=[{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:Kue}];function Jue(e){return[`Target: ${e.target}`,`Matched: symbol=${dS(e.matched.symbol)} file=${dS(e.matched.file)} module=${dS(e.matched.module)}`]}function Yue(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}`)),fi(n,t).rows}function Que(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Rt(r.line)} in ${r.enclosingShort}`);return yo(fi(n,t))}function Xue(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(fi([...n,...r],t))}function Zue(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(fi([...n,...r,...i],t))}function ede(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(fi(n,t))}function tde(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(fi(n,t))}function nde(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(fi(n,t))}function rde(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(fi(n,t))}function ide(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 ode(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 fi(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 dS(e){return e?"yes":"no"}import{existsSync as zc}from"fs";import{existsSync as fde,mkdtempSync as gde,rmSync as hde}from"fs";import{tmpdir as yde}from"os";import{dirname as mS,join as fS}from"path";import{performance as Y_}from"perf_hooks";import{spawnSync as bde}from"child_process";import{createHash as sde}from"crypto";import{existsSync as ade,mkdirSync as cde,readFileSync as lde,renameSync as ude,writeFileSync as dde}from"fs";import{homedir as pde}from"os";import{dirname as mde,join as pS}from"path";function z_(e){return sde("sha256").update(e).digest("hex")}function K_(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?pS(t.XDG_CACHE_HOME,"scip-query"):pS(pde(),".cache","scip-query"));return pS(n,e)}async function J_(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(ade(t)){let l=z_(lde(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=z_(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);cde(mde(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return dde(c,s),ude(c,t),{status:"downloaded",path:t,sha256:a}}var Sde=12e4,Z_="v1.8.0",vde=`https://github.com/tlaplus/tlaplus/releases/download/${Z_}/tla2tools.jar`,xde="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function jp(e){let t=e.spawn??bde,n=Rde(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??Sde,i=Y_.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??[])hde(l,{recursive:!0,force:!0})}let s=Math.round(Y_.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:Cde(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Rde(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"&&Pr(Q_(e),t)){let o=Q_(e);return Pr(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:mS(e.specPath)}:Op("apalache",`Apalache binary is not available: ${o}`)}let r=gS(e),i=Pr("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Op(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Op(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:mS(e.specPath)};let s=e.metaDir??gde(fS(yde(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:mS(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Op("none",`unknown checker mode: ${n}`)}function Q_(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function gS(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,eM(t),fS(e.projectRoot,"tla2tools.jar"),fS(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>fde(r))??null}function eM(e=process.env){return K_("tla2tools.jar",e)}async function tM(e={}){let t=e.cachePath??eM(e.env),n=e.expectedSha256??xde,r=e.version??Z_,i=e.url??vde;return{...await J_({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Cde(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=[...X_(n),...X_(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function X_(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Op(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as wde}from"crypto";import{readFileSync as rM}from"fs";import{join as iM}from"path";var oM=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),sM=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),aM=new Set(["readFileSync","existsSync","statSync"]),kde=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Ide=/^\s*SELECT\b/i;function cM(e){return kde.test(e)?"write":Ide.test(e)?"read":null}var Pde=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Ede(e,t){let n=e.match(Pde);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${J(t)}\\b`).test(r)}function lM(e,t,n,r=[],i=[]){let o=[],s=Lde(e,t,o),a=s.aliases,c=Fde(t),l=Nde(t),u=Ade(t),d=$de(e,t,o),p=jde(e,t,o);n&&Bde(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=Hde(e,t,d,a,c,l,u,f,g,o,m),y=Ude(e,d,a,c,l,u,o,m);return Gde(e,d,o),zde(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:yS(d.flatMap(x=>x.referents))+yS(s.referents)+yS(p?.referents??[]),staticWrites:h,staticReads:y,waivers:mpe(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:Dde(o)}}function Dde(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=Tde(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Bp(r.severity)-Bp(n.severity)||n.groupKey.localeCompare(r.groupKey))}function Tde(e,t){return Bp(t)>Bp(e)?t:e}function Bp(e){return e==="error"?2:e==="warning"?1:0}function Lde(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=qp(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}ape(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:ppe(r),referents:i}}function Fde(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 Nde(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 Ade(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=sS(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function _de(e,t,n,r,i,o){return uM(e,t,(s,a,c)=>bo(e,s,a,c,n,r,i,o))}function Mde(e,t,n,r,i,o){return uM(e,t,(s,a,c)=>Wp(e,s,a,c,n,r,i,o))}function uM(e,t,n){let r=Jr(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 $de(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=aS(s),c="error"in a?s:a.ref,u=qp(e,c,n,r).match;return u?(cpe(e,r,s,u,n),"error"in a||!a.window?{ref:s,match:u}:Ode(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 Ode(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=qp(e,s,n,"Init"),c=a.match;return c?lpe(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 Bde(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&&(nM({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)}),nM({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 nM(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 Hde(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=_de(e,g.match.symbol,r,i,o,s).filter(b=>x.has(b.variable));f.push(...R),d.push(...R)}qde(m,f,l,u.get(m.name))}let p=t.unmappedWriteScope==="actions"?[]:ipe(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),Wde(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 vS(d)}function Wde(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function qde(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}${Hp(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}${Hp(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 Ude(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=Wp(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=Mde(e,d.match.symbol,n,r,i,o).filter(h=>f.has(h.variable));u.push(...g),c.push(...g)}Vde(l,u,s,a.get(l.name))}return xS(c)}function Vde(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}${Hp(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}${Hp(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 Gde(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>qp(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=Jr(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 zde(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=dpe(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=Kde(e,t,n,r,i,o,s,a);return c||npe(e,t,n,r,i,o,s,a)}function Wp(e,t,n,r,i,o=[],s=[],a=[]){let c=Jde(e,t,n,r,i,o,s,a);return c||rpe(e,t,n,r,i,o,s,a)}function Kde(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)){Yde(e,t,d,i,l),dM(e,t,d,o,"write",l),pM(e,t,d,s,"write",l),mM(e,t,d,a,"write",l);for(let p of d.children)u(p)}};return u(c.rootNode),vS(l)}function Jde(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)){Zde(e,t,d,i,l),dM(e,t,d,o,"read",l),pM(e,t,d,s,"read",l),mM(e,t,d,a,"read",l);for(let p of d.children)u(p)}};return u(c.rootNode),xS(l)}function Yde(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||!gM(o))return;Uc(e,t,o,"mutation-call",r,i)}}}function dM(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?bS(s):null;if(!a||!(i==="write"?sM:aM).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=Zn(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 bS(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 pM(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=Qde(a);if(c!==null&&cM(c)===i)for(let l of r){if(!l.regex.test(c))continue;let u=Zn(e,t,n.startPosition.row),d=n.childForFieldName("function")??n.namedChild(0),p=(d&&bS(d))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${p}(${Xde(c)})`,kind:"statement",enclosingSymbol:u?.symbol,enclosingShort:u?P(u.symbol):void 0})}}}function Qde(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Xde(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function mM(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?bS(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(!fM(d,a,u,i))continue;let p=Zn(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 fM(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 Zde(e,t,n,r,i){if(!(!epe(n)||tpe(n)))for(let o of r){if(n.text!==o.alias)continue;let s=Zn(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 epe(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function tpe(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&&hS(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&&hS(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&gM(n)&&hS(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 hS(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function gM(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&oM.has(t.text))}function Uc(e,t,n,r,i,o){for(let s of i){if(!upe(s.alias,n.text))continue;let a=Zn(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 npe(e,t,n,r,i,o=[],s=[],a=[]){let l=rM(iM(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(Ede(m,f.alias))continue;let g=J(f.alias);if(!new RegExp(`(?:\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${g}\\b\\s*\\.\\s*(?:${[...oM].join("|")})\\s*\\(|\\b${g}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(m))continue;let y=Zn(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})}hM(e,t,p,m,o,sM,u),yM(e,t,p,m,s,"write",u),bM(e,t,p,m,a,"write",u)}return vS(u)}function rpe(e,t,n,r,i,o=[],s=[],a=[]){let l=rM(iM(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=Zn(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})}hM(e,t,p,m,o,aM,u),yM(e,t,p,m,s,"read",u),bM(e,t,p,m,a,"read",u)}return xS(u)}function hM(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=Zn(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 yM(e,t,n,r,i,o,s){if(i.length!==0&&cM(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=Zn(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 bM(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(!fM(u,c,l,o))continue;let d=Zn(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 ipe(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 qp(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&&!ope(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.`,spe(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 ope(e){return/[/#:]/.test(e)}function spe(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function ape(e,t,n,r,i,o=!1){let s=SS(e,r);if(s===null||fpe.has(s)||o)return;let a=RS.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 ${Wn(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${P(r.symbol)} with SCIP kind ${Wn(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function cpe(e,t,n,r,i){let o=SS(e,r);o===null||SM.has(o)||RS.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 ${Wn(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function lpe(e,t,n,r,i){let o=SS(e,n);o===null||SM.has(o)||i||RS.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 ${Wn(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function SS(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Zn(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 upe(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${J(e)}([^A-Za-z0-9_$]|$)`).test(t)}function dpe(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 vS(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 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 ppe(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 yS(e){return e.filter(t=>t.match).length}function Hp(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 mpe(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 RS=new Set(Pu()),SM=new Set(dn()),fpe=new Set(yw());function Le(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${wde("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as gpe}from"fs";import{basename as hpe,join as vM}from"path";var CS=/^[A-Za-z_][A-Za-z0-9_]*$/;function xM(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=gpe(vM(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&&CS.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:Spe(s,C)),m=null,f;if(p.length>0)f=i.filter(C=>a(C)&&C.parentTypeName===null);else{if(m=ype(e,t,i,a),!m){let C=i.some(k=>!a(k)&&!k.isTypeLike&&k.parentTypeName!==null&&CS.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=>vpe(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=Wp(e,t,C.startLine,C.endLine,h),F=wpe(RM(C.leaf),x);y.push({name:F,leaf:C.leaf,codeRef:bpe(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??kpe(t),b=n.specDir??vM("specs",R),v=Ipe(R,g,y,t),w=Ppe(),I=Epe(R,b,t,g,y);return{moduleName:R,file:t,variables:g,actions:y,warnings:r,spec:v,cfg:w,map:I}}function ype(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!CS.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 bpe(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function Spe(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function vpe(e,t,n,r,i){let o=xpe(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=Rpe(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 xpe(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function Rpe(e,t){let r=t.match(new RegExp(`\\b${Dpe(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=Cpe(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 Cpe(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 RM(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function wpe(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function kpe(e){let n=hpe(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return RM(n||"Model")}function Ipe(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 Ppe(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
|
|
1473
|
-
`)}function Epe(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 Dpe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CM(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:Tpe(n),wiring:r,variables:n}}function Tpe(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 Lpe,mkdtempSync as Fpe,readdirSync as Npe,rmSync as Ape,writeFileSync as wM}from"fs";import{tmpdir as _pe}from"os";import{basename as Mpe,dirname as $pe,join as Gc}from"path";function Up(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 Ope(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=Bpe(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} |-> ${IM(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 kM(e){let t=e.mappedActions??[],n=Ope(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Up(t,[])};let r=Fpe(Gc(_pe(),"scip-tla-trace-"));try{let i=$pe(e.specPath);for(let u of Npe(i))u.endsWith(".tla")&&Lpe(Gc(i,u),Gc(r,u));let o=Gc(r,`${n.moduleName}.tla`),s=Gc(r,`${n.moduleName}.cfg`);wM(o,n.moduleText),wM(s,n.cfgText);let a=jp({...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:Up(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:Up(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:Up(t,l)}}finally{Ape(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 Bpe(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 IM(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>IM(t)).join(", ")}>>`}function PM(e){return Mpe(e).replace(/\.tla$/i,"")}import{mkdirSync as DM,writeFileSync as TM}from"fs";import{dirname as Hpe,join as js}from"path";var Wpe=async(...e)=>{let{args:t,opts:n}=Zb(e),r=U(t,0);if(r==="fetch-tools"){let o=await tM();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=>qpe(s,t,n,o));return}if(r==="instrument"){let o=ke(t,1);Ee(s=>Upe(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=>Vpe(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=>Kpe(o,t,n,i))};function qpe(e,t,n,r){let i=e.config.projectRoot,o=xM(e,r,{moduleName:A(n,"moduleName"),specDir:A(n,"out")}),s=A(n,"out")??js("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:js(a,`${o.moduleName}.tla`),body:o.spec},{path:js(a,`${o.moduleName}.cfg`),body:o.cfg},{path:js(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)`);DM(a,{recursive:!0});for(let u of l)TM(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 ${js(s,`${o.moduleName}.tla`)}'.`)}function Upe(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=Ap(i,o);if(!s.loaded)throw new Error(s.errors.join(`
|
|
1521
|
-
`));let{contract:a,mapDir:c}=s.loaded,l=CM(e,a),u=A(n,"out")??js(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(DM(Hpe(d),{recursive:!0}),TM(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 Vpe(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=Ap(i,s);if(!a.loaded)throw new Error(a.errors.join(`
|
|
1522
|
-
`));let{contract:c}=a.loaded,l=_s(n,"trace"),d=lS(i,[...c.traces,...l]).flatMap(f=>cS(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=kM({specPath:o,baseModuleName:PM(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")&&Gpe(p.actionCoverage),process.exitCode=m}function Gpe(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 zpe(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=c_(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 Kpe(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}=zpe(i,r,o,n),c=Ap(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=r_(i,d,p),f=Ype(A(n,"checker")??"auto"),g=A(n,"tlaTools"),h=Jpe(i,r,o,g)??i_(i,r),y=s_(m),x=_s(n,"trace"),b=lS(i,[...l.traces,...x]).map(F=>({tracePath:F,...cS(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=lM(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=jp({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:Qpe(k,C,E(n,"allowUnknown"))};if(E(n,"json")){H("tla",t,n,T),process.exitCode=T.exitCode;return}Xpe(T,E(n,"full")),process.exitCode=T.exitCode}function Jpe(e,t,n,r){let i=gS({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=zA({specPath:n,jarPath:i});return o?o_(e,t,o):null}var LM=[{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)",Ir),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:Wpe}];function Ype(e){if(!n_(e))throw new Error(`unknown checker mode: ${e}`);return e}function Qpe(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 EM=3;function Xpe(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=eme(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 tme(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)FM(o);return}Zpe(e.conformance)}function Zpe(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,EM)){let o=t.get(i);o&&FM(o)}let r=n.count-EM;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function eme(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 tme(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 FM(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 NM=["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"],nme=[H_,V_,W_,$p,U_,G_,LM,q_],AM=nme.flat(),rme=new Map(AM.map(e=>[e.id,e]));for(let e of AM)if(!NM.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Bs=NM.map(e=>ime(e));function ime(e){let t=rme.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var ome=Bs.slice(0,wS("plan-context")),sme=Bs.slice(Vp("drift"),wS("self-audit")),ame=Bs.slice(Vp("convergence"),wS("slice")),cme=Bs.slice(Vp("redundant-reexports")),_M=[{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",Ir),S("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:N("Indexing",["scip-query reindex"]),handler:uA},{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:dA},{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:pA},...ome,{id:Bd,command:Bd,description:"Internal diff-impact batch worker",hidden:!0,options:[S("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:mA},{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:fA},...sme,{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:gA},{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:hA},{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",Ir,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:yA},{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",Ir,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:bA},{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",Ir),S("--max-mismatches <n>","Maximum mismatch details to include in output",Is),S("--full","Compare every indexed TypeScript-like definition"),S("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:SA},...ame,{id:"install-skills",command:"install-skills",description:`Install skills (${rp.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:N("Maintenance"),handler:RA},{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:CA},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:lL},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:uL},{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:wA},{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:kA},{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:IA},...cme,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:N("Maintenance"),handler:EA},{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:DA},{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:TA},{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:LA},{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:FA},{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:_A},{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:AA},{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:MA},{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:$A},{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)",Is),S("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",Is),S("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Is),S("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",Is)]),renderShape:"custom",docs:N("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:OA},{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:HA}];function Vp(e){let t=Bs.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function wS(e){return Vp(e)+1}function MM(e){return e.evidence?e.evidence:lme.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var lme=new Set(["diff-gate","health","plan-context","co-change"]);function $M(e,t){return eA(new Map(t.map(n=>[n.id,MM(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){ume(o)}}),{descriptor:n,command:r}})}function ume(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as dme,mkdirSync as pme,readFileSync as mme,writeFileSync as fme}from"fs";import{homedir as gme}from"os";import{join as Gp}from"path";var hme=1440*60*1e3,jM="update-check.json",yme="https://registry.npmjs.org/scip-query/latest";async function BM(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER||e.commandName&&bme(e.commandName))return;let n=e.cacheDir??xme(t),r=e.now??Date.now(),i=e.currentVersion??Fe,o=Rme(n),s=o&&r-o.checkedAt<hme?o.latestVersion:await Cme(n,e.fetchLatestVersion??kme,r);if(!s||!vme(s,i))return;(e.writeNotice??(c=>console.error(c)))(Sme(i,s))}function bme(e){return e==="hook-context"||e==="hook-stop"}function Sme(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 vme(e,t){let n=OM(e),r=OM(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 xme(e){let t=e.XDG_CACHE_HOME||Gp(gme(),".cache");return Gp(t,"scip-query")}function Rme(e){let t=Gp(e,jM);if(!dme(t))return null;try{let n=JSON.parse(mme(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 Cme(e,t,n){let r;try{r=await t()}catch{r=null}return wme(e,{checkedAt:n,latestVersion:r}),r}function wme(e,t){try{pme(e,{recursive:!0}),fme(Gp(e,jM),`${JSON.stringify(t,null,2)}
|
|
1529
|
-
`)}catch{}}async function kme(){let e=await fetch(yme,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function OM(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}zp.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Fe);$M(zp,_M);zp.hook("preAction",async(e,t)=>{Pme();let n=t.name();await BM({commandName:n});let r=rT(n),i=Af(n);if(!r&&!i)return;let o=Me(),s=ut(o),a=Gt(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(NN(o,Fe),!i)return;let c=su({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 Pme(){if(ol(),!re()||sl())return;let e=null;try{e=Ee(t=>Ye(t))}catch{}hm({command:il()??`scip-query ${process.argv.slice(2).join(" ")}`,toolVersion:Fe,projectFingerprint:e})}Eme()&&await zp.parseAsync();function Eme(){if(!process.argv[1])return!1;let e=Ime(import.meta.url);try{return HM(e)===HM(process.argv[1])}catch{return e===process.argv[1]}}export{zp as program,Jt as renderHeuristicNotice};
|
|
2
|
+
import{a as g}from"./chunk-XTF6ELXT.js";import{$c as V,Ec as a,Y as A,a as E,ad as f,bd as I,da as P,dd as U,ea as x,ed as _,fa as S,fd as j,h as v,ha as k,i as D,j as w,k as N,l as b,qd as W,xd as T}from"./chunk-6AITNECC.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-CVCFER5G.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-7UUURHWT.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
|