scip-query 0.19.8 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/README.md +158 -48
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-26QA6FAI.js +8 -0
- package/dist/{chunk-KJ2IIBZN.js → chunk-2HPVVXM5.js} +2 -2
- package/dist/chunk-2KAZEZ6M.js +2 -0
- package/dist/chunk-32LVLCLN.js +40 -0
- package/dist/{chunk-24GTWJ3N.js → chunk-3CLX5EOX.js} +2 -2
- package/dist/{chunk-QGGLL3UH.js → chunk-3G66UZBH.js} +2 -2
- package/dist/{chunk-AA4UWRNL.js → chunk-3ORVDL3H.js} +2 -2
- package/dist/chunk-4MAK2HOY.js +6 -0
- package/dist/{chunk-QIQ63BHW.js → chunk-4TURLRL5.js} +2 -2
- package/dist/chunk-4UQVNCQE.js +2 -0
- package/dist/chunk-55Q3WLZX.js +2 -0
- package/dist/{chunk-CTF2GDEX.js → chunk-5E4WNAVD.js} +2 -2
- package/dist/{chunk-ZCEJ63SP.js → chunk-5I5G2QOX.js} +2 -2
- package/dist/chunk-6LDJQXAH.js +2 -0
- package/dist/{chunk-3EDFLQ6A.js → chunk-6O5TICIZ.js} +2 -2
- package/dist/{chunk-ACAM6O5R.js → chunk-6SHPK5ZE.js} +2 -2
- package/dist/chunk-7BAVHKMJ.js +49 -0
- package/dist/chunk-7O5IKBTZ.js +16 -0
- package/dist/{chunk-WJL2L6MV.js → chunk-7PIO7NKH.js} +2 -2
- package/dist/chunk-7S5E7KWT.js +2 -0
- package/dist/{chunk-YLFORA5G.js → chunk-7SQQWSY3.js} +2 -2
- package/dist/chunk-7WPLAODU.js +5 -0
- package/dist/chunk-A73XVBCR.js +20 -0
- package/dist/chunk-AFHORGLH.js +42 -0
- package/dist/chunk-AIE7TFJW.js +9 -0
- package/dist/{chunk-TWMJ3Y3G.js → chunk-AZJQQKDD.js} +2 -2
- package/dist/{chunk-BDOIKGDI.js → chunk-B2PX5I6M.js} +2 -2
- package/dist/{chunk-DQBCO2UY.js → chunk-B7PBSLZN.js} +2 -2
- package/dist/chunk-BBW6JFHN.js +2 -0
- package/dist/{chunk-YTVWB7YJ.js → chunk-BDCC2NPY.js} +2 -2
- package/dist/{chunk-O23I56NA.js → chunk-BNXCIFVY.js} +2 -2
- package/dist/{chunk-MLFZP76A.js → chunk-BPAPWKP6.js} +2 -2
- package/dist/chunk-BS2NMXQZ.js +4 -0
- package/dist/chunk-C3KV2II6.js +2 -0
- package/dist/chunk-C43RDDP4.js +20 -0
- package/dist/{chunk-K2WO7XY7.js → chunk-CJST5ETY.js} +2 -2
- package/dist/chunk-DAFAHMNB.js +42 -0
- package/dist/{chunk-KKME5ZAI.js → chunk-DQGFVPUV.js} +2 -2
- package/dist/chunk-DQLPXMH6.js +8 -0
- package/dist/chunk-EKZTZXHZ.js +117 -0
- package/dist/{chunk-FJ5UDTQF.js → chunk-EN3O7VJA.js} +2 -2
- package/dist/{chunk-HZYDQPNY.js → chunk-EW2NTSFA.js} +2 -2
- package/dist/chunk-F3Z4OUDS.js +8 -0
- package/dist/chunk-FJH2NW7J.js +66 -0
- package/dist/{chunk-MSBDMFER.js → chunk-FKSELJQF.js} +2 -2
- package/dist/chunk-FTFP6O3L.js +11 -0
- package/dist/chunk-FYLK2DEJ.js +2 -0
- package/dist/{chunk-WUW7YUAH.js → chunk-GH74ASD6.js} +2 -2
- package/dist/{chunk-464PLI5O.js → chunk-GMXWZP2B.js} +2 -2
- package/dist/chunk-GOUBFH5O.js +3 -0
- package/dist/{chunk-FIJCV235.js → chunk-HLF2TX6R.js} +2 -2
- package/dist/{chunk-WWKWUPSU.js → chunk-HX4GQPZP.js} +2 -2
- package/dist/chunk-HX7M4BDI.js +30 -0
- package/dist/chunk-HZ72SESS.js +128 -0
- package/dist/{chunk-SERUIGV5.js → chunk-IB2N4FIY.js} +2 -2
- package/dist/chunk-ILMHV3KM.js +2 -0
- package/dist/chunk-IZYYAFN5.js +2 -0
- package/dist/{chunk-GNC4JVAN.js → chunk-JAYYFEQY.js} +2 -2
- package/dist/{chunk-QJIVBYEK.js → chunk-JDOEX4E6.js} +2 -2
- package/dist/chunk-JFGGXWQF.js +947 -0
- package/dist/chunk-JN4NMBEX.js +8 -0
- package/dist/{chunk-6M7RONVB.js → chunk-JVYA47YU.js} +2 -2
- package/dist/{chunk-7KYNAMMH.js → chunk-JW56N3KI.js} +2 -2
- package/dist/{chunk-OUBAF226.js → chunk-JZ2OXNWB.js} +2 -2
- package/dist/chunk-KMKTIO2G.js +8 -0
- package/dist/chunk-L5GJNV2T.js +8 -0
- package/dist/{chunk-MNSTUIDD.js → chunk-L7AW2QB5.js} +2 -2
- package/dist/chunk-L7JDSCDF.js +4 -0
- package/dist/chunk-LU47HG23.js +14 -0
- package/dist/chunk-LVY7NPF7.js +2 -0
- package/dist/chunk-LY4WC4AD.js +74 -0
- package/dist/{chunk-7FT5Y65S.js → chunk-MKCDWWGV.js} +2 -2
- package/dist/chunk-MNE7YG56.js +2 -0
- package/dist/{chunk-7QHY3H7P.js → chunk-MRXBEXSY.js} +2 -2
- package/dist/chunk-MV7OWDUX.js +2 -0
- package/dist/{chunk-ZJ5CBXK3.js → chunk-N5W4YZMK.js} +2 -2
- package/dist/chunk-NGEXCJJW.js +11 -0
- package/dist/{chunk-7SWJEWJF.js → chunk-NIW6JDC5.js} +2 -2
- package/dist/{chunk-O3O4XXO6.js → chunk-O64IZ6UX.js} +2 -2
- package/dist/{chunk-3ZSJ3PWF.js → chunk-PBUQFCNB.js} +2 -2
- package/dist/{chunk-7RAG65VK.js → chunk-POAVPHH7.js} +2 -2
- package/dist/{chunk-A3QXWFBK.js → chunk-PQCI4SQX.js} +2 -2
- package/dist/{chunk-4BV4QAZJ.js → chunk-PXY7F6Y4.js} +2 -2
- package/dist/chunk-RDO52JGY.js +2 -0
- package/dist/chunk-RJT3TUUZ.js +2 -0
- package/dist/{chunk-S4S2WOIX.js → chunk-RUJURYSV.js} +2 -2
- package/dist/{chunk-JAY7YWS3.js → chunk-RVLDN63O.js} +2 -2
- package/dist/chunk-RXOXSKY3.js +2 -0
- package/dist/chunk-S7OYBOCK.js +2 -0
- package/dist/chunk-SMNXQT5Z.js +3 -0
- package/dist/{chunk-NE3TZUCI.js → chunk-SRAFT254.js} +2 -2
- package/dist/{chunk-ELLMY7XJ.js → chunk-SXP2MBJH.js} +2 -2
- package/dist/chunk-T7YQSHPQ.js +3 -0
- package/dist/{chunk-WY45BHKQ.js → chunk-TFRAYKN6.js} +2 -2
- package/dist/{chunk-2SNGN6U4.js → chunk-UJCOIXDY.js} +2 -2
- package/dist/{chunk-MZZBAITE.js → chunk-UJPRPGCO.js} +2 -2
- package/dist/chunk-W4ETQAXM.js +2 -0
- package/dist/chunk-WCCFZ7V7.js +113 -0
- package/dist/chunk-WUPW3UN3.js +3 -0
- package/dist/{chunk-7LSVMFX7.js → chunk-WXZLAAWK.js} +2 -2
- package/dist/{chunk-5ML2BNRH.js → chunk-X54AGLVX.js} +2 -2
- package/dist/chunk-XKWKXZKW.js +20 -0
- package/dist/{chunk-5YLUDDAF.js → chunk-XSRF6Q77.js} +2 -2
- package/dist/chunk-Y2MVPNKY.js +5 -0
- package/dist/{chunk-JHF3E4YM.js → chunk-YKUU5AIC.js} +2 -2
- package/dist/{chunk-E3HYEQO7.js → chunk-YLCJLTPL.js} +2 -2
- package/dist/{chunk-7VCOXZH3.js → chunk-YTQVETEO.js} +2 -2
- package/dist/chunk-Z4N3MZYA.js +38 -0
- package/dist/chunk-ZHXX42OH.js +18 -0
- package/dist/chunk-ZJOOT3BG.js +2 -0
- package/dist/{chunk-P3UO3EH3.js → chunk-ZK26BAQL.js} +2 -2
- package/dist/{chunk-33KUO7CG.js → chunk-ZTETIQ35.js} +2 -2
- package/dist/cli.js +3 -8
- package/dist/command-descriptors-DSS46KXI.js +642 -0
- package/dist/{config-types-B6MEoRNy.d.ts → config-types-jVM3D7MA.d.ts} +68 -2
- package/dist/{db-DYLKr9Wn.d.ts → db-B5PM5yNk.d.ts} +20 -2
- package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
- package/dist/direct-navigation-6YHV6IB5.js +3 -0
- package/dist/{health-DgxIDXJC.d.ts → health-Do5TKSJI.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +22 -3
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +3 -3
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +3 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +40 -7
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +84 -6
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +3 -3
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +3 -3
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +12 -3
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +8 -6
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +141 -10
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +34 -3
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +3 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +3 -3
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +14 -3
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +21 -21
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +33 -33
- package/dist/runtime.d.ts +5 -3
- package/dist/runtime.js +3 -3
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-Cc6c00-a.d.ts → scip-cli-BnEwZRLJ.d.ts} +1 -1
- package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
- package/dist/typescript-mailbox-worker.js +2 -0
- package/dist/watch-server.js +2 -42
- package/docs/AGENT_GUIDE.md +13 -6
- package/docs/CLI_JSON_OUTPUT.md +110 -22
- package/docs/COMMAND_REFERENCE.md +88 -88
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
- package/docs/DURABILITY.md +88 -38
- package/docs/INDEX_GENERATIONS.md +65 -19
- package/docs/MAILBOX_LIFECYCLE.md +28 -1
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
- package/docs/SECURITY_MODEL.md +31 -14
- package/docs/TELEMETRY_RETENTION.md +11 -4
- package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
- package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
- package/docs/analyzer-inventory.md +31 -22
- package/docs/analyzer-validation-ledger.md +8 -0
- package/docs/schemas/outcome-event-record.schema.json +57 -1
- package/docs/schemas/project-config.schema.json +82 -1
- package/docs/schemas/suppression-record.schema.json +84 -3
- package/package.json +5 -5
- package/skills/_shared/SKILL.md +2 -2
- package/skills/_shared/references/agent-contract-catalog.md +1 -1
- package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
- package/skills/scip-audit/SKILL.md +6 -6
- package/skills/scip-audit/references/claims.md +1 -1
- package/skills/scip-audit/references/cleanup.md +19 -20
- package/skills/scip-audit/references/directory.md +4 -4
- package/skills/scip-audit/references/frontend.md +10 -10
- package/skills/scip-audit/references/twin-drift.md +2 -2
- package/skills/scip-diagnose/references/debug.md +8 -8
- package/skills/scip-diagnose/references/root-cause.md +3 -3
- package/skills/scip-diagnose/references/triage.md +10 -10
- package/skills/scip-explore/SKILL.md +3 -3
- package/skills/scip-improve/SKILL.md +10 -10
- package/skills/scip-improve/references/cleanup-batches.md +3 -3
- package/skills/scip-improve/references/directory-moves.md +3 -3
- package/skills/scip-improve/references/doc-reconcile.md +1 -1
- package/skills/scip-improve/references/frontend-extraction.md +2 -2
- package/skills/scip-improve/references/twin-drift.md +3 -3
- package/skills/scip-plan/SKILL.md +2 -2
- package/skills/scip-plan/references/api-impact.md +5 -5
- package/skills/scip-plan/references/conductor.md +2 -2
- package/skills/scip-plan/references/hyper-optimization.md +1 -1
- package/skills/scip-query/SKILL.md +15 -5
- package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
- package/skills/scip-setup/references/language-verification.md +2 -2
- package/skills/scip-setup/references/per-repo-triage.md +1 -1
- package/skills/scip-verify/SKILL.md +10 -10
- package/skills/scip-verify/references/calibrate-detectors.md +7 -7
- package/dist/chunk-2465DLHK.js +0 -3
- package/dist/chunk-2U3OLUNJ.js +0 -61
- package/dist/chunk-33XTHFKR.js +0 -2
- package/dist/chunk-43KC6EQZ.js +0 -2
- package/dist/chunk-47BU5Z4T.js +0 -8
- package/dist/chunk-4YTUWQ6M.js +0 -18
- package/dist/chunk-64MNV6AB.js +0 -8
- package/dist/chunk-67QRR5YC.js +0 -6
- package/dist/chunk-6GXYN7YA.js +0 -40
- package/dist/chunk-A2TNXAXO.js +0 -8
- package/dist/chunk-APMMR5Y2.js +0 -2
- package/dist/chunk-AZFUMCQB.js +0 -2
- package/dist/chunk-BNXICU42.js +0 -33
- package/dist/chunk-C5Q44Q5D.js +0 -3
- package/dist/chunk-DQGSM7RZ.js +0 -20
- package/dist/chunk-E2LAW7SL.js +0 -30
- package/dist/chunk-E4NFOAD4.js +0 -6
- package/dist/chunk-E5HNT4X2.js +0 -3
- package/dist/chunk-FD3HFKXR.js +0 -5
- package/dist/chunk-GHKEJTCE.js +0 -35
- package/dist/chunk-GLZTVKAB.js +0 -16
- package/dist/chunk-HIB452NU.js +0 -949
- package/dist/chunk-IF6FP6B2.js +0 -66
- package/dist/chunk-JORHF5AL.js +0 -108
- package/dist/chunk-KSGTULOS.js +0 -9
- package/dist/chunk-KXDJAG4N.js +0 -38
- package/dist/chunk-L4S2A7BV.js +0 -2
- package/dist/chunk-LP3ARJKF.js +0 -8
- package/dist/chunk-LSOR3LQG.js +0 -3
- package/dist/chunk-NTUMF2X3.js +0 -56
- package/dist/chunk-QOXBSI6G.js +0 -20
- package/dist/chunk-QXK6UUSM.js +0 -2
- package/dist/chunk-RA3AYNWP.js +0 -112
- package/dist/chunk-RJMDJR3A.js +0 -2
- package/dist/chunk-RLH5VUMG.js +0 -2
- package/dist/chunk-SMQWE25B.js +0 -3
- package/dist/chunk-TAVELHYR.js +0 -2
- package/dist/chunk-VAXNI5NE.js +0 -146
- package/dist/chunk-VVY2G5ET.js +0 -2
- package/dist/chunk-W3DBTGL4.js +0 -11
- package/dist/chunk-WANA4KAQ.js +0 -5
- package/dist/chunk-X4FR5BZF.js +0 -9
- package/dist/chunk-X6RKPDY7.js +0 -2
- package/dist/chunk-YCPASUCX.js +0 -2
- package/dist/chunk-ZL2OGDCD.js +0 -2
- package/dist/command-descriptors-ZW5J4ZEM.js +0 -631
- package/dist/direct-navigation-42YHQPOI.js +0 -3
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as $d,d as Cd,e as kr,f as wr,g as Pd,h as Td,i as Ed,l as Id,n as Ad}from"./chunk-LU47HG23.js";import{a as lt,b as k,c as qt,d as Ze,e as we,f as p,g as oo,h as gd,i as T,j as P,k as w,l as ge,m as he,n as Le,o as bn,p as wd}from"./chunk-F3Z4OUDS.js";import{$a as Ui,$b as wc,$c as hl,$d as zl,$e as ne,A as B,Aa as Ea,Ab as Za,Ac as zc,Ad as ze,Ae as cd,B as da,Ba as Ia,Bc as Qc,Bd as Ml,Be as gr,C as ua,Ca as Aa,Cb as ec,Cc as Yc,Cd as bt,Ce as hr,D as pa,Da as ir,Db as tc,Dc as Xc,Dd as Xi,De as ld,E as zn,Ea as ja,Eb as nc,Ec as Zc,Ed as Zi,Ee as ro,F as J,Fa as Dt,Fb as rc,Fc as lr,Fd as Nl,Fe as yr,G as Z,Ga as Oa,Gb as ic,Gc as el,Gd as pr,Ha as mn,Hb as oc,Hc as tl,Hd as St,He as io,Ia as Mt,Ib as sc,Ic as ct,Id as mr,Ie as br,Ja as W,Jb as ac,Jc as nl,Jd as Qe,Je as dd,Ka as La,Kb as cc,Kc as rl,Kd as ke,Ke as qe,La as Vi,Lb as lc,Lc as il,Ld as _t,Le as fe,M as cn,Mc as ol,Md as Ie,Me as U,N as ln,Nb as dc,Nc as sl,Nd as Fl,Ne as Sr,O as dn,Ob as uc,Oc as al,Od as _l,Oe as O,P as ma,Pa as or,Pb as pc,Pc as cl,Pd as Bl,Pe as hn,Q as Ue,Qa as Da,Qb as mc,Qc as zi,Qd as vt,Qe as yn,R as Qn,Ra as Wi,Rb as fc,Rc as Be,Rd as ql,Re as Ve,S as fa,Sa as Ma,Sb as gc,Sc as Qi,Sd as Vl,Se as ud,T as Je,Ta as Hi,Tb as hc,Tc as ll,Td as Wl,Te as vr,U as ga,Ua as Gi,Ub as yc,Uc as dl,Ud as Hl,Ue as Rr,V as Yn,Va as Na,Vb as bc,Vc as dr,Vd as Ye,Ve as pd,W as ha,Wa as sr,Wb as Sc,Wc as ul,Wd as Ae,We as md,X as qi,Xb as vc,Xc as pl,Xd as Gl,Xe as fd,Y as ya,Yb as Rc,Yc as ml,Yd as Ul,Z as ba,Za as Fa,Zb as xc,Zc as fl,Zd as Jl,_ as Sa,_a as ar,_b as kc,_c as gl,_d as Kl,_e as ue,a as Un,aa as va,ac as gn,ad as yl,ae as Ql,af as hd,b as ia,ba as Xn,bb as _a,bc as $c,bd as bl,be as Yl,bf as yd,c as oa,ca as re,cb as Ee,cc as Cc,cd as Sl,ce as Xl,cf as bd,d as Jn,da as Ra,dc as Pc,dd as vl,de as Zl,df as dt,e as At,ec as Tc,ed as Rl,ee as ed,ef as Sd,fa as Zn,fb as _e,fc as Ec,fd as me,fe as td,ff as Oe,g as sa,ga as xa,gb as Ba,gc as Ic,gd as xl,ge as fr,gf as vd,h as Mi,ha as ka,hb as qa,hc as Ac,hd as Yi,he as nd,hf as Se,i as on,ia as er,ib as Va,ic as jc,id as ur,if as xr,j as jt,jb as Wa,jc as Oc,jd as kl,je as eo,jf as Rd,k as Ni,kb as fn,kc as Lc,kd as wl,ke as rd,kf as M,l as aa,lb as Ha,lc as Dc,ld as $l,le as to,lf as K,m as Fi,mb as Ga,mc as Mc,md as Cl,me as id,mf as C,n as ca,na as un,nb as cr,nc as Nc,nd as Pl,ne as od,nf as X,oa as wa,ob as Ua,oc as Fc,od as Tl,of as S,pa as $a,pc as _c,pd as El,pe as te,pf as Rt,q as Kn,qa as Ca,qb as Nt,qc as Ki,qd as Il,qf as I,r as ce,ra as Ke,rb as Ji,rc as Bc,rd as Al,re as sd,rf as N,s as la,sa as Ot,sb as Ja,sc as qc,se as Xe,sf as xd,t as Re,ta as tr,tc as Vc,td as jl,te as Bt,tf as A,u as xe,ua as nr,ub as Ka,uc as Wc,ud as Ol,ue as ad,uf as kd,v as _i,va as Lt,vb as za,vc as Hc,vd as Ll,vf as Y,w as sn,wa as rr,wb as Qa,wc as Gc,wd as be,we as de,x as Bi,xa as pn,xb as Ya,xc as Uc,xd as Dl,y as an,ya as Pa,yb as Ft,yc as Jc,ye as je,z as G,za as Ta,zb as Xa,zc as Kc,ze as no}from"./chunk-JFGGXWQF.js";import{randomUUID as vb}from"crypto";import{unlinkSync as Rb}from"fs";import{join as Kd}from"path";import{fileURLToPath as xb}from"url";import{createHash as lb,randomUUID as db}from"crypto";import{createHash as tb}from"crypto";import{existsSync as Tr,mkdirSync as nb,readdirSync as rb,rmSync as Dd,writeFileSync as Nd}from"fs";import{join as et}from"path";var so="scip-query-outcome-event",$r=1;function Cr(e){return JSON.stringify([e.check,e.findingId,e.event,e.commit])}function Od(e,t){if(t.trim()==="")throw new Error("outcome event writer requires a non-empty tool version");return{...e,kind:so,schemaVersion:$r,eventIdentity:Cr(e),writer:{tool:"scip-query",version:t}}}function Ld(e){if(!At(e))return{state:"malformed",error:"not an outcome event object"};let t=e,n=t.schemaVersion;if(n===void 0){if(t.kind!==void 0||t.eventIdentity!==void 0||t.writer!==void 0)return{state:"malformed",error:"outcome event envelope metadata requires schemaVersion"};let o=jd(t);return o?{state:"legacy",event:o,record:o,schemaVersion:0}:{state:"malformed",error:"invalid legacy outcome event fields"}}if(!Number.isSafeInteger(n)||n<1)return Number.isSafeInteger(n)?{state:"unsupported-older",error:`unsupported schemaVersion ${String(n)}`}:{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n!==$r)return{state:n>$r?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n)}`};if(t.kind!==so)return{state:"malformed",error:`kind must be ${so}`};let r=jd(t);if(!r)return{state:"malformed",error:"invalid current outcome event fields"};if(t.eventIdentity!==Cr(r))return{state:"malformed",error:"eventIdentity does not match the outcome event"};let i=t.writer;return!At(i)||i.tool!=="scip-query"||typeof i.version!="string"||i.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:{state:"current",event:r,record:t,schemaVersion:$r}}var Qy=["caught","resolved","suppressed","reopened"];function jd(e){if(!(typeof e.ts!="number"||!Number.isFinite(e.ts)||typeof e.check!="string"||e.check.trim()===""||typeof e.findingId!="string"||e.findingId.trim()===""||!Qy.includes(e.event)||e.commit!==null&&typeof e.commit!="string"||e.comparisonBaseCommit!==void 0&&typeof e.comparisonBaseCommit!="string"||e.verifiedAgainstCommit!==void 0&&(e.event!=="resolved"||typeof e.verifiedAgainstCommit!="string")||e.symbol!==void 0&&typeof e.symbol!="string"||e.gateRunId!==void 0&&!eb(e.gateRunId)||e.observer!==void 0&&!Zy(e.observer)||e.observation!==void 0&&!lr(e.observation)||e.suppressionPolicyVersion!==void 0&&(e.event!=="suppressed"||!Number.isSafeInteger(e.suppressionPolicyVersion)||e.suppressionPolicyVersion<1)))return{ts:e.ts,check:e.check,findingId:e.findingId,event:e.event,commit:e.commit,...typeof e.comparisonBaseCommit=="string"?{comparisonBaseCommit:e.comparisonBaseCommit}:{},...typeof e.verifiedAgainstCommit=="string"?{verifiedAgainstCommit:e.verifiedAgainstCommit}:{},...typeof e.symbol=="string"?{symbol:e.symbol}:{},...typeof e.gateRunId=="string"?{gateRunId:e.gateRunId}:{},...e.observer!==void 0?{observer:e.observer}:{},...e.observation!==void 0?{observation:e.observation}:{},...typeof e.suppressionPolicyVersion=="number"?{suppressionPolicyVersion:e.suppressionPolicyVersion}:{}}}var Yy=["local-agent","local-human","protected-ci"],Xy=["repository-writable","protected-external"];function Zy(e){if(!At(e))return!1;let t=e.kind,n=e.authority;return Yy.includes(t)&&Xy.includes(n)&&(n!=="protected-external"||t==="protected-ci")&&(e.source===void 0||typeof e.source=="string"&&e.source.length>0&&e.source.length<=256)}function eb(e){return typeof e=="string"&&e.length>0&&e.length<=256&&!/[\0\r\n]/u.test(e)}var Sn=et(".scipquery","events"),Fd=et(".scipquery","ledger"),ao="events.jsonl";function _d(e){return et(e,Fd)}function co(e){return et(_d(e),ao)}function Bd(e,t,n){let r=co(e),i=Tr(r),o=i?qd(r):ab(),s=[...o.events,...t];if(s.length>0){let a=et(e,Sn);nb(a,{recursive:!0});for(let c of s)ib(a,c,n.toolVersion)}if(i&&o.compatibility.complete)ob(e);else if(i)return{warning:`legacy outcome ledger preserved because ${o.compatibility.omitted} of ${o.compatibility.total} non-empty record(s) are incompatible: ${o.warnings.join("; ")}`};return{}}function ib(e,t,n){let r=`${JSON.stringify(Od(t,n),null,2)}
|
|
3
|
+
`,i=tb("sha256").update(r).digest("hex").slice(0,16).toUpperCase(),o=et(e,`${t.ts}-${i}.json`);try{Nd(o,r,{flag:"wx"})}catch(s){if(s.code!=="EEXIST")throw s;if(B(o,"outcome event record")!==r)throw new Error(`outcome event filename collision: ${o}`,{cause:s})}}function ob(e){Dd(co(e));let t=et(_d(e),".gitattributes");if(!Tr(t))return;let n=B(t,"outcome event attributes").split(`
|
|
4
|
+
`).filter(r=>r.trim()!==`${ao} merge=union`).join(`
|
|
5
|
+
`).replace(/^\n+|\n+$/g,"");n===""?Dd(t):Nd(t,`${n}
|
|
6
|
+
`)}function Er(e){let t=[],n=[],r=et(e,Sn);if(Tr(r))for(let o of rb(r).sort()){if(!o.endsWith(".json"))continue;let s=`${Sn}/${o}`,a=Vd(B(et(r,o),"outcome event record"));n.push({path:s,state:a.state,..."error"in a?{reason:a.error}:{}}),"event"in a&&t.push(a.event)}let i=co(e);if(Tr(i)){let o=qd(i);t.push(...o.events),n.push(...o.observations)}return lo(t,n)}function qd(e){let t=[],n=[],r=`${Fd}/${ao}`;for(let[i,o]of ua(e,"legacy outcome-event ledger").split(`
|
|
7
|
+
`).entries()){if(o.trim()==="")continue;let s=Vd(o);n.push({path:`${r}:${i+1}`,state:s.state,..."error"in s?{reason:s.error}:{}}),"event"in s&&t.push(s.event)}return{...lo(t,n),observations:n}}function Vd(e){if(e.trim()==="")return{state:"malformed",error:"empty record"};let t;try{t=JSON.parse(e)}catch{return{state:"malformed",error:"malformed JSON"}}return Ld(t)}function sb(e){let t=new Map;for(let n of e){let r=Cr(n),i=t.get(r);(!i||Pr(n)>Pr(i)||Pr(n)===Pr(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts||n.check.localeCompare(r.check)||n.findingId.localeCompare(r.findingId)||Md(n.event)-Md(r.event))}function Pr(e){return+(e.verifiedAgainstCommit!==void 0)*64+ +(e.comparisonBaseCommit!==void 0)*32+ +(e.observer?.authority==="protected-external")*16+ +(e.observer!==void 0)*8+ +(e.observation!==void 0)*4+ +(e.gateRunId!==void 0)*2+ +(e.suppressionPolicyVersion!==void 0)}function Md(e){return e==="caught"?0:e==="resolved"?1:e==="suppressed"?2:3}function lo(e,t){let n=tl(t);return{events:sb(e),compatibility:n,warnings:n.issues.map(r=>`${r.path}: ${r.reason} \u2014 ignored`)}}function ab(){return{...lo([],[]),observations:[]}}import{createHash as Wd}from"crypto";import{resolve as cb}from"path";function vn(e){let t=e.db?{generationIdentity:e.db.generation.identity,source:e.db.generation.source,alignment:"not-certified"}:void 0,n=e.gitContext?{identity:Wd("sha256").update(JSON.stringify({worktreeId:e.gitContext.worktreeId,headCommit:e.gitContext.headCommit,status:e.statusPorcelain??"",trackedDiff:e.trackedDiff??""})).digest("hex"),clean:e.gitContext.clean,...e.gitContext.headCommit?{headCommit:e.gitContext.headCommit}:{},...e.gitContext.treeOid?{treeOid:e.gitContext.treeOid}:{}}:void 0;return{schemaVersion:1,authorityKind:t?n?"index-worktree":"index-only":n?"worktree-only":"process-local",observedAt:(e.observedAt??new Date).toISOString(),projectIdentity:Wd("sha256").update(cb(e.projectRoot)).digest("hex"),...t?{index:t}:{},...n?{worktree:n}:{}}}function Hd(e){let t=Ee(e.projectRoot);return{...vn({projectRoot:e.projectRoot,observedAt:new Date(e.observedAt),...t?{gitContext:t}:{}}),authorityKind:"index-worktree",index:{generationIdentity:e.generationIdentity,source:e.generationSource,alignment:"leased"},worktree:{identity:e.worktreeIdentity,clean:t?.clean??!1,...t?.headCommit?{headCommit:t.headCommit}:{},...t?.treeOid?{treeOid:t.treeOid}:{}}}}function Gd(){let e=sd(),t=e?.config.projectRoot??te();if(!e)return vn({projectRoot:t});let n=Ee(t);return vn({projectRoot:t,db:e,...n?{gitContext:n,statusPorcelain:_e(t,["status","--porcelain=v1","-z","--untracked-files=all"])??"",trackedDiff:_e(t,["diff","--no-ext-diff","--binary","HEAD","--"])??""}:{}})}function Jd(e,t,n={}){let r=(n.now??Date.now)(),i=n.observationId??db(),o=n.observer??pb(),s=bb(t),a=wl(e),c=e.config.projectRoot,l=n.headCommit?n.headCommit(c):Ee(c)?.headCommit??null,d=n.resolveCommit?n.resolveCommit(c,t.base):yb(c,t.base),u=n.observation??mb(e,c,r),m=fb({previous:a,observed:s,result:t,projectRoot:c,commit:l,comparisonBaseCommit:d,runtime:n}),f=$l(e,m.ledgerObserved,m.checksRun,r,m.retainedKeys,i),g=f.current,h=f.status==="busy"?"finding outcome ledger not updated: evidence database remained busy":f.status==="unavailable"?"finding outcome ledger not updated: evidence database unavailable":f.status==="conflict"?`finding outcome ledger not updated: observation id ${i} names different evidence`:void 0;try{let b=new Map;for(let v of t.findings)v.symbol&&b.set(v.id,v.symbol);for(let v of t.suppressed)v.finding.symbol&&b.set(v.finding.id,v.finding.symbol);let y=new Map;for(let v of t.suppressed){let E=v.suppression.decision?.policyVersion;E!==void 0&&y.set(me(v.finding.check,v.finding.id),E)}for(let[v,E]of m.replaySymbols)b.set(v,E);let R=xl(f.previous,g,b,l,r,{...d?{comparisonBaseCommit:d}:{},verifiedAgainstByFinding:m.verifiedAgainstByFinding,gateRunId:i,observer:o,observation:u,suppressionPolicyVersionByFinding:y}),$;return n.appendEvents?n.appendEvents(c,R):$=Bd(c,R,{toolVersion:be}).warning,{ledger:g,observed:s,now:r,...Ud(m.warning,h,$)}}catch(b){return{ledger:g,observed:s,now:r,...Ud(m.warning,h,`outcome event ledger not updated: ${b instanceof Error?b.message:String(b)}`)}}}function ub(e,t){return{kind:e,authority:"repository-writable",...t?{source:t}:{}}}function pb(e=process.env){let t=e.SCIP_QUERY_OUTCOME_OBSERVER_KIND==="local-human"?"local-human":"local-agent",n=e.SCIP_QUERY_OUTCOME_OBSERVER_SOURCE?.trim();return ub(t,n&&n.length<=256?n:void 0)}function mb(e,t,n){let r=Ee(t);return vn({projectRoot:t,observedAt:new Date(n),db:e,...r?{gitContext:r,statusPorcelain:_e(t,["status","--porcelain=v1","-z","--untracked-files=all"])??"",trackedDiff:_e(t,["diff","--no-ext-diff","--binary","HEAD","--"])??""}:{}})}function Ud(...e){let t=e.filter(n=>!!n).join("; ");return t?{warning:t}:{}}function fb(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(v=>me(v.check,v.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!ll(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(v=>v.outcome!=="resolved"&&(a.has(v.check)||c)&&!s.has(me(v.check,v.findingId)));if(xt(`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 d;try{d=(e.runtime.readEvents??Er)(e.projectRoot)}catch(v){for(let E of l)r.add(me(E.check,E.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${v instanceof Error?v.message:String(v)}`}}if(!d.compatibility.complete){for(let v of l)r.add(me(v.check,v.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${ct("committed outcome history",d.compatibility)}`}}let u=d.events,m=new Map;for(let v of u){let E=me(v.check,v.findingId),L=m.get(E)??[];L.push(v),m.set(E,L)}let f=new Map;for(let v of l){let E=me(v.check,v.findingId),L=Yi(m.get(E)??[]),Q=L?.comparisonBaseCommit??L?.commit;if(xt(`candidate ${E} anchor=${String(Q)} current=${String(e.comparisonBaseCommit)}`),!L?.comparisonBaseCommit&&L?.commit&&L.commit===e.commit){n.add(v.check);continue}if(!Q||!e.commit||!e.comparisonBaseCommit){r.add(E);continue}if(Q===e.comparisonBaseCommit){n.add(v.check);continue}let x=f.get(Q)??[];x.push(v),f.set(Q,x)}if(f.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let g=e.runtime.worktreeIsClean?.(e.projectRoot)??Ee(e.projectRoot)?.clean??!1;if(xt(`replay groups=${f.size} clean=${g} callback=${!!e.runtime.replayGate}`),!g||!e.runtime.replayGate){for(let v of f.values())for(let E of v)r.add(me(E.check,E.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let h=[],b=hb(f,e.commit,e.runtime.maxReplayBases),y=new Set(b.map(([v])=>v)),R=0,$=0;for(let[v,E]of f)if(!y.has(v)){R+=1,$+=E.length;for(let L of E)r.add(me(L.check,L.findingId))}R>0&&h.push(`cross-HEAD outcome verification bounded to ${b.length} of ${f.size} historical base(s); retained ${$} finding(s) across ${R} base(s) for later verification`);for(let[v,E]of b){let L;try{let j=[...new Set(E.map(_=>_.check))].filter(_=>Be.includes(_)).sort();L=e.runtime.replayGate(v,j),xt(`replay base=${v} checks=${L.checksRun.join(",")} findings=${L.findings.length} suppressed=${L.suppressed.length}`)}catch(j){for(let _ of E)r.add(me(_.check,_.findingId));h.push(`cross-HEAD outcome verification deferred for ${v.slice(0,12)}: ${j instanceof Error?j.message:String(j)}`);continue}let Q=new Set(L.checksRun),x=Sb(L);for(let j of E){let _=me(j.check,j.findingId);if(!Q.has(j.check)){r.add(_);continue}n.add(j.check);let F=x.find(yt=>yt.key===_);if(F){xt(`replay retained exact ${_}`),t.push(F.observed),F.symbol&&o.set(F.observed.findingId,F.symbol);continue}let H=Yi(m.get(_)??[]),Pe=H?.symbol?x.find(yt=>yt.check===j.check&&yt.symbol===H.symbol):void 0;if(Pe){xt(`replay moved ${_} -> ${Pe.key}`),t.push(Pe.observed),Pe.symbol&&o.set(Pe.observed.findingId,Pe.symbol);continue}i.set(_,v),xt(`replay verified ${_} against ${v}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...h.length>0?{warning:h.join("; ")}:{}}}var gb=1;function hb(e,t,n){let r=[...e.entries()].sort(([c],[l])=>c.localeCompare(l));if(r.length<=1)return r;let i=n===void 0||!Number.isSafeInteger(n)||n<0?gb:n,o=Math.min(r.length,i);if(o===0)return[];if(o>=r.length)return r;let a=lb("sha256").update(t??"unresolved-head").digest().readUInt32BE(0)%r.length;return Array.from({length:o},(c,l)=>r[(a+l)%r.length])}function yb(e,t){let n=_e(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function xt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function bb(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 Sb(e){return[...e.findings.map(t=>({key:me(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:me(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 wt="__diff-gate-run",kt="SCIP_QUERY_DIFF_GATE_REQUEST",kb="SCIP_QUERY_DIFF_GATE_TIMEOUT_MS",Qd="SCIP_QUERY_DIFF_GATE_PROGRESS_PATH",Yd="SCIP_QUERY_DIFF_GATE_PROGRESS_TOKEN",mo=6e4,wb=18e4,$b=6e5,Cb=5e3,Pb=5e3;function Xd(e,t=0){let n=Cb,r=Pb,i=t+e+n+r;return{childTimeoutMs:e,preflightMs:t,processReapGraceMs:n,serializationGraceMs:r,hostTimeoutSeconds:Math.floor(i/1e3)+1}}var uo=class extends Error{constructor(n,r){let i=r.owner,o=r.record?.startedAt;super(`another diff-gate is already running${i?` (PID ${i.pid})`:""}${o?` since ${o}`:""}; wait for that gate to finish instead of starting a duplicate`);this.lockPath=n;this.observation=r;this.name="DiffGateBusyError"}lockPath;observation;code="SCIP_QUERY_DIFF_GATE_BUSY"},po=class extends io{constructor(n,r,i=!0){super("diff-gate",n,i);this.progress=r;let o=r?.activeCheck?` Active detector: ${r.activeCheck} (${r.stage}).`:r?` Active phase: ${r.stage}.`:" No detector progress record was available.",s=r?.lastCompletedCheck?` Last completed detector: ${r.lastCompletedCheck}.`:"";this.message=`diff-gate timed out after ${n}ms.${o}${s}`,this.name="DiffGateDetectorTimeoutError"}progress};function Zd(e,t){let n=ud(e,"diff-gate",t.full,{quiet:!0}),r=Ab(process.env);r.stage("current-gate");let i={base:t.base,minTogether:t.minTogether,maxEchoChecks:t.maxEchoChecks,maxHelpers:t.maxHelpers,includeBaseline:t.includeBaseline,scanLimit:n.scanLimit,semantic:n.semantic,historyMode:t.full?"full":"bounded",skip:t.skip},o=zi(r.observer("current-gate"),()=>Qi(e,i));r.stage("outcome-ledger");let s=Jd(e,o,{replayGate:(a,c)=>{let l=new Set(c);return r.stage("replay-gate",a),zi(r.observer("replay-gate",a),()=>Qi(e,{...i,base:a,includeBaseline:l.has("baseline"),skip:Be.filter(d=>!l.has(d))}))}});return r.stage("complete"),{result:o,outcomes:{observed:s.observed,now:s.now,...s.warning?{warning:s.warning}:{},...t.includeOutcomeLedger?{ledger:s.ledger}:{}},...n.analysisBudget?{analysisBudget:n.analysisBudget}:{}}}function eu(e){if(!e)throw new Error(`${kt} is required for ${wt}.`);let t;try{t=JSON.parse(e)}catch(r){throw new Error(`${kt} is not valid JSON.`,{cause:r})}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${kt} must contain an object.`);let n=t;if(n.base!==void 0&&typeof n.base!="string"||!Ib(n.minTogether)||n.maxEchoChecks!==void 0&&!zd(n.maxEchoChecks)||n.maxHelpers!==void 0&&!zd(n.maxHelpers)||typeof n.includeBaseline!="boolean"||typeof n.includeOutcomeLedger!="boolean"||typeof n.full!="boolean"||!Array.isArray(n.skip)||n.skip.some(r=>!Be.includes(r)))throw new Error(`${kt} contains invalid diff-gate options.`);return{...n.base===void 0?{}:{base:n.base},minTogether:n.minTogether,...n.maxEchoChecks===void 0?{}:{maxEchoChecks:n.maxEchoChecks},...n.maxHelpers===void 0?{}:{maxHelpers:n.maxHelpers},includeBaseline:n.includeBaseline,includeOutcomeLedger:n.includeOutcomeLedger,full:n.full,skip:[...n.skip]}}function Ir(e,t){let n=Kd(t.cacheDir,"runtime","diff-gate.lock");return Tb(n,t.projectRoot,()=>{let r=vb(),i=Kd(t.cacheDir,"runtime",`diff-gate-progress-${r}.json`),o=t.timeoutMs??Eb(e.full,t.env??process.env);try{return tu(i,{schemaVersion:1,token:r,stage:"initializing",updatedAt:new Date().toISOString()}),dd({cliPath:t.cliPath??process.argv[1]??xb(import.meta.url),command:wt,args:["--json"],env:{...t.env??process.env,SCIP_QUERY_PROJECT_ROOT:t.projectRoot,[kt]:JSON.stringify(e),[Qd]:i,[Yd]:r},label:"diff-gate",timeoutMs:o,maxBuffer:50*1024*1024})}catch(s){throw s instanceof io?new po(o,jb(i,r),s.reaped):s}finally{try{Rb(i)}catch(s){s.code}}})}function Tb(e,t,n){let r=Nt(e,{kind:"diff-gate",detail:{projectRoot:t}});if(r.kind==="contended")throw new uo(e,r.observation);try{return n()}finally{r.lock.release()}}function Eb(e,t=process.env){let n=e?wb:mo,r=t[kb];if(!r)return n;let i=Number(r);return!Number.isSafeInteger(i)||i<=0?n:Math.min(i,$b)}function Ib(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function zd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Ab(e){let t=e[Qd],n=e[Yd],r=t&&n?{schemaVersion:1,token:n,stage:"initializing",updatedAt:new Date().toISOString()}:void 0,i=o=>{!t||!r||(r={...r,...o,updatedAt:new Date().toISOString()},tu(t,r))};return{stage:(o,s)=>i({stage:o,activeCheck:void 0,...s?{replayBase:s}:{replayBase:void 0}}),observer:(o,s)=>({onCheckStart:a=>i({stage:o,activeCheck:a,replayBase:s}),onCheckComplete:a=>i({stage:o,activeCheck:void 0,lastCompletedCheck:a,replayBase:s})})}}function tu(e,t){try{or(e,t,{spacing:2,trailingNewline:!0})}catch{}}function jb(e,t){try{let n=JSON.parse(B(e,"diff-gate progress record"));if(!At(n)||n.schemaVersion!==1||n.token!==t||typeof n.stage!="string"||typeof n.updatedAt!="string")return;let r=n.stage;if(!["initializing","current-gate","outcome-ledger","replay-gate","complete"].includes(r))return;let i=n.activeCheck,o=n.lastCompletedCheck;return i!==void 0&&!Be.includes(i)||o!==void 0&&!Be.includes(o)||n.replayBase!==void 0&&typeof n.replayBase!="string"?void 0:{schemaVersion:1,token:t,stage:r,...i===void 0?{}:{activeCheck:i},...o===void 0?{}:{lastCompletedCheck:o},...n.replayBase===void 0?{}:{replayBase:n.replayBase},updatedAt:n.updatedAt}}catch{return}}import{execFileSync as Ao,spawn as zS}from"child_process";import{createHash as jo}from"crypto";import{existsSync as Ct,mkdirSync as QS,realpathSync as Hu,rmSync as YS,writeFileSync as XS}from"fs";import{homedir as ZS}from"os";import{dirname as ep,isAbsolute as ev,join as $n,resolve as tv}from"path";import{execFileSync as vS}from"child_process";import{readdirSync as Ob}from"fs";import{isAbsolute as nu,join as Lb,resolve as Db}from"path";var Ar="@sourcegraph/scip-typescript@0.4.0",ru="scip-python-plus@0.7.5",iu="github.com/sourcegraph/scip-go@v0.2.7",ou="scip-dotnet@0.2.14",Mb="scip_dart@1.6.2",Nb={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",identity:Ar,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Ar]}],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",identity:Ar,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Ar]}],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:Lt.language,indexerBinary:Lt.indexerBinary,checkCommand:`${Lt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Lt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[],installUrl:Lt.installUrl},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",identity:ru,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",ru]}],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",nu(r)?r:Db(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",identity:iu,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",iu]}],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",su(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",identity:ou,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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",su(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",identity:ou,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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",identity:Mb,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],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:({indexerBinary:e})=>nu(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function $t(e){return Nb[e]}function su(e,t){let n;try{n=Ob(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Lb(e,i);return null}import{createRequire as Fb}from"module";var _b=Fb(import.meta.url);function au(e,t=[]){let n=Bb(),r=Ga(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 Bb(){try{return _b.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Vt,spawnSync as qb}from"child_process";import{existsSync as De,mkdtempSync as uu,readdirSync as Vb,rmSync as pu,symlinkSync as Wb,writeFileSync as Hb}from"fs";import{tmpdir as mu}from"os";import{join as ye}from"path";var Gb=3e5,Ub=12,fu=3e4,gu=1024*1024,Jb={readWorkingTreeStatus(e){return Vt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:fu,maxBuffer:gu,killSignal:"SIGKILL"})}};function go(e,t,n={}){let r=rS(e,n.workingTreeRuntime),i=r.state==="known"?r.files:[],o=nS(t,r),s=ho(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:r,dirtyOverlap:o,dirtyWorkingTree:i,batches:[]};let a=Yb(t,s),c=n.timeoutMs??Gb,l=uu(ye(mu(),"scip-cleanup-verify-")),d=[],u=new Map;try{Vt("git",["-C",e,"worktree","add","--detach","--force",l,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),oS(e,l);for(let m of s)u.set(m.label,lu(m,l,c).rawErrors);for(let m of t.batches){yu(l,m);let f=null;for(let g of s){let h=lu(g,l,c),b=Kb(h,u.get(g.label)??[],h.rawErrors);if(b.status==="failed"){let y=b.errors.length>0?b.errors:h.outputTail;f={depth:m.depth,status:"failed",reason:`${g.label}: ${b.reason}`,errors:y.slice(0,Ub)};break}}if(!f)d.push({depth:m.depth,status:"verified"});else{d.push(f);break}}}finally{try{Vt("git",["-C",e,"worktree","remove","--force",l],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{pu(l,{recursive:!0,force:!0})}}return{checkers:s.map(m=>m.label),uncoveredFiles:a,baselineErrors:[...u.values()].reduce((m,f)=>m+f.length,0),workingTree:r,dirtyOverlap:o,dirtyWorkingTree:i,batches:d}}function Kb(e,t,n){let r=zb(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 zb(e,t){let n=Qb(e),r=new Map,i=[];for(let o of t){let s=hu(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Qb(e){let t=new Map;for(let n of e){let r=hu(n);t.set(r,(t.get(r)??0)+1)}return t}function Yb(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 hu(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var cu=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Xb=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function ho(e){let t=[];if(De(ye(e,"tsconfig.json"))){let n=ye(e,"node_modules",".bin","tsc");t.push(De(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:cu,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:cu,strength:"reference-aware"})}if(De(ye(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=>De(ye(e,n)))){let n=Zb();n&&t.push(n)}if(Xb.some(n=>De(ye(e,n)))){let n=eS(e);n&&t.push(n)}for(let n of tS(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:ye(e,n,"..","target")}});return t}function Zb(){return Ke("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"}:Ke("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function eS(e){let t=ye(e,"node_modules",".bin","clj-kondo");return De(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...zn],strength:"reference-aware"}:Ke("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...zn],strength:"reference-aware"}:Ke("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...zn],strength:"reference-aware"}:null}function tS(e){let t=[];if(De(ye(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Vb(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||De(ye(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function nS(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function rS(e,t=Jb){try{return{state:"known",files:t.readWorkingTreeStatus(e).split(`
|
|
8
|
+
`).map(r=>r.slice(3).trim()).filter(r=>r!=="").sort()}}catch(n){return{state:"unavailable",reason:iS(n)}}}function iS(e){let t=e&&typeof e=="object"?e:{};if(t.code==="ETIMEDOUT"||t.killed===!0)return`git status timed out after ${fu}ms`;if(t.code==="ENOBUFS"||typeof t.message=="string"&&/maxBuffer|stdout.*buffer/i.test(t.message))return`git status exceeded its ${gu}-byte output limit`;if(typeof t.signal=="string"&&t.signal!=="")return`git status was terminated by ${t.signal}`;if(typeof t.status=="number")return`git status exited with status ${t.status}`;let n=typeof t.message=="string"?t.message.replaceAll(/\s+/g," ").trim().slice(0,240):String(e).replaceAll(/\s+/g," ").trim().slice(0,240);return n===""?"git status failed for an unknown reason":`git status failed: ${n}`}function oS(e,t){for(let n of["node_modules"]){let r=ye(e,n),i=ye(t,n);if(De(r)&&!De(i))try{Wb(r,i,"junction")}catch{}}}function yu(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=ye(e,r);if(!De(o))continue;let s=G(o,{maxBytes:xe,inputKind:"cleanup verification source file"});Hb(o,sS(s,i,{rust:r.endsWith(".rs")}))}}function yo(e,t={}){let n=e.flatMap(r=>r.entries.map(i=>({batch:r.depth,file:i.file,startLine:i.startLine,endLine:i.endLine,loc:i.loc,symbol:i.shortName})));return{dryRun:t.dryRun===!0,batches:e.length,symbols:n.length,loc:e.reduce((r,i)=>r+i.loc,0),files:[...new Set(n.map(r=>r.file))],filesEmptied:[...new Set(e.flatMap(r=>r.filesEmptied))],targets:n}}function bo(e,t,n={}){let r=yo(t,n);if(!r.dryRun)for(let i of t)yu(e,i);return r}function bu(e,t){let n=uu(ye(mu(),"scip-cleanup-patch-"));try{return Vt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),bo(n,t),Vt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{try{Vt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{pu(n,{recursive:!0,force:!0})}}}function So(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 vo(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.allowUnknownWorkingTree&&e.workingTree.state==="unavailable"&&r.push(`Working-tree inspection is unavailable: ${e.workingTree.reason}.`),!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 sS(e,t,n={}){let r=e.split(`
|
|
9
|
+
`),i=(n.rust===!0?aS(e):ga(e)).split(`
|
|
10
|
+
`),o=new Set;for(let s of t){let a=cS(r,s.start),c=dS(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(`
|
|
11
|
+
`)}function aS(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 cS(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 lS=200;function dS(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>lS)break}return n}function lu(e,t,n){let r=qb(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
|
|
12
|
+
${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:du(i)};let o=uS(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(SS),diagnostics:s,parseBasis:o.parseBasis,outputTail:du(i)}}function uS(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:pS(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:mS(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=fS(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:gS(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:hS(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:yS(t),parseBasis:"clj-kondo-json"}:{diagnostics:bS(t),parseBasis:"heuristic"}}function pS(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 mS(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 fS(e){let t=Su(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 gS(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 hS(e){let t=[];for(let n of e.split(`
|
|
13
|
+
`)){if(!n.trim().startsWith("{"))continue;let r=fo(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(u=>!!u&&typeof u=="object"&&u.is_primary===!0),d=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:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function yS(e){let t=Su(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 bS(e){return e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function SS(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 Su(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return fo(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?fo(t.slice(n)):null}function fo(e){try{return JSON.parse(e)}catch{return null}}function du(e,t=10){return e.split(`
|
|
15
|
+
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var xu={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"]},RS={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"},xS={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 $e(e,t){let n=t.languages??vt(e),r=n.map(a=>{let c=ir($t(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=IS(e,n,t),o=Ro({semantics:i},"typescript"),s=ho(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:OS(e)}}function ut(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=>PS(e,c,{hasIndexedGraph:TS(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.`},...kS(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 kS(e){return wS(e).map(t=>{let n=Ro(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${$S(t)} semantic provider`,status:r,evidence:"semantic",reason:CS(t,n)}})}function wS(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of wu(e))t.add(n.language);return[...t].sort((n,r)=>vu(n)-vu(r))}function vu(e){return e==="typescript"?0:1}function $S(e){return e==="typescript"?"TypeScript":"Rust"}function CS(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 PS(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=ES(t,n.runtimeProbe),a=AS(e,t),c=jS(e,t),l=c.length===0?"unavailable":c.every(d=>d.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(d=>d.label).join(", "):`No detected checker covers ${xu[t].join(", ")} files.`}}}function TS(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function ES(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)??Ru(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=ku(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)??Ru(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 Ru(e){let t=RS[e];return t?Yn(t):ku(e)==="regex-only"?"regex":"unavailable"}function ku(e){let t=xS[e],n=t?va(t):null;return n?.imports??n?.exports??n?.reExports??null}function IS(e,t,n){let r=[];if(t.includes("typescript")&&r.push({language:"typescript",...au(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let i=ja(e);r.push({language:"rust",available:i.available,dependencyAvailable:i.dependencyAvailable,resolvedBinary:i.resolvedBinary,reason:i.available?i.note:i.reason})}return r}function wu(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ro(e,t){return wu(e).find(n=>n.language===t)}function AS(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=Ro(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 jS(e,t){let n=new Set(xu[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function OS(e){try{return vS("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{existsSync as xo}from"fs";import{join as Rn}from"path";var tt="<!-- scip-query:agent-setup:begin -->",Wt="<!-- scip-query:agent-setup:end -->",jr="# scip-query:agent-setup";function Ht(){if(process.stdin.isTTY)return"";try{return pa(0,{maxBytes:Re,inputKind:"agent hook input"})}catch{return""}}function Or(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function xn(e){let t=dr(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(`
|
|
16
|
+
`)}function Tu(e){let t=e.written.length+e.unchanged.length,n=e.skipped.length;return{verdict:n===0?"ready":t===0?"blocked":"partial",ready:t,skipped:n}}function Lr(e,t={}){let n={written:[],unchanged:[],skipped:[]};return LS(e,n),t.gitHook&&MS(e,n),n}function Eu(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Cu(e,"AGENTS.md",t,n),Cu(e,"CLAUDE.md",t,n),NS(e,t,n),n}function LS(e,t){let n=[tt,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Use native search and file reads for literal text and source. Use scip-query when a claim depends on compiler-resolved identity, references, callers, dependencies, consumers, public surface, transitive impact, architecture, historical co-change, or a scip detector/gate.","- 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.","- Before the first SCIP graph claim in a work session, run `scip-query status --capabilities` once. Reuse that fresh generation until source changes. After edits, let an active watcher finish its refresh; if it is busy or a refresh request is pending, wait and recheck instead of starting a competing reindex. Run `scip-query reindex` only when freshness is stale, missing, or unknown and the watcher is disabled, unavailable, or failed to refresh.","- For a non-trivial change: establish the current entry-to-effect flow, the affected consumers, and the reuse options before editing (`scip-plan` skill, anchored by `scip-query plan-context <target>`).","- Before claiming a complete relationship set, inspect the command coverage. If it is bounded or unknown, use `--full`, a narrower scope, or follow pagination emitted by the command before making the claim.","- After the change, run the postchecks matching what you actually edited \u2014 the table is in the `scip-verify` skill \u2014 then `scip-query diff-gate`. Fix findings or state why each is accepted.","- Prefer ordinary human output for agent reading: it preserves hierarchy, whitespace, and source line numbers without the JSON transport envelope. Use `--json` only for a programmatic consumer; add `--result-only` when that consumer needs only the command result. Do not use `--compact` for model-readable evidence.","- Run scip-query commands normally, without choosing `--output-page-size` in advance. If and only if scip-query emits `Continue exactly:`, run each emitted command unchanged until the human footer reports transport completion or a JSON page reports `complete: true`; incomplete output is not evidence. Transport completion means every rendered character was retrieved, not that bounded command coverage became exhaustive. Never pipe scip-query through `head`, `tail`, or line-range `sed`. The emitted transport cursor is separate from a command result cursor such as `refs --cursor`.","- 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.",Wt].join(`
|
|
17
|
+
`);$u(e,"AGENTS.md",n,t);let r=[tt,"@AGENTS.md",Wt].join(`
|
|
18
|
+
`);$u(e,"CLAUDE.md",r,t,i=>i.includes("@AGENTS.md")&&!i.includes(tt))}function $u(e,t,n,r,i){let o=Rn(e,t),s=!1,a=Dr(o,t,r,c=>{if(i?.(c.text))return s=!0,{kind:"unchanged"};let l=DS(c.text,n);return l===c.text?{kind:"unchanged"}:{kind:"write",text:l,...c.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?r.unchanged.push(t):r.written.push(t))}function Cu(e,t,n,r){let i=Rn(e,t);if(n.dryRun){if(!xo(i)){r.unchanged.push(t);return}try{let s=B(i,"agent instruction file");s.includes(tt)?(Pu(s),r.removed.push(t)):r.unchanged.push(t)}catch(s){r.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let o=Dr(i,t,r,s=>{if(!s.revision.exists||!s.text.includes(tt))return{kind:"unchanged"};let a=Pu(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});o&&(o.changed?r.removed.push(t):r.unchanged.push(t))}function DS(e,t){if(Iu(e)==="present"){let r=new RegExp(`${tt}[\\s\\S]*?${Wt}`);return e.replace(r,t)}return e.length>0?`${e.replace(/\n*$/,`
|
|
19
|
+
|
|
20
|
+
`)}${t}
|
|
21
|
+
`:`${t}
|
|
22
|
+
`}function Pu(e){Iu(e);let t=new RegExp(`${tt}[\\s\\S]*?${Wt}`),n=e.replace(t,"").replace(/\n{3,}/g,`
|
|
23
|
+
|
|
24
|
+
`).trim();return n.length===0?"":`${n}
|
|
25
|
+
`}function Iu(e){let t=e.split(tt).length-1,n=e.split(Wt).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(tt)<e.indexOf(Wt))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function Dr(e,t,n,r){try{return Qe(e,r,{maxRetries:0})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function MS(e,t){let n=Rn(e,".git","hooks");if(!xo(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=Rn(n,"pre-commit"),i=["#!/bin/sh",jr,"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(`
|
|
26
|
+
`),o=!1,s=Dr(r,".git/hooks/pre-commit",t,a=>a.revision.exists&&!a.text.includes(jr)?(o=!0,{kind:"unchanged"}):a.text===i?{kind:"unchanged"}:{kind:"write",text:i,mode:493});s&&(o?t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"}):s.changed?t.written.push(".git/hooks/pre-commit"):t.unchanged.push(".git/hooks/pre-commit"))}function NS(e,t,n){let r=Rn(e,".git","hooks","pre-commit");if(t.dryRun){xo(r)?B(r,"pre-commit hook").includes(jr)?n.removed.push(".git/hooks/pre-commit"):n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):n.unchanged.push(".git/hooks/pre-commit");return}let i=!1,o=Dr(r,".git/hooks/pre-commit",n,s=>s.revision.exists?s.text.includes(jr)?{kind:"delete"}:(i=!0,{kind:"unchanged"}):{kind:"unchanged"});o&&(i?n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):o.changed?n.removed.push(".git/hooks/pre-commit"):n.unchanged.push(".git/hooks/pre-commit"))}import{createHash as ju}from"crypto";import{closeSync as FS,fstatSync as Au,mkdirSync as _S,openSync as BS,readSync as qS}from"fs";import{dirname as VS,join as WS,resolve as ko}from"path";var Ou=1,HS=1440*60*1e3,GS=2*1024*1024,Lu=8,Du=16384;function Mu(e,t){return WS(e,"agent-hooks",`session-${Co(t).slice(0,32)}.json`)}function Nu(e,t,n,r=Date.now()){let i=Mu(e,t);try{let o=JSON.parse(B(i,"agent session state"));return!Po(o)||o.sessionIdentity!==Co(t)||o.projectIdentity!==Vu(n)||o.expiresAtMs<=r?void 0:o}catch{return}}function $o(e){let t=e.nowMs??Date.now(),n=Mu(e.cacheDir,e.sessionId);_S(VS(n),{recursive:!0,mode:448});let r=Co(e.sessionId),i=Vu(e.projectRoot),o=Qe(n,a=>{let c=US(a.text,r,i,t),l={schemaVersion:Ou,sessionIdentity:r,projectIdentity:i,updatedAtMs:t,expiresAtMs:t+HS,...e.latestStop??c?.latestStop?{latestStop:e.latestStop??c.latestStop}:{},unfinishedOutput:qu(e.unfinishedOutput??c?.unfinishedOutput??[])};return{kind:"write",text:`${JSON.stringify(l,null,2)}
|
|
27
|
+
`,mode:384}},{maxRetries:3}),s=JSON.parse(o.current.text);if(!Po(s))throw new Error("Agent session state failed validation after publication.");return s}function Fu(e,t,n=Id){let r=new Map,i=/--output-cursor(?:=|\s+)['"]?([A-Za-z0-9_-]{20,4096})/gu;for(let o of e.matchAll(i)){let s=o[1];if(!s)continue;let a=n(s);if(!a||!JS(t,a.cwd)||a.continuationCommand.length>Du)continue;let c={snapshotId:a.snapshotId,pageIndex:a.pageIndex,command:a.command,continuationCommand:a.continuationCommand,remainingCharacters:a.remainingCharacters,totalCharacters:a.totalCharacters,outputHash:a.outputHash,createdAtMs:a.createdAtMs},l=r.get(c.snapshotId);(!l||c.pageIndex>l.pageIndex)&&r.set(c.snapshotId,c)}return qu([...r.values()])}function _u(e,t=GS){if(!Number.isSafeInteger(t)||t<=0)return;let n;try{n=BS(e,"r");let r=Au(n);if(!r.isFile())return;let i=Math.min(r.size,t),o=r.size-i,s=Buffer.allocUnsafe(i),a=0;for(;a<i;){let d=qS(n,s,a,i-a,o+a);if(d===0)break;a+=d}let c=Au(n);if(r.dev!==c.dev||r.ino!==c.ino||r.size!==c.size||a!==i)return;let l=s.toString("utf8");if(o>0){let d=l.indexOf(`
|
|
28
|
+
`);l=d<0?"":l.slice(d+1)}return l}catch{return}finally{n!==void 0&&FS(n)}}function Bu(e){let t=[];if(e.unfinishedOutput.length>0){t.push(`${e.unfinishedOutput.length} unfinished scip-query output snapshot(s) from this session remain. Incomplete pages are not evidence.`);for(let n of e.unfinishedOutput)t.push(`- ${n.command}: ${n.remainingCharacters}/${n.totalCharacters} characters remain. Continue exactly: ${n.continuationCommand}`)}if(e.latestStop){let n=e.latestStop;t.push(`Latest scip-query Stop attempt: ${n.outcome}; ${n.findingCount} finding(s), ${n.automaticSuppressionCount} automatic suppression(s), ${n.policyEscalationCount} policy escalation(s).`),n.observation&&t.push(`Observed state: generation=${n.observation.index?.generationIdentity??"unknown"}, worktree=${n.observation.worktree?.identity??"unknown"} (${n.observation.index?.alignment??"not-certified"}).`),n.warning&&t.push(`Stop evidence warning: ${n.warning}`)}return t.length>0?`Restored scip-query evidence state after compaction:
|
|
29
|
+
${t.join(`
|
|
30
|
+
`)}`:void 0}function US(e,t,n,r){if(e.trim())try{let i=JSON.parse(e);return Po(i)&&i.sessionIdentity===t&&i.projectIdentity===n&&i.expiresAtMs>r?i:void 0}catch{return}}function qu(e){return[...e].filter(Wu).sort((t,n)=>n.createdAtMs-t.createdAtMs||n.pageIndex-t.pageIndex).slice(0,Lu)}function JS(e,t){return ce(ko(e),ko(t))}function Co(e){return ju("sha256").update(e).digest("hex")}function Vu(e){return ju("sha256").update(ko(e)).digest("hex")}function Po(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.schemaVersion===Ou&&wo(t.sessionIdentity)&&wo(t.projectIdentity)&&Number.isSafeInteger(t.updatedAtMs)&&(t.updatedAtMs??-1)>=0&&Number.isSafeInteger(t.expiresAtMs)&&(t.expiresAtMs??-1)>=0&&(t.latestStop===void 0||KS(t.latestStop))&&Array.isArray(t.unfinishedOutput)&&t.unfinishedOutput.length<=Lu&&t.unfinishedOutput.every(Wu)}function KS(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Number.isSafeInteger(t.attemptedAtMs)&&(t.attemptedAtMs??-1)>=0&&(t.outcome==="pass"||t.outcome==="pass-with-suppressions"||t.outcome==="findings"||t.outcome==="unresolved")&&kn(t.findingCount)&&kn(t.automaticSuppressionCount)&&kn(t.policyEscalationCount)&&(t.observation===void 0||lr(t.observation))&&(t.warning===void 0||Mr(t.warning,4096))}function Wu(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Mr(t.snapshotId,64)&&Number.isSafeInteger(t.pageIndex)&&(t.pageIndex??-1)>=1&&Mr(t.command,256)&&Mr(t.continuationCommand,Du)&&kn(t.remainingCharacters)&&kn(t.totalCharacters)&&(t.remainingCharacters??1)>0&&(t.remainingCharacters??0)<=(t.totalCharacters??-1)&&wo(t.outputHash)&&Number.isSafeInteger(t.createdAtMs)&&(t.createdAtMs??-1)>=0}function kn(e){return Number.isSafeInteger(e)&&Number(e)>=0}function Mr(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function wo(e){return typeof e=="string"&&/^[a-f0-9]{64}$/u.test(e)}var tp="SCIP_QUERY_SKIP_HOOK_INSTALL",To="SCIP_QUERY_STOP_HOOK_MODE",nv="scip-query hook-",rv="scip-query diff-gate --hook",Gu="# scip-query:local-hooks:begin",Uu="# scip-query:local-hooks:end",wn=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}],np=5e3,iv=100,ov=1e4,sv=50*1024*1024,rp=Xd(mo,np),Nr=class extends Error{constructor(n,r){super(r);this.state=n;this.name="StopHookEvidenceLeaseError"}state};function ip(e){return e.remove&&e.force?{ok:!1,message:"--remove cannot be combined with --force; force only reinstalls hooks."}:e.dryRun&&!e.remove?{ok:!1,message:"--dry-run requires --remove; installation is already non-destructive to user-owned hooks."}:e.remove?{ok:!0,mode:e.dryRun?"preview-remove":"remove"}:{ok:!0,mode:"install"}}function Gt(e,t={}){let n=op(),r=t.env??process.env;if(dv(r))return n.skipped.push({target:"project agent hooks",reason:`${tp}=1`}),n;if(t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),cv(e,n,t.dryRun),t.remove)return Ku(e,wn[0],n,{dryRun:t.dryRun}),Ku(e,wn[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n;let i=t.commandPrefix??bv(e);return Ju(e,wn[0],n,{provider:"codex",commandPrefix:i,force:t.force}),Ju(e,wn[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&av({homeDir:t.homeDir,result:n}),n}function av(e={}){let t=e.result??op(),n=e.homeDir??ZS();return Eo({configPath:$n(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Eo({configPath:$n(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function op(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function Ju(e,t,n,r){if(Oo(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=$n(e,t.relativePath);uv({provider:r.provider,rootDir:ep(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function Ku(e,t,n,r){if(Oo(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}pv({configPath:$n(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function cv(e,t,n=!1){let r=lv(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=wn.filter(a=>!Oo(e,a.relativePath));if(i.length===0)return;let o=[Gu,...i.map(a=>`/${a.relativePath}`),Uu].join(`
|
|
31
|
+
`),s=new RegExp(`${Je(Gu)}[\\s\\S]*?${Je(Uu)}\\n?`,"g");if(!n)try{Qe(r,a=>{let c=a.text.replace(s,"").replace(/\n*$/,""),l=`${c}${c?`
|
|
32
|
+
|
|
33
|
+
`:""}${o}
|
|
34
|
+
`;return l===a.text?{kind:"unchanged"}:{kind:"write",text:l,...a.revision.exists?{}:{mode:420}}})}catch(a){t.warnings.push(a instanceof Error?a.message:String(a));return}t.gitExcluded.push(...i.map(a=>a.label))}function lv(e){try{let t=Ao("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).trim();return t?ev(t)?t:tv(e,t):null}catch{return null}}function Oo(e,t){try{return Ao("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),!0}catch{return!1}}function dv(e=process.env){let t=e[tp];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function zu(e=process.env){let t=e[To]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function uv(e){if(!e.createRoot&&!Ct(e.rootDir))return;let t=!1,n=sp(e.configPath,e.label,e.result,r=>{if(r.scipQueryHooks==="declined"&&!e.force)return t=!0,{kind:"unchanged"};let i=gv(r,e.provider,e.commandPrefix);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:{kind:"write",text:ap(i)}});if(n){if(t){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}if(!n.changed){e.result.unchanged.push(e.label);return}e.result[n.previous.revision.exists?"updated":"installed"].push(e.label)}}function Eo(e){if(!Ct(e.configPath)&&!e.writeDeclinedTombstone)return;let t=r=>{let i=mv(r,e.writeDeclinedTombstone);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:Object.keys(i).length===0?{kind:"delete"}:{kind:"write",text:ap(i)}};if(e.dryRun){let r=cp(e.configPath,e.label,e.result);if(!r)return;t(r).kind!=="unchanged"&&e.result.removed.push(e.label);return}sp(e.configPath,e.label,e.result,t)?.changed&&e.result.removed.push(e.label)}function pv(e){let t=e.result.removed.length;Eo(e),e.writeDeclinedTombstone&&e.result.removed.length===t&&cp(e.configPath,e.label,e.result)?.scipQueryHooks==="declined"&&e.result.removed.push(`${e.label} (declined)`)}function mv(e,t=!1){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},r={...n};for(let o of["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]){if(!Array.isArray(n[o]))continue;let s=n[o],a=lp(s);a.length>0?r[o]=a:delete r[o]}let i={...e};return Object.keys(r).length>0?i.hooks=r:delete i.hooks,t&&(i.scipQueryHooks="declined"),i}function sp(e,t,n,r){try{return Qe(e,i=>{let o=fv(i);return r(o,i)})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function fv(e){if(!e.revision.exists)return{};try{let t=JSON.parse(e.text);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("top-level value is not an object");return t}catch(t){throw new Error(`Cannot update ${e.path}: the latest hook config is invalid JSON (${t instanceof Error?t.message:String(t)}).`,{cause:t})}}function ap(e){return`${JSON.stringify(e,null,2)}
|
|
35
|
+
`}function cp(e,t,n){if(!Ct(e))return{};try{let r=JSON.parse(B(e,"agent hook settings"));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 gv(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;let o=t==="claude"?["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]:["SessionStart","UserPromptSubmit","Stop"];for(let s of o){let a=Array.isArray(r[s])?r[s]:[];i.hooks[s]=[...lp(a),yv(t,s,n)]}return i}function lp(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!hv(n)):[]})).filter(t=>t.hooks.length>0)}function hv(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(nv)||t===rv||/(?:^|\s)hook-(?:context|pretool|stop)$/.test(t))}function yv(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"}]}:t==="PostCompact"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:10,statusMessage:"Resetting scip-query context reminder"}]}:t==="PreToolUse"?{matcher:"Bash|Grep|Glob",hooks:[{type:"command",command:`${n} hook-pretool`,timeout:10,statusMessage:"Checking scip-query evidence integrity"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:rp.hostTimeoutSeconds,statusMessage:"Running scip-query diff gate"}]}}function bv(e){let t=Hu(e),n=[nr("scip-query"),process.argv[1]].filter(r=>!!r);for(let r of n){if(!Ct(r))continue;let i=Hu(r);if(ce(t,i))continue;let o=tr(i,[]);return[o.binary,...o.args].map(Sv).join(" ")}throw new Error("Cannot install persistent hooks without a scip-query CLI identity outside the target checkout. Install scip-query globally and rerun setup-hooks.")}function Sv(e){return process.platform==="win32"?`"${e.replaceAll("%","%%").replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}async function dp(){let e=await Lv(Ht());e&&yr(JSON.stringify(e))}function up(){let e=Fr(Ht()),t=_r(e);if(!t||!Ct(t.paths.dbPath))return;let n=pp(t.paths.cacheDir,e),r=vv(e,n?Ct(n):!0);if(r.kind==="allow")return;r.kind==="reconsider"&&n&&(QS(ep(n),{recursive:!0}),XS(n,`shown
|
|
36
|
+
`));let i={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:r.reason}};yr(JSON.stringify(i))}function vv(e,t){let n=typeof e.tool_name=="string"?e.tool_name:"",r=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:{},i=n==="Bash"&&typeof r.command=="string"?r.command:"";return i&&Rv(i)?{kind:"deny",reason:"Do not pipe scip-query output through head, tail, or a line-range sed selector: that discards evidence without a resumable position. Re-run the exact emitted paging command and follow each --output-cursor continuation until complete; command-level coverage such as refs --cursor remains a separate step."}:!(n==="Grep"||n==="Glob"||n==="Bash"&&/(?:^|[;&|]\s*)(?:rg|grep)(?:\s|$)/.test(i))||t?{kind:"allow"}:{kind:"reconsider",reason:"Pause once before native search in this indexed repository. If you need compiler-resolved identity or a complete set of definitions, references, callers, consumers, dependencies, or affected units, use scip-query. If you only need literal text, filenames, or local source, retry the same search unchanged; it will be allowed for the rest of this context window."}}function Rv(e){return xv(e)?/\|\s*(?:head|tail)(?:\s|$)/.test(e)||/\|\s*sed\s+(?:-[A-Za-z]+\s+)*(?:['"])?\d+\s*,\s*\d+\s*p/.test(e):!1}function xv(e){let t=String.raw`(?:^|[;&(]\s*|\|\|?\s*|&&\s*|\s)`,n=String.raw`(?:\S*[\\/])?scip-query(?:\.(?:cmd|exe))?`,r=new RegExp(`${t}${n}\\s+[A-Za-z][A-Za-z0-9-]*(?:\\s|$)`,"u"),i=new RegExp(`${t}(?:(?:npx|bunx|yarn(?:\\s+dlx)?)\\s+|pnpm\\s+(?:exec|dlx)\\s+|npm\\s+exec(?:\\s+--)?\\s+)${n}\\s+[A-Za-z][A-Za-z0-9-]*(?:\\s|$)`,"u"),o=String.raw`(?:"[^"]*(?:dist[\\/]cli\.js|src[\\/]runtime[\\/]cli\.ts)"|'[^']*(?:dist[\\/]cli\.js|src[\\/]runtime[\\/]cli\.ts)'|\S*(?:dist[\\/]cli\.js|src[\\/]runtime[\\/]cli\.ts))`,s=new RegExp(`${t}(?:\\S*[\\\\/])?(?:node|bun)(?:\\.exe)?\\s+${o}\\s+[A-Za-z][A-Za-z0-9-]*(?:\\s|$)`,"u");return r.test(e)||i.test(e)||s.test(e)}function pp(e,t){let n=typeof t.session_id=="string"?t.session_id:null;if(!n)return null;let r=jo("sha256").update(n).digest("hex").slice(0,24);return $n(e,"agent-hooks",`native-search-${r}`)}function kv(e,t){let n=pp(e.paths.cacheDir,t);n&&YS(n,{force:!0})}async function mp(){let e=Ht(),t=Fr(e),n=_r(t),r;try{r=await wv(e)}catch(o){let s=o instanceof Error?o.message:String(o);Yu(n,t,{attemptedAtMs:Date.now(),outcome:"unresolved",findingCount:0,automaticSuppressionCount:0,policyEscalationCount:0,warning:s}),Qu(Iv(s,zu()));return}let i=r?.result;r&&i&&Yu(n,t,{attemptedAtMs:Date.now(),outcome:i.outcome??(i.findings.length>0?"findings":"pass"),findingCount:i.findings.length,automaticSuppressionCount:i.suppressionSummary?.automaticSuppressionCount??i.suppressed.length,policyEscalationCount:i.suppressionSummary?.policyEscalationCount??0,observation:Hd({projectRoot:n?.projectRoot??process.cwd(),generationIdentity:r.evidenceLease.generationIdentity,generationSource:r.evidenceLease.generationSource,worktreeIdentity:r.evidenceLease.worktreeIdentity,observedAt:r.evidenceLease.observedAt}),...r.outcomes.warning?{warning:r.outcomes.warning}:{}}),!(!i||i.findings.length===0&&i.suppressed.length===0&&!Lo(i)&&!r?.outcomes.warning&&!hp(i))&&Qu(Av(i,zu(),r))}function Qu(e){yr(JSON.stringify(e))}async function wv(e){if(Or(e))return;let t=Fr(e),n=_r(t);if(!n)return;let r=await $v(n),i=Ir({minTogether:6,includeBaseline:!1,includeOutcomeLedger:!0,full:!1,skip:[]},{projectRoot:n.projectRoot,cacheDir:n.paths.cacheDir,timeoutMs:rp.childTimeoutMs});return Cv(n,r),{...i,evidenceLease:r}}function Yu(e,t,n){let r=typeof t.session_id=="string"?t.session_id:void 0;if(!(!e||!r))try{$o({cacheDir:e.paths.cacheDir,sessionId:r,projectRoot:e.projectRoot,latestStop:n})}catch{}}var fp={refresh(e){return yp(e,"Stop")},observe:Pv,now:Date.now,wait(e){return new Promise(t=>setTimeout(t,e))}};async function $v(e,t=fp,n={}){let r=t.observe(e),i=Io(r);if(i)return i;let o;if(Ie(e.config).autoRefresh!==!1){o=await t.refresh(e);let s=n.waitMs??np,a=n.pollMs??iv,c=t.now()+s;for(;t.now()<c;){await t.wait(Math.min(a,Math.max(1,c-t.now()))),r=t.observe(e);let l=Io(r);if(l)return l}}throw gp(r,o)}function Cv(e,t,n=fp){let r=n.observe(e),i=Io(r);if(!i)throw gp(r);if(i.generationIdentity!==t.generationIdentity||i.worktreeIdentity!==t.worktreeIdentity)throw new Nr("changed-during-run","The scip-query index generation or Git worktree changed while diff-gate was running. The result was discarded; wait for the watcher to become idle and retry Stop.")}function Io(e){if(!(e.freshness.state!=="fresh"||!e.generationIdentity||!e.worktreeIdentity))return{generationIdentity:e.generationIdentity,generationSource:e.generationSource??"legacy",worktreeIdentity:e.worktreeIdentity,observedAt:e.freshness.checkedAt}}function gp(e,t){let n=e.freshness.state==="fresh"&&(!e.generationIdentity||!e.worktreeIdentity)?"unverifiable":e.freshness.state,r=n==="unverifiable"?" A stable index-generation and Git-worktree identity could not both be established.":"",i=t?` ${t}`:"";return new Nr(n,`scip-query index evidence is ${n}: ${e.freshness.reason}.${r}${i} Diff-gate was not allowed to report a clean Stop result.`)}function Pv(e){let t=Ae(e.projectRoot,e.config,e.paths);return{freshness:t,...Tv(e,t),worktreeIdentity:Ev(e.projectRoot)}}function Tv(e,t){let n=Ye(e.paths.dbPath,e.paths.metaPath);if(n.state==="current"||n.state==="drifted")return{generationIdentity:n.generation.currentGeneration,generationSource:"immutable"};if(!Ct(e.paths.metaPath))return{};try{return{generationIdentity:jo("sha256").update(B(e.paths.metaPath,"reindex metadata")).digest("hex"),generationSource:"legacy"}}catch{return t.updatedAt?{generationIdentity:t.updatedAt,generationSource:"legacy"}:{}}}function Ev(e){try{let t=Ao("git",["-C",e,"diff","--no-ext-diff","--binary","HEAD","--"],{encoding:"utf8",timeout:ov,maxBuffer:sv});return jo("sha256").update(t).digest("hex")}catch{return}}function Iv(e,t="feedback"){let n=`Diff gate could not complete and therefore cannot certify this turn: ${e}`;return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${n}
|
|
37
|
+
|
|
38
|
+
Wait for an existing gate or investigate the timeout before declaring the work complete.`}}:{systemMessage:`${n}
|
|
39
|
+
|
|
40
|
+
Stop-hook warn mode allowed the turn to finish, but the diff was not certified.`}}function Av(e,t="feedback",n){let r=Lo(e),i=e.findings.length>0?xn(e):void 0,o=Ov(e,n),s=[r,...o,i].filter(c=>!!c).join(`
|
|
41
|
+
|
|
42
|
+
`),a=jv(e,o);if(t==="block"&&e.findings.length>0)return{decision:"block",reason:s};if(t==="feedback"){let c=e.findings.length>0?"Fix true findings, or provide policy-admissible counterevidence before finishing.":"Automatic adjudication completed without a human approval prompt; no finding action is required for this Stop.";return{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${a}
|
|
43
|
+
|
|
44
|
+
This is non-error Stop hook feedback. ${c}`}}}return{systemMessage:`${a}
|
|
45
|
+
|
|
46
|
+
Stop hook allowed this turn to finish. Review these findings when relevant. Set ${To}=feedback to ask the agent to continue without a hook error, or ${To}=block to enforce the gate.`}}function jv(e,t){let n=e.findings.length>0?xn(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:"):void 0,r=(e.suppressionSummary?.automaticSuppressionCount??e.suppressed.length)>0?`Diff gate outcome: pass-with-suppressions. ${e.suppressionSummary?.automaticSuppressionCount??e.suppressed.length} exact finding(s) passed automated adjudication; ${e.suppressionSummary?.policyEscalationCount??0} policy escalation(s) remain.`:void 0;return[Lo(e),...t,n,r].filter(i=>!!i).join(`
|
|
47
|
+
|
|
48
|
+
`)}function Ov(e,t){let n=[];if(t?.outcomes.ledger){let o=ur(t.outcomes.ledger,t.outcomes.observed,t.outcomes.now);o&&n.push(o)}t?.outcomes.warning&&n.push(`Outcome history warning: ${t.outcomes.warning}`);let r=hp(e);r&&n.push(r);let i=vr(t?.analysisBudget);return i&&n.push(i),n}function hp(e){let t=(e.evidenceTiers??[]).filter(i=>i.state==="failed");if(e.skipped.length===0&&t.length===0)return;let n=e.skipped.length>0?`${e.skipped.length} skipped check(s): ${e.skipped.map(({check:i})=>i).join(", ")}`:void 0,r=t.length>0?`${t.length} failed evidence tier(s): ${t.map(({tier:i})=>i).join(", ")}`:void 0;return`Evidence coverage is incomplete \u2014 ${[n,r].filter(Boolean).join("; ")}.`}function Lo(e){return e.recordCompatibility?ct("Committed suppression",e.recordCompatibility.suppressions):void 0}async function Lv(e){let t=Fr(e),n=Vv(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit"&&n!=="PostCompact")return;let r=_r(t);if(!r)return;if((n==="SessionStart"||n==="PostCompact")&&kv(r,t),n==="PostCompact"){let a=Dv(r,t);return a?{hookSpecificOutput:{hookEventName:n,additionalContext:a}}:void 0}let i=await yp(r,n),o=n==="SessionStart"?Fv(r.projectRoot,r.config,r.paths):_v(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
|
|
49
|
+
`);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}function Dv(e,t){let n=typeof t.session_id=="string"?t.session_id:void 0;if(!n)return;let r=typeof t.transcript_path=="string"?t.transcript_path:void 0,i=r?_u(r):void 0,o=i===void 0?Nu(e.paths.cacheDir,n,e.projectRoot):$o({cacheDir:e.paths.cacheDir,sessionId:n,projectRoot:e.projectRoot,unfinishedOutput:Fu(i,e.projectRoot)});return o?Bu(o):void 0}var Mv={prepare:ad,ensureService:Cd,freshness:Ae,requestRefresh:Td,startOneShot(e){zS("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function yp(e,t,n=Mv){let r=Ie(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:be,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}).`:(Nv(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 Nv(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(ar(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Fv(e,t,n){let r=Ae(e,t,n),i=$e(e,t),s=ut(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.","Before a non-trivial edit, establish the current entry-to-effect flow, affected consumers, and reuse options with scip-plan; then verify the finished diff with scip-verify."].filter(c=>c!==void 0).join(`
|
|
50
|
+
`)}function _v(e,t={},n=process.env){if(qv(t,n)==="off")return"";let r=Bv(e);return r?`scip-query routing reminder:
|
|
51
|
+
${r.message}`:""}var Xu=[{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-diagnose"],keywords:["debug","bug","regression","failing","fails","error","wrong","broken","doesn't work","not working","crash"],message:"Debug, root-cause, or issue-triage request: use scip-diagnose."},{id:"review",skillNames:["scip-audit","scip-plan","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-audit for current structure, scip-plan for prospective API impact, or scip-verify for a finished change."},{id:"implementation",skillNames:["scip-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Before editing: use scip-plan and `scip-query plan-context <target>` to establish the current flow, affected consumers, and reuse options. After editing: use 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-explore"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-explore and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-audit","scip-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-audit before editing; use scip-improve when the user wants confirmed issues fixed autonomously."}];function Bv(e){let t=Xu.find(i=>i.skillNames.some(o=>Zu(e,o)));if(t)return t;let n=0,r=[];for(let i of Xu){let o=i.keywords.filter(s=>Zu(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function qv(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function Zu(e,t){let n=t.trim().split(/\s+/).map(r=>Je(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function Fr(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Vv(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function _r(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=_a(t);if(n)try{let r=ke(n),i=ze(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}import{existsSync as qr,mkdirSync as zv,symlinkSync as Qv,readlinkSync as No,unlinkSync as Fo,readdirSync as wp}from"fs";import{join as We,dirname as En,resolve as pt,relative as Yv,isAbsolute as Xv}from"path";import{homedir as Vr,platform as Zv}from"os";import{fileURLToPath as $p}from"url";import{execFileSync as bp}from"child_process";import{createRequire as Wv}from"module";import{existsSync as Hv}from"fs";import{platform as Cn,arch as Sp}from"os";var Pn="v0.8.1",Do="https://github.com/sourcegraph/scip",Br=`github.com/sourcegraph/scip/cmd/scip@${Pn}`,vp=Wv(import.meta.url),Rp="SCIP_QUERY_SCIP_BIN";function Gv(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[Rp];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 Uv(e){for(let t of e==="arm64"?["arm64","x64"]:[e])try{return vp.resolve(`scip-query-scip-windows/scip-win32-${t}.exe`)}catch{}return null}function Ut(e=process.env){let t=Gv({platform:Cn(),arch:Sp(),env:e,isOnPath:Ot,fileExists:Hv,resolveSidecar:Uv});return t?.source==="path"?nr("scip")??t.path:t?.path??null}function Tn(){return Ut()!==null}function xp(){let e=Ut();if(!e)return null;try{return bp(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}function Jv(){let e=Cn(),t=Sp(),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:`${Do}/releases/download/${Pn}/${o}`,filename:o}}function Mo(){let e=Jv();if(console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Cn()==="darwin"||Cn()==="linux")console.log("Install the reviewed version with Go:"),console.log(` go install ${Br}
|
|
52
|
+
`),console.log("Or download that exact release manually:");else if(Cn()==="win32"){let t=Kv();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 ${t}`),console.log(`Or set ${Rp} to a local scip.exe path.
|
|
53
|
+
`),console.log("Upstream release page:")}else console.log("Download from:");console.log(e?` ${e.url}
|
|
54
|
+
`:` ${Do}/releases/tag/${Pn}
|
|
55
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Kv(){let t=vp("../../package.json").optionalDependencies?.["scip-query-scip-windows"];if(!t||!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(t))throw new Error("scip-query package metadata does not declare an exact Windows sidecar version.");return`scip-query-scip-windows@${t}`}function kp(e){if(Ot("go")){e(`Installing immutable ${Br} via go install into the Go bin directory (GOBIN or GOPATH/bin); expected executable: scip.`);try{if(bp("go",["install",Br],{stdio:"inherit",timeout:3e5,env:process.env}),Ot("scip")){let t=Ut(),n=xp();if(t&&n&&n.includes(Pn))return e(`Successfully installed ${Br}; resolved executable: ${t}; reported version: ${n}.`),!0;e(`go install completed, but the resolved scip executable did not report ${Pn} (executable: ${t??"unresolved"}; version: ${n??"unavailable"}).`)}}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: ${Do}/releases`),!1}var eR=Zv()==="win32",Wr=["_shared","scip-query","scip-setup","scip-explore","scip-plan","scip-diagnose","scip-audit","scip-improve","scip-verify"];function Hr(e={}){let t=e.quiet?()=>{}:console.log,n=$p(import.meta.url),r=pt(En(n),"..","skills"),i=[We(Vr(),".claude","skills"),We(Vr(),".codex","skills"),We(Vr(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=En(s);if(!qr(a))continue;zv(s,{recursive:!0});let c=Tp(s);tR(s,r,c,o,t);for(let l of Wr){let d=We(r,l),u=We(s,l);if(!qr(d)){o.skipped.push(`${c}/${l}`);continue}if(qr(u)){try{let m=No(u);if(pt(m)===pt(d)){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}Fo(u)}Qv(d,u,eR?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function tR(e,t,n,r,i){let o=new Set(Wr);for(let s of wp(e)){if(o.has(s))continue;let a=We(e,s),c;try{c=pt(En(a),No(a))}catch{continue}Pp(c,t)&&(Fo(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Cp(e={}){let t=$p(import.meta.url),n=pt(En(t),"..","skills"),r=e.homeDir??Vr(),i=[We(r,".claude","skills"),We(r,".codex","skills"),We(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!qr(s))continue;let a=Tp(s);for(let c of wp(s)){let l=We(s,c),d;try{let u=No(l);d=pt(En(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!Pp(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{Fo(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function Pp(e,t){let n=Yv(pt(t),pt(e));return n===""||!n.startsWith("..")&&!Xv(n)}function Tp(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as yg}from"child_process";import{performance as gt}from"perf_hooks";import{chmodSync as fP,existsSync as se,mkdirSync as gP,realpathSync as hP,renameSync as Os,rmSync as As,unlinkSync as Ls,writeFileSync as yP}from"fs";import{dirname as bi,extname as bP,join as Tt,resolve as SP}from"path";import{execFileSync as _w}from"child_process";import{createHash as Bw}from"crypto";import{copyFileSync as ai,existsSync as Me,mkdirSync as oi,mkdtempSync as qw,readdirSync as lf,renameSync as df,rmSync as zt,statSync as Vw}from"fs";import{basename as ii,dirname as V,extname as Ww,join as oe,resolve as ef}from"path";import{platform as Hw}from"os";import nR from"better-sqlite3";import{execFileSync as rR}from"child_process";import{existsSync as iR,readdirSync as oR}from"fs";import{extname as Gr,join as sR}from"path";function Pt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Ur({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Ur(e){let t=new Set((e.extensions??ba).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!iR(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=mr(e.projectRoot),r=aR(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new nR(e.dbPath);try{let o=lR(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
56
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let f=Ue(e.projectRoot,m,{inputKind:"auxiliary source file"}),g=s.run(dR(m),m,f);u+=Number(g.changes)}return u})(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 aR(e,t){let n=cR(e,t);if(n)return n;let r=[],i=o=>{let s=o?sR(e,o):e,a;try{a=oR(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Sa.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Gr(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function cR(e,t){try{return rR("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
57
|
+
`).filter(r=>r&&t.has(Gr(r).toLowerCase())).sort()}catch{return null}}function lR(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 dR(e){return Gr(e).toLowerCase()===".vue"?"vue":Gr(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as PR}from"crypto";import{existsSync as TR}from"fs";import{dirname as ER,join as Ip}from"path";function _o(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 Jr(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=_o(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"),Ep(r,i,s)):s.size>0?Ep(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:uR(r,t,i),reasons:[]}}function Ep(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function uR(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()}import{appendFileSync as pR,existsSync as mR,mkdirSync as fR,renameSync as gR,rmSync as hR,statSync as yR,truncateSync as bR}from"fs";import{basename as SR,dirname as vR}from"path";var In=".previous",RR=".rotation.lock",xR=2e3,Bo=class extends Error{constructor(n,r){super(`Timed out after ${r}ms waiting for rotating JSONL lock: ${n}`);this.lockPath=n;this.timeoutMs=r;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},qo=class extends Error{constructor(n){super(`Rotating JSONL lock ownership changed before release: ${n}`);this.lockPath=n;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},kR=Object.freeze({monotonicNow:W,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let n=Nt(e,{kind:"rotating-jsonl",detail:{target:SR(t)}});return n.kind==="acquired"?{kind:"acquired",lock:n.lock}:{kind:"contended"}},makeDirectory(e){fR(e,{recursive:!0})},exists:mR,readBytes(e){return an(e,{maxBytes:sn,inputKind:"rotating JSONL segment"})},size(e){return yR(e).size},truncate:bR,remove(e){hR(e,{force:!0})},rename:gR,append:pR});function Kr(e,t,n){let r=n.runtime??kR,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
|
|
58
|
+
`),s=Math.max(1,Math.floor(n.maxSegmentBytes),o.length);return wR(e,n.lockTimeoutMs,r,()=>{r.makeDirectory(vR(e));let a=$R(e,sn,r);n.onPhase?.("tail-repaired");let c=`${e}${n.previousSuffix??In}`,l=!1,d=!1;return r.exists(e)&&r.size(e)+o.length>s&&(r.exists(c)&&(r.remove(c),d=!0),n.onPhase?.("previous-pruned"),r.rename(e,c),l=!0,n.onPhase?.("current-rotated")),r.append(e,o),n.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:s,repairedTailBytes:a,rotated:l,prunedPrevious:d}})}function wR(e,t,n,r){let i=`${e}${RR}`,o=Math.max(0,t??xR),s=n.monotonicNow()+o,a;for(;;){let m=n.tryAcquireLock(i,e);if(m.kind==="acquired"){a=m.lock;break}let f=s-n.monotonicNow();if(f<=0)throw new Bo(i,o);n.wait(Math.min(5,f))}let c=!1,l,d;try{d=r()}catch(m){c=!0,l=m}let u=!1;try{u=a.release()}catch(m){if(!c)throw m}if(c)throw l;if(!u)throw new qo(i);return d}function $R(e,t,n){if(!n.exists(e))return 0;let r=CR(e,t,n);if(r.length===0||r[r.length-1]===10)return 0;let i=r.lastIndexOf(10),o=i<0?0:i+1;return n.truncate(e,o),r.length-o}function CR(e,t,n){let r=n.size(e);if(r>t)throw new Bi("rotating JSONL segment",e,"too-large",r,t);let i=n.readBytes(e),o=n.size(e);if(o!==r||i.byteLength!==r)throw new Bi("rotating JSONL segment",e,"changed-during-read",o,t);return i}var IR="<global-symbols>";function AR(e){let t=[];for(let n of e.all(`
|
|
59
|
+
SELECT relative_path, language, position_encoding, text
|
|
60
|
+
FROM documents
|
|
61
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
62
|
+
SELECT d.relative_path,
|
|
63
|
+
c.chunk_index,
|
|
64
|
+
c.start_line,
|
|
65
|
+
c.end_line,
|
|
66
|
+
hex(c.occurrences) AS occurrences_hex
|
|
67
|
+
FROM chunks c
|
|
68
|
+
JOIN documents d ON d.id = c.document_id
|
|
69
|
+
`))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(`
|
|
70
|
+
SELECT d.relative_path,
|
|
71
|
+
r.start_line,
|
|
72
|
+
r.start_char,
|
|
73
|
+
r.end_line,
|
|
74
|
+
r.end_char,
|
|
75
|
+
g.symbol,
|
|
76
|
+
g.display_name,
|
|
77
|
+
g.kind,
|
|
78
|
+
g.documentation,
|
|
79
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
80
|
+
g.enclosing_symbol,
|
|
81
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
82
|
+
FROM defn_enclosing_ranges r
|
|
83
|
+
JOIN documents d ON d.id = r.document_id
|
|
84
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
85
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:Vo(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
86
|
+
SELECT d.relative_path,
|
|
87
|
+
c.chunk_index,
|
|
88
|
+
m.role,
|
|
89
|
+
g.symbol,
|
|
90
|
+
g.display_name,
|
|
91
|
+
g.kind,
|
|
92
|
+
g.documentation,
|
|
93
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
94
|
+
g.enclosing_symbol,
|
|
95
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
96
|
+
FROM mentions m
|
|
97
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
98
|
+
JOIN documents d ON d.id = c.document_id
|
|
99
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
100
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:Vo(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
101
|
+
SELECT g.symbol,
|
|
102
|
+
g.display_name,
|
|
103
|
+
g.kind,
|
|
104
|
+
g.documentation,
|
|
105
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
106
|
+
g.enclosing_symbol,
|
|
107
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
108
|
+
FROM global_symbols g
|
|
109
|
+
WHERE NOT EXISTS (
|
|
110
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
111
|
+
) AND NOT EXISTS (
|
|
112
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
113
|
+
)
|
|
114
|
+
`))t.push({relativePath:IR,kind:"global-symbol",values:Vo(n)});return jR(t)}function jR(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=PR("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
|
|
115
|
+
`);n.set(r,o.digest("hex"))}return n}function OR(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 Wo(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 Ho(e,t=FR){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),s=(l,d)=>{let u=r();return _p(e.refreshResult,l,n?u:i(),Math.max(0,u-o),d)};if(!t.databaseExists(e.previousDbPath))return s("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return s("candidate-index-unavailable");let a=null,c=null;try{a=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let l=[...new Set([...t.indexedPaths(a),...t.indexedPaths(c)])].sort(),d=Jn(e.previousSnapshot,e.currentSnapshot),u=new Set(l),m=d.changes.length>0&&!_o(d).fullProject&&d.changes.every(b=>u.has(b.path)),f=Jr(d,m?t.dependencyGraph(a):new Map,l),g=OR(t.factDigests(a),t.factDigests(c)),h=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?h:i()).toISOString(),durationMs:Math.max(0,h-o),manifest:d,plan:f,comparison:g,evaluation:Wo(f,g,l.length)}}catch(l){return s("oracle-error",l instanceof Error?l.message:String(l))}finally{Ap(a),Ap(c)}}function Lp(e,t,n,r=Date.now()){return _p(e,t,r,0,n)}function Dp(e){let t=ER(e);return{latestPath:Ip(t,"affected-shadow-latest.json"),historyPath:Ip(t,"affected-shadow.jsonl")}}function Mp(e,t=n=>da(n,"affected-shadow source file")){let n=Dp(e),r;try{r=JSON.parse(t(n.latestPath))}catch(y){let R=WR(y),$=R?"telemetry-missing":VR(y);return mt(n,$,R?void 0:y instanceof Error?y.message:String(y))}if(J(r)&&typeof r.version=="number"&&r.version!==1)return mt(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!BR(r))return mt(n,"telemetry-malformed");if(r.status==="unavailable")return qR(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:mt(n,"telemetry-malformed");if(r.status!=="evaluated")return mt(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!J(r.manifest)||!J(i)||!J(o)||!J(s))return mt(n,"telemetry-malformed");let a=i.mode,c=Z(i.affectedFiles),l=Z(i.reasons),d=Z(o.changedFiles),u=Z(s.predictedFiles),m=Z(s.actualFiles),f=Z(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||f===null||typeof s.passed!="boolean"||!jp(g)||!jp(h))return mt(n,"telemetry-malformed");let b=m.length===0?1:(m.length-f.length)/m.length;return!Op(c,u)||!Op(d,m)||s.passed!==(f.length===0)||Math.abs(g-b)>Number.EPSILON||f.some(y=>!m.includes(y)||u.includes(y))?mt(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:f,fallbackReasons:l}}function Np(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 Fp(e,t,n=_R){let r=Dp(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var LR=8*1024*1024,DR=In;function MR(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function NR(e,t,n=LR){Kr(e,MR(t),{maxSegmentBytes:n,previousSuffix:DR})}function Vo(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 FR={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:W,databaseExists:e=>TR(e),openDatabase:(e,t,n)=>new St({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Kn(e),dependencyGraph:e=>Xn(e),factDigests:e=>AR(e)},_R={appendHistory:NR,writeLatest:(e,t)=>or(e,t,{spacing:2,trailingNewline:!0})};function _p(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function Ap(e){try{e?.close()}catch{}}function BR(e){return J(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 qR(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function jp(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Op(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function mt(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function VR(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function WR(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as HR}from"crypto";import{copyFileSync as GR,existsSync as Bp,rmSync as qp}from"fs";import{resolve as UR}from"path";import Hp from"better-sqlite3";var JR={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}]},KR={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_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Gp(e){let t=W(),n=zR(e.affectedFiles);if(QR(e.previousDbPath,e.miniDbPath,e.candidateDbPath),qp(e.candidateDbPath,{force:!0}),!Bp(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Bp(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Vp(e.previousDbPath,"previous SQLite generation",!1),Vp(e.miniDbPath,"incremental SQLite mini database"),GR(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Hp(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Go(r,"main","candidate SQLite generation"),Go(r,"incremental","incremental SQLite mini database"),YR(r,n),XR(r,n.length);let i=Uo(r,"main",!0),o=ft(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ZR(r),ex(r),tx(r),e.onStage?.("after-delete"),nx(r),e.onStage?.("after-symbol-reconciliation"),rx(r),e.onStage?.("after-insert"),ix(r),ox(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Up(r,"main","candidate SQLite generation");let c=[...sx(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:W()-t}}catch(i){try{r?.close()}finally{qp(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function zR(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 QR(e,t,n){let r=[e,t,n].map(i=>UR(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Vp(e,t,n=!0){let r=new Hp(e,{readonly:!0,fileMustExist:!0});try{Go(r,"main",t),n&&Up(r,"main",t)}finally{r.close()}}function Go(e,t,n){for(let[r,i]of Object.entries(JR)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(KR)){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}`)}Wp(e,t,"documents",["relative_path"],n),Wp(e,t,"global_symbols",["symbol"],n)}function Wp(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 Up(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 YR(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 XR(e,t){let n=ft(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=ft(e,`SELECT COUNT(*) AS value
|
|
116
|
+
FROM main.documents d
|
|
117
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
118
|
+
FROM temp.incremental_affected_paths p
|
|
119
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
120
|
+
WHERE d.id IS NULL
|
|
121
|
+
LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
|
|
122
|
+
FROM incremental.documents d
|
|
123
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
124
|
+
WHERE p.relative_path IS NULL
|
|
125
|
+
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 ZR(e){e.exec(`
|
|
126
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
127
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
128
|
+
SELECT g.symbol
|
|
129
|
+
FROM main.defn_enclosing_ranges r
|
|
130
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
131
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
132
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
|
|
133
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
134
|
+
SELECT g.symbol
|
|
135
|
+
FROM main.mentions m
|
|
136
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
137
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
138
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
139
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
140
|
+
WHERE m.role = 1;
|
|
141
|
+
|
|
142
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
143
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
144
|
+
SELECT g.symbol
|
|
145
|
+
FROM incremental.defn_enclosing_ranges r
|
|
146
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
147
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
148
|
+
SELECT g.symbol
|
|
149
|
+
FROM incremental.mentions m
|
|
150
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
151
|
+
WHERE m.role = 1;
|
|
152
|
+
`)}function ex(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
153
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
154
|
+
UNION
|
|
155
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
156
|
+
), unaffected_definitions AS (
|
|
157
|
+
SELECT g.symbol
|
|
158
|
+
FROM main.defn_enclosing_ranges r
|
|
159
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
160
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
161
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
162
|
+
WHERE p.relative_path IS NULL
|
|
163
|
+
UNION
|
|
164
|
+
SELECT g.symbol
|
|
165
|
+
FROM main.mentions m
|
|
166
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
167
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
168
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
169
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
170
|
+
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
171
|
+
)
|
|
172
|
+
SELECT u.symbol
|
|
173
|
+
FROM unaffected_definitions u
|
|
174
|
+
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
175
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function tx(e){e.exec(`
|
|
176
|
+
DELETE FROM main.mentions
|
|
177
|
+
WHERE chunk_id IN (
|
|
178
|
+
SELECT c.id
|
|
179
|
+
FROM main.chunks c
|
|
180
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
181
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
182
|
+
);
|
|
183
|
+
DELETE FROM main.chunks
|
|
184
|
+
WHERE document_id IN (
|
|
185
|
+
SELECT d.id
|
|
186
|
+
FROM main.documents d
|
|
187
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
188
|
+
);
|
|
189
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
190
|
+
WHERE document_id IN (
|
|
191
|
+
SELECT d.id
|
|
192
|
+
FROM main.documents d
|
|
193
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
194
|
+
);
|
|
195
|
+
DELETE FROM main.documents
|
|
196
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
197
|
+
`)}function nx(e){e.exec(`
|
|
198
|
+
UPDATE main.global_symbols
|
|
199
|
+
SET display_name = NULL,
|
|
200
|
+
kind = NULL,
|
|
201
|
+
documentation = NULL,
|
|
202
|
+
signature = NULL,
|
|
203
|
+
enclosing_symbol = NULL,
|
|
204
|
+
relationships = NULL
|
|
205
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
206
|
+
|
|
207
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
208
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
209
|
+
)
|
|
210
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
211
|
+
FROM incremental.global_symbols;
|
|
212
|
+
|
|
213
|
+
UPDATE main.global_symbols
|
|
214
|
+
SET display_name = (
|
|
215
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
216
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
217
|
+
),
|
|
218
|
+
kind = (
|
|
219
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
220
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
221
|
+
),
|
|
222
|
+
documentation = (
|
|
223
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
224
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
225
|
+
),
|
|
226
|
+
signature = (
|
|
227
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
228
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
229
|
+
),
|
|
230
|
+
enclosing_symbol = (
|
|
231
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
232
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
233
|
+
),
|
|
234
|
+
relationships = (
|
|
235
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
236
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
237
|
+
)
|
|
238
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
239
|
+
`)}function rx(e){let t=ft(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=ft(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=ft(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)
|
|
240
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
241
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
242
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
243
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
244
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
245
|
+
FROM incremental.mentions m
|
|
246
|
+
JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
247
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
248
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
249
|
+
)
|
|
250
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
251
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
252
|
+
FROM incremental.defn_enclosing_ranges r
|
|
253
|
+
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
254
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ix(e){e.exec(`
|
|
255
|
+
DELETE FROM main.global_symbols
|
|
256
|
+
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
257
|
+
AND NOT EXISTS (
|
|
258
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
259
|
+
);
|
|
260
|
+
`)}function ox(e,t,n){let r=ft(e,"SELECT COUNT(*) AS value FROM main.documents"),i=ft(e,`SELECT COUNT(*) AS value
|
|
261
|
+
FROM main.documents d
|
|
262
|
+
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 sx(e){let t=Uo(e,"main",!0),n=Uo(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 Uo(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
|
|
263
|
+
FROM ${t}.documents d
|
|
264
|
+
${r}
|
|
265
|
+
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
|
|
266
|
+
FROM ${t}.chunks c
|
|
267
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
268
|
+
${r}
|
|
269
|
+
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,
|
|
270
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
271
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
272
|
+
g.enclosing_symbol,
|
|
273
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
274
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
275
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
276
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
277
|
+
${r}
|
|
278
|
+
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
|
|
279
|
+
FROM ${t}.mentions m
|
|
280
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
281
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
282
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
283
|
+
${r}
|
|
284
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of u){let f=JSON.stringify([d,m]),g=c.get(m.relative_path)??[];g.push(f),c.set(m.relative_path,g)}let l=new Map;for(let[d,u]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=HR("sha256");for(let f of u.sort())m.update(f).update(`
|
|
285
|
+
`);l.set(d,m.digest("hex"))}return l}function ft(e,t){return e.prepare(t).get().value}import ax from"better-sqlite3";var zr="idx_mentions_definitions",cx=["symbol_id","chunk_id"];function Jo(e){let t=new ax(e),n=[],r=[],i=[];try{return t.transaction(()=>{lx(t,n),Qr(t,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Jp(t,"global_symbols").some(a=>a.name!=="idx_global_symbols_symbol"&&a.unique&&a.columns.join("\0")==="symbol")?(t.exec('DROP INDEX "idx_global_symbols_symbol"'),r.push("idx_global_symbols_symbol")):Qr(t,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=Qr(t,"idx_chunks_doc_id"),s=Jp(t,"chunks").some(a=>a.name!=="idx_chunks_doc_id"&&a.columns.length>1&&a.columns[0]==="document_id");o?.join("\0")==="document_id"&&s?(t.exec('DROP INDEX "idx_chunks_doc_id"'),r.push("idx_chunks_doc_id")):o&&i.push("idx_chunks_doc_id"),t.exec("ANALYZE")})(),{added:n,removed:r,retained:i,analyzed:!0}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{t.close()}}function lx(e,t){let n=Kp(e,zr);if(n){let r=n.columns.join("\0")===cx.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${zr} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${zr}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(zr)}function Jp(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:Qr(e,n.name)??[]}))}function Qr(e,t){return Kp(e,t)?.columns??null}function Kp(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(i=>i.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{writeFileSync as dx}from"fs";function Jt(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Qp(e){let t=e.readFingerprint(),n=ux(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return px(e.cachePath,e.readFingerprint(),r),r}function ux(e,t){try{let n=JSON.parse(G(e,{maxBytes:Re,inputKind:"post-index augmentation cache"}));return zp(n.fingerprint)===zp(t)?{result:n.result}:null}catch{return null}}function px(e,t,n){dx(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
286
|
+
`)}function zp(e){return JSON.stringify(e)}import{statSync as mx}from"fs";import{dirname as fx,join as gx}from"path";var Ko="reindex-activity.jsonl",hx=In,yx=1024*1024,qL=1440*60*1e3;function zo(e){return gx(fx(e),Ko)}function bx(e){if(e.reused)return 0;let t=Yp(e.indexPath)+Yp(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function Qo(e,t){let n=t.lastRefresh;return n?Yo(zo(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:bx(t)}):{state:"failed",reason:"reindex result has no refresh metadata"}}function Xp(e,t){return Yo(zo(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function Zp(e,t,n=new Date){return Yo(zo(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function Sx(e,t,n=yx,r){Kr(e,t,{maxSegmentBytes:n,previousSuffix:hx,...r?{runtime:r}:{}})}function Yo(e,t){try{return Sx(e,t),{state:"recorded"}}catch(n){return{state:"failed",reason:n instanceof Error?n.message:String(n)}}}function Yp(e){try{return mx(e).size}catch{return 0}}import{createHash as vx}from"crypto";import{existsSync as Xo,readdirSync as Rx}from"fs";import{dirname as Zo,join as Yr,relative as xx,resolve as es,sep as em}from"path";function tm(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=om(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function nm(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=om(a,e);c&&c!==i&&s.add(c)}}return kx(e,r)}function rm(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 ts(e){if(e===".")return"root";let t=vx("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function im(e,t){let n=es(e),r={};for(let i of t)r[i]=wx(n,i);return r}function om(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 kx(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 wx(e,t){let n=t==="."?e:Yr(e,t),r=$x(n),i=Cx(n),o=i?Px(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 $x(e){let t=Yr(e,"package.json");if(!Xo(t))return{name:void 0,dependencyNames:[],failed:!1};let n=ns(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 Cx(e){let t=Yr(e,"tsconfig.json");if(Xo(t))return t;let n;try{n=Rx(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Yr(e,n[0]):void 0}function Px(e,t){let n=ns(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Tx(n.value,e,t),i=sm(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Tx(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Zo(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=am(a,i,n);c&&o.add(c)}return[...o]}function sm(e,t,n,r){let i=Ex(t);if(i)return{pathsTargets:Ix(i,Zo(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Ax(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=ns(o);return s.ok?sm(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Ex(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 Ix(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=am(o,t,n);s&&r.add(s)}return[...r]}function Ax(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=es(Zo(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(em).includes("node_modules")&&ce(n,i)&&Xo(i))return i}function am(e,t,n){let r=e.replace(/\/?\*+$/,""),i=es(t,r===""?".":r);if(!ce(n,i))return;let s=xx(n,i).split(em).join("/");return s===""?".":s}function jx(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]!==`
|
|
287
|
+
`;)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 ns(e){try{let t=G(e,{maxBytes:Re,inputKind:"TypeScript project manifest"}),n=JSON.parse(jx(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Ox,readdirSync as Lx,statSync as Dx}from"fs";import le from"path";var Mx=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function An(e,t=[]){let n=le.resolve(e),r=t.flatMap(c=>Fx(n,c));if(r.length>0)return cm(n,lm(r));let i=Nx(n),o=lm(i),s=Bx(n,o)?[n,...o]:o,a=s.length>0?s:[n];return cm(n,a)}function cm(e,t){return[...new Set(t.map(n=>Vx(e,n)))].sort((n,r)=>n.localeCompare(r))}function Nx(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Lx(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=le.join(r,o.name);if(o.isDirectory()){!Mx.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&_x(s)&&t.push(le.dirname(s))}}return t}function Fx(e,t){let n=t.trim();if(!n)return[];let r=le.resolve(e,n);if(!ce(e,r))return[];try{let i=Dx(r);if(i.isDirectory())return[r];if(i.isFile()&&dm(le.basename(r)))return[le.dirname(r)]}catch{return[]}return[]}function _x(e){if(!dm(le.basename(e)))return!1;let t=um(e);return t?le.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function dm(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function lm(e){let t=[...new Set(e.map(n=>le.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Wx(n,r)))}function Bx(e,t){if(t.length===0||t.some(r=>le.resolve(r)===e))return!1;let n=le.join(e,"tsconfig.json");return Ox(n)&&qx(n)}function qx(e){let n=um(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!le.extname(r))):!1}function um(e){try{let t=JSON.parse(B(e,"TypeScript project config"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Vx(e,t){let n=le.relative(e,t);return n?n.split(le.sep).join("/"):"."}function Wx(e,t){let n=le.relative(e,t);return!!n&&!n.startsWith("..")&&!le.isAbsolute(n)}import{createHash as ck}from"crypto";import{existsSync as is,statSync as lk,writeFileSync as os}from"fs";import{join as dk}from"path";import{createRequire as Hx}from"module";import{dirname as Gx,isAbsolute as nD,relative as rD,resolve as iD,sep as oD}from"path";var pm=Hx(import.meta.url),Ux=1,mm="0.4.0";function rs(){let e=Jx();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Jx(){try{let e=pm.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(B(e,"scip-typescript package manifest"));if(t.version!==mm)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${mm}`};let n=Gx(e),r=pm.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(B(r,"TypeScript package manifest"));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:Kx(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Kx(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Ux}`}import{createHash as zx}from"crypto";import{dirname as Qx,join as fm}from"path";var Xr=3;var Yx="typescript-index";function gm(e){let t=fm(e,Yx),n=Ma(t);return{...n,requestDir:n.legacyRequestDir}}function hm(e){try{let t=aa(jt(B(fm(Qx(e),"meta.json"),"reindex metadata")));return t?zx("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Xx}from"crypto";import{existsSync as Zx}from"fs";var ek=12e4,tk=5,Zr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=qa(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??sk(),this.runtime=n.runtime??ak,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=ar(this.cacheDir),r=gm(this.cacheDir),i=Ui(n.statePath);if(!ym(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),s=o+this.timeoutMs,a=(this.runtime.monotonicNow??W)()+this.timeoutMs,c=Hi("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),l=Gi(c),d=Na(r,{mailboxVersion:Wi,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:s,protocolVersion:Xr,id:l,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??W)()<=a;){if(Zx(d.responsePath))return nk(G(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),l,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=Ui(n.statePath);if(!ym(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(tk)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function ym(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Xr&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&mn(e.processIdentity,r))}function nk(e,t,n,r,i,o){let s=JSON.parse(e);if(s.protocolVersion!==Xr||s.id!==t||s.operationKey!==n||s.ok===!0&&s.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(s.ok!==!0)throw new Error(typeof s.error=="string"?s.error:"TypeScript index service request failed.");let a=rk(s.response,i),c=[...new Set(o)].sort(),l=a.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(l)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return a}function rk(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(ik)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:ok(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 ik(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 ok(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function sk(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:ek}var ak={now:Date.now,monotonicNow:W,randomId:Xx,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Dt,readProcessIdentity:Mt};function uk(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=Jn(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"||!fn(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Jr(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=pk([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=bm(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=bm(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=vm(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=vm(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Sm(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Sm(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 pk(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 Rm(e){let t=W();try{if(!is(e.previousDbPath)||!is(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=rs();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new St({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=Kn(o,{includeIgnored:!1}).filter(fn).sort(),a=Xn(o)}finally{o.close()}let c=performance.now()-n,l=uk({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?An(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:is(dk(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=hm(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new Zr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),f=performance.now()-n,g=lk(e.previousShardPath).size>=zl;n=performance.now();let h=g?null:an(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_i}),b=g?{completeIndexBytes:null,affectedIndexBytes:Gl(m.fragments)}:Kl({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),y=performance.now()-n;n=performance.now(),g?Ql({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Ul({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Jl({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let R=performance.now()-n;n=performance.now(),b.completeIndexBytes&&os(e.candidateShardPath,b.completeIndexBytes),os(e.candidateAffectedScipPath,b.affectedIndexBytes);let $=performance.now()-n,v={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:W()-t,cold:m.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(m.fragments.map(E=>[E.relativePath,E.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:y,fragmentStoreMs:R,writeMs:$}};return e.onStatus(`Incremental TypeScript index emitted ${v.affectedFiles.length} affected document(s) in ${(v.durationMs/1e3).toFixed(3)}s (${v.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${y.toFixed(0)}ms, fragments ${R.toFixed(0)}ms, write ${$.toFixed(0)}ms).`),v}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 xm(e){let t=rs();if(!t.available)throw new Error(t.reason);let n=Yl({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:an(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_i}),packageVersion:t.packageVersion});os(e.candidateShardPath,n)}function bm(e,t,n){let r=e.files.filter(i=>ia(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 ss(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Sm(e,t){return ss(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function vm(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=Qa({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,ss(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function ss(e){return ck("sha256").update(e).digest("hex")}import{existsSync as ei,renameSync as ls,rmSync as ds,statSync as mk}from"fs";import{cpus as fk}from"os";import{join as $m}from"path";var as=Symbol("no-error");async function km(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),s=0,a=as,c=!0,l=Array.from({length:o},async()=>{for(;c&&s<e.length;){let d=s++;try{r[d]=await n(e[d])}catch(u){a===as&&(a=u),c=!1}}});if(await Promise.all(l),a!==as)throw a;return r}function gk(e,t,n){if(!e.defaultOutputPath)return;let r=$m(t,e.defaultOutputPath);n!==r&&ei(r)&&ls(r,n)}function hk(e,t,n){if(!e.defaultOutputPath)return null;let r=$m(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return ds(i,{force:!0}),ei(r)?(ls(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function yk(e){e&&(ds(e.defaultOutputPath,{force:!0}),e.backupPath&&ei(e.backupPath)&&ls(e.backupPath,e.defaultOutputPath))}function bk(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,fk().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Cm(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=bk(o.length,r),c=await km(o,a,l=>cs(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.result.skipped&&u.retryable)){let u=o.find(m=>m.id===d.result.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,(await cs(u,t,n)).result))}s.push(...c.map(({result:d})=>l.get(d.id)??d))}else s.push(...c.map(({result:l})=>l));for(let l of i)s.push((await cs(l,t,n)).result);return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function cs(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),ds(e.scipPath,{force:!0});let r=hk(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=W();try{e.trustedProjectTool&&Ia(t,e.trustedProjectTool);let a=tr(e.binary,e.args),c=await hr({command:a.binary,args:a.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Sk(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let l=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${l?`:
|
|
288
|
+
${l}`:""}`)}gk(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
289
|
+
`)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,skipped:{language:e.language,reason:d}},retryable:vk(a)}}finally{yk(r)}if(!ei(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}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let s;try{s=mk(e.scipPath).size}catch{s=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,outputBytes:s},retryable:!1}}function Sk(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):cd.indexer}function vk(e){return e instanceof gr?e.kind==="spawn"&&wm(e.cause):wm(e)}function wm(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Tm}from"child_process";import{homedir as Pm,platform as Rk}from"os";import{delimiter as xk,join as ti}from"path";function ni(e,t){let n=e.installMethods,r=rr(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(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Ot(i.prerequisite))continue;let o=kk(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Tm(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Rk()==="win32"});let s=pn(e);if(s){let a=s===e.indexerBinary?"":` (using ${s})`;return t(`Successfully installed ${i.identity} via ${i.label}${a}; resolved executable: ${s}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(s){let a=s instanceof Error?s.message:String(s);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function kk(e){if(e.binary==="npm")return us("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=us("go",["env","GOBIN"]);if(t)return t;let n=us("go",["env","GOPATH"]);if(n)return ti(n.split(xk)[0],"bin")}return e.binary==="dotnet"?ti(process.env.DOTNET_CLI_HOME??Pm(),".dotnet","tools"):e.binary==="dart"?ti(process.env.PUB_CACHE??ti(Pm(),".pub-cache"),"bin"):e.destination}function us(e,t){try{return Tm(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import hw from"better-sqlite3";import{existsSync as yw}from"fs";import{dirname as bw,join as Sw,resolve as vw}from"path";import{randomUUID as $k}from"crypto";import{mkdtempSync as Ck,rmSync as Pk,statSync as Im}from"fs";import{tmpdir as Tk}from"os";import{join as Am}from"path";import{Worker as Ek}from"worker_threads";function wk(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Kt(){return{skippedReferences:0,skippedReferenceReasons:wk(),skippedReferenceSamples:[]}}function ri(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)}}var Ik=3e5,jm=64*1024*1024,Ak={createResultDirectory:()=>Ck(Am(Tk(),"scip-query-vue-workers-")),spawn:(e,t)=>new Ek(e,{workerData:t}),resultSize:e=>Im(e).size,readResult:e=>G(e,{maxBytes:jm,inputKind:"Vue worker result"}),removeResultDirectory:e=>Pk(e,{recursive:!0,force:!0})};function Om(e){return e.length>=8&&Dm(e.length)>1}async function Lm(e,t=Ak){let n=Dm(e.vueFiles.length),r=Hk(e.vueFiles),i=Uk(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),s=e.timeoutMs??Vk(),a=e.maxResultBytes??Wk();Em("timeoutMs",s),Em("maxResultBytes",a);let c=$k(),l=t.createResultDirectory(),d=[],u,m,f;try{for(let h=0;h<i.length;h++){let b=h,y=i[h]??[],R=y.map(E=>E.taskId),$=Am(l,`${b}.json`),v=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:y,resultPath:$,runId:c,workerId:b,taskIds:R});d.push({workerId:b,taskIds:R,resultPath:$,handle:v,completion:jk(v,b)})}await Ok(d,s);let g=d.sort((h,b)=>h.workerId-b.workerId).map(h=>Dk(h,c,a,t));f={occurrences:g.flatMap(h=>h.occurrences),...Kt()};for(let h of g)ri(f,h)}catch(g){u=g}finally{let g=await Lk(d);if(g.length===0)try{t.removeResultDirectory(l)}catch(h){g.push(h)}if(g.length>0){let h=u===void 0?g:[u,...g];m=new AggregateError(h,`Vue worker cleanup failed: ${qk(h[0])}`)}}if(m)throw m;if(u!==void 0)throw u;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function jk(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",s),e.off("exit",a),c?r(c):n())},s=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},a=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",s),e.once("exit",a)})}async function Ok(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Lk(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Dk(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(s){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:s})}if(!jn(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!Bk(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!Mk(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Mk(e){if(!jn(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Nk)||!nt(e.skippedReferences)||!jn(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!nt(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Fk)}function Nk(e){return jn(e)&&typeof e.sourceFile=="string"&&nt(e.sourceLine)&&nt(e.sourceStartChar)&&nt(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&nt(e.symbolId)}function Fk(e){return jn(e)&&typeof e.sourceFile=="string"&&nt(e.sourceLine)&&nt(e.sourceStartChar)&&nt(e.sourceEndChar)&&typeof e.token=="string"&&_k(e.reason)}function _k(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function nt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bk(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Em(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function qk(e){return e instanceof Error?e.message:String(e)}function Dm(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 Vk(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Ik}function Wk(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:jm}function Hk(e){let t=Gk(),n=[];for(let r of e){let i=Mm(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({taskId:`${n.length}:${r}:${s}`,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 Gk(){return Number.POSITIVE_INFINITY}function Uk(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Jk(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 Jk(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Mm(e.fileName)-e.startOffset)}function Mm(e){try{return Im(e).size}catch{return 1}}import{createRequire as Kk}from"module";import{existsSync as zk}from"fs";import{dirname as Nm,extname as Qk,join as Fm,relative as Yk,resolve as Xk}from"path";import{pathToFileURL as Zk}from"url";function ew(e){e.transaction(()=>{e.prepare(`
|
|
290
|
+
DELETE FROM mentions
|
|
291
|
+
WHERE chunk_id IN (
|
|
292
|
+
SELECT c.id
|
|
293
|
+
FROM chunks c
|
|
294
|
+
JOIN documents d ON d.id = c.document_id
|
|
295
|
+
WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
|
|
296
|
+
)
|
|
297
|
+
`).run(),e.prepare(`
|
|
298
|
+
DELETE FROM chunks
|
|
299
|
+
WHERE document_id IN (
|
|
300
|
+
SELECT id
|
|
301
|
+
FROM documents
|
|
302
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
303
|
+
)
|
|
304
|
+
`).run()})()}function _m(e,t){return e.prepare(`
|
|
305
|
+
SELECT relative_path AS relativePath
|
|
306
|
+
FROM documents
|
|
307
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
308
|
+
ORDER BY relative_path
|
|
309
|
+
`).all().map(r=>Xk(t,r.relativePath))}function Bm(e,t){let{vueCore:n,ts:r,volarTs:i}=tw(e),{parsed:o,vueOptions:s}=nw(n,r,t),a=Nm(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=rw(n,r,c),d=iw(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function tw(e){let t=Kk(Zk(Fm(e,"package.json")).href);return{vueCore:ps(t,"@vue/language-core",e),ts:ps(t,"typescript",e),volarTs:ps(t,"@volar/typescript",e)}}function nw(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,Nm(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function rw(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!zk(o))return;let s=G(o,{maxBytes:xe,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??dw(o))});return r.current=i,i}function iw(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function ps(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 qm(e,t,n){let r=ow(e);return i=>{if(!i.name)return null;let o=rt(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(u=>u.line===a.line&&u.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:sw(c.starts,a.line,2,i.name)}}function ow(e){let t=e.prepare(`
|
|
310
|
+
SELECT
|
|
311
|
+
d.relative_path AS relativePath,
|
|
312
|
+
der.start_line AS startLine,
|
|
313
|
+
der.end_line AS endLine,
|
|
314
|
+
der.symbol_id AS symbolId,
|
|
315
|
+
gs.display_name AS displayName
|
|
316
|
+
FROM defn_enclosing_ranges der
|
|
317
|
+
JOIN documents d ON d.id = der.document_id
|
|
318
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
319
|
+
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
320
|
+
`).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 sw(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 Vm(e,t,n){let r=mw(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
321
|
+
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
322
|
+
VALUES (?, ?, ?, ?)
|
|
323
|
+
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=rt(t,l),u=Ym(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=fw(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Wm(e,t,n,r,i){return e.transaction(()=>(ew(e),aw(e,t,n,r),cw(e,i)))()}function aw(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
324
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
325
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
326
|
+
`),s=e.prepare(`
|
|
327
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
328
|
+
VALUES (?, ?, 1)
|
|
329
|
+
`);for(let a of n){let c=r.get(a);if(!c)continue;let l=rt(t,a),d=i.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Hm(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(ms(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Gm(e){let t=new Set,n=[];for(let r of e){let i=Um(r);t.has(i)||(t.add(i),n.push(r))}return n}function Um(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function cw(e,t){let n=pw(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
330
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
331
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
332
|
+
`),i=e.prepare(`
|
|
333
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
334
|
+
VALUES (?, ?, 0)
|
|
335
|
+
`),o=new Set,s=0,a=0;for(let c of t){let l=Um(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Jm(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 Km(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function ms(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function lw(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 zm(e,t){return rt(e,t).startsWith("node_modules/")}function rt(e,t){return Yk(e,t).replaceAll("\\","/")}function dw(e){switch(Qk(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 Qm(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=G(t,{maxBytes:xe,inputKind:"Vue source file"}),r={text:n,lineStarts:uw(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:lw}}function uw(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function pw(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 mw(e){try{let t=JSON.parse(G(Fm(e,"package.json"),{maxBytes:Re,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function fw(e,t,n,r){let i=rt(n,r),o=Ym(t.name,t.version,i);return e.get(o)?.id??null}function Ym(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function hs(e){return Jt(Pt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Rw(e)}async function Rw(e){let t=vw(e.projectRoot,e.tsconfig);if(!yw(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new hw(e.dbPath);try{let r=_m(n,e.projectRoot),i=Sw(bw(e.dbPath),"augment-vue-meta.json");return await Qp({cachePath:i,readFingerprint:()=>$w(n,e.projectRoot,e.tsconfig),compute:()=>xw({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()}}async function xw(e){let t=Vm(e.db,e.projectRoot,e.vueFiles),n=Om(e.vueFiles)?await Lm({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):ww(e,t);return kw(e,t,n)}function kw(e,t,n){let r=Gm(n.occurrences),i=Wm(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Lw(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Ow(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function ww(e,t){let n=Cw({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Pw({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function $w(e,t,n){let r=e.prepare(`
|
|
336
|
+
SELECT
|
|
337
|
+
(SELECT COUNT(*) FROM documents) AS documents,
|
|
338
|
+
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
339
|
+
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
340
|
+
(SELECT COUNT(*) FROM mentions) AS mentions,
|
|
341
|
+
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
342
|
+
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
343
|
+
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
344
|
+
`).get();return{version:3,tsconfig:n,files:Qn(t),db:r}}function Cw(e){let t=Qm();return{projectRoot:e.projectRoot,context:Bm(e.projectRoot,e.configPath),symbolLookup:qm(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Pw(e){let t=[],n=Kt(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Tw(e,i);t.push(...o.occurrences),ri(n,o)}return{occurrences:t,...n}}function Tw(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Xm(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 Xm(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=rt(e.projectRoot,t.fileName),a=[...Jm(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:Mw(a),processedStarts:new Set};return Ew({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function Ew(e){let t=[],n=Kt();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Iw(e.sourceInfo.text,r.start))continue;let i=Km(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!zm(e.projectRoot,d.fileName));if(!s){fs(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=rt(e.projectRoot,s.fileName),c=Aw(e.sourceFile,r.text,a);if(c){fs(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Hm(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){fs(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Zm(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),Dw(t,e,r,i,a,l)}return{occurrences:t,...n}}function Iw(e,t){let n=e.lastIndexOf(`
|
|
345
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Aw(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Xm(e,t,n){let r=Kt();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:rt(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function fs(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 gs(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 jw(e,t){let n=gs(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=gs(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Ow(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(...gs(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function Lw(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return jw(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Dw(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of Nw(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&&(Zm(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Zm(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 Mw(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Nw(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 d=Fw(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function Fw(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=ms(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Yt(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Uw(e),s=Date.now(),a=W();oi(V(o.outputScip),{recursive:!0}),oi(V(o.outputDb),{recursive:!0});let c=e.languages??vt(t);if(c.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: ${c.join(", ")}`);let l=cn("reindex.fingerprint",()=>fa(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,u;if(e.skipIfUnchanged!==!1&&!nd(t,o.outputDb)&&ef(o.outputScip)===ef(oe(V(o.outputDb),"index.scip"))){let h=Ee(t);if(d=h?fr(h,l):void 0,d){let b=eo(d);if(b){if(!Gw(o,l))try{to({snapshot:d,manifest:b,targetCacheDir:V(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${Qt(y)}`)}}else{let y=await id(d);if(y.kind==="owner")u=y.release;else if(y.kind==="generation-ready"){let R=eo(d);if(R)try{to({snapshot:d,manifest:R,targetCacheDir:V(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch($){r(`Shared generation attach failed after waiting; continuing locally: ${Qt($)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let m=Ka(oe(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!m)throw u?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let f;try{f=await ln("reindex.lock",()=>S$(oe(V(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(h){throw m.release(),u?.(),h}let g=null;try{Vl(o.outputDb,o.outputScip,o.metaPath);let h=Qw(V(o.outputDb));h.removed>0&&r(`Removed ${h.removed} abandoned reindex workspace(s)`);for(let L of h.errors)r(`Could not remove abandoned reindex workspace: ${L}`);let b=null,y=cn("reindex.reuse-check",()=>(b=Jw({opts:e,paths:o,languages:c,fingerprint:l,start:s,monotonicStart:a,onStatus:r}),b),()=>({languages:c.length,reused:b!==null}));if(y){tf({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r});let L=Qo(o.outputDb,y);return L.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${L.reason}`),Zi(t,V(o.outputDb)),y}await ln("reindex.scip-cli-ready",()=>u$(i,r));let R=zw(o);g=R.runDir;let $,v=await ln("reindex.fresh",async()=>($=await Yw({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:l,start:s,monotonicStart:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),$),()=>({languages:c.length,reused:$?.reused,skipped:$?.skipped.length}));tf({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r});let E=Qo(o.outputDb,v);return E.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${E.reason}`),Zi(t,V(o.outputDb)),v}catch(h){let b=li({trigger:e.trigger,result:"failed",start:s,monotonicStart:a,error:h instanceof Error?h.message:String(h)});kf(o.metaPath,b);let y=Xp(o.outputDb,b);throw y.state==="failed"&&r(`Warning: failed reindex activity telemetry was not recorded: ${y.reason}`),h}finally{g&&zt(g,{recursive:!0,force:!0}),f(),m.release(),u?.()}}function tf(e){if(e.snapshot)try{let t=Ee(e.projectRoot),n=t?fr(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}let r=rd({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ee(e.projectRoot);return(i?fr(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});od(e.snapshot,V(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Qt(t)}`)}}function Gw(e,t){if(!Me(e.outputScip)||!Me(e.outputDb)||!xf(e.metaPath,t))return!1;let n=Ye(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Qt(e){return e instanceof Error?e.message:String(e)}function Uw(e){let t=e.outputScip??oe(e.projectRoot,"index.scip"),n=e.outputDb??oe(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:oe(V(n),"meta.json")}}function Jw(e){let t=Ye(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Me(e.paths.outputScip)||!Me(e.paths.outputDb)||!xf(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;Jt(Pt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=W()-e.monotonicStart,r=li({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return kf(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:Kw(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Kw(e,t,n,r){let i=vf(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:On(i[o]),outputBytes:Ln(vs(e.outputDb,o)),durationMs:0}))}function zw(e){let t=qw(oe(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:oe(t,ii(e.outputScip)),tempOutputDb:oe(t,ii(e.outputDb)),tempMetaPath:oe(t,ii(e.metaPath))}}function Qw(e){let t=[],n;try{n=lf(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Qt(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{zt(oe(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Qt(o)}`)}return{removed:r,errors:t}}async function Yw(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ln("reindex.language-indexers",async()=>(n=await Zw(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:d}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),Xw({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=cn("reindex.publish",()=>c$(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let u=cn("reindex.publish",()=>a$(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=u.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:u,shards:c}}function Xw(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Me(e.run.paths.outputScip)||!Me(e.run.paths.outputDb))return!1;let t=Ye(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 Zw(e,t){let n=i$({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[j,_]of n)_.reused&&(r.push({language:j,scipPath:_.scipPath}),i.add(j));for(let j of i)e.onStatus(`Reusing cached ${j} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=Ye(e.paths.outputDb,e.paths.metaPath),a=Mn(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Rm({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Dn(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Dn(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Ss(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:e$(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=p$({languages:e.languages.filter(j=>!i.has(j)&&!u.has(j)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=m?f.filter(j=>j.language!=="typescript"||m.missedProjectIds.has(j.id)):f,y=await Cm(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),R=[];if(m){n$(e.paths.outputDb,y);let j=h.typescript??e.tempPaths.tempOutputScip;R=r$({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:j,reusedProjects:m.reusedProjects})}let $=[...y,...R],{indexedOutputs:v}=f$($,g),E=d?[{language:"typescript",scipPath:d.scipPath}]:[],L=[...r,...E,...v];g$(L,g,e.languages,e.opts.allowPartial,e.onStatus);let Q=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Ln(d.scipPath)??void 0}]:[],x=o$(n,[...y,...Q],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:L,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:s$(n,e.languages),shards:x,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function e$(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=An(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=im(e.projectRoot,r),o=tm(n.fingerprint.files,r),s=nm(r,i),a=rm(r,o,s),c=Mn(e.paths.metaPath),d=t$(c,a,g=>Me(ci(e.paths.outputDb,g))),u=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(u),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:f}}function t$(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.version===on&&Fi(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;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(it(s)!==it(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 n$(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=ci(e,r);oi(V(i),{recursive:!0}),ai(n.scipPath,i)}}function r$(e){return e.reusedProjects.map((t,n)=>{let r=ci(e.outputDb,t),i=Dn(e.tempOutputScip,"typescript-project-cached",n);return ai(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ln(i)??void 0}})}function i$(e){let t=Mn(e.paths.metaPath),n=vf(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=vs(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!==on){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(!Fi(t).languageShardReuse||!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(!Me(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(it(a)!==it(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 o$(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:On(o.fingerprint),outputBytes:Ln(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?On(a.fingerprint):o?On(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:On(o.fingerprint),outputBytes:Ln(ci(n.outputDb,i)),durationMs:0});return r}function On(e){return Bw("sha256").update(it(e)).digest("hex").slice(0,16)}function Ln(e){try{return Vw(e).size}catch{return null}}function s$(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function a$(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(nf(e.paths.outputDb,n),l=rf(n,e.tempPaths.tempOutputScip,e.onStatus));let d=h$({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..."),xm({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(E=>E.language==="typescript"?{language:E.language,scipPath:a.candidateScipPath}:E);return nf(e.paths.outputDb,v),l=rf(v,e.tempPaths.tempOutputScip,e.onStatus),l}});Jt(Pt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let u=Jo(e.tempPaths.tempOutputDb);if(u.added.length>0&&e.onStatus(`Added SQLite query indexes: ${u.added.join(", ")}`),u.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${u.removed.join(", ")}`),d.mode==="incremental"&&a){let v=null,E=null;try{v=new St({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),E=new St({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let L=Ya(v,e.fingerprint,a.referenceFragmentsByFile,E);e.onStatus(`Cached exact TypeScript reference fragments for ${L} affected document(s).`)}catch(L){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${L instanceof Error?L.message:String(L)}.`)}finally{v?.close(),E?.close()}}let m=Ss(e.paths.metaPath),f=d.mode==="incremental"&&a?b$(a,d.changedDocumentPaths):Ho({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:m,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),g=li({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(v=>v.language),skipped:[...r]}),h=d.mode==="incremental"&&d.scipCompanion==="deferred",b={...o};h&&delete b.typescript;let{metadata:y,pruneProjects:R}=pf({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:b,typescriptProjectShardContext:s,lastRefresh:g});y.scipCompanion=h?"deferred":"current",mf(e.paths.outputDb,R),Rs(e.tempPaths.tempMetaPath,y);let $=ql({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:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}});return $.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${$.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),Xl(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),uf(e.paths.outputDb,f,e.onStatus),g}function c$(e,t,n,r,i,o){let s=Ss(e.paths.metaPath),a=null;try{ai(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(m){a=Lp("reused","oracle-error",`Could not snapshot the prior database: ${m instanceof Error?m.message:String(m)}`)}Jt(Pt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let c=Jo(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),a??=Ho({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 l=li({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(m=>m.language),skipped:[...n]}),{metadata:d,pruneProjects:u}=pf({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:l});return mf(e.paths.outputDb,u),Rs(e.paths.metaPath,d),Wl(e.paths.outputDb,e.paths.metaPath),uf(e.paths.outputDb,a,e.onStatus),l}function Ss(e){return oa(Mn(e)?.fingerprint)}function uf(e,t,n){try{Fp(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 pf(e){let t=l$({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:on,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,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 l$(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=Mn(e.metaPath),n=t?.version===on?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function mf(e,t){let n=Rf(e);if(t===null){zt(n,{recursive:!0,force:!0});return}let r;try{r=lf(n)}catch{return}for(let i of d$(r,t))zt(oe(n,i),{force:!0})}function d$(e,t){let n=new Set(t.map(r=>`${ts(r)}.scip`));return e.filter(r=>!n.has(r))}function nf(e,t){for(let n of t){let r=vs(e,n.language);oi(V(r),{recursive:!0}),n.scipPath!==r&&ai(n.scipPath,r)}}async function u$(e,t){if(!Ut()){if(Hw()==="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 scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
346
|
+
To install the reviewed version, run: scip-query reindex --install-missing
|
|
347
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!kp(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
348
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function p$(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?Dn(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=m$({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?ff(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function m$(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[ys({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??An(e.projectRoot,e.typescriptProjects);return t.length===0?[ys({...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)=>ys({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Dn(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function ys(e){let t=$t(e.language),n=rr(t),r=Ta(t,e.projectRoot),i=e.trustProjectTools&&r?Ea(t,e.projectRoot):null,o=pn(t);if(!i&&!o&&r){let l=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!i&&!o&&!Pa(t)){if(e.skipAutoInstall){let l=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!ni(t,e.onStatus)){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}}let s=i?.canonicalPath??pn(t);if(!s){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}let{binary:a,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:s,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});if(i&&!i.executable){let l=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:s,binary:a,args:c,env:Aa(t,e.env,s),...i?{trustedProjectTool:i}:{}}}}function f$(e,t){let n=new Map;for(let i of e)if(i.skipped)ff(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)ed(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&df(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function ff(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 g$(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
|
|
349
|
+
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
350
|
+
`+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.
|
|
351
|
+
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
352
|
+
`))}function rf(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=td(e.map(o=>o.scipPath),t);return hf(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&df(e[0].scipPath,t);return!1}function h$(e){let t;if(y$(e)){let i=oe(e.run.tempPaths.runDir,"typescript-affected.db");try{gf(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();of(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=Gp({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),zt(i,{force:!0}),zt(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 of(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function y$(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Me(e.run.paths.outputDb)||!Me(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 b$(e,t){let n=W(),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:W()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Wo(e.plan,o,e.projectFileCount)}}function of(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Me(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||gf(e,r);let o=Ut();if(!o)throw new Error("scip CLI is not available");_w(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}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 gf(e,t){let n=Zl(e);hf(n,t)}function hf(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Dn(e,t,n){let r=Ww(e)||".scip",i=ii(e,r);return oe(V(e),`${i}.${n+1}.${t}${r}`)}async function S$(e,t){for(let n=0;n<2;n++){let r=v$(e,t);if(r)return r;let i=R$(e);if(i&&Sf(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await k$(i)}catch(a){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${Qt(a)}`,{cause:a})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${V(e)}; refusing to steal an active lock.`);let s=Ji(e,{parseLegacy:si});if(!Ja(e,s,{parseLegacy:si}))throw new Error(`Reindex lock ownership changed before preemption completed for ${V(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${V(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${V(e)}.`)}function v$(e,t){let n=Mt(process.pid),r=Nt(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:si});if(r.kind==="acquired"&&r.reclaimed){let i=yf(r.reclaimed,e);i&&Sf(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${V(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function R$(e){return yf(Ji(e,{parseLegacy:si}),e)}var si=e=>{let t=bf(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function yf(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:V(t),startedAt:e.record.startedAt,trigger:n.trigger}}return bf(e.parsed,t)}function bf(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=Oa(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:V(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function Sf(e,t){return e?.kind==="manual-cli"&&x$(t?.trigger)}function x$(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function k$(e){return!Dt(e.pid)||(bs(e),sf(e,"SIGTERM"),await af(e,2e3))?!0:(bs(e),sf(e,"SIGKILL"),af(e,1e3))}function sf(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!Dt(e.pid))return;bs(e)}try{process.kill(e.pid,t)}catch{}}async function af(e,t){let n=W()+t;for(;W()<n;){if(cf(e))return!0;await w$(50)}return cf(e)}function bs(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=Mt(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!mn(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function cf(e){if(!Dt(e.pid))return!0;if(!e.processIdentity)return!1;let t=Mt(e.pid);return t!==null&&!mn(e.processIdentity,t)}function w$(e){return new Promise(t=>setTimeout(t,e))}function vf(e,t,n){return Object.fromEntries(t.map(r=>{let i=$t(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:ma(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?$$(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&C$(n),...o,clojureConfigPath:s,files:Qn(e,{language:r,markerFiles:i})}]}))}function $$(e){return e?.trim()||void 0}function C$(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function vs(e,t){return oe(V(e),"language-indexes",`${t}.scip`)}function Rf(e){return oe(V(e),"language-indexes","typescript-projects")}function ci(e,t){return oe(Rf(e),`${ts(t)}.scip`)}function Mn(e){try{return Ni(jt(B(e,"reindex metadata")))}catch{return null}}function xf(e,t){try{let n=jt(B(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&ca(r)&&it(r.fingerprint)===it(t)&&it([...r.indexedLanguages??[]].sort())===it(t.languages)}catch{return!1}}function Rs(e,t){Da(e,t,{spacing:2,trailingNewline:!0})}function kf(e,t){try{let n=Ni(jt(B(e,"reindex metadata")));if(!n)return;Rs(e,{...n,lastRefresh:t})}catch{}}function li(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:W()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function it(e){return JSON.stringify(e)}import{statSync as P$}from"fs";import{basename as T$,isAbsolute as E$,join as I$,relative as A$}from"path";import{watch as j$}from"chokidar";import O$ from"ignore";var Pf=5e3,ui=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ie(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.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??F$,Tf.set(this,U$(t.stopTimeoutMs??Pf,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??H$(),this.subscriptionFactory=t.subscriptionFactory??_$,this.gitignoreFilter=mr(t.projectRoot),this.extraIgnore=O$(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,di(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let r=[...di(this).closures],i=D$(this),o=this.clock.now()+i;return this.stopPromise=this.finishStop(t,r,n,o,i).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=Cf(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(r||this.sourcePollingFallbackStarted||!G$(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),M$(di(this),t,i=>this.onError(i));try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||T$(n).startsWith(Ko)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=E$(t)?t:I$(this.projectRoot,t);return A$(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=Cf(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=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-t;this.dirty=!0;let s=this.wallNow()+o;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let i=this.reindexRunner.start(this.reindexRequest(n));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=!1;try{s=this.onReindexComplete(o,n)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(s){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.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(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=o instanceof Error?o:new Error(String(o));this.onReindexError(s,n),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(t,n,r,i,o){let s=[],a=t.map(async m=>{try{await m.close()}catch(f){s.push(`watch subscription close failed: ${String(f)}`)}});a.push(...n),r&&a.push((async()=>{try{let m=await r.cancel();m.state==="degraded"&&s.push(m.reason)}catch(m){s.push(`reindex cancellation failed: ${m instanceof Error?m.message:String(m)}`)}})());let c=a.length,l=a.map(m=>m.finally(()=>{c-=1})),d=await L$(l,i,this.clock),u=di(this);return s.push(...u.errors),u.errors=[],d?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.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=_e(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Ba(this.projectRoot,t),r={head:_e(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=P$(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function L$(e,t,n){if(e.length===0)return!0;let r=Promise.all(e).then(()=>!0),i=Math.max(0,t-n.now()),o=null,s=new Promise(c=>{o=n.setTimeout(()=>c(!1),i)}),a=await Promise.race([r,s]);return a&&o&&n.clearTimeout(o),a}var wf=new WeakMap,Tf=new WeakMap;function di(e){let t=wf.get(e);if(t)return t;let n={closures:new Set,errors:[]};return wf.set(e,n),n}function D$(e){return Tf.get(e)??Pf}function M$(e,t,n){let r=Promise.resolve().then(()=>t.close()).catch(i=>{let o=`watch subscription close failed during polling fallback: ${String(i)}`;e.errors.push(o),n(new Error(o))});e.closures.add(r),r.then(()=>e.closures.delete(r))}function N$(e){let{projectRoot:t,config:n,languages:r,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=e,d=ke(t),u=Object.keys(d).length>0?d:n,m=ze(t,u),f=u.indexer?.typescript,g=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:t,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:f?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:f?.projectMode??o,projects:f?.projects??s??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:g?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var F$={now:W,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_$=(e,t)=>j$(e,t),B$=15*6e4,q$=1e3,V$=64*1024;function W$(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function $f(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
|
|
353
|
+
${r}`:n}function H$(e={}){let t=e.timeoutMs??B$,n=e.terminationGraceMs??q$,r=e.maxOutputBytes??V$,i=e.resolveLaunch??N$;return{start(o){let s=i(o),a=new AbortController,c=W$(),l=!1,d=hr({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error($f(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof gr&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error($f(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Cf(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}function G$(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function U$(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}import{existsSync as fC}from"fs";import{existsSync as If,mkdirSync as Af,writeFileSync as jf}from"fs";import{homedir as J$}from"os";import{dirname as Of,isAbsolute as K$,join as xs,relative as Ef,resolve as z$}from"path";function Lf(e,t={}){let n=t.dossierDir?z$(e.projectRoot,t.dossierDir):xs(e.projectRoot,"docs","scip-query"),r={markdownPath:xs(n,"health-dossier.md"),jsonPath:xs(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=iC({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return tC(r.markdownPath,Q$(i),r),nC(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Q$(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${ws(e.health)}`,"","## Items That Need Attention","",...Y$(e),"","## Blocked Or Unavailable Checks","",...X$(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","",...Z$(e),"","## JSON","",`Machine-readable report: \`${eC(e)}\``,""].join(`
|
|
354
|
+
`)}`}function Y$(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 X$(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 Z$(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 ws(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function eC(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function tC(e,t,n){if(Af(Of(e),{recursive:!0}),(If(e)?B(e,"health dossier Markdown"):null)===t){n.unchanged.push(e);return}jf(e,t),n.written.push(e)}function nC(e,t,n){Af(Of(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
|
|
355
|
+
`,i=If(e)?B(e,"health dossier JSON"):null;if(i&&rC(i,r)){n.unchanged.push(e);return}jf(e,r),n.written.push(e)}function rC(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 iC(e,t){return ks(e,t)}function ks(e,t){return typeof e=="string"?oC(e,t):Array.isArray(e)?e.map(n=>ks(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,ks(r,t)])):e}function oC(e,t){if(e===t)return".";if(!K$(e))return e;let n=Ef(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=Ef(J$(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as sC}from"child_process";import{dirname as Df,join as aC,resolve as cC}from"path";import{fileURLToPath as lC}from"url";var pi={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 dC(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of pi[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function $s(e){return[...new Set(e.filter(t=>pi[t]!==void 0))].sort()}function Mf(e,t={}){let n=t.runtime??mC,r=t.packageRoot??uC(),i=$s(e),o=i.filter(u=>n.probe(pi[u].ast)),s=i.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=pC(r),c=dC(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(pi[u].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function uC(){let e=Df(lC(import.meta.url));for(;;){let t=aC(e,"package.json");try{if(JSON.parse(B(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=Df(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function pC(e){return JSON.parse(B(cC(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var mC={probe:e=>Yn(e)==="ast",resetProbe:ha,install:(e,t)=>{let n=sC(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",timeout:3e5,killSignal:"SIGKILL",maxBuffer:10485760});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function _f(e){if(e.guided){if(e.yes)throw new Error("--guided cannot be combined with --yes; choose interactive or automatic setup.");if(e.json)throw new Error("--guided cannot be combined with --json; the interactive checklist emits human output.");if(!e.stdinIsTty||!e.stdoutIsTty)throw new Error("--guided requires an interactive terminal; use --yes for non-interactive setup.")}}function Bf(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 --install-missing"}),{actions:t}}async function qf(e={}){let t=[],n=Xe(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?_l(r,n.config,e.languages):null,c=a?.config??n.config,l=_t(c,{projectRoot:r}),d=l.filter(D=>D.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=Bl(r,c,s)}catch(D){m=Xt(D)}let f=u?.config??c,g=Tn();q(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:m!==null?"failed":d.length>0||!s?"skipped":"ok",message:m??(d.length>0?"Skipped because the existing project config has validation errors.":s?u?.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."),...u?{details:[u.configPath]}:{}}),q(t,{id:"scip-cli",label:"scip CLI",status:g?"ok":"warn",message:g?"scip CLI is available.":"scip CLI is not available; installation requires explicit --install-missing consent."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Hr({quiet:!0});q(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(D=>`Pruned ${D}`),...h.skipped.map(D=>`Skipped ${D}`)]});let b=u?_t(f,{projectRoot:r}):l,y=b.filter(D=>D.level==="error");q(t,{id:"config",label:"Project config",status:y.length>0?"failed":b.length>0?"warn":"ok",message:b.length===0?"Config OK.":`${b.length} diagnostic(s), ${y.length} error(s).`,details:b.map(D=>`${D.level.toUpperCase()} ${D.path}: ${D.message}`)});let R=$e(r,f);q(t,{id:"readiness",label:"Indexer readiness",status:R.languages.length===0?"failed":R.indexers.some(D=>!D.runnable)?"warn":"ok",message:R.languages.length===0?"No supported project languages detected.":`Detected languages: ${R.languages.join(", ")}`,details:R.indexers.map(D=>`${D.runnable?"OK":D.installed?"WARN":"MISSING"} ${D.language}: ${D.binaryLabel}${D.note?` - ${D.note}`:""}`)});let $=e.installAstParsers!==!0?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Mf(R.languages);q(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers!==!0?"skipped":$.unavailable.length>0?"warn":"ok",message:e.installAstParsers!==!0?"Skipped because installing missing parser packages requires explicit consent.":$.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${$.availableAfter.length}/${$.supportedLanguages.length} selected language parser(s) available${$.installed.length>0?`; installed ${$.installed.join(", ")}`:""}.`,details:[...$.unavailable.length>0?[`Unavailable: ${$.unavailable.join(", ")}`]:[],...$.error?[$.error]:[]]});let v=e.installIndexers===!0,E=v?$C(r,R,t):[];v||q(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent."});let L=$e(r,f),Q=await gC({projectRoot:r,paths:i,config:f,readiness:L,configHasErrors:y.length>0,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),x=Q.reindexResult,j=Q.freshness,_=Ie(f),F=hC({projectRoot:r,cacheDir:i.cacheDir,watchConfig:_,readiness:L,configHasErrors:y.length>0,reindexResult:x,postReindexFreshness:j,steps:t}),H=$e(r,f),Pe=ut(H),yt=Ae(r,f,i);q(t,{id:"capabilities",label:"Capability matrix",status:AC(Pe),message:jC(Pe)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let ra=e.runHealth===!1?TC(t):await PC(i.dbPath,t),Ne=H.languages.includes("rust")?sr(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;q(t,{id:"rust-semantic-session",label:"Rust semantic session",status:Ne===null?"skipped":Ne.valid?"ok":"failed",message:Ne===null?"Skipped because Rust was not detected.":`${Ne.transport}/${Ne.state} selected from ${Ne.source}; ${Ne.fallback} fallback; opt out with ${Ne.optOut}.`});let ae=null;try{e.noHooks?q(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ae=Gt(r),q(t,{id:"project-hooks",label:"Project agent hooks",status:ae.skipped.length>0?"warn":"ok",message:`${ae.installed.length} installed, ${ae.updated.length} updated, ${ae.unchanged.length} already configured, ${ae.removed.length} hook config(s) cleaned up, ${ae.skipped.length} skipped.`,details:[...ae.gitExcluded.map(D=>`Checkout-local Git exclude: ${D}`),...ae.removed.map(D=>`Removed ${D}`),...ae.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`),...ae.warnings]}))}catch(D){q(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Xt(D)})}let Te=null;try{e.noAgentGuidance?q(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Te=Lr(r,{gitHook:e.gitHook}),q(t,{id:"agent-guidance",label:"Project agent guidance",status:Te.skipped.length>0?"warn":"ok",message:`${Te.written.length} written, ${Te.unchanged.length} already wired, ${Te.skipped.length} skipped.`,details:Te.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`)}))}catch(D){q(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Xt(D)})}let Gn=yC({reindexResult:x,readiness:H,capabilities:Pe,freshness:yt,health:ra,hooksResult:ae,agentResult:Te,watchConfig:_,watchService:F,rustSemanticSession:Ne,steps:t});q(t,{id:"smoke-tests",label:"Setup smoke tests",status:bC(Gn),message:SC(Gn),details:Gn.map(D=>`${D.command}: ${D.status} - ${D.evidence}`)});let zy={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...Te?.written.filter(D=>!D.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ae?.installed??[],...ae?.updated??[],...ae?.gitExcluded??[],...Te?.written.filter(D=>D.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...$.installed,...E.filter(D=>D.attempted).map(D=>`${D.binaryLabel} installer`)]},Ge={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:$,initialReadiness:R,indexerRemediation:E,readiness:H,capabilities:Pe,freshness:yt,reindex:x,automaticRefreshConfig:u,watchService:F,rustSemanticSession:Ne,health:ra,smokeTests:Gn,healthDossier:null,hooks:ae,setupAgent:Te,changeScopes:zy,filesWritten:Te?.written??[],verdict:Ps(t,H)};if(e.runHealth===!1)return q(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ge.verdict=Ps(t,H),Ge;let Fe=Lf(Ge,{dossierDir:e.dossierDir});return Ge.healthDossier=Fe,Ge.changeScopes.repository.push(...Fe.written),Ge.filesWritten=[...Ge.filesWritten,...Fe.written],q(t,{id:"health-dossier",label:"Health dossier",status:Fe.status==="failed"?"failed":"ok",message:Fe.status==="failed"?Fe.error:`${Fe.written.length} written, ${Fe.unchanged.length} unchanged.`,details:[Fe.markdownPath,Fe.jsonPath]}),Ge.verdict=Ps(t,H),Ge}async function gC(e){if(e.readiness.languages.length===0||e.configHasErrors)return q(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 Yt({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,installMissing:e.installMissing,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=Ae(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.");q(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){q(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Xt(i),details:t})}return{reindexResult:n,freshness:r}}function hC(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 q(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=wr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:be,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 q(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 q(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Xt(n)}),null}}function Vf(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${ws(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:"),Cs("Repository records (commit)",e.changeScopes.repository),Cs("Checkout preferences (do not commit)",e.changeScopes.checkout),Cs("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 Cs(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function yC(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:vC(e.steps),evidence:RC(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?xC(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:Nf(e.readiness,e.freshness),evidence:Ff(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Nf(e.readiness,e.freshness),evidence:Ff(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:kC(e.capabilities),evidence:wC(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 bC(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function SC(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 vC(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function RC(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function xC(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 Nf(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Ff(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 kC(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function wC(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 $C(e,t,n){let r=[];if(t.languages.length===0)return q(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=$t(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=ni(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=CC(ir(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return q(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 q(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 CC(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function PC(e,t){if(!fC(e)){let n="Skipped because no SQLite index database exists yet.";return q(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Ts(n)}try{let n=await Rr({full:!0,json:!0});return q(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),EC(n)}catch(n){let r=Xt(n);return q(t,{id:"health",label:"Health audit",status:"failed",message:r}),Ts(r)}}function TC(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return q(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Ts(t)}function EC(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(IC),warnings:e.warnings??[]}}function IC(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-audit to confirm this signal; use scip-improve when the user wants confirmed issues fixed autonomously."}}function Ts(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ps(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 AC(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 jC(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 q(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Xt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as OC}from"readline";function LC(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function DC(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 Wf(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=LC(e);OC(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
|
|
356
|
+
`),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
|
|
357
|
+
|
|
358
|
+
`),e.forEach((a,c)=>{let l=c===r.cursor?"\u203A":" ",d=r.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
|
|
359
|
+
`)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(d,u)=>{if(u.ctrl&&u.name==="c"){l(),a(new Error("Setup cancelled."));return}if(u.name==="return"||u.name==="enter"){l(),n.write(`
|
|
360
|
+
`),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=DC(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Hf,mkdirSync as MC,writeFileSync as NC}from"fs";import{dirname as FC,join as Gf}from"path";function Uf(e,t={}){let n=Gf(e,".github","workflows","scip-query.yml"),r=_C({hasNpmProject:Hf(Gf(e,"package.json"))});return Hf(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(MC(FC(n),{recursive:!0}),NC(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function _C(e){let t=`scip-query@${be}`;return`name: scip-query
|
|
361
|
+
|
|
362
|
+
# Generated by scip-query setup-ci.
|
|
363
|
+
# Install the language indexers your repository needs before the reindex step
|
|
364
|
+
# if they are not already provided by your dependency install.
|
|
365
|
+
|
|
366
|
+
on:
|
|
367
|
+
pull_request:
|
|
368
|
+
|
|
369
|
+
jobs:
|
|
370
|
+
diff-gate:
|
|
371
|
+
runs-on: ubuntu-latest
|
|
372
|
+
steps:
|
|
373
|
+
- uses: actions/checkout@v4
|
|
374
|
+
with:
|
|
375
|
+
fetch-depth: 0
|
|
376
|
+
- uses: actions/setup-node@v4
|
|
377
|
+
with:
|
|
378
|
+
node-version: 22
|
|
379
|
+
- uses: actions/cache@v4
|
|
380
|
+
with:
|
|
381
|
+
path: ~/.cache/scip-query
|
|
382
|
+
key: scip-query-\${{ runner.os }}-\${{ hashFiles('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock', 'go.sum', 'poetry.lock', 'uv.lock') }}
|
|
383
|
+
${e.hasNpmProject?` - run: npm ci
|
|
384
|
+
`:[" # TODO: install this repository's dependencies before indexing."," # This project did not have a package.json when the workflow was generated."].join(`
|
|
385
|
+
`)+`
|
|
386
|
+
`} - run: npx ${t} reindex
|
|
387
|
+
- run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
|
|
388
|
+
`}import{existsSync as BC}from"fs";import{join as mi}from"path";function Jf(e,t={}){let n=[],r=e.dryRun?"would ":"";if(e.global){for(let o of e.global.removed)n.push(` ${r}remove: ${o}`);if(t.verbose)for(let o of e.global.left)n.push(` left: ${o}`);else if(e.global.left.length>0){let o=e.global.left.length===1?"entry":"entries";n.push(` left: ${e.global.left.length} unrelated global skill ${o} (use --verbose to list)`)}for(let o of e.global.skipped)n.push(` skip: ${o}`)}if(e.project){for(let o of e.project.hooks.removed)n.push(` ${r}remove: ${o}`);for(let o of e.project.agentSetup.removed)n.push(` ${r}remove: ${o}`);for(let o of e.project.agentSetup.unchanged)n.push(` ok: ${o} (no managed block)`);for(let o of e.project.hooks.skipped)n.push(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of e.project.agentSetup.skipped)n.push(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of e.project.left)n.push(` left: ${o}`)}return(e.global?.removed.length??0)+(e.project?.hooks.removed.length??0)+(e.project?.agentSetup.removed.length??0)===0&&n.push(e.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed."),n}function Es(e){let t=e.global===!0,n=e.project===!0;return t&&n?{ok:!1,message:"choose either --global or --project, not both."}:!t&&!n?e.dryRun===!0?{ok:!0,global:!0,project:!0}:{ok:!1,message:"uninstall requires an explicit scope: use --global or --project. To preview both scopes without removing anything, run uninstall --dry-run."}:{ok:!0,global:t,project:n}}function Kf(e){let t=Es(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=Cp({dryRun:e.dryRun,homeDir:e.homeDir})),t.project&&(n.project=qC(e.projectRoot,{dryRun:e.dryRun})),n}function qC(e,t={}){return{hooks:Gt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Eu(e,{dryRun:t.dryRun}),left:VC(e)}}function VC(e){return[[".scipquery.json",mi(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",mi(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",mi(e,".scipquery","ledger")],["docs/scip-query/",mi(e,"docs","scip-query")]].filter(([,t])=>BC(t)).map(([t])=>t)}import{existsSync as WC}from"fs";import{createRequire as HC}from"module";import gi from"path";import{performance as fi}from"perf_hooks";var GC=HC(import.meta.url),Nn;function Zf(e){let t=UC();if(!t)return cr("typescript is not installed");let n=Ha(e);if(n.length===0)return cr("no tsconfig found");try{return new Is(e.config.projectRoot,t,n.map(r=>JC(t,r)))}catch(r){return cr(r instanceof Error?r.message:String(r),n[0],n)}}function eg(e,t,n){let r=fi.now(),i=zf(t,e),o=fi.now()-r,s=fi.now(),a=zf(n,e),c=fi.now()-s,l=[],d=0,u=0,m=0,f=0,g=0;for(let h of e){let b=i.get(h.symbolId)??[],y=a.get(h.symbolId)??[];u+=b.length,m+=y.length;let R=Qf(b),$=Qf(y),v=Yf(b,$),E=Yf(y,R);if(v.length===0&&E.length===0){d+=1;continue}f+=v.length,g+=E.length,l.push({symbol:h.symbol,missing:v,extra:E})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:f,extraReferenceCount:g,baselineReferenceCount:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var Is=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=gi.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=zC(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 d=QC(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return Va(a)}bundleForFile(t){let n=ng(t);return this.bundles.find(r=>r.files.has(n))??null}};function UC(){if(Nn!==void 0)return Nn;try{Nn=GC("typescript")}catch{Nn=null}return Nn}function JC(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Xf(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,gi.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Xf(e,s)).join(`
|
|
389
|
+
`));let i=new Set(r.fileNames.map(ng)),o=e.createLanguageService(KC(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function KC(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?gi.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(WC(n))return e.ScriptSnapshot.fromString(G(n,{maxBytes:xe,inputKind:"TypeScript language-service source file"}))},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 zC(e,t,n){let r=t.text.split(`
|
|
390
|
+
`),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 QC(e,t,n,r){let i=Wa(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 zf(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Qf(e){return new Set(e.map(tg))}function Yf(e,t){return e.filter(n=>!t.has(tg(n)))}function tg(e){return`${e.file}:${e.line}:${e.column}`}function ng(e){return gi.resolve(e).replace(/\\/g,"/")}function Xf(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
|
|
391
|
+
`)}function rg(e){let t=[],n=G(e,{maxBytes:sn,inputKind:"profile JSONL artifact"});for(let[r,i]of n.split(`
|
|
392
|
+
`).entries()){let o=i.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch(a){throw new Error(`${e}:${r+1}: invalid profile JSON: ${a instanceof Error?a.message:String(a)}`,{cause:a})}if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`${e}:${r+1}: profile event must be a JSON object`);t.push(s)}return t}function ig(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,d=0,u=0;for(let[b,y]of e.entries()){let R=Ce(y.name)??Ce(y.phase),$=rP(y.durationMs),v=Ce(y.runId);R&&$!==null&&(l+=1,s.add(R),v&&o.add(v),YC(i,y,R,$),XC(r,y,R,$,v),Ce(y.subsystemWorkIdentity)&&c.add(R));let E=Ce(y.workIdentity);if(!E)continue;d+=1,R&&a.add(R);let L=nP(y.workOutcome);if(!R||$===null||!L){u+=1;continue}let Q=v??`unknown-run-${b}`,x=JSON.stringify([R,E]),j=n.get(x)??{spanName:R,workIdentity:E,observations:[]};j.observations.push({runId:Q,command:Ce(y.command)??"unknown",durationMs:$,outcome:L}),n.set(x,j)}let m=[...n.values()].map(tP).filter(b=>b!==null).sort((b,y)=>y.estimatedAvoidableMs-b.estimatedAvoidableMs||y.repeatComputations-b.repeatComputations||b.spanName.localeCompare(y.spanName)||b.workIdentity.localeCompare(y.workIdentity)),f=[...r.values()].map(ZC).filter(b=>b!==null).sort((b,y)=>y.laterRunMs-b.laterRunMs||y.laterRunEvents-b.laterRunEvents||b.spanName.localeCompare(y.spanName)),g=[...i.values()].map(eP).sort((b,y)=>y.totalDurationMs-b.totalDurationMs||b.subsystem.localeCompare(y.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:u,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:g.reduce((b,y)=>b+y.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:f.length,largestRepeatedWorkloadMs:f[0]?.laterRunMs??0,workloadRows:f.slice(0,h),subsystemCoverage:g}}function og(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(`
|
|
393
|
+
`)}
|
|
394
|
+
`}function YC(e,t,n,r){let i=Ce(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),Ce(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),Ce(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function XC(e,t,n,r,i){let o=Ce(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=Ce(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:Ce(t.command)??"unknown",durationMs:r}),e.set(a,c)}function ZC(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:Zt(e.observations.map(o=>o.durationMs)),firstRunMs:Zt(r.map(o=>o.durationMs)),laterRunMs:Zt(i.map(o=>o.durationMs))}}function eP(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 tP(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=Zt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Zt(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:Zt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:hi(e.observations,"cache-hit"),cacheMisses:hi(e.observations,"cache-miss"),reused:hi(e.observations,"reused"),skipped:hi(e.observations,"skipped")}}function nP(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function hi(e,t){return e.filter(n=>n.outcome===t).length}function rP(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ce(e){return typeof e=="string"&&e.length>0?e:null}function Zt(e){return e.reduce((t,n)=>t+n,0)}var sg={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 ag(e,t){let n=iP(t);return{...e,warnings:[...e.warnings??[],sg.note,...n],capabilities:t,scoreInterpretation:sg}}function iP(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.`]})}import{createHash as oP}from"crypto";import{basename as sP,join as aP}from"path";function ug(e,t){let n=[t.id?`finding ${t.id}`:void 0,t.check?`check ${t.check}`:void 0,t.file?`file ${t.file}`:void 0].filter(i=>i!==void 0),r=t.decision;return[`Suppression ${e.disposition} at ${e.path}.`,` scope: ${n.join("; ")}`,` reason code: ${r?.reasonCode??"legacy/manual"}`,` counterevidence: ${r?.evidence.length??0} item(s)`,` expires: ${t.expiresAt??"none \u2014 no time limit; evidence invalidation still applies"}`,` revision: ${e.revision}`]}var Fn=class extends Error{constructor(n,r,i){super(`${n} ${i?`Current revision: ${i}. Retry with --replace ${i} after reviewing it.`:"The suppression file was left untouched."}`);this.path=r;this.currentRevision=i;this.name="SuppressionWriteConflictError"}path;currentRevision};function pg(e,t,n,r,i){if(!Mi.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${Mi.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let o=n.map(s=>mP(e,s,r));return{kind:"automated-adjudication",reasonCode:t,decidedBy:"agent",policyVersion:1,...i?{observation:i}:{},evidence:o,invalidateOn:{targetContentChange:o.some(s=>s.contentHash!==void 0),detectorMajorChange:!0}}}function mg(e,t,n={}){let r=n instanceof Date?{now:n}:n,i=lP(t),o=dP(r.expectedRevision),s=aP(ol(e),sl(i)),a=r.now??new Date,c="unchanged",l=Qe(s,d=>{if(!d.revision.exists){if(o)throw new Fn(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:dg(cg(i,void 0,a,r.toolVersion))}}let u=cP(d);if(uP(u.suppression,i))return c="unchanged",{kind:"unchanged"};if(!o)throw new Fn(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(o!==d.revision.hash)throw new Fn(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:dg(cg(i,u.suppression,a,r.toolVersion))}},{maxRetries:0,onBeforeCommit:r.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function cP(e){let t;try{t=JSON.parse(e.text)}catch(r){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:r})}let n=cl(t,pP(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function cg(e,t,n,r=be){let i=n.toISOString(),{decision:o,createdAt:s,...a}=e,c={kind:nl,suppressionIdentity:al(e),writer:{tool:"scip-query",version:r},...a,createdAt:t?.createdAt??s??i,...t?{updatedAt:i}:{}};return o?{...c,schemaVersion:il,decision:o}:{...c,schemaVersion:rl}}function lP(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),r=e.check?.trim();if(!n&&!r)throw new Error("suppression requires an id or a check");if(e.decision!==void 0&&!el(e.decision))throw new Error("suppression decision is malformed");return{...n?{id:n}:{},...r?{check:r}:{},...e.file?{file:e.file}:{},reason:t,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function dP(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("--replace requires the 64-character SHA-256 revision reported by suppress.");return t}function uP(e,t){return JSON.stringify(lg(e))===JSON.stringify(lg(t))}function lg(e){let{createdAt:t,...n}=e;return n}function pP(e){let t=sP(e);return t.endsWith(".json")?t.slice(0,-5):t}function dg(e){return`${JSON.stringify(e,null,2)}
|
|
395
|
+
`}function mP(e,t,n){let r=t.indexOf(":");if(r<=0||r===t.length-1)throw new Error("--evidence must use <source|config|test|graph>:<referent>");let i=t.slice(0,r),o=t.slice(r+1).trim();if(i==="graph"){if(!o.startsWith("scip-query "))throw new Error("graph suppression evidence must name the exact scip-query command that produced it");return{kind:i,referent:o,claim:n}}if(i!=="source"&&i!=="config"&&i!=="test")throw new Error(`unsupported suppression evidence kind ${JSON.stringify(i)}`);let s=la(o),a=Ue(e,s);return{kind:i,referent:s,claim:n,contentHash:oP("sha256").update(a).digest("hex")}}var vP=new Set(sa),RP=18e4,bg=100*1024*1024,xP=new Set(ya),kP=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],wP=[["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 $P(e){return e.filter(t=>vP.has(t))}async function Sg(e){let t=Y(e),n=te(),r=ke(n),i=ze(n,r),o=S(t,"json");try{let s=$P(Rt(t,"language")),a=await Yt({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:S(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!S(t,"force"),allowPartial:S(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:S(t,"installMissing"),trustProjectTools:S(t,"trustProjectTools"),indexerConcurrency:X(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){A("reindex",[],t,a);return}if(a.skipped.length>0){let c=a.languages.length>0?a.languages.join(", "):"none";console.log(`Reindex partial: available language output ${c}; ${a.skipped.length} skipped in ${(a.durationMs/1e3).toFixed(1)}s.`);for(let l of a.skipped)console.log(` skip: ${l.language} \u2014 ${l.reason}`)}else 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 vg(){let e=te(),t=Bt(e);try{let n=Ur({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)}}async function Rg(e){let t=Y(e),n=te(),r=Bt(n);try{let i=await hs({projectRoot:n,dbPath:r,tsconfig:C(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 xg(e){let t=Y(e);de(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=qc(n,{base:C(t,"base")}),o=Vc(n,r,i.changedFiles,i.changedRanges);br(yn,o)})}function kg(){let e=eu(process.env[kt]);de(t=>{br(wt,Zd(t,e))})}async function wg(e){let t=Y(e);try{let n=await md({base:C(t,"base")});if(S(t,"json")){A("diff-impact",[],t,n);return}fd(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function $g(e,t){let n=Y(t),r=String(e).split(",").filter(i=>i.length>0);de(i=>{let o=[];for(let c of r)Cl.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:C(n,"scope"),full:S(n,"full")},a=o.length===1?Pl(i,o[0],s):Tl(i,o,s);br(hn,a)})}async function Cg(e){let t=Y(e);if(S(t,"writeBaseline")||S(t,"baseline")){BP(t);return}try{let n=await Rr({scope:C(t,"scope"),full:S(t,"full"),json:S(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Xe(),s=ut($e(r,i),{hasIndexedGraph:se(o)}),a=ag(n,s);if(S(t,"json")){A("health",[],t,a);return}pd(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Pg(e){let t=Y(e),n=te(),r=X(t,"timeoutMs")??RP,i=S(t,"progress"),o=S(t,"profile"),s=C(t,"profileOut"),a={projectRoot:n,...MP(n),index:js(se(Bt(n))),commands:[]};S(t,"coldIndex")&&(en(i,"cold index started"),a.coldIndex=await CP(n),en(i,`cold index finished ${a.coldIndex.durationMs}ms`),dn({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),en(i,"warm index started"),a.warmIndex=await AP(n),en(i,`warm index finished ${a.warmIndex.durationMs}ms`),dn({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=js(se(Bt(n))));for(let c of jP(t))a.commands.push(LP(n,c,r,{progress:i,profile:o,profileOut:s}));if(S(t,"json")){A("bench",[],t,a);return}NP(a)}function Tg(e,t){let n=Y(t),r=SP(String(e)),i=ig(rg(r),{top:X(n,"top")??20});if(S(n,"json")){A("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(ld(og(i,r)))}function Eg(e){let t=Y(e);de(n=>{let r=n.config.projectRoot,i=C(t,"scope")??null,o=S(t,"full"),s=X(t,"limit")??200,a=Math.max(0,X(t,"maxMismatches")??10),c=xa(n).filter($=>fn($.relativePath)).filter($=>!n.isIgnored($.relativePath)).sort(_P),l=i?c.filter($=>$.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=gt.now(),m=Ua(n),f=Number((gt.now()-u).toFixed(3)),g=gt.now(),h=Zf(n),b=Number((gt.now()-g).toFixed(3)),y=eg(d,m,h),R={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:d.length},baseline:{provider:"ts-morph",createMs:f,availability:m.availability()},candidate:{provider:"tsserver",createMs:b,availability:h.availability()},comparison:{...y,mismatches:y.mismatches.slice(0,a)}};if(S(t,"json")){A("typescript-semantic-compare",[],t,R);return}FP(R)})}async function CP(e){let t=ke(e),n=ze(e,t),r=bi(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;PP(e,r);let o=TP(e,r,i);Ml(e,r);try{let s=await Ag(()=>Yt({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 fg(e,r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...jg(e)}}catch(s){throw fg(e,r,i,o,"restore-backup"),s}}function yi(e){return Tt(Dl(),"bench-restores",`${Nl(e)}.json`)}function PP(e,t){let n=yi(t);if(!se(n))return!1;let r=Ig(B(n,"benchmark restore marker")),i=hP(e),o=pr(t);if(!r||r.canonicalProjectRoot!==i||r.originalCachePath!==o||yi(r.originalCachePath)!==n)throw new Error(`refusing invalid cold-index restore marker ${n}`);return se(r.backupPath)?(Xi(e,r.backupPath,r.originalCachePath,r.ownerSha256),se(r.originalCachePath)&&(bt(e,r.originalCachePath),As(r.originalCachePath,{recursive:!0,force:!0})),Os(r.backupPath,r.originalCachePath),bt(e,r.originalCachePath)):se(r.originalCachePath)&&bt(e,r.originalCachePath),Ls(n),!0}function TP(e,t,n){if(!se(t))return!1;let r=bt(e,t),i=EP(r.record.canonicalCacheDir,n);if(se(i))throw new Error(`refusing existing cold-index backup ${i}`);let o=yi(r.record.canonicalCacheDir),s={schemaVersion:1,canonicalProjectRoot:r.record.canonicalProjectRoot,originalCachePath:r.record.canonicalCacheDir,backupPath:i,ownerSha256:r.ownerSha256};IP(o),yP(o,`${JSON.stringify(s,null,2)}
|
|
396
|
+
`,{flag:"wx",mode:384});try{Os(r.physicalCacheDir,i)}catch(a){throw Ls(o),a}return!0}function fg(e,t,n,r,i){if(!r)return;let o=yi(t),s=Ig(B(o,"benchmark restore marker"));if(!s||s.backupPath!==n||s.originalCachePath!==pr(t))throw new Error(`refusing invalid cold-index restore marker ${o}`);Xi(e,n,s.originalCachePath,s.ownerSha256),i==="restore-backup"?(se(t)&&(bt(e,t),As(t,{recursive:!0,force:!0})),Os(n,s.originalCachePath),bt(e,s.originalCachePath)):As(n,{recursive:!0,force:!0}),Ls(o)}function Ig(e){try{let t=JSON.parse(e);return t.schemaVersion===1&&typeof t.canonicalProjectRoot=="string"&&typeof t.originalCachePath=="string"&&typeof t.backupPath=="string"&&typeof t.ownerSha256=="string"&&/^[a-f0-9]{64}$/.test(t.ownerSha256)?t:null}catch{return null}}function EP(e,t){let n=`${e}.bench-backup-`,r=pr(t);if(!r.startsWith(n)||!/^\d+$/.test(r.slice(n.length)))throw new Error(`refusing cold-index backup outside the owned cache namespace: ${t}`);return r}function IP(e){let t=bi(e);gP(t,{recursive:!0,mode:448}),process.platform!=="win32"&&fP(t,448)}async function AP(e){let t=ke(e),n=ze(e,t),r=await Ag(()=>Yt({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,...jg(e)}}async function Ag(e){let t=gt.now(),n=await e();return{durationMs:Math.round(gt.now()-t),value:n}}function jg(e){return se(Bt(e))?de(t=>{let n=Ft(t);return{files:n.documents,symbols:n.symbols}}):{}}function jP(e){let t=Rt(e,"command");return t.length>0?t.map(OP).filter(n=>n.length>0):[...kP.map(n=>[...n]),...S(e,"includeHeavy")?wP.map(n=>[...n]):[]]}function OP(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function LP(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;en(r.progress,`${i} started`),dn({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=gt.now(),s={...r.profile?DP(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=yg(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:bg,timeout:n}),c=Math.round(gt.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 en(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),dn({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 en(e,t){e&&process.stderr.write(`[bench] ${ro(t)}
|
|
397
|
+
`)}function DP(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function MP(e){let t=yg("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:bg,timeout:3e4,killSignal:"SIGKILL"});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
|
|
398
|
+
`).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>xP.has(bP(r).toLowerCase())).length}}function NP(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, ${je(e.index.indexSizeBytes)}`),e.coldIndex&&gg("Cold index",e.coldIndex),e.warmIndex&&gg("Warm index",e.warmIndex),console.log(`
|
|
399
|
+
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 gg(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function FP(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(`
|
|
400
|
+
Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function _P(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function BP(e){let t=C(e,"scope");de(n=>{if(S(e,"writeBaseline")){let i=Qc(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Yc(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 Og(){let e=Hr(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
401
|
+
${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 Lg(e){let t=Y(e),n=ip({remove:S(t,"remove"),force:S(t,"force"),dryRun:S(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let r=te(),i=Gt(r,{shared:S(t,"shared"),remove:S(t,"remove"),force:S(t,"force"),dryRun:S(t,"dryRun")});if(S(t,"json")){A("setup-hooks",[],t,i);return}for(let s of i.installed)console.log(` done: ${s}`);for(let s of i.updated)console.log(` update: ${s}`);for(let s of i.unchanged)console.log(` ok: ${s} (already configured)`);for(let s of i.removed)console.log(` ${n.mode==="preview-remove"?"would remove":"remove"}: ${s}`);for(let s of i.gitExcluded)console.log(` local: ${s} (excluded through .git/info/exclude)`);for(let s of i.warnings)console.log(` warning: ${s}`);for(let s of i.skipped)console.log(` skip: ${s.target} \u2014 ${s.reason}`);if(n.mode!=="install"){i.removed.length===0?console.log(n.mode==="preview-remove"?`
|
|
402
|
+
No managed project hooks would be removed.`:`
|
|
403
|
+
No managed project hooks were removed.`):console.log(n.mode==="preview-remove"?`
|
|
404
|
+
Preview only: no project hook files were changed.`:`
|
|
405
|
+
Managed project hooks were removed; the Claude opt-out marker prevents automatic reinstallation.`);return}i.installed.length+i.updated.length+i.unchanged.length>0?(console.log(`
|
|
406
|
+
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(`
|
|
407
|
+
No project-local hook config was written.`)}function Dg(){let e=!1;Tn()?console.log("scip CLI: installed"):(Mo(),e=!0);let t=te(),n=ke(t),r=$e(t,n);if(r.languages.length===0){console.log(`
|
|
408
|
+
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
409
|
+
Detected languages: ${r.languages.join(", ")}`),console.log(`
|
|
410
|
+
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=Zg(r);i.length>0&&console.log(`
|
|
411
|
+
Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${YP(o)}${eh(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function Mg(e){Fg(e,"capabilities")}function Ng(e){S(Y(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),Fg(e,"capability-matrix")}function Fg(e,t){let n=Y(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Xe(),a=$e(r,i),c=Ae(r,i,o),l=ut(a,{hasIndexedGraph:se(s)&&c.state!=="missing"});if(S(n,"json")){A(t,[],n,l);return}Ds(l)}function _g(){let e=te(),t=vt(e),n=Fl(e,t);console.log(n.changed?`Config written to ${n.configPath}`:`Config already exists at ${n.configPath}; existing contents left unchanged.`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Bg(e){let t=Y(e),n=te(),r=ke(n),i=_t(r,{projectRoot:n});if(S(t,"json"))A("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 qg(e,t){let n=Y(t),r=C(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let i=C(n,"reasonCode"),o=Rt(n,"evidence");if(!i||o.length===0){console.error("error: suppress requires --reason-code <code> and at least one --evidence <source|config|test|graph>:<referent> so automatic adjudication has inspectable counterevidence."),process.exitCode=1;return}try{let s=te(),a=(()=>{try{return de(()=>Gd())}catch{return}})(),c={id:String(e),check:C(n,"check"),file:C(n,"file"),reason:r,expiresAt:C(n,"expiresAt"),decision:pg(s,i,o,r,a)},l=mg(s,c,{expectedRevision:C(n,"replace")});if(S(n,"json")){A("suppress",[String(e)],n,l);return}for(let d of ug(l,c))console.log(d)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}function Vg(e){let t=Y(e),n=Date.now(),r=C(t,"since"),i;if(r){let y=Il(r,n);if(y===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=y}let o=te(),s=Er(o),a=El(s.events,{sinceMs:i,check:C(t,"check")}),c=ct("Committed outcome history",s.compatibility);if(S(t,"json")){A("effectiveness",[],t,{...a,recordCompatibility:{outcomeEvents:s.compatibility}});return}if(c&&console.log(`WARN: ${c}`),a.checks.length===0){console.log(s.events.length===0?`No outcome events recorded yet (${Tt(Sn,"*.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 l=["check","caught","fixed","suppressed","open","moved","unverified","resolution-vs-suppression","evaluation-precision","authority","median-days-to-fix"],d=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.resolutionVsSuppressionRate===null?"-":`${Math.round(y.resolutionVsSuppressionRate*100)}%`,y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.authority,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),u=l.map((y,R)=>Math.max(y.length,...d.map($=>$[R].length))),m=y=>y.map((R,$)=>R.padEnd(u[$])).join(" ");console.log(m(l));for(let y of d)console.log(m(y));let f=a.checks.reduce((y,R)=>y+R.fixed,0),g=a.checks.reduce((y,R)=>y+R.suppressed,0),h=a.checks.reduce((y,R)=>y+R.unverified,0),b=f+g;if(b>0){let y=Math.round(f/b*100);console.log(a.authority==="protected-external-evaluation"?`
|
|
412
|
+
Protected external evaluation: ${f} finding(s) verified fixed, ${g} suppressed, ${h} unverified \u2014 precision ${y}%.`:`
|
|
413
|
+
Repository-writable telemetry: ${f} finding(s) verified fixed, ${g} suppressed, ${h} unverified \u2014 resolution-vs-suppression ${y}%. This is operational handling data, not an independent correctness grade.`)}else h>0&&console.log(`
|
|
414
|
+
${h} finding(s) disappeared without comparable comparison-base evidence; no correctness metric is available.`);for(let y of a.anomalies){let R=y.samples.map($=>`${$.check}:${$.findingId}`).join(", ");console.log(`WARN: ${y.message}${R?` Samples: ${R}.`:""}`)}}function Wg(e){let t=Y(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Hg("doctor");S(t,"json")?A("doctor",[],t,n):UP(n,r),process.exitCode=i?1:0}function Hg(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Xe(),o=_t(n,{projectRoot:t}),s=$e(t,n),a=Ae(t,n,r),c=se(i),l=ut(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Ad(t,n,r),u=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||u||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||u||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:d,ok:!m},hasIndexerProblems:u,hasErrors:f}}function Gg(e){let t=Y(e),n=te(),r=Lr(n,{gitHook:S(t,"gitHook")});for(let o of r.written)console.log(` done: ${o}`);for(let o of r.unchanged)console.log(` ok: ${o} (already wired)`);for(let o of r.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);let i=Tu(r);i.verdict==="ready"?console.log(`
|
|
415
|
+
Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
|
|
416
|
+
Project agent guidance is only partially configured: ${i.ready} target(s) ready, ${i.skipped} skipped. Resolve the skips before relying on every agent integration.`):console.log(`
|
|
417
|
+
Project agent guidance was not configured: all ${i.skipped} selected target(s) were skipped.`),i.ready>0&&console.log("Configured agents are instructed to check freshness once per work session, reuse a fresh generation, wait for an active watcher after edits, and reindex only when stale and no watcher can refresh it."),process.exitCode=i.verdict==="ready"?0:1}async function Ug(e){let t=Y(e);try{let n=S(t,"guided"),r=S(t,"yes"),i=S(t,"json");_f({guided:n,yes:r,json:i,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let o=S(t,"installMissing"),s={gitHook:S(t,"gitHook"),noHooks:S(t,"noHooks")||t.hooks===!1,dossierDir:C(t,"dossierDir"),runHealth:r?!1:t.health!==!1,installSkills:t.skills!==!1,installIndexers:o,installAstParsers:o&&t.parsers!==!1,...r?{automaticRefresh:!0}:{}},a=!i&&!r&&process.stdin.isTTY&&process.stdout.isTTY;(n||a)&&(s=await qP(s,{json:i})),i||(s.onStatus=l=>console.log(` ${l}`));let c=await qf(s);i?A("setup",[],t,c):Vf(c),process.exitCode=c.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function qP(e,t){let{projectRoot:n,config:r}=Xe(),i=$e(n,r),o=Bf({files:VP(n),watchEnabled:Ie(r).enabled,readiness:i}),s=i.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=$s(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,d=l?await Wf([...s,...a]):new Set([...WP(o.actions),...s.map(g=>g.id)]);l&&HP(o.actions,d);let u=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(g=>g.id==="enable-automatic-refresh"),f=o.actions.some(g=>g.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(g=>g.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!u,...f?{installIndexers:l?d.has("install-indexers"):e.installIndexers===!0}:{},languages:i.languages.filter(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:l?d.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:d.has("run-health-analysis")}}function VP(e){return{agentsMd:se(Tt(e,"AGENTS.md")),claudeMd:se(Tt(e,"CLAUDE.md")),codexHooks:se(Tt(e,".codex","hooks.json")),claudeSettings:se(Tt(e,".claude","settings.local.json"))}}function WP(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function HP(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 Jg(e){let t=Y(e),n=te(),r=Uf(n,{force:S(t,"force"),dryRun:S(t,"dryRun")});if(S(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 Kg(e){let t=Y(e),n=Es({global:S(t,"global"),project:S(t,"project"),dryRun:S(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let r=Kf({projectRoot:te(),global:n.global,project:n.project,dryRun:S(t,"dryRun")});if(S(t,"json")){A("uninstall",[],t,r);return}for(let i of Jf(r,{verbose:S(t,"verbose")}))console.log(i)}function zg(e){let t=Y(e),n=te(),r=ke(n),i=X(t,"debounce"),o=X(t,"cooldown"),s=X(t,"gitPoll"),a=X(t,"idleTimeout"),c=S(t,"daemon"),l=S(t,"status"),d=S(t,"stop"),u=S(t,"json"),m=[c,l,d].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(u&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let g=[["--debounce",i],["--cooldown",o],["--git-poll",s],["--idle-timeout",a]].filter(([,x])=>x!==void 0);if((l||d)&&g.length>0){console.error(`error: timing options (${g.map(([x])=>x).join(", ")}) only apply when starting a foreground or daemon watcher; --status and --stop do not accept them.`),process.exitCode=1;return}let h=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,x,j])=>x!==void 0&&(!Number.isInteger(x)||(j?Number(x)<0:Number(x)<=0)));if(h){console.error(`error: ${h[0]} requires ${h[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let b={...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 y=Ie(r);r.watch=y;let R=ze(n,r),$={projectRoot:n,cacheDir:R.cacheDir,cliVersion:be,watchOverrides:b};if(l){let x=Qg(kr($),y.enabled);u?A("watch",[],t,x):Yg(x);return}if(d){try{let x=Pd($);u?A("watch",[],t,x):console.log(x.disposition==="stopped"?`Stopped watch service${x.pid?` (pid ${x.pid})`:""}.`:"Watch service is already stopped.")}catch(x){console.error(`error: ${x instanceof Error?x.message:String(x)}`),process.exitCode=1}return}if(!y.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{if(g.length>0){let j=kr($);if(j.classification.kind==="live")throw new Error(`watch service pid ${j.classification.state.pid} is already running. Timing options only apply when the process starts; run "scip-query watch --stop", then repeat this daemon command.`)}let x=wr($);u?A("watch",[],t,x):(console.log(`${x.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${x.state.pid}).`),g.length>0&&console.log(`Process-local timing overrides: ${g.map(([j,_])=>`${j}=${_}`).join(", ")}. These were not written to .scipquery.json.`))}catch(x){console.error(`error: ${x instanceof Error?x.message:String(x)}`),process.exitCode=1}return}let v=Ed(Tt(bi(R.dbPath),Fa),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let E=new ui({projectRoot:n,config:r,languages:r.languages,onStatus:x=>{process.stdout.write(`\r\x1B[K${ro(no(x))}`)},onReindexComplete:x=>(console.log(`
|
|
418
|
+
Reindex complete in ${(x/1e3).toFixed(1)}s`),Ae(n,r,R).state==="fresh"),onRefreshSuppressed:x=>{let j=Zp(R.dbPath,x);j.state==="failed"&&console.error(`
|
|
419
|
+
Watch warning: suppressed-refresh telemetry was not recorded: ${j.reason}`),console.log(`
|
|
420
|
+
Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:x=>{console.error(`
|
|
421
|
+
Watch error: ${x.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${y.debounceMs}ms | Cooldown: ${y.cooldownMs}ms | Git poll: ${y.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
|
|
422
|
+
`),E.start();let L=!1,Q=()=>{L||(L=!0,E.stop().then(x=>{if(x.state==="degraded"){L=!1,console.error(`
|
|
423
|
+
Unable to stop safely: ${x.reasons.join("; ")}`);return}v.release(),console.log(`
|
|
424
|
+
Stopped.`),process.exit(0)}))};process.on("SIGINT",Q),process.on("SIGTERM",Q)}function Qg(e,t=!0){let{classification:n}=e,r=$d(e.paths.refreshRequestsPath);switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt,refreshRequests:r}:{enabled:t,state:"stopped",mode:"none",refreshRequests:r};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return GP(n)}}function Yg(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),hg(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${no(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"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}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${je(n.estimatedLogicalOutputBytes)} estimated logical output${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),n.confidence&&n.confidence!=="complete"&&console.log(`Reindex evidence: ${n.recordsRead??0} record(s) read, ${n.invalidRecords??0} invalid, ${n.readErrors??0} read error(s), ${n.ignoredPartialTailBytes??0} incomplete byte(s) ignored`)}if("refreshRequests"in e&&e.refreshRequests&&hg(e.refreshRequests),"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 hg(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function GP(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Xg(e){let t=Y(e),{report:n}=Hg("status"),r=Ie(ke(n.projectRoot)).enabled,i=Qg(kr({projectRoot:n.projectRoot,cacheDir:bi(n.configuredDbPath),cliVersion:be}),r),o=Mp(n.dbPath),s=Ye(n.dbPath,n.freshness.metaPath),a=Hl(n.dbPath),c=sr(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(S(t,"json")){A("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:i,stats:js(n.exists)});return}JP(n,{affectedSetShadow:o,capabilities:S(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:i})}function UP(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})`:""}`),Ds(e.capabilities)}function JP(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 Zg(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}${eh(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: ${XP(e.freshness.lastRefresh)}`),Yg(t.watchService),KP(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"),zP(t.sqliteGeneration),QP(t.localGenerations),console.log(`Shadow: ${Np(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),ZP(e.exists),t.capabilities&&(console.log(""),Ds(e.capabilities))}function KP(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), ${je(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${je(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), ${je(e.cleanup.deletedBytes??0)} removed`)}function zP(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})`),console.log(`DB layout: ${e.generation.artifactSet==="immutable-v1"?"immutable artifact set; stable paths are mirrors":"legacy stable paths"}`),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 QP(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${je(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${je(e.limits.maxLogicalBytes)}`),e.oldestGenerationAt&&console.log(`Local age: oldest generation ${e.oldestGenerationAt}`),e.lastCollection&&console.log(`Local last: ${e.lastCollection.state} at ${e.lastCollection.at}, ${e.lastCollection.removedGenerations} removed`),e.reason&&console.log(`Local why: ${e.reason}`))}function Zg(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function YP(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function eh(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function XP(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 js(e){if(e)return de(t=>{let n=Ft(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function ZP(e){e&&de(t=>{let n=Ft(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${je(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function Ds(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(`
|
|
425
|
+
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 _n(e){return{...e,options:T(e.options)}}function st({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=_n(l);return{...d,renderShape:"list",handler:hd({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c})}}function Si({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...u}){let m=_n(u);return{...m,renderShape:"table",handler:yd({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function th({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l,...d}){let u=_n(d);return{...u,renderShape:"grouped-by-file",handler:bd({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l})}}function nh({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=_n(l);return{...d,renderShape:"sectioned-report",handler:Sd({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}function vi({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=_n(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:vd(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}import{existsSync as AT,mkdirSync as jT,writeFileSync as OT}from"fs";import{dirname as LT,relative as DT}from"path";import{existsSync as at,readdirSync as oT}from"fs";import{basename as sT,dirname as lh,isAbsolute as dh,join as aT,relative as cT,resolve as Bn,sep as lT}from"path";import{spawnSync as tT}from"child_process";import{dirname as nT}from"path";function ih(e){let n=(e.spawnSync??tT)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:nT(e.specPath),maxBuffer:1024*1024*32,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function oh(e){let t=iT(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=sh(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 rT=8;function iT(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=Ms(s,"uniquename"),c=Ms(s,"kind"),l=Ms(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:rh(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:rh(l),block:s})}return t}function sh(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,u,m]of l){if(u==="BuiltInKindRef"){let f=n.get(m)??"";f==="'"?d="write-next":f==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&f==="$Tuple"||d!=="write-next"&&(d="read");continue}if(u==="OpDeclNodeRef"){let f=t.get(m);if(!f)continue;d==="write-next"?(c.add(f),d="read"):d==="unchanged-run"||a.add(f);continue}if(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<rT&&!o.has(f.uid)&&f.filename===i){let g=sh(f.block,t,n,r,i,new Set([...o,f.uid]),s+1);for(let h of g.reads)a.add(h);for(let h of g.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function Ms(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function rh(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var uh=["update","insert","delete"],ph=["select","query","findFirst","findMany"],Ns=new Set([...uh,...ph]);function Fs(e){let t=e.methods&&e.methods.length>0?e.methods:[...Ns],n=new Set(uh),r=new Set(ph);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var dT=/^(.*)@L(\d+)-L(\d+)$/;function _s(e){let t=e.match(dT);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 uT=new Set(["auto","sany","tlc","apalache","none"]),xi=/^[A-Za-z_][A-Za-z0-9_]*$/;function mh(e){return uT.has(e)}function ki(e,t){let n=[],r=ve(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!at(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(G(r,{inputKind:"TLA mapping",maxBytes:Re}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=pT(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:lh(r)},errors:n}:{errors:n}}function ve(e,t){if(!t)return null;let n=dh(t)?Bn(t):Bn(e,t);return ce(e,n)?n:null}function fh(e,t,n){if(!n)return null;if(dh(n)){let s=Bn(n);return ce(e,s)?s:null}let r=Bn(e,n);if(ce(e,r)&&at(r))return r;let i=Bn(t,n);if(ce(e,i)&&at(i))return i;let o=ce(e,r)?r:i;return ce(e,o)?o:null}function gh(e,t){let n=ve(e,t);if(!n||!at(n))return null;let r=G(n,{inputKind:"TLA module",maxBytes:xe});return{path:n,modelParse:"regex-fallback",text:r,variables:CT(r),operators:PT(r),actions:[]}}function hh(e,t,n){let r=ve(e,t);if(!r||!at(r))return null;let i=G(r,{inputKind:"TLA module",maxBytes:xe}),o=oh(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function Bs(e,t){let n=ve(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!at(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(G(n,{inputKind:"TLA trace",maxBytes:xe})),i=Array.isArray(r)?r:J(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(!J(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:J(c.before)?c.before:void 0,after:J(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 qs(e,t){let n=new Set,r=[];for(let i of t){let o=ve(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function pT(e,t){if(!J(e))return t.push("map file must contain a JSON object"),null;let n=bT(e.variables,t);yT(n,t);let r=wT(e.actions,n,t),i=mT(e.init,t);gT(i,r,t);let o={module:ch(e.module,"module",t),config:ch(e.config,"config",t),scope:Z(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:Z(e.invariants)??[],traces:Z(e.traces)??[],unmappedWriteScope:hT(e.unmappedWriteScope,t)};return ET(e.scope,t),t.length===0?o:null}function mT(e,t){if(e===void 0)return;if(!J(e)){t.push("init must be an object when present");return}let n=Z(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=fT(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function fT(e,t){if(e===void 0)return;if(!J(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 gT(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 hT(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 yT(e,t){Ri(e,t,"alias",n=>n.aliases),Ri(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Ri(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Ri(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=Fs(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Ri(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 bT(e,t){if(!J(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(!xi.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!J(i)){t.push(`variables.${r} must be an object`);continue}let o=bh(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=Z(i.aliases)??[],a=vT(i.resource,r,t),c=RT(i.statements,r,t),l=xT(i.ormCalls,r,t),d=kT(i.waive,r,t),u=ST(i.selfAlias,r,t),m=u?[...new Set([r,...s])]:[...new Set(s)];u===!1&&m.length===0&&!a&&!c&&!l&&!d&&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:m,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...u===!1?{selfAlias:!1}:{}}}return n}function ST(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 vT(e,t,n){if(e===void 0)return;if(!J(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 RT(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(!J(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{Un(s,`variables.${t}.statements[${o}].pattern`)}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 xT(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(!J(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=Z(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=>!Ns.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...Ns].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function kT(e,t,n){if(e===void 0)return;if(!J(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 wT(e,t,n){if(!J(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(!xi.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!J(s)){n.push(`actions.${o} must be an object`);continue}let a=bh(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let m of a){let f=_s(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=Z(s.reads)??[],l=Z(s.writes)??[],d=Z(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let u=$T(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}return i}function $T(e,t,n,r,i,o,s){if(J(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=Z(e.reads)??[],l=Z(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),ah(o,"reads",c,i,s),ah(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 ah(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function CT(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();xi.test(o)&&t.add(o)}}return[...t].sort()}function PT(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 TT=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function yh(e){if(!e||!at(e))return[];let t=G(e,{inputKind:"TLA checker configuration",maxBytes:Re}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(TT.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&xi.test(i)&&n.add(i)}return[...n].sort()}function ch(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function bh(e){return typeof e=="string"?[e]:Z(e)}function ET(e,t){e!==void 0&&(Z(e)||t.push("scope must be an array of strings when present"))}function wi(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var IT=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Sh(e,t){if(!at(t))return{status:"none"};let r=G(t,{inputKind:"TLA module",maxBytes:xe}).match(IT)?.[1],i=cT(e,t).split(lT).join("/"),o=sT(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=lh(t);if(!at(a))return{status:"none"};let c=[];for(let d of oT(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=aT(a,d),m;try{m=JSON.parse(G(u,{inputKind:"TLA mapping candidate",maxBytes:Re}))}catch{continue}J(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}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 $i(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 d=s.get(l.relativePath)??[];d.push(l),s.set(l.relativePath,d)}let a=[...s.entries()].map(([l,d])=>({file:l,bucket:d,totalLoc:d.reduce((u,m)=>u+m.loc,0)})).sort((l,d)=>d.totalLoc-l.totalLoc||l.file.localeCompare(d.file)),c=!0;for(let{file:l,bucket:d}of a){c||console.log(""),c=!1,console.log(` ${l}`),d.sort((u,m)=>u.startLine-m.startLine);for(let u of d){let m=u.implicitUsageReason?` [implicit usage: ${u.implicitUsageReason}]`:"";console.log(` ${fe(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var Vs=20,vh=ne("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:K(t,0)||void 0,minLoc:I(n,"minLoc",1),includeTests:S(n,"includeTests"),skipBarrels:S(n,"skipBarrels"),includeMembers:S(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=oc(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=!S(n,"onlyInternal"),d=!S(n,"onlyDead"),u=!S(n,"onlyDead")&&!S(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=u?c:[],h=m.reduce((F,H)=>F+H.loc,0),b=f.reduce((F,H)=>F+H.loc,0),y=g.reduce((F,H)=>F+H.loc,0),R=S(n,"full"),$=R?m:m.slice(0,Vs),v=R?f:f.slice(0,Vs),E=R?g:g.slice(0,Vs),L=$.reduce((F,H)=>F+H.loc,0),Q=v.reduce((F,H)=>F+H.loc,0),x=E.reduce((F,H)=>F+H.loc,0),j={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+b+y};if(S(n,"json")){A("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:j,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(m.length===0&&f.length===0&&g.length===0){O.empty("No matching dead-code symbols found.");return}m.length>0&&($i($,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
426
|
+
Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,L,{count:m.length,loc:h}),!R&&m.length>$.length&&console.log(`
|
|
427
|
+
Showing top ${$.length} by LOC. Re-run with --full for the remaining ${m.length-$.length}.`)),f.length>0&&(m.length>0&&console.log(""),$i(v,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
428
|
+
single-use helper, an abstraction-in-progress, or a callback registered
|
|
429
|
+
through a framework path that static analysis cannot trace (signal
|
|
430
|
+
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
431
|
+
review case by case.`,Q,{count:f.length,loc:b}),!R&&f.length>v.length&&console.log(`
|
|
432
|
+
Showing top ${v.length} by LOC. Re-run with --full for the remaining ${f.length-v.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),$i(E,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
|
|
433
|
+
consumer that the static reference graph cannot trace. Investigation
|
|
434
|
+
signals only \u2014 not deletion candidates and not counted as dead code.`,x,{count:g.length,loc:y}),!R&&g.length>E.length&&console.log(`
|
|
435
|
+
Showing top ${E.length} by LOC. Re-run with --full for the remaining ${g.length-E.length}.`));let _=[];l&&_.push(`${m.length} dead code (${h} LOC)`),d&&_.push(`${f.length} file-internal (${b} LOC)`),u&&_.push(`${g.length} implicit usage (${y} LOC)`),console.log(`
|
|
436
|
+
\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: ${m.length+f.length+g.length} symbols \u2014 ${_.join(" + ")}`)}),Rh=Se("unused-imports",{query:({db:e,args:t,budget:n})=>lc(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
437
|
+
${e.length} unused import(s)`)}),xh=Rd("isolated",{query:({db:e,opts:t,budget:n})=>vc(e,{scope:C(t,"scope"),minLoc:I(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${fe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
|
|
438
|
+
${e.length} isolated symbol(s)`)}),kh=ne("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Mc(e,{scope:C(n,"scope"),minLoc:I(n,"minLoc",10),minCallees:I(n,"minCallees",6),limit:N(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(S(n,"json")){A("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return O.empty("No extraction candidates found.");Ve("extraction candidates");for(let o of i){console.log(`
|
|
439
|
+
${U(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(`
|
|
440
|
+
${i.length} extraction candidate(s) found.`)}),wh=ne("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Nc(e,{target:K(t,0)||void 0,scope:C(n,"scope"),minConsumers:I(n,"minConsumers",1),limit:N(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(S(n,"json")){A("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return O.empty("No locality candidates found.");Ve("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?U(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
|
|
441
|
+
${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(`
|
|
442
|
+
${i.length} locality candidate(s) found.`)}),$h=Se("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>zc(e,{scope:C(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:N(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${U(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
443
|
+
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
444
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
445
|
+
${e.length} wrapper candidate(s).`)}),Ch=Se("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Jc(e,{scope:C(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:N(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${U(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
446
|
+
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
447
|
+
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
448
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
449
|
+
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
450
|
+
${e.length} passthrough candidate(s).`)}),Ph=Se("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Kc(e,{scope:C(t,"scope"),minLoc:I(t,"minLoc",3),limit:N(t,"limit",30),includeLowConfidence:S(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}] ${U(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
451
|
+
${e.reason}
|
|
452
|
+
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
453
|
+
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
454
|
+
${e.length} stale abstraction(s).`)}),Th=xr("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Rl(e,{scope:C(t,"scope"),minLoc:I(t,"minLoc",10),limit:N(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]}),Eh=Oe("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(S(n,"plan")){let o=K(t,0),s=K(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Cc(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=K(t,0);return i?{mode:"target",rows:$c(e,i,{minSimilarity:I(n,"minSimilarity",.4),limit:N(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Pc(e,{minSimilarity:I(n,"minSimilarity",.4),limit:N(n,"limit",20),scope:C(n,"scope"),minCallees:I(n,"minCallees",4),crossFileOnly:S(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(`
|
|
455
|
+
${Math.round(t.similarity*100)}% ${n}
|
|
456
|
+
`),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}
|
|
457
|
+
`),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
|
|
458
|
+
Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
|
|
459
|
+
Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
|
|
460
|
+
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=[`
|
|
461
|
+
${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(`
|
|
462
|
+
`)});return}O.list(e.rows,t=>`
|
|
463
|
+
${Math.round(t.similarity*100)}% similar:
|
|
464
|
+
A: ${t.shortNameA} (${t.fileA})
|
|
465
|
+
B: ${t.shortNameB} (${t.fileB})
|
|
466
|
+
Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
|
|
467
|
+
Recommendation: ${t.recommendation}
|
|
468
|
+
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
469
|
+
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
470
|
+
${e.rows.length} similar pair(s) found.`)}}),Ih=dt({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Tc(e,{minSimilarity:I(n,"minSimilarity",.5),limit:N(n,"limit",20),scope:C(n,"scope"),minDeps:X(n,"minDeps"),filePattern:K(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=[`
|
|
471
|
+
${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(`
|
|
472
|
+
`)}),console.log(`
|
|
473
|
+
${e.length} similar pair(s) found.`)}}),Ah=dt({commandName:"similar-chains",query:({db:e,opts:t})=>Dc(e,{minSimilarity:I(t,"minSimilarity",.5),limit:N(t,"limit",15),scope:C(t,"scope"),minChainLength:I(t,"minLength",3),maxChainLength:I(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(`
|
|
474
|
+
\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(`
|
|
475
|
+
${e.length} similar chain pair(s) found.`)}}),jh=Oe("drift",{query:({db:e,args:t,opts:n,budget:r})=>Uc(e,{scope:K(t,0),minDeviation:I(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:S(n,"patterns"),includeArchitecture:S(n,"architecture"),limit:N(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),O.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"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(`
|
|
476
|
+
`)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(r=>r.policyStatus==="undeclared").length;if(console.log(`
|
|
477
|
+
Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let r of t.reciprocalPairs)console.log(` ${r.boundaries[0]} <-> ${r.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let r of t.cycles){let i=r.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${r.boundaries.join(", ")} }${i}`)}}}console.log(`
|
|
478
|
+
${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),Oh=Oe("convergence",{query:({db:e,args:t,budget:n})=>Al(e,M(t,0),M(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(`
|
|
479
|
+
${Math.round(e.similarity*100)}% callee overlap
|
|
480
|
+
`),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)
|
|
481
|
+
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
482
|
+
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
483
|
+
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
484
|
+
Strategy: ${e.consolidationStrategy}`)}}}),Lh=Se("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ll(e,{scope:C(t,"scope"),minLoc:I(t,"minLoc",3),maxShapeFrequency:I(t,"maxShapeFrequency",12),limit:N(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
|
|
485
|
+
Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${U(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
486
|
+
`);return`${n}
|
|
487
|
+
${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
488
|
+
${e.length} group(s) found.`)}),Dh=Se("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>Hc(e,{scope:C(t,"scope"),maxLoc:I(t,"maxLoc",15),minLoc:I(t,"minLoc",3),limit:N(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
489
|
+
Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${U(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
|
|
490
|
+
`);return`${t}
|
|
491
|
+
${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
|
|
492
|
+
${e.length} group(s) found.`)}),Mh=Se("twin-drift",{query:({db:e,opts:t,budget:n})=>Gc(e,{scope:C(t,"scope"),minSimilarity:I(t,"minSimilarity",.3),includeHomonyms:S(t,"includeHomonyms"),limit:N(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
493
|
+
${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${U(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
494
|
+
`),r=e.firstDivergentTokens?`
|
|
495
|
+
first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
|
|
496
|
+
${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
|
|
497
|
+
${e.length} group(s) found.`)}),Nh=Se("not-implemented",{query:({db:e,opts:t,budget:n})=>ml(e,{scope:C(t,"scope"),limit:N(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${U(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
|
|
498
|
+
${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
|
|
499
|
+
${e.length} reachable placeholder stub(s).`)}),Fh=Se("decorative-checkers",{query:({db:e,opts:t,budget:n})=>fl(e,{scope:C(t,"scope"),limit:N(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${U(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(`
|
|
500
|
+
${e.length} decorative checker candidate(s).`)}),_h=ne("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=gl(e,{scope:C(n,"scope"),limit:N(n,"limit",30),scanLimit:r.scanLimit,rotDays:X(n,"rotDays")});if(S(n,"json")){A("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Ve("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(`
|
|
501
|
+
ASSERTION-FREE (${i.assertionFree.length})`),O.list(i.assertionFree,s=>` ${U(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
|
|
502
|
+
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(`
|
|
503
|
+
MOCK-ECHO (${i.mockEcho.length})`),O.list(i.mockEcho,s=>` ${U(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
|
|
504
|
+
${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),Bh=dt({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=M(t,0),i=M(t,1),o=C(n,"out")??ul(r,i),s=ve(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=pl(e,{refA:r,refB:i,outFile:s});if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=DT(e.config.projectRoot,s);if(!S(n,"force")&&AT(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return jT(LT(s),{recursive:!0}),OT(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
|
|
505
|
+
Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${U(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${U(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(`
|
|
506
|
+
Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),qh=ne("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Ki(e,{scope:C(n,"scope"),minLoc:I(n,"minLoc",1),maxDepth:I(n,"maxDepth",5),scanLimit:r.scanLimit}),o=te(),s=S(n,"patch"),a=S(n,"json"),c=S(n,"verify")||s;if(s&&!S(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){A("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=So(i),d=c?go(o,i):void 0;if(a){A("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=vo(d,l);if(u.length>0){for(let f of u)console.error(`error: ${f}`);process.exitCode=1;return}let m=bu(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(m);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.
|
|
507
|
+
`);for(let u of i.batches){let m=u.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${u.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${u.depth}: dead once batch ${u.depth-1} lands (cascade, ${u.loc} LOC) \u2500\u2500`;console.log(m);for(let f of u.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);u.filesEmptied.length>0&&console.log(` -> empties: ${u.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of i.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
|
|
508
|
+
Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.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 f of d.checkers)console.log(` Checker: ${f}`);if(d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.workingTree.state==="unavailable"&&console.log(` WARNING: working-tree inspection unavailable: ${d.workingTree.reason}`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`),d.dirtyWorkingTree.length>0){let f=d.dirtyWorkingTree.slice(0,5),g=d.dirtyWorkingTree.length-f.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${f.join(", ")}${g>0?`, ... ${g} more`:""}`)}let u=MT(d.checkers),m=NT(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${u})${m}`);else{console.log(` Batch ${f.depth}: FAILED${f.reason?` (${f.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let g of f.errors??[])console.log(` ${g}`)}}}),Vh=ne("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!S(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=S(t,"all"),i=X(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Ki(e,{scope:C(t,"scope"),minLoc:I(t,"minLoc",1),maxDepth:I(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=So(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=te(),c=go(a,o),l=vo(c,s,{allowDirty:S(t,"forceDirty")});if(l.length>0){for(let f of l)console.error(`error: ${f}`);process.exitCode=1;return}let d=S(t,"dryRun"),u=yo(s,{dryRun:d});console.log(`${d?"Cleanup preview":"Applying cleanup"}: ${u.batches} verified batch(es), ${u.symbols} symbol(s), ${u.loc} LOC across ${u.files.length} file(s).`),console.log(` verifier: ${c.checkers.join(", ")}`);for(let f of u.targets)console.log(` batch ${f.batch} ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.symbol} (${f.loc} LOC)`);u.filesEmptied.length>0&&console.log(` files emptied: ${u.filesEmptied.join(", ")}`);let m=bo(a,s,{dryRun:d});if(m.dryRun){console.log("Preview complete: verification passed and no working-tree files were changed.");return}console.log(`Applied ${m.batches} verified cleanup batch(es): ${m.symbols} symbol(s), ${m.loc} LOC.`)});function MT(e){return e.join(", ")}function NT(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var Wh=ne("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=S(n,"full"),o=hl(e,{windowCommits:I(n,"window",100),minSimilarity:X(n,"minSimilarity"),limit:N(n,"limit",30),scope:C(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(S(n,"json")){A("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).`);Ve("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
|
|
509
|
+
`);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(`
|
|
510
|
+
${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Hh=ue(({db:e,args:t,opts:n})=>{let r=S(n,"full"),i=Wc(e,{doc:t[0]===void 0?void 0:M(t,0),limit:N(n,"limit",20),minCoupling:I(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(S(n,"json")){A("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.`);Ve("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
|
|
511
|
+
`);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 d=c.docIntentReasons[0];d&&console.log(` intent: ${d}`);let u=c.citationContexts?.[0];u&&console.log(` cited claim: ${Sr(u)}`)}}console.log(`
|
|
512
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Gh=Se("unused-params",{query:({db:e,opts:t,budget:n})=>Zc(e,{scope:C(t,"scope"),limit:N(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${U(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
513
|
+
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(`
|
|
514
|
+
${e.length} function(s) with trailing unused parameters.`)});var Uh=Oe("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Ec(e,{minSimilarity:I(n,"minSimilarity",.62),minTokens:I(n,"minTokens",8),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=[`
|
|
515
|
+
${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(`
|
|
516
|
+
`)}),console.log(`
|
|
517
|
+
${e.length} duplicated React component pair(s) found.`)}}),Jh=Oe("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Ic(e,{minSimilarity:I(n,"minSimilarity",.45),minSharedBehaviors:I(n,"minSharedBehaviors",6),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=[`
|
|
518
|
+
${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(`
|
|
519
|
+
`)}),console.log(`
|
|
520
|
+
${e.length} React hook candidate pair(s) found.`)}}),Kh=Oe("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ac(e,{minComponentLines:I(n,"minComponentLines",300),minFileLines:I(n,"minFileLines",800),minJsxTokens:I(n,"minJsxTokens",80),minBehaviorTokens:I(n,"minBehaviorTokens",40),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=>[`
|
|
521
|
+
${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(`
|
|
522
|
+
`)),console.log(`
|
|
523
|
+
${e.length} large React component(s) found.`)}}),zh=Oe("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>jc(e,{minSimilarity:I(n,"minSimilarity",.62),minTokens:I(n,"minTokens",8),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=[`
|
|
524
|
+
${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(`
|
|
525
|
+
`)}),console.log(`
|
|
526
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),Qh=Oe("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Oc(e,{minSimilarity:I(n,"minSimilarity",.45),minSharedBehaviors:I(n,"minSharedBehaviors",6),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=[`
|
|
527
|
+
${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(`
|
|
528
|
+
`)}),console.log(`
|
|
529
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),Yh=Oe("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Lc(e,{minTotalLines:S(n,"reviewThresholds")&&xd(n,"minTotalLines")==="default"?300:I(n,"minTotalLines",800),minTemplateLines:I(n,"minTemplateLines",300),minScriptLines:I(n,"minScriptLines",300),minStyleLines:I(n,"minStyleLines",500),limit:N(n,"limit",20),scope:C(n,"scope"),scanLimit:r.scanLimit,filePattern:K(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=[`
|
|
530
|
+
${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(`
|
|
531
|
+
`)}),console.log(`
|
|
532
|
+
${e.length} large Vue view pressure file(s) found.`)}});function pe(e){return{docs:P("Cleanup"),...e}}function ie({heuristicLabel:e,...t}){return pe({...t,heuristic:{label:e}})}var Ci=[pe({id:"unused-params",command:"unused-params",agent:w("Which trailing parameters are never read by their bodies?","candidate parameters with callable and file identities",[],"bounded","repository"),description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",k,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:P("Cleanup",["scip-query unused-params -s src/services"]),handler:Gh}),pe({id:"cleanup-plan",command:"cleanup-plan",agent:w("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository"),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",k,1),p("--max-depth <n>","Maximum cascade depth",k,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:qh}),pe({id:"cleanup-apply",command:"cleanup-apply",agent:w("Can a compiler-verified cleanup batch be applied to this working tree?","applied files, deletions, verification, and refusal reasons",[],"bounded","repository"),description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",k,1),p("--max-depth <n>","Maximum cascade depth",k,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",k),p("--all","Apply every compiler-verified batch in the plan"),p("--dry-run","Verify and print exact deletion targets without changing working-tree files"),p("--force-dirty","Allow deleting ranges from files with uncommitted edits; those edits can be lost, so preview first"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query cleanup-apply --verified --batch 0 --dry-run","scip-query cleanup-apply --verified --batch 0"]),handler:Vh}),pe({id:"recent-duplicates",command:"recent-duplicates",agent:w("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:T([p("--window <n>",'How many commits back counts as "recent"',k,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",we),p("-n, --limit <n>","Maximum findings",k,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:P("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Wh}),pe({id:"doc-drift",command:"doc-drift [doc]",agent:w("Which documentation may be stale relative to changing code?","document paths, coupled code subjects, and history evidence",["path"],"bounded","repository"),description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:T([p("-n, --limit <n>","Maximum docs to report",k,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",k,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:P("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Hh}),pe({id:"dead",command:"dead [scope]",agent:w("Which symbols have no repository use or only file-internal use?","symbol identities, ranges, liveness classes, and evidence",["path"],"bounded","repository"),description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:T([p("--min-loc <n>","Only show symbols >= N lines",k,1),p("--include-tests","Include definitions from test files (test references always count)"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),p("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query dead --min-loc 10"]),handler:vh}),pe({id:"unused-imports",command:"unused-imports <file>",agent:w("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Rh}),pe({id:"isolated",command:"isolated",agent:w("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",k,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:xh}),ie({id:"similar",command:"similar [symbol] [other]",agent:w("Which callable resembles this one, or how similar are these two?","symbol pairs, similarity scores, and shared evidence",["symbol","symbol"],"bounded","repository"),description:"Find heuristic function similarity candidates from callee fingerprints",options:T([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",we,.4),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",k,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--plan","Render a consolidation preview for two symbols"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Eh}),ie({id:"similar-files",command:"similar-files [file]",agent:w("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:T([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",we,.5),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",k),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Ih}),ie({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:w("Which React components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:T([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",we,.62),p("--min-tokens <n>","Minimum structural tokens to consider",k,8),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Uh}),ie({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:w("Which repeated React logic could become a custom hook?","component groups and shared hook-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:T([p("--min-similarity <n>","Minimum behavior similarity (0-1)",we,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",k,6),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Jh}),ie({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:w("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:T([p("--min-component-lines <n>","Minimum component lines",k,300),p("--min-file-lines <n>","Minimum file lines",k,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",k,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",k,40),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Kh}),ie({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:w("Which Vue components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:T([p("--min-similarity <n>","Minimum template similarity (0-1)",we,.62),p("--min-tokens <n>","Minimum structural tokens to consider",k,8),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:zh}),ie({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:w("Which repeated Vue logic could become a composable?","component groups and shared composable-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:T([p("--min-similarity <n>","Minimum behavior similarity (0-1)",we,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",k,6),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Qh}),ie({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:w("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:T([p("--min-total-lines <n>","Minimum total component lines",k,800),p("--min-template-lines <n>","Minimum template lines",k,300),p("--min-script-lines <n>","Minimum script lines",k,300),p("--min-style-lines <n>","Minimum style lines",k,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Yh}),ie({id:"similar-chains",command:"similar-chains",agent:w("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:T([p("--min-similarity <n>","Minimum chain similarity (0-1)",we,.5),p("-n, --limit <n>","Number of results",k,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",k,3),p("--max-length <n>","Maximum chain length",k,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Ah}),ie({id:"extract-candidates",command:"extract-candidates",agent:w("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",k,10),p("--min-callees <n>","Minimum callees to analyze",k,6),p("-n, --limit <n>","Number of results",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:kh}),ie({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:w("Which definitions live far from most of their consumers?","symbols, current homes, consumer locality, and suggested homes",[["symbol","file"]],"bounded","repository"),description:"Find directory-locality and ancestry candidates from consumer ownership",options:T([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",k,1),p("-n, --limit <n>","Number of results",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:wh}),ie({id:"drift",command:"drift [module]",agent:w("Where has a module or abstraction drifted across parallel implementations?","drifted symbol families, files, and evidence",["module"],"bounded","repository"),description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:T([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Ze,5),p("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),p("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),p("-n, --limit <n>","Number of results",k,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:jh}),ie({id:"wrapper-candidates",command:"wrapper-candidates",agent:w("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",k,15),p("-n, --limit <n>","Number of results",k,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:$h}),ie({id:"passthrough-candidates",command:"passthrough-candidates",agent:w("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",k,15),p("-n, --limit <n>","Number of results",k,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Ch}),ie({id:"stale-abstractions",command:"stale-abstractions",agent:w("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",k,3),p("-n, --limit <n>","Number of results",k,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Ph}),ie({id:"complexity-hotspots",command:"complexity-hotspots",agent:w("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",k,10),p("-n, --limit <n>","Number of results",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Th}),pe({id:"convergence",command:"convergence <symbol1> <symbol2>",agent:w("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Oh}),th({id:"redundant-reexports",command:"redundant-reexports",agent:w("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",k,30),p("--full","Run unbounded analysis on large indexes")],docs:P("Cleanup"),query:({db:e,opts:t})=>jl(e,{scope:C(t,"scope"),limit:N(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
533
|
+
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
534
|
+
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
535
|
+
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
536
|
+
${e.length} redundant re-export(s).`)}),pe({id:"duplicate-bodies",command:"duplicate-bodies",agent:w("Which callable bodies are exact duplicates?","callable groups with exact normalized-body identity",[],"bounded","repository"),description:"Find exact duplicate small-body candidates across files",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",k,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",k,3),p("-n, --limit <n>","Number of groups",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:Dh}),pe({id:"twin-drift",command:"twin-drift",agent:w("Which same-concept twin implementations have drifted?","twin symbol pairs, history, and divergence evidence",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",we,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:Mh}),ie({id:"not-implemented",command:"not-implemented",agent:w("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",k,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:P("Cleanup",["scip-query not-implemented -s src/services"]),handler:Nh}),ie({id:"decorative-checkers",command:"decorative-checkers",agent:w("Which validation checks cannot meaningfully fail?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",k,30),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:P("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:Fh}),pe({id:"test-quality",command:"test-quality",agent:w("Which tests have weak assertions or poor production-code reach?","test identities with assertion and reachability evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",k,30),p("--rot-days <n>","Skips older than this many days are reported as rot",k,60),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:P("Cleanup",["scip-query test-quality -s tests/queries"]),handler:_h}),pe({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:w("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete"),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-audit integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:T([p("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),p("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:P("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Bh}),pe({id:"similar-signatures",command:"similar-signatures",agent:w("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Find functions with near-identical type signatures (same shape)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",k,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",k,12),p("-n, --limit <n>","Number of groups",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Lh})];var FT=ue(({db:e,args:t,opts:n})=>{let r=Ft(e);if(S(n,"json")){A("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: ${je(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Xh=[{id:"stats",command:"stats",description:"Show index statistics",agent:w("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:T(),renderShape:"custom",docs:P("Core"),handler:FT}];var _T=xr("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Sc(e,{limit:N(t,"limit",20),scope:C(t,"scope"),minFanIn:I(t,"minFanIn",2),minFanOut:I(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."}),BT=ue(({db:e,args:t,opts:n})=>{let r=K(t,0),i=N(n,"limit",30);if(r){let c=uc(e,r);if(S(n,"json")){A("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=mc(e,{limit:i,scope:C(n,"scope")});if(S(n,"json")){A("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}]`:""}`))}),qT=ue(({db:e,args:t,opts:n})=>{let r=K(t,0),i=N(n,"limit",30);if(r){let s=pc(e,r);if(S(n,"json")){A("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=fc(e,{limit:i,scope:C(n,"scope")});if(S(n,"json")){A("fan-out",t,n,{mode:"top",rows:o});return}O.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),VT=ue(({db:e,args:t,opts:n})=>{let r=K(t,0),i=K(t,1),o=N(n,"limit",20);if(r&&i){let a=gc(e,r,i);if(S(n,"json")){A("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=hc(e,{limit:o,scope:C(n,"scope")});if(S(n,"json")){A("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}`))}),WT=dt({commandName:"cycles",query:({db:e,opts:t})=>yc(e,{scope:C(t,"scope"),maxDepth:I(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(`
|
|
537
|
+
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(`
|
|
538
|
+
${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.)`)}}),HT=dt({commandName:"architecture",query:({db:e,opts:t})=>bc(e,{scope:C(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0&&console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}`),e.coverage.ambiguousFiles.length>0){console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}`);for(let t of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${t.file} -> ${t.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
|
|
539
|
+
Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
|
|
540
|
+
No declared boundary violations found.`);if(e.staleAllowances.length>0){console.log(`
|
|
541
|
+
Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.`);for(let t of e.staleAllowances)console.log(` ${t.from} -> ${t.to}`)}if(e.boundaryLimits.length>0){console.log(`
|
|
542
|
+
Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
|
|
543
|
+
Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
|
|
544
|
+
Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
|
|
545
|
+
Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let r of n.examples.slice(0,3))console.log(` ${r.fromFile} -> ${r.toFile}`)}}}if(e.edges.length>0){console.log(`
|
|
546
|
+
Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
|
|
547
|
+
Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
|
|
548
|
+
Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n}`);for(let r of t.narrowestEdges)console.log(` inspect ${r.from} -> ${r.to}: ${r.fileEdgeCount} file edge(s)`)}}}}),GT=dt({commandName:"deep-chains",query:({db:e,opts:t})=>kc(e,{limit:N(t,"limit",10),scope:C(t,"scope"),minDepth:I(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(`
|
|
549
|
+
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("; ")}`)}}}),Zh=[Si({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",agent:w("Which symbols are the largest reference choke points?","ranked symbol identities with reference and file counts",[],"bounded","repository"),options:[p("-n, --limit <n>","Number of results",k,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:P("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>sc(e,{limit:N(t,"limit",30),scope:C(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",agent:{...w("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},options:T([p("-n, --limit <n>","Number of results for top mode",k,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:BT},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:w("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results for top mode",k,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:qT},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",agent:w("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results for top mode",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:VT},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",agent:w("Which file dependency cycles exist?","dependency-cycle file chains",[],"bounded","repository"),options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",k,10)]),renderShape:"custom",docs:P("Graph"),handler:WT},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:w("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:T([p("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:P("Graph",["scip-query architecture --json"]),handler:HT},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",agent:w("Which files are high-connectivity coupling hubs?","ranked files with fan-in and fan-out counts",[],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results",k,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",k,2),p("--min-fan-out <n>","Minimum fan-out",k,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:P("Graph"),handler:_T},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",agent:w("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:T([p("-n, --limit <n>","Number of chains to show",k,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",k,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:GT},vi({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",agent:w("Who calls this symbol and what does it call?","caller and callee symbol identities with files",["symbol"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:P("Graph"),query:({db:e,args:t,budget:n})=>gn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:he(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(ge(t,String(n[0])),console.log(`Symbol: ${e.shortName}
|
|
550
|
+
`))},toJson:(e,{db:t,args:n})=>Le(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 UT=ne("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=M(t,0),o=yl(e,i,{semantic:r.semantic});if(S(n,"json")){A("complexity",t,n,Le(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return O.empty(he(e,i,"Symbol not found."));ge(e,i),console.log(`${U(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
|
|
551
|
+
`),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}`)}),JT=ue(({db:e,args:t,opts:n})=>{let r=Ol(e,{samples:I(n,"samples",50),scope:C(n,"scope")});if(S(n,"json")){A("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)}%.
|
|
552
|
+
`),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(`
|
|
553
|
+
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(", ")}`)}}),ey=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:w("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:T([p("--samples <n>","Number of symbols to sample",k,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:P("Health",["scip-query self-audit --samples 100"]),handler:JT},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:w("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Health"),handler:UT}];import{dirname as KT}from"path";var zT=ue(({db:e,args:t,opts:n})=>{let r=M(t,0),i=Fc(e,r,{maxDepth:I(n,"maxDepth",5),scope:C(n,"scope")});if(S(n,"json")){A("affected",t,n,Le(e,r,i,"affected"));return}if(i.length===0)return O.empty(he(e,r,"No affected symbols found."));ge(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
|
|
554
|
+
\u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
|
|
555
|
+
${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),QT=ne("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:M(t,0),o=S(n,"full"),s=Bc(e,i,{minTogether:I(n,"minTogether",4),limit:N(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(S(n,"json")){A("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.`);Ve("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
|
|
556
|
+
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
|
|
557
|
+
`),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.
|
|
558
|
+
`);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,d=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${d}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${YT(a.lastTogetherAt)}`),console.log(` subjects: ${XT(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
559
|
+
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function YT(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function XT(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 ZT=ne("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=_c(e,M(t,0),{semantic:r.semantic});if(S(n,"json")){A("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}`),i.fileRisk&&i.fileRisk.reasons.length>0&&console.log(`File risk factors (${i.fileRisk.coverage} metadata): ${i.fileRisk.reasons.map(o=>`${o.kind}: ${o.detail}`).join("; ")}`),console.log(""),O.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"",a=o.riskReasons??[],c=a.length===0?"":` [why: ${a.map(l=>`${l.kind}: ${l.detail}`).join("; ")}]`;return` ${fe(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}${c}`})}),eE=ne("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=Xc(e,{base:C(n,"base"),minContainment:I(n,"minContainment",.7),maxHelpers:X(n,"maxHelpers"),limit:N(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(S(n,"json")){A("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),(!i.available||i.findings.length>0)&&(process.exitCode=1);return}if(!i.available){console.error(`error: ${i.note??"Required Git history is unavailable."}`),process.exitCode=1;return}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(`
|
|
560
|
+
No incomplete migrations detected.`);return}Ve("incomplete migration candidates");for(let o of i.findings){console.log(`
|
|
561
|
+
${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(`
|
|
562
|
+
${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function tE(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Be.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Be.join(", ")}`),process.exit(1)),t}var nE=ue(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Or(Ht()))return;let r=S(t,"full"),i;try{i=Ir({base:C(t,"base"),minTogether:I(t,"minTogether",6),maxEchoChecks:X(t,"maxEchoChecks"),maxHelpers:X(t,"maxHelpers"),includeBaseline:S(t,"baseline"),includeOutcomeLedger:n,full:r,skip:tE(t.skip)},{projectRoot:e.config.projectRoot,cacheDir:KT(e.config.dbPath)})}catch(h){let b=h instanceof Error?h.message:String(h);if(n){console.error(`diff gate FAILED CLOSED: ${b}`),process.exitCode=2;return}S(t,"json")?A("diff-gate",[],t,{exitCode:1,gateError:b,advisoryFindingCount:0,base:C(t,"base")??"HEAD",changedFiles:[],changedSymbols:0,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:[]},{coverage:{complete:!1,totalKnown:!1,returned:0},agentResult:{outcome:"fail",exitCode:1,gateError:b,changedFileCount:0,changedSymbolCount:0,checksRun:[],skippedChecks:[],blockingFindings:[],advisoryFindingCount:0}}):console.error(`FAIL (gate error): ${b}`),process.exitCode=1;return}let{result:o,outcomes:s,analysisBudget:a}=i,c=dr(o.findings),l=dl(o),d=l!==void 0,u=o.recordCompatibility?ct("Committed suppression",o.recordCompatibility.suppressions):void 0;if(s.warning&&console.error(`note: ${s.warning}`),!n&&S(t,"json")){let h=c.length>0||d?1:0;A("diff-gate",[],t,{exitCode:h,...l?{gateError:l}:{},advisoryFindingCount:o.findings.length-c.length,...a?{analysisBudget:a}:{},...o},{analysisBudget:a,coverage:r&&!d?{complete:!0,totalKnown:!0,returned:o.findings.length,total:o.findings.length,omitted:0}:{complete:!1,totalKnown:!1,returned:o.findings.length},agentResult:{outcome:h===0?"pass":"fail",exitCode:h,changedFileCount:o.changedFiles.length,changedSymbolCount:o.changedSymbols,checksRun:o.checksRun,skippedChecks:o.skipped,blockingFindings:c.map(b=>({id:b.id,check:b.check,severity:b.severity,file:b.file,symbol:b.symbol,message:b.message,remediation:b.remediation})),advisoryFindingCount:o.findings.length-c.length}}),(c.length>0||d)&&(process.exitCode=1);return}if(n){let{observed:h,now:b}=s,y=s.ledger??[];if(d){console.error(`diff gate FAILED CLOSED: ${l}. Investigate with: scip-query diff-gate`),process.exitCode=2;return}if(u&&console.error(`note: ${u}`),c.length===0)return;let R=ur(y,h,b),$=kl(y,o.checksRun),v=vr(a),E=[...R?[R]:[],xn(o),...$,...v?[v]:[]];console.error(E.join(`
|
|
563
|
+
`)),process.exitCode=2;return}if(d){console.error(`FAIL (gate error): ${l}.`),process.exitCode=1;return}if(u&&console.log(`WARN: ${u}`),o.changedFiles.length===0)return O.empty(o.note??`No changes vs ${o.base}.`);console.log(`Diff gate vs ${o.base}: ${o.changedFiles.length} file(s), ${o.changedSymbols} symbol(s) changed.`);let m=o.attributionNotes.filter(h=>h.method==="unattributed");if(m.length>0)for(let h of[...new Set(m.map(b=>b.file))]){let b=m.filter(y=>y.file===h).length;console.log(`note: ${b} changed line-range(s) in ${h} belong to no indexed symbol`)}console.log(`Checks: ${o.checksRun.join(", ")}
|
|
564
|
+
`);for(let h of o.skipped)console.log(` skipped ${h.check}: ${h.reason}`);if(o.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}Ve("diff gate candidates");let f=o.rootCauseGroups?.filter(h=>h.count>1)??[];if(f.length>0){console.log(`Root-cause groups (${f.length}):`);for(let h of f){console.log(` [${h.check}] ${h.count} finding(s), ${h.severity}${h.actionTier?`, tier: ${h.actionTier}`:""}`),(h.sourceAnalyzer||h.rootCauseKey)&&console.log(` source: ${h.sourceAnalyzer??h.check}${h.rootCauseKey?` root cause: ${h.rootCauseKey}`:""}`);let b=[...new Set([...h.files,...h.relatedFiles])].slice(0,6);b.length>0&&console.log(` files: ${b.join(", ")}`),console.log(` -> ${h.remediation}`)}console.log("")}for(let h of o.findings){if(console.log(` [${h.check}]${h.advisory?" (advisory)":""} ${h.message}`),h.partnerClass){console.log(` partner class: ${h.partnerClass}`);for(let b of h.partnerClassReasons??[])console.log(` reason: ${b}`)}h.citationKind&&console.log(` citation kind: ${h.citationKind}${h.actionTier?` (tier: ${h.actionTier})`:""}`);for(let b of h.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Sr(b)}`);h.declaredCouplingSuggestion&&console.log(` declare coupling: ${h.declaredCouplingSuggestion.name} (${h.declaredCouplingSuggestion.reason})`),console.log(` -> ${h.remediation}`)}if(c.length===0){console.log(`
|
|
565
|
+
PASS (advisory only): ${o.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let g=o.findings.length-c.length;console.log(`
|
|
566
|
+
FAIL: ${c.length} finding(s)${g>0?` (+${g} advisory)`:""}, ${o.rootCauseGroups?.length??o.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),ty=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",agent:w("Which downstream symbols could break if this symbol changes?","affected symbol identities, files, and traversal depths",["symbol"],"bounded"),options:T([p("--max-depth <n>","Maximum traversal depth",k,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:P("Impact"),handler:zT},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: consumers, published API, operational roots, and explained change risk",agent:w("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:P("Impact"),handler:ZT},{id:"diff-gate",command:"diff-gate",description:"Runtime-bounded, single-flight gate for the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings",options:T([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",k,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",k),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",k),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",lt,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop")]),heuristic:{label:"diff gate candidates"},agent:{answers:["Does my current diff introduce something this repo blocks on?","What must I fix or explicitly accept before reporting the work done?"],returns:["blocking findings with check id, message, and remediation","advisory findings","root-cause groups","changed file and symbol counts","process exit status (1 when blocking findings exist)"],inputs:[],scope:"diff",coverage:"bounded",contrasts:[{command:"diff-impact",distinction:"diff-impact reports what the diff touches downstream; diff-gate judges the diff against repo policy and exits non-zero."}]},renderShape:"custom",docs:P("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:nE},{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",agent:w("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:T([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",we,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",k),p("-n, --limit <n>","Maximum findings to report",k,20),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:P("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:eE},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:w("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:T([p("--min-together <n>","Minimum commits where both files changed",k,4),p("-n, --limit <n>","Maximum pairs to report",k,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:P("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:QT}];function rE(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${U(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
|
|
567
|
+
`).map((s,a)=>` ${qe(i.startLine+a)} ${s}`).join(`
|
|
568
|
+
`))}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 ${qe(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var iE=Se("imports",{query:({db:e,args:t,budget:n})=>ac(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),oE=ne("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=M(t,0),o=bl(e,i,{semantic:r.semantic});if(S(n,"json")){A("dataflow",t,n,Le(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return O.empty(he(e,i,"No dataflow found."));if(ge(e,i),console.log(`${o.shortName} (${o.relativePath})
|
|
569
|
+
`),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${qe(s.line)}`)}if(o.usageSites.length>0){console.log(`
|
|
570
|
+
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${qe(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
|
|
571
|
+
\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(`
|
|
572
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),sE=ne("slice",({db:e,args:t,opts:n,budget:r})=>{let i=M(t,0),o=S(n,"forward")?"forward":"backward",s=Sl(e,i,{direction:o,maxDepth:I(n,"depth",3),semantic:r.semantic});if(S(n,"json")){A("slice",t,n,Le(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return O.empty(he(e,i,"No slice found."));if(ge(e,i),console.log(`${s.direction} slice of ${s.shortName}
|
|
573
|
+
`),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}O.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
574
|
+
${a.relationship}`),console.log(`
|
|
575
|
+
${s.connectedSymbols.length} connected symbol(s).`)}),aE=ue(({db:e,args:t,opts:n})=>{let r=M(t,0),i=Za(e,{className:r});if(S(n,"json")){A("methods",t,n,i,{coverage:cE(i)}),i.kind!=="matched"&&(process.exitCode=1);return}if(i.kind==="matched"){O.list(i.methods,o=>` ${fe(o.startLine,o.endLine)} ${o.name}`);return}O.empty(lE(i)),process.exitCode=1});function cE(e){let t=e.kind==="matched"?e.methods.length:0,n=e.kind==="matched"?{state:"exact",totalCandidates:1}:e.kind==="missing"?{state:"missing",totalCandidates:0}:{state:"ambiguous",totalCandidates:e.total};return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0,resolution:n}}function lE(e){if(e.kind==="missing"){let n=`No class definition matched '${e.query}'.`;return e.suggestions.length>0?`${n} Suggestions: ${e.suggestions.join(", ")}`:n}let t=e.candidates.map(n=>`${n.relativePath}:${qe(n.startLine)}`).join(", ");return`Class '${e.query}' is ambiguous across ${e.total} definitions (${t}). Qualify it with a path or exact SCIP symbol identity.`}var ny=[...wd,st({id:"files",command:"files <pattern>",description:"Find files matching a pattern",agent:w("Which indexed files match this text pattern?","matching file paths",["pattern"],"complete"),docs:P("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Xa(e,M(t,0)),format:e=>e.relativePath}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:T(),agent:{...w("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:P("Navigation"),renderShape:"list",handler:aE},vi({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes"),oo()],budget:"semantic",agent:{answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:P("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>ec(e,M(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?he(t,M(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>ge(t,M(n,0)),toJson:(e,{db:t,args:n})=>({...bn(t,M(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:rE}),st({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:w("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>tc(e,M(t,0)),format:e=>e.relativePath}),st({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:w("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>nc(e,M(t,0)),format:e=>e.relativePath}),nh({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",options:[oo()],agent:{answers:["What is in this module?","What does this module depend on, and what depends on it?"],returns:["module file paths","exported symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",contrasts:[{command:"surface",distinction:"system lists everything the module exports; surface lists only what consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:P("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>rc(e,M(t,0)),coverage:e=>{let t=e.files.length+e.symbols.length+e.dependsOn.length+e.dependedOnBy.length;return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}},agentResult:e=>({counts:{files:e.files.length,symbols:e.symbols.length,dependencies:e.dependsOn.length,consumers:e.dependedOnBy.length},files:e.files,dependsOn:e.dependsOn,dependedOnBy:e.dependedOnBy,detail:{location:"result",symbolUnits:"result.symbols contains every exported symbol with its line range"}}),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${fe(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}`)}]}),st({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:w("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>ic(e,M(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:w("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:P("Navigation"),handler:iE},st({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:w("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>cc(e,M(t,0)),format:e=>` ${e.fromFile}`}),st({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:w("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>dc(e,M(t,0)),format:e=>` ${fe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>ge(t,M(n,0)),emptyMessage:({db:e,args:t})=>he(e,M(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Le(t,M(n,0),e,"members")}),st({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:w("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",k,100),p("--full","Run unbounded analysis on large indexes")],docs:P("Navigation"),query:({db:e,args:t,opts:n})=>Rc(e,M(t,0),{scope:C(n,"scope"),limit:N(n,"limit",100)}),format:e=>` ${U(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${M(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
576
|
+
${e.length} symbol(s)`)}),Si({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:w("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[p("-s, --scope <path>","Limit to files matching path")],docs:P("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>xc(e,{scope:C(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),st({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:w("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:P("Navigation"),query:({db:e,args:t})=>wc(e,M(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>ge(t,M(n,0)),emptyMessage:({db:e,args:t})=>he(e,M(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Le(t,M(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",agent:w("What defines, uses, produces, and consumes this symbol?","definition sites, usage sites, producer symbols, and consumer symbols",["symbol"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Navigation"),handler:oE},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",agent:w("What transitively affects this symbol, or what does it affect?","connected symbols with relationship and depth",["symbol"],"bounded"),options:T([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",k,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Navigation"),handler:sE}];var dE=ne("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=N(n,"limit",20),o=Xe(e.config.projectRoot).gitContext?.headCommit,s=vl(e,M(t,0),{semantic:r.semantic,impactDepth:I(n,"impactDepth",3),sliceDepth:I(n,"sliceDepth",3),scope:C(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(S(n,"json")){A("plan-context",t,n,{...bn(e,M(t,0)),...s},{analysisBudget:r.analysisBudget,coverage:ry(s),agentResult:iy(s)});return}return O.empty(he(e,M(t,0)))}if(S(n,"json")){A("plan-context",t,n,s.matched.symbol?{...bn(e,M(t,0)),...s}:s,{analysisBudget:r.analysisBudget,coverage:ry(s),agentResult:iy(s)});return}s.matched.symbol&&ge(e,M(t,0));let a=[{title:"TARGET",rows:pE(s)},{title:"DEFINITIONS",rows:mE(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:fE(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:gE(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:hE(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:yE(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:bE(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:SE(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:vE(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:RE(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:xE(s),skipIfEmpty:!0}];O.sectionedReport(a)}),oy=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:gd([p("--impact-depth <n>","Maximum affected traversal depth",k,3),p("--slice-depth <n>","Maximum backward slice depth",k,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",k,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",agent:{answers:["What must I know before editing this target?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions"],inputs:[["symbol","file","module"]],coverage:"bounded",contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; plan-context embeds it alongside flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:P("Planning",["scip-query plan-context parseSymbol"]),handler:dE}];function ry(e){return{complete:!1,totalKnown:!1,returned:uE(e)}}function uE(e){return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length}function iy(e){return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,fileRisk:e.changeSurface.fileRisk,riskCounts:{high:e.changeSurface.symbols.filter(t=>t.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(t=>t.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(t=>t.riskLevel==="low").length}}:null,history:e.history}}function pE(e){return[`Target: ${e.target}`,`Matched: symbol=${Ws(e.matched.symbol)} file=${Ws(e.matched.file)} module=${Ws(e.matched.module)}`]}function mE(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${U(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
|
|
577
|
+
`).map((o,s)=>` ${String(qe(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${fe(r.startLine,r.endLine)} ${r.shortName}`)),ht(n,t).rows}function fE(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${qe(r.line)} in ${r.enclosingShort}`);return Et(ht(n,t))}function gE(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 Et(ht([...n,...r],t))}function hE(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}:${qe(o.line)} in ${o.enclosingShort}`);return Et(ht([...n,...r,...i],t))}function yE(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 Et(ht(n,t))}function bE(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${fe(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Et(ht(n,t))}function SE(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 Et(ht(n,t))}function vE(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),e.changeSurface.fileRisk&&e.changeSurface.fileRisk.reasons.length>0&&n.push(` File risk factors (${e.changeSurface.fileRisk.coverage} metadata): ${e.changeSurface.fileRisk.reasons.map(r=>`${r.kind}: ${r.detail}`).join("; ")}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"",o=r.riskReasons??[],s=o.length===0?"":` [why: ${o.map(a=>`${a.kind}: ${a.detail}`).join("; ")}]`;return` ${fe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}${s}`}))),e.complexity&&(n.push(` Complexity: ${U(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}`)),Et(ht(n,t))}function RE(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 xE(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.changeSurface?.fileRisk?.operationalRoot&&t.push(" This file is an operational root; validate its launch and shutdown path even when source fan-in is zero."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function ht(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Et(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Ws(e){return e?"yes":"no"}import{existsSync as Hn}from"fs";import{existsSync as qE,mkdtempSync as VE,rmSync as WE}from"fs";import{tmpdir as HE}from"os";import{dirname as Us,join as GE}from"path";import{performance as my}from"perf_hooks";import{spawnSync as UE}from"child_process";import{createHash as cy,randomUUID as kE}from"crypto";import{closeSync as Pi,createReadStream as wE,existsSync as $E,fsyncSync as CE,mkdirSync as PE,openSync as Gs,renameSync as TE,unlinkSync as EE,writeSync as IE}from"fs";import{homedir as AE}from"os";import{dirname as ly,join as Hs}from"path";var jE=3e5,OE=256*1024*1024;function dy(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?Hs(t.XDG_CACHE_HOME,"scip-query"):Hs(AE(),".cache","scip-query"));return Hs(n,e)}var ee=class extends Error{constructor(n,r,i={}){super(r,i.cause===void 0?void 0:{cause:i.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function uy(e){let{cachePath:t,url:n,expectedSha256:r}=e,i=e.timeoutMs??jE,o=e.maxBytes??OE,s=e.lockWaitMs??i;LE(i,o,s);let a=DE(n,i,e.signal);try{let c=await sy(t,r,o,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};PE(ly(t),{recursive:!0});let l=await za(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new ee("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let d=await sy(t,r,o,a.controller.signal);return d?{status:"cached",path:t,sha256:d}:await ME(e,a.controller,o)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?tn(a.controller.signal,n):c instanceof ee?c:new ee("stream",`failed to download ${n}: ${py(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function LE(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function DE(e,t,n){let r=new AbortController,i=()=>{r.abort(new ee("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i();let o=setTimeout(()=>{r.abort(new ee("timeout",`download of ${e} timed out after ${t}ms`))},t);return o.unref(),{controller:r,timeout:o,detachExternalAbort:()=>n?.removeEventListener("abort",i)}}async function sy(e,t,n,r){if(!$E(e))return null;let i=cy("sha256"),o=0;try{for await(let a of wE(e,{signal:r})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(o+=c.length,o>n)return null;i.update(c)}}catch{if(r.aborted)throw tn(r,e);return null}let s=i.digest("hex");return s===t?s:null}async function ME(e,t,n){let r=e.fetchImpl??fetch,i;try{i=await ay(r(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?tn(t.signal,e.url):new ee("stream",`failed to download ${e.url}: ${py(l)}`,{cause:l})}if(!i.ok){let l=new ee("http",`failed to download ${e.url}: HTTP ${i.status}`);throw t.abort(l),l}let o=NE(i,n,e.url);if(!i.body)throw new ee("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${kE()}`,a,c=!1;try{a=Gs(s,"wx",384),c=!0;let l=i.body.getReader(),d=cy("sha256"),u=0;for(;;){let{done:f,value:g}=await ay(l.read(),t.signal);if(f)break;if(!(g instanceof Uint8Array))throw new ee("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(u+=g.byteLength,u>n||o!==void 0&&u>o){let b=new ee("length",`downloaded ${e.url} exceeded its ${o??n} byte limit`);throw t.abort(b),b}let h=Buffer.from(g.buffer,g.byteOffset,g.byteLength);d.update(h),La(a,h,{writeFile:e.writeImpl??IE},"verified binary staging")}if(o!==void 0&&u!==o)throw new ee("length",`downloaded ${e.url} length mismatch: declared ${o} bytes, received ${u}`);let m=d.digest("hex");if(m!==e.expectedSha256)throw new ee("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${m}`);Pi(a),a=void 0;try{FE(s,e.cachePath,e.renameImpl??TE,e.syncImpl??CE)}catch(f){throw new ee("install",`failed to install verified binary at ${e.cachePath}`,{cause:f})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:m}}catch(l){throw t.signal.aborted?tn(t.signal,e.url):l instanceof ee?l:new ee("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{Pi(a)}catch{}if(c)try{EE(s)}catch{}}}function NE(e,t,n){let r=e.headers?.get("content-length");if(r==null)return;if(!/^\d+$/.test(r))throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);let i=Number(r);if(!Number.isSafeInteger(i)||i<0)throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);if(i>t)throw new ee("length",`downloaded ${n} declares ${i} bytes, above the ${t} byte limit`);return i}function FE(e,t,n,r){_E(e,r),n(e,t),BE(ly(t),r)}function _E(e,t){let n=Gs(e,"r");try{t(n)}finally{Pi(n)}}function BE(e,t){let n;try{n=Gs(e,"r")}catch(r){if(Vi(r,process.platform))return;throw r}try{t(n)}catch(r){if(!Vi(r,process.platform))throw r}finally{Pi(n)}}function ay(e,t){return t.aborted?Promise.reject(tn(t,"operation")):new Promise((n,r)=>{let i=()=>{t.removeEventListener("abort",i),r(tn(t,"operation"))};t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),n(o)},o=>{t.removeEventListener("abort",i),r(o)})})}function tn(e,t){return e.reason instanceof Error?e.reason:new ee("aborted",`verified binary operation for ${t} was aborted`)}function py(e){return e instanceof Error?e.message:String(e)}var JE=12e4,hy="v1.8.0",KE=`https://github.com/tlaplus/tlaplus/releases/download/${hy}/tla2tools.jar`,zE="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Ei(e){let t=e.spawn??UE,n=QE(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??JE,i=my.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,killSignal:"SIGKILL",maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])WE(l,{recursive:!0,force:!0})}let s=Math.round(my.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:YE(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function QE(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"&&Ke(fy(e),t)){let o=fy(e);return Ke(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Us(e.specPath)}:Ti("apalache",`Apalache binary is not available: ${o}`)}let r=Js(e),i=Ke("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Ti(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Ti(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:Us(e.specPath)};let s=e.metaDir??VE(GE(HE(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Us(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Ti("none",`unknown checker mode: ${n}`)}function fy(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Js(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,yy(t)].filter(r=>typeof r=="string"&&r.length>0).find(r=>qE(r))??null}function yy(e=process.env){return dy("tla2tools.jar",e)}async function by(e={}){let t=e.cachePath??yy(e.env),n=e.expectedSha256??zE,r=e.version??hy,i=e.url??KE;return{...await uy({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:r,url:i}}function YE(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=[...gy(n),...gy(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function gy(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Ti(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as XE}from"crypto";var vy=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Ry=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),xy=new Set(["readFileSync","existsSync","statSync"]),ZE=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,eI=/^\s*SELECT\b/i;function ky(e){return ZE.test(e)?"write":eI.test(e)?"read":null}var tI=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function nI(e,t){let n=e.match(tI);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Je(t)}\\b`).test(r)}function wy(e,t,n,r=[],i=[]){let o=[],s=oI(e,t,o),a=s.aliases,c=sI(t),l=aI(t),d=cI(t),u=uI(e,t,o),m=mI(e,t,o);n&&fI(t,n,i,o);let f=new Map((n?.actions??[]).map(R=>[R.name,R])),g=new Set(u.flatMap(R=>R.referents.map($=>$.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(R=>R.match?.symbol).filter(Boolean)),b=gI(e,t,u,a,c,l,d,g,h,o,f),y=bI(e,u,a,c,l,d,o,f);return vI(e,u,o),RI(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:zs(u.flatMap(R=>R.referents))+zs(s.referents)+zs(m?.referents??[]),staticWrites:b,staticReads:y,waivers:qI(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:rI(o)}}function rI(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=iI(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ii(r.severity)-Ii(n.severity)||n.groupKey.localeCompare(r.groupKey))}function iI(e,t){return Ii(t)>Ii(e)?t:e}function Ii(e){return e==="error"?2:e==="warning"?1:0}function oI(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 d=Oi(e,l,n,o);i.push(d);let u=d.match;if(!u){c||n.push(z("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}DI(e,o,l,u,n,c),s.aliases.length===0&&a.add(Ra(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:BI(r),referents:i}}function sI(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 aI(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:Un(i.pattern,`variables.${n}.statements pattern`)});return t}function cI(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=Fs(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function lI(e,t,n,r,i,o){return $y(e,t,(s,a,c)=>It(e,s,a,c,n,r,i,o))}function dI(e,t,n,r,i,o){return $y(e,t,(s,a,c)=>ji(e,s,a,c,n,r,i,o))}function $y(e,t,n){let r=gn(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=er(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 uI(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=_s(s),c="error"in a?s:a.ref,d=Oi(e,c,n,r).match;return d?(MI(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:pI(a.window,d)?(n.push(z("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${re(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${re(d.symbol)} at ${d.relativePath}:${d.startLine+1}-${d.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${d.startLine+1}-L${d.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:d,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(z("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 pI(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function mI(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Oi(e,s,n,"Init"),c=a.match;return c?NI(e,s,c,n,i):i||n.push(z("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 fI(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(z("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(z("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&&(Sy({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)}),Sy({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(z("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 Sy(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(z(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(z(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 gI(e,t,n,r,i,o,s,a,c,l,d){let u=[];for(let f of n){let g=[];for(let h of f.referents){if(!h.match)continue;let b=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},y=It(e,h.match.relativePath,b.startLine,b.endLine,r,i,o,s);g.push(...y),u.push(...y);let R=new Set(f.mapping.writes),$=lI(e,h.match.symbol,r,i,o,s).filter(v=>R.has(v.variable));g.push(...$),u.push(...$)}yI(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:jI(e,t);for(let f of m)for(let g of It(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(g),hI(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(z("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.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 ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return Xs(u)}function hI(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function yI(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)&&!Vn(e,"write",a.variable)&&n.push(z("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}${Ai(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)&&!Vn(e,"write",a.variable)&&n.push(z("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}${Ai(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)&&!Vn(e,"write",a)&&n.push(z("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 bI(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let u of l.referents){if(!u.match)continue;let m=u.window??{startLine:u.match.startLine,endLine:u.match.endLine},f=ji(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=dI(e,u.match.symbol,n,r,i,o).filter(b=>g.has(b.variable));d.push(...h),c.push(...h)}SI(l,d,s,a.get(l.name))}return Zs(c)}function SI(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(z("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}${Ai(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)&&!Vn(e,"read",a.variable)&&n.push(z("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}${Ai(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)&&!Vn(e,"read",a)&&n.push(z("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 vI(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Oi(e,s,n,r.name));for(let s of i)s.match||n.push(z("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=gn(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(z("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 ${re(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 RI(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(z("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=_I(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(z("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 It(e,t,n,r,i,o=[],s=[],a=[]){let c=xI(e,t,n,r,i,o,s,a);return c||II(e,t,n,r,i,o,s,a)}function ji(e,t,n,r,i,o=[],s=[],a=[]){let c=kI(e,t,n,r,i,o,s,a);return c||AI(e,t,n,r,i,o,s,a)}function xI(e,t,n,r,i,o=[],s=[],a=[]){let c=qi(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){wI(e,t,u,i,l),Cy(e,t,u,o,"write",l),Py(e,t,u,s,"write",l),Ty(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),Xs(l)}function kI(e,t,n,r,i,o=[],s=[],a=[]){let c=qi(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){PI(e,t,u,i,l),Cy(e,t,u,o,"read",l),Py(e,t,u,s,"read",l),Ty(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),Zs(l)}function wI(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&qn(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&&qn(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&&qn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&qn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!Iy(o))return;qn(e,t,o,"mutation-call",r,i)}}}function Cy(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?Qs(s):null;if(!a||!(i==="write"?Ry:xy).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of r){if(!u.includes(m.path))continue;let f=He(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?re(f.symbol):void 0})}}function Qs(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 Py(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=$I(a);if(c!==null&&ky(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=He(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&Qs(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${CI(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?re(d.symbol):void 0})}}}function $I(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function CI(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Ty(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?Qs(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of r){if(!Ey(u,a,d,i))continue;let m=He(e,t,n.startPosition.row);o.push({variable:u.variable,alias:u.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?re(m.symbol):void 0})}}function Ey(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 PI(e,t,n,r,i){if(!(!TI(n)||EI(n)))for(let o of r){if(n.text!==o.alias)continue;let s=He(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?re(s.symbol):void 0})}}function TI(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function EI(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&&Ks(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&&Ks(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Iy(n)&&Ks(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 Ks(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Iy(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&vy.has(t.text))}function qn(e,t,n,r,i,o){for(let s of i){if(!FI(s.alias,n.text))continue;let a=He(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?re(a.symbol):void 0})}}function II(e,t,n,r,i,o=[],s=[],a=[]){let l=Ue(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of i){if(nI(f,g.alias))continue;let h=Je(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...vy].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let y=He(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?re(y.symbol):void 0})}Ay(e,t,m,f,o,Ry,d),jy(e,t,m,f,s,"write",d),Oy(e,t,m,f,a,"write",d)}return Xs(d)}function AI(e,t,n,r,i,o=[],s=[],a=[]){let l=Ue(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of i){let h=Je(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let b=He(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:b?.symbol,enclosingShort:b?re(b.symbol):void 0})}Ay(e,t,m,f,o,xy,d),jy(e,t,m,f,s,"read",d),Oy(e,t,m,f,a,"read",d)}return Zs(d)}function Ay(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 d of i){if(!l.includes(d.path))continue;let u=He(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?re(u.symbol):void 0})}}}function jy(e,t,n,r,i,o,s){if(i.length!==0&&ky(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=He(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?re(c.symbol):void 0})}}function Oy(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 d of i){if(!Ey(d,c,l,o))continue;let u=He(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?re(u.symbol):void 0})}}}function jI(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 Oi(e,t,n,r){let i=er(e,t),o=i.match??(t.includes("#")?er(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!OI(t)&&n.push(z("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 ${re(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,LI(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 OI(e){return/[/#:]/.test(e)}function LI(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function DI(e,t,n,r,i,o=!1){let s=Ys(e,r);if(s===null||VI.has(s)||o)return;let a=ea.has(s);i.push(z("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${un(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${re(r.symbol)} with SCIP kind ${un(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function MI(e,t,n,r,i){let o=Ys(e,r);o===null||Ly.has(o)||ea.has(o)&&i.push(z("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 ${re(r.symbol)} with SCIP kind ${un(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function NI(e,t,n,r,i){let o=Ys(e,n);o===null||Ly.has(o)||i||ea.has(o)&&r.push(z("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 ${re(n.symbol)} with SCIP kind ${un(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Ys(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function He(e,t,n){return Zn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function FI(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Je(e)}([^A-Za-z0-9_$]|$)`).test(t)}function _I(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function Xs(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function Zs(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 BI(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 zs(e){return e.filter(t=>t.match).length}function Ai(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Vn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function qI(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 ea=new Set($a()),Ly=new Set(wa()),VI=new Set(Ca());function z(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${XE("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{basename as WI,join as HI}from"path";var ta=/^[A-Za-z_][A-Za-z0-9_]*$/;function Dy(e,t,n={}){let r=[],i=Zn(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=Ue(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=x=>x.symbol.trimEnd().endsWith("()."),c=i.filter(x=>!a(x)&&!x.isTypeLike&&x.parentTypeName===null&&ta.test(x.leaf)),l=c.map(x=>({variable:x.leaf,alias:x.leaf})),d=l.length>0?It(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(x=>x.variable)),m=c.filter(x=>u.has(x.leaf)?!0:JI(s,x)),f=null,g;if(m.length>0)g=i.filter(x=>a(x)&&x.parentTypeName===null);else{if(f=GI(e,t,i,a),!f){let x=i.some(j=>!a(j)&&!j.isTypeLike&&j.parentTypeName!==null&&ta.test(j.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 `+(x?"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.")}m=f.fields,g=f.methods,r.push(`state scoped to class ${f.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 h=m.map(x=>KI(x,s,t,r,f?.className)),b=h.map(x=>({variable:x.name,alias:x.leaf})),y=[],R=new Set;for(let x of g){let j=It(e,t,x.startLine,x.endLine,b);if(j.length===0)continue;let _=ji(e,t,x.startLine,x.endLine,b),F=XI(My(x.leaf),R);y.push({name:F,leaf:x.leaf,codeRef:UI(t,x,f?.className),startLine:x.startLine,writes:[...new Set(j.map(H=>H.variable))].sort(),reads:[...new Set(_.map(H=>H.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 $=n.moduleName??ZI(t),v=n.specDir??HI("specs",$),E=eA($,h,y,t),L=tA(),Q=nA($,v,t,h,y);return{moduleName:$,file:t,variables:h,actions:y,warnings:r,spec:E,cfg:L,map:Q}}function GI(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!ta.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(m=>r(m)&&m.parentTypeName===s),l=a.map(m=>({variable:m.leaf,alias:m.leaf})),d=new Set;for(let m of c)for(let f of It(e,t,m.startLine,m.endLine,l))d.add(f.variable);let u=a.filter(m=>d.has(m.leaf));u.length!==0&&(!o||u.length>o.fields.length)&&(o={className:s,fields:u,methods:c})}return o}function UI(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function JI(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function KI(e,t,n,r,i){let o=zI(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=QI(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 zI(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function QI(e,t){let r=t.match(new RegExp(`\\b${rA(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=YI(r);l?(s=`{${l.map(d=>`"${d}"`).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 YI(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 My(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function XI(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function ZI(e){let n=WI(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return My(n||"Model")}function eA(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 d=t.find(u=>u.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${d} \\* 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(`
|
|
578
|
+
`)}function tA(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
|
|
579
|
+
`)}function nA(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)}
|
|
580
|
+
`}function rA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ny(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?ka(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:iA(n),wiring:r,variables:n}}function iA(e){return`/**
|
|
581
|
+
* Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
|
|
582
|
+
*
|
|
583
|
+
* Usage inside a mapped action (record the model-visible slice around the
|
|
584
|
+
* mutation):
|
|
585
|
+
*
|
|
586
|
+
* import { tlaRecord } from './scip-tla-recorder.js';
|
|
587
|
+
* export function enqueue(job: string) {
|
|
588
|
+
* const before = snapshot();
|
|
589
|
+
* queue.push(job);
|
|
590
|
+
* tlaRecord('Enqueue', before, snapshot());
|
|
591
|
+
* }
|
|
592
|
+
*
|
|
593
|
+
* where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
|
|
594
|
+
* each field with the real runtime value, e.g.
|
|
595
|
+
* const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
|
|
596
|
+
*
|
|
597
|
+
* Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
|
|
598
|
+
* wiring is safe to leave in place. The output is a JSON array compatible
|
|
599
|
+
* with 'scip-query tla trace-check --trace <path>'.
|
|
600
|
+
*/
|
|
601
|
+
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
602
|
+
|
|
603
|
+
interface TlaTraceStep {
|
|
604
|
+
action: string;
|
|
605
|
+
before: Record<string, unknown>;
|
|
606
|
+
after: Record<string, unknown>;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const tracePath = process.env['SCIP_TLA_TRACE'];
|
|
610
|
+
const TRACE_MAX_BYTES = 16 * 1024 * 1024;
|
|
611
|
+
const TRACE_MAX_STEPS = 100_000;
|
|
612
|
+
|
|
613
|
+
export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
|
|
614
|
+
if (!tracePath) return;
|
|
615
|
+
let steps: TlaTraceStep[] = [];
|
|
616
|
+
try {
|
|
617
|
+
const size = statSync(tracePath).size;
|
|
618
|
+
if (size > TRACE_MAX_BYTES) throw new Error(\`TLA trace exceeds \${TRACE_MAX_BYTES} bytes\`);
|
|
619
|
+
steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
|
|
620
|
+
if (!Array.isArray(steps)) steps = [];
|
|
621
|
+
} catch (error) {
|
|
622
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
623
|
+
}
|
|
624
|
+
if (steps.length >= TRACE_MAX_STEPS) throw new Error(\`TLA trace exceeds \${TRACE_MAX_STEPS} steps\`);
|
|
625
|
+
steps.push({ action, before, after });
|
|
626
|
+
const payload = JSON.stringify(steps, null, 2);
|
|
627
|
+
const payloadBytes = Buffer.byteLength(payload);
|
|
628
|
+
if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
|
|
629
|
+
writeFileSync(tracePath, payload);
|
|
630
|
+
}
|
|
631
|
+
`}import{copyFileSync as oA,mkdtempSync as sA,readdirSync as aA,rmSync as cA,writeFileSync as Fy}from"fs";import{tmpdir as lA}from"os";import{basename as dA,dirname as uA,join as Wn}from"path";function Li(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 pA(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=h=>{let b={};for(let[y,R]of Object.entries(h)){if(!t.includes(y))continue;let $=fA(R);$!==void 0&&(b[y]=$)}return b};s.push(c(a));for(let h of n){if(h.before)for(let[b,y]of Object.entries(h.before))b in a||(a[b]=y);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(b=>h in b)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let u=`${e}Trace`,m=s.map(h=>` [${l.map(b=>`${b} |-> ${By(h[b])}`).join(", ")}]`).join(`,
|
|
632
|
+
`),f=[`---- MODULE ${u} ----`,"\\* 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 ==","<<",m,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(h=>` /\\ ${h} = TraceStates[1].${h}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${r}`,...l.map(h=>` /\\ ${h}' = TraceStates[traceIdx + 1].${h}`),"","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(`
|
|
633
|
+
`),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
|
|
634
|
+
`);return{moduleName:u,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function _y(e){let t=e.mappedActions??[],n=pA(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Li(t,[])};let r=sA(Wn(lA(),"scip-tla-trace-"));try{let i=uA(e.specPath);for(let d of aA(i))d.endsWith(".tla")&&oA(Wn(i,d),Wn(r,d));let o=Wn(r,`${n.moduleName}.tla`),s=Wn(r,`${n.moduleName}.cfg`);Fy(o,n.moduleText),Fy(s,n.cfgText);let a=Ei({...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:Li(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:Li(t,e.steps)};let c=mA(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:Li(t,l)}}finally{cA(r,{recursive:!0,force:!0})}}function mA(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 fA(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 By(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>By(t)).join(", ")}>>`}function qy(e){return dA(e).replace(/\.tla$/i,"")}import{mkdirSync as Wy,writeFileSync as Hy}from"fs";import{dirname as gA,join as nn}from"path";var hA=async(...e)=>{let{args:t,opts:n}=kd(e),r=M(t,0);if(r==="fetch-tools"){let o=await by();if(S(n,"json")){A("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=K(t,1);if(!o)throw new Error("tla scaffold requires a target source file");de(s=>yA(s,t,n,o));return}if(r==="instrument"){let o=K(t,1);de(s=>bA(s,t,n,o));return}if(r==="trace-check"){let o=K(t,1);if(!o)throw new Error("tla trace-check requires a spec path");de(s=>SA(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=K(t,1);if(!i)throw new Error("tla verify requires a spec path");de(o=>xA(o,t,n,i))};function yA(e,t,n,r){let i=e.config.projectRoot,o=Dy(e,r,{moduleName:C(n,"moduleName"),specDir:C(n,"out")}),s=C(n,"out")??nn("specs",o.moduleName),a=ve(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=S(n,"force"),l=[{path:nn(a,`${o.moduleName}.tla`),body:o.spec},{path:nn(a,`${o.moduleName}.cfg`),body:o.cfg},{path:nn(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&Hn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);Wy(a,{recursive:!0});for(let d of l)Hy(d.path,d.body);if(S(n,"json")){A("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:r,written:l.map(d=>d.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 d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${o.variables.length}): ${o.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${o.actions.length}): ${o.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of o.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${nn(s,`${o.moduleName}.tla`)}'.`)}function bA(e,t,n,r){let i=e.config.projectRoot,o=C(n,"map")??(r?wi(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=ki(i,o);if(!s.loaded)throw new Error(s.errors.join(`
|
|
635
|
+
`));let{contract:a,mapDir:c}=s.loaded,l=Ny(e,a),d=C(n,"out")??nn(c,"scip-tla-recorder.ts"),u=ve(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!S(n,"force")&&Hn(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(Wy(gA(u),{recursive:!0}),Hy(u,l.recorderSource),S(n,"json")){A("tla",t,n,{operation:"instrument",recorder:u,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${u}`),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 m of l.wiring){let f=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${f} writes: ${m.writes.join(", ")||"-"}`)}}function SA(e,t,n,r){let i=e.config.projectRoot,o=ve(i,r);if(!o||!Hn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=C(n,"map")??wi(r),a=ki(i,s);if(!a.loaded)throw new Error(a.errors.join(`
|
|
636
|
+
`));let{contract:c}=a.loaded,l=Rt(n,"trace"),u=qs(i,[...c.traces,...l]).flatMap(g=>Bs(i,g).steps);if(u.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=_y({specPath:o,baseModuleName:qy(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:C(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:C(n,"tlaTools"),timeoutMs:X(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&S(n,"allowUnknown")?0:1;if(S(n,"json")){A("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${u.length} step(s) -> ${m.states} pinned state(s)`),m.generation){console.log(`Pinned variables: ${m.generation.variables.join(", ")}`);for(let g of m.generation.warnings)console.log(`WARNING: ${g}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),S(n,"coverage")&&vA(m.actionCoverage),process.exitCode=f}function vA(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 RA(e,t,n,r){let i=C(r,"map");if(i)return{mapArg:i};let o=wi(t),s=ve(e,o);if(s&&Hn(s))return{mapArg:o};let a=Sh(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 xA(e,t,n,r){let i=e.config.projectRoot,o=ve(i,r);if(!o||!Hn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=RA(i,r,o,n),c=ki(i,s);if(!c.loaded)throw new Error(c.errors.join(`
|
|
637
|
+
`));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=C(n,"config")??l.config,f=fh(i,u,m),g=wA(C(n,"checker")??"auto"),h=C(n,"tlaTools"),b=kA(i,r,o,h)??gh(i,r),y=yh(f),R=Rt(n,"trace"),v=qs(i,[...l.traces,...R]).map(F=>({tracePath:F,...Bs(i,F)})),E=v.flatMap(F=>F.steps),L=new Set(R),Q=v.filter(F=>L.has(F.tracePath)).flatMap(F=>F.errors),x=wy(e,l,b,E,y);for(let F of[...c.errors,...Q])x.findings.push({id:`TLA-CONTRACT-${x.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 j=Ei({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:C(n,"apalache"),length:I(n,"length",10),timeoutMs:X(n,"timeoutMs")});j.status==="skipped"&&g!=="none"&&x.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:j.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 _={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:j,conformance:x,exitCode:$A(j,x,S(n,"allowUnknown"))};if(S(n,"json")){A("tla",t,n,_),process.exitCode=_.exitCode;return}CA(_,S(n,"full")),process.exitCode=_.exitCode}function kA(e,t,n,r){let i=Js({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=ih({specPath:n,jarPath:i});return o?hh(e,t,o):null}var Gy=[{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",agent:w("Does this TLA+ model and code mapping agree, or can the requested model artifact be generated?","checker status, conformance findings, trace coverage, or generated artifact paths",["action","path"],"bounded","repository"),options:T([p("--map <file>","scip-query TLA mapping JSON file"),p("--config <file>","TLA+ checker config file"),p("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),p("--tla-tools <jar>","Path to tla2tools.jar"),p("--apalache <binary>","Path to apalache-mc binary"),p("--length <n>","Bounded checker length for Apalache",k,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",Ze),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",lt,[]),p("--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"),p("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),p("--allow-unknown","Exit zero when only unknown findings remain"),p("--out <path>","Output directory (scaffold) or file (instrument)"),p("--module-name <name>","Module name for scaffolded specs"),p("--force","Overwrite existing scaffold/instrument output"),p("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:P("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:hA}];function wA(e){if(!mh(e))throw new Error(`unknown checker mode: ${e}`);return e}function $A(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 Vy=3;function CA(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=TA(e);console.log(`
|
|
638
|
+
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 EA(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)Uy(o);return}PA(e.conformance)}function PA(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
|
|
639
|
+
Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
|
|
640
|
+
[${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,Vy)){let o=t.get(i);o&&Uy(o)}let r=n.count-Vy;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function TA(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 EA(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 Uy(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${U(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
|
|
641
|
+
[${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 Jy=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","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"],IA=[Xh,ny,Zh,Ci,ty,oy,Gy,ey],Ky=IA.flat(),AA=new Map(Ky.map(e=>[e.id,e]));for(let e of Ky)if(!Jy.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var rn=Jy.map(e=>jA(e));function jA(e){let t=AA.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var OA=rn.slice(0,na("plan-context")),LA=rn.slice(Di("drift"),na("self-audit")),DA=rn.slice(Di("convergence"),na("slice")),MA=rn.slice(Di("redundant-reexports")),Cq=[{id:"reindex",command:"reindex",agent:w("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository"),description:"Index the codebase and convert to SQLite",options:T([p("-l, --language <lang>","Index only this language (can be repeated)",lt,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--trust-project-tools","Permit reviewed indexers from this repository for this run"),p("--install-missing","Install missing global tools at reviewed immutable versions for this run"),p("--indexer-concurrency <n>","Number of language indexers to run at once",Ze)]),renderShape:"custom",docs:P("Indexing",["scip-query reindex"]),handler:Sg},{id:"augment-sources",command:"augment-sources",agent:w("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository"),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:P("Indexing"),handler:vg},{id:"augment-vue",command:"augment-vue",agent:w("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository"),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:P("Indexing"),handler:Rg},...OA,{id:wt,command:wt,description:"Internal bounded diff-gate worker",hidden:!0,options:[p("--json","Emit the private worker envelope without transport pagination")],renderShape:"custom",handler:kg},{id:yn,command:yn,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--json","Emit the private worker envelope without transport pagination"),p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:xg},{id:"diff-impact",command:"diff-impact",agent:w("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Compute changed symbols and downstream consumers from current git diff",options:T([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:P("Impact"),handler:wg},...LA,{id:hn,command:hn,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("--json","Emit the private worker envelope without transport pagination"),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:$g},{id:"health",command:"health",agent:w("What are the highest-priority verified health problems in this codebase?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository"),description:"Composite codebase health report with prioritized action list",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")]),renderShape:"custom",docs:P("Health",["scip-query health --json","scip-query health --baseline"]),handler:Cg},{id:"bench",command:"bench",agent:w("How fast are indexing and selected commands under this benchmark matrix?","timings, command outcomes, environment, and optional profiles",[],"sampled","repository"),description:"Benchmark indexing and command runtimes for this repository",options:T([p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",lt,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",Ze,18e4),p("--progress","Print benchmark command start/finish progress to stderr"),p("--profile","Enable low-overhead phase profiling in benchmarked commands"),p("--profile-out <path>","Append benchmark and phase profile events as JSONL")]),renderShape:"custom",docs:P("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:Pg},{id:"work-audit",command:"work-audit <profile>",agent:w("Which repeated computations in this profile waste the most measured time?","ranked repeated-work groups, counts, and avoidable duration",["path"],"bounded"),description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:T([p("--top <n>","Maximum repeated-work groups to show",Ze,20)]),evidence:"mixed",renderShape:"custom",docs:P("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:Tg},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[p("-s, --scope <path>","Limit compared definitions to files matching path"),p("--limit <n>","Maximum definitions to compare unless --full is set",Ze),p("--max-mismatches <n>","Maximum mismatch details to include in output",qt),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:Eg},...DA,{id:"install-skills",command:"install-skills",agent:w("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository"),description:`Install skills (${Wr.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:P("Maintenance"),handler:Og},{id:"setup-hooks",command:"setup-hooks",agent:w("Were project-local agent hooks installed or removed safely?","hook config targets, changes, skips, and warnings",[],"complete","repository"),description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:T([p("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),p("--remove","Remove managed project hooks and remember the opt-out"),p("--force","Reinstall hooks even after a previous --remove opt-out"),p("--dry-run","With --remove, preview exact hook changes without writing")]),renderShape:"custom",docs:P("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:Lg},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:dp},{id:"hook-pretool",command:"hook-pretool",description:"Internal Claude PreToolUse evidence-integrity guard",hidden:!0,renderShape:"custom",handler:up},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:mp},{id:"check-deps",command:"check-deps",agent:w("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository"),description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:P("Maintenance"),handler:Dg},{id:"capabilities",command:"capabilities",agent:w("Which evidence and verification capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository"),description:"Report which evidence and verification capabilities are available in this project",options:T([p("--matrix","Render the project capability matrix (default output)")]),renderShape:"custom",docs:P("Maintenance"),handler:Mg},{id:"capability-matrix",command:"capability-matrix",agent:w("Which evidence and verification capabilities are available here?","deprecated alias of the capability matrix",[],"complete","repository"),description:"Deprecated alias for capabilities --matrix",options:T(),renderShape:"custom",docs:P("Maintenance"),handler:Ng},...MA,{id:"init",command:"init",agent:w("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository"),description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:P("Maintenance"),handler:_g},{id:"config-validate",command:"config-validate",agent:w("Is this project configuration valid and internally consistent?","validation diagnostics with config paths",[],"complete","repository"),description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:T(),renderShape:"custom",docs:P("Maintenance",["scip-query config-validate"]),handler:Bg},{id:"suppress",command:"suppress <id>",agent:w("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete"),description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:T([p("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),p("--reason-code <code>","Required adjudication code: compatibility-shim, generated-code, detector-counterexample, and related policies"),p("--evidence <kind:referent>","Required counterevidence; repeat source/config/test paths or exact graph commands",lt,[]),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires"),p("--replace <revision>","Replace a different existing decision only when it still has this reported SHA-256 revision")]),renderShape:"custom",docs:P("Maintenance",['scip-query suppress SQABC123DEF456 --reason-code compatibility-shim --evidence source:src/compat.ts --reason "v1 remains public"']),handler:qg},{id:"effectiveness",command:"effectiveness",agent:w("What handling outcomes has diff-gate observed, and what authority produced those observations?","per-check caught, fixed, suppressed, unresolved, provenance, and resolution-vs-suppression telemetry",[],"complete","repository"),description:"Per-check repository telemetry from the committed outcome ledger: verified fixes, suppressions, unresolved findings, observer authority, and anomalies",options:T([p("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),p("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:P("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:Vg},{id:"doctor",command:"doctor",agent:w("Why is scip-query unhealthy or unavailable in this project?","config, freshness, dependency, and capability diagnostics",[],"complete","repository"),description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:T(),renderShape:"custom",docs:P("Maintenance"),handler:Wg},{id:"setup",command:"setup",agent:w("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository"),description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:T([p("--guided","Require and open the interactive terminal checklist (the default in a terminal)"),p("--yes","Accept recommended setup defaults without prompting"),p("--git-hook","Also install a git pre-commit hook that runs diff-gate"),p("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),p("--no-skills","Skip user-level agent skill installation"),p("--no-parsers","Skip Tree-sitter AST parser installation and repair"),p("--install-missing","Install missing global tools at reviewed immutable versions"),p("--no-health","Skip the optional full health audit and dossier"),p("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:P("Maintenance",["scip-query setup","scip-query setup --install-missing","scip-query setup --json"]),handler:Ug},{id:"setup-agent",command:"setup-agent",agent:w("Can project agent guidance and optional git enforcement be seeded?","written, unchanged, and skipped agent files or hooks",[],"complete","repository"),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:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:P("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Gg},{id:"setup-ci",command:"setup-ci",agent:w("Can a CI workflow enforce reindex and diff-gate on pull requests?","workflow path, rendered content, and write outcome",[],"complete","repository"),description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:P("Maintenance",["scip-query setup-ci"]),handler:Jg},{id:"uninstall",command:"uninstall",agent:w("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository"),description:"Remove selected scip-query-owned integrations; real removal requires exactly one of --global or --project",options:T([p("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),p("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),p("--dry-run","List what would be removed without changing files"),p("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:P("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Kg},{id:"watch",command:"watch",agent:w("What is the watcher doing, or can its background service be started or stopped?","watcher/service state, generation, activity, and errors",[],"complete","repository"),description:"Watch in the foreground or manage the per-project background refresh service",options:T([p("--daemon","Ensure the demand-started background service is running; timing flags apply only at start"),p("--status","Show background/foreground watcher state"),p("--stop","Stop the watcher or background service for this project"),p("--debounce <ms>","Process-local ms to wait after last change (default: 250)",qt),p("--cooldown <ms>","Process-local min ms between reindexes; 0 disables spacing (default: 5000)",qt),p("--git-poll <ms>","Process-local ms between Git HEAD/index checks (default: 2000)",qt),p("--idle-timeout <ms>","Process-local ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",qt)]),renderShape:"custom",docs:P("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:zg},{id:"status",command:"status",agent:w("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, watcher, and optional capabilities",[],"complete","repository"),description:"Show index status for this project",options:T([p("--capabilities","Include the project capability matrix")]),renderShape:"custom",docs:P("Maintenance"),handler:Xg}];function Di(e){let t=rn.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function na(e){return Di(e)+1}export{Cq as commandDescriptors};
|
|
642
|
+
//# sourceMappingURL=command-descriptors-DSS46KXI.js.map
|