scip-query 0.24.0 → 0.26.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 +247 -1
- package/README.md +111 -124
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-PRVFAGTQ.js +2 -0
- package/dist/call-graph-DVPAQV2F.js +2 -0
- package/dist/{call-graph-evidence-BociKRpF.d.ts → call-graph-evidence-CUtj8V2I.d.ts} +1 -1
- package/dist/chunk-2FSBGL5P.js +2 -0
- package/dist/chunk-2HLAFUCY.js +2 -0
- package/dist/chunk-2IWUT6CJ.js +3 -0
- package/dist/chunk-2KNN7GTQ.js +2 -0
- package/dist/chunk-2LHXRE2B.js +8 -0
- package/dist/{chunk-E65ELFKU.js → chunk-2YXE77TJ.js} +2 -2
- package/dist/chunk-36SGVCGX.js +2 -0
- package/dist/chunk-3ABBFPTP.js +2 -0
- package/dist/chunk-3IVFU4FD.js +3 -0
- package/dist/chunk-3JIQS44J.js +7 -0
- package/dist/chunk-3ZRB6DNK.js +7 -0
- package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
- package/dist/{chunk-BHKK5RJY.js → chunk-4BHGBMNO.js} +2 -2
- package/dist/chunk-4BP3UBDG.js +2 -0
- package/dist/chunk-4D6RO7G4.js +2 -0
- package/dist/chunk-4FEWQ6RH.js +2 -0
- package/dist/chunk-4IGEOBG7.js +2 -0
- package/dist/chunk-4QZXBUKC.js +2 -0
- package/dist/chunk-4WBDEVX2.js +4 -0
- package/dist/chunk-4WCUBZU3.js +8 -0
- package/dist/chunk-4WTUBQ36.js +40 -0
- package/dist/chunk-4XQ4O6IM.js +3 -0
- package/dist/chunk-55UQAMZO.js +4 -0
- package/dist/chunk-5D2LVK7O.js +125 -0
- package/dist/chunk-5IYJ56TT.js +2 -0
- package/dist/chunk-5PLMJC7Q.js +2 -0
- package/dist/chunk-5TNQJUR2.js +5 -0
- package/dist/chunk-62BDNPMI.js +2 -0
- package/dist/chunk-64DZ5TXR.js +7 -0
- package/dist/chunk-65245JCM.js +2 -0
- package/dist/chunk-6FFVZZL4.js +2 -0
- package/dist/chunk-6KO5JHAR.js +2 -0
- package/dist/chunk-6LRXOOSX.js +2 -0
- package/dist/chunk-6LSEIIF7.js +2 -0
- package/dist/chunk-6YMNWD3H.js +6 -0
- package/dist/chunk-72AD6ZRR.js +5 -0
- package/dist/chunk-73AAKPUC.js +4 -0
- package/dist/chunk-76CZ77DF.js +2 -0
- package/dist/chunk-7VPEEAAG.js +2 -0
- package/dist/chunk-7WTPQ4NX.js +14 -0
- package/dist/chunk-7Y5T6XDP.js +2 -0
- package/dist/chunk-A2IIGFMJ.js +5 -0
- package/dist/chunk-AB5KCTEV.js +2 -0
- package/dist/chunk-AC566WBP.js +6 -0
- package/dist/chunk-AGWFSTXC.js +3 -0
- package/dist/chunk-AOSIYPTA.js +2 -0
- package/dist/chunk-AUVEWPIF.js +2 -0
- package/dist/chunk-B56T42J3.js +25 -0
- package/dist/chunk-BIQEF5NE.js +2 -0
- package/dist/chunk-BL6XJKTA.js +3 -0
- package/dist/chunk-BMKOQJRI.js +2 -0
- package/dist/chunk-BOZ4EXBB.js +3 -0
- package/dist/chunk-BUTWYEPH.js +2 -0
- package/dist/chunk-BZB4QPIP.js +2 -0
- package/dist/{chunk-6ILKOOGH.js → chunk-CE357GEE.js} +4 -4
- package/dist/chunk-CFN45HFP.js +2 -0
- package/dist/chunk-CFYMZFXT.js +368 -0
- package/dist/chunk-CN5EH7O3.js +2 -0
- package/dist/chunk-D254DNNQ.js +4 -0
- package/dist/chunk-D3FDISIC.js +2 -0
- package/dist/chunk-D3NX5XIE.js +3 -0
- package/dist/chunk-DA7RPPDF.js +3 -0
- package/dist/chunk-DDMC3FON.js +3 -0
- package/dist/chunk-DIO3FUSG.js +2 -0
- package/dist/chunk-DJ2NNSUK.js +3 -0
- package/dist/chunk-DKYQIM3C.js +18 -0
- package/dist/{chunk-OHIV323X.js → chunk-DOOEL2IV.js} +2 -2
- package/dist/chunk-DVFP6PZI.js +2 -0
- package/dist/chunk-E3FDPXZK.js +2 -0
- package/dist/chunk-E7YNJLCB.js +2 -0
- package/dist/chunk-EFGW5JPH.js +2 -0
- package/dist/chunk-EJVTR244.js +13 -0
- package/dist/chunk-EOV7RTRZ.js +2 -0
- package/dist/chunk-ETOIKRHO.js +2 -0
- package/dist/chunk-EYK3ZAO2.js +3 -0
- package/dist/chunk-F2V2LPET.js +52 -0
- package/dist/chunk-F4LUHJTF.js +2 -0
- package/dist/chunk-F4PUT6IT.js +2 -0
- package/dist/chunk-F56GCXXS.js +5 -0
- package/dist/chunk-FC2EVQRM.js +2 -0
- package/dist/chunk-FL7NBMHP.js +3 -0
- package/dist/chunk-FMRN2TRL.js +3 -0
- package/dist/chunk-FVULPZDF.js +20 -0
- package/dist/chunk-GCKCF5FL.js +43 -0
- package/dist/chunk-GH2PYF46.js +2 -0
- package/dist/chunk-GHJAGXIP.js +2 -0
- package/dist/{chunk-2GJSD5GY.js → chunk-GMVSHUKZ.js} +2 -2
- package/dist/chunk-GS6KDO4R.js +2 -0
- package/dist/chunk-GUUBXNN7.js +2 -0
- package/dist/chunk-GVWX5T43.js +80 -0
- package/dist/chunk-GZKFETP5.js +2 -0
- package/dist/chunk-H4EQHO6J.js +9 -0
- package/dist/chunk-H73WY2RM.js +2 -0
- package/dist/chunk-H75GSPRV.js +60 -0
- package/dist/chunk-HDR3AHSV.js +61 -0
- package/dist/chunk-HQBSL74Y.js +2 -0
- package/dist/chunk-HRRFKWPZ.js +2 -0
- package/dist/chunk-HXENDJC6.js +2 -0
- package/dist/chunk-IIBAZNSW.js +21 -0
- package/dist/chunk-INLMWEUU.js +12 -0
- package/dist/chunk-IWQPAF4F.js +2 -0
- package/dist/chunk-IZJ6YUKP.js +35 -0
- package/dist/chunk-J2TMAIN5.js +60 -0
- package/dist/chunk-J5FJMODQ.js +142 -0
- package/dist/chunk-J7HZPIO3.js +2 -0
- package/dist/chunk-JEVRKFRL.js +2 -0
- package/dist/chunk-JFXSGAEB.js +30 -0
- package/dist/chunk-JVRTHGFS.js +3 -0
- package/dist/chunk-JYWEX7RR.js +360 -0
- package/dist/chunk-K3YL22N6.js +2 -0
- package/dist/chunk-K4CN7GXK.js +12 -0
- package/dist/chunk-K5TBVXU4.js +30 -0
- package/dist/chunk-KDDIE2DP.js +9 -0
- package/dist/chunk-KHWRRPV4.js +2 -0
- package/dist/chunk-KI6NBKDY.js +14 -0
- package/dist/chunk-KU3QRSTH.js +2 -0
- package/dist/chunk-KZBJWZJB.js +2 -0
- package/dist/chunk-L7GFM3NP.js +3 -0
- package/dist/chunk-LMO6PK3V.js +35 -0
- package/dist/chunk-LN4YXJJU.js +2 -0
- package/dist/chunk-LOVIZBJ4.js +43 -0
- package/dist/chunk-LPCRK4A2.js +11 -0
- package/dist/chunk-MMHZKBFA.js +2 -0
- package/dist/{chunk-A4WEAK35.js → chunk-MOQQBQRD.js} +2 -2
- package/dist/chunk-N2WN6I3L.js +2 -0
- package/dist/chunk-N3ORQT7L.js +2 -0
- package/dist/chunk-NAZ3RAIW.js +2 -0
- package/dist/chunk-NDUNO5JQ.js +2 -0
- package/dist/chunk-NEIWRNAZ.js +4 -0
- package/dist/chunk-NJJMVD65.js +2 -0
- package/dist/chunk-NLOQOBXI.js +20 -0
- package/dist/chunk-NOLZOVCU.js +2 -0
- package/dist/chunk-NOWINRRN.js +2 -0
- package/dist/chunk-NZAXKGRL.js +16 -0
- package/dist/chunk-O2C4UILI.js +2 -0
- package/dist/chunk-O3RHA6ZT.js +3 -0
- package/dist/chunk-O4UZSPPI.js +3 -0
- package/dist/chunk-OGFV2BUX.js +2 -0
- package/dist/chunk-OZCJXZK6.js +499 -0
- package/dist/chunk-P6ODM7BY.js +2 -0
- package/dist/{chunk-GHNPACNP.js → chunk-PAVGPRHJ.js} +2 -2
- package/dist/chunk-PH52RA7D.js +2 -0
- package/dist/chunk-PKN354TH.js +3 -0
- package/dist/chunk-PWOASWEG.js +11 -0
- package/dist/chunk-QIWXRW72.js +2 -0
- package/dist/chunk-QJRMOK5N.js +2 -0
- package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
- package/dist/chunk-QXEUDXBT.js +3 -0
- package/dist/chunk-QYUVVBMR.js +6 -0
- package/dist/chunk-QZ7KQZRN.js +2 -0
- package/dist/chunk-R6LQBUDH.js +2 -0
- package/dist/chunk-RBS42E55.js +20 -0
- package/dist/chunk-RSJKPCFX.js +26 -0
- package/dist/chunk-S6CZA3MV.js +2 -0
- package/dist/chunk-STMVAHJP.js +2 -0
- package/dist/chunk-SYVPTTVW.js +2 -0
- package/dist/chunk-T6DK3ZP7.js +2 -0
- package/dist/chunk-TKD34PHN.js +4 -0
- package/dist/chunk-TNNQFH7W.js +2 -0
- package/dist/chunk-TNV7SSUF.js +2 -0
- package/dist/chunk-TO7ZR3EH.js +8 -0
- package/dist/chunk-TOU3CHK4.js +2 -0
- package/dist/chunk-TRBI4UKT.js +2 -0
- package/dist/chunk-TZCVNCAN.js +4 -0
- package/dist/chunk-U4LZA5LL.js +3 -0
- package/dist/chunk-U5RIG3JP.js +3 -0
- package/dist/chunk-UP5KXN2I.js +2 -0
- package/dist/chunk-UQFR3NDH.js +5 -0
- package/dist/chunk-UXYXF7GV.js +2 -0
- package/dist/chunk-VB3GOKOS.js +2 -0
- package/dist/{chunk-4FR6GQIT.js → chunk-VF5JZICY.js} +2 -2
- package/dist/chunk-VTY3VK6E.js +2 -0
- package/dist/chunk-VX2O4RIS.js +2 -0
- package/dist/chunk-WKPV2TDZ.js +2 -0
- package/dist/chunk-WOFQ5DTB.js +2 -0
- package/dist/chunk-WS4C6TCK.js +2 -0
- package/dist/chunk-WXU3DGPU.js +2 -0
- package/dist/{chunk-ATXPTSEI.js → chunk-X6RMKHJQ.js} +7 -7
- package/dist/{chunk-44IETFOU.js → chunk-XHMN6ZX7.js} +2 -2
- package/dist/chunk-XHTVFLWW.js +2 -0
- package/dist/chunk-XKIDJCIK.js +2 -0
- package/dist/chunk-XTYTYZPT.js +2 -0
- package/dist/chunk-Y2JHHTTA.js +2 -0
- package/dist/chunk-YGVRMGYN.js +4 -0
- package/dist/chunk-YNQCGEQE.js +2 -0
- package/dist/chunk-YOQVEXVE.js +14 -0
- package/dist/chunk-YRT2WLYY.js +2 -0
- package/dist/chunk-YTAP5Y2G.js +2 -0
- package/dist/chunk-YTYWI7VB.js +2 -0
- package/dist/chunk-YULZRALL.js +2 -0
- package/dist/chunk-Z33WQG4Q.js +2 -0
- package/dist/chunk-ZGTYGDMF.js +16 -0
- package/dist/chunk-ZHMRSZFD.js +43 -0
- package/dist/chunk-ZHSP366W.js +10 -0
- package/dist/chunk-ZIBYCYKK.js +7 -0
- package/dist/chunk-ZLADLUE6.js +3 -0
- package/dist/chunk-ZO4YXUT6.js +4 -0
- package/dist/{chunk-MZPXPSUJ.js → chunk-ZR4HBC2H.js} +2 -2
- package/dist/cli-main.js +6 -6
- package/dist/cli.js +1 -1
- package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
- package/dist/code-IL5WH3NZ.js +2 -0
- package/dist/code-result-json-ANTBEDFP.js +4 -0
- package/dist/command-descriptors-HEEMDHTU.js +222 -0
- package/dist/deps-EOWFC6FD.js +2 -0
- package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
- package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
- package/dist/files-K4AI3JUM.js +2 -0
- package/dist/{health-BI2a9WPy.d.ts → health-BtfmNrfa.d.ts} +5 -79
- package/dist/hierarchy-6W5NDIFI.js +2 -0
- package/dist/imports-WH365QY4.js +2 -0
- package/dist/index.d.ts +13 -1
- package/dist/index.js +1 -1
- package/dist/members-K3PHMF5S.js +2 -0
- package/dist/methods-E7KVMBX4.js +2 -0
- package/dist/output-continuation-command-BJSY67SN.js +3 -0
- package/dist/output-pagination-UZJ5ACIX.js +24 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-EP24WT4X.js +3 -0
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +15 -4
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -0
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +3 -3
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity.d.ts +6 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +1 -7
- package/dist/queries/context.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/dependence-slice.d.ts +46 -22
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.d.ts +1 -7
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +2 -4
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.d.ts +121 -61
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +1 -1
- 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 +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +1 -0
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +15 -64
- package/dist/queries/index.js +1 -1
- package/dist/queries/locality-candidates.d.ts +4 -4
- 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.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -6
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +4 -14
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +4 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/review.d.ts +188 -0
- package/dist/queries/review.js +2 -0
- package/dist/queries/similar-files.d.ts +7 -10
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +19 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice-cohesion.d.ts +205 -0
- package/dist/queries/slice-cohesion.js +2 -0
- package/dist/queries/source-inspection.d.ts +6 -202
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.d.ts +2 -3
- package/dist/queries/source-search.js +1 -1
- package/dist/queries/stats.d.ts +1 -0
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +4 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/twin-drift.d.ts +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +3 -15
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/query-service-fastpath.js +5 -5
- package/dist/query-service-server.js +4 -4
- package/dist/refs-CCBJG7WK.js +2 -0
- package/dist/refs-pagination-DRNLVU4S.js +2 -0
- package/dist/reindex-worker.js +79 -29
- package/dist/reindex.js +45 -45
- package/dist/repository-cache-worker.js +2 -0
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +3 -4
- 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/service-queries-2WAJI7R6.js +6 -0
- package/dist/source-inspection-91U9zdO3.d.ts +341 -0
- package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
- package/dist/stats-G7DIV6VU.js +2 -0
- package/dist/surface-IO55UALI.js +2 -0
- package/dist/system-ZBMSHJXU.js +2 -0
- package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
- package/dist/typescript-indexer.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +3 -3
- package/docs/AGENT_GUIDE.md +19 -128
- package/docs/CLI_JSON_OUTPUT.md +21 -17
- package/docs/COMMAND_REFERENCE.md +34 -49
- package/docs/CURRENT_COMMANDS.md +123 -0
- package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
- package/docs/DETECTOR_GUIDE.md +27 -23
- package/docs/PRODUCT_VISION.md +135 -0
- package/docs/PROPERTY_TESTING.md +73 -0
- package/docs/REVIEW.md +76 -0
- package/docs/SKILLS.md +51 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
- package/docs/accuracy-audit-checklist.md +34 -0
- package/docs/analyzer-inventory.md +2 -2
- package/package.json +18 -80
- package/scripts/evidence-product-contract.mjs +7 -3
- package/scripts/record-review-coverage.mjs +118 -0
- package/scripts/scip-windows-provenance.mjs +29 -19
- package/skills/scip-architecture-review/SKILL.md +57 -0
- package/skills/scip-architecture-review/agents/openai.yaml +4 -0
- package/skills/scip-architecture-review/references/design-checks.md +17 -0
- package/skills/scip-explore/SKILL.md +15 -59
- package/skills/scip-explore/agents/openai.yaml +3 -3
- package/skills/scip-explore/references/external-evidence.md +2 -2
- package/skills/scip-explore/references/information-model.md +26 -29
- package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
- package/skills/scip-integrity-audit/SKILL.md +53 -181
- package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
- package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
- package/skills/scip-plan/SKILL.md +39 -65
- package/skills/scip-plan/agents/openai.yaml +2 -2
- package/skills/scip-query/SKILL.md +28 -81
- package/skills/scip-query/agents/openai.yaml +2 -2
- package/skills/scip-query/references/command-guide.md +169 -0
- package/skills/scip-setup/SKILL.md +4 -2
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/dist/by-kind-H3P6BR5G.js +0 -2
- package/dist/call-graph-VTG2CUOQ.js +0 -2
- package/dist/chunk-26CT72HM.js +0 -2
- package/dist/chunk-2BMSSRBH.js +0 -2
- package/dist/chunk-2M2LSIMY.js +0 -7
- package/dist/chunk-2N6WBNDC.js +0 -29
- package/dist/chunk-2OOY75BW.js +0 -2
- package/dist/chunk-2USA3S3P.js +0 -3
- package/dist/chunk-2VAHDDLM.js +0 -133
- package/dist/chunk-2XWIUW5Z.js +0 -455
- package/dist/chunk-35NLDRZC.js +0 -2
- package/dist/chunk-3AF4TUFK.js +0 -3
- package/dist/chunk-3D4BOXW6.js +0 -20
- package/dist/chunk-3LO4FST5.js +0 -16
- package/dist/chunk-3WTY4LP2.js +0 -3
- package/dist/chunk-3Z5AMSK6.js +0 -29
- package/dist/chunk-4KBTHJLP.js +0 -2
- package/dist/chunk-5BIKR67W.js +0 -2
- package/dist/chunk-5PROPLHI.js +0 -2
- package/dist/chunk-5V7EPTII.js +0 -2
- package/dist/chunk-62LPZCBQ.js +0 -3
- package/dist/chunk-64O2JHQA.js +0 -2
- package/dist/chunk-6D4F5VWG.js +0 -10
- package/dist/chunk-6ERFBC3X.js +0 -3
- package/dist/chunk-6MFXCMZC.js +0 -2
- package/dist/chunk-6O7FACKB.js +0 -2
- package/dist/chunk-6TS3KOXR.js +0 -2
- package/dist/chunk-76QOU4PK.js +0 -3
- package/dist/chunk-7DUI77BN.js +0 -2
- package/dist/chunk-7F45LJKI.js +0 -2
- package/dist/chunk-7F7T6DCR.js +0 -2
- package/dist/chunk-7H6VHWWJ.js +0 -2
- package/dist/chunk-7HXT6YLU.js +0 -5
- package/dist/chunk-7KCZELVM.js +0 -2
- package/dist/chunk-7R4V5ES6.js +0 -6
- package/dist/chunk-7RIRIADH.js +0 -7
- package/dist/chunk-7ZLWLOGT.js +0 -2
- package/dist/chunk-AADQLOQ4.js +0 -38
- package/dist/chunk-AN76MGUE.js +0 -2
- package/dist/chunk-ANLNLY66.js +0 -2
- package/dist/chunk-AX7IDVFT.js +0 -2
- package/dist/chunk-B3X6KU75.js +0 -2
- package/dist/chunk-B7MPDEAK.js +0 -3
- package/dist/chunk-BBB5FBX4.js +0 -2
- package/dist/chunk-BJT7LSPK.js +0 -3
- package/dist/chunk-BJWFVAA5.js +0 -2
- package/dist/chunk-BKVWUP7Y.js +0 -2
- package/dist/chunk-BKZYTLGE.js +0 -35
- package/dist/chunk-BL6DCHQP.js +0 -2
- package/dist/chunk-BOW7SSQH.js +0 -43
- package/dist/chunk-C4RHHCKL.js +0 -7
- package/dist/chunk-C7C6AKAT.js +0 -117
- package/dist/chunk-CD6M6LS2.js +0 -16
- package/dist/chunk-CFE6PSG6.js +0 -2
- package/dist/chunk-CFNIGQMT.js +0 -2
- package/dist/chunk-CKBUBRYD.js +0 -2
- package/dist/chunk-CZW5MZ5B.js +0 -2
- package/dist/chunk-DBBZ63ZX.js +0 -2
- package/dist/chunk-DBN7DMJB.js +0 -18
- package/dist/chunk-DUULLZHZ.js +0 -3
- package/dist/chunk-DV5Y5NOS.js +0 -2
- package/dist/chunk-DZOIKCTM.js +0 -3
- package/dist/chunk-E4PKTOL3.js +0 -2
- package/dist/chunk-E7QR35ST.js +0 -2
- package/dist/chunk-EFSXAINW.js +0 -2
- package/dist/chunk-EHVEIEQN.js +0 -18
- package/dist/chunk-EHYDXE3Z.js +0 -2
- package/dist/chunk-EP63Y6LD.js +0 -2
- package/dist/chunk-EPX6NQN6.js +0 -4
- package/dist/chunk-ETC674NS.js +0 -5
- package/dist/chunk-F5GSBHC6.js +0 -3
- package/dist/chunk-FH3DGXC6.js +0 -2
- package/dist/chunk-FI7VGOR4.js +0 -16
- package/dist/chunk-FJF6VO2P.js +0 -2
- package/dist/chunk-FLMTCX5R.js +0 -2
- package/dist/chunk-FVFDOIM3.js +0 -2
- package/dist/chunk-G2HU5WRN.js +0 -2
- package/dist/chunk-G4ALYS4J.js +0 -2
- package/dist/chunk-G56I7K4W.js +0 -26
- package/dist/chunk-GC4DG2V5.js +0 -2
- package/dist/chunk-GG45PK4S.js +0 -4
- package/dist/chunk-GINH3YQU.js +0 -20
- package/dist/chunk-GTZZVLKJ.js +0 -2
- package/dist/chunk-GXXW5ZHH.js +0 -2
- package/dist/chunk-H5EXS3HM.js +0 -2
- package/dist/chunk-HAXXKRTD.js +0 -4
- package/dist/chunk-HEZWBAZY.js +0 -2
- package/dist/chunk-HMEWLMML.js +0 -2
- package/dist/chunk-HOBOVYPO.js +0 -11
- package/dist/chunk-HRFQ6GW5.js +0 -8
- package/dist/chunk-HX4X7KG3.js +0 -2
- package/dist/chunk-HYT2R7LX.js +0 -4
- package/dist/chunk-IKQVBVQL.js +0 -40
- package/dist/chunk-IW5XQG5G.js +0 -2
- package/dist/chunk-J6GLBBRK.js +0 -4
- package/dist/chunk-J7A4PWFX.js +0 -3
- package/dist/chunk-JCSAZ35V.js +0 -2
- package/dist/chunk-JDU2IV3A.js +0 -2
- package/dist/chunk-JFMEXGFE.js +0 -2
- package/dist/chunk-JFMI5SGB.js +0 -4
- package/dist/chunk-JJP37RGX.js +0 -57
- package/dist/chunk-JZ2A7LDM.js +0 -5
- package/dist/chunk-KMVGRIO2.js +0 -2
- package/dist/chunk-KNLQGXVH.js +0 -80
- package/dist/chunk-KVQCECPR.js +0 -2
- package/dist/chunk-KXXORBZ2.js +0 -4
- package/dist/chunk-L5KYH6U3.js +0 -35
- package/dist/chunk-L6XHYJPZ.js +0 -21
- package/dist/chunk-L7KTFEAV.js +0 -43
- package/dist/chunk-LDXHR5EL.js +0 -23
- package/dist/chunk-LEECKFCJ.js +0 -2
- package/dist/chunk-MHGDSBFX.js +0 -2
- package/dist/chunk-MLQVVDG3.js +0 -74
- package/dist/chunk-MOKUWRHO.js +0 -3
- package/dist/chunk-MPYAPMNE.js +0 -2
- package/dist/chunk-MTDBHTSF.js +0 -2
- package/dist/chunk-MV6SPXCR.js +0 -7
- package/dist/chunk-MWN53KRN.js +0 -60
- package/dist/chunk-MXNGIEPU.js +0 -3
- package/dist/chunk-N55KIE46.js +0 -2
- package/dist/chunk-NB4D3BNM.js +0 -2
- package/dist/chunk-NGKBOT6G.js +0 -23
- package/dist/chunk-NJGKXKQF.js +0 -2
- package/dist/chunk-NJQISBL4.js +0 -8
- package/dist/chunk-NJT3ZEKY.js +0 -16
- package/dist/chunk-NKMKZP6A.js +0 -2
- package/dist/chunk-NODFZ6ED.js +0 -2
- package/dist/chunk-NSM5IEVW.js +0 -2
- package/dist/chunk-NTGUVNR2.js +0 -3
- package/dist/chunk-NU3KFF2O.js +0 -57
- package/dist/chunk-NWLVNU66.js +0 -557
- package/dist/chunk-NYKZMCRC.js +0 -4
- package/dist/chunk-O6BUXZEH.js +0 -6
- package/dist/chunk-ODPDP7A4.js +0 -3
- package/dist/chunk-OIAPEKMT.js +0 -3
- package/dist/chunk-OIOC5EHF.js +0 -3
- package/dist/chunk-ONPPQM4G.js +0 -2
- package/dist/chunk-OUHEZBYI.js +0 -2
- package/dist/chunk-OVGYW7UD.js +0 -29
- package/dist/chunk-OYKU4B3Y.js +0 -2
- package/dist/chunk-POBJ6FR2.js +0 -5
- package/dist/chunk-PSZPMMWN.js +0 -2
- package/dist/chunk-PXTRBKRK.js +0 -3
- package/dist/chunk-Q5JRIHT3.js +0 -4
- package/dist/chunk-Q7ATHARX.js +0 -2
- package/dist/chunk-Q7CSKIDM.js +0 -5
- package/dist/chunk-QBQE7ZJ5.js +0 -3
- package/dist/chunk-QH22UIXP.js +0 -5
- package/dist/chunk-QXCKQTKR.js +0 -60
- package/dist/chunk-RBAD4GJ2.js +0 -13
- package/dist/chunk-RMDPFPNW.js +0 -2
- package/dist/chunk-ROPJDEJZ.js +0 -4
- package/dist/chunk-RVZC6TJE.js +0 -2
- package/dist/chunk-S4QZBKSR.js +0 -3
- package/dist/chunk-SCPMZ73U.js +0 -2
- package/dist/chunk-SIAP5RGI.js +0 -73
- package/dist/chunk-SIX4RFR3.js +0 -3
- package/dist/chunk-SKKXTABJ.js +0 -16
- package/dist/chunk-SSRFUQBD.js +0 -2
- package/dist/chunk-SYVJEEUJ.js +0 -3
- package/dist/chunk-T3CZAZSI.js +0 -8
- package/dist/chunk-T6DWDI5E.js +0 -3
- package/dist/chunk-T6HRIROJ.js +0 -7
- package/dist/chunk-TAA7HXHE.js +0 -2
- package/dist/chunk-TJ2JQYT3.js +0 -2
- package/dist/chunk-TULNMD5T.js +0 -368
- package/dist/chunk-U2FPY5XA.js +0 -3
- package/dist/chunk-U3SXIMII.js +0 -38
- package/dist/chunk-U6KCHXJ4.js +0 -2
- package/dist/chunk-UH3XSKS5.js +0 -9
- package/dist/chunk-UIFUZVCC.js +0 -2
- package/dist/chunk-UXKURIVI.js +0 -2
- package/dist/chunk-V2RBODHL.js +0 -2
- package/dist/chunk-VBKUWB6N.js +0 -2
- package/dist/chunk-VBV6ALJE.js +0 -2
- package/dist/chunk-VDGFWCQV.js +0 -2
- package/dist/chunk-VDSDOEWF.js +0 -2
- package/dist/chunk-VZPWVCLN.js +0 -20
- package/dist/chunk-WDSFQDPN.js +0 -2
- package/dist/chunk-WFA35BGR.js +0 -7
- package/dist/chunk-WLMP3OCW.js +0 -2
- package/dist/chunk-WSA52GOR.js +0 -2
- package/dist/chunk-WYPL7GF7.js +0 -2
- package/dist/chunk-X3YVZAKZ.js +0 -5
- package/dist/chunk-X6OGVFIT.js +0 -2
- package/dist/chunk-XDAUYDFT.js +0 -2
- package/dist/chunk-XKXTR6ZI.js +0 -9
- package/dist/chunk-Y5DFAW5W.js +0 -4
- package/dist/chunk-YSYPDRD5.js +0 -3
- package/dist/chunk-ZFVPWH62.js +0 -5
- package/dist/chunk-ZGIHTH27.js +0 -2
- package/dist/chunk-ZGIQN2SX.js +0 -2
- package/dist/chunk-ZHG4WAHR.js +0 -12
- package/dist/chunk-ZKB2XUEN.js +0 -4
- package/dist/chunk-ZLMXIQLC.js +0 -21
- package/dist/chunk-ZMCQIHI4.js +0 -2
- package/dist/code-TAVIKWJI.js +0 -2
- package/dist/code-result-json-5FEFQCAQ.js +0 -2
- package/dist/command-descriptors-7BKH53Y3.js +0 -343
- package/dist/dataflow-GFBTVDH3.js +0 -2
- package/dist/dependence-slice-GWGQCODG.js +0 -2
- package/dist/deps-4QHVDPYA.js +0 -2
- package/dist/direct-navigation-4UBC6HNW.js +0 -3
- package/dist/entry-map-QCTF4RVY.js +0 -2
- package/dist/files-M2UBF5HJ.js +0 -2
- package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
- package/dist/hierarchy-2UIHRLW4.js +0 -2
- package/dist/imports-WIE3YZOB.js +0 -2
- package/dist/members-YKD636DA.js +0 -2
- package/dist/methods-VDF4IMYG.js +0 -2
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
- package/dist/output-continuation-command-4UMDOOLO.js +0 -3
- package/dist/output-pagination-2GME6OPY.js +0 -19
- package/dist/project-reindex-XEQTRCV5.js +0 -3
- package/dist/queries/anchors.d.ts +0 -123
- package/dist/queries/anchors.js +0 -2
- package/dist/queries/complexity-hotspots.d.ts +0 -40
- package/dist/queries/complexity-hotspots.js +0 -2
- package/dist/queries/convergence.d.ts +0 -33
- package/dist/queries/convergence.js +0 -2
- package/dist/queries/dataflow.d.ts +0 -77
- package/dist/queries/dataflow.js +0 -2
- package/dist/queries/deep-chains.d.ts +0 -5
- package/dist/queries/deep-chains.js +0 -2
- package/dist/queries/extract-candidates.d.ts +0 -79
- package/dist/queries/extract-candidates.js +0 -2
- package/dist/queries/isolated.d.ts +0 -24
- package/dist/queries/isolated.js +0 -2
- package/dist/queries/plan-context.d.ts +0 -33
- package/dist/queries/plan-context.js +0 -2
- package/dist/queries/reference-neighborhood.d.ts +0 -4
- package/dist/queries/reference-neighborhood.js +0 -2
- package/dist/queries/reference-reachability.d.ts +0 -48
- package/dist/queries/reference-reachability.js +0 -2
- package/dist/queries/self-audit.d.ts +0 -69
- package/dist/queries/self-audit.js +0 -2
- package/dist/queries/similar-chains.d.ts +0 -48
- package/dist/queries/similar-chains.js +0 -2
- package/dist/queries/slice.d.ts +0 -4
- package/dist/queries/slice.js +0 -2
- package/dist/queries/stale-abstractions.d.ts +0 -72
- package/dist/queries/stale-abstractions.js +0 -2
- package/dist/queries/system-map.d.ts +0 -449
- package/dist/queries/system-map.js +0 -2
- package/dist/queries/trace.js +0 -2
- package/dist/queries/twin-ab.d.ts +0 -66
- package/dist/queries/twin-ab.js +0 -2
- package/dist/queries/value-flow.d.ts +0 -43
- package/dist/queries/value-flow.js +0 -2
- package/dist/queries/wrapper-candidates.d.ts +0 -49
- package/dist/queries/wrapper-candidates.js +0 -2
- package/dist/refs-JNK5CLM7.js +0 -2
- package/dist/refs-pagination-6BLRYGMV.js +0 -2
- package/dist/slice-PHPVNCWX.js +0 -2
- package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
- package/dist/stats-OOJ74B32.js +0 -2
- package/dist/surface-MQX5MPIV.js +0 -2
- package/dist/symbol-resolution-DBLVXLBC.js +0 -2
- package/dist/system-JOPKV4OG.js +0 -2
- package/dist/trace-I2P2YFH4.js +0 -2
- package/dist/value-flow-JJVMF7NP.js +0 -2
- package/skills/concrete-plan/SKILL.md +0 -8
- package/skills/concrete-plan/agents/openai.yaml +0 -4
- package/skills/conductor/SKILL.md +0 -110
- package/skills/conductor/agents/openai.yaml +0 -4
- package/skills/principal-maintainability-review/SKILL.md +0 -273
- package/skills/principal-maintainability-review/agents/openai.yaml +0 -4
- package/skills/scip-calibrate/SKILL.md +0 -102
- package/skills/scip-calibrate/agents/openai.yaml +0 -4
- package/skills/scip-claim-audit/SKILL.md +0 -113
- package/skills/scip-claim-audit/agents/openai.yaml +0 -4
- package/skills/scip-probe-reachability/SKILL.md +0 -93
- package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
- package/skills/scip-root-cause/SKILL.md +0 -160
- package/skills/scip-root-cause/agents/openai.yaml +0 -4
- package/skills/scip-system-compression/SKILL.md +0 -252
- package/skills/scip-system-compression/agents/openai.yaml +0 -4
- package/skills/scip-system-compression/references/compression-atlas.md +0 -116
- package/skills/scip-system-compression/references/compression-patterns.md +0 -87
- package/skills/scip-twin-drift/SKILL.md +0 -109
- package/skills/scip-twin-drift/agents/openai.yaml +0 -4
|
@@ -1,343 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as pc,b as mc,c as hc,d as fc,e as Di,f as gc,g as nn,h as yc,i as bc,l as vc,m as Lt,n as Dn,o as qn,p as Sc,r as wc,s as $c,t as Rc,u as xc,v as Cc,w as kc,x as Ec,z as Fn}from"./chunk-U2FPY5XA.js";import{a as Wa}from"./chunk-44IETFOU.js";import"./chunk-3D4BOXW6.js";import{a as U,b as S,c as ze,d as pe,e as Oe,f as u,g as ji,h as _a,i as x,j as R,k as Je,l as Ba,m as X,n as Ga,o as st,p as C,q as be,r as Pt,s as Xt,t as Mi,u as Zt,v as en,w as de,x as me,y as Ae,z as Xa}from"./chunk-OVGYW7UD.js";import{A as b,B as O,C as k,D,E as Ja,F as P,G as Ya,H as le,a as ye,b as z,i as Z,j as te,k as Va,l as Ua,m as Ha,n as ft,o as Ni,p as Qa,q as Fe,r as Ka,s as Ie,t as Ln,u as za,v as M,x as H,y as w,z as K}from"./chunk-DUULLZHZ.js";import{$ as ns,$a as ia,$b as La,A as In,Aa as Is,B as Nr,Ba as As,C as ot,Ca as Ps,Cb as qe,D as Ii,Da as Ls,Db as Pi,E as Or,Ea as js,F as Dr,Fa as Ms,G as Ai,Ga as Ns,H as qr,Ha as Os,Hb as Ca,I as Fr,Ia as Ds,Ib as Ne,J as Wr,Ja as qs,Jb as ka,K as _r,Ka as Fs,L as Br,La as Ws,Lb as ce,M as Gr,Ma as _s,Mb as Ea,N as Vr,Na as Bs,O as Ur,Oa as Gs,P as Hr,Pa as Vs,Q as Qr,Qa as Us,R as Kr,Ra as Hs,S as zr,Sa as Qs,Sb as Aa,T as Jr,Ta as Ks,U as Yr,Ua as zs,V as Xr,Va as Js,W as Zr,Wa as Xs,Wb as Pa,X as It,Xa as Zs,Xb as Pn,Y as $t,Ya as ea,Yb as j,Z as es,Za as ta,Zb as ge,_ as ts,_a as na,_b as V,a as yn,aa as is,ab as oa,ac as A,b as Vt,ba as os,bb as ra,bc as Kt,c as sr,ca as rs,cb as sa,cc as zt,d as ar,da as ss,db as ca,dc as Jt,e as Ut,ea as as,ec as rt,f as lr,fa as cs,fb as la,g as dr,ga as ls,gb as At,gc as ja,h as ur,ha as ds,hb as Ee,hc as Ma,i as pr,ia as us,ib as Rt,ic as Na,j as kn,ja as ps,jb as Ke,jc as Oa,k as Rr,ka as ms,kb as da,kc as Da,l as Tn,la as hs,lb as ua,lc as qa,m as kr,ma as fs,mb as pa,n as Er,na as gs,nb as ma,o as Tr,oa as ys,p as Ht,pa as bs,pb as Te,pc as ht,qa as vs,qb as ga,qc as Yt,ra as Ss,rb as ya,s as Ir,sa as ws,sb as ba,sc as Fa,t as Ar,ta as $s,tb as va,u as Pr,ua as Rs,ub as Sa,v as Lr,va as xs,vb as wa,vc as Li,w as jr,wa as Cs,wb as $a,x as Mr,xa as ks,xb as Ra,ya as Es,yb as xa,z as Qt,za as Ts,zb as ue}from"./chunk-NWLVNU66.js";import{a as Za,b as ec,c as jn,d as tn,e as Oi,f as tc,g as nc,h as ic,i as Mn,j as oc,k as rc,l as Nn,m as sc,n as On,o as ac,p as cc,q as lc,r as dc,s as uc,t as Tc}from"./chunk-TULNMD5T.js";import{A as Vo,C as Uo,Cb as wt,Db as nr,Dd as it,Ff as Ta,Ga as Gt,Gf as Ia,H as Ho,Ha as vi,Ja as er,K as bi,Kc as Sn,L as Qo,Ne as Ys,Ob as vn,P as Ko,Pb as ir,Pd as $n,Qb as Si,Qd as Rn,Rd as mr,S as zo,Sd as xn,Td as He,Ud as ke,Ue as Qe,Vd as hr,Xd as Cn,Yd as wi,Ye as aa,Zd as $i,Ze as An,_ as Ve,a as yi,aa as Jo,ae as Ri,ba as Yo,bb as tr,be as xi,c as Bo,ce as fr,dd as cr,de as Ci,ea as Ue,ed as wn,fb as bn,fc as or,fe as gr,ga as Xo,ge as yr,he as br,ib as ie,ie as vr,jb as Se,je as ki,ke as Ei,l as bt,le as Ti,m as Go,me as Sr,n as Tt,o as vt,oe as wr,of as ha,pa as St,pf as fa,qe as En,re as $r,t as fe,u as ae,vc as oe,ve as xr,wc as rr,we as Cr,xa as Zo}from"./chunk-2XWIUW5Z.js";import{existsSync as Wn,mkdirSync as jm,symlinkSync as Mm,readlinkSync as qi,unlinkSync as Fi,readdirSync as Ic}from"fs";import{join as Ye,dirname as on,resolve as gt,relative as Nm,isAbsolute as Om}from"path";import{homedir as Ac,platform as Dm}from"os";import{fileURLToPath as Pc}from"url";var qm=Dm()==="win32",Lc=["scip-query","scip-explore","scip-plan","scip-setup","scip-integrity-audit","principal-maintainability-review","scip-system-compression","scip-root-cause","scip-claim-audit","scip-probe-reachability","scip-twin-drift","scip-calibrate","conductor"];var jc=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","principal-maintainability-review","scip-system-compression","scip-root-cause","scip-claim-audit","scip-probe-reachability","scip-twin-drift","scip-calibrate","conductor","concrete-plan"];function _n(e={}){let t=e.quiet?()=>{}:console.log,n=Pc(import.meta.url),i=gt(on(n),"..","skills"),o=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Ac(),r=[Ye(o,".claude","skills"),Ye(o,".codex","skills"),Ye(o,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of r){let c=on(a);if(!Wn(c))continue;jm(a,{recursive:!0});let l=Oc(a);Fm(a,i,l,s,t);for(let d of jc){let m=Ye(i,d),h=Ye(a,d);if(!Wn(m)){s.skipped.push(`${l}/${d}`);continue}if(Wn(h)){try{let p=qi(h);if(gt(p)===gt(m)){s.alreadyLinked.push(`${l}/${d}`),t(` ok: ${d} \u2192 ${l} (already linked)`);continue}}catch{s.skipped.push(`${l}/${d}`),t(` skip: ${d} \u2192 ${l} (exists, not a symlink)`);continue}Fi(h)}Mm(m,h,qm?"junction":"dir"),s.installed.push(`${l}/${d}`),t(` done: ${d} \u2192 ${l}`)}}return s}function Fm(e,t,n,i,o){let r=new Set(jc);for(let s of Ic(e)){if(r.has(s))continue;let a=Ye(e,s),c;try{c=gt(on(a),qi(a))}catch{continue}Nc(c,t)&&(Fi(a),i.pruned.push(`${n}/${s}`),o(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Mc(e={}){let t=Pc(import.meta.url),n=gt(on(t),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Ac(),o=[Ye(i,".claude","skills"),Ye(i,".codex","skills"),Ye(i,".agents","skills")],r={removed:[],left:[],skipped:[]};for(let s of o){if(!Wn(s))continue;let a=Oc(s);for(let c of Ic(s)){let l=Ye(s,c),d;try{let m=qi(l);d=gt(on(l),m)}catch{r.left.push(`${a}/${c} (not a symlink)`);continue}if(!Nc(d,n)){r.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(r.removed.push(`${a}/${c}`),!e.dryRun)try{Fi(l)}catch(m){r.skipped.push(`${a}/${c} (${m instanceof Error?m.message:String(m)})`)}}}return r}function Nc(e,t){let n=Nm(gt(t),gt(e));return n===""||!n.startsWith("..")&&!Om(n)}function Oc(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as ln}from"fs";import{dirname as Vy,join as Md}from"path";import{execFileSync as Eh}from"child_process";import{createRequire as Wm}from"module";var _m=Wm(import.meta.url);function Dc(e,t=[]){let n=Bm(),i=Rr(e,t),o=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i,reason:"ts-morph is not installed"}}function Bm(){try{return _m.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as rn,spawnSync as Gm}from"child_process";import{existsSync as We,mkdtempSync as Vm,readdirSync as Um,rmSync as qc,symlinkSync as Hm,writeFileSync as Qm}from"fs";import{tmpdir as Km}from"os";import{join as we}from"path";var zm=3e5,Jm=12,Bc=3e4,_i=1024*1024,Ym={readWorkingTreeStatus(e){return rn("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:Bc,maxBuffer:_i,killSignal:"SIGKILL"})}};function Gc(e,t,n={}){let i=ah(e,n.workingTreeRuntime),o=i.state==="known"?i.files:[],r=sh(t,i),s=Bi(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:[]};let a=th(t,s),c=n.timeoutMs??zm,l=[],d=new Map,m;try{m=Uc(e,"scip-cleanup-verify-")}catch(h){return{checkers:s.map(p=>p.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,unavailableReason:dh(h),batches:[]}}try{lh(e,m.root);for(let h of s)d.set(h.label,Wc(h,m.root,c).rawErrors);for(let h of t.batches){Hc(m.root,h);let p=null;for(let f of s){let g=Wc(f,m.root,c),y=Xm(g,d.get(f.label)??[],g.rawErrors);if(y.status==="failed"){let v=y.errors.length>0?y.errors:g.outputTail;p={depth:h.depth,status:"failed",reason:`${f.label}: ${y.reason}`,errors:v.slice(0,Jm)};break}}if(!p)l.push({depth:h.depth,status:"verified"});else{l.push(p);break}}}finally{m.dispose()}return{checkers:s.map(h=>h.label),uncoveredFiles:a,baselineErrors:[...d.values()].reduce((h,p)=>h+p.length,0),workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:l}}function Xm(e,t,n){let i=Zm(t,n);return i.length>0?{status:"failed",reason:"checker reported new errors",errors:i}: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 Zm(e,t){let n=eh(e),i=new Map,o=[];for(let r of t){let s=Vc(r),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&o.push(r)}return o}function eh(e){let t=new Map;for(let n of e){let i=Vc(n);t.set(i,(t.get(i)??0)+1)}return t}function th(e,t){let n=new Set(t.flatMap(o=>o.coversExtensions));return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>{let r=o.slice(o.lastIndexOf("."));return!n.has(r)}).sort()}function Vc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Fc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],nh=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Bi(e){let t=[];if(We(we(e,"tsconfig.json"))){let n=we(e,"node_modules",".bin","tsc");t.push(We(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Fc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Fc,strength:"reference-aware"})}if(We(we(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=>We(we(e,n)))){let n=ih();n&&t.push(n)}if(nh.some(n=>We(we(e,n)))){let n=oh(e);n&&t.push(n)}for(let n of rh(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:we(e,n,"..","target")}});return t}function ih(){return it("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"}:it("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function oh(e){let t=we(e,"node_modules",".bin","clj-kondo");return We(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:it("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:it("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:null}function rh(e){let t=[];if(We(we(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Um(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||We(we(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function sh(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>n.has(o)).sort()}function ah(e,t=Ym){try{return{state:"known",files:t.readWorkingTreeStatus(e).split(`
|
|
3
|
-
`).map(i=>i.slice(3).trim()).filter(i=>i!=="").sort()}}catch(n){return{state:"unavailable",reason:ch(n)}}}function ch(e){let t=e&&typeof e=="object"?e:{};if(t.code==="ETIMEDOUT"||t.killed===!0)return`git status timed out after ${Bc}ms`;if(t.code==="ENOBUFS"||typeof t.message=="string"&&/maxBuffer|stdout.*buffer/i.test(t.message))return`git status exceeded its ${_i}-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 lh(e,t){for(let n of["node_modules"]){let i=we(e,n),o=we(t,n);if(We(i)&&!We(o))try{Hm(i,o,"junction")}catch{}}}function Uc(e,t){let n=Vm(we(Km(),t)),i=we(n,"checkout");try{let o=rn("git",["-C",e,"rev-parse","--verify","HEAD"],{encoding:"utf-8",timeout:3e4,maxBuffer:_i,killSignal:"SIGKILL"}).trim();return rn("git",["clone","--quiet","--no-checkout","--shared","--",e,i],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),rn("git",["-C",i,"checkout","--quiet","--detach","--force",o],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),{root:i,dispose(){qc(n,{recursive:!0,force:!0})}}}catch(o){throw qc(n,{recursive:!0,force:!0}),o}}function dh(e){let t=e;return t?.code==="ETIMEDOUT"||t?.killed===!0?"isolated HEAD snapshot timed out after 30000ms":typeof t?.signal=="string"&&t.signal!==""?`isolated HEAD snapshot was terminated by ${t.signal}`:typeof t?.status=="number"?`isolated HEAD snapshot failed because Git exited with status ${t.status}`:"isolated HEAD snapshot failed; confirm that Git can read the repository and committed HEAD"}function Hc(e,t){let n=new Map;for(let i of t.entries){let o=n.get(i.file)??[];o.push({start:i.startLine,end:i.endLine}),n.set(i.file,o)}for(let[i,o]of n){let r=we(e,i);if(!We(r))continue;let s=fe(r,{maxBytes:vt,inputKind:"cleanup verification source file"});Qm(r,mh(s,o,{rust:i.endsWith(".rs")}))}}function uh(e,t={}){let n=e.flatMap(i=>i.entries.map(o=>({batch:i.depth,file:o.file,startLine:o.startLine,endLine:o.endLine,loc:o.loc,symbol:o.shortName})));return{dryRun:t.dryRun===!0,batches:e.length,symbols:n.length,loc:e.reduce((i,o)=>i+o.loc,0),files:[...new Set(n.map(i=>i.file))],filesEmptied:[...new Set(e.flatMap(i=>i.filesEmptied))],targets:n}}function ph(e,t,n={}){let i=uh(t,n);if(!i.dryRun)for(let o of t)Hc(e,o);return i}function Qc(e,t){let n=Uc(e,"scip-cleanup-patch-");try{return ph(n.root,t),rn("git",["-C",n.root,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{n.dispose()}}function Kc(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function zc(e,t,n={}){if(e.unavailableReason)return[`Cleanup verification is unavailable: ${e.unavailableReason}.`];let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowUnknownWorkingTree&&e.workingTree.state==="unavailable"&&i.push(`Working-tree inspection is unavailable: ${e.workingTree.reason}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let o=new Set(e.batches.filter(r=>r.status==="verified").map(r=>r.depth));for(let r of t)o.has(r.depth)||i.push(`Batch ${r.depth} is not verified by the detected checker(s).`);return i}function mh(e,t,n={}){let i=e.split(`
|
|
4
|
-
`),o=(n.rust===!0?hh(e):nr(e)).split(`
|
|
5
|
-
`),r=new Set;for(let s of t){let a=fh(i,s.start),c=yh(o,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)r.add(l)}return i.filter((s,a)=>!r.has(a)).join(`
|
|
6
|
-
`)}function hh(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 fh(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var gh=200;function yh(e,t,n){let i=0;for(let o=t;o<e.length;o++){for(let r of e[o]??"")r==="("||r==="["||r==="{"?i+=1:(r===")"||r==="]"||r==="}")&&(i-=1);if(o>=n&&i<=0)return o;if(o-n>gh)break}return n}function Wc(e,t,n){let i=Gm(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),o=`${i.stdout??""}
|
|
7
|
-
${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:_c(o)};let r=bh(e.label,o),s=r.diagnostics.length>0?r.diagnostics:i.error?[{file:"",message:String(i.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:i.status,rawErrors:s.map(kh),diagnostics:s,parseBasis:r.parseBasis,outputTail:_c(o)}}function bh(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:vh(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Sh(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=wh(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:$h(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Rh(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:xh(t),parseBasis:"clj-kondo-json"}:{diagnostics:Ch(t),parseBasis:"heuristic"}}function vh(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"tsc"});return t}function Sh(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),message:i[4]??"",parseBasis:"go"});return t}function wh(e){let t=Jc(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=i,r=o.location,s=r&&typeof r=="object"?r:{},a=typeof o.filename=="string"?o.filename:"",c=typeof o.message=="string"?o.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 o.code=="string"?o.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function $h(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"ruff-text"});return t}function Rh(e){let t=[];for(let n of e.split(`
|
|
8
|
-
`)){if(!n.trim().startsWith("{"))continue;let i=Wi(n);if(!i||typeof i!="object")continue;let o=i;if(o.reason!=="compiler-message")continue;let r=o.message;if(!r||typeof r!="object")continue;let s=r;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(m=>!!m&&typeof m=="object"&&m.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 xh(e){let t=Jc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!o||typeof o!="object")continue;let r=o;r.level==="error"&&i.push({file:typeof r.filename=="string"?r.filename:"",line:typeof r.row=="number"?r.row:void 0,column:typeof r.col=="number"?r.col:void 0,code:typeof r.type=="string"?r.type:void 0,message:typeof r.message=="string"?r.message:"",parseBasis:"clj-kondo-json"})}return i}function Ch(e){return e.split(`
|
|
9
|
-
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function kh(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 Jc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Wi(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?Wi(t.slice(n)):null}function Wi(e){try{return JSON.parse(e)}catch{return null}}function _c(e,t=10){return e.split(`
|
|
10
|
-
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Zc={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"]},Th={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"},Ih={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 Xe(e,t){let n=t.languages??An(e),i=n.map(a=>{let c=$n(Mn(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),o=_h(e,n,t),r=Vi({semantics:o},"typescript"),s=Bi(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:o,semantic:r,checkers:s,gitAvailable:Vh(e)}}function jt(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",o=i!=="unavailable",r=e.languages.map(c=>qh(e,c,{hasIndexedGraph:Fh(c,t),runtimeProbe:t.runtimeProbe})),s=r.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:r,relations:Ah(r,o),capabilities:[{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="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.`},...Mh(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"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"?r.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-impact",label:"Git change mapping",status:e.gitAvailable&&o?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-symbol and downstream-consumer mapping.":"Git is unavailable or the project root is not a git worktree."}]}}function Ah(e,t){return pc.map(n=>{let i=Nr.flatMap(r=>{let s=r.relations.filter(a=>a.family===n.family);return s.length===0?[]:[Ph(r,s,e,t)]}),o=Gi(i.map(r=>r.status));return{...n,status:o,providerCapabilities:i,reason:o==="unsupported"?t?"The current project has no available provider for this relationship family.":"An indexed graph is required before this relationship family can be queried.":o==="exact"?"Exact within indexed compiler/source identity coverage; dynamic or unindexed constructs remain outside scope.":"Supported by bounded static providers; unresolved and unsupported constructs remain explicitly reported."}})}function Ph(e,t,n,i){let o=n.map(a=>Lh(e,t,a,i)),r=Gi(o.map(a=>a.status)),s=o.filter(a=>a.status!=="unsupported").map(a=>a.language);return{id:e.id,label:e.label,status:r,requirements:e.requirements,subtypes:t.map(a=>a.subtype),languages:o,reason:s.length===0?`Unavailable: requires ${e.requirements.join(", ")}.`:`${r} support for ${s.join(", ")}; analytical ceiling is declared per subtype.`}}function Lh(e,t,n,i){let o=e.requirements.filter(s=>!jh(s,n,i));if(o.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${o.join(", ")}.`};let r=Gi(t.map(s=>s.supportCeiling));return{language:n.language,status:r,reason:`${e.label} is available; subtype coverage is ${r}.`}}function jh(e,t,n){switch(e){case"indexed-graph":return n&&t.indexing.status!=="unavailable";case"source-facts":return t.sourceFacts.status!=="unavailable";case"typescript-semantic":return t.language==="typescript"&&t.semantic.status==="available"}}function Gi(e){let t=e.filter(n=>n!=="unsupported");return t.length===0?"unsupported":t.every(n=>n==="exact")?"exact":t.some(n=>n==="exact"||n==="partial")?"partial":"candidate"}function Mh(e){return Nh(e).map(t=>{let n=Vi(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Oh(t)} semantic provider`,status:i,evidence:"semantic",reason:Dh(t,n)}})}function Nh(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of tl(e))t.add(n.language);return[...t].sort((n,i)=>Yc(n)-Yc(i))}function Yc(e){return e==="typescript"?0:1}function Oh(e){return e==="typescript"?"TypeScript":"Rust"}function Dh(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 qh(e,t,n){let i=e.indexers.find(d=>d.language===t),o=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",r=o!=="unavailable",s=Wh(t,n.runtimeProbe),a=Bh(e,t),c=Gh(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:o,evidence:"graph-fact",reason:o==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:o==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:r?s.status:"unavailable",evidence:"heuristic",reason:r?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"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 ${Zc[t].join(", ")} files.`}}}function Fh(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Wh(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)??Xc(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=el(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 i=t?.(e)??Xc(e);return i==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:i==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:i==="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 Xc(e){let t=Th[e];return t?vn(t):el(e)==="regex-only"?"regex":"unavailable"}function el(e){let t=Ih[e],n=t?or(t):null;return n?.imports??n?.exports??n?.reExports??null}function _h(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...Dc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let o=pr(e);i.push({language:"rust",available:o.available,dependencyAvailable:o.dependencyAvailable,resolvedBinary:o.resolvedBinary,reason:o.available?o.note:o.reason})}return i}function tl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Vi(e,t){return tl(e).find(n=>n.language===t)}function Bh(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=Vi(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 Gh(e,t){let n=new Set(Zc[t]);return e.checkers.filter(i=>i.coversExtensions.some(o=>n.has(o)))}function Vh(e){try{return Eh("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import Kf from"better-sqlite3";import $e from"process";import{rmSync as jl}from"fs";import{resolve as zf}from"path";import{pathToFileURL as Jf}from"url";import{statSync as Uh,watch as Hh}from"fs";function nl(e){let t=!1,n=!1,i,o=[],r=[...new Set(e)],s=new Map,a=m=>{try{return Uh(m).mtimeMs}catch{return null}},c=()=>{for(let m of r)s.set(m,a(m))},l=()=>r.some(m=>a(m)!==s.get(m));c();let d=()=>{n=!0;let m=i;i=void 0,m?.()};for(let m of r)try{let h=Hh(m,{persistent:!1},d);h.on("error",()=>{}),o.push(h)}catch{}return{wait(m){return t||m<=0?(n=!1,Promise.resolve()):new Promise(h=>{let p=setTimeout(()=>{i===f&&(i=void 0),h()},m),f=()=>{clearTimeout(p),i===f&&(i=void 0),h()};i=f,(n||t||l())&&(n=!1,c(),f())})},close(){if(!t){t=!0;for(let m of o)try{m.close()}catch{}o.length=0}d()}}}import{lstatSync as Qh}from"fs";function ol(e,t){let n=Bn(e);if(n.kind!=="directory")throw new Error(`Watcher root is not a directory: ${e}`);if(!t)return{projectRoot:e,projectDirectory:n};let i=Bn(t);if(i.kind!=="directory")throw new Error(`Git control path is not a directory: ${t}`);return{projectRoot:e,projectDirectory:n,gitControlDirectory:{path:t,identity:i}}}function rl(e){try{if(!il(e.projectDirectory,Bn(e.projectRoot)))return!1;let t=e.gitControlDirectory;return!t||il(t.identity,Bn(t.path))}catch{return!1}}function Bn(e){let t=Qh(e,{bigint:!0}),n=t.isDirectory()?"directory":t.isFile()?"file":void 0;if(!n||t.isSymbolicLink())throw new Error(`Unsupported watcher identity path: ${e}`);return{device:t.dev,inode:t.ino,birthtimeNs:t.birthtimeNs,kind:n}}function il(e,t){return e.device===t.device&&e.inode===t.inode&&e.birthtimeNs===t.birthtimeNs&&e.kind===t.kind}import{existsSync as Ji,lstatSync as zh,statSync as fl,watch as Jh}from"fs";import{EventEmitter as Yh}from"events";import{basename as Xh,dirname as gl,isAbsolute as Yi,join as _e,relative as yl,resolve as bl}from"path";import{watch as Zh}from"chokidar";import ef from"ignore";function Ui(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}var vl=5e3,Un=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;pendingChanges=new Map;pendingChangesComplete=!0;pendingChangesIncompleteReason;reindexInFlight=!1;lastReindexEnd=0;lastObservedGeneration=null;publishedGeneration;indexFreshness;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;reconcileTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ke(t.config),this.outputDb=t.outputDb??_e(Jo(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=kf(this.projectRoot,gl(this.outputDb)),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??sf,Sl.set(this,Ef(t.stopTimeoutMs??vl,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??gf(),this.subscriptionFactory=t.subscriptionFactory??af,this.budgetInspector=t.budgetInspector??sc,this.publishedGeneration=t.publishedGeneration??Qe,this.indexFreshness=t.indexFreshness??Cf,this.lastObservedGeneration=this.readPublishedGeneration(),wl.set(this,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Vo,languages:Rl(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=aa(t.projectRoot),this.extraIgnore=ef(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),Qi(this)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Vn(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.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Vn(this).closures],o=nf(this),r=this.clock.now()+o;return this.stopPromise=this.finishStop(t,i,n,r,o).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Hi(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,o)=>this.isIgnoredWatchPath(i,o?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(i,o)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(i,o)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(this.markPendingChangesIncomplete("source-watcher-error"),i||this.sourcePollingFallbackStarted||!Sf(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(o=>o!==t),of(Vn(this),t,o=>this.onError(o));try{this.startSourceWatcher(!0)}catch(o){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(o)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;if(ll(i,this.localCacheWatchPath))return!0;let o=n?`${i}/`:i;return this.gitignoreFilter.isIgnored(o)||this.extraIgnore.ignores(o)}handleFileChange(t,n){let i=this.relativeWatchPath(n);if(!i||i===".."||i.startsWith("../")||ll(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||i.endsWith("index.db")||i.endsWith("index.scip")||i.endsWith("index.db.tmp")||Xh(i).startsWith(oc))return;i===".scipquery.json"&&pl(this,this.projectRoot);let o=ml(this,t,i);o!==null&&(o||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:i},o?[{path:i,kind:o}]:void 0,o!==void 0))}relativeWatchPath(t){let n=Yi(t)?t:_e(this.projectRoot,t);return yl(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,i=!1){this.pendingTrigger=Hi(this.pendingTrigger,t),i||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let r of n??[])this.recordPendingChange(r);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let r=this.activeOperation;r&&Mt.get(this)!==r&&(Mt.set(this,r),r.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let o=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:o}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcileExternalPublication())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,c-this.wallNow())));return}let i=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&i<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-i;this.dirty=!0;let l=this.wallNow()+c;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},c);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let o=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(o,n,r));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),Gn.set(this,0),this.stopped)return;if(Mt.get(this)===a){if(this.restorePendingChangeJournal(r),this.dirty){let d=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.clearCooldownTimer(),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"});return}Qi(this),this.lastObservedGeneration=this.readPublishedGeneration();let l=!1;try{l=this.onReindexComplete(c,o,{pendingChanges:this.dirty})===!0}catch(d){this.onError(d instanceof Error?d:new Error(String(d)))}if(this.dirty&&!this.stopped){if(l){let m=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(m),this.setStatus({state:"idle"});return}let d=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.clearCooldownTimer(),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(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let l=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(r);let d=$l(l),m=0;if(d?(m=(Gn.get(this)??0)+1,Gn.set(this,m),this.dirty=!0,this.pendingTrigger=Hi(this.pendingTrigger,o)):Gn.set(this,0),!d&&Mt.get(this)!==a&&(this.onReindexError(l,o),this.onError(l)),this.dirty){let h=d?ff(this.watchConfig.cooldownMs,m):this.watchConfig.cooldownMs,p=this.wallNow()+h;this.setStatus({state:"cooldown",until:p,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},h);return}this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===a&&(this.activeOperation=null),Mt.get(this)===a&&Mt.delete(this)})}async finishStop(t,n,i,o,r){let s=[],a=t.map(async h=>{try{await h.close()}catch(p){s.push(`watch subscription close failed: ${String(p)}`)}});a.push(...n),i&&a.push((async()=>{try{let h=await i.cancel();h.state==="degraded"&&s.push(h.reason)}catch(h){s.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=a.length,l=a.map(h=>h.finally(()=>{c-=1})),d=await tf(l,o,this.clock),m=Vn(this);return s.push(...m.errors),m.errors=[],d?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${r}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()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,i){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,changeJournal:i,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),i=bf(n,t.kind);i===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,i)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=Qe(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),i=this.pendingChangesComplete,o=this.pendingChangesIncompleteReason;t||(i=!1,o??="accepted-generation-unavailable");let r={version:1,baseGeneration:t,complete:i,...o?{incompleteReason:o}:{},entries:n};return Ui(r)||(r={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),r}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([r,s])=>({path:r,kind:s})),i=this.pendingChangesComplete,o=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let r of t.entries)this.recordPendingChange(r);i||this.markPendingChangesIncomplete(o??"failed-reindex");for(let r of n)this.recordPendingChange(r)}resetPendingChanges(){this.pendingChanges.clear(),this.pendingChangesComplete=!0,this.pendingChangesIncompleteReason=void 0}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(at(this).stagedIndexEntries=hl(this.projectRoot,at(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let i=Math.min(this.watchConfig.gitPollMs,n);this.reconcileTimer=this.clock.setTimeout(()=>{this.reconcileTimer=null,!(this.stopped||this.reconcileExternalPublication())&&(this.status.state==="cooldown"||this.status.state==="budget-paused")&&this.armReconcileTimer(this.status.until)},i),this.reconcileTimer.unref?.()}clearReconcileTimer(){this.reconcileTimer&&(this.clock.clearTimeout(this.reconcileTimer),this.reconcileTimer=null)}readPublishedGeneration(){try{return this.publishedGeneration(this.outputDb)}catch{return null}}reconcileExternalPublication(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting"))return!1;let n=this.readPublishedGeneration();if(n===null||n===this.lastObservedGeneration)return!1;this.lastObservedGeneration=n;let i;try{i=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(i!=="fresh")return!1;let o=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),Qi(this),this.onRefreshSuppressed({...o,detail:`a generation published outside the watcher is fresh${o.detail?` (${o.detail})`:""}`}),this.setStatus({state:"idle"}),!0}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let i=t.head!==n.head,o=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;if(!i&&!o)return;let r=at(this),s=r.stagedIndexEntries,a=hl(this.projectRoot,r.gitReader);r.stagedIndexEntries=a;let c=Pf(this.projectRoot,r.gitReader,t,n,s,a,i,o),l=null;if(c!==null&&(c.includes(".scipquery.json")&&pl(this,this.projectRoot),l=c.filter(m=>ml(this,"add",m)!==null),l.length===0))return;let d=l?.map(m=>({path:m,kind:Ji(_e(this.projectRoot,m))?"change":"delete"}));i&&o?this.scheduleReindex({kind:"watch-git-state",detail:Ki("HEAD and index changed",l)},d,d!==void 0):i?this.scheduleReindex({kind:"watch-git-head",detail:Ki("HEAD changed",l)},d,d!==void 0):o&&this.scheduleReindex({kind:"watch-git-index",detail:Ki(n.indexPath??"index changed",l)},d,d!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??wf(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=$f(t.gitDir);return n?ul(n,t.indexPath):null}readGitStateFromGit(){let t=at(this).gitReader,n=bi(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=Qo(this.projectRoot,n);return ul(bi(this.projectRoot,["rev-parse","--verify","HEAD"],t),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function tf(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),o=Math.max(0,t-n.now()),r=null,s=new Promise(c=>{r=n.setTimeout(()=>c(!1),o)}),a=await Promise.race([i,s]);return a&&r&&n.clearTimeout(r),a}var al=new WeakMap,Sl=new WeakMap,wl=new WeakMap,Mt=new WeakMap,Gn=new WeakMap;function Vn(e){let t=al.get(e);if(t)return t;let n={closures:new Set,errors:[]};return al.set(e,n),n}function nf(e){return Sl.get(e)??vl}function at(e){let t=wl.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function of(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(o=>{let r=`watch subscription close failed during polling fallback: ${String(o)}`;e.errors.push(r),n(new Error(r))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function rf(e,t=He){let{projectRoot:n,config:i,languages:o,pnpmWorkspaces:r,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:l,trigger:d}=e,m=Ee(n),h=Object.keys(m).length>0?m:i,p=Ue(n,h),f=h.indexer?.typescript,g=h.indexer?.clojure,y=t(process.pid);if(!y)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??o)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??l??""),SCIP_REINDEX_PNPM_WORKSPACES:f?.pnpmWorkspaces??r?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:f?.projectMode??s,projects:f?.projects??a??[],maxHeapMb:f?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:g?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:d.kind,SCIP_REINDEX_TRIGGER_DETAIL:d.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?Ui(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(y)}}}var sf={now:ke,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},af=(e,t)=>cf(process.platform,t.usePolling)?new zi(e):Zh(e,t);function cf(e,t){return e==="darwin"&&t!==!0}var sn=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},zi=class{events=new Yh;watcher;constructor(t){this.watcher=Jh(t,{recursive:!0},(n,i)=>{if(i===null){this.events.emit("error",new sn("Recursive source watcher omitted the changed path."));return}let o=_e(t,i.toString());this.events.emit("all",lf(n,o),o)}),this.watcher.on("error",n=>{this.events.emit("error",new sn(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function lf(e,t){return e==="change"?"change":Ji(t)?fl(t).isDirectory()?"addDir":"add":"unlink"}var df=15*6e4,uf=1e3,pf=64*1024;function mf(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function cl(e,t){let n=e instanceof Error?e.message:String(e),i=t.stderrTail.trim()||t.stdoutTail.trim();return i?`${n}
|
|
11
|
-
${i}`:n}function hf(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function $l(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function ff(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function gf(e={}){let t=e.timeoutMs??df,n=e.terminationGraceMs??uf,i=e.maxOutputBytes??pf,o=e.resolveLaunch??rf;return{start(r){let s=o(r),a=new AbortController,c=mf(),l=!1,d=Ia({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(m=>{if(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated},m.status!==0){let h=cl(new Error(`Reindex worker exited with ${m.signal?`signal ${m.signal}`:`code ${m.status}`}`),c);throw m.status===75?hf(h):new Error(h)}return m.durationMs}).catch(m=>{throw $l(m)?m:(m instanceof Ta&&(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated}),new Error(cl(m,c),{cause:m}))}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Hi(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 yf(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function bf(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function vf(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Sf(e){return e instanceof sn||vf(e)}var Xi=/^[0-9a-f]{40,64}$/i;function ll(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function wf(e){let t=_e(e,".git");try{let n=zh(t),i;if(n.isDirectory())i=t;else if(n.isFile()){let o=/^gitdir:\s*(.+)\s*$/m.exec(ae(t,"Git directory marker"));if(!o?.[1])return null;let r=o[1].trim();i=Yi(r)?r:bl(e,r)}else return null;return Ji(i)?{gitDir:i,indexPath:_e(i,"index")}:null}catch{return null}}function $f(e){let t;try{t=ae(_e(e,"HEAD"),"Git HEAD").trim()}catch{return}if(Xi.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let i=Rf(e);return dl(e,n)??dl(i,n)??xf(i,n)}function Rf(e){try{let t=ae(_e(e,"commondir"),"Git common-directory marker").trim();return t?Yi(t)?t:bl(e,t):e}catch{return e}}function dl(e,t){try{let n=ae(_e(e,t),"Git reference").trim();return Xi.test(n)?n.toLowerCase():void 0}catch{return}}function xf(e,t){try{for(let n of ae(_e(e,"packed-refs"),"Git packed references").split(`
|
|
12
|
-
`)){if(n.startsWith("#")||n.startsWith("^"))continue;let i=n.indexOf(" ");if(i===-1)continue;let o=n.slice(0,i);if(n.slice(i+1).trim()===t&&Xi.test(o))return o.toLowerCase()}}catch{return}}function Cf(e,t,n){let i=gl(n);return Te(e,t,{dbPath:n,metaPath:_e(i,"meta.json"),cacheDir:i}).state}function ul(e,t){let n={head:e,indexPath:t};try{let i=fl(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function kf(e,t){let n=yl(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Ef(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function Rl(e){return e&&e.length>0?[...e]:Gt}function pl(e,t){try{let n=at(e);n.config=Ee(t),n.languages=Rl(n.config.languages)}catch{at(e).languages=Gt}}function ml(e,t,n){let i=at(e);if(yi(n,i.languages)==="other")return null;let r=yf(t);if(n===".scipquery.json"||Ko(n))return i.typeScriptInputPaths=null,r;if(!Tf(n,i.languages))return r;let s=i.typeScriptInputPaths;if(!s)return r;let a=s.has(n);if(r!=="add")return a?r:null;if(a)return"change";let c=xl(e);return c?c.has(n)?"add":null:r}function Qi(e){let t=at(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=If(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??xl(e)}function xl(e){let t=at(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,i=zo(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=i,i}catch{return t.typeScriptInputPaths=null,null}}function Tf(e,t){if(!t.includes("typescript"))return!1;let n=yi(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function If(e,t,n){try{let i=er(ae(Ue(e,t).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let o=Bo(i.metadata.fingerprint);return!o||!Af(o,n,t)?null:new Set(o.files.map(r=>r.path))}catch{return null}}function Af(e,t,n){let i=Zo(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===i.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(i.languages)&&e.pnpmWorkspaces===i.pnpmWorkspaces&&e.typescriptProjectMode===i.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(i.typescriptProjects)&&e.clojureConfigPath===i.clojureConfigPath}function Pf(e,t,n,i,o,r,s,a){let c=new Set;if(s){if(!n.head||!i.head)return null;let l=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(l.kind!=="success")return null;for(let d of Lf(l.output))c.add(d)}if(a){if(o===null||r===null)return null;for(let l of Mf(o,r))c.add(l)}return[...c].sort()}function hl(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?jf(n.output):null}function Lf(e){return e.split("\0").filter(t=>t.length>0)}function jf(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let o=t[i],r=t[i+1];if(!o.startsWith(":")||!r)return null;n.set(r,o)}return n}function Mf(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function Ki(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}var Hn=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(t,n={}){this.root=t,this.now=n.now??Date.now,this.randomId=n.randomId,this.retryDelayMs=Math.max(1,Math.floor(n.retryDelayMs??1e3)),this.currentStatus=nn(t)}initializeAfterOwnershipAcquired(){let t=gc(this.root),n=yc(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:n}}observeLegacyRequest(t,n){mc(this.root,n??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${t}`,now:()=>new Date(t)}),this.refreshStatus()}poll(t,n){if(this.active||t.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=hc(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return n(Nf(i)),!0}catch(o){throw Di(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),o}}completeActive(){return this.active?(fc(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Di(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=nn(this.root)}};function Nf(e){if(e.requests.length===1)return e.requests[0].detail;let n=[...new Set(e.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${e.requests.length} coalesced refresh requests${n?`: ${n}`:""}`.slice(0,2048)}import{totalmem as Df}from"os";import{randomUUID as qf}from"crypto";import{rmSync as Ff}from"fs";import{Worker as Wf}from"worker_threads";var Qn=class{constructor(t){this.options=t;if(this.now=t.now??Date.now,this.setTimer=t.setTimer??setTimeout,this.clearTimer=t.clearTimer??clearTimeout,t.maxWorkerFailureRetries!==void 0&&(!Number.isInteger(t.maxWorkerFailureRetries)||t.maxWorkerFailureRetries<0))throw new Error("Worker maxWorkerFailureRetries must be a non-negative integer.")}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;idleTimer=null;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}hasWorker(){return this.worker!==null}start(t){if(!this.canAccept())return!1;if(this.clearIdleTimer(),t.deadlineAtMs<this.now()){try{this.options.onReject(t,`${this.options.name} request expired before processing.`)}catch(o){this.closed=!0,this.options.onFatal(Zi(o))}return!0}let n=this.ensureWorker(),i=this.deadlineTimer(t);this.active={request:t,timer:i,workerFailureRetries:0,workerFailureReasons:[]};try{n.postMessage({kind:"request",...t})}catch(o){this.failActiveAfterTermination(eo(o),!0)}return!0}async close(t=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.clearIdleTimer(),this.active){await this.failActiveAfterTermination(t);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let t=this.options.createWorker(),n=++this.workerGeneration;return t.on("message",i=>this.handleMessage(n,i)),t.on("error",i=>{n===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`,!0)}),t.on("exit",i=>{n!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`,!0))}),this.worker=t,t}handleMessage(t,n){if(t!==this.workerGeneration||this.closed||!this.active)return;let i=Of(n);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let o=this.active,r;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(o.request,i.result,i.status):this.options.onReject(o.request,i.error,i.status),r=this.options.retireAfterResponse?.(i.status)??!1}catch(s){this.closed=!0,this.clearTimer(o.timer),this.options.onFatal(Zi(s));return}this.releaseActive(o),r?this.terminateWorker():this.scheduleIdleTermination()}async failActiveAfterTermination(t,n=!1){if(this.activeFailure){await this.activeFailure;return}let i=this.active;if(!i){await this.terminateWorker();return}this.clearTimer(i.timer),n&&i.workerFailureReasons.push(t);let o=(async()=>{if(!await this.terminateWorker())return;let s=this.options.maxWorkerFailureRetries??0;if(n&&!this.closed&&i.workerFailureRetries<s&&this.now()<=i.request.deadlineAtMs){i.workerFailureRetries+=1;try{let c=this.ensureWorker();i.timer=this.deadlineTimer(i.request),c.postMessage({kind:"request",...i.request});return}catch(c){let l=`Cold Worker retry failed: ${eo(c)}`;if(i.workerFailureReasons.push(l),t=`${t} ${l}`,!await this.terminateWorker())return}}let a=i.workerFailureReasons.length===0?t:[...new Set([...i.workerFailureReasons,t])].join(" Cold Worker retry: ");try{this.options.onReject(i.request,a)}catch(c){this.closed=!0,this.options.onFatal(Zi(c));return}this.releaseActive(i)})();this.activeFailure=o;try{await o}finally{this.activeFailure===o&&(this.activeFailure=null)}}deadlineTimer(t){let n=Math.max(1,Math.min(2147483647,t.deadlineAtMs-this.now()));return this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},n)}releaseActive(t){this.active===t&&(this.active=null,this.clearTimer(t.timer))}scheduleIdleTermination(){let t=this.options.idleTtlMs;!t||t<=0||this.closed||this.active||!this.worker||(this.clearIdleTimer(),this.idleTimer=this.setTimer(()=>{this.idleTimer=null,!(this.closed||this.active||!this.worker)&&this.terminateWorker()},t))}clearIdleTimer(){this.idleTimer&&(this.clearTimer(this.idleTimer),this.idleTimer=null)}async terminateWorker(){if(this.clearIdleTimer(),this.terminating)return this.terminating;let t=this.worker;if(!t)return!0;this.worker=null;let n=++this.workerGeneration;return this.terminating=(async()=>{try{return await t.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${eo(i)}`,{cause:i})),!1}finally{n===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Of(e){if(!e||typeof e!="object")return null;let t=e;if(t.kind!=="response"||typeof t.requestId!="string"||!("status"in t))return null;if(t.ok===!0){if(!("result"in t)||"error"in t)return null}else if(t.ok===!1){if("result"in t||typeof t.error!="string")return null}else return null;return t}function Zi(e){return e instanceof Error?e:new Error(String(e))}function eo(e){return e instanceof Error?e.message:String(e)}var _f=6e4,Bf=10*6e4;function Cl(e){let t=e.maxActiveSessions??8,n=e.workerSoftMemoryMb??Pl(e.workerHeapMb),i=()=>({protocolVersion:On,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,sessionsEvicted:0,activeSessions:0,maxActiveSessions:t,softMemoryLimitBytes:n*1024*1024,retireRequested:!1,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return El({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:i,parseEnvelope:cc,createWorker:()=>Ll(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath,maxActiveSessions:t,softMemoryLimitMb:n}),complete(o,r,s,a){ki(e.paths,o,{ok:!0,protocolVersion:On,id:r.id,baseGeneration:r.baseGeneration,response:s},{nowMs:a,limits:e.limits})},reject(o,r,s,a){Ei(e.paths,o,{ok:!1,protocolVersion:On,id:r,error:s},s,{nowMs:a,limits:e.limits})},idleTtlMs:e.workerIdleMs??Bf,maxWorkerFailureRetries:1,retireAfterResponse:o=>o.retireRequested===!0,statusWhenWorkerAbsent:o=>({...o,state:"idle",activeSessions:0,heapUsedBytes:0,retireRequested:!1}),onBusy:e.onBusy,onFatal:e.onFatal})}function kl(e){let t=e.workerSoftMemoryMb??Pl(e.workerHeapMb),n=()=>({protocolVersion:Tn,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0,softMemoryLimitBytes:t*1024*1024,retireRequested:!1});return El({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:n,parseEnvelope:Er,createWorker:()=>Ll(e,{kind:"semantic",projectRoot:e.projectRoot,softMemoryLimitMb:t}),complete(i,o,r,s){ki(e.paths,i,{ok:!0,protocolVersion:Tn,id:o.id,generation:o.generation,response:r},{nowMs:s,limits:e.limits})},reject(i,o,r,s){Ei(e.paths,i,{ok:!1,protocolVersion:Tn,id:o,error:r},r,{nowMs:s,limits:e.limits})},idleTtlMs:_f,maxWorkerFailureRetries:1,retireAfterResponse:i=>i.retireRequested===!0,statusWhenWorkerAbsent:i=>({...i,state:"idle",heapUsedBytes:0,retireRequested:!1}),onBusy:e.onBusy,onFatal:e.onFatal})}function El(e){let t=e.now??Date.now,n=He(process.pid),i={pid:process.pid,...n?{processIdentity:n}:{}},o=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${qf()}`,r={...e.limits,maxBatch:1},s=null,a=e.initialStatus(),c=!1,l=p=>{c=!0,e.onFatal(p)},d=new Qn({name:e.name,createWorker:e.createWorker,now:t,idleTtlMs:e.idleTtlMs,maxWorkerFailureRetries:e.maxWorkerFailureRetries,retireAfterResponse:e.retireAfterResponse,onComplete(p,f,g){let y=m(p.requestId);a=g;let v=t();try{e.complete(y.claim,y.envelope,f,v)}catch($){if(!($ instanceof xi))throw $;try{e.reject(y.claim,y.envelope.id,$.message,v)}catch(L){if(!(L instanceof xi))throw L;Ff(y.claim.path,{force:!0})}}h(y)},onReject(p,f,g){let y=m(p.requestId);g!==void 0&&(a=g),e.reject(y.claim,y.envelope.id,f,t()),h(y)},onStatus(p){a=p},onFatal:l});return{poll(){if(c||!d.canAccept())return 0;let p=br(e.paths,{ownerId:o,nowMs:t(),limits:r,owner:i,liveness:{isProcessAlive:Rn,readProcessIdentity:He}})[0];if(!p)return 0;let f=p.requestId;try{let g=e.parseEnvelope(vr(p,r));if(f=g.id,g.id!==p.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(g.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(s={claim:p,envelope:g},e.onBusy?.(g.deadlineAtMs),!d.start({requestId:g.id,deadlineAtMs:g.deadlineAtMs,payload:g}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(g){let y=Qf(g);try{e.reject(p,f,y,t()),s?.claim===p&&h(s)}catch(v){l(Hf(v))}}return 1},status(){return{...d.hasWorker()||!e.statusWhenWorkerAbsent?a:e.statusWhenWorkerAbsent(a),mailbox:Sr(e.paths)}},async close(p){await d.close(p)}};function m(p){let f=s;if(!f||f.envelope.id!==p)throw new Error(`${e.name} parent lost the active mailbox claim.`);return f}function h(p){s===p&&(s=null,e.onBusy?.(void 0))}}var Tl=6144;function Il(){let e=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(e)&&e>0?e:Tl}var Gf=.6;function Al(e,t=Vf()){let n=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);if(Number.isFinite(n)&&n>0)return n;let i=Math.ceil(xr+e*Cr),o=Math.floor(t*Gf/(1024*1024));return Math.max(Tl,Math.min(i,o))}function Vf(e=Uf,t=Df()){let n=[e("/sys/fs/cgroup/memory.max"),e("/sys/fs/cgroup/memory/memory.limit_in_bytes")].map(i=>i===null?Number.NaN:Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0&&i<t);return n.length>0?Math.min(...n):t}function Uf(e){try{return fe(e,{maxBytes:Tt,inputKind:"cgroup memory limit"})}catch{return null}}function Pl(e){return Math.max(1,Math.floor((e??Il())*.9))}function Ll(e,t){if(e.createWorker)return e.createWorker(t);let n=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new Wf(n,{workerData:t,resourceLimits:{maxOldGenerationSizeMb:e.workerHeapMb??Il()}})}function Hf(e){return e instanceof Error?e:new Error(String(e))}function Qf(e){return e instanceof Error?e.message:String(e)}var Ml=2e3,Yf=5e3,Xf=5e3,Zf=6e4,eg=10,tg=50,ng=1e4;function ig(e,t=1){return hr(e,t,eg,tg,ng,8)}function og(e,t){let n;return{begin(){return n||(t.requestStop(),t.closeWake(),n=e.stop(),n.catch(()=>{})),n}}}async function rg(e,t){let n=t.processIndexRequests(),i=t.processSemanticRequests(),o=n+i,r=o>0?0:e+1;if(t.afterMailboxPoll({indexRequests:n,semanticRequests:i,processedRequests:o}),t.shouldStop())return{indexRequests:n,semanticRequests:i,processedRequests:o,consecutiveIdlePolls:r,stopped:!0};let s=ig(o,r);return await t.wait(s),{indexRequests:n,semanticRequests:i,processedRequests:o,consecutiveIdlePolls:r,stopped:!1,delayMs:s}}function sg(e){return e==="fresh"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}function ag(e){Sc(e.statePath,{version:1,protocolVersion:wr,pid:$e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{},projectRoot:e.projectRoot,...e.worktreeId?{worktreeId:e.worktreeId}:{},cliVersion:e.cliVersion,startedAt:new Date(e.startedAtMs).toISOString(),heartbeatAt:new Date(e.nowMs).toISOString(),lastActivityAt:new Date(e.lastActivityAtMs).toISOString(),...e.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(e.lastActivityAtMs+e.idleTimeoutMs).toISOString()},watcher:e.watcherStatus,...e.watcherStatus.state==="idle"&&e.indexGeneration?{indexGeneration:e.indexGeneration}:{},...e.lastRefresh?{lastRefresh:e.lastRefresh}:{},...e.lastError?{lastError:e.lastError}:{},reindexActivity:e.reindexActivity,refreshRequests:e.refreshCoordinator.status(),typescriptSemantic:{...e.semanticLane.status(),...e.semanticBusyUntilMs===void 0?{}:{busyUntil:new Date(e.semanticBusyUntilMs).toISOString()}},typescriptIndex:{...e.indexLane.status(),...e.indexBusyUntilMs===void 0?{}:{busyUntil:new Date(e.indexBusyUntilMs).toISOString()}}},{durability:e.durability})}function cg(e){let t=0,n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return({processedRequests:s})=>{let a=ke();if(a-i>=Xf&&(i=a,!rl(e.worktreeLiveness))){e.requestStop();return}if(a-r>=Zf&&(r=a,Ti(e.indexMailboxPaths),Ti(e.semanticMailboxPaths)),a-o>=Cc&&(o=a,kc(e.projectRoot,e.cliVersion)),a-n>=Yf){n=a;let c=wc(e.activityPath);c&&e.updateObservedActivity(c.atMs,a),c?.refreshRequestedAtMs!==void 0&&c.refreshRequestedAtMs>t&&(t=c.refreshRequestedAtMs,e.refreshCoordinator.observeLegacyRequest(c.refreshRequestedAtMs,c.refreshDetail??"stale index observed by a legacy command"))}e.refreshCoordinator.poll(e.watcherStatus(),c=>{e.recordActivity(),e.requestRefresh(c)}),s>0&&(e.recordActivity(),e.persistState(!0,"visibility")),e.persistState()}}async function lg(e){let t,n=0,i=!1,o,r;$e.once("SIGINT",e.stopSignal),$e.once("SIGTERM",e.stopSignal);try{e.watcher.start();let a=e.initializeFreshness();for(e.recordActivity(),e.markReady(),e.persistState(!0),t=setInterval(()=>e.persistState(),Ml),t.unref?.(),a&&e.requestRefresh(a);!e.stopRequested();){let c=await rg(n,{processIndexRequests:e.processIndexRequests,processSemanticRequests:e.processSemanticRequests,afterMailboxPoll:e.afterMailboxPoll,shouldStop:e.shouldStop,wait:e.wait});if(n=c.consecutiveIdlePolls,c.stopped)break}}catch(a){i=!0,o=a}finally{$e.off("SIGINT",e.stopSignal),$e.off("SIGTERM",e.stopSignal),t!==void 0&&clearInterval(t);let a=e.shutdown.begin();await e.closeLanes();let c=await a;c.state==="stopped"?e.finalizeStopped():r=e.finalizeDegraded(c.reasons)}let s=e.mailboxFatalError();if(!i&&s&&(i=!0,o=s),i&&r)throw new AggregateError([o,r],"Watch service execution and shutdown both failed.");if(i)throw o;if(r)throw r}function dg(e){try{let t=new Kf(e,{readonly:!0,fileMustExist:!0});try{return t.prepare("SELECT count(*) AS documents FROM documents").get().documents}finally{t.close()}}catch{return 0}}function ug(e){let t=e.config.indexer?.typescript,n=t?.workerHeapMb??Al(dg(e.dbPath)),i=kl({paths:e.semanticPaths,projectRoot:e.projectRoot,workerHeapMb:n,onBusy:e.onSemanticBusy,onFatal:e.onFatal}),o=Cl({paths:e.indexPaths,projectRoot:e.projectRoot,dbPath:e.dbPath,...t?.maxWarmSessions===void 0?{}:{maxActiveSessions:t.maxWarmSessions},...t?.workerIdleMs===void 0?{}:{workerIdleMs:t.workerIdleMs},...t?.workerSoftMemoryMb===void 0?{}:{workerSoftMemoryMb:t.workerSoftMemoryMb},workerHeapMb:n,onBusy:e.onIndexBusy,onFatal:e.onFatal});return{semanticLane:i,indexLane:o}}async function to(e,t,n={}){let i=vc(e,t),o=i.projectRoot,r=i.worktreeKind==="git"?pg(o,i.worktreeId):void 0,s=ol(o,r),a=Ee(o);a.watch={...a.watch,...n};let c=Ke(a);if(!c.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let l=Ue(o,a),d=En(l.cacheDir),m=He($e.pid),h=$c(d.lockPath,o,{readProcessIdentity:q=>q===$e.pid?m:He(q)});if(!h.acquired)return;let p=new Hn(d.refreshRequestsPath,{retryDelayMs:Math.max(1e3,c.cooldownMs)});p.initializeAfterOwnershipAcquired();let f=Date.now(),g=ke(),y=f,v=g,$={state:"idle"},L,_,I,T,W=Nn(l.dbPath),E=!1,B=!1,J=Number.NEGATIVE_INFINITY,F,Y,pt=kr(l.cacheDir),et=ac(l.cacheDir);Ci(pt),Ci(et);let gn=nl([et.pendingDir,et.legacyRequestDir,pt.pendingDir,pt.legacyRequestDir,d.refreshRequestsPath]),xe=(q=!1,nt=q?"durable":"visibility")=>{if(!B)return;let he=Date.now(),ne=ke();!q&&ne-J<Ml||(J=ne,ag({statePath:d.statePath,durability:nt,processIdentity:m,projectRoot:o,worktreeId:i.worktreeId,cliVersion:t,startedAtMs:f,nowMs:he,lastActivityAtMs:y,idleTimeoutMs:c.idleTimeoutMs,watcherStatus:$,indexGeneration:L,lastRefresh:_,lastError:I,reindexActivity:W,refreshCoordinator:p,semanticLane:mt,indexLane:Et,semanticBusyUntilMs:F,indexBusyUntilMs:Y}))},tt=()=>{y=Date.now(),v=ke()},Ge=q=>{tt(),T??=q,I={at:new Date().toISOString(),message:q.message},xe(!0,"visibility")},{semanticLane:mt,indexLane:Et}=ug({semanticPaths:pt,indexPaths:et,projectRoot:o,dbPath:l.dbPath,config:a,onSemanticBusy(q){F=q===void 0?void 0:q+5e3,xe(!0,"visibility")},onIndexBusy(q){Y=q===void 0?void 0:q+5e3,xe(!0,"visibility")},onFatal:Ge}),ve=new Un({projectRoot:o,config:{...a,watch:c},outputDb:l.dbPath,languages:a.languages,onStatus(q){$=q,q.state!=="idle"&&(L=void 0),q.state!=="idle"&&tt(),xe(!0)},onReindexComplete(q,nt,he){tt();let ne=he?.pendingChanges!==!1?Te(o,a,l):ga(l);return _=ne.lastRefresh,L=ne.state==="fresh"?Qe(l.dbPath)??void 0:void 0,W=Nn(l.dbPath),p.completeActive(),I=void 0,xe(!0),ne.state==="fresh"},onReindexError(){p.failActive()},onRefreshSuppressed(q){let nt=rc(l.dbPath,q);nt.state==="failed"&&(I={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${nt.reason}`},xe(!0,"visibility")),W=Nn(l.dbPath)},onError(q){tt(),L=void 0,I={at:new Date().toISOString(),message:q.message},xe(!0)}}),_t=og(ve,{requestStop(){E=!0},closeWake(){gn.close()}}),Ce=()=>{_t.begin()},Me=cg({worktreeLiveness:s,indexMailboxPaths:et,semanticMailboxPaths:pt,projectRoot:o,cliVersion:t,activityPath:d.activityPath,refreshCoordinator:p,watcherStatus:()=>$,requestRefresh:q=>ve.requestRefresh({kind:"watch-demand",detail:q},{immediate:!0}),requestStop:()=>{E=!0},recordActivity:tt,updateObservedActivity(q,nt){q<=y||(y=q,v=nt)},persistState:xe});await lg({watcher:ve,shutdown:_t,stopSignal:Ce,initializeFreshness(){let q=Te(o,a,l);return _=q.lastRefresh,L=q.state==="fresh"?Qe(l.dbPath)??void 0:void 0,sg(q.state)},markReady:()=>{B=!0},recordActivity:tt,persistState:xe,requestRefresh:q=>ve.requestRefresh(q,{immediate:!0}),stopRequested:()=>E,processIndexRequests:()=>Et.poll(),processSemanticRequests:()=>mt.poll(),afterMailboxPoll:Me,shouldStop:()=>E||T!==void 0||xc({watcher:$,lastActivityAtMs:v,nowMs:ke(),idleTimeoutMs:c.idleTimeoutMs}),wait:q=>gn.wait(q),closeLanes:()=>Promise.all([mt.close("TypeScript semantic service stopped before completing the request."),Et.close("TypeScript index service stopped before completing the request.")]).then(()=>{}),mailboxFatalError:()=>T,finalizeStopped(){jl(d.statePath,{force:!0}),jl(d.activityPath,{force:!0}),h.release()},finalizeDegraded(q){return I={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${q.join("; ")}`},xe(!0),new Error(I.message)}})}function pg(e,t){let n=Ho(e);if(n.kind!=="worktree"||n.identity.worktreeId!==t)throw new Error(`Git worktree identity changed while starting the watch service for ${e}.`);return n.identity.gitDir}function mg(e,t={report:n=>console.error(n),exit:n=>$e.exit(n)}){return t.report(`watch-service: ${Aa(e instanceof Error?e.message:String(e))}`),t.exit(1)}var hg=$e.argv[1]?Jf(zf($e.argv[1])).href:null;if(hg===import.meta.url){let e=$e.argv[2],t=$e.argv[3],n=fg($e.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),$e.exitCode=1;else try{await to(e,t,n)}catch(i){mg(i)}}function fg(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}import{execFileSync as gg}from"child_process";import{existsSync as zn,lstatSync as yg,realpathSync as Ol}from"fs";import{dirname as bg,join as yt}from"path";var Nl=["- `scip-query search <exact-text>` \u2014 Where does this exact text occur in current project text, and which aligned compiler symbol owns each line? Requires: One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.","- `scip-query outline <file>` \u2014 What symbols and nesting exist in this file? Requires: One exact current project file path.","- `scip-query entrypoints [text]` \u2014 Which detected external roots or entry-surface candidates match this text? Requires: Optional exact text to filter candidates; otherwise the current indexed repository.","- `scip-query evidence` \u2014 Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap? Requires: One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.","- `scip-query inspect` \u2014 Which related source units across several known text, symbol, or location anchors should be read together? Requires: One or more exact text, symbol, or file:line selectors naming the unresolved behavior.","- `scip-query code <selectors...>` \u2014 What exact source defines these symbols, ranges, or file surfaces? Requires: One or more exact symbols, file:line ranges, or file paths.","- Choose graph controls explicitly: `execution incoming` \u2014 Who can call or reach this?; `execution outgoing` \u2014 What can this call or reach?; `dataflow incoming` \u2014 Where can this value come from?; `dataflow outgoing` \u2014 Where can this value go?; `runtime both` \u2014 Which producer and consumer rendezvous?; `state both` \u2014 What resource is observed or changed?; `temporal both` \u2014 What occurs before or after this?; `contract both` \u2014 What interface constrains this?; `identity both` \u2014 Are these observations the same entity?; `ownership both` \u2014 What contains or owns this?; `dependencies outgoing` \u2014 What does this statically rely on?. The CLI does not infer them from English intent.","- Calibration: exact is directly observed; derived is deterministically computed; candidate needs confirmation; mixed discloses its constituents; unknown cannot support a stronger claim. Read coverage and recovery before making absence claims.","- The controls above are complete for ordinary exploration. Run `scip-query capabilities --matrix` only when a named claim depends on uncertain provider support; do not run it for routine orientation."],Kn=[{stage:"locate",id:"search",command:"search <exact-text>",question:"Where does this exact text occur in current project text, and which aligned compiler symbol owns each line?",requiredInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",returnedFact:"exact cardinality, bounded identities and source, and scope commands that recover withheld matches",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned.",nonClaim:"Structural source ranking orders exact matches but does not establish task relevance. A literal co-occurrence does not establish a graph relationship.",outputCost:"small",contrasts:["outline: search locates exact text across files; outline enumerates compiler-owned constructs in one known file."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"outline",command:"outline <file>",question:"What symbols and nesting exist in this file?",requiredInput:"One exact current project file path.",returnedFact:"symbol names, nesting, and line ranges",evidenceCeiling:"Exact compiler-owned constructs and ranges when the file is indexed; no invented semantic overlay.",nonClaim:"File ownership and nesting do not establish execution or task relevance.",outputCost:"small",contrasts:["search: outline enumerates constructs in one known file; search locates exact text across current project text.","code: outline returns identities and ranges; code materializes exact source for selected identities."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"entrypoints",command:"entrypoints [text]",question:"Which detected external roots or entry-surface candidates match this text?",requiredInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",returnedFact:"entry symbols with files, confidence, evidence, and indexed caller counts",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",nonClaim:"A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress. Entry classification does not establish that the callable executes.",outputCost:"bounded",contrasts:["entry-map: entrypoints locates possible external roots; entry-map traverses static calls from one selected root.","search: entrypoints classifies callable roots; search only locates exact text and ownership."],gapClosingCommands:["evidence","inspect","code"]},{stage:"project",id:"evidence",command:"evidence",question:"Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap?",requiredInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",returnedFact:"batched exact selectors and typed graph relationships; compact endpoints with exact locations and follow-up commands; coverage and recoverable omissions; exact source-recovery command when source was requested with a graph projection; explicit ambiguity failure with exact rerun commands",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage.",nonClaim:"The projection does not infer which relationships are relevant to the user task. Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims.",outputCost:"bounded",contrasts:["refs: refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships.","call-graph: call-graph specializes in static calls; evidence can combine execution with other selected families.","value-flow: value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families.","dependence-slice: dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."],gapClosingCommands:["inspect","code"]},{stage:"read",id:"inspect",command:"inspect",question:"Which related source units across several known text, symbol, or location anchors should be read together?",requiredInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",returnedFact:"one ranked, deduplicated semantic packet plus exact selector cardinality and explicit expansion coverage",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit.",nonClaim:"A source packet does not choose which implementation details are relevant to the user task. A reference mention does not establish executable reachability.",outputCost:"potentially-large",contrasts:["code: inspect batches bounded behavior or source gaps; code materializes complete exact source.","evidence: inspect reads implementation units; evidence projects typed relationships without source."],gapClosingCommands:[]},{stage:"read",id:"code",command:"code <selectors...>",question:"What exact source defines these symbols, ranges, or file surfaces?",requiredInput:"One or more exact symbols, file:line ranges, or file paths.",returnedFact:"per-selector resolution, complete definition source, exact ranges with statically attributed same-file call closure, file export surfaces, omitted-local ledgers, and line ranges",evidenceCeiling:"Exact current source bytes for every resolved selector, with omitted file-local constructs disclosed.",nonClaim:"Source materialization does not establish callers, runtime reachability, or task relevance by itself.",outputCost:"potentially-large",contrasts:["inspect: code materializes complete exact source; inspect batches bounded behavior or source gaps.","outline: code reads selected implementations; outline enumerates file structure without reading every body."],gapClosingCommands:[]}];var ct="<!-- scip-query:agent-setup:begin -->",Nt="<!-- scip-query:agent-setup:end -->",vg="# scip-query:agent-setup",no=[".codex/hooks.json",".claude/settings.local.json"],Dl="# scip-query:local-agent-hooks:begin",ql="# scip-query:local-agent-hooks:end",Gl="hook-architecture-stop";function Vl(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 Jn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Sg(e,n),t.architectureHook!==!1&&Rg(e,n,t.architectureHook),n}function Ul(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Wl(e,"AGENTS.md",t,n),Hl(e,"CLAUDE.md")?n.unchanged.push("CLAUDE.md"):Wl(e,"CLAUDE.md",t,n),xg(e,t,n),$g(e,t,n),n}function Sg(e,t){let n=[ct,"## scip-query","","This repository uses scip-query as its primary code exploration surface.","","Native text and file tools show matching lines or file slices. scip-query is an indexed code-exploration surface that additionally resolves exact compiler-owned identities and typed execution, data, runtime, state, temporal, contract, identity, ownership, and dependency relationships. The agent chooses the repository question and relevant controls; the CLI returns observations without guessing task relevance.","","- Use scip-query for tracked repository text, including literal search and exact source reads. Native tools are for applying edits, running checks, binary content, or a specific unsupported gap reported by scip-query\u2014not a parallel exploration workflow.",...Nl,"- Treat commands as controls, not a checklist. Use every capability needed by the task, but make each query answer a distinct repository question. There is no mandatory command sequence or query-count limit. Thoroughness means understanding the relevant system end to end, not exhausting the repository.","- Use a discriminating exact `search`, `outline`, or `entrypoints` locator, then reuse every returned symbol or `file:line` as a graph root. Do not repeat generic synonym searches after usable candidates exist. There is no required anchor-discovery phase, and locator ordering does not establish relevance.","- When several implementations match the same vocabulary, do not select one by path, naming, apparent recency, or result order. Compare their entry surfaces, incoming execution, ownership, callers, or runtime connections; if the repository does not establish one as authoritative, explain the alternatives and their scopes.","- `evidence` requires one or more repeated `--symbol`, `--at`, or `--search` roots, one or more repeated `--edge <family>` flags, `--direction incoming|outgoing|both`, `--depth <n>`, and `--max-edges <n>`. Use `--subtype <subtype>` to narrow a family, `--connecting` when the roots themselves must be connected, and `--inventory-only` when counts are enough to choose the next projection.","- Treat execution and exact runtime handoffs as executable reachability. Other families describe what data moves, state changes, ordering occurs, contracts constrain, identities coincide, owners contain, or static dependencies require; they do not become call claims.","- Read request, observed facts, evidence calibration, coverage, and recovery together. Exact observations are facts within their reported coverage; derived observations are deterministic computations; candidate observations require confirmation. Missing or bounded output is not evidence of absence.","- An emitted `Continue exactly:` command is a cursor: a next-page read from one immutable rendered result. It is required transport, not optional evidence expansion. Run the emitted command unchanged and repeat until no continuation remains before interpreting that command's complete result. Do not rerun the original query or alter cursor flags. Continuation reads saved output without repository preparation, reindexing, or watcher startup. Printed recovery and expansion commands are different: run those only when their omitted evidence matters.","- Batch independent roots and source gaps when practical. `inspect --view behavior` returns connected behavior for named units; `code` returns exact source. Do not reread source already rendered by either command.","- After edits, use `scip-query diff-impact` when downstream consumers matter, `scip-query architecture` for declared boundaries, and `scip-query health --full` for configured quality or cleanup detectors.","- Prefer human output for agent reading. If a model-facing consumer genuinely needs JSON, add `--json --agent-output`; add `--result-only` only when the common envelope is unnecessary, and drain every emitted cursor before interpreting the result. Never send raw `--json` output through a model-facing terminal or tool. When a program needs the exhaustive machine payload, use `--json --json-output <path>` and inspect that file programmatically instead of injecting its complete contents into model context.","- Commit relevant `.scipquery/suppressions/*.json` records with the change. Do not commit local agent-tool settings.",Nt].join(`
|
|
13
|
-
`);if(Fl(e,"AGENTS.md",n,t),Hl(e,"CLAUDE.md")){t.unchanged.push("CLAUDE.md");return}let i=[ct,"@AGENTS.md",Nt].join(`
|
|
14
|
-
`);Fl(e,"CLAUDE.md",i,t,o=>o.includes("@AGENTS.md")&&!o.includes(ct))}function Hl(e,t){let n=yt(e,t);try{return yg(n).isSymbolicLink()?Ol(n)===Ol(yt(e,"AGENTS.md")):!1}catch{return!1}}function Fl(e,t,n,i,o){let r=yt(e,t),s=!1,a=io(r,t,i,c=>{if(o?.(c.text))return s=!0,{kind:"unchanged"};let l=wg(c.text,n);return l===c.text?{kind:"unchanged"}:{kind:"write",text:l,...c.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?i.unchanged.push(t):i.written.push(t))}function Wl(e,t,n,i){let o=yt(e,t);if(n.dryRun){if(!zn(o)){i.unchanged.push(t);return}try{let s=ae(o,"agent instruction file");s.includes(ct)?(_l(s),i.removed.push(t)):i.unchanged.push(t)}catch(s){i.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let r=io(o,t,i,s=>{if(!s.revision.exists||!s.text.includes(ct))return{kind:"unchanged"};let a=_l(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});r&&(r.changed?i.removed.push(t):i.unchanged.push(t))}function wg(e,t){if(Ql(e)==="present"){let i=new RegExp(`${ct}[\\s\\S]*?${Nt}`);return e.replace(i,t)}return e.length>0?`${e.replace(/\n*$/,`
|
|
15
|
-
|
|
16
|
-
`)}${t}
|
|
17
|
-
`:`${t}
|
|
18
|
-
`}function _l(e){Ql(e);let t=new RegExp(`${ct}[\\s\\S]*?${Nt}`),n=e.replace(t,"").replace(/\n{3,}/g,`
|
|
19
|
-
|
|
20
|
-
`).trim();return n.length===0?"":`${n}
|
|
21
|
-
`}function Ql(e){let t=e.split(ct).length-1,n=e.split(Nt).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(ct)<e.indexOf(Nt))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function io(e,t,n,i){try{return At(e,i,{maxRetries:0})}catch(o){n.skipped.push({target:t,reason:o instanceof Error?o.message:String(o)});return}}function $g(e,t,n){let i=".git/hooks/pre-commit",o=yt(e,i);if(!zn(o)){n.unchanged.push(i);return}if(!ae(o,"pre-commit hook").includes(vg)){n.skipped.push({target:i,reason:"pre-commit hook is not managed by scip-query"});return}if(t.dryRun){n.removed.push(i);return}io(o,i,n,()=>({kind:"delete"}))?.changed&&n.removed.push(i)}function Rg(e,t,n={}){let i=(n.inspectReadiness??Cg)(e);if(i.state==="not-configured")return;if(i.state==="blocked"){t.skipped.push({target:"architecture Stop hook",reason:i.reason});return}let o=n.commandPrefix??"scip-query";for(let r of no){if(Xl(e,r)){t.skipped.push({target:r,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}Jl(yt(e,r),r,t,s=>kg(s,o))}Ig(e,t)}function xg(e,t={},n){for(let i of no){let o=yt(e,i);if(zn(o)){if(Xl(e,i)){n.skipped.push({target:i,reason:"tracked repository config; the checkout-local hook remover will not modify it"});continue}if(t.dryRun){try{let r=Tg(o);JSON.stringify(Bl(r))!==JSON.stringify(r)&&n.removed.push(i)}catch(r){n.skipped.push({target:i,reason:Yn(r)})}continue}Jl(o,i,n,Bl,!0)}}}function Cg(e){let t=Ee(e);if(!t.architecture||t.architecture.boundaries.length===0)return{state:"not-configured"};let n=Ue(e,t),i=Te(e,t,n);if(i.state!=="fresh")return{state:"blocked",reason:`the index is ${i.state}; refresh it before installing a persistent architecture grader`};let o;try{o=Ca(e);let r=$t(It(o));return r.length>0?{state:"blocked",reason:`the current architecture baseline has ${r.length} enforced violation(s); make the declared policy clean before installing the Stop hook`}:{state:"ready"}}catch(r){return{state:"blocked",reason:Yn(r)}}finally{o?.close()}}function kg(e,t="scip-query"){let n=Kl(e.hooks),i=Array.isArray(n.Stop)?n.Stop:[];return{...e,hooks:{...n,Stop:[...zl(i),{hooks:[{type:"command",command:`${t} ${Gl}`,timeout:120,statusMessage:"Checking architecture boundaries"}]}]}}}function Bl(e){let t=Kl(e.hooks),n=Array.isArray(t.Stop)?t.Stop:[],i=zl(n),o={...t};i.length>0?o.Stop=i:delete o.Stop;let r={...e};return Object.keys(o).length>0?r.hooks=o:delete r.hooks,r}function Kl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function zl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Eg(n)):[]})).filter(t=>t.hooks.length>0)}function Eg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&new RegExp(`(?:^|\\s)${Gl}$`,"u").test(t)}function Jl(e,t,n,i,o=!1){try{At(e,s=>{let a=s.revision.exists?Yl(s.text,e):{},c=i(a);return JSON.stringify(c)===JSON.stringify(a)?{kind:"unchanged"}:o&&Object.keys(c).length===0?{kind:"delete"}:{kind:"write",text:`${JSON.stringify(c,null,2)}
|
|
22
|
-
`,mode:384}}).changed?"written"in n?n.written.push(t):n.removed.push(t):o||n.unchanged.push(t)}catch(r){n.skipped.push({target:t,reason:Yn(r)})}}function Tg(e){return Yl(ae(e,"agent hook settings"),e)}function Yl(e,t){let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Cannot update ${t}: the hook config is not a JSON object.`);return n}function Xl(e,t){try{return gg("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function Ig(e,t){let n=yt(e,".git","info","exclude");if(!zn(bg(n))){t.skipped.push({target:".git/info/exclude",reason:"Git metadata was not found; local hook files may appear as untracked"});return}try{At(n,i=>{let o=new RegExp(`${Dl}[\\s\\S]*?${ql}\\n?`,"gu"),r=i.text.replace(o,"").replace(/\n*$/u,""),s=[Dl,...no.map(c=>`/${c}`),ql].join(`
|
|
23
|
-
`),a=`${r}${r?`
|
|
24
|
-
|
|
25
|
-
`:""}${s}
|
|
26
|
-
`;return a===i.text?{kind:"unchanged"}:{kind:"write",text:a,mode:420}})}catch(i){t.skipped.push({target:".git/info/exclude",reason:Yn(i)})}}function Yn(e){return e instanceof Error?e.message:String(e)}import{existsSync as Xg}from"fs";import{randomUUID as Zg}from"crypto";import{existsSync as ro,mkdirSync as ed,rmSync as Ag}from"fs";import{homedir as Pg}from"os";import{dirname as td,isAbsolute as Lg,join as Xn,relative as Zl,resolve as jg}from"path";function nd(e,t){return t?jg(e,t):Xn(e,"docs","scip-query")}function id(e,t,n={}){let i=Xn(nd(e,n.dossierDir),"health-dossier.attempt.json"),o=Mg(i);ed(td(i),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
|
|
27
|
-
`;return ro(i)?wi(i,r,{durability:"durable"}):$i(i,r,{durability:"durable"}),{attemptPath:i,attempt:t,interrupted:o}}function od(e){Ag(e.attemptPath,{force:!0})}function Mg(e){if(!ro(e))return null;try{let t=JSON.parse(ae(e,"health dossier attempt"));return typeof t.runId!="string"||typeof t.startedAt!="string"?null:{runId:t.runId,startedAt:t.startedAt,indexGeneration:typeof t.indexGeneration=="string"?t.indexGeneration:null,...typeof t.completedAt=="string"?{completedAt:t.completedAt}:{}}}catch{return null}}function rd(e,t={}){let n=nd(e.projectRoot,t.dossierDir),i={markdownPath:Xn(n,"health-dossier.md"),jsonPath:Xn(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},o=Gg({...e,generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return Wg(i.markdownPath,Ng(o),i),_g(i.jsonPath,o,i),i}catch(r){return{...i,status:"failed",error:r instanceof Error?r.message:String(r)}}}function Ng(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${so(e.health)}`,`Index generation: ${e.indexGeneration??"unavailable"}`,...e.attempt?[`Audit attempt: ${e.attempt.runId} started ${e.attempt.startedAt}, completed ${e.attempt.completedAt??"not recorded"}`]:[],"","## Items That Need Attention","",...Og(e),"","## Blocked Or Unavailable Checks","",...Dg(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","",...qg(e),"","## JSON","",`Machine-readable report: \`${Fg(e)}\``,""].join(`
|
|
28
|
-
`)}`}function Og(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 Dg(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 qg(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function so(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Fg(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Wg(e,t,n){sd(e,t,n,"health dossier Markdown",i=>i===t)}function _g(e,t,n){let i=`${JSON.stringify(t,null,2)}
|
|
29
|
-
`;sd(e,i,n,"health dossier JSON",o=>Bg(o,i))}function sd(e,t,n,i,o){ed(td(e),{recursive:!0});let r=ro(e)?ae(e,i):null;if(r!==null&&o(r)){n.unchanged.push(e);return}r===null?$i(e,t,{durability:"durable"}):wi(e,t,{durability:"durable"}),n.written.push(e)}function Bg(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,delete n.attempt,delete i.attempt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function Gg(e,t){return oo(e,t)}function oo(e,t){return typeof e=="string"?Vg(e,t):Array.isArray(e)?e.map(n=>oo(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,oo(i,t)])):e}function Vg(e,t){if(e===t)return".";if(!Lg(e))return e;let n=Zl(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Zl(Pg(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as Ug}from"child_process";import{dirname as ad,join as Hg,resolve as Qg}from"path";import{fileURLToPath as Kg}from"url";var an={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 zg(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let o of an[i]?.packages??[])n.add(o);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function Zn(e){return[...new Set(e.filter(t=>an[t]!==void 0))].sort()}function cd(e,t=dd){let n=Zn(e),i=n.filter(o=>t.probe(an[o].ast));return{supportedLanguages:n,available:i,missing:n.filter(o=>!i.includes(o))}}function ld(e,t={}){let n=t.runtime??dd,i=t.packageRoot??Jg(),o=Zn(e),r=o.filter(m=>n.probe(an[m].ast)),s=o.filter(m=>!r.includes(m));if(s.length===0)return{supportedLanguages:o,availableBefore:r,installed:[],availableAfter:r,unavailable:[],attempted:!1};let a=Yg(i),c=zg(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let d=o.filter(m=>n.probe(an[m].ast));return{supportedLanguages:o,availableBefore:r,installed:l.ok?c:[],availableAfter:d,unavailable:o.filter(m=>!d.includes(m)),attempted:!0,...l.error?{error:l.error}:{}}}function Jg(){let e=ad(Kg(import.meta.url));for(;;){let t=Hg(e,"package.json");try{if(JSON.parse(ae(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=ad(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Yg(e){return JSON.parse(ae(Qg(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var dd={probe:e=>vn(e)==="ast",resetProbe:ir,install:(e,t)=>{let n=Ug(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 ud(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 pd(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"});let n=e.readiness.indexers.filter(i=>!i.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 md(e={}){let t=[],n=qe(),{projectRoot:i,paths:o,dbPath:r}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,c=Rt(n.config,{projectRoot:i}).filter(N=>N.level==="error"),l=null,d=null;if(c.length===0&&!n.config.collaborationDomainId)try{l=ua(i,n.config)}catch(N){d=Ot(N)}let m=l?.config??n.config,h=e.languages?pa(i,m,e.languages):null,p=h?.config??m,f=Rt(p,{projectRoot:i}),g=f.filter(N=>N.level==="error"),y=null,v=null;if(g.length===0&&p.watch?.enabled!==s)try{y=ma(i,p,s)}catch(N){v=Ot(N)}let $=y?.config??p,L=tn();G(t,{id:"collaboration-domain-config",label:"Collaboration domain",status:d!==null?"failed":c.length>0?"skipped":"ok",message:d??(c.length>0?"Skipped because the existing project config has validation errors.":l?.changed?"Generated the committed identity shared by merge-intended branches, clones, and forks.":"The committed collaboration-domain identity is already present."),...l?{details:[l.configPath]}:{}}),G(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:v!==null?"failed":g.length>0||!s?"skipped":"ok",message:v??(g.length>0?"Skipped because the existing project config has validation errors.":s?y?.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."),...y?{details:[y.configPath]}:{}});let _=jn();G(t,{id:"scip-cli",label:"scip CLI",status:L||!_?"ok":"warn",message:L?"scip CLI is available.":_?e.installIndexers===!0?"scip CLI is not installed; the reviewed release will be installed during the index refresh.":"scip CLI is required by SCIP_QUERY_SQLITE_CONVERTER=scip-cli but not installed; pass --install-missing to install the reviewed release.":"scip CLI is not installed and not required: SCIP is converted to SQLite in-process (SCIP_QUERY_SQLITE_CONVERTER=scip-cli selects the external converter)."});let I=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:_n({quiet:!0});G(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":I.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${I.installed.length} installed, ${I.alreadyLinked.length} already linked, ${I.pruned.length} pruned, ${I.skipped.length} skipped.`,details:[...I.pruned.map(N=>`Pruned ${N}`),...I.skipped.map(N=>`Skipped ${N}`)]});let T=y?Rt($,{projectRoot:i}):f,W=T.filter(N=>N.level==="error");G(t,{id:"config",label:"Project config",status:W.length>0?"failed":T.length>0?"warn":"ok",message:T.length===0?"Config OK.":`${T.length} diagnostic(s), ${W.length} error(s).`,details:T.map(N=>`${N.level.toUpperCase()} ${N.path}: ${N.message}`)});let E=Xe(i,$);G(t,{id:"readiness",label:"Indexer readiness",status:E.languages.length===0?"failed":E.indexers.some(N=>!N.runnable)?"warn":"ok",message:E.languages.length===0?"No supported project languages detected.":`Detected languages: ${E.languages.join(", ")}`,details:E.indexers.map(N=>`${N.runnable?"OK":N.installed?"WARN":"MISSING"} ${N.language}: ${N.binaryLabel}${N.note?` - ${N.note}`:""}`)});let B;if(e.installAstParsers===!0)B=ld(E.languages),G(t,{id:"ast-parsers",label:"AST parser packages",status:B.unavailable.length>0?"warn":"ok",message:B.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${B.availableAfter.length}/${B.supportedLanguages.length} selected language parser(s) available${B.installed.length>0?`; installed ${B.installed.join(", ")}`:""}.`,details:[...B.unavailable.length>0?[`Unavailable: ${B.unavailable.join(", ")}`]:[],...B.error?[B.error]:[]]});else{let N=cd(E.languages);B={supportedLanguages:N.supportedLanguages,availableBefore:N.available,installed:[],availableAfter:N.available,unavailable:N.missing,attempted:!1},G(t,{id:"ast-parsers",label:"AST parser packages",status:N.missing.length===0?"ok":"skipped",message:N.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":N.missing.length===0?`${N.available.length}/${N.supportedLanguages.length} selected language parser(s) available; nothing to install.`:"Skipped because installing missing parser packages requires explicit consent.",details:N.missing.length>0?[`Missing: ${N.missing.join(", ")}`]:[]})}let J=e.installIndexers===!0,F=J?py(i,E,t):[];if(!J){let N=E.indexers.filter(Bt=>!Bt.runnable);G(t,N.length===0?{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"Nothing to install: every detected language has a runnable indexer."}:{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent.",details:N.map(Bt=>`Missing ${Bt.language}: ${Bt.binaryLabel}`)})}let Y=Xe(i,$),pt=await ey({projectRoot:i,paths:o,config:$,readiness:Y,configHasErrors:W.length>0,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),et=pt.reindexResult,gn=pt.freshness,xe=Ke($),tt=ty({projectRoot:i,cacheDir:o.cacheDir,watchConfig:xe,readiness:Y,configHasErrors:W.length>0,reindexResult:et,postReindexFreshness:gn,steps:t}),Ge=Xe(i,$),mt=jt(Ge),Et=Te(i,$,o);G(t,{id:"capabilities",label:"Capability matrix",status:by(mt),message:vy(mt)}),e.onStatus?.(e.runHealth===!0?"Running optional full health audit\u2026":"Skipping optional full health audit.");let ve=e.runHealth===!0?id(i,{runId:Zg(),startedAt:new Date().toISOString(),indexGeneration:Qe(o.dbPath)},{dossierDir:e.dossierDir}):null;ve?.interrupted&&G(t,{id:"health-dossier-attempt",label:"Previous health audit",status:"warn",message:`A health audit started at ${ve.interrupted.startedAt} (index generation ${ve.interrupted.indexGeneration??"unavailable"}) did not complete; the dossier it would have written was never published.`,details:[ve.attemptPath]});let _t=e.runHealth===!0?await hy(o.dbPath,t):fy(t),Ce=Ge.languages.includes("rust")?kn(i,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;G(t,{id:"rust-semantic-session",label:"Rust semantic session",status:Ce===null?"skipped":Ce.valid?"ok":"failed",optional:Ce===null,message:Ce===null?"Skipped because Rust was not detected.":`${Ce.transport}/${Ce.state} selected from ${Ce.source}; ${Ce.fallback} fallback; opt out with ${Ce.optOut}.`});let Me=null;try{e.noAgentGuidance?G(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Me=Jn(i),G(t,{id:"agent-guidance",label:"Project agent guidance",status:Me.skipped.length>0?"warn":"ok",message:`${Me.written.length} written, ${Me.unchanged.length} already wired, ${Me.skipped.length} skipped.`,details:Me.skipped.map(N=>`Skipped ${N.target}: ${N.reason}`)}))}catch(N){G(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Ot(N)})}let q=ny({reindexResult:et,readiness:Ge,capabilities:mt,freshness:Et,health:_t,healthSelected:e.runHealth===!0,agentResult:Me,watchConfig:xe,watchService:tt,rustSemanticSession:Ce,steps:t});G(t,{id:"smoke-tests",label:"Setup smoke tests",status:iy(q),message:oy(q),details:q.map(N=>`${N.command}: ${N.status} - ${N.evidence}`)});let nt={repository:[...h?.changed?[h.configPath]:[],...y?.changed?[y.configPath]:[],...Me?.written??[]],checkout:[],user:[...I.installed,...B.installed,...F.filter(N=>N.attempted).map(N=>`${N.binaryLabel} installer`)]},he={projectRoot:i,dbPath:r,configuredDbPath:o.dbPath,scipCliInstalled:L,languages:Ge.languages,steps:t,skills:I,astParsers:B,initialReadiness:E,indexerRemediation:F,readiness:Ge,capabilities:mt,freshness:Et,reindex:et,automaticRefreshConfig:y,watchService:tt,rustSemanticSession:Ce,health:_t,smokeTests:q,healthDossier:null,setupAgent:Me,changeScopes:nt,filesWritten:Me?.written??[],verdict:co(t,Ge)};if(e.runHealth!==!0)return G(t,{id:"health-dossier",label:"Health dossier",status:"skipped",optional:!0,message:"Skipped because the optional health audit was not selected."}),he.verdict=co(t,Ge),he;ve&&(he.indexGeneration=ve.attempt.indexGeneration,he.attempt={...ve.attempt,completedAt:new Date().toISOString()});let ne=rd(he,{dossierDir:e.dossierDir});return ve&&ne.status!=="failed"&&od(ve),he.healthDossier=ne,he.changeScopes.repository.push(...ne.written),he.filesWritten=[...he.filesWritten,...ne.written],G(t,{id:"health-dossier",label:"Health dossier",status:ne.status==="failed"?"failed":"ok",message:ne.status==="failed"?ne.error:`${ne.written.length} written, ${ne.unchanged.length} unchanged.`,details:[ne.markdownPath,ne.jsonPath]}),he.verdict=co(t,Ge),he}async function ey(e){if(e.readiness.languages.length===0||e.configHasErrors)return G(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,i=null;try{let o=0,r=!1;for(let s=0;s<2;s+=1){if(n=await uc({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,maxHeapMb:e.config.indexer?.typescript?.maxHeapMb,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)}}),o+=n.durationMs,r||=!n.reused,i=Te(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&i.state==="stale"){t.push(`Index inputs changed during the first build (${i.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");G(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${r?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(o/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(o){G(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Ot(o),details:t})}return{reindexResult:n,freshness:i}}function ty(e){let t=e.readiness.languages.length===0?{reason:"Skipped because no supported languages were detected.",optional:!1}:e.configHasErrors?{reason:"Skipped because config validation has errors.",optional:!1}:e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?{reason:"Skipped because the initial refresh did not produce a complete fresh generation.",optional:!1}:null:{reason:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.",optional:!0};if(t===null&&!e.watchConfig.autoStart)return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",optional:!0,message:"Demand-started: the service starts with the first query that needs it (watch.autoStart=false); run scip-query watch --daemon to start it now."}),null;if(t!==null)return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",optional:t.optional,message:t.reason}),null;try{let n=Dn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ve,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 i=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${i}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Ot(n)}),null}}function hd(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${so(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:"),ao("Repository records (commit)",e.changeScopes.repository),ao("Checkout preferences (do not commit)",e.changeScopes.checkout),ao("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",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function ao(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function ny(e){let t=e.steps.find(o=>o.id==="reindex"),n=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:ry(e.steps),evidence:sy(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?ay(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",optional:!e.healthSelected,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:cy(e.readiness,e.freshness),evidence:ly(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:dy(e.capabilities),evidence:uy(e.capabilities)},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",...i?.optional===!0?{optional:!0}:{},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",...e.rustSemanticSession===null?{optional:!0}:{},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":n?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:n?.message??"Project agent guidance was not written."}]}function iy(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable"&&t.optional!==!0)?"warn":"ok"}function oy(e){let t=e.filter(o=>o.status==="pass").length,n=e.filter(o=>o.status==="unavailable").length,i=e.filter(o=>o.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function ry(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function sy(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function ay(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function cy(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function ly(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 dy(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function uy(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(o=>o.cleanupVerification.status==="available").length,n=e.matrix.filter(o=>o.cleanupVerification.status==="partial").length,i=e.matrix.filter(o=>o.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function py(e,t,n){let i=[];if(t.languages.length===0)return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=Mn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=lc(a,h=>c.push(h)):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 m=my($n(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:m,messages:c,recovery:m.runnable?void 0:m.note??m.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let o=i.filter(s=>!s.after.runnable),r=i.filter(s=>s.attempted);return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:o.length>0?"warn":"ok",message:o.length===0?`${r.length} install attempt(s); all detected indexers are runnable.`:`${r.length} install attempt(s); ${o.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function my(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function hy(e,t){if(!Xg(e)){let n="Skipped because no SQLite index database exists yet.";return G(t,{id:"health",label:"Health audit",status:"skipped",message:n}),lo(n)}try{let n=await Ma({full:!0,json:!0});return G(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),gy(n)}catch(n){let i=Ot(n);return G(t,{id:"health",label:"Health audit",status:"failed",message:i}),lo(i)}}function fy(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return G(e,{id:"health",label:"Health audit",status:"skipped",optional:!0,message:t}),lo(t)}function gy(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(yy),warnings:e.warnings??[]}}function yy(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:"Confirm this signal against its named source evidence before editing; fix it only when it matches the requested goal."}}function lo(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function co(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"&&n.optional!==!0)?"partial":"ready"}function by(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 vy(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 G(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Ot(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Sy}from"readline";function wy(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function $y(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 i=n[e.cursor]?.id;if(!i)return e;let o=new Set(e.selected);return o.has(i)?o.delete(i):o.add(i),{...e,selected:o}}async function fd(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=wy(e);Sy(t);let o=t.isRaw;t.setRawMode(!0),t.resume();let r=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
|
|
30
|
-
`),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
|
|
31
|
-
|
|
32
|
-
`),e.forEach((a,c)=>{let l=c===i.cursor?"\u203A":" ",d=i.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
|
|
33
|
-
`)}),n.write("\x1B[K")};r(!0);try{return await new Promise((s,a)=>{let c=(d,m)=>{if(m.ctrl&&m.name==="c"){l(),a(new Error("Setup cancelled."));return}if(m.name==="return"||m.name==="enter"){l(),n.write(`
|
|
34
|
-
`),s(i.selected);return}let h=m.name==="up"?"up":m.name==="down"?"down":m.name==="space"?"toggle":null;h&&(i=$y(i,h,e),r())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!o),t.pause()}}import{existsSync as Ry}from"fs";import{join as uo}from"path";function gd(e,t={}){let n=[],i=e.dryRun?"would ":"";if(e.global){for(let r of e.global.removed)n.push(` ${i}remove: ${r}`);if(t.verbose)for(let r of e.global.left)n.push(` left: ${r}`);else if(e.global.left.length>0){let r=e.global.left.length===1?"entry":"entries";n.push(` left: ${e.global.left.length} unrelated global skill ${r} (use --verbose to list)`)}for(let r of e.global.skipped)n.push(` skip: ${r}`)}if(e.project){for(let r of e.project.agentSetup.removed)n.push(` ${i}remove: ${r}`);for(let r of e.project.agentSetup.unchanged)n.push(` ok: ${r} (no managed block)`);for(let r of e.project.agentSetup.skipped)n.push(` skip: ${r.target} \u2014 ${r.reason}`);for(let r of e.project.left)n.push(` left: ${r}`)}return(e.global?.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 po(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 yd(e){let t=po(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=Mc({dryRun:e.dryRun,homeDir:e.homeDir})),t.project&&(n.project=xy(e.projectRoot,{dryRun:e.dryRun})),n}function xy(e,t={}){return{agentSetup:Ul(e,{dryRun:t.dryRun}),left:Cy(e)}}function Cy(e){return[[".scipquery.json",uo(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",uo(e,".scipquery","suppressions")],["docs/scip-query/",uo(e,"docs","scip-query")]].filter(([,t])=>Ry(t)).map(([t])=>t)}import{existsSync as bd,lstatSync as ky,readdirSync as Ey}from"fs";import{join as vd}from"path";function $d(e={}){let t=vd(e.cacheRoot??Yo(),"projects"),n={projectsDirectory:t,scannedCacheDirs:0,ownedCacheDirs:0,retainedRoots:0,orphanedRoots:0,stoppedServices:0,alreadyStoppedServices:0,skipped:[],failures:[]};if(!Sd(t))return n;let i=e.rootIsCurrent??Sd,o=e.stopService??qn;for(let r of Ey(t,{withFileTypes:!0}).sort((s,a)=>s.name.localeCompare(a.name))){let s=vd(t,r.name);if(n.scannedCacheDirs+=1,!r.isDirectory()||r.isSymbolicLink()){n.skipped.push({cacheDir:s,message:"not a regular cache directory"});continue}let a;try{a=Xo(s).record.canonicalProjectRoot,n.ownedCacheDirs+=1}catch(c){n.skipped.push({cacheDir:s,message:wd(c)});continue}if(i(a)){n.retainedRoots+=1;continue}try{if(Ty(s,a),i(a)){n.retainedRoots+=1;continue}n.orphanedRoots+=1,o({projectRoot:a,cacheDir:s,cliVersion:"orphan-prune"}).disposition==="stopped"?n.stoppedServices+=1:n.alreadyStoppedServices+=1}catch(c){n.failures.push({cacheDir:s,projectRoot:a,message:wd(c)})}}return n}function Ty(e,t){let n=En(e),i=$r(n.statePath),o=Rc(n.lockPath);if(bd(n.statePath)&&!i)throw new Error("watch state exists but is not a valid ownership record");if(bd(n.lockPath)&&!o)throw new Error("watch lock exists but is not a valid ownership record");if(i&&i.projectRoot!==t)throw new Error("watch state belongs to a different project root");if(o&&o.projectRoot!==t)throw new Error("watch lock belongs to a different project root");if(i&&o&&i.pid!==o.pid)throw new Error("watch state and lock name different process owners");if(i?.processIdentity&&o?.processIdentity&&!xn(i.processIdentity,o.processIdentity))throw new Error("watch state and lock name different process identities")}function Sd(e){try{let t=ky(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){let n=t.code;if(n==="ENOENT"||n==="ENOTDIR")return!1;throw t}}function wd(e){return e instanceof Error?e.message:String(e)}var Rd={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 xd(e,t){let n=Iy(t);return{...e,warnings:[...e.warnings??[],Rd.note,...n],capabilities:t,scoreInterpretation:Rd}}function Iy(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(i=>/syntax only/i.test(i.reason)?`${i.label}=partial (syntax only)`:i.status==="available"?null:`${i.label}=${i.status}`).filter(i=>i!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}import{createHash as Ay}from"crypto";import{basename as Py,join as Ly}from"path";function Td(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(o=>o!==void 0),i=t.decision;return[`Suppression ${e.disposition} at ${e.path}.`,` scope: ${n.join("; ")}`,` reason code: ${i?.reasonCode??"legacy/manual"}`,` counterevidence: ${i?.evidence.length??0} item(s)`,` expires: ${t.expiresAt??"none \u2014 no time limit; evidence invalidation still applies"}`,` revision: ${e.revision}`]}var cn=class extends Error{constructor(n,i,o){super(`${n} ${o?`Current revision: ${o}. Retry with --replace ${o} after reviewing it.`:"The suppression file was left untouched."}`);this.path=i;this.currentRevision=o;this.name="SuppressionWriteConflictError"}path;currentRevision};function Id(e,t,n,i,o){if(!vi.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${vi.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let r=n.map(s=>qy(e,s,i));return{kind:"automated-adjudication",reasonCode:t,decidedBy:"agent",policyVersion:1,...o?{observation:o}:{},evidence:r,invalidateOn:{targetContentChange:r.some(s=>s.contentHash!==void 0),detectorMajorChange:!0}}}function Ad(e,t,n={}){let i=n instanceof Date?{now:n}:n,o=My(t),r=Ny(i.expectedRevision),s=Ly(Sa(e),wa(o)),a=i.now??new Date,c="unchanged",l=At(s,d=>{if(!d.revision.exists){if(r)throw new cn(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:Ed(Cd(o,void 0,a,i.toolVersion))}}let m=jy(d);if(Oy(m.suppression,o))return c="unchanged",{kind:"unchanged"};if(!r)throw new cn(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(r!==d.revision.hash)throw new cn(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:Ed(Cd(o,m.suppression,a,i.toolVersion))}},{maxRetries:0,onBeforeCommit:i.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function jy(e){let t;try{t=JSON.parse(e.text)}catch(i){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:i})}let n=Ra(t,Dy(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function Cd(e,t,n,i=Ve){let o=n.toISOString(),{decision:r,createdAt:s,...a}=e,c={kind:ya,suppressionIdentity:$a(e),writer:{tool:"scip-query",version:i},...a,createdAt:t?.createdAt??s??o,...t?{updatedAt:o}:{}};return r?{...c,schemaVersion:va,decision:r}:{...c,schemaVersion:ba}}function My(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),i=e.check?.trim();if(!n&&!i)throw new Error("suppression requires an id or a check");if(e.decision!==void 0&&!la(e.decision))throw new Error("suppression decision is malformed");return{...n?{id:n}:{},...i?{check:i}:{},...e.file?{file:e.file}:{},reason:t,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function Ny(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 Oy(e,t){return JSON.stringify(kd(e))===JSON.stringify(kd(t))}function kd(e){let{createdAt:t,...n}=e;return n}function Dy(e){let t=Py(e);return t.endsWith(".json")?t.slice(0,-5):t}function Ed(e){return`${JSON.stringify(e,null,2)}
|
|
35
|
-
`}function qy(e,t,n){let i=t.indexOf(":");if(i<=0||i===t.length-1)throw new Error("--evidence must use <source|config|test|graph>:<referent>");let o=t.slice(0,i),r=t.slice(i+1).trim();if(o==="graph"){if(!r.startsWith("scip-query "))throw new Error("graph suppression evidence must name the exact scip-query command that produced it");return{kind:o,referent:r,claim:n}}if(o!=="source"&&o!=="config"&&o!=="test")throw new Error(`unsupported suppression evidence kind ${JSON.stringify(o)}`);let s=Go(r),a=St(e,s);return{kind:o,referent:s,claim:n,contentHash:Ay("sha256").update(a).digest("hex")}}import{execFileSync as Fy}from"child_process";var Wy={changedPaths:By,indexedPaths:e=>tr(e,{includeIgnored:!1}),architectureFindings:e=>$t(It(e))},_y=/\.(?:[cm]?[jt]sx?|vue|java|scala|kt|kts|rs|py|rb|go|c|cc|cpp|cxx|h|hh|hpp|hxx|cs|vb|dart|php|clj|cljs|cljc)$/iu;function Ld(e,t,n=Wy){let i=n.changedPaths(e);if(i.includes(".scipquery.json"))return{kind:"block",checkedSourceFiles:[],findings:[],reason:"Architecture policy changed in the same worktree as the implementation. Keep .scipquery.json policy changes in a separate reviewed change, then stop again."};let o=new Set(n.indexedPaths(t)),r=i.filter(a=>o.has(a)||_y.test(a));if(r.length===0)return{kind:"allow",checkedSourceFiles:[],findings:[]};let s=n.architectureFindings(t);return s.length===0?{kind:"allow",checkedSourceFiles:r,findings:[]}:{kind:"block",checkedSourceFiles:r,findings:s,reason:`scip-query found ${s.length} enforced architecture violation(s):
|
|
36
|
-
${s.map(a=>`- ${a}`).join(`
|
|
37
|
-
`)}
|
|
38
|
-
|
|
39
|
-
Inspect the boundary graph with: scip-query architecture`}}function jd(e){return e.kind==="block"?{decision:"block",reason:e.reason}:{}}function By(e){let t=Pd(e,["diff","--name-only","--diff-filter=ACMRTUXB","HEAD","--"]),n=Pd(e,["ls-files","--others","--exclude-standard","--"]);return[...new Set([...t,...n])].sort()}function Pd(e,t){try{return Fy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:10*1024*1024,killSignal:"SIGKILL"}).split(/\r?\n/u).map(n=>n.trim()).filter(Boolean)}catch(n){throw new Error(`Could not inspect changed files for the architecture Stop hook: ${Gy(n)}`,{cause:n})}}function Gy(e){return e instanceof Error?e.message:String(e)}var Uy=new Set(Gt),Dd=Z(({db:e})=>{try{let t=Ld(ue(),e);process.stdout.write(`${JSON.stringify(jd(t))}
|
|
40
|
-
`)}catch(t){let n=`scip-query could not verify architecture at Stop: ${t instanceof Error?t.message:String(t)}. The Stop was blocked because the architecture result is unknown.`;process.stdout.write(`${JSON.stringify({decision:"block",reason:n})}
|
|
41
|
-
`)}});function Hy(e){return e.filter(t=>Uy.has(t))}async function qd(e){let t=le(e),n=ue(),i=Ee(n),o=Ue(n,i),r=b(t,"json");try{let s=Hy(O(t,"language")),a=await Tc(n,i,o,{languages:s.length>0?s:i.languages,force:b(t,"force"),allowPartial:b(t,"allowPartial"),allowExpensiveRebuild:b(t,"allowExpensiveRebuild"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:b(t,"installMissing"),trustProjectTools:b(t,"trustProjectTools"),indexerConcurrency:K(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...r?{onStatus:()=>{}}:{onStatus:console.log}});if(r){P("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 Fd(){let e=ue(),t=Pi(e);try{let n=tc({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Wd(e){let t=le(e),n=ue(),i=Pi(n);try{let o=await dc({projectRoot:n,dbPath:i,tsconfig:w(t,"project")??"frontend/tsconfig.scip.json",onStatus:r=>console.log(r)});console.log(`Vue files: ${o.vueFiles}; resolved references: ${o.resolvedReferences}; inserted mentions: ${o.insertedMentions}; not-inserted identifier tokens: ${o.skippedReferences}; synthetic symbols: ${o.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${o.skippedReferenceReasons["no-definition"]}; same-file definition ${o.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${o.skippedReferenceReasons["unindexed-definition"]}; missing source ${o.skippedReferenceReasons["missing-source-file"]}; missing service script ${o.skippedReferenceReasons["missing-service-script"]}. Samples: ${o.skippedReferenceSamples.length} omitted, ${o.resolvedReferenceSamples.length} resolved.`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function _d(e){let t=le(e);Ne(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),o=xs(n,{base:w(t,"base")}),r=Cs(n,i,o.changedFiles,o.changedRanges);Pn(Jt,r)})}async function Bd(e){let t=le(e);try{let n=await Da({base:w(t,"base")});if(b(t,"json")){P("diff-impact",[],t,n.result,{observationReceipt:n.observationReceipt});return}qa(n.result)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Gd(e,t){let n=le(t),i=String(e).split(",").filter(o=>o.length>0);Ne(o=>{let r=[];for(let c of i)Xs.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),r.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=r.length===1?Zs(o,r[0],s):ea(o,r,s);Pn(Kt,a)})}async function Vd(e){let t=le(e);await ka(async n=>{let i=Number.parseInt(w(t,"shardIndex")??"",10),o=Number.parseInt(w(t,"shardCount")??"",10),r=Number.isSafeInteger(i)&&Number.isSafeInteger(o)&&o>1&&i>=0&&i<o?{index:i,count:o}:void 0,s=await ja(n,{scope:w(t,"scope"),full:b(t,"full"),...r?{shard:r}:{}});Pn(zt,s)})}async function Ud(e){let t=le(e);if(b(t,"writeBaseline")||b(t,"baseline")){Qy(t);return}try{let n=await Na({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:i,config:o,dbPath:r}=qe(),s=jt(Xe(i,o),{hasIndexedGraph:ln(r)}),a=xd(n.result,s);if(b(t,"json")){P("health",[],t,a,{observationReceipt:n.observationReceipt});return}Oa(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Qy(e){let t=w(e,"scope");Ne(n=>{if(b(e,"writeBaseline")){let o=Qs(n,{scope:t});console.log(`Baseline written to ${o.path} (${o.findingCount} finding(s)).`);return}let i=Ks(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let o of i.newFindings)console.log(` + ${o}`);process.exitCode=1})}function Hd(){let e=_n(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
42
|
-
${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 Qd(){let e=!1;tn()?console.log("scip CLI: installed"):jn()?(Oi(),e=!0):console.log("scip CLI: not installed (not required; SCIP is converted to SQLite in-process unless SCIP_QUERY_SQLITE_CONVERTER=scip-cli).");let t=ue(),n=Ee(t),i=Xe(t,n);if(i.languages.length===0){console.log(`
|
|
43
|
-
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
44
|
-
Detected languages: ${i.languages.join(", ")}`),console.log(`
|
|
45
|
-
Indexer readiness:`);for(let r of i.indexers){let s=r.runnable?" OK":r.installed?" WARN":" MISSING",a=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${s} ${r.language}: ${r.binaryLabel}${a}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}let o=cu(i);o.length>0&&console.log(`
|
|
46
|
-
Semantic provider readiness:`);for(let r of o){let s=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${r.language}: ${sb(r)}${lu(r)}`),r.reason&&console.log(` ${r.reason}`)}process.exitCode=e?1:0}function Kd(e){Ky(e)}function Ky(e){let t=le(e),{projectRoot:n,config:i,paths:o,dbPath:r}=qe(),s=Xe(n,i),a=Te(n,i,o),c=jt(s,{hasIndexedGraph:ln(r)&&a.state!=="missing"});if(b(t,"json")){P("capabilities",[],t,{...c,explorationControls:Kn,relationshipQuestions:Fn(),unavailableRelationshipFrontiers:In});return}ub(c,{matrix:b(t,"matrix")})}function zd(){let e=ue(),t=An(e),n=da(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 Jd(e){let t=le(e),n=ue(),i=Ee(n),o=xa(n),r=[...Rt(i,{projectRoot:n}),...o.compatibility.issues.map(s=>({level:"error",path:s.path,message:s.reason}))];if(b(t,"json"))P("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let s of r)console.log(`${s.level.toUpperCase()} ${s.path}: ${s.message}`);r.some(s=>s.level==="error")&&(process.exitCode=1)}function Yd(e,t){let n=le(t),i=w(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let o=w(n,"reasonCode"),r=O(n,"evidence");if(!o||r.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=ue(),a=(()=>{try{return Ne(()=>Pa())}catch{return}})(),c={id:String(e),check:w(n,"check"),file:w(n,"file"),reason:i,expiresAt:w(n,"expiresAt"),decision:Id(s,o,r,i,a)},l=Ad(s,c,{expectedRevision:w(n,"replace")});if(b(n,"json")){P("suppress",[String(e)],n,l);return}for(let d of Td(l,c))console.log(d)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}function Xd(e){let t=le(e),{report:n,hasIndexerProblems:i,hasErrors:o}=Zd("doctor");b(t,"json")?P("doctor",[],t,n):tb(n,i),process.exitCode=o?1:0}function Zd(e){let{projectRoot:t,config:n,paths:i,dbPath:o}=qe(),r=Rt(n,{projectRoot:t}),s=Xe(t,n),a=Te(t,n,i),c=ln(o),l=jt(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Ec(t,n,i),m=s.indexers.some(f=>!f.runnable),h=r.some(f=>f.level==="error")||m||a.state==="missing"||a.state==="stale",p=r.some(f=>f.level==="error")||m||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:o,configuredDbPath:i.dbPath,exists:c,configDiagnostics:r,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!h},hasIndexerProblems:m,hasErrors:p}}function eu(e){le(e);let t=ue(),n=Jn(t);for(let o of n.written)console.log(` done: ${o}`);for(let o of n.unchanged)console.log(` ok: ${o} (already wired)`);for(let o of n.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);let i=Vl(n);i.verdict==="ready"?console.log(`
|
|
47
|
-
Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
|
|
48
|
-
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(`
|
|
49
|
-
Project agent guidance was not configured: all ${i.skipped} selected target(s) were skipped.`),i.ready>0&&console.log("Configured agents can use compiler-backed exploration, impact, architecture, and health evidence. When declared architecture rules are ready, setup also installs the local architecture-only Stop hook."),process.exitCode=i.verdict==="ready"?0:1}async function tu(e){let t=le(e);try{let n=b(t,"guided"),i=b(t,"yes"),o=b(t,"json");ud({guided:n,yes:i,json:o,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let r=b(t,"installMissing"),s={dossierDir:w(t,"dossierDir"),runHealth:t.health===!0,installSkills:t.skills!==!1,installIndexers:r,installAstParsers:r&&t.parsers!==!1,...i?{automaticRefresh:!0}:{}},a=!o&&!i&&process.stdin.isTTY&&process.stdout.isTTY;(n||a)&&(s=await zy(s,{json:o})),o||(s.onStatus=l=>console.log(` ${l}`));let c=await md(s);o?P("setup",[],t,c):hd(c),process.exitCode=c.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function zy(e,t){let{projectRoot:n,config:i}=qe(),o=Xe(n,i),r=pd({files:Jy(n),watchEnabled:Ke(i).enabled,readiness:o}),s=o.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=r.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=Zn(o.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:e.runHealth===!0});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await fd([...s,...a]):new Set([...Yy(r.actions),...s.map(f=>f.id),...e.runHealth===!0?["run-health-analysis"]:[]]);l&&Xy(r.actions,d);let m=d.has("create-agent-guidance")||d.has("update-agent-guidance"),h=r.actions.some(f=>f.id==="enable-automatic-refresh"),p=r.actions.some(f=>f.id==="install-indexers");return{...e,...h?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noAgentGuidance:!m,...p?{installIndexers:l?d.has("install-indexers"):e.installIndexers===!0}:{},languages:o.languages.filter(f=>d.has(`language:${f}`)),installSkills:d.has("install-agent-skills"),installAstParsers:l?d.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:d.has("run-health-analysis")}}function Jy(e){return{agentsMd:ln(Md(e,"AGENTS.md")),claudeMd:ln(Md(e,"CLAUDE.md"))}}function Yy(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function Xy(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let i=e.filter(r=>r.scope===n&&t.has(r.id)).map(r=>r.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"}): ${i.length>0?i.join(", "):"none"}`)}}function nu(e){let t=le(e),n=po({global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let i=yd({projectRoot:ue(),global:n.global,project:n.project,dryRun:b(t,"dryRun")});if(b(t,"json")){P("uninstall",[],t,i);return}for(let o of gd(i,{verbose:b(t,"verbose")}))console.log(o)}async function iu(e){let t=le(e),n=K(t,"debounce"),i=K(t,"cooldown"),o=K(t,"gitPoll"),r=K(t,"idleTimeout"),s=b(t,"daemon"),a=b(t,"status"),c=b(t,"stop"),l=b(t,"prune"),d=b(t,"json"),m=[s,a,c,l].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, --stop, or --prune."),process.exitCode=1;return}if(d&&m===0){console.error("error: --json requires --daemon, --status, --stop, or --prune."),process.exitCode=1;return}let p=[["--debounce",n],["--cooldown",i],["--git-poll",o],["--idle-timeout",r]].filter(([,I])=>I!==void 0);if((a||c||l)&&p.length>0){console.error(`error: timing options (${p.map(([I])=>I).join(", ")}) only apply when starting a foreground or daemon watcher; ${l?"--prune does":"--status and --stop do"} not accept them.`),process.exitCode=1;return}let f=[["--debounce",n,!1],["--cooldown",i,!0],["--git-poll",o,!1],["--idle-timeout",r,!0]].find(([,I,T])=>I!==void 0&&(!Number.isInteger(I)||(T?Number(I)<0:Number(I)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}if(l){Zy(t,d);return}let g=ue(),y=Ee(g),v={...n===void 0?{}:{debounceMs:n},...i===void 0?{}:{cooldownMs:i},...o===void 0?{}:{gitPollMs:o},...r===void 0?{}:{idleTimeoutMs:r}};n&&((y.watch??={}).debounceMs=n),i!==void 0&&((y.watch??={}).cooldownMs=i),o&&((y.watch??={}).gitPollMs=o),r!==void 0&&((y.watch??={}).idleTimeoutMs=r);let $=Ke(y);y.watch=$;let L=Ue(g,y),_={projectRoot:g,cacheDir:L.cacheDir,cliVersion:Ve,watchOverrides:v};if(a){let I=ou(Lt(_),$.enabled);d?P("watch",[],t,I):ru(I);return}if(c){try{let I=qn(_);d?P("watch",[],t,I):console.log(I.disposition==="stopped"?`Stopped watch service${I.pid?` (pid ${I.pid})`:""}.`:"Watch service is already stopped.")}catch(I){console.error(`error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}return}if(!$.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(s){try{if(p.length>0){let T=Lt(_);if(T.classification.kind==="live")throw new Error(`watch service pid ${T.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 I=Dn(_);d?P("watch",[],t,I):(console.log(`${I.disposition==="started"?"Started":"Reused"} watch service for ${g} (pid ${I.state.pid}).`),p.length>0&&console.log(`Process-local timing overrides: ${p.map(([T,W])=>`${T}=${W}`).join(", ")}. These were not written to .scipquery.json.`))}catch(I){console.error(`error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}return}console.log(`Watching ${g}`),console.log(`Debounce: ${$.debounceMs}ms | Cooldown: ${$.cooldownMs}ms | Git poll: ${$.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
|
|
50
|
-
`);try{await to(g,Ve,v),console.log(`
|
|
51
|
-
Stopped.`)}catch(I){console.error(`
|
|
52
|
-
Watch error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}}function Zy(e,t){try{let n=$d();if(t)P("watch",[],e,n);else{console.log(`Watcher cleanup scanned ${n.scannedCacheDirs} cache ${n.scannedCacheDirs===1?"directory":"directories"}: stopped ${n.stoppedServices} orphaned service(s), found ${n.alreadyStoppedServices} already stopped, retained ${n.retainedRoots} live root(s), and skipped ${n.skipped.length} unowned or invalid entry/entries.`);for(let i of n.skipped)console.log(`Skipped ${i.cacheDir}: ${i.message}`);for(let i of n.failures)console.error(`error: could not clean ${i.cacheDir}: ${i.message}`)}n.failures.length>0&&(process.exitCode=1)}catch(n){console.error(`error: ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}}function ou(e,t=!0){let{classification:n}=e,i=nn(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:i}:{enabled:t,state:"stopped",mode:"none",refreshRequests:i};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:i,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:i,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return eb(n)}}function ru(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),Nd(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: ${Ea(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, ${ce(n.estimatedWriteBytes??n.estimatedLogicalOutputBytes)} estimated writes (${ce(n.estimatedLogicalOutputBytes)} logical output)${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),(n.reflinkedBytes!==void 0||n.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${ce(n.reflinkedBytes??0)} reflinked, ${ce(n.fallbackCopiedBytes??0)} byte-copied`);for(let[i,o]of Object.entries(n.byLanguage??{}).sort(([r],[s])=>r.localeCompare(s)))o&&console.log(`Reindex language ${i}: ${o.runs} run(s) (${o.rebuilt} rebuilt, ${o.reused} reused), ${ce(o.producedOutputBytes)} produced, ${cb(o.durationMs)} cumulative indexer time`);n.languageAttribution&&n.languageAttribution!=="complete"&&console.log(`Reindex language attribution: ${n.languageAttribution}; ${n.unattributedRuns??0} completed run(s) unattributed, ${n.invalidLanguageDetails??0} invalid detail(s) ignored`),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&&Nd(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,i=n.activeSessions===void 0||n.maxActiveSessions===void 0?"":`, ${n.activeSessions}/${n.maxActiveSessions} warm sessions`;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests${i}${n.sessionsEvicted?`, ${n.sessionsEvicted} evicted`:""})`),n.heapUsedBytes!==void 0&&console.log(`TypeScript index memory: ${ce(n.heapUsedBytes)}${n.heapLimitBytes===void 0?"":` / ${ce(n.heapLimitBytes)} heap`}${n.softMemoryLimitBytes===void 0?"":`; ${ce(n.softMemoryLimitBytes)} retirement mark`}${n.retireRequested?"; retirement requested":""}`)}}function Nd(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function eb(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function su(e){let t=le(e),{report:n}=Zd("status"),i=Ke(Ee(n.projectRoot)).enabled,o=ou(Lt({projectRoot:n.projectRoot,cacheDir:Vy(n.configuredDbPath),cliVersion:Ve}),i),r=nc(n.dbPath),s=fa(n.dbPath,n.freshness.metaPath),a=ha(n.dbPath),c=kn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){P("status",[],t,{...n,affectedSetShadow:r,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o,stats:lb(n.exists)});return}nb(n,{affectedSetShadow:r,capabilities:b(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o})}function tb(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),au(e.capabilities)}function nb(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 cu(e.readiness)){let i=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",o=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${o.padEnd(9)}${i}${lu(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: ${ab(e.freshness.lastRefresh)}`),ru(t.watchService),ib(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"),ob(t.sqliteGeneration),rb(t.localGenerations),console.log(`Shadow: ${ic(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),db(e.exists),t.capabilities&&(console.log(""),au(e.capabilities),console.log("Run `scip-query capabilities` for the semantic control manual."))}function au(e){let t=Od(e.capabilities),n=Od(e.relations);console.log(` Languages: ${e.languages.join(", ")||"(none detected)"}`),console.log(` Analysis readiness: ${t.available} available, ${t.partial} partial, ${t.unavailable} unavailable`),console.log(` Relationship providers: ${n.available} available, ${n.partial} partial, ${n.unavailable} unavailable`)}function Od(e){return{available:e.filter(t=>t.status==="available").length,partial:e.filter(t=>t.status==="partial").length,unavailable:e.filter(t=>t.status!=="available"&&t.status!=="partial").length}}function ib(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.baseGenerationId?.slice(0,12)??"none",n=e.activeGenerationId?.slice(0,12)??"none",i=e.lastAction??"none";console.log(`Shared: ${i}, base ${t}, active ${n}, ${e.generations} generation(s), ${ce(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${ce(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), ${ce(e.cleanup.deletedBytes??0)} removed`)}function ob(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",i=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(o=>o!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${i})`),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 rb(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${ce(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${ce(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 cu(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function sb(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function lu(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function ab(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",i=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${i}`}function cb(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function lb(e){if(e)return Ne(t=>{let n=Vt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function db(e){e&&Ne(t=>{let n=Vt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${ce(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function ub(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
|
|
53
|
-
Primary controls:`);for(let n of Kn)console.log(` ${n.stage.toUpperCase().padEnd(8)} scip-query ${n.command} [${n.outputCost}] \u2014 ${n.question}`);console.log(`
|
|
54
|
-
Relationship controls:`);for(let n of Fn()){let o=e.relations.find(r=>r.family===n.family)?.status??"unsupported";console.log(` ${o.toUpperCase().padEnd(11)} ${n.family} ${n.direction} \u2014 ${n.question}`)}if(console.log(`
|
|
55
|
-
Strengths: ${Object.keys(Qt).join(", ")}. Unavailable analyses: ${In.map(n=>n.id).join(", ")}.`),console.log(`
|
|
56
|
-
The agent chooses a question, family, and direction; this command reports support and does not infer intent.`),!t.matrix){console.log("Run `scip-query capabilities --matrix` only when a named claim needs contract or provider details.");return}pb(e),mb(e)}function pb(e){console.log(`
|
|
57
|
-
Control contracts:`);for(let t of Kn)console.log(` scip-query ${t.command}`),console.log(` Input: ${t.requiredInput}`),console.log(` Returns: ${t.returnedFact}`),console.log(` Ceiling: ${t.evidenceCeiling}`),console.log(` Does not establish: ${t.nonClaim}`),t.contrasts.length>0&&console.log(` Contrast: ${t.contrasts.join(" ")}`),t.gapClosingCommands.length>0&&console.log(` Close disclosed gaps with: ${t.gapClosingCommands.join(", ")}`);console.log(`
|
|
58
|
-
Relationship contracts:`);for(let t of Fn()){let i=e.relations.find(o=>o.family===t.family)?.status??"unsupported";console.log(` ${i.toUpperCase().padEnd(11)} ${t.family} ${t.direction}`),console.log(` Establishes: ${t.establishes}`),console.log(` Strengths: ${t.evidenceStrengths.join(", ")||"none registered"}`),console.log(` Provider ceilings: ${t.supportCeilings.join(", ")||"none registered"}`),console.log(` Does not establish: ${t.nonClaim}`)}console.log(`
|
|
59
|
-
Evidence strength legend:`);for(let[t,n]of Object.entries(Qt))console.log(` ${t.toUpperCase().padEnd(11)} ${n}`);console.log(`
|
|
60
|
-
Explicitly unavailable relationship analyses:`);for(let t of In)console.log(` ${t.id} [${t.families.join(", ")}]`),console.log(` ${t.capability}`),console.log(` Consequence: ${t.consequence}`),console.log(` Recover selected paths with: ${t.recoverWith.join(", ")}`)}function mb(e){console.log(`
|
|
61
|
-
Project capability matrix:`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);console.log(`
|
|
62
|
-
Relationship support:`);for(let t of e.relations){console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.family}`),console.log(` ${t.establishes}`),console.log(` Does not establish: ${t.nonClaims.join(" ")}`);for(let n of t.providerCapabilities)console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.id}: ${n.subtypes.join(", ")}`),console.log(` ${n.reason}`)}if(e.matrix.length!==0){console.log(`
|
|
63
|
-
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 Dt(e){return{...e,options:x(e.options)}}function lt({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Dt(l);return{...d,renderShape:"list",handler:Va({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c})}}function ei({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...m}){let h=Dt(m);return{...h,renderShape:"table",handler:Ua({commandName:h.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function du({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l,...d}){let m=Dt(d);return{...m,renderShape:"grouped-by-file",handler:Ha({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l})}}function mo({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Dt(l);return{...d,renderShape:"sectioned-report",handler:Ni({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}function uu({query:e,precomputed:t,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l,...d}){let m=Dt(d),h={commandName:m.id,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l},p=Ni({...h,query:e});return{...m,renderShape:"sectioned-report",handler:Qa(h,t,p)}}function xt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Dt(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:Ka(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}import{existsSync as Ub,mkdirSync as Hb,writeFileSync as Qb}from"fs";import{dirname as Kb,relative as zb}from"path";import{existsSync as dt,readdirSync as vb}from"fs";import{basename as Sb,dirname as bu,isAbsolute as vu,join as wb,relative as $b,resolve as dn,sep as Rb}from"path";import{spawnSync as fb}from"child_process";import{dirname as gb}from"path";function mu(e){let n=(e.spawnSync??fb)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:gb(e.specPath),maxBuffer:1024*1024*32,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let i=n.stdout??"";return i.includes("<?xml")?i:null}function hu(e){let t=bb(e),n=new Map,i=new Map,o=[],r=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?i.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(o.push(a),r.set(a.uid,a));let s=[];for(let a of o){let c=fu(a.block,n,i,r,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:o.map(a=>a.uniquename).sort(),actions:s}}var yb=8;function bb(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let i of e.matchAll(n)){let o=i.index,r=e.indexOf("</entry>",o),s=e.slice(o,r<0?e.length:r),a=ho(s,"uniquename"),c=ho(s,"kind"),l=ho(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:pu(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:pu(l),block:s})}return t}function fu(e,t,n,i,o,r,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,m,h]of l){if(m==="BuiltInKindRef"){let p=n.get(h)??"";p==="'"?d="write-next":p==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&p==="$Tuple"||d!=="write-next"&&(d="read");continue}if(m==="OpDeclNodeRef"){let p=t.get(h);if(!p)continue;d==="write-next"?(c.add(p),d="read"):d==="unchanged-run"||a.add(p);continue}if(m==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let p=i.get(h);if(p&&s<yb&&!r.has(p.uid)&&p.filename===o){let f=fu(p.block,t,n,i,o,new Set([...r,p.uid]),s+1);for(let g of f.reads)a.add(g);for(let g of f.writes)c.add(g)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function ho(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function pu(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var Su=["update","insert","delete"],wu=["select","query","findFirst","findMany"],fo=new Set([...Su,...wu]);function go(e){let t=e.methods&&e.methods.length>0?e.methods:[...fo],n=new Set(Su),i=new Set(wu);return{write:t.filter(o=>n.has(o)),read:t.filter(o=>i.has(o))}}var xb=/^(.*)@L(\d+)-L(\d+)$/;function yo(e){let t=e.match(xb);if(!t)return{ref:e};let n=t[1],i=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return n?i<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:o<i?{error:`codeRef "${e}" line window end (L${o}) is before its start (L${i})`}:{ref:n,window:{startLine:i,endLine:o}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var Cb=new Set(["auto","sany","tlc","apalache","none"]),ni=/^[A-Za-z_][A-Za-z0-9_]*$/;function $u(e){return Cb.has(e)}function ii(e,t){let n=[],i=Pe(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!dt(i))return{errors:[`map file not found: ${t}`]};let o;try{o=JSON.parse(fe(i,{inputKind:"TLA mapping",maxBytes:Tt}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let r=kb(o,n);return r?{loaded:{contract:r,mapPath:i,mapDir:bu(i)},errors:n}:{errors:n}}function Pe(e,t){if(!t)return null;let n=vu(t)?dn(t):dn(e,t);return bt(e,n)?n:null}function Ru(e,t,n){if(!n)return null;if(vu(n)){let s=dn(n);return bt(e,s)?s:null}let i=dn(e,n);if(bt(e,i)&&dt(i))return i;let o=dn(t,n);if(bt(e,o)&&dt(o))return o;let r=bt(e,i)?i:o;return bt(e,r)?r:null}function xu(e,t){let n=Pe(e,t);if(!n||!dt(n))return null;let i=fe(n,{inputKind:"TLA module",maxBytes:vt});return{path:n,modelParse:"regex-fallback",text:i,variables:Wb(i),operators:_b(i),actions:[]}}function Cu(e,t,n){let i=Pe(e,t);if(!i||!dt(i))return null;let o=fe(i,{inputKind:"TLA module",maxBytes:vt}),r=hu(n);return{path:i,modelParse:"sany",text:o,variables:r.variables,operators:r.operators,actions:r.actions}}function bo(e,t){let n=Pe(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!dt(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(fe(n,{inputKind:"TLA trace",maxBytes:vt})),o=Array.isArray(i)?i:ie(i)&&Array.isArray(i.steps)?i.steps:null;if(!o)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let r=[],s=[];for(let[a,c]of o.entries()){if(!ie(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}r.push({action:c.action,before:ie(c.before)?c.before:void 0,after:ie(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:r,errors:s}}catch(i){let o=i instanceof Error?i.message:String(i);return{steps:[],errors:[`trace file is not valid JSON: ${o}`]}}}function vo(e,t){let n=new Set,i=[];for(let o of t){let r=Pe(e,o)??o;n.has(r)||(n.add(r),i.push(o))}return i}function kb(e,t){if(!ie(e))return t.push("map file must contain a JSON object"),null;let n=Lb(e.variables,t);Pb(n,t);let i=qb(e.actions,n,t),o=Eb(e.init,t);Ib(o,i,t);let r={module:yu(e.module,"module",t),config:yu(e.config,"config",t),scope:Se(e.scope)??[],variables:n,actions:i,...o?{init:o}:{},invariants:Se(e.invariants)??[],traces:Se(e.traces)??[],unmappedWriteScope:Ab(e.unmappedWriteScope,t)};return Gb(e.scope,t),t.length===0?r:null}function Eb(e,t){if(e===void 0)return;if(!ie(e)){t.push("init must be an object when present");return}let n=Se(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=Tb(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function Tb(e,t){if(e===void 0)return;if(!ie(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 Ib(e,t,n){if(!e)return;let i=new Set(e.codeRefs),o=new Set;for(let r of Object.values(t))for(let s of r.code)i.has(s)&&o.add(s);o.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...o].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function Ab(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 Pb(e,t){ti(e,t,"alias",n=>n.aliases),ti(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),ti(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),ti(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:o,read:r}=go(i);return[...o,...r].map(s=>`${i.table}:${s}`)}))}function ti(e,t,n,i){let o=new Map;for(let[r,s]of Object.entries(e))for(let a of i(s)){let c=o.get(a);c?c.push(r):o.set(a,[r])}for(let[r,s]of o)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${r}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function Lb(e,t){if(!ie(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[i,o]of Object.entries(e)){if(!ni.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!ie(o)){t.push(`variables.${i} must be an object`);continue}let r=Eu(o.code);if(!r||r.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=Se(o.aliases)??[],a=Mb(o.resource,i,t),c=Nb(o.statements,i,t),l=Ob(o.ormCalls,i,t),d=Db(o.waive,i,t),m=jb(o.selfAlias,i,t),h=m?[...new Set([i,...s])]:[...new Set(s)];m===!1&&h.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${i}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${i} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${i}.waive with a reason`),n[i]={code:r,aliases:h,projection:typeof o.projection=="string"?o.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...m===!1?{selfAlias:!1}:{}}}return n}function jb(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 Mb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.resource must be an object when present`);return}let i=typeof e.path=="string"?e.path.trim():"";if(!i){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:i}}function Nb(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 i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.statements[${r}] must be an object`);return}let s=typeof o.pattern=="string"?o.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${r}].pattern must be a non-empty string`);return}try{yn(s,`variables.${t}.statements[${r}].pattern`)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${r}].pattern is not a valid regular expression: ${c}`);return}i.push({pattern:s})}),i.length>0?i:void 0}function Ob(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 i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.ormCalls[${r}] must be an object`);return}let s=typeof o.table=="string"?o.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${r}].table must be a non-empty string`);return}if(o.methods===void 0){i.push({table:s});return}let a=Se(o.methods);if(!a){n.push(`variables.${t}.ormCalls[${r}].methods must be an array of strings when present`);return}let c=a.filter(l=>!fo.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${r}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...fo].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function Db(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.waive must be an object when present`);return}let i=typeof e.reason=="string"?e.reason.trim():"";if(!i){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:i}}function qb(e,t,n){if(!ie(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let i=new Set(Object.keys(t)),o={};for(let[r,s]of Object.entries(e)){if(!ni.test(r)){n.push(`invalid TLA+ action name: ${r}`);continue}if(!ie(s)){n.push(`actions.${r} must be an object`);continue}let a=Eu(s.code);if(!a||a.length===0){n.push(`actions.${r}.code must name at least one TypeScript referent`);continue}for(let h of a){let p=yo(h);"error"in p&&n.push(`actions.${r}.code: ${p.error}`)}let c=Se(s.reads)??[],l=Se(s.writes)??[],d=Se(s.calls)??[];for(let h of[...c,...l])i.has(h)||n.push(`actions.${r} references unknown variable: ${h}`);let m=Fb(s.waive,s.allowUnknown===!0,c,l,i,r,n);o[r]={code:a,reads:c,writes:l,calls:d,...m?{waive:m}:{}}}return o}function Fb(e,t,n,i,o,r,s){if(ie(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${r}.waive.reason must be a non-empty string`);let c=Se(e.reads)??[],l=Se(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${r}.waive must list reads or writes`),gu(r,"reads",c,o,s),gu(r,"writes",l,o,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${r}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(i)],reason:"legacy allowUnknown",legacy:!0}}function gu(e,t,n,i,o){for(let r of n)i.has(r)||o.push(`actions.${e}.waive.${t} references unknown variable: ${r}`)}function Wb(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let i=n[1]??"";for(let o of i.split(",")){let r=o.trim();ni.test(r)&&t.add(r)}}return[...t].sort()}function _b(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 Bb=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function ku(e){if(!e||!dt(e))return[];let t=fe(e,{inputKind:"TLA checker configuration",maxBytes:Tt}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let o of t.split(/[\s,]+/))if(o){if(Bb.has(o)){i=o==="INVARIANT"||o==="INVARIANTS";continue}i&&ni.test(o)&&n.add(o)}return[...n].sort()}function yu(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function Eu(e){return typeof e=="string"?[e]:Se(e)}function Gb(e,t){e!==void 0&&(Se(e)||t.push("scope must be an array of strings when present"))}function oi(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Vb=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Tu(e,t){if(!dt(t))return{status:"none"};let i=fe(t,{inputKind:"TLA module",maxBytes:vt}).match(Vb)?.[1],o=$b(e,t).split(Rb).join("/"),r=Sb(t),s=new Set([i,o,r,r.replace(/\.tla$/i,"")].filter(d=>!!d)),a=bu(t);if(!dt(a))return{status:"none"};let c=[];for(let d of vb(a)){if(!d.endsWith(".scip-tla.json"))continue;let m=wb(a,d),h;try{h=JSON.parse(fe(m,{inputKind:"TLA mapping candidate",maxBytes:Tt}))}catch{continue}ie(h)&&typeof h.module=="string"&&s.has(h.module)&&c.push(m)}c.sort();let l=i??o;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function ri(e,t,n,i,o={count:e.length,loc:i}){let r=o.count===e.length&&o.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${o.count}, ${i} of ${o.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${r}) \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((m,h)=>m+h.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((m,h)=>m.startLine-h.startLine);for(let m of d){let h=m.implicitUsageReason?` [implicit usage: ${m.implicitUsageReason}]`:"";console.log(` ${ge(m.startLine,m.endLine)} (${m.loc} LOC) ${m.shortName}${h}`)}}}var So=20,Au=te("dead",({db:e,args:t,opts:n,budget:i})=>{let o={scope:H(t,0)||void 0,minLoc:k(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},r=_r(e,o),s=r.symbols.filter(F=>F.kind==="dead-code"),a=r.symbols.filter(F=>F.kind==="file-internal"),c=r.symbols.filter(F=>F.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),m=!b(n,"onlyDead")&&!b(n,"onlyInternal"),h=l?s:[],p=d?a:[],f=m?c:[],g=h.reduce((F,Y)=>F+Y.loc,0),y=p.reduce((F,Y)=>F+Y.loc,0),v=f.reduce((F,Y)=>F+Y.loc,0),$=b(n,"full"),L=$?h:h.slice(0,So),_=$?p:p.slice(0,So),I=$?f:f.slice(0,So),T=L.reduce((F,Y)=>F+Y.loc,0),W=_.reduce((F,Y)=>F+Y.loc,0),E=I.reduce((F,Y)=>F+Y.loc,0),B={total:h.length+p.length+f.length,deadCode:h.length,fileInternal:p.length,implicitUsage:f.length,loc:g+y+v};if(b(n,"json")){P("dead",t,n,{...r,shown:{deadCode:h,fileInternal:p,implicitUsage:f},shownCounts:B,totals:{total:r.counts.total,deadCode:r.counts.deadCode,fileInternal:r.counts.fileInternal,implicitUsage:r.counts.implicitUsage,loc:r.counts.loc}},{analysisBudget:i.analysisBudget});return}if(h.length===0&&p.length===0&&f.length===0){A.empty("No matching dead-code symbols found.");return}h.length>0&&(ri(L,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
64
|
-
Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,T,{count:h.length,loc:g}),!$&&h.length>L.length&&console.log(`
|
|
65
|
-
Showing top ${L.length} by LOC. Re-run with --full for the remaining ${h.length-L.length}.`)),p.length>0&&(h.length>0&&console.log(""),ri(_,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
66
|
-
single-use helper, an abstraction-in-progress, or a callback registered
|
|
67
|
-
through a framework path that static analysis cannot trace (signal
|
|
68
|
-
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
69
|
-
review case by case.`,W,{count:p.length,loc:y}),!$&&p.length>_.length&&console.log(`
|
|
70
|
-
Showing top ${_.length} by LOC. Re-run with --full for the remaining ${p.length-_.length}.`)),f.length>0&&((h.length>0||p.length>0)&&console.log(""),ri(I,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
|
|
71
|
-
consumer that the static reference graph cannot trace. Investigation
|
|
72
|
-
signals only \u2014 not deletion candidates and not counted as dead code.`,E,{count:f.length,loc:v}),!$&&f.length>I.length&&console.log(`
|
|
73
|
-
Showing top ${I.length} by LOC. Re-run with --full for the remaining ${f.length-I.length}.`));let J=[];l&&J.push(`${h.length} dead code (${g} LOC)`),d&&J.push(`${p.length} file-internal (${y} LOC)`),m&&J.push(`${f.length} implicit usage (${v} LOC)`),console.log(`
|
|
74
|
-
\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: ${h.length+p.length+f.length} symbols \u2014 ${J.join(" + ")}`)}),Pu=Ie("unused-imports",{query:({db:e,args:t,budget:n})=>Ur(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
75
|
-
${e.length} unused import(s)`)}),Lu=za("isolated",{query:({db:e,opts:t,budget:n})=>ts(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ge(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
|
|
76
|
-
${e.length} isolated symbol(s)`)}),ju=te("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=vs(e,{scope:w(n,"scope"),minLoc:k(n,"minLoc",10),minCallees:k(n,"minCallees",6),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){P("extract-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No extraction candidates found.");rt("extraction candidates");for(let r of o){console.log(`
|
|
77
|
-
${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC, ${r.totalCallees} callees)`),console.log(` Kind: ${r.extractionKind}; tier: ${r.actionTier}`),console.log(` Recommendation: ${r.recommendation}`);for(let s of r.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<r.regions.length;s++){let a=r.regions[s];console.log(` Region ${s+1} ${ge(a.startLine,a.endLine)} (${a.lines} lines, ${a.kind}, ${a.callees.length} exclusive callees):`);for(let c of a.callees)console.log(` ${c}`);a.inboundLocals.length>0&&console.log(` needs: ${a.inboundLocals.join(", ")}`),a.outboundLocals.length>0&&console.log(` returns: ${a.outboundLocals.join(", ")}`),a.ambientCallees.length>0&&console.log(` also uses ambient: ${a.ambientCallees.join(", ")}`)}}console.log(`
|
|
78
|
-
${o.length} extraction candidate(s) found.`)}),Mu=te("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=Ss(e,{target:H(t,0)||void 0,scope:w(n,"scope"),minConsumers:k(n,"minConsumers",1),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){P("locality-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No locality candidates found.");rt("locality candidates");for(let r of o){let s=r.sourceUnit.kind==="symbol"&&r.sourceUnit.startLine!==void 0&&r.sourceUnit.endLine!==void 0?V(r.sourceUnit.file,r.sourceUnit.startLine,r.sourceUnit.endLine):r.sourceUnit.file;if(console.log(`
|
|
79
|
-
${s} ${r.sourceUnit.shortName}`),console.log(` Current directory: ${r.currentDirectory}; tier: ${r.recommendedTier}; action: ${r.actionTier}`),console.log(` Consumer coverage: ${r.consumerCoverage}; consumers: ${r.consumerFiles.length}`),r.nearestCommonOwner&&console.log(` Nearest common owner: ${r.nearestCommonOwner}`),r.suggestedHome&&console.log(` Suggested home: ${r.suggestedHome}`),r.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${r.whyNoSuggestedHome}`),r.boundaryMarkers.length>0&&console.log(` Boundary markers: ${r.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${r.recommendation}`),r.consumerFiles.length>0){for(let a of r.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);r.consumerFiles.length>8&&console.log(` - ... ${r.consumerFiles.length-8} more consumer(s)`)}for(let a of r.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
|
|
80
|
-
${o.length} locality candidate(s) found.`)}),Nu=Ie("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Hs(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
81
|
-
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, body: ${e.bodyShape}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
82
|
-
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
83
|
-
${e.length} wrapper candidate(s).`)}),Ou=Ie("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Ps(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
84
|
-
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
85
|
-
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
86
|
-
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
87
|
-
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
88
|
-
${e.length} passthrough candidate(s).`)}),Du=Ie("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Us(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),limit:D(t,"limit",30),includeLowConfidence:b(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}] ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
89
|
-
${e.reason}
|
|
90
|
-
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
91
|
-
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
92
|
-
${e.length} stale abstraction(s).`)}),qu=Ln("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Js(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",10),limit:D(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]}),Fu=Fe("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(b(n,"plan")){let r=H(t,0),s=H(t,1);if(!r||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:ls(e,r,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let o=H(t,0);return o?{mode:"target",rows:cs(e,o,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:ds(e,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scope:w(n,"scope"),minCallees:k(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.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(`
|
|
93
|
-
${Math.round(t.similarity*100)}% ${n}
|
|
94
|
-
`),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}
|
|
95
|
-
`),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let i of t.sharedEvidence)console.log(` ${i}`);if(t.uniqueToA.length>0){console.log(`
|
|
96
|
-
Unique to A (${t.uniqueToA.length}):`);for(let i of t.uniqueToA)console.log(` ${i}`)}if(t.uniqueToB.length>0){console.log(`
|
|
97
|
-
Unique to B (${t.uniqueToB.length}):`);for(let i of t.uniqueToB)console.log(` ${i}`)}console.log(`
|
|
98
|
-
Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){A.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",o=n==="source-tokens"?"Only tokens in":"Only in",r=[`
|
|
99
|
-
${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${i}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&r.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&r.push(` ${o} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&r.push(` ${o} B: ${t.uniqueToB.join(", ")}`),r.join(`
|
|
100
|
-
`)});return}A.list(e.rows,t=>`
|
|
101
|
-
${Math.round(t.similarity*100)}% similar:
|
|
102
|
-
A: ${t.shortNameA} (${t.fileA})
|
|
103
|
-
B: ${t.shortNameB} (${t.fileB})
|
|
104
|
-
Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
|
|
105
|
-
Recommendation: ${t.recommendation}
|
|
106
|
-
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
107
|
-
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
108
|
-
${e.rows.length} similar pair(s) found.`)}}),Wu=ft({commandName:"similar-files",query:({db:e,args:t,opts:n})=>us(e,{minSimilarity:k(n,"minSimilarity",.5),limit:D(n,"limit",20),scope:w(n,"scope"),minDeps:K(n,"minDeps"),filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
109
|
-
${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(`
|
|
110
|
-
`)}),console.log(`
|
|
111
|
-
${e.length} similar pair(s) found.`)}}),_u=ft({commandName:"similar-chains",query:({db:e,opts:t})=>bs(e,{minSimilarity:k(t,"minSimilarity",.5),limit:D(t,"limit",15),scope:w(t,"scope"),minChainLength:k(t,"minLength",3),maxChainLength:k(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(`
|
|
112
|
-
\u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
|
|
113
|
-
${e.length} similar chain pair(s) found.`)}}),Bu=Fe("drift",{query:({db:e,args:t,opts:n,budget:i})=>Vs(e,{scope:H(t,0),minDeviation:k(n,"minDeviation",5),semantic:i.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:D(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),A.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",o=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&o.push(` ${t.detail}`),o.join(`
|
|
114
|
-
`)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(i=>i.policyStatus==="undeclared").length;if(console.log(`
|
|
115
|
-
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 i of t.reciprocalPairs)console.log(` ${i.boundaries[0]} <-> ${i.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let i of t.cycles){let o=i.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${i.boundaries.join(", ")} }${o}`)}}}console.log(`
|
|
116
|
-
${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)`:""}`)}}),Gu=Fe("convergence",{query:({db:e,args:t,budget:n})=>ta(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(`
|
|
117
|
-
${Math.round(e.similarity*100)}% callee overlap
|
|
118
|
-
`),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)
|
|
119
|
-
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
120
|
-
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
121
|
-
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
122
|
-
Strategy: ${e.consolidationStrategy}`)}}}),Vu=Ie("similar-signatures",{query:({db:e,opts:t,budget:n})=>sa(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),maxShapeFrequency:k(t,"maxShapeFrequency",12),limit:D(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
|
|
123
|
-
Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
124
|
-
`);return`${n}
|
|
125
|
-
${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
126
|
-
${e.length} group(s) found.`)}),Iu=[],Uu=Ie("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>{let i=Is(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),minLoc:k(t,"minLoc",3),limit:D(t,"limit",20),scanLimit:n.scanLimit});return Iu=i.exclusions,i.groups},format:e=>{let t=`
|
|
127
|
-
Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,o)=>` ${(o===0?"canonical":"duplicate").padEnd(9)} ${V(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
128
|
-
`);return`${t}
|
|
129
|
-
${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>{for(let t of Iu)console.log(`Policy exclusion: ${t.count} ${t.detail}`);console.log(`
|
|
130
|
-
${e.length} group(s) found.`)}}),Hu=Ie("twin-drift",{query:({db:e,opts:t,budget:n})=>As(e,{scope:w(t,"scope"),minSimilarity:k(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
131
|
-
${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
132
|
-
`),i=e.firstDivergentTokens?`
|
|
133
|
-
first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
|
|
134
|
-
${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
|
|
135
|
-
${e.length} group(s) found.`)}),Qu=Ie("not-implemented",{query:({db:e,opts:t,budget:n})=>Ms(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
|
|
136
|
-
${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
|
|
137
|
-
${e.length} reachable placeholder stub(s).`)}),Ku=Ie("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Ns(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(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(`
|
|
138
|
-
${e.length} decorative checker candidate(s).`)}),zu=te("test-quality",({db:e,args:t,opts:n,budget:i})=>{let o=Os(e,{scope:w(n,"scope"),limit:D(n,"limit",30),scanLimit:i.scanLimit,rotDays:K(n,"rotDays")});if(b(n,"json")){P("test-quality",t,n,o,{analysisBudget:i.analysisBudget});return}if(rt("test-quality findings"),o.assertionFree.length+o.skipped.length+o.mockEcho.length===0){A.empty("No test-quality findings.");return}o.assertionFree.length>0&&(console.log(`
|
|
139
|
-
ASSERTION-FREE (${o.assertionFree.length})`),A.list(o.assertionFree,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),o.skipped.length>0&&(console.log(`
|
|
140
|
-
SKIPPED (${o.skipped.length})`),A.list(o.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),o.mockEcho.length>0&&(console.log(`
|
|
141
|
-
MOCK-ECHO (${o.mockEcho.length})`),A.list(o.mockEcho,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
|
|
142
|
-
${o.assertionFree.length} assertion-free, ${o.skipped.length} skipped, ${o.mockEcho.length} mock-echo.`)}),Ju=ft({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let i=M(t,0),o=M(t,1),r=w(n,"out")??Ls(i,o),s=Pe(e.config.projectRoot,r);if(!s)throw new Error(`twin-ab output path escapes the project root: ${r}`);let a=js(e,{refA:i,refB:o,outFile:s});if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=zb(e.config.projectRoot,s);if(!b(n,"force")&&Ub(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return Hb(Kb(s),{recursive:!0}),Qb(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
|
|
143
|
-
Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${V(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${V(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(`
|
|
144
|
-
Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),Yu=te("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let o=Rs(e,{scope:w(n,"scope"),minLoc:k(n,"minLoc",1),maxDepth:k(n,"maxDepth",5),scanLimit:i.scanLimit}),r=ue(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(o.batches.length===0){if(a){P("cleanup-plan",t,n,o,{analysisBudget:i.analysisBudget});return}return A.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Kc(o),d=c?Gc(r,o):void 0;if(a){P("cleanup-plan",t,n,{result:o,verification:d},{analysisBudget:i.analysisBudget});return}if(s){let m=zc(d,l);if(m.length>0){for(let p of m)console.error(`error: ${p}`);process.exitCode=1;return}let h=Qc(r,l);if(h.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), ${o.totalLoc} LOC.`),console.log(h);return}console.log(`Cleanup plan: ${o.totalSymbols} symbol(s), ${o.totalLoc} LOC across ${o.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
|
|
145
|
-
`);for(let m of o.batches){let h=m.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${m.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${m.depth}: dead once batch ${m.depth-1} lands (cascade, ${m.loc} LOC) \u2500\u2500`;console.log(h);for(let p of m.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);m.filesEmptied.length>0&&console.log(` -> empties: ${m.filesEmptied.join(", ")}`),console.log("")}if(o.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let m of o.blocked)console.log(` ${m.shortName} (${m.file}) blocked by ${m.blockingFiles.join(", ")}`)}if(d){if(console.log(`
|
|
146
|
-
Verifying batches against the project checker (isolated snapshot of committed 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 p of d.checkers)console.log(` Checker: ${p}`);if(d.unavailableReason){console.log(` UNAVAILABLE: ${d.unavailableReason}.`);return}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 p=d.dirtyWorkingTree.slice(0,5),f=d.dirtyWorkingTree.length-p.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${p.join(", ")}${f>0?`, ... ${f} more`:""}`)}let m=Jb(d.checkers),h=Yb(d.checkers);for(let p of d.batches)if(p.status==="verified")console.log(` Batch ${p.depth}: VERIFIED (${m})${h}`);else{console.log(` Batch ${p.depth}: FAILED${p.reason?` (${p.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let f of p.errors??[])console.log(` ${f}`)}}});function Jb(e){return e.join(", ")}function Yb(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var Xu=te("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let o=b(n,"full"),r=Ds(e,{windowCommits:k(n,"window",100),minSimilarity:K(n,"minSimilarity"),limit:D(n,"limit",30),scope:w(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:o?"full":"bounded"});if(b(n,"json")){P("recent-duplicates",t,n,r,{analysisBudget:i.analysisBudget});return}if(!r.available)return A.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return A.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);rt("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
|
|
147
|
-
`);let s=r.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 r.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(`
|
|
148
|
-
${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Zu=Z(({db:e,args:t,opts:n})=>{let i=b(n,"full"),o=Ts(e,{doc:t[0]===void 0?void 0:M(t,0),limit:D(n,"limit",20),minCoupling:k(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(b(n,"json")){P("doc-drift",t,n,o);return}if(!o.available)return A.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return A.empty(`No drifting docs found across ${o.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);rt("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${o.docsScanned} docs scanned, ${o.commitsAnalyzed} commits analyzed):
|
|
149
|
-
`);for(let r of o.findings){let s=r.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=r.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${r.staleness} ${r.doc}${s}${a}`);for(let c of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of r.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 m=c.citationContexts?.[0];m&&console.log(` cited claim: ${La(m)}`)}}console.log(`
|
|
150
|
-
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),ep=Ie("unused-params",{query:({db:e,opts:t,budget:n})=>zs(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
151
|
-
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(`
|
|
152
|
-
${e.length} function(s) with trailing unused parameters.`)});var tp=Fe("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>ps(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
153
|
-
${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(`
|
|
154
|
-
`)}),console.log(`
|
|
155
|
-
${e.length} duplicated React component pair(s) found.`)}}),np=Fe("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>ms(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
156
|
-
${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(`
|
|
157
|
-
`)}),console.log(`
|
|
158
|
-
${e.length} React hook candidate pair(s) found.`)}}),ip=Fe("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>hs(e,{minComponentLines:k(n,"minComponentLines",300),minFileLines:k(n,"minFileLines",800),minJsxTokens:k(n,"minJsxTokens",80),minBehaviorTokens:k(n,"minBehaviorTokens",40),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{A.list(e,t=>[`
|
|
159
|
-
${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(`
|
|
160
|
-
`)),console.log(`
|
|
161
|
-
${e.length} large React component(s) found.`)}}),op=Fe("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>fs(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
162
|
-
${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(`
|
|
163
|
-
`)}),console.log(`
|
|
164
|
-
${e.length} duplicated Vue component pair(s) found.`)}}),rp=Fe("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>gs(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
165
|
-
${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(`
|
|
166
|
-
`)}),console.log(`
|
|
167
|
-
${e.length} Vue composable candidate pair(s) found.`)}}),sp=Fe("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>ys(e,{minTotalLines:b(n,"reviewThresholds")&&Ja(n,"minTotalLines")==="default"?300:k(n,"minTotalLines",800),minTemplateLines:k(n,"minTemplateLines",300),minScriptLines:k(n,"minScriptLines",300),minStyleLines:k(n,"minStyleLines",500),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{A.list(e,t=>{let n=[`
|
|
168
|
-
${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(`
|
|
169
|
-
`)}),console.log(`
|
|
170
|
-
${e.length} large Vue view pressure file(s) found.`)}});function Re(e){return{docs:R("Cleanup"),...e}}function re({heuristicLabel:e,...t}){return Re({...t,heuristic:{label:e}})}var si=[Re({id:"unused-params",command:"unused-params",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings",S,30),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:R("Cleanup",["scip-query unused-params -s src/services"]),handler:ep}),Re({id:"cleanup-plan",command:"cleanup-plan",agent:C("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository",z("repository-preview")),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",S,1),u("--max-depth <n>","Maximum cascade depth",S,5),u("--verify","Apply batches in an isolated HEAD snapshot and run the project checker (tsc / cargo check)"),u("--patch","With --verify, print the compiler-verified deletion patch to stdout"),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Yu}),Re({id:"recent-duplicates",command:"recent-duplicates",agent:C("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:x([u("--window <n>",'How many commits back counts as "recent"',S,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Oe),u("-n, --limit <n>","Maximum findings",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:R("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Xu}),Re({id:"doc-drift",command:"doc-drift [doc]",agent:C("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:x([u("-n, --limit <n>","Maximum docs to report",S,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",S,3),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:R("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Zu}),Re({id:"dead",command:"dead [scope]",agent:C("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:x([u("--min-loc <n>","Only show symbols >= N lines",S,1),u("--include-tests","Include definitions from test files (test references always count)"),u("--skip-barrels","Ignore refs from barrel re-export files"),u("--include-members","Include class members"),u("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),u("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query dead --min-loc 10"]),handler:Au}),Re({id:"unused-imports",command:"unused-imports <file>",agent:C("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:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Pu}),Re({id:"isolated",command:"isolated",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum lines of code",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Lu}),re({id:"similar",command:"similar [symbol] [other]",agent:C("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:x([u("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",Oe,.4),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",S,4),u("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),u("--plan","Render a consolidation preview for two symbols"),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Fu}),re({id:"similar-files",command:"similar-files [file]",agent:C("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:x([u("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Oe,.5),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",S),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Wu}),re({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Oe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",S,8),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:tp}),re({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum behavior similarity (0-1)",Oe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:np}),re({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:C("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:x([u("--min-component-lines <n>","Minimum component lines",S,300),u("--min-file-lines <n>","Minimum file lines",S,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",S,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",S,40),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:ip}),re({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum template similarity (0-1)",Oe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",S,8),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:op}),re({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum behavior similarity (0-1)",Oe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:rp}),re({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:C("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:x([u("--min-total-lines <n>","Minimum total component lines",S,800),u("--min-template-lines <n>","Minimum template lines",S,300),u("--min-script-lines <n>","Minimum script lines",S,300),u("--min-style-lines <n>","Minimum style lines",S,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:sp}),re({id:"similar-chains",command:"similar-chains",agent:C("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:x([u("--min-similarity <n>","Minimum chain similarity (0-1)",Oe,.5),u("-n, --limit <n>","Number of results",S,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",S,3),u("--max-length <n>","Maximum chain length",S,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:_u}),re({id:"extract-candidates",command:"extract-candidates",agent:C("Which contiguous regions of a large function use callees that appear nowhere else in it?","symbol identities with exclusive callee regions and the local data each region would need",[],"bounded","repository"),description:"Find extraction candidates: contiguous regions whose callees are used nowhere else in the function",options:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum function LOC",S,10),u("--min-callees <n>","Minimum callees to analyze",S,6),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ju}),re({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:C("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:x([u("-s, --scope <path>","Limit scan mode to files matching path"),u("--min-consumers <n>","Minimum consumers in scan mode",S,1),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Mu}),re({id:"drift",command:"drift [module]",agent:C("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:x([u("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",pe,5),u("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),u("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),u("-n, --limit <n>","Number of results",S,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Bu}),re({id:"wrapper-candidates",command:"wrapper-candidates",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",S,15),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Nu}),re({id:"passthrough-candidates",command:"passthrough-candidates",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",S,15),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Ou}),re({id:"stale-abstractions",command:"stale-abstractions",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",S,3),u("-n, --limit <n>","Number of results",S,30),u("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Du}),re({id:"complexity-hotspots",command:"complexity-hotspots",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",S,10),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:qu}),Re({id:"convergence",command:"convergence <symbol1> <symbol2>",hidden:!0,agent:C("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:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Gu}),du({id:"redundant-reexports",command:"redundant-reexports",agent:C("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:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded analysis on large indexes")],docs:R("Cleanup"),query:({db:e,opts:t})=>oa(e,{scope:w(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
171
|
-
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
172
|
-
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
173
|
-
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
174
|
-
${e.length} redundant re-export(s).`)}),Re({id:"duplicate-bodies",command:"duplicate-bodies",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC per function body",S,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",S,3),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:Uu}),Re({id:"twin-drift",command:"twin-drift",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",Oe,.3),u("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:Hu}),re({id:"not-implemented",command:"not-implemented",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["scip-query not-implemented -s src/services"]),handler:Qu}),re({id:"decorative-checkers",command:"decorative-checkers",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:Ku}),Re({id:"test-quality",command:"test-quality",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings per sub-check",S,30),u("--rot-days <n>","Skips older than this many days are reported as rot",S,60),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:R("Cleanup",["scip-query test-quality -s tests/queries"]),handler:zu}),Re({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:C("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete",void 0,z("mutation")),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (cleanup integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:x([u("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),u("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:R("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Ju}),Re({id:"similar-signatures",command:"similar-signatures",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC per function",S,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",S,12),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Vu})];var Xb=Z(({db:e,args:t,opts:n})=>{let i=Vt(e);if(b(n,"json")){P("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${ce(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),ap=[{id:"stats",command:"stats",description:"Show index statistics",agent:C("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:x(),renderShape:"custom",docs:R("Core"),handler:Xb}];var Zb=Ln("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>es(e,{limit:D(t,"limit",20),scope:w(t,"scope"),minFanIn:k(t,"minFanIn",2),minFanOut:k(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."}),ev=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=D(n,"limit",30);if(i){let c=Qr(e,i);if(b(n,"json")){P("fan-in",t,n,{mode:"symbol",symbol:i,rows:c});return}if(c.length===0)return A.empty(`No fan-in for ${i}.`);A.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let r=zr(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){P("fan-in",t,n,{mode:"top",rows:r});return}let s=new Map;for(let c of r)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));A.table(["files","symbol"],r.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),tv=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=D(n,"limit",30);if(i){let s=Kr(e,i);if(b(n,"json")){P("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return A.empty(`No fan-out for ${i}.`);A.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let r=Jr(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){P("fan-out",t,n,{mode:"top",rows:r});return}A.table(["symbols","file"],r.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),nv=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=H(t,1),r=D(n,"limit",20);if(i&&o){let a=Yr(e,i,o);if(b(n,"json")){P("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=Xr(e,{limit:r,scope:w(n,"scope")});if(b(n,"json")){P("coupling",t,n,{mode:"top",rows:s});return}A.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}`))}),iv=ft({commandName:"cycles",query:({db:e,opts:t})=>Zr(e,{scope:w(t,"scope"),maxDepth:k(t,"maxDepth",10),edgeBasis:b(t,"importsOnly")?"imports":"symbol-references"}),emptyMessage:e=>e.cycles.length===0?`No cycles found in the ${e.edgeBasis} graph.`:void 0,toJson:e=>e,render:e=>{console.log(`Cyclic strongly connected components in the ${e.edgeBasis} graph:`);for(let t=0;t<e.cycles.length;t++){let n=e.cycles[t],i=n.component??[...new Set(n.path.slice(0,-1))].sort();console.log(`
|
|
175
|
-
Component ${t+1} (${i.length} files; ${n.classification??n.kind}; one witness follows):`);for(let o=0;o<n.path.length;o++){let r=o<n.path.length-1?" \u2192":" (cycle witness)";console.log(` ${n.path[o]}${r}`)}i.length>new Set(n.path.slice(0,-1)).size&&console.log(` Full component: ${i.join(", ")}`)}console.log(`
|
|
176
|
-
${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),ov=ft({commandName:"architecture",query:({db:e,opts:t})=>It(e,{scope:w(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{let t=$t(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.`),t.length===0?console.log("Architecture policy passed."):console.log(`Architecture policy failed with ${t.length} enforced finding(s). Update the code or narrow the declared policy before treating the structure as clean.`),e.policyCoverage.missingRows.length>0){let n=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${n}`)}if(e.coverage.unmappedFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}${n}`)}if(e.coverage.ambiguousFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}${n}`);for(let i of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${i.file} -> ${i.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
|
|
177
|
-
Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let n of e.forbiddenEdges){console.log(` ${n.from} -> ${n.to}: ${n.fileEdgeCount} file edge(s), ${n.importerCount} importer(s), ${n.importedFileCount} imported file(s)`);for(let i of n.examples)console.log(` ${i.fromFile} -> ${i.toFile}`)}}else console.log(`
|
|
178
|
-
No forbidden dependency edges found.`);if(e.staleAllowances.length>0){let n=e.policyCoverage.requiresMinimalPolicy?" [violates requireMinimalPolicy]":"";console.log(`
|
|
179
|
-
Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.${n}`);for(let i of e.staleAllowances)console.log(` ${i.from} -> ${i.to}`)}if(e.boundaryLimits.length>0){console.log(`
|
|
180
|
-
Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let n of e.boundaryLimits)console.log(` ${n.boundary}: ${n.kind} ${n.observed} exceeds limit ${n.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
|
|
181
|
-
Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let n of e.testBoundaryViolations.slice(0,20)){let i=n.ownerBoundary??"(no subject found)";console.log(` ${n.testFile} [${i}] -> ${n.importedBoundary} (${n.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
|
|
182
|
-
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 n of e.fragileEdges.slice(0,10)){let i=n.examples[0];console.log(` ${n.from} -> ${n.to}${i?` (${i.fromFile} -> ${i.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
|
|
183
|
-
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 n of e.coarseBoundaries){console.log(` ${n.boundary}: ${n.subUnits.join(" <-> ")}`);for(let i of n.narrowestEdges){console.log(` narrowest: ${i.from} -> ${i.to} (${i.fileEdgeCount} file edge(s))`);for(let o of i.examples.slice(0,3))console.log(` ${o.fromFile} -> ${o.toFile}`)}}}if(e.edges.length>0){console.log(`
|
|
184
|
-
Boundary graph (${e.edges.length} directed edge(s)):`);for(let n of e.edges)console.log(` ${n.from} -> ${n.to} ${n.policyStatus.padEnd(10)} ${n.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
|
|
185
|
-
Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let n of e.reciprocalPairs)console.log(` ${n.boundaries[0]} <-> ${n.boundaries[1]} ${n.forward.fileEdgeCount}/${n.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
|
|
186
|
-
Strongly connected boundary groups (${e.cycles.length}):`);for(let n of e.cycles){let i=n.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${n.boundaries.join(", ")} }${i}`);for(let o of n.narrowestEdges)console.log(` inspect ${o.from} -> ${o.to}: ${o.fileEdgeCount} file edge(s)`)}}},after:e=>{$t(e).length>0&&(process.exitCode=1)}});function up(e){return ft({commandName:e,query:({db:t,opts:n})=>os(t,{limit:D(n,"limit",10),scope:w(n,"scope"),minDepth:k(n,"minDepth",3),edgeBasis:b(n,"importsOnly")?"imports":"symbol-references"}),emptyMessage:t=>t.length===0?"No deep chains found.":void 0,render:t=>{for(let n=0;n<t.length;n++){console.log(`
|
|
187
|
-
Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of t[n].components){let o=i.length===1?i[0]:`{ ${i.join(", ")} } (cycle)`;console.log(` \u2192 ${o}`)}console.log(` Tier: ${t[n].actionTier} Risk: ${t[n].chainKind}`),console.log(` Recommendation: ${t[n].recommendation}`),console.log(` Evidence: ${t[n].evidenceReasons.join("; ")}`)}}})}var rv=up("deep-chains"),sv=up("dependency-depth"),av=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=ss(e,{search:i,scope:w(n,"scope")});if(b(n,"json")){P("entrypoints",t,n,o,{coverage:{complete:!0,totalKnown:!0,returned:o.length,total:o.length,omitted:0}});return}let r=w(n,"scope");if(console.log(`\u2550\u2550\u2550 REQUEST \u2550\u2550\u2550
|
|
188
|
-
text=${i?JSON.stringify(i):"<all>"}; scope=${r??"<repository>"}`),o.length===0){console.log(`
|
|
189
|
-
\u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550
|
|
190
|
-
${i?`No detected entry candidate matched ${JSON.stringify(i)}.`:"No entry candidates were detected."}`),console.log(`
|
|
191
|
-
\u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
|
|
192
|
-
Absence from this detector does not prove that the repository has no runtime ingress.`),console.log(`
|
|
193
|
-
\u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
|
|
194
|
-
Complete within the detector's indexed source/compiler entry evidence.`);return}console.log(`
|
|
195
|
-
\u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550`),A.list(o,s=>` [${s.confidence}] ${s.file}:${j(s.startLine)} ${s.shortName}
|
|
196
|
-
evidence: ${s.evidence.join(", ")}; indexed callers: ${s.indexedCallerCount}
|
|
197
|
-
symbol: ${s.symbol}`),console.log(`
|
|
198
|
-
\u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
|
|
199
|
-
[root] has configured, framework-dispatched, Rust public-library, or entry-surface evidence. [candidate] is package-public or lacks indexed callers; neither label proves a runtime invocation.`),console.log(`
|
|
200
|
-
\u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
|
|
201
|
-
${o.length} entry candidate(s); complete within indexed detector evidence.`),console.log(`
|
|
202
|
-
\u2550\u2550\u2550 RECOVERY \u2550\u2550\u2550
|
|
203
|
-
Any printed exact symbol can be projected with scip-query evidence using the family and direction required by the material question.`)}),cv=Z(({db:e,args:t,opts:n})=>{let i=M(t,0),o=as(e,i,{expand:O(n,"expand")});if(b(n,"json")){P("entry-map",t,n,o,{coverage:o.kind==="matched"?{complete:!0,totalKnown:!0,returned:o.regions.length,total:o.regions.length,omitted:0}:{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0}});return}if(o.kind==="missing")return process.exitCode=1,A.empty(`No symbol matched '${i}'.`);if(o.kind==="ambiguous"){process.exitCode=1,console.error(`'${i}' is ambiguous across ${o.total} definitions:`);for(let s of o.candidates)console.error(` ${s.relativePath}:${j(s.startLine)} ${s.shortName}`),console.error(` symbol: ${s.symbol}`);return}if(o.kind==="not-entry")return process.exitCode=1,A.empty(`${o.shortName} (${o.file}) is not a detected entry point. ${o.reason}`);console.log(`Entry: ${o.entry.shortName} (${o.entry.file})`),console.log(`Evidence: ${o.entry.evidence.join(", ")}
|
|
204
|
-
`),console.log("\u2550\u2550\u2550 COLLAPSED FILE REGIONS \u2550\u2550\u2550");for(let s of o.regions){let a=s.expanded?"expanded":`expand with --expand '${s.id}'`;console.log(` depth ${s.minDepth} ${s.id}
|
|
205
|
-
${s.symbolCount} symbol(s); ${s.internalEdgeCount} internal edge(s); ${s.externalCallCount} unresolved/external call(s); ${s.incomingRegionIds.length} incoming region(s); ${s.outgoingRegionIds.length} outgoing region(s)
|
|
206
|
-
${a}`)}if(o.regionEdges.length>0){console.log(`
|
|
207
|
-
\u2550\u2550\u2550 CROSS-REGION CALLS \u2550\u2550\u2550`);for(let s of o.regionEdges)console.log(` ${s.fromRegionId} \u2192 ${s.toRegionId} (${s.callCount} edge(s); ${s.evidence.join(", ")})
|
|
208
|
-
${s.fromSymbols.join(", ")} \u2192 ${s.toSymbols.join(", ")}`)}let r=o.regions.filter(s=>s.expanded);if(r.length>0){console.log(`
|
|
209
|
-
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`);for(let s of r){console.log(` ${s.id}`);for(let a of s.symbols)console.log(` depth ${a.depth} ${a.shortName}
|
|
210
|
-
${a.symbol}`);for(let a of s.internalEdges)console.log(` call ${a.fromShortName} \u2192 ${a.toShortName} (${a.source})`);for(let a of s.externalCalls)console.log(` unresolved/external ${a.fromShortName} \u2192 ${a.toShortName} (${a.reportedFile}; ${a.source})`)}}o.unmatchedExpansions.length>0&&console.error(`
|
|
211
|
-
Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
|
|
212
|
-
Coverage: ${o.coverage.symbolCount} symbol(s), ${o.coverage.symbolEdgeCount} call edge(s), ${o.coverage.regionCount} region(s), ${o.coverage.externalCallCount} unresolved/external call(s).`),console.log("Complete within indexed static call edges; dynamic dispatch is not represented.")}),lv=Z(({db:e,args:t,opts:n})=>{let i=O(n,"selectionTerm"),o=Dr(e,{searches:O(n,"search"),symbols:O(n,"symbol"),behaviorFocusLocations:O(n,"focusAt").map(mv),maxDepth:k(n,"depth",5),expand:O(n,"expand"),relations:O(n,"relation"),evidenceFloor:w(n,"evidenceFloor"),sourceScopes:O(n,"sourceScope"),maxTopologyCharacters:k(n,"topologyCharacters",12e3),topologyFrontiers:O(n,"frontier"),routeIds:O(n,"route"),fullLiteralTraversal:b(n,"fullLiteralTraversal"),selectionTerms:i});if(i.length>0&&!b(n,"json")&&console.error("Deprecated: --selection-term is accepted as a no-op; graph selection is explicit and query-neutral."),b(n,"json")){P("system-map",t,n,o,{coverage:{complete:!1,totalKnown:!1,returned:o.regions.length}});return}if(b(n,"gapRecoveryOnly")){dv(o.nextAnchors,O(n,"gapCallee"));return}let r=new Set(o.presentation.regionIds),s=new Set(o.presentation.relationKeys),a=o.regions.filter(p=>r.has(p.id)),c=o.regionRelations.filter(p=>s.has(`${p.fromRegionId}\0${p.toRegionId}`)),l=a.some(p=>p.expanded),d=!!(o.behavior&&o.behavior.steps.length>0);console.log("\u2550\u2550\u2550 EXPLICIT ANCHORS \u2550\u2550\u2550");for(let p of o.anchors){let f=p.kind==="literal"?`${p.matchingLines??0} matching line(s); ${p.seedMatchingLines??0} materialized source seed(s), ${p.matchOnlyLines??0} match-only, ${p.withheldMatchingLines??0} withheld before traversal`:`${p.totalSymbolCandidates??0} candidate definition(s)`;console.log(` [${p.status}] ${p.kind} ${p.query} \u2014 ${f}`),(p.seedRegionIds??[]).length>0&&console.log(` traversal seed regions: ${p.seedRegionIds.join(", ")}`),(p.matchOnlyRegionIds??[]).length>0&&console.log(` retained match-only regions: ${p.matchOnlyRegionIds.join(", ")}`);for(let g of p.representativeMatches??[]){let y=g.ownerShortName?` ${se(g.ownerShortName)}`:"";console.log(` representative: ${g.file}:${j(g.line)}${y} \u2014 ${g.sourceLine.slice(0,160)}`)}for(let g of p.narrowingCommands??[])console.log(` narrow exactly: ${g}`);if(p.exhaustiveTraversalCommand&&console.log(` exhaustive recovery: ${p.exhaustiveTraversalCommand}`),p.kind==="symbol"&&p.matchedRegionIds.length>0&&console.log(` regions: ${p.matchedRegionIds.join(", ")}`),!l){let g=d?(p.symbolCandidates??[]).slice(0,3):p.symbolCandidates??[];for(let y of g)console.log(` ${y.relativePath}:${j(y.startLine)} ${se(y.shortName)}`)}(p.omittedSymbolCandidates??0)>0&&console.log(` ${p.omittedSymbolCandidates} additional candidate(s) omitted by symbol resolution.`)}if(o.topology){let p=new Map(o.topology.nodes.map(T=>[T.id,T])),f=o.topology.nodes.filter(T=>T.disposition==="emitted"),g=o.topology.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"&&T.fromNodeId!==T.toNodeId),y=o.topology.frontiers.filter(T=>T.disposition==="folded");console.log(`
|
|
213
|
-
\u2550\u2550\u2550 QUERY CONNECTOR GRAPH \u2550\u2550\u2550`),console.log(` ${f.length}/${o.topology.nodes.length} node(s) selected; ${g.length} typed connector edge(s); ${y.length} reversible frontier group(s).`),o.topology.completion&&console.log(` [${o.topology.completion.status}] ${o.topology.completion.explanation}`);for(let T of o.topology.paths){let W=T.nodeIds.map(E=>p.get(E)?.label??E);console.log(` [${T.status}] ${W.length>0?W.join(" \u2194 "):"no proved connector"}`)}let v=o.topology.routeCatalog;if(v){let T=new Set(v.selectedRouteIds);console.log(` Route catalogue [${v.coverage.status}]: ${v.routes.length} distinct proved public/runtime endpoint route(s); ${v.coverage.enumeration}; depth \u2264 ${v.coverage.maximumDepth}.`);for(let W of v.routes){let E=T.has(W.id)?"; selected":"",B=W.relatedEdgeFamilies.length>0?W.relatedEdgeFamilies.join(","):"control",J=W.nodeIds.map(F=>se(p.get(F)?.label??F)).join(" \u2192 ");console.log(` [${W.id}; ${W.endpointKind}; ${W.edgeIds.length} edge(s); families ${B}${E}] ${J} @ ${W.endpointLocation.file}:${j(W.endpointLocation.line)}`)}v.coverage.anchorsWithoutRoutes.length>0&&console.log(` [no proved public/runtime route] ${v.coverage.anchorsWithoutRoutes.length} anchor node(s): `+v.coverage.anchorsWithoutRoutes.join(", ")),v.routes.length>0&&v.selectedRouteIds.length===0&&console.log(` Select only routes whose interior behavior is a named missing fact; repeat --route to batch: ${pv(n,[])} --route '<route-id>'`)}let $=f.filter(T=>typeof T.attributes.upstreamCausalEndpoint=="string");if($.length>0){console.log(" Upstream causal roots are the earliest source-backed constructs selected on bounded proved paths into the anchors; a traversal root has no earlier proved caller in this query graph and is not necessarily a public application entry.");for(let T of $){let W=T.location?` @ ${T.location.file}:${j(T.location.line)}`:"",E=Number(T.attributes.upstreamCausalDistance??0);console.log(` [${String(T.attributes.upstreamCausalEndpoint)}; ${E} edge(s) to anchor] ${se(T.label)}${W}`)}}let L=d?4:8;for(let T of g.slice(0,L)){let W=p.get(T.fromNodeId)?.label??T.fromNodeId,E=p.get(T.toNodeId)?.label??T.toNodeId,B=[...new Set(T.evidence.map(J=>J.strength))].join("/");console.log(` ${W} \u2192 ${E} \u2014 ${T.kind} [${B}]`)}g.length>L&&console.log(` +${g.length-L} selected connector edge(s).`);let _=y.slice(0,d?1:2);for(let T of _){let W=T.memberNodeIds.slice(0,2).map(E=>p.get(E)?.label??E).join(", ");console.log(` [folded ${T.id}] ${T.memberCount} node(s), ${T.edgeIds.length} edge(s)${W?` \u2014 ${W}`:""}`)}let I=_.find(T=>T.expansion)?.expansion;if(I&&!d){let T=I.replace(/ --frontier '[^']+'$/u,"");console.log(` Expand shown frontiers together: ${T} ${_.map(W=>`--frontier '${W.id}'`).join(" ")}`)}y.length>_.length&&console.log(` +${y.length-_.length} frontier group(s); all exact members and expansion commands remain in the structured result.`),hv(o.topology,o.behavior)}if(o.behavior&&o.behavior.steps.length>0){if(console.log(`
|
|
214
|
-
\u2550\u2550\u2550 CONNECTED BEHAVIOR \u2550\u2550\u2550`),console.log(` [${o.behavior.status}] ${o.behavior.steps.length}/${o.behavior.coverage.candidateNodes} selected construct(s); ${o.behavior.transitions.length} evidenced transition(s); ${o.behavior.coverage.withheldStatements} non-connector statement(s) withheld with exact-source recovery.`),o.behavior.coverage.requestedFocusLocations.length>0){console.log(` Question-aligned focus: ${o.behavior.coverage.matchedFocusLocations.length}/${o.behavior.coverage.requestedFocusLocations.length} exact location(s) fell inside selected constructs.`);for(let f of o.behavior.coverage.unmatchedFocusLocations)console.log(` [unmatched focus] ${f.file}:${j(f.line)}`)}console.log(" Read every relevant sibling branch under the explicit anchors before using optional gap recovery; the branch outcomes are jointly required behavior, not alternative search results.");let p=new Map(o.behavior.steps.map(f=>[f.id,f.order+1]));for(let f of o.behavior.steps){let g=f.location?` @ ${f.location.file}:${j(f.location.line)}`:"";if(console.log(` ${f.order+1}. [${f.role}; ${f.kind}] ${se(f.label)}${g}`),!f.behavior)continue;let y=[` [${f.behavior.kind}; ${f.behavior.constructKind}] ${f.behavior.signature} (${f.behavior.renderedCharacters}/${f.behavior.rawCharacters} chars; ${f.behavior.coverage.representedStatements}/${f.behavior.coverage.sourceStatements} detected behavior statements selected)`];for(let v of f.behavior.lines){let $=v.signals.length>0?` [${v.signals.join(",")}]`:"";y.push(` ${j(v.line)}${$} ${" ".repeat(v.depth)}${v.text}`)}for(let v of f.behavior.supportingDeclarations??[]){let $=v.text.replace(/\s*\n\s*/gu," ");y.push(` [support; ${v.kind}] ${v.label} @ ${v.file}:${j(v.line)} \u2014 ${$}`)}for(let v of f.behavior.omittedSupportingDeclarations??[])y.push(` [support omitted; ${v.reason}] ${v.label} @ ${v.file}:${j(v.line)}-${j(v.endLine)}`);console.log(Yt({kind:"unit",identity:f.nodeId,content:y.join(`
|
|
215
|
-
`),label:se(f.label),indent:" "}))}if(o.behavior.transitions.length>0){console.log(" Transitions (arrows preserve repository-edge direction):");for(let f of o.behavior.transitions){let g=f.evidence.map(L=>`${L.method}/${L.strength}`).join(", "),y=f.kind==="runtime-boundary"?[...new Set(f.evidence.flatMap(L=>typeof L.identity=="string"&&L.identity.length>0?[L.identity]:[]))]:[],v=p.get(f.fromStepId)??"?",$=p.get(f.toStepId)??"?";console.log(Yt({kind:"edge",identity:f.edgeId,content:` ${v} \u2192 ${$} \u2014 ${f.kind}; path=${f.pathTraversal}; ${g}`+(y.length>0?`; key=${y.join(" | ")}`:""),label:`${v} \u2192 ${$} ${f.kind}`,indent:" "}))}}o.behavior.coverage.omittedNodeIds.length>0&&console.log(` ${o.behavior.coverage.omittedNodeIds.length} bounded emitted construct(s) were not materialized; their identities remain in behavior.coverage.omittedNodeIds.`),o.behavior.exactSourceCommand&&console.log(" Exhaustive exact-source recovery (usually unnecessary; never combine with the drill batch below): "+o.behavior.exactSourceCommand)}if(o.nextAnchors&&o.nextAnchors.candidateAnchors>0){console.log(`
|
|
216
|
-
\u2550\u2550\u2550 ADJACENT RECOVERY INVENTORY \u2550\u2550\u2550`);let p=[...o.nextAnchors.anchors,...o.nextAnchors.withheldAnchors],f=new Map;for(let g of p){let y=`${g.direction}/${g.relationKind}/${g.causalRole}`;f.set(y,(f.get(y)??0)+1)}console.log(` ${o.nextAnchors.candidateAnchors} exact or candidate adjacent target(s) are recoverably folded.`);for(let[g,y]of[...f].sort(([v],[$])=>v.localeCompare($)))console.log(` ${g}: ${y}`);console.log(` Select a named missing callee without relevance inference: ${uv(n,["<callee-from-connected-behavior>"])}.`)}if(o.regions.length===0)console.log(`
|
|
217
|
-
No structural regions matched the supplied anchors.`);else{console.log(`
|
|
218
|
-
\u2550\u2550\u2550 COLLAPSED SYSTEM REGIONS \u2550\u2550\u2550`);for(let p of a){let f=p.expanded?"expanded":"collapsed",g=p.notableSymbols.slice(0,2);if(l){console.log(` d${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}`);continue}if(d){console.log(` d${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out`);continue}console.log(` depth ${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file (${p.sourceFileCount} src/${p.testFileCount} test); ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}
|
|
219
|
-
anchors: ${p.anchorQueries.join(", ")||"none"}; drill: ${g.map(y=>`${se(y.shortName)} (${y.file})`).join(", ")||"none"}${p.symbolCount>g.length?`; +${p.symbolCount-g.length}`:""}`)}}if(o.presentation.complete||(console.log(`
|
|
220
|
-
\u2550\u2550\u2550 TOPOLOGY WITHHELD MANIFEST \u2550\u2550\u2550`),console.log(` The ${o.presentation.maxCharacters}-character topology budget selected ${o.presentation.regionIds.length}/${o.regions.length} region(s) and ${o.presentation.relationKeys.length}/${o.regionRelations.length} cross-region relation(s).`),o.presentation.omittedRegionIds.length>0&&console.log(` Withheld region ids: ${dp(o.presentation.omittedRegionIds,12)}.`),console.log(` Structured JSON retains all facts. Expand the human topology without paging: ${o.presentation.expansionCommand}`)),!l&&!d&&o.expansion?.command&&(console.log(`
|
|
221
|
-
\u2550\u2550\u2550 NEXT ABSTRACTION LEVEL \u2550\u2550\u2550`),o.expansion.command)){let p=o.regions.length-o.expansion.regionCount,f=o.expansion.candidateRegionCount??o.expansion.regionCount,g=o.expansion.omittedRegionIds??[];console.log(` Expand ${o.expansion.regionCount}/${f} ranked traversal-relevant region(s) in one complete child-file summary; ${p} other observed region(s) remain visible above.`),console.log(` Expand together: ${o.expansion.command}`),g.length>0&&console.log(` Withheld traversal-relevant regions: ${g.join(", ")}. Add several --expand selectors to the command when they can change the decision.`)}if(c.length>0){console.log(`
|
|
222
|
-
\u2550\u2550\u2550 CROSS-REGION RELATIONSHIPS \u2550\u2550\u2550`),d||console.log(" Evidence A=AST callsite; M=source candidate (receiver type unproved); S=semantic callee; C=SCIP chunk; K=cross-workspace contract symbol; I=index/source import; R=index/source reference; B=proven runtime-boundary join.");for(let p of c)console.log(` ${lp(p.fromRegionId)} \u2192 ${lp(p.toRegionId)} \u2014 ${p.relationCount} rel [${p.kinds.join(",")}; ${p.evidence.map(Rv).join(",")}]`)}if(o.boundaryFrontiers.length>0){console.log(`
|
|
223
|
-
\u2550\u2550\u2550 UNRESOLVED RUNTIME BOUNDARIES \u2550\u2550\u2550`);let p=vv(o.boundaryFrontiers),f=p.slice(0,d?3:8);for(let g of f){let y=g.frontiers.slice(0,d?1:2).map(v=>`${Sv(v.address)} @ ${v.file}:${j(v.line)}`);console.log(` [${g.strength}] ${g.action} \xD7${g.frontiers.length} \u2014 ${y.join("; ")}`),d||console.log(` ${g.reason}`)}p.length>f.length&&console.log(` ${p.length-f.length} additional frontier bucket(s); every observation and reason remains in --json.`),d&&console.log(" These are disclosed candidate observations, not proven connector edges; expand only when a named missing fact crosses one of them.")}o.externalBoundaries.length>0&&(console.log(`
|
|
224
|
-
\u2550\u2550\u2550 EXTERNAL IMPORT BOUNDARIES \u2550\u2550\u2550`),console.log(d?` ${o.externalBoundaries.length} imported external symbol(s) remain accounted in the structured result.`:` ${o.externalBoundaries.length} imported external symbol(s): ${dp(o.externalBoundaries.map(p=>p.name),12)}. Use --json when the complete external-import list can change the decision.`));let m=a.filter(p=>p.expanded);if(m.length>0){console.log(`
|
|
225
|
-
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`),console.log(" Every child file is listed. d=depth; S/T/E/B/W=source/test/entry/barrel/worker; sym/hit/rel counts are complete; C/I/R/B=call/import/reference/runtime-boundary; x=connected-region count; final names are ranked symbol@line drill candidates.");for(let p of m)console.log(` ${p.label} (${p.id})`),bv(p);o.drilldown?.command&&(console.log(`
|
|
226
|
-
\u2550\u2550\u2550 BATCHED DRILL-DOWN \u2550\u2550\u2550`),console.log(` ${o.drilldown.selectedAnchors}/${o.drilldown.candidateAnchors} coverage-diverse child-file anchor(s) selected${o.drilldown.omittedAnchors>0?`; ${o.drilldown.omittedAnchors} withheld by the ranked drill-down budget and still listed above`:""}.`),console.log(` Inspect the selected behavior together: ${o.drilldown.command}`),o.drilldown.definitionCommand&&console.log(` Full-source escalation for the selected exact units: ${o.drilldown.definitionCommand}`))}o.unmatchedExpansions.length>0&&console.error(`
|
|
227
|
-
Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
|
|
228
|
-
Query plan: relations=${o.coverage.requestedRelationKinds.join(",")}; evidence>=${o.coverage.evidenceFloor}; scopes=${o.coverage.includedSourceScopes.join(",")}.`),console.log(`Query closure: ${o.closure.status}; emitted ${o.closure.emitted.regions} region(s), ${o.closure.emitted.relations} relation(s), and ${o.closure.emitted.runtimeLinks} runtime link(s); withheld ${o.closure.withheld.symbols} symbol(s), ${o.closure.withheld.files} file(s), ${o.closure.withheld.regions} region(s), and ${o.closure.withheld.drillAnchors} drill anchor(s); ${o.closure.ambiguous.anchors} ambiguous anchor(s), ${o.closure.external} external boundary(ies), ${o.closure.unresolved} unresolved runtime frontier(s).`),console.log(` ${o.closure.explanation}`),console.log(`
|
|
229
|
-
Coverage: ${o.coverage.matchedAnchorCount}/${o.coverage.explicitAnchorCount} anchor(s) matched; ${o.regions.length} region(s); depth ${o.coverage.maxTraversalDepth}; ${o.coverage.frontierSymbols} untraversed symbol(s); ${o.coverage.frontierFiles} untraversed file(s); ${o.coverage.supportFilesNotTraversed} visible support file(s) not traversed; ${o.coverage.filteredUnverifiedCallEdges} unverified call edge(s) filtered; ${o.coverage.memberCallCandidateEdges} source-attributed member-call candidate edge(s); ${o.coverage.unresolvedMemberCallsites} unresolved member callsite(s); ${o.coverage.runtimeBoundaryTraversedLinks}/${o.coverage.runtimeBoundaryExactLinks+o.coverage.runtimeBoundaryDerivedLinks} map-relevant proven runtime-boundary link(s) traversed (${o.coverage.repositoryRuntimeBoundaryExactLinks+o.coverage.repositoryRuntimeBoundaryDerivedLinks} repository-wide); ${o.coverage.runtimeBoundaryCandidateLinks} candidate boundary link(s); ${o.coverage.runtimeBoundaryFrontiers} relevant unresolved boundary frontier(s); ${o.coverage.referenceExpansionEligibleSymbols} symbol(s) reverse-expanded and ${o.coverage.referenceExpansionSkippedSymbols} discovered symbol(s) not reverse-expanded.`),o.coverage.symbolCandidateSetsComplete||console.log(`Symbol resolution omitted ${o.coverage.omittedSymbolCandidates} ambiguous candidate(s).`),console.log("Blind spots:");let h=d?o.coverage.blindSpots.slice(0,2):o.coverage.blindSpots;for(let p of h)console.log(` - ${p}`);if(o.coverage.blindSpots.length>h.length&&console.log(` - ${o.coverage.blindSpots.length-h.length} additional disclosed limitation(s) remain in coverage.blindSpots.`),d){let p=new Map([["branch conditions",new Map],["structured payloads",new Map],["terminal outcomes",new Map]]);for(let f of o.behavior?.steps??[])if(!(!f.location||!f.behavior))for(let g of f.behavior.lines){let y=`${f.location.file}:${j(g.line)}`;g.signals.includes("branch")&&p.get("branch conditions")?.set(y,null),g.signals.includes("shape")&&(g.signals.includes("call")||g.signals.includes("mutation")||g.signals.includes("return"))&&p.get("structured payloads")?.set(y,g.text.replace(/\s*\n\s*/gu," ")),(g.signals.includes("return")||g.signals.includes("throw"))&&p.get("terminal outcomes")?.set(y,null)}console.log(`
|
|
230
|
-
\u2550\u2550\u2550 ANSWER EVIDENCE CONTRACT \u2550\u2550\u2550`),console.log(" Before another query, account for each question-relevant condition and outcome already rendered above. Preserve exact ownership/lifetime (including singleton/shared/per-invocation scope), normalization and path rules, invocation arguments, working directory and standard I/O, bounds/defaults, returned fields or instructions, every condition that stops or continues the enclosing loop, policy or dispatch precedence and bypass scope, and rethrown-versus-rendered interruption behavior."),console.log(" Draft audit locations are mechanically derived from selected syntax. For every category material to the question, explicitly account for every listed location:");for(let[f,g]of p)if(g.size!==0)if(f==="structured payloads"){console.log(` Draft audit \u2014 ${f}:`);for(let[y,v]of g)console.log(` ${y} \u2014 ${v??""}`)}else console.log(` Draft audit \u2014 ${f}: ${[...g.keys()].join(", ")}`);console.log(" No causal target is automatically recommended. Use the adjacent recovery inventory only for a named material fact with no rendered evidence; otherwise answer from the map.")}});function dv(e,t){if(console.log("\u2550\u2550\u2550 OPTIONAL GAP RECOVERY (ONLY AFTER NAMING A MISSING FACT) \u2550\u2550\u2550"),!e||e.candidateAnchors===0){console.log(" No causal drill targets were resolved from the connected behavior.");return}if(t.length===0)throw new Error("--gap-recovery-only requires at least one --gap-callee named in connected behavior.");let n=new Set(t.map(cp)),i=[...e.anchors,...e.withheldAnchors].filter(r=>[r.callsite.calleeLeaf,...r.alternatives.map(s=>s.label)].some(s=>n.has(cp(s))));if(i.length===0){console.log(` No resolved target matched ${t.map(ee).join(", ")}. Copy callee names exactly from connected behavior.`);return}console.log(` ${i.length}/${e.candidateAnchors} causal target(s) matched the named callee selector(s); no English intent inferred.`);for(let r of i){let s=r.alternatives[0],a=s?`${se(s.label)} @ ${s.file}:${j(s.line)}`:r.callsite.calleeLeaf,c=r.callsite.signals.filter(d=>d!=="anchor"&&d!=="call").join(","),l=[r.direction,r.causalRole,r.relationKind].filter(Boolean).join("; ");if(console.log(` [${r.status}; ${r.source}${l?`; ${l}`:""}${c?`; ${c}`:""}] ${a}${r.alternativeCount>1?` \u2014 ${r.alternativeCount} possible identities`:""}`),console.log(` from ${se(r.fromLabel)} @ ${r.callsite.file}:${j(r.callsite.line)} \u2014 `+r.callsite.text.slice(0,220)),r.alternativeCount>1)for(let d of r.alternatives)console.log(` candidate: ${se(d.label)} @ ${d.file}:${j(d.line)}`)}let o=new Map;for(let r of i){if(r.alternativeCount!==1)continue;let s=r.alternatives[0];s&&o.set(`${s.file}:${s.line}`,s)}o.size>0&&console.log(` Inspect named targets together: scip-query inspect ${[...o.values()].map(r=>`--at ${ee(`${r.file}:${j(r.line)}`)}`).join(" ")} --view behavior`),i.some(r=>r.source==="leaf-identity-candidate"||r.status==="ambiguous")&&console.log(" Identity candidates locate possible definitions but do not prove the receiver-to-callee edge; confirm before making a relationship claim.")}function uv(e,t=O(e,"gapCallee")){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",ee(o));for(let o of O(e,"symbol"))n.push("--symbol",ee(o));for(let o of O(e,"focusAt"))n.push("--focus-at",ee(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",ee(o));let i=w(e,"evidenceFloor");i&&n.push("--evidence-floor",ee(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",ee(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",ee(o));for(let o of O(e,"frontier"))n.push("--frontier",ee(o));for(let o of O(e,"route"))n.push("--route",ee(o));for(let o of t)n.push("--gap-callee",ee(o));return n.push("--gap-recovery-only"),n.join(" ")}function pv(e,t){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",ee(o));for(let o of O(e,"symbol"))n.push("--symbol",ee(o));for(let o of O(e,"focusAt"))n.push("--focus-at",ee(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",ee(o));let i=w(e,"evidenceFloor");i&&n.push("--evidence-floor",ee(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",ee(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",ee(o));for(let o of O(e,"frontier"))n.push("--frontier",ee(o));for(let o of t)n.push("--route",ee(o));return n.join(" ")}function cp(e){let t=e.replace(/\(\)$/u,"").replace(/^#/u,"");return(t.slice(Math.max(t.lastIndexOf(":"),t.lastIndexOf("."))+1)||t).toLocaleLowerCase()}function mv(e){let t=e.match(/^(.+):(\d+)$/u),n=t?Number(t[2]):Number.NaN;if(!t||!Number.isSafeInteger(n)||n<=0)throw new Error(`Invalid --focus-at location '${e}'; expected path:line with a positive line number.`);return{file:t[1],line:n-1}}function hv(e,t){let n=e.corridor;if(!n)return;let i=new Map(e.nodes.map(p=>[p.id,p])),o=new Map(e.edges.map(p=>[p.id,p])),r=p=>p.map(f=>se(i.get(f)?.label??f)).join(", "),s=new Map,a=new Map;for(let p of t?.steps??[]){if(!p.location||!p.behavior)continue;let f=a.get(p.location.file)??[];f.push(...p.behavior.lines.map(g=>({line:g.line,endLine:g.endLine}))),a.set(p.location.file,f)}let c=p=>p?.location?(a.get(p.location.file)??[]).some(f=>p.location.line>=f.line&&p.location.line<=f.endLine):!1,l=new Map,d=new Map,m=[],h=new Map;for(let p of n.edgeIds){let f=o.get(p);if(f)for(let g of f.semantics??[])if(g.family==="identity"){let y=s.get(f.fromNodeId)??[];y.push(f.toNodeId),s.set(f.fromNodeId,y)}else if(g.family==="control"&&!wo(g.subtype)){let y=i.get(f.fromNodeId),v=i.get(f.toNodeId),$=typeof y?.attributes.ownerNodeId=="string"?y.attributes.ownerNodeId:f.fromNodeId;if(c(y)&&c(v)){let T=l.get($)??new Map;T.set(g.subtype,(T.get(g.subtype)??0)+1),l.set($,T);continue}let L=d.get($)??new Map,_=L.get(f.fromNodeId)??{controllerLabel:y?.label??se(f.fromNodeId),controllerLocation:y?.location?{file:y.location.file,line:y.location.line}:null,outcomes:new Map},I=_.outcomes.get(g.subtype)??new Set;I.add(v?.label??se(f.toNodeId)),_.outcomes.set(g.subtype,I),L.set(f.fromNodeId,_),d.set($,L)}else if(fv(g.family,g.subtype)){let y=gv(f.fromNodeId,i),v=`${g.family}\0${g.subtype}\0${y.label}`,$=h.get(v)??{family:g.family,subtype:g.subtype,ownerLabel:y.label,ownerLocation:y.location,count:0,targetLabels:new Set,values:new Set};$.count+=1,$.targetLabels.add(se(i.get(f.toNodeId)?.label??f.toNodeId));let L=g.attributes?.value;(typeof L=="string"||typeof L=="number"||typeof L=="boolean")&&$.values.add(String(L)),h.set(v,$)}else m.push({edge:f,semantic:g})}console.log(`
|
|
231
|
-
\u2550\u2550\u2550 CAUSAL CORRIDOR \u2550\u2550\u2550`),console.log(` [${n.status}] ${n.startNodeIds.length} anchor node(s) \u2192 ${n.outcomeNodeIds.length} mechanical outcome(s); ${n.coverage.protectedNodes} protected node(s), ${n.coverage.protectedEdges} protected edge(s).`),console.log(` Starts: ${r(n.startNodeIds)||"none proved"}`),console.log(` Outcomes: ${yv(n.outcomeNodeIds,e)}`);for(let[p,f]of[...s].sort(([g],[y])=>g.localeCompare(y))){let g=new Map;for(let v of new Set(f)){let $=i.get(v)?.kind??"unknown";g.set($,(g.get($)??0)+1)}let y=[...g].sort(([v],[$])=>v.localeCompare($)).map(([v,$])=>`${v}\xD7${$}`).join(", ");console.log(` [owns] ${r([p])} \u2192 ${new Set(f).size} local construct(s) [${y}]`)}for(let[p,f]of[...l].sort(([g],[y])=>g.localeCompare(y))){let g=[...f].sort(([y],[v])=>y.localeCompare(v)).map(([y,v])=>`${y}\xD7${v}`).join(", ");console.log(` [local-control] ${r([p])} \u2014 ${g}; exact decisions are represented below`)}for(let[p,f]of[...d].sort(([g],[y])=>g.localeCompare(y)))for(let g of[...f.values()].sort((y,v)=>(y.controllerLocation?.file??"").localeCompare(v.controllerLocation?.file??"")||(y.controllerLocation?.line??-1)-(v.controllerLocation?.line??-1)||y.controllerLabel.localeCompare(v.controllerLabel))){let y=[...g.outcomes].sort(([$],[L])=>$.localeCompare(L)).flatMap(([$,L])=>[...L].sort().map(_=>`${$} \u2192 ${_}`)).join("; "),v=g.controllerLocation?` @ ${g.controllerLocation.file}:${j(g.controllerLocation.line)}`:"";console.log(` [local-control] ${r([p])}: ${g.controllerLabel} \u2014 ${y}${v}`)}for(let p of[...h.values()].sort((f,g)=>f.ownerLabel.localeCompare(g.ownerLabel)||f.family.localeCompare(g.family)||f.subtype.localeCompare(g.subtype))){let f=p.family==="control"?`; targets=[${[...p.targetLabels].sort().join(", ")}]`:p.family==="data"&&p.subtype==="constant-to-parameter"?`; values=[${[...p.values].sort().join(", ")}]`:p.family==="data"?`; ${p.targetLabels.size} parameter target(s)`:"",g=p.ownerLocation?` @ ${p.ownerLocation.file}:${j(p.ownerLocation.line)}`:"";console.log(` [${p.family}:${p.subtype}; grouped] ${p.ownerLabel} \u2014 ${p.count} proved edge(s)${f}${g}`)}for(let{edge:p,semantic:f}of m){let g={...f.context??{},...f.attributes??{}},y=Object.entries(g).map(([$,L])=>`${$}=${String(L)}`).join(", "),v=p.evidence.find($=>$.location)?.location;console.log(` [${f.family}:${f.subtype}] ${r([p.fromNodeId])} \u2192 ${r([p.toNodeId])}${y?`; ${y}`:""}${v?` @ ${v.file}:${j(v.line)}`:""}`)}console.log(` Frontier manifest: ${n.accountedFrontierIds.length} accounted; ${n.unresolvedFrontierIds.length} unsupported; ${n.unresolvedEdgeIds.length} candidate/unknown edge(s).`),h.size>0&&console.log(" Grouped edge identities remain in the structured corridor; inspect a named owner only when that flow is material."),n.status==="incomplete"&&console.log(` ${n.explanation}`)}function fv(e,t){return e==="control"&&wo(t)||e==="data"&&["argument-to-parameter","constant-to-parameter"].includes(t)||e==="temporal"&&["await-completion-before","awaits-completion","lexical-successor"].includes(t)}function gv(e,t){let n=t.get(e),i=typeof n?.attributes.ownerNodeId=="string"?n.attributes.ownerNodeId:null,o=i?t.get(i):null,r=typeof n?.attributes.ownerSymbol=="string"?n.attributes.ownerSymbol:null;return{label:se(o?.label??r??n?.label??e),location:o?.location??n?.location??null}}function wo(e){return["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e)}function yv(e,t){if(e.length===0)return"none proved";let n=new Set(e),i=new Map(t.nodes.map(l=>[l.id,l])),o=new Set,r=new Set,s=0,a=0,c=new Set;for(let l of t.edges)if(n.has(l.toNodeId))for(let d of l.semantics??[])d.family==="state"?(o.add(se(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):d.family==="control"&&wo(d.subtype)?(r.add(se(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):d.family==="control"&&d.subtype==="returns"?(s+=1,c.add(l.toNodeId)):d.family==="control"&&d.subtype==="throws"&&(a+=1,c.add(l.toNodeId));return[r.size>0?`navigation=[${[...r].sort().join(", ")}]`:"",o.size>0?`resources=[${[...o].sort().join(", ")}]`:"",s>0?`return\xD7${s}`:"",a>0?`throw\xD7${a}`:"",e.length>c.size?`other-causal-sink\xD7${e.length-c.size}`:""].filter(Boolean).join("; ")}function ee(e){return`'${e.replaceAll("'","'\\''")}'`}function bv(e){let t=Ii(e.symbols,o=>o.file),n=Ii(e.literalHits,o=>o.file),i=new Map;for(let o of e.relations)for(let r of new Set([o.fromFile,o.toFile])){if(!e.files.some(a=>a.file===r))continue;let s=i.get(r)??[];s.push(o),i.set(r,s)}for(let o of e.files){let r=(t.get(o.file)??[]).sort(Or),s=n.get(o.file)??[],a=i.get(o.file)??[],c=r.slice(0,4),l=[...new Set(a.map(h=>h.kind))].sort(),d=[...new Set(a.flatMap(h=>[h.fromRegionId,h.toRegionId].filter(p=>p!==e.id)))].sort(),m=c.length>0?c.map(h=>`${se(h.shortName)}@${j(h.startLine)}`).join(", ")+(r.length>c.length?`; +${r.length-c.length}`:""):"none";console.log(` d${o.depth} ${wv(o.kind)} ${o.file} | sym${r.length} hit${s.length} rel${a.length}${l.length>0?`:${l.map($v).join("/")}`:""} x${d.length} | ${m}`);for(let h of s)console.log(` literal ${h.query}@${j(h.line)} ${h.sourceLine}`)}}function se(e){return e.split(":").at(-1)||e}function vv(e){let t=new Map;for(let n of e){let i=`${n.strength}\0${n.action}\0${n.reason}`,o=t.get(i)??{action:n.action,strength:n.strength,reason:n.reason,frontiers:[]};o.frontiers.push(n),t.set(i,o)}return[...t.values()].sort((n,i)=>i.frontiers.length-n.frontiers.length||n.action.localeCompare(i.action))}function Sv(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=120?t:`${t.slice(0,117)}...`}function lp(e){return e.replace(/^region:(?:apps|packages)\//,"")}function wv(e){return{source:"S",test:"T",entry:"E",barrel:"B",worker:"W"}[e]??e}function $v(e){return{call:"C","contract-symbol":"K",import:"I",reference:"R","runtime-boundary":"B"}[e]??e}function Rv(e){return e.startsWith("runtime-boundary:")?`B:${e.slice(17)}`:{"ast-callsite":"A","scip-occurrence":"O","ast-member-import-candidate":"M","compiler-cross-workspace-symbol":"K","semantic-callee":"S","scip-chunk":"C","indexed-or-source-import":"I","indexed-or-source-reference":"R"}[e]??e}function dp(e,t){let n=e.slice(0,t);return`${n.join(", ")}${e.length>n.length?`; ${e.length-n.length} more`:""}`}var pp=[ei({id:"hotspots",command:"hotspots",description:"Rank symbols by cross-file reference count; a reference metric, not runtime contention",agent:C("Which symbols have the most observed cross-file reference evidence?","ranked symbol identities with explicit evidence basis and counting units",[],"bounded","repository"),options:[u("-n, --limit <n>","Number of results",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")],docs:R("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Br(e,{limit:D(t,"limit",30),scope:w(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:{...st("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",ye,Pt(["symbol","construct"],["Entry-point detection reports evidenced external roots and candidates; it does not establish task relevance."])),resultUnits:{kind:"field",field:"rows"}},options:x([u("-n, --limit <n>","Number of results for top mode",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:ev},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:C("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results for top mode",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:tv},{id:"coupling",command:"coupling [file1] [file2]",description:"Count shared-symbol coupling between two files, or rank file pairs by that metric",agent:C("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results for top mode",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:nv},{id:"cycles",command:"cycles",description:"Find every cyclic file-dependency component and show one deterministic witness for each",agent:C("Which file dependency cycles exist?","dependency-cycle file chains",[],"complete","repository"),options:x([u("-s, --scope <path>","Limit to files matching path"),u("--imports-only","Analyze only resolved file imports instead of all cross-file symbol references"),u("--max-depth <n>","Deprecated compatibility option; SCC detection no longer truncates by depth",S,10)]),renderShape:"custom",docs:R("Graph"),handler:iv},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:C("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:x([u("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",claims:Je(["index-generation","live-workspace"],[X("declared-policy","boundaries","repository-source"),X("dependency-observations","edges","compiler-graph"),X("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:R("Graph",["scip-query architecture --json"]),handler:ov},{id:"bottlenecks",command:"bottlenecks",description:"Rank coordination hubs by incoming evidence files \xD7 outgoing cross-file callable targets",agent:C("Which callable symbols are high-connectivity coordination hubs?","ranked callable symbols with incoming evidence-file and outgoing callable-target counts",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",S,2),u("--min-fan-out <n>","Minimum fan-out",S,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:R("Graph"),handler:Zb},{id:"deep-chains",command:"deep-chains",hidden:!0,description:"Deprecated alias for dependency-depth",agent:C("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of chains to show",S,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",S,3),u("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:rv},{id:"dependency-depth",command:"dependency-depth",description:"Find longest paths through the SCC-condensed file dependency graph",agent:C("Which file dependency paths have the greatest condensed depth?","ranked component paths with full cycle membership, edge basis, and condensed depth",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of paths to show",S,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum condensed component depth",S,3),u("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:sv},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...st("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and indexed caller counts",["pattern"],"complete","repository",ye,Pt(["symbol","construct"],["A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress.","Entry classification does not establish that the callable executes."],{ranking:"identity-only",manualInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",outputCost:"bounded",frontierClosure:["evidence","inspect","code"]})),contrasts:[{command:"entry-map",distinction:"entrypoints locates possible external roots; entry-map traverses static calls from one selected root."},{command:"search",distinction:"entrypoints classifies callable roots; search only locates exact text and ownership."}]},options:x([u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Graph",["scip-query entrypoints","scip-query entrypoints work-session"]),handler:av},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...st("What statically reachable call structure begins at this detected entry point?","all reachable file regions, cross-region call edges, coverage, and selected expanded symbol details",["symbol"],"complete",void 0,ye,Xt({rootKinds:["symbol","construct"],edgeFamilies:["execution"],directions:["outgoing"],operations:["reachability"],compression:["topology"],nonClaims:["Static may-call reachability does not establish runtime execution."]})),contrasts:[{command:"entrypoints",distinction:"entry-map traverses one selected root; entrypoints locates and classifies candidate roots."},{command:"evidence",distinction:"entry-map is outgoing execution reachability; evidence projects explicitly selected families and directions."}]},options:x([u("--expand <region-id>","Expand one file region; repeat to expand several together",U,[])]),renderShape:"custom",docs:R("Graph",["scip-query entry-map start","scip-query entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:cv},{id:"system-map",command:"system-map",hidden:!0,description:"Deprecated compatibility view for collapsed regions and legacy route catalogues; use evidence",agent:st("Which components and proven compiler or runtime relationships connect these explicit literals or symbols?","all matched anchors, collapsed structural regions, compiler and exact runtime relationships, unresolved boundary frontiers, simultaneous drilldown summaries, and explicit coverage gaps",[],"bounded","repository",ye,Xt({rootKinds:["text","symbol","construct","runtime-key"],edgeFamilies:ot,directions:["incoming","outgoing","both"],operations:["reachability","connecting"],compression:["topology"],nonClaims:["Legacy region and next-anchor ranking does not establish task relevance.","Structural region membership does not establish execution."],compatibility:"deprecated"})),options:x([u("--search <literal>","Add an exact indexed-source anchor; repeat to include several",U,[]),u("--symbol <symbol>","Add a symbol anchor; repeat to include several",U,[]),u("--focus-at <file:line>","Focus connected behavior at one exact source location inside a selected construct; repeat to include several",U,[]),u("--depth <n>","Traverse this many relationship levels",S,5),u("--relation <kind>","Traverse one relation family; repeat for call, contract-symbol, import, reference, or runtime-boundary",U,[]),u("--evidence-floor <floor>","Runtime evidence floor: exact or derived"),u("--topology-characters <n>","Soft character budget for the first human topology view; complete JSON facts remain available",S,12e3),u("--source-scope <scope>","Include one source scope; repeat for production, test, fixture, example, generated, script, or unknown",U,[]),u("--full-literal-traversal","Traverse every literal match after deliberately accepting broad-selector expansion"),u("--expand <region-id>","Expand one structural region; repeat to expand several together",U,[]),u("--frontier <frontier-id>","Expand one accounted topology frontier; repeat to expand several together",U,[]),u("--route <route-id>","Select one proved upstream route; repeat to materialize several routes together",U,[]),u("--gap-callee <name>","Resolve one callee already shown in connected behavior; repeat to batch a named gap",U,[]),u("--selection-term <term>","Deprecated no-op retained for command compatibility; query vocabulary no longer changes graph selection",U,[]),u("--gap-recovery-only","Render only the --gap-callee targets and one exact batched recovery command")]),evidence:"mixed",claims:Je(["index-generation","live-workspace"],[X("matched-anchors","anchors","compiler-graph"),X("typed-relations","regionRelations","repository-source"),X("structural-grouping","regions","heuristic"),X("coverage","coverage","repository-source")]),renderShape:"custom",docs:R("Compatibility"),handler:lv},xt({id:"call-graph",command:"call-graph <symbol>",description:"Show static may-call edges with exact/candidate evidence and explicit blind spots",agent:C("Who calls this symbol and what does it call?","caller and callee symbol identities, files, evidence strengths, and static-analysis blind spots",["symbol"],"bounded"),options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:R("Graph"),query:({db:e,args:t,budget:n})=>Ht(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:me(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(de(t,String(n[0])),console.log(`Symbol: ${e.shortName}
|
|
232
|
-
`))},toJson:(e,{db:t,args:n})=>Ae(t,String(n[0]),e,"callGraph"),sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callerEvidence?e.callerEvidence.map(t=>` [${t.evidenceStrength}:${t.relationship}${t.interaction?`:${t.interaction}`:""}] ${t.file} ${t.shortName} (${t.evidenceSource})`):e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.calleeEvidence?e.calleeEvidence.map(t=>` [${t.evidenceStrength}:${t.relationship}${t.interaction?`:${t.interaction}`:""}] ${t.file} ${t.shortName} (${t.evidenceSource})`):e.callees.map(t=>` ${t.file} ${t.shortName}`)},{title:"COVERAGE",rows:e.coverage?[` ${e.coverage.scope}`,...e.coverage.blindSpots.map(t=>` Blind spot: ${t}`)]:[" Legacy result: explicit static-analysis coverage was not reported."]}]:[]})];var xv=te("complexity",({db:e,args:t,opts:n,budget:i})=>{let o=M(t,0),r=qs(e,o,{semantic:i.semantic});if(b(n,"json")){P("complexity",t,n,Ae(e,o,r,"complexity"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"Symbol not found."));de(e,o),console.log(`${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
|
|
233
|
-
`),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),Cv=Z(({db:e,args:t,opts:n})=>{let i=ra(e,{samples:k(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){P("self-audit",t,n,i);return}if(!i.available)return A.empty("No semantic or source-backed oracle available to audit against.");let o=i.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${i.sampleSize} symbols; ${o} oracle answered ${Math.round(i.oracleCoverage*100)}%.
|
|
234
|
-
`),console.log(`Agreement with ${o} (file-level):`);for(let r of i.scores){let s=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${s} recall ${r.recall} (${r.comparedSymbols} compared, ${r.skippedOraclePartial} skipped: oracle-partial)`),r.outsideOracleCoverage>0&&console.log(`${" ".repeat(14)}${r.outsideOracleCoverage} cheap answer(s) outside the oracle's compiler project (unverifiable, not counted)`);let a=Object.entries(r.cheapSources).sort((c,l)=>l[1]-c[1]);a.length>0&&console.log(`${" ".repeat(14)}cheap rows by source: ${a.map(([c,l])=>`${c} ${l}`).join(", ")}`)}if(i.topDisagreements.length>0){console.log(`
|
|
235
|
-
Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),mp=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:C("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:x([u("--samples <n>","Number of symbols to sample",S,50),u("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:R("Health",["scip-query self-audit --samples 100"]),handler:Cv},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:C("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Health"),handler:xv}];var kv=Z(({db:e,args:t,opts:n})=>{let i=M(t,0),o=b(n,"full"),r=K(n,"maxDepth");if(o&&r!==void 0)throw new Error("--full cannot be combined with --max-depth. Use --full for complete traversal or --max-depth N for a bounded traversal.");let s=ws(e,i,{maxDepth:o?Number.MAX_SAFE_INTEGER:r,scope:w(n,"scope")}),a=s.rows;if(b(n,"json")){P("affected",t,n,{...Ae(e,i,a,"affected"),coverage:s.coverage});return}if(a.length===0)return A.empty(me(e,i,"No possible impacts found in the bounded reverse caller/reference closure."));de(e,i);let c=-1;for(let l of a)l.depth!==c&&(console.log(`
|
|
236
|
-
\u2500\u2500 Depth ${l.depth} \u2500\u2500`),c=l.depth),console.log(` ${l.file} ${l.shortName}`);console.log(`
|
|
237
|
-
${a.length} possible-impact symbol(s) across ${new Set(a.map(l=>l.file)).size} files; reachability does not prove breakage.`),console.log(` coverage: ${s.coverage.status} \u2014 ${s.coverage.reasons.join(" ")}`)}),Ev=te("co-change",({db:e,args:t,opts:n,budget:i})=>{let o=t[0]===void 0?void 0:M(t,0),r=b(n,"full"),s=Es(e,o,{minTogether:k(n,"minTogether",4),limit:D(n,"limit",30),includeLinked:n.all===!0,scanLimit:i.scanLimit,historyMode:r?"full":"bounded"});if(b(n,"json")){P("co-change",t,n,s,{analysisBudget:i.analysisBudget});return}if(!s.available)return A.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return A.empty(o?`No co-change partners found for ${o} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);rt("co-change candidates"),console.log(o?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
|
|
238
|
-
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
|
|
239
|
-
`),o&&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.
|
|
240
|
-
`);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 ${Tv(a.lastTogetherAt)}`),console.log(` subjects: ${Iv(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
241
|
-
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Tv(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Iv(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(o=>`"${o}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var Av=te("change-surface",({db:e,args:t,opts:n,budget:i})=>{let o=$s(e,M(t,0),{semantic:i.semantic});if(b(n,"json")){P("change-surface",t,n,o,{analysisBudget:i.analysisBudget});return}if(!o)return A.empty("File not found in index.");console.log(`File: ${o.file}`),console.log(`External consumers: ${o.totalExternalConsumers}`),o.fileRisk&&o.fileRisk.reasons.length>0&&console.log(`File risk factors (${o.fileRisk.coverage} metadata): ${o.fileRisk.reasons.map(r=>`${r.kind}: ${r.detail}`).join("; ")}`),console.log(""),A.list(o.symbols,r=>{let s=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"",a=r.riskReasons??[],c=a.length===0?"":` [why: ${a.map(l=>`${l.kind}: ${l.detail}`).join("; ")}]`;return` ${ge(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${s}${c}`})}),Pv=te("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let o=ks(e,{base:w(n,"base"),minContainment:k(n,"minContainment",.7),maxHelpers:K(n,"maxHelpers"),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){P("incomplete-migration",t,n,o,{analysisBudget:i.analysisBudget}),(!o.available||o.findings.length>0)&&(process.exitCode=1);return}if(!o.available){console.error(`error: ${o.note??"Required Git history is unavailable."}`),process.exitCode=1;return}if(o.changedFiles.length===0)return A.empty(`No changes vs ${o.base}.`);console.log(`Incomplete migrations vs ${o.base}: ${o.changedFiles.length} changed file(s), ${o.helpersChecked} new helper(s) scored.`),o.note&&console.log(` note: ${o.note}`);for(let r of o.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(o.findings.length===0){console.log(`
|
|
242
|
-
No incomplete migrations detected.`);return}rt("incomplete migration candidates");for(let r of o.findings){console.log(`
|
|
243
|
-
${r.helperShortName} (${r.helperFile})`),console.log(` helper shape: ${r.helperShape} (${r.specificHelperCalleeCount}/${r.helperCalleeCount} specific callees)`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let s of r.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(`
|
|
244
|
-
${o.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),hp=[{id:"affected",command:"affected <symbol>",description:"Conservative reverse caller/reference closure of symbols that may be impacted by a change",agent:C("Which downstream symbols are statically reachable as possible change impacts?","possible-impact symbol identities, files, and traversal depths; not predicted failures",["symbol"],"bounded"),options:x([u("--full","Traverse without the default depth and per-frontier caller caps"),u("--max-depth <n>","Maximum traversal depth (default: 5)",S),u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Impact"),handler:kv},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: consumers, published API, operational roots, and explained change risk",agent:C("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Impact"),handler:Av},{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:C("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:x([u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Oe,.7),u("--max-helpers <n>","Maximum new helpers to score (default: all)",S),u("-n, --limit <n>","Maximum findings to report",S,20),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:R("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:Pv},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:C("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:x([u("--min-together <n>","Minimum commits where both files changed",S,4),u("-n, --limit <n>","Maximum pairs to report",S,30),u("--all","Include pairs that already have a dependency edge"),u("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},claims:Je(["index-generation","live-workspace"],[X("historical-pairs","findings[]","change-history"),X("structural-link-classification","findings[].structurallyLinked","compiler-graph")]),renderShape:"custom",docs:R("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:Ev}];import{spawn as Lv}from"child_process";import{createHash as Ro,randomUUID as jv}from"crypto";import{existsSync as $o,realpathSync as Mv}from"fs";import{tmpdir as Nv}from"os";import{join as xo,resolve as un}from"path";import{fileURLToPath as Ov}from"url";var Ct=18,Dv=1e3,qv=2*Dv,Fv=4,Wv=4,_v=5,Bv=3,Gv=3,Vv=4,Uv=3,Hv=3,Qv=8,fp=3e4,Kv=5e3,yp=5,zv=10,Jv=1,Yv=5,bp=64*1024*1024,Xv={maxItems:64,maxBytes:128*1024*1024,maxItemBytes:bp,maxBatch:1,responseRetentionMs:6e4};function vp(e,t,n={},i={}){return Zv(e,o=>({kind:"source-search",expectedGeneration:o,pattern:t,options:n}),rS,"search result",i)}function Zv(e,t,n,i,o){if(!cS(o.allowDefault===!0))return null;try{let r=o.allowDefault===!0&&process.env.SCIP_QUERY_QUERY_SERVICE!=="1",s=r?Uo(e):void 0,a=qe(e,s);if(!$o(a.dbPath))return null;let c=Qe(a.dbPath);if(!c||r&&!eS(a,s,c))return null;let l=nS({projectRoot:a.projectRoot,dbPath:a.dbPath,generationIdentity:c},t(c),n,i);return{result:l.result,generationIdentity:c,observationReceipt:l.observationReceipt}}catch(r){return wp()&&console.error(`query-service fallback: ${r instanceof Error?r.message:String(r)}`),null}}function eS(e,t,n){if(e.config.watch?.enabled!==!0)return!1;try{return bc(Lt({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ve,gitContext:t}))===n}catch{return!1}}function Sp(e){return Ro("sha256").update(Cn({kind:"scip-query-service-mailbox",protocolVersion:Ct,sessionDir:un(e)})).digest("hex")}function ai(e){let t=xo(e,"server.json");try{let n=JSON.parse(fe(t,{maxBytes:65536,inputKind:"query service state"}));if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,o=i.processIdentity===void 0?void 0:mr(i.processIdentity);return i.protocolVersion!==Ct||typeof i.sessionIdentity!="string"||i.sessionIdentity!==Sp(e)||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<=0||i.processIdentity!==void 0&&(!o||o.pid!==i.pid)||typeof i.generation!="string"||typeof i.heartbeatAtMs!="number"||!Number.isFinite(i.heartbeatAtMs)?null:{protocolVersion:Ct,sessionIdentity:i.sessionIdentity,pid:i.pid,...o?{processIdentity:o}:{},generation:i.generation,heartbeatAtMs:i.heartbeatAtMs}}catch{return null}}function ci(e,t=Date.now()){if(!Rn(e.pid))return!1;let n=t-e.heartbeatAtMs;if(n>=0&&n<=qv||!e.processIdentity)return!0;let i=He(e.pid);return i!==null&&xn(e.processIdentity,i)}function tS(e){let t=e<zv;return{intervalMs:t?Jv:yp,checkServerState:!t||e%Yv===0}}function nS(e,t,n,i){let o=aS();if(!$o(o))throw new Error("Query service server executable is unavailable.");let r=Math.abs(process.pid)%dS(t),s=sS(e,o,r),a=fr(s),c=Date.now(),l=c+fp,d=ke()+fp,m=jv(),h=iS(m,t),p=gr(h),f=Sp(s),g=yr(a,{mailboxVersion:Ri,protocolVersion:Ct,id:p,operationKey:h,clientId:m,enqueuedAtMs:c,deadlineAtMs:l,sessionIdentity:f,request:t},{nowMs:c,limits:Xv,durability:"visibility"});gp(s,e.projectRoot,o,d);let y=0;for(;ke()<=d;){if($o(g.responsePath))return oS(fe(g.responsePath,{maxBytes:bp,inputKind:"query service response"}),{id:p,operationKey:h,clientId:m,deadlineAtMs:g.authoritativeDeadlineAtMs,generation:e.generationIdentity},n,i);let v=tS(y);if(v.checkServerState){let $=ai(s);(!$||!ci($))&&gp(s,e.projectRoot,o,d)}$p(v.intervalMs),y+=1}throw new Error("Persistent query service timed out.")}function iS(e,t){return Ro("sha256").update(Cn({namespace:"query-service-v18",payload:{clientId:e,request:t}})).digest("hex")}function gp(e,t,n,i){let o=ai(e);if(o&&ci(o))return;let r=Math.min(i,ke()+Kv),s=Ys(xo(e,"startup.lock"),{kind:"query-service-startup",detail:{projectRoot:un(t)},directoryDurability:"recoverable"});try{if(s.kind==="acquired"){let a=ai(e);if(!a||!ci(a)){let c=wp();Lv(process.execPath,[n,e,t],{cwd:t,detached:!c,stdio:c?["ignore","ignore","inherit"]:"ignore",env:{...process.env,SCIP_QUERY_QUERY_SERVICE_SERVER:"1"}}).unref()}}for(;ke()<=r;){let a=ai(e);if(a&&ci(a))return;$p(yp)}}finally{s.kind==="acquired"&&s.lock.release()}throw new Error("Persistent query service did not become ready within 5s.")}function oS(e,t,n,i){let o=JSON.parse(e);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Invalid query service response.");let r=o;if(r.mailboxVersion!==Ri||r.protocolVersion!==Ct||r.id!==t.id||r.operationKey!==t.operationKey||r.clientId!==t.clientId||r.deadlineAtMs!==t.deadlineAtMs)throw new Error("Query service response identity does not match the request.");if(r.ok!==!0)throw new Error(typeof r.error=="string"?r.error:"Persistent query service rejected the request.");if(r.generation!==t.generation)throw new Error("Persistent query service generation changed.");if(!n(r.result))throw new Error(`Persistent query service returned an invalid ${i}.`);let s=ca(r.observationReceipt);if(s.kind!=="supported")throw new Error("Persistent query service returned an invalid observation receipt.");return{ok:!0,protocolVersion:Ct,id:t.id,generation:t.generation,result:r.result,observationReceipt:s.receipt}}function rS(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.pattern=="string"&&(t.mode==="literal"||t.mode==="regexp")&&Array.isArray(t.matches)&&typeof t.matchingLines=="number"&&Number.isSafeInteger(t.matchingLines)&&t.matchingLines>=0&&typeof t.omittedMatches=="number"&&Number.isSafeInteger(t.omittedMatches)&&t.omittedMatches>=0&&typeof t.scannedFiles=="number"&&Number.isSafeInteger(t.scannedFiles)&&t.scannedFiles>=0}function sS(e,t,n){let i=uS(e.projectRoot),o=Ro("sha256").update(Cn({protocolVersion:Ct,projectRoot:i,dbPath:un(e.dbPath),serverPath:un(t),lane:n})).digest("hex");return xo(Nv(),"scip-query-query-service",o)}function aS(){return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER_PATH??Ov(new URL("./query-service-server.js",import.meta.url))}function cS(e){let t=process.env.SCIP_QUERY_QUERY_SERVICE;return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER!=="1"&&t!=="0"&&(t==="1"||e)}function wp(){return process.env.SCIP_QUERY_QUERY_SERVICE_DEBUG==="1"}function lS(){let e=Number(process.env.SCIP_QUERY_QUERY_SERVICE_POOL_SIZE);return Number.isInteger(e)&&e>=1&&e<=Qv?e:Fv}function dS(e){let t=lS();return e.kind==="value-flow"?Math.min(t,Uv):e.kind==="dependence-slice"?Math.min(t,Hv):e.kind==="call-graph"?Math.min(t,Bv):e.kind==="system"?Math.min(t,Vv):e.kind==="reference-reachability"||e.kind==="slice"?Math.min(t,Gv):e.kind==="refs"||e.kind==="trace"||e.kind==="reference-neighborhood"||e.kind==="dataflow"||e.kind==="imports"||e.kind==="unused-imports"?Math.min(t,_v):e.kind==="imported-by"||e.kind==="hierarchy"||e.kind==="by-kind"||e.kind==="kind-counts"?Math.min(t,Wv):t}function uS(e){try{return Mv.native(e)}catch{return un(e)}}function $p(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function pS(e){let t=b(e,"full"),n=D(e,"limit",12);return t?void 0:n}function Rp(e){return{scope:w(e,"scope"),context:k(e,"context",2),limit:D(e,"limit",6),regexp:b(e,"regexp"),ignoreCase:b(e,"ignoreCase"),ranking:"structural"}}function mS(e){let t=w(e,"view")??"source";if(t!=="source"&&t!=="behavior")throw new Error(`Unknown inspect view: ${t}. Use source or behavior.`);return t}function hS(e){let t=[];for(let o of e.definitions){let r=o.signature?` \u2014 ${o.signature}`:"";o.source?t.push(ht({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"exact-unit",headerSuffix:r,ownerSymbol:o.signature??void 0})):t.push(` ${V(o.relativePath,o.startLine,o.endLine)}${r}`)}let n=[],i="";for(let o of e.referencedBy){o.relativePath!==i&&(i&&n.push(""),n.push(` ${o.relativePath}`),i=o.relativePath);let r=Ip(e.referenceEvidence,o.relativePath,o.line);n.push(` line ${j(o.line)} in ${o.enclosingShort} [${Ap(r)}]`),o.source!==void 0&&o.source!==null&&o.sourceStartLine!==void 0&&o.sourceStartLine!==null&&n.push(ht({relativePath:o.relativePath,startLine:o.sourceStartLine,source:o.source,sessionPolicy:"preview",focusLines:new Set([o.line]),ownerSymbol:o.enclosingShort??void 0,indent:" ",sourceIndent:" "}))}return[{title:"DEFINITION",rows:t,preserveRowNewlines:!0},{title:"REFERENCED BY",rows:n,preserveRowNewlines:!0},{title:"CLAIM SUPPORT",rows:Pp(e.claimSupport),skipIfEmpty:!0}]}function Ip(e,t,n){return e.find(i=>i.relativePath===t&&i.line===n)?.sourceKind}function Ap(e){switch(e){case"complete-call-expression":return"complete call";case"non-call-reference":return"non-call reference";case"bounded-context":return"bounded context";case"unavailable":return"source unavailable";default:return"coverage unknown"}}function Pp(e){return e?[xp("Reference-absence claims",e.referenceAbsence),xp("Callsite-argument claims",e.callsitePredicates)]:[]}function xp(e,t){return t.status==="eligible"?` ${e}: eligible within ${t.scope}. ${t.limitations.join(" ")}`:[` ${e}: INELIGIBLE within ${t.scope}; ${t.reason}`,...t.followup?[` Inspect uncertain sites together: ${t.followup}`]:[]].join(`
|
|
245
|
-
`)}var Co=["definition","references","callers","callees","dependencies","consumers"],Eo=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function ko(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Co];let n=t.filter(i=>!Co.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Co.join(", ")}, or all.`);return[...new Set(t)]}function fS(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...ot];let n=t.filter(i=>!ot.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${ot.join(", ")}, or all.`);return[...new Set(t)]}function gS(e){if(e!==void 0){if(Ai.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${Ai.join(", ")}.`)}}function yS(e){if(e!==void 0){if(["incoming","outgoing","both"].includes(e))return e;throw new Error(`Unknown evidence direction: ${e}. Use incoming, outgoing, or both.`)}}function bS(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function vS(e){if(e.length===0)return;let t={};for(let n of e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean)){let i=n.lastIndexOf("="),o=n.slice(0,i),r=n.slice(i+1);if(i<=0||!Eo.includes(o))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Eo.join(", ")}.`);if(Object.hasOwn(t,o))throw new Error(`Duplicate inspect evidence budget: ${o}.`);if(!/^\d+$/u.test(r))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);let s=Number(r);if(!Number.isSafeInteger(s))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);t[o]=s}return t}function SS(e){let t=li(e),n=Lp(e,t),i=e.matches.map(h=>$S(e,h)),o=i.map(h=>h.text),r=i.reduce((h,p)=>h+p.shortenedLines,0),s=i.reduce((h,p)=>h+p.omittedContextLines,0),a=ES(t),c=n.mode==="complete"?TS(e,t):[],l=e.textCoverage,d=To(e),m=n.mode==="bounded"?kS(e):c.length>0?[` Recover every unmaterialized owning unit in ${c.length} bounded batch command(s):`,...c.map(h=>` ${h}`)]:[" Every matching source window was materialized; no drilldown remains."];return[{title:"REQUEST",rows:[` exact-text=${JSON.stringify(e.pattern)}; mode=${e.mode}`]},{title:`OBSERVED MATCH IDENTITIES (${t.length}/${e.matchingLines}, ${n.mode.toUpperCase()})`,rows:a},{title:`OBSERVED SOURCE (${e.matches.length}/${e.matchingLines} WINDOWS)`,rows:o,preserveRowNewlines:!0},{title:"EVIDENCE CALIBRATION",rows:[` ${d?"Exact":"Observed"} cardinality is current project text; compiler ownership is an aligned semantic overlay. Neither ownership nor co-occurrence proves task relevance or a graph relationship.`,...r>0?[` ${r} overlong matched line(s) were shortened; every exact path:line identity remains recoverable with scip-query code.`]:[],...s>0?[` ${s} nonfocus context line(s) were omitted from expensive previews; the matched lines remain visible and JSON retains complete windows.`]:[]]},{title:"COVERAGE",rows:[` ${d?"Exact":"Observed"} cardinality: ${e.matchingLines} matching line(s) across ${e.matchingFiles??e.fileCoverage?.length??0} file(s). Identity manifest: ${t.length}/${e.matchingLines} matching line(s); ${n.mode==="complete"?"complete":`${n.omitted} lower-ranked identities withheld before rendering`}. Source materialization: ${e.matches.length}/${e.matchingLines} window(s); ${e.omittedMatches} exact match location(s) were not expanded into source.`,...l?[` Exact text: ${l.scannedTextFiles}/${l.candidateFiles} current project text file(s), ${l.scannedBytes.toLocaleString()} byte(s); semantic owners ${l.semanticFiles.aligned} aligned, ${l.semanticFiles.stale} stale, ${l.semanticFiles.unavailable} unavailable; exclusions ${l.skippedBinaryPaths.length} binary, ${l.skippedUnreadablePaths.length} unreadable, ${l.skippedOversizedPaths.length} oversized.`,...d?[]:[" Text coverage is incomplete: unreadable or oversized text may contain additional matches."]]:[]]},{title:"RECOVERY",rows:m}]}var ut=320,wS=1200;function $S(e,t){let n=t.source.split(`
|
|
246
|
-
`);if(!(n.some(m=>m.length>ut)||t.source.length>wS)){let m=t.ownerShort?` in ${t.ownerShort}`:"";return{text:ht({relativePath:t.relativePath,startLine:t.startLine,source:t.source,sessionPolicy:"preview",focusLines:new Set([t.focusLine]),ownerSymbol:t.ownerShort??void 0,headerSuffix:m}),shortenedLines:0,omittedContextLines:0}}let r=t.ownerShort?` in ${t.ownerShort}`:"",s=Math.max(0,Math.min(n.length-1,t.focusLine-t.startLine)),a=n[s]??"",c=a.length>ut?1:0,l=` >${String(j(t.focusLine)).padStart(5)} ${RS(e,a)}`,d=Math.max(0,n.length-1);return{text:[` ${V(t.relativePath,t.startLine,t.endLine)}${r}`,l,...d>0?[` \u2026[${d} nonfocus context line(s) omitted]`]:[]].join(`
|
|
247
|
-
`),shortenedLines:c,omittedContextLines:d}}function RS(e,t){if(t.length<=ut)return t;let n=xS(e,t);if(n<0){let l=ut/2,d=t.length-ut;return`${t.slice(0,l)}\u2026[${d} characters omitted]\u2026${t.slice(-l)}`}let i=e.mode==="literal"?Math.min(e.pattern.length,ut):1,o=n-Math.floor((ut-i)/2),r=Math.max(0,Math.min(o,t.length-ut)),s=r+ut,a=r>0?`\u2026[${r} characters omitted]\u2026`:"",c=s<t.length?`\u2026[${t.length-s} characters omitted]\u2026`:"";return`${a}${t.slice(r,s)}${c}`}function xS(e,t){if(e.mode==="literal"){let n=t.indexOf(e.pattern);return n>=0?n:t.toLowerCase().indexOf(e.pattern.toLowerCase())}try{return new RegExp(e.pattern,"u").exec(t)?.index??-1}catch{return-1}}function CS(e){let t=e.groups.flatMap((n,i)=>{let o=n.kind==="shared-callee-owners"?"shared callee":n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?"basis root":"root",r=n.roots.slice(0,6),s=r.map(c=>{let l=c.matches.map(d=>`${d.term}[${d.sources.join("+")}]`).join(", ");return` ${o} ${c.label} \u2014 ${c.file}:${j(c.line)} \u2014 ${l}`}),a=n.relations.map(c=>` ${c.fromLabel} \u2192 ${c.toLabel} [${c.kind}; ${c.strength}; ${c.evidence}; depth ${c.depth}${c.runtimeBoundaryKey?`; ${c.runtimeBoundaryKey}`:""}]`);return[` [${i+1}] ${n.kind}; terms: ${n.matchedTerms.join(", ")||"(structural only)"}`,...n.kind==="shared-callee-owners"?[` map owners: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.omittedCandidateOwners.length>0?[` additional candidate owners: ${n.omittedCandidateOwners.map(c=>c.label).join(", ")}`,...n.ownerRecoveryCommands.map(c=>` additional owner map if those candidates can change the answer: ${c}`)]:[]]:n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?[` map anchors: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.kind==="parallel-paths"?[` shared path vocabulary: ${n.parallelSharedPathTerms?.join(", ")||"(none)"}`,` causal evidence on ${n.parallelConnectedSides??0}/2 independently named path(s); matched orchestration roots on ${n.parallelOrchestrationSides??0}/2; no cross-path edge is claimed.`]:[],...n.upstreamEntries.map(c=>` upstream entry: ${c.name} \u2014 ${c.file}:${j(c.line)}; if command preconditions can change the answer, include this location in the one batched gap inspect after the map.`)]:[],...s,...n.roots.length>r.length?[` ... ${n.roots.length-r.length} additional basis owner(s) retained in the result.`]:[],...a,...n.omittedRelations>0?[` ... ${n.omittedRelations} additional relationship(s) withheld from this compact view.`]:[],` next abstraction (run to completion before any inspect): ${n.systemMapCommand}`]});return[{title:"REQUIRED NEXT STEP",rows:[" Choose one evidence-grounded anchor set below and run its exact next-abstraction system-map command to transport completion."," inspect, code, and evidence are intentionally unavailable until that map completes."]},{title:"NORMALIZED REPOSITORY VOCABULARY",rows:[` matched: ${e.matchedTerms.join(", ")||"(none)"}`,` unmatched: ${e.unmatchedTerms.join(", ")||"(none)"}`]},{title:`EVIDENCE-GROUNDED ANCHOR SETS (${e.groups.length} SHOWN)`,rows:t},{title:"ANCHOR DISCOVERY COVERAGE",rows:[` Repository scan: ${e.scannedFiles} current text file(s), ${e.scannedBytes.toLocaleString()} byte(s).`,` Lexical owners: ${e.candidateRootCount}; structurally analyzed: ${e.analyzedRootCount}; lower-ranked owners not graph-expanded: ${e.omittedRootCount}.`,` Displayed anchor sets: ${e.groups.length}; withheld sets or unanalyzed roots: ${e.omittedGroupCount}.`," cross-boundary-flow joins otherwise separate call groups only when an indexed runtime producer\u2192consumer link and bounded downstream calls connect them; parallel-paths batches disconnected regions only when the query names distinct path vocabulary shared by those regions and does not claim a causal edge; connected-flow follows calls forward from matched owners; shared-callee-owners finds callable owners that converge on common callees without claiming those callees are effects."," Ranking uses repository vocabulary, compiler ownership, and bounded call connectivity; it does not establish task relevance."," Selection gate: reject a set whose roots and matched terms omit an object, branch, or stage named by a material claim. Connectivity cannot make a partial set eligible. Among sets that cover every named part, use the first ranked eligible set; use parallel-paths when no connected-flow covers them together."," Anchor roots are locator evidence, not behavior evidence. Select one set, run its next-abstraction command to transport completion, and only then decide whether source inspection is necessary. Never run a map and inspect concurrently.",...e.recoveryCommand?[` Expand the ranked manifest only if the shown sets cannot establish the requested flow: ${e.recoveryCommand}`]:[" Every candidate owner was structurally analyzed and every resulting anchor set was shown."]]}]}function To(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function Lp(e,t){return e.identityCoverage??{mode:t.length===e.matchingLines?"complete":"bounded",returned:t.length,total:e.matchingLines,omitted:Math.max(0,e.matchingLines-t.length)}}function kS(e){let t=e.fileCoverage??[],n=new Map;for(let o of t){let r=o.relativePath.indexOf("/"),s=r<0?"<root>":o.relativePath.slice(0,r),a=n.get(s)??[];a.push(o),n.set(s,a)}let i=[...n].sort(([o],[r])=>o.localeCompare(r)).flatMap(([o,r])=>{let s=[...r].sort((c,l)=>c.relativePath.localeCompare(l.relativePath)),a=s.reduce((c,l)=>c+l.matchingLines,0);return o==="<root>"?s.map(c=>` ${c.relativePath}: ${c.matchingLines} match(es); scip-query search ${Le(e.pattern)} --scope ${Le(c.relativePath)}`):[` ${o}: ${a} matching line(s) across ${s.length} file(s); scip-query search ${Le(e.pattern)} --scope ${Le(o)}`]});return[" Broad selector: identity enumeration stopped before output transport; there is no cursor to drain.",...i.length>0?[" Complete top-level recovery manifest:",...i]:[]," Narrow one structural region; ordering does not infer task relevance."]}function jp(e){return e.identities??e.matches.map(t=>({relativePath:t.relativePath,focusLine:t.focusLine,ownerSymbol:t.ownerSymbol,ownerShort:t.ownerShort,ownerStartLine:t.ownerStartLine??null,ownerEndLine:t.ownerEndLine??null,fileKind:t.fileKind??"source",freshness:t.freshness}))}function li(e){return e.identityManifest??jp(e)}function ES(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return[...t.entries()].flatMap(([n,i])=>{let o=new Map;for(let r of i){let s=r.ownerSymbol??"<file>",a=r.ownerStartLine===null||r.ownerEndLine===null?"":` ${j(r.ownerStartLine)}-${j(r.ownerEndLine)}`,c=o.get(s)??{label:r.ownerShort?`${r.ownerShort}${a}`:"<file scope>",lines:[]};c.lines.push(j(r.focusLine)),o.set(s,c)}return[` ${n} [${i[0].fileKind}; ${i.length} match(es)]`,...[...o.values()].flatMap(r=>Mp(r.lines,24).map((s,a)=>` ${a===0?r.label:"\u21B3"} @ ${s.join(",")}`))]})}function TS(e,t){let n=new Set(e.matches.map(o=>Cp(o))),i=new Set;for(let o of t){if(n.has(Cp(o)))continue;let r=j(o.ownerStartLine??o.focusLine),s=j(o.ownerEndLine??o.focusLine);i.add(`${o.relativePath}:${r}-${s}`)}return Mp([...i],24).map(o=>`scip-query code ${o.map(r=>Le(r)).join(" ")}`)}function Cp(e){return`${e.relativePath}\0${e.focusLine}`}function Mp(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Le(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function IS(e){let t=["scip-query inspect"];for(let i of O(e,"search"))t.push(`--search ${Le(i)}`);for(let i of O(e,"symbol"))t.push(`--symbol ${Le(i)}`);for(let i of O(e,"at"))t.push(`--at ${Le(i)}`);let n=w(e,"scope");return n&&t.push(`--scope ${Le(n)}`),t.push("--view behavior"),t.join(" ")}function AS(e,t){if(!(e.view!=="source"||b(t,"allowLargeSource")||(e.returnedCharacters??0)<=2e4))throw new Error(["INSPECT SOURCE PACKET REFUSED",`${e.returnedCharacters??0} exact source character(s) across ${e.units?.length??0} selected unit(s) exceed the ${2e4}-character safe materialization ceiling.`,"No partial source was emitted.",`Read the same constructs with complete statement accounting: ${IS(t)}`,"Narrow to smaller exact selectors, or rerun with --allow-large-source only when the omitted syntax itself can change the decision."].join(`
|
|
248
|
-
`))}function PS(e,t){if(e.view!=="behavior"||b(t,"allowLargeBehavior"))return;let n=(e.omissionGroups??[]).filter(r=>r.sourceCharacters>2e4&&r.roles.some(s=>s==="location"||s==="definition"));if(n.length===0&&(e.returnedViewCharacters??0)<=2e4)return;let i=n.flatMap(r=>r.anchors).map(r=>`${r.relativePath}:${j(r.line)}`),o=i.length>0?i.join(", "):O(t,"at").join(", ");throw new Error(["INSPECT BEHAVIOR FOCUS REQUIRED",`The selector set resolves to behavioral constructs above the ${2e4}-character evidence ceiling${o?` (${o})`:""}.`,"No partial behavior was emitted, and this refusal does not establish an exploration obligation.","Use one or more interior file:line locations already visible in connected behavior, and batch only the named gaps. Do not use --full to turn a broad construct into a focus.","Use --allow-large-behavior only when every statement in the construct can change the decision."].join(`
|
|
249
|
-
`))}function LS(e){let t=e.units??[],n=e.searches.map(h=>{let p=[` ${h.pattern}: ${h.returnedMatches}/${h.matchingLines} matching line(s) materialized across ${h.returnedFiles??0}/${h.matchingFiles??0} file(s); ${h.selectedUnits??0}/${h.candidateUnits??0} deduplicated unit(s) selected`];return(h.omittedMatches>0||(h.omittedUnits??0)>0)&&(p.push(` Withheld: ${h.omittedMatches} matching line(s), ${h.omittedFiles??0} file(s) with no materialized match, and ${h.omittedUnits??0} materialized unit(s) outside the packet ceiling.`),(h.scopeHints?.length??0)>0&&(p.push(" Highest-coverage scopes available for focused expansion:"),p.push(...(h.scopeHints??[]).map(f=>` ${f.scope}: ${f.returnedMatches}/${f.matchingLines} matching line(s) materialized; ${f.exactFollowup}`)),(h.omittedScopeHints??0)>0&&p.push(` ... ${h.omittedScopeHints} additional matching scope(s).`)),h.exactFollowup&&p.push(` Expand this selector completely only if omitted matches can change the decision: ${h.exactFollowup}`)),p.join(`
|
|
250
|
-
`)}),i=e.locations.map(h=>` ${h.matched?"matched":"missing"} ${h.target}`),o=t.map(DS),r=Dp(e.bindingClosure),s=(e.omissionGroups??[]).map(qS),a=jS(e),c=e.evidence.flatMap(h=>{let p=Np(h,"inspect");return p?[` ${p}`]:[]}),l=e.packetCoverage,d=l?[` ${l.mode==="complete"?"Complete":"Ranked bounded"} semantic packet: ${l.returnedUnits}/${l.candidateUnits} materialized unit(s), ${e.returnedLines??0} underlying source line(s), and ${e.returnedViewCharacters??e.returnedCharacters??0} displayed evidence character(s).`,` Selection ceiling: ${l.maxUnits} unit(s) or ${l.maxCharacters} displayed evidence character(s); syntax units are never clipped.`,` Exact symbol/location evidence: ${l.exactSelectorsComplete?"complete within materialized compiler evidence":"some lower-ranked units withheld"}.`,...l.channels?[` Evidence channels: ${OS(l.channels)}.`]:[],...l.omittedUnits>0?[` Withheld materialized units by role: ${NS(l.omittedByRole)}.`]:[],...l.expansionCommand?[` Expand the complete selector set only if omitted evidence can change the decision: ${l.expansionCommand}`]:[]," Universal output transport may still page the rendered bytes; transport pages do not change this selection coverage."]:[` Complete semantic packet: ${t.length} deduplicated unit(s), ${e.returnedLines??0} source line(s), and ${e.returnedCharacters??0} source character(s).`],m=e.stoppingSummary?[` ${e.stoppingSummary.queryStatus??e.stoppingSummary.status}: ${e.stoppingSummary.guidance}`,...e.stoppingSummary.openEvidence>0?[` ${e.stoppingSummary.openEvidence} open evidence item(s); ${(e.omissionGroups??[]).length} recoverable omission group(s).`]:[]]:[];return[{title:"REQUEST",rows:[...n.map(h=>` search ${h.trimStart()}`),...i.map(h=>` location ${h.trimStart()}`),...c.map(h=>` symbol ${h.trimStart()}`)]},{title:"OBSERVED FACTS",rows:[...o,...r],preserveRowNewlines:!0,skipIfEmpty:!0},{title:"EVIDENCE CALIBRATION",rows:[` view=${e.view}; exact source is current working-tree text; behavioral outlines label whether they are statement-complete, partial, or verbatim source units.`," Source co-location and references do not become executable reachability. Runtime facts retain their displayed strength and resolution."]},{title:"COVERAGE",rows:[...d,...m]},{title:"RECOVERY",rows:[...s,...a],skipIfEmpty:!0}]}function jS(e){let t=e.causalFrontier;if(!t||t.candidateAnchors===0)return[];let n=t.anchors.filter(r=>r.alternativeCount===1),i=[` ${n.length}/${t.candidateAnchors} bounded downstream target(s) are uniquely resolved and visible; these targets are outside the materialized constructs, not evidence already inspected.`];for(let r of n){let s=r.alternatives[0],a=r.callsite.signals.length>0?` [${r.callsite.signals.join(",")}]`:"";i.push(` ${r.direction??"downstream"} ${r.causalRole??"callee"} from ${r.fromLabel} at ${r.callsite.file}:${j(r.callsite.line)}${a}`,` ${s.label} \u2014 ${s.file}:${j(s.line)}`)}let o=MS([...(e.omissionGroups??[]).flatMap(r=>r.anchors.map(s=>({file:s.relativePath,line:s.line}))),...n.map(r=>({file:r.alternatives[0].file,line:r.alternatives[0].line}))]).slice(0,24);return o.length>0&&i.push(` If any listed target or withheld requested construct remains material, run this one final recovery batch before answering: scip-query inspect ${o.map(r=>`--at ${Le(`${r.file}:${j(r.line)}`)}`).join(" ")} --view behavior`),t.omittedAnchors>0&&i.push(` ${t.omittedAnchors} additional downstream target(s) remain accounted in the frontier; use the printed remaining inspect commands only for a named unresolved fact.`),i}function MS(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}`,n);return[...t.values()]}function NS(e){return Object.entries(e).map(([t,n])=>`${t}=${n}`).join(", ")}function OS(e){return Eo.filter(t=>e[t].candidateUnits>0||e[t].omittedUnits>0).map(t=>{let n=e[t],i=n.maxUnits===Number.MAX_SAFE_INTEGER?"unbounded":String(n.maxUnits);return`${t} ${n.returnedUnits}/${n.candidateUnits} (limit ${i})`}).join("; ")}function DS(e){switch(e.kind){case"source":{let t=e.ownerShort?` in ${e.ownerShort}`:"";if(e.behavior){let o=e.behavior.coverage,s=[` representation: ${o.omittedStatements>0?"partial behavioral outline":o.copiedStatements===o.sourceStatements?"verbatim source unit (not compressed)":"statement-complete behavioral outline"}`,` ${e.behavior.constructKind}: ${e.behavior.signature}`,...e.behavior.lines.map(a=>` L${j(a.line)}${a.endLine>a.line?`-${j(a.endLine)}`:""} ${" ".repeat(a.depth)}${a.text}${a.copied?" [verbatim]":""}`),...e.behavior.testCases.length>0?[` related test cases: ${e.behavior.testCases.join("; ")}`]:[],...kp(e.runtimeFacts??[]),` coverage: ${o.representedStatements}/${o.sourceStatements} source statement(s) represented; ${o.copiedStatements} verbatim; ${o.omittedStatements} omitted; ${e.behavior.outlineCharacters}/${e.behavior.rawCharacters} estimated characters`];return[` ${V(e.relativePath,e.startLine,e.endLine)}${t}`,` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`,Yt({kind:"unit",identity:`inspect-behavior:${e.relativePath}:${e.startLine}:${e.endLine}`,content:s.join(`
|
|
251
|
-
`),label:e.ownerShort??`${e.relativePath}:${j(e.startLine)}`,indent:" "})].join(`
|
|
252
|
-
`)}let n=ht({relativePath:e.relativePath,startLine:e.startLine,source:e.source,sessionPolicy:"exact-unit",focusLines:new Set(e.focusLines),ownerSymbol:e.ownerShort??void 0,headerSuffix:t,afterHeader:[` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`]}),i=kp(e.runtimeFacts??[]);return i.length>0?`${n}
|
|
253
|
-
${i.join(`
|
|
254
|
-
`)}`:n}case"path":return[` ${e.relationship}`,` ${e.roles.join(", ")} edge source was not located. Follow up exactly: ${e.exactFollowup}`].join(`
|
|
255
|
-
`);default:return FS(e)}}function kp(e){return e.map(t=>{let n=t.keyParts.map(i=>`${i.name}=${i.value}`).join(", ")||"no resolved key";return` runtime L${j(t.line)} [${t.strength}] ${t.action} (${t.role}; ${t.resolution}) ${n}; proof=${t.derivation.rule}`})}function qS(e){let t=e.anchors.slice(0,4).map(n=>{let i=n.ownerShort?` in ${n.ownerShort}`:"",o=n.behaviorSignals.length>0?` [${n.behaviorSignals.join(",")}]`:"";return` ${n.relativePath}:${j(n.line)}${i}${o}`});return e.anchors.length>t.length&&t.push(` ... ${e.anchors.length-t.length} additional anchor(s) represented by this group.`),[` ${e.id} ${e.scope} \u2014 ${e.candidateUnits} unit(s), ${e.sourceCharacters} source character(s)`,` channel: ${e.channel??"unclassified"}; roles: ${e.roles.join(", ")}; behavior: ${e.behaviorSignals.join(", ")||"not summarized"}`,...t,` Drill into this group together: ${e.drillCommand}`].join(`
|
|
256
|
-
`)}function FS(e){throw new Error(`Unhandled source inspection unit: ${JSON.stringify(e)}`)}function Np(e,t="evidence"){if(e.kind==="missing")return`No definition matched '${e.query}'.`;if(e.kind!=="ambiguous")return;let n=e.candidates.map(r=>{let s=`'${r.symbol.replaceAll("'","'\\''")}'`;return t==="inspect"?` scip-query inspect --symbol ${s}`:` scip-query evidence ${s}`}).join(`
|
|
257
|
-
`),i=e.candidates.length,o=i<e.total?` Showing the highest-ranked ${i}; narrow by path or`:"";return`Target '${e.query}' is ambiguous across ${e.total} definitions.${o} run one listed exact command:
|
|
258
|
-
${n}`}function Io(e){if(e.kind!=="matched")return[];let t=e.definition?[ht({relativePath:e.definition.relativePath,startLine:e.definition.startLine,source:e.definition.source,sessionPolicy:"exact-unit",ownerSymbol:e.definition.shortName,headerSuffix:` ${e.definition.shortName}`}),...Dp(e.definition.bindingClosure)]:[],n=e.referenceWindows.map(o=>{let r=o.references.map(s=>`${j(s.line)} in ${s.enclosingShort} [${Ap(Ip(e.referenceEvidence,o.relativePath,s.line))}]`).join(", ");return ht({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"preview",focusLines:new Set(o.references.map(s=>s.line)),headerSuffix:` references: ${r}`})}),i=o=>o.map(r=>ht({relativePath:r.relativePath,startLine:r.startLine,source:r.source,sessionPolicy:"preview",ownerSymbol:r.shortName,headerSuffix:` ${r.shortName}${r.omittedLines>0?` (${r.omittedLines} line(s) omitted)`:""}`}));return[{title:"DEFINITION",rows:t,preserveRowNewlines:!0,skipIfEmpty:!0},{title:"REFERENCE SITES",rows:n,preserveRowNewlines:!0,skipIfEmpty:!0},{title:"CALLERS",rows:i(e.callers),preserveRowNewlines:!0,skipIfEmpty:!0},{title:"CALLEES",rows:i(e.callees),preserveRowNewlines:!0,skipIfEmpty:!0},{title:"DEPENDENCIES",rows:e.dependencies.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CONSUMERS",rows:e.consumers.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CLAIM SUPPORT",rows:Pp(e.claimSupport),skipIfEmpty:!0}]}function WS(e){if(e.kind!=="graph-packet")return Io(e);let t=e.graph.selection??{direction:"both",subtypes:[],connecting:!1,inventoryOnly:!1,foldIds:[]},n=[` direction=${t.direction}; subtypes=${t.subtypes.length>0?t.subtypes.join(","):"all"}; operation=${t.connecting?"connecting":"reachability"}; materialization=${t.inventoryOnly?"inventory-only":t.foldIds.length>0?`folds(${t.foldIds.join(",")})`:"edges"}`,...e.graph.targets.map(m=>{let h=m.omittedCandidates>0?`; ${m.omittedCandidates} candidate(s) omitted`:"";return` selector [${m.status}] ${m.kind} ${m.query}${h}`})],i=ot.flatMap(m=>{let h=e.graph.edges.filter(p=>p.family===m);return h.length===0?[]:[` ${m} (${h.length})`,...h.map(p=>` ${Ao(p)}`)]}),o=(e.graph.inventory??[]).map(m=>` inventory ${m.family}/${m.subtype}: incoming=${m.incoming}; outgoing=${m.outgoing}; both=${m.both}`);o.length>0&&o.unshift(" Inventory basis: incoming and outgoing are separately deduplicated reachable-edge sets around the selected roots; both is their deduplicated union, so it need not equal their sum.");let r=_S(e.graph.folds??[]),s=BS(e.graph.edges),a=e.graph.coverage,c=[` ${a.status}: ${a.returnedEdges}/${a.eligibleEdges} materialized relationship(s); ${a.matchedEdges??a.eligibleEdges} matched the projection; depth <= ${a.maxDepth}; ${a.frontierGroups} accounted frontier group(s); ${a.unsupportedFrontiers} unsupported frontier(s).`,` ${a.explanation}`,...Op(a.blindSpots).map(m=>` Unsupported or unavailable: ${m}`)],l=e.source.flatMap(m=>m.kind!=="matched"?[{title:`SOURCE SELECTOR \u2014 ${m.query}`,rows:[` [${m.kind}]`]}]:Io(m).map(h=>({...h,title:`${m.shortName} \u2014 ${h.title}`}))),d=[...r,...a.omittedEdges>0&&r.length===0?[` Expand the same selectors only if an omitted relationship is material: add --max-edges ${a.eligibleEdges}.`]:[],...e.sourceRecovery?[` Graph traversal stays graph-sized; ${e.sourceRecovery.selectors} requested source selector(s) were not embedded.`,` Read the named source gap separately: ${e.sourceRecovery.command}`]:[]];return[{title:"REQUEST",rows:n},{title:"OBSERVED FACTS",rows:[...o,...i],skipIfEmpty:!0},...l,{title:"EVIDENCE CALIBRATION",rows:s},{title:"COVERAGE",rows:c},{title:"RECOVERY",rows:d,skipIfEmpty:!0}]}function _S(e){return e.length===0?[]:[" Rerun the same selectors and bounds with --fold <id>; each ID materializes exactly that folded edge set.",...[...e].sort((n,i)=>n.family.localeCompare(i.family)||(n.region??"").localeCompare(i.region??"")||n.id.localeCompare(i.id)).map(n=>{let i=n.subtypes??[n.subtype],o=i.length===1?i[0]:`${i.length} subtypes`;return` ${n.id} ${n.family}/${o} ${n.edgeCount} edge(s), ${n.nodeIds.length} node(s), ${n.mode} @ ${n.region??"unscoped"}`})]}function BS(e){let t=Op(e.map(o=>o.evidenceStrength)),n=t.length===0?[" No relationships were materialized, so no edge evidence strength is claimed."]:t.map(o=>` ${o}: ${Qt[o]}`),i=new Map;for(let o of e){let r=(o.evidenceConstituents??o.evidenceMethods.map(a=>({method:a,strength:o.evidenceStrength}))).map(a=>`${a.method}=${a.strength}`).join(", "),s=`${o.family}/${o.subtype}\0${o.providerId}\0${o.evidenceStrength}\0${r}`;i.set(s,` ${o.family}/${o.subtype} [${o.evidenceStrength}] provider=${o.providerId}; ceiling=${o.supportCeiling}; constituents=${r||"none reported"}; establishes=${o.establishes}; does-not-establish=${o.nonClaims.join(" ")||"no additional provider non-claim"}`)}return[...n,...i.values()]}function Op(e){return[...new Set(e)]}function Ao(e){let t=e.context?Object.entries(e.context).filter(([,o])=>o!==void 0).map(([o,r])=>`${o}=${Ep(r)}`):[],n=e.attributes?Object.entries(e.attributes).map(([o,r])=>`${o}=${Ep(r)}`):[],i=[...t,...n];return`[${e.evidenceStrength}] ${Tp(e.from)} -> ${Tp(e.to)} \u2014 ${e.subtype}${i.length>0?`; ${i.join(", ")}`:""}`}function Ep(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}function Tp(e){let t=e.location?` @ ${V(e.location.file,e.location.line,e.location.endLine??e.location.line)}`:"";return`${e.label}${t}`}function Dp(e){if(!e)return[];let t=[];for(let n of e.inline)t.push(` inline ${n.name} @ ${V(n.relativePath,n.startLine,n.endLine)}`,` ${n.source??""}`);return t}var GS=Ie("imports",{query:({db:e,args:t,budget:n})=>Gr(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)."}),VS=te("dataflow",({db:e,args:t,opts:n,budget:i})=>{let o=M(t,0),r=Ws(e,o,{semantic:i.semantic});if(b(n,"json")){P("dataflow",t,n,Ae(e,o,r,"dataflow"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"No dataflow found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
|
|
259
|
-
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${j(s.line)}`)}if(r.usageSites.length>0){console.log(`
|
|
260
|
-
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of r.usageSites)console.log(` ${s.file}:${j(s.line)} in ${s.enclosingShort}`)}if(r.producers.length>0){console.log(`
|
|
261
|
-
\u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of r.producers)console.log(` ${s.file} ${s.shortName}`)}if(r.consumers.length>0){console.log(`
|
|
262
|
-
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of r.consumers)console.log(` ${s.file} ${s.shortName}`)}}),US=te("reference-neighborhood",({db:e,args:t,opts:n,budget:i})=>{let o=M(t,0),r=Fs(e,o,{semantic:i.semantic});if(b(n,"json")){P("reference-neighborhood",t,n,Ae(e,o,r,"reference-neighborhood"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"No reference neighborhood found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
|
|
263
|
-
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINITION \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${j(s.line)}`)}if(r.referenceSites.length>0){console.log(`
|
|
264
|
-
\u2550\u2550\u2550 REFERENCES \u2550\u2550\u2550`);for(let s of r.referenceSites)console.log(` ${s.file}:${j(s.line)} in ${s.enclosingShort}`)}if(r.incomingCalls.length>0){console.log(`
|
|
265
|
-
\u2550\u2550\u2550 INCOMING CALLS \u2550\u2550\u2550`);for(let s of r.incomingCalls)console.log(` ${s.file} ${s.shortName}`)}if(r.outgoingCalls.length>0){console.log(`
|
|
266
|
-
\u2550\u2550\u2550 OUTGOING CALLS \u2550\u2550\u2550`);for(let s of r.outgoingCalls)console.log(` ${s.file} ${s.shortName}`)}}),HS=Z(({db:e,args:t,opts:n})=>{let i=M(t,0),o=na(e,{symbols:[i]},{maxDepth:k(n,"depth",2),maxEdges:k(n,"maxEdges",48)});if(b(n,"json")){P("value-flow",t,n,o);return}de(e,i),o.edges.length===0?A.empty("No proved value transfers found. Missing output is not evidence that no value flow exists; inspect coverage."):A.list(o.edges,r=>` ${Ao(r)}`),console.log(`
|
|
267
|
-
Coverage: ${o.coverage.status}; ${o.coverage.basis}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),QS=te("slice",({db:e,args:t,opts:n,budget:i})=>{let o=M(t,0),r=b(n,"forward")?"forward":"backward",s=Bs(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){P("slice",t,n,Ae(e,o,s,"slice"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(me(e,o,"No slice found."));if(de(e,o),console.log(`${s.direction} slice of ${s.shortName}
|
|
268
|
-
`),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
269
|
-
${a.relationship}`),console.log(`
|
|
270
|
-
${s.connectedSymbols.length} connected symbol(s).`)}),KS=te("reference-reachability",({db:e,args:t,opts:n,budget:i})=>{let o=M(t,0),r=b(n,"forward")?"forward":"backward",s=_s(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){P("reference-reachability",t,n,Ae(e,o,s,"reference-reachability"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(me(e,o,"No reference reachability found."));de(e,o),console.log(`${s.direction} reference/call reachability from ${s.shortName}
|
|
271
|
-
`),A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
272
|
-
${a.relationship}`),console.log(`
|
|
273
|
-
${s.connectedSymbols.length} connected symbol(s).`)}),zS=Z(({db:e,args:t,opts:n})=>{let i=M(t,0),o=ia(e,i,{direction:b(n,"forward")?"forward":"backward",maxDepth:k(n,"depth",3),maxEdges:k(n,"maxEdges",200)});if(b(n,"json")){P("dependence-slice",t,n,o);return}console.log(`${o.direction} dependence slice of ${i}
|
|
274
|
-
`),o.edges.length===0?A.empty("No proved dependence path found. Missing output is not evidence of absence; inspect coverage."):A.list(o.edges,r=>` depth ${r.traversalDepth} ${r.supporting?"[support] ":""}${Ao(r)}`),console.log(`
|
|
275
|
-
Coverage: ${o.coverage.status}; ${o.coverage.basis}; ${o.coverage.criterionKind}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),JS=Z(({db:e,args:t,opts:n})=>{let i=M(t,0),o=Mr(e,{className:i});if(b(n,"json")){P("methods",t,n,o,{coverage:YS(o)}),o.kind!=="matched"&&(process.exitCode=1);return}if(o.kind==="matched"){A.list(o.methods,r=>` ${ge(r.startLine,r.endLine)} ${r.name}`);return}A.empty(XS(o)),process.exitCode=1});function YS(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 XS(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}:${j(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 qp=[...Xa,lt({id:"files",command:"files <pattern>",description:"Find current project files matching a path pattern",agent:C("Which current project files match this path pattern?","matching file paths",["pattern"],"complete"),docs:R("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>sr(e,M(t,0)),format:e=>e.relativePath}),xt({id:"inspect",command:"inspect",description:"Batch related searches, symbols, and source locations into one deduplicated source packet",options:[u("--search <text>","Find this literal text; repeat for related anchors",U,[]),u("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",U,[]),u("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",U,[]),u("-s, --scope <path>","Limit literal searches to indexed paths matching this text"),u("-C, --context <n>","Fallback lines around a match with no syntax unit",ze,6),u("-n, --limit <n>","Set matching lines materialized per search (default 12)",pe),u("--max-units <n>","Set the ranked packet unit ceiling (default 48)",pe),u("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",pe),u("--view <view>","Render exact source, or raw/normalized behavior chosen by token cost with complete statement accounting (source or behavior; default source)"),u("--allow-large-source",`Explicitly allow an exact-source packet above the ${2e4}-character safety ceiling`),u("--allow-large-behavior",`Explicitly allow a behavioral construct above the ${2e4}-character focus ceiling`),u("--unit-lines <n>","Deprecated compatibility option; inspect now returns complete syntax units",pe),u("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",pe),u("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",U,[]),u("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",U,[]),u("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...st("Which related source units across several known text, symbol, or location anchors should be read together?","one ranked, deduplicated semantic packet plus exact selector cardinality and explicit expansion coverage",[],"bounded","repository",ye,Mi(["behavior","construct","exact-source"],["A source packet does not choose which implementation details are relevant to the user task.","A reference mention does not establish executable reachability."],void 0,{manualInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit."})),contrasts:[{command:"code",distinction:"inspect batches bounded behavior or source gaps; code materializes complete exact source."},{command:"evidence",distinction:"inspect reads implementation units; evidence projects typed relationships without source."}]},docs:R("Navigation",["scip-query inspect --search sessionStreamEvents --search work_session_stream_events --search 'agent:work_session' --view behavior","scip-query inspect --symbol appendEvent --symbol publishEvent --include definition,references,callers,callees","scip-query inspect --at src/api.ts:42 --at src/web.tsx:90"]),query:({db:e,opts:t,budget:n})=>{Li(e.config.projectRoot,"inspect",t.session!==!1);let i=b(t,"full"),o=jr(e,{searches:O(t,"search"),symbols:O(t,"symbol"),locations:O(t,"at"),scope:w(t,"scope"),context:k(t,"context",6),searchLimit:pS(t),maxUnits:K(t,"maxUnits"),maxCharacters:K(t,"maxCharacters"),view:mS(t),full:i,unitLines:K(t,"unitLines"),totalLines:K(t,"totalLines"),evidence:{parts:ko(O(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:vS(O(t,"evidenceBudget"))});return PS(o,t),AS(o,t),o},coverage:(e,{budget:t})=>{let n=e.searches.reduce((o,r)=>o+r.omittedMatches,0),i=e.units?.length??e.slices.length;return t.analysisBudget||n>0||(e.omittedUnits??0)>0?{complete:!1,totalKnown:!1,returned:i}:{complete:!0,totalKnown:!0,returned:i,total:i,omitted:0}},agentResult:e=>({searches:e.searches,evidence:e.evidence.map(t=>({query:t.query,kind:t.kind})),locations:e.locations,returnedUnits:e.units?.length??e.slices.length,candidateUnits:e.candidateUnits??e.candidateSlices,omittedUnits:e.omittedUnits??e.omittedSlices,view:e.view,omissionGroups:e.omissionGroups,causalFrontier:e.causalFrontier,packetCoverage:e.packetCoverage,stoppingSummary:e.stoppingSummary}),sections:LS}),uu({id:"search",command:"search <exact-text>",description:"Count current project text matches and preview a bounded, recoverable identity and source manifest",options:[u("-s, --scope <path>","Limit the search to current project paths matching this text"),u("-C, --context <n>","Source lines before and after each representative match",ze,2),u("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",pe,6),u("--full","Materialize source for every match after deliberately narrowing broad selectors"),u("--regexp","Treat the search text as a bounded regular expression"),u("-i, --ignore-case","Ignore case")],agent:{...st("Where does this exact text occur in current project text, and which aligned compiler symbol owns each line?","exact cardinality, bounded identities and source, and scope commands that recover withheld matches",["pattern"],"bounded",void 0,ye,Pt(["text","symbol","construct","runtime-key"],["Structural source ranking orders exact matches but does not establish task relevance.","A literal co-occurrence does not establish a graph relationship."],{ranking:"identity-only",manualInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned."})),contrasts:[{command:"outline",distinction:"search locates exact text across files; outline enumerates compiler-owned constructs in one known file."}]},docs:R("Navigation",["scip-query search 'eventName'","scip-query search -- '--config'","scip-query search 'send.*event' --regexp --scope src"]),query:({db:e,args:t,opts:n})=>ar(e,M(t,0),Rp(n)),precomputed:({args:e,opts:t})=>vp(ue(),M(e,0),Rp(t)),emptyMessage:e=>e.matchingLines===0?`${To(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=jp(e).length;return To(e)?{complete:!0,totalKnown:!0,returned:t,total:e.matchingLines,omitted:0}:{complete:!1,totalKnown:!1,returned:t}},agentResult:e=>({identityCoverage:e.identityCoverage,mode:e.mode,scannedFiles:e.scannedFiles,returnedMatches:li(e).length,totalMatches:e.matchingLines,omittedMatches:Lp(e,li(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:li(e).map(t=>`${t.relativePath}:${j(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:SS}),mo({id:"anchors",command:"anchors <question>",hidden:!0,description:"Deprecated compatibility view for query-vocabulary candidate groups; use exact locators plus evidence",options:[u("-s, --scope <path>","Limit candidate ownership and text evidence to indexed paths matching this text"),u("-n, --limit <n>","Connected anchor sets to return; omitted candidates remain counted",pe,4),u("--full","Analyze every candidate anchor group with semantic enrichment")],agent:st("Which small graph-connected code regions contain repository vocabulary from this question?","ranked candidate owners, two-hop compiler call evidence, exact map commands, and an omission ledger",["pattern"],"bounded",void 0,ye,Pt(["text","symbol","construct"],["Connected candidate groups are compatibility navigation hints, not inferred task relevance.","Candidate grouping does not establish implementation behavior."],{ranking:"identity-only",compatibility:"deprecated"})),docs:R("Compatibility"),query:({db:e,args:t,opts:n})=>{let i=Tr(e,M(t,0),{scope:w(n,"scope"),limit:D(n,"limit",4),full:b(n,"full"),semantic:b(n,"full")});return Fa(e.config.projectRoot,i.groups.map(o=>o.systemMapCommand),n.session!==!1),i},emptyMessage:e=>e.candidateRootCount===0?`No compiler-owned repository construct matched the normalized terms: ${e.normalizedTerms.join(", ")}.`:void 0,coverage:e=>e.omittedRootCount===0&&e.omittedGroupCount===0?{complete:!0,totalKnown:!0,returned:e.candidateRootCount,total:e.candidateRootCount,omitted:0}:{complete:!1,totalKnown:!0,returned:e.analyzedRootCount,total:e.candidateRootCount,omitted:e.omittedRootCount},agentResult:e=>({normalizedTerms:e.normalizedTerms,matchedTerms:e.matchedTerms,unmatchedTerms:e.unmatchedTerms,candidateRoots:e.candidateRootCount,analyzedRoots:e.analyzedRootCount,omittedRoots:e.omittedRootCount,omittedAnchorSets:e.omittedGroupCount,anchorSets:e.groups.map(t=>({roots:t.roots.map(n=>({symbol:n.symbol,file:n.file,line:j(n.line),matchedTerms:n.matchedTerms})),keyAnchors:t.keyAnchors.map(n=>({file:n.file,line:j(n.line)})),relations:t.relations,systemMapCommand:t.systemMapCommand})),recoveryCommand:e.recoveryCommand}),sections:CS}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:x(),agent:{...C("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:R("Navigation"),renderShape:"list",handler:JS},xt({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[u("--full","Run unbounded semantic analysis on large indexes"),ji()],budget:"semantic",agent:{operation:ye,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",semantic:Zt("Resolve one symbol definition and its indexed reference sites.","Definition source and signatures plus referencing files and line numbers.",["Flat reference sites do not establish runtime calls, data flow, or task relevance."]),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:R("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Pr(e,M(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?me(t,M(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>de(t,M(n,0)),toJson:(e,{db:t,args:n})=>({...en(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:hS}),xt({id:"evidence",command:"evidence",description:"Traverse selected typed relationships around exact referents; recover source separately when needed",options:[u("--symbol <symbol>","Add an exact compiler symbol; repeat to batch",U,[]),u("--at <file:line>","Add the construct owning an exact source location; repeat to batch",U,[]),u("--search <literal>","Add an exact source or runtime literal; repeat to batch",U,[]),u("--view <view>","Select causal, structure, or complete graph evidence"),u("--edge <family>","Select execution, runtime, dataflow, state, temporal, contract, identity, ownership, dependencies, or all; repeat or comma-separate",U,[]),u("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),u("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",U,[]),u("--connecting","Return deterministic shortest paths connecting the resolved roots"),u("--inventory-only","Count relationships by family, subtype, and direction without rendering edges"),u("--fold <id>","Materialize an exact recoverable fold from the same projection; repeat to batch",U,[]),u("--depth <n>","Required maximum graph traversal depth",ze),u("--max-edges <n>","Required maximum typed relationships to render",pe),{...u("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",U,[]),hidden:!0},u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ye,answers:["Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents?","Which related source must be read only when graph evidence leaves a named implementation gap?"],returns:["batched exact selectors and typed graph relationships","compact endpoints with exact locations and follow-up commands","coverage and recoverable omissions","exact source-recovery command when source was requested with a graph projection","explicit ambiguity failure with exact rerun commands"],inputs:[],scope:"repository",coverage:"bounded",semantic:Xt({rootKinds:["text","symbol","construct","runtime-key","state-resource"],edgeFamilies:ot,directions:["incoming","outgoing","both"],operations:["adjacency","reachability","connecting","slice"],compression:["none","linear","scc","topology"],nonClaims:["The projection does not infer which relationships are relevant to the user task.","Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims."],manualInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage."}),contrasts:[{command:"refs",distinction:"refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships."},{command:"call-graph",distinction:"call-graph specializes in static calls; evidence can combine execution with other selected families."},{command:"value-flow",distinction:"value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families."},{command:"dependence-slice",distinction:"dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."}]},docs:R("Navigation",["scip-query evidence --symbol 'exact-symbol' --edge execution --edge dataflow --direction both --depth 2 --max-edges 32","scip-query evidence --symbol 'first' --symbol 'second' --edge runtime --direction both --depth 3 --max-edges 32 --connecting","scip-query evidence --at 'src/file.ts:40' --edge runtime --edge state --edge contract --direction outgoing --depth 2 --inventory-only"]),query:({db:e,opts:t})=>{let n=O(t,"symbol"),i=O(t,"at"),o=O(t,"search"),r=gS(w(t,"view")),s=fS(O(t,"edge")),a=yS(w(t,"direction")),c=bS(O(t,"subtype")),l=b(t,"connecting"),d=b(t,"inventoryOnly"),m=O(t,"fold"),h=K(t,"depth"),p=K(t,"maxEdges");if(s===void 0)throw new Error("Graph evidence requires at least one explicit --edge <family>; repeat --edge to select several relationship families.");if(a===void 0)throw new Error("Graph evidence requires explicit --direction incoming, outgoing, or both.");if(h===void 0)throw new Error("Graph evidence requires an explicit finite --depth <n>.");if(!d&&p===void 0)throw new Error("Materialized graph evidence requires an explicit finite --max-edges <n>.");let f=ko(O(t,"include")),g=[...n,...i],y=f===void 0?null:{parts:f,selectors:g.length,command:["scip-query inspect",...n.map(v=>`--symbol ${Le(v)}`),...i.map(v=>`--at ${Le(v)}`),"--view source",`--include ${Le(f.join(","))}`].join(" ")};return{kind:"graph-packet",graph:qr(e,{symbols:n,locations:i,searches:o},{view:r,families:s,direction:a,subtypes:c,connecting:l,inventoryOnly:d,foldIds:m,maxDepth:h,maxEdges:p??1}),source:[],sourceRecovery:y}},before:e=>{e.graph.targets.some(t=>t.status!=="matched")&&(process.exitCode=1)},coverage:e=>{let t=e.graph.edges.length,n=e.graph.targets.every(r=>r.status==="matched"),i=e.sourceRecovery!==null;return e.graph.coverage.status==="accounted"&&n&&!i?{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}:e.graph.coverage.status==="incomplete"||!n||i?{complete:!1,totalKnown:!1,returned:t}:{complete:!1,totalKnown:!0,returned:t,total:t+e.graph.coverage.omittedEdges,omitted:e.graph.coverage.omittedEdges}},agentResult:e=>({view:e.graph.view,families:e.graph.families,selection:e.graph.selection,targets:e.graph.targets,inventory:e.graph.inventory,relationshipCount:e.graph.edges.length,coverage:e.graph.coverage,sourceSelectors:e.source.length,sourceRecovery:e.sourceRecovery}),sections:WS}),xt({id:"evidence-source",command:"evidence-source <symbol>",description:"Deprecated compatibility path for positional source evidence; use inspect or code",hidden:!0,options:[u("--include <part>","Source parts to include",U,[]),u("-C, --context <n>","Source lines before and after each reference",ze,2),u("--related-source-lines <n>","Maximum source lines for each caller or callee",pe,80),u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ye,answers:["Which legacy definition, reference, caller, callee, dependency, and consumer source surrounds this symbol?"],returns:["deprecated qualified source-evidence packet"],inputs:["symbol"],coverage:"bounded",semantic:Mi(["construct","exact-source"],["This compatibility read does not establish graph reachability beyond its rendered evidence."],"deprecated")},docs:R("Compatibility"),query:({db:e,args:t,opts:n,budget:i})=>(Li(e.config.projectRoot,"evidence",n.session!==!1),Lr(e,M(t,0),{parts:ko(O(n,"include")),referenceContext:k(n,"context",2),relatedSourceLines:k(n,"relatedSourceLines",80),semantic:i.semantic})),emptyMessage:e=>Np(e),before:e=>{e.kind!=="matched"&&(process.exitCode=1)},coverage:(e,{budget:t})=>{if(e.kind!=="matched")return{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0};let n=(e.definition?1:0)+e.referenceWindows.reduce((i,o)=>i+o.references.length,0)+e.callers.length+e.callees.length+e.dependencies.length+e.consumers.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>e.kind==="matched"?{symbol:e.symbol,file:e.file,parts:e.parts,referenceSites:e.referenceWindows.reduce((t,n)=>t+n.references.length,0),sourceWindows:e.referenceWindows.length,callers:e.callers.length,callees:e.callees.length,dependencies:e.dependencies.length,consumers:e.consumers.length}:e,sections:Io}),lt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:C("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Ir(e,M(t,0)),format:e=>e.relativePath}),lt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:C("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Ar(e,M(t,0)),format:e=>e.relativePath}),mo({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[ji()],agent:{operation:ye,answers:["Which files and documented symbols match this module selector?","What one-hop file reference dependencies cross the selected module?"],returns:["module file paths","documented indexed symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",semantic:Zt("Summarize files, documented symbols, and one-hop file reference dependencies for a module selector.","Matched files, documented indexed symbols, dependencies, and reverse dependencies.",["A one-hop module summary does not establish runtime execution or complete transitive behavior."]),contrasts:[{command:"surface",distinction:"system lists documented indexed symbols; surface lists callable symbols that external consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:R("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Fr(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 documented indexed symbols with their line ranges"}}),sections:e=>[{title:"FILES",rows:e.files},{title:"DOCUMENTED INDEXED SYMBOLS",rows:e.symbols.map(t=>` ${ge(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}`)}]}),lt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:C("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Wr(e,M(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:C("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Navigation"),handler:GS},lt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:C("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Vr(e,M(t,0)),format:e=>` ${e.fromFile}`}),lt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:C("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Hr(e,M(t,0)),format:e=>` ${ge(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>de(t,M(n,0)),emptyMessage:({db:e,args:t})=>me(e,M(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Ae(t,M(n,0),e,"members")}),lt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:C("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,100),u("--full","Run unbounded analysis on large indexes")],docs:R("Navigation"),query:({db:e,args:t,opts:n})=>ns(e,M(t,0),{scope:w(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${V(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(`
|
|
276
|
-
${e.length} symbol(s)`)}),ei({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:C("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[u("-s, --scope <path>","Limit to files matching path")],docs:R("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>is(e,{scope:w(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),lt({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:C("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>rs(e,M(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>de(t,M(n,0)),emptyMessage:({db:e,args:t})=>me(e,M(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Ae(t,M(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",hidden:!0,description:"Deprecated compatibility alias for a reference/call neighborhood; use value-flow",agent:C("What definitions, references, incoming calls, and outgoing calls surround this symbol?","legacy reference sites and call-neighborhood rows; no value-flow claim",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:VS},{id:"reference-neighborhood",command:"reference-neighborhood <symbol>",description:"Show definition/reference sites and incoming/outgoing static calls without value-flow claims",agent:C("What exact references and static calls surround this symbol?","definition sites, reference sites, incoming calls, and outgoing calls",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:US},{id:"value-flow",command:"value-flow <symbol>",description:"Show only proved argument/parameter and bounded static-value transfers around a symbol",agent:C("Which values are proved to flow into or through this symbol?","typed value-transfer edges with evidence strength and explicit unsupported relations",["symbol"],"bounded"),options:x([u("--depth <n>","Maximum graph depth",S,2),u("--max-edges <n>","Maximum typed value-transfer edges",S,48)]),renderShape:"custom",docs:R("Navigation"),handler:HS},{id:"slice",command:"slice <symbol>",hidden:!0,description:"Deprecated compatibility alias for reference/call reachability; use dependence-slice",agent:C("Which calls or reference owners are reachable from this symbol under the legacy traversal?","legacy connected symbols; no program-dependence claim",["symbol"],"bounded"),options:x([u("--forward","Forward slice (what does this affect). Default is backward."),u("--depth <n>","Max transitive depth for backward slice",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:QS},{id:"reference-reachability",command:"reference-reachability <symbol>",description:"Traverse legacy callee or reference-owner reachability without calling it a program slice",agent:C("Which call/reference nodes are reachable from this symbol?","connected symbols with relationship and traversal depth",["symbol"],"bounded"),options:x([u("--forward","Traverse reference owners. Default traverses callees."),u("--depth <n>","Maximum callee depth",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:KS},{id:"dependence-slice",command:"dependence-slice <symbol-or-location>",description:"Directional slice over proved data/control dependencies with explicit supporting call edges",agent:C("What proved program dependencies can affect this criterion, or be affected by it?","directional dependence edges, supporting connectors, and coverage limits",[["symbol","path"]],"bounded"),options:x([u("--forward","Compute a forward slice. Default is backward."),u("--depth <n>","Maximum dependence traversal depth",S,3),u("--max-edges <n>","Maximum topology edges considered",S,200)]),renderShape:"custom",docs:R("Navigation"),handler:zS}];var ZS=te("context",({db:e,args:t,opts:n,budget:i})=>{let o=D(n,"limit",20),r=qe(e.config.projectRoot).gitContext?.headCommit,s=Gs(e,M(t,0),{semantic:i.semantic,impactDepth:k(n,"impactDepth",3),sliceDepth:k(n,"sliceDepth",3),scope:w(n,"scope"),...r?{gitHead:r}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){P("context",t,n,{...en(e,M(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:Fp(s),agentResult:Wp(s)});return}return A.empty(me(e,M(t,0)))}if(b(n,"json")){let c=s.primaryCallable?.symbol??M(t,0);P("context",t,n,s.matched.symbol?{...en(e,c),...s}:s,{analysisBudget:i.analysisBudget,coverage:Fp(s),agentResult:Wp(s)});return}s.matched.symbol&&de(e,s.primaryCallable?.symbol??M(t,0));let a=b(n,"detail")?tw(s,o):ew(s,M(t,0),o,k(n,"impactDepth",3),k(n,"sliceDepth",3));A.sectionedReport(a)}),_p=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:_a([u("--impact-depth <n>","Maximum affected traversal depth",S,3),u("--slice-depth <n>","Maximum backward slice depth",S,3),u("-s, --scope <path>","Limit downstream impact to files matching path"),u("-n, --limit <n>","Rows per section",S,20),u("--detail","Render every planning component instead of the compact decision packet"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",claims:Je(["index-generation","live-workspace"],[X("compiler-graph","trace","compiler-graph"),X("semantic-flow","dataflow","semantic-analysis"),X("change-history","history","change-history"),X("planning-notes","warnings[]","heuristic")]),agent:{operation:ye,answers:["How is this target connected to the rest of the repository?","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","reuse candidates with evidence class and action tier","possible shared owners found from a bounded scan of affected consumers"],inputs:[["symbol","file","module"]],coverage:"bounded",semantic:Zt("Assemble bounded compiler, semantic, history, and heuristic context around one explicit target.","A multi-section repository context report with each evidence family kept distinct.",["This composite report does not infer task relevance or prove that every returned candidate affects the requested change."]),contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; context includes flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:R("Exploration",["scip-query context parseSymbol"]),handler:ZS}];function ew(e,t,n,i,o){return[{title:"TARGET",rows:Gp(e)},{title:"CURRENT FLOW",rows:nw(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:iw(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Bp(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:ow(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:rw(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Vp(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:sw(e,t,i,o)}]}function tw(e,t){return[{title:"TARGET",rows:Gp(e)},{title:"DEFINITIONS",rows:Up(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:lw(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Hp(e,t),skipIfEmpty:!0},{title:"DATAFLOW",rows:Qp(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Bp(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Vp(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:dw(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:uw(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:pw(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:mw(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:Kp(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:zp(e),skipIfEmpty:!0}]}function nw(e,t){return De(je([...Up(e,Math.min(t,12)),...Hp(e,t),...Qp(e,t)],t))}function iw(e,t){let n=e.trace.referencedBy.map(o=>` direct ${o.relativePath}:${j(o.line)} ${o.enclosingShort}`),i=e.affected.map(o=>` depth ${o.depth} ${o.file} ${o.shortName}`);return De(je(aw([...n,...i]),t))}function ow(e,t){let n=[...e.changeSurface?[` External consumers: ${e.changeSurface.totalExternalConsumers}`,` Changed-file risk factors: ${e.changeSurface.fileRisk?.reasons.length??0}`]:[],` Dependencies: ${e.deps.length}; reverse dependencies: ${e.rdeps.length}`,` Module files: ${e.system.files.length}; exported symbols: ${e.system.symbols.length}; external surface uses: ${e.surface.length}`,...Kp(e),...zp(e)];return De(je(n,t))}function rw(e,t){let n=[...e.trace.definitions.map(i=>i.relativePath),...e.trace.referencedBy.map(i=>i.relativePath),...e.callGraph?.callers.map(i=>i.file)??[],...e.callGraph?.callees.map(i=>i.file)??[],...e.reuseCandidates?.map(i=>i.fileB)??[],...Ft(e).candidates.map(({candidate:i})=>i.fileB)];return De(je([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function sw(e,t,n,i){let o=Ft(e).coverage,r=[` Direct compiler references observed: ${e.trace.referencedBy.length}.`,` Downstream and slice evidence is bounded at impact depth ${n} and slice depth ${i}.`,` Affected-consumer reuse scan: ${o.analyzedConsumers}/${o.totalConsumers} analyzed; ${o.omittedConsumers} omitted.`];return e.sourcePacket&&(r.push(` Source packet: ${e.sourcePacket.slices.length}/${e.sourcePacket.candidateSlices} slice(s); ${e.sourcePacket.omittedSlices} omitted; at most ${e.sourcePacket.maxSlices} slices, ${e.sourcePacket.maxLinesPerSlice} lines per slice, and ${e.sourcePacket.maxTotalLines} lines total.`),e.sourcePacket.targetLineLimit!==void 0&&e.sourcePacket.consumerContextLines!==void 0&&e.sourcePacket.reuseLineLimit!==void 0&&r.push(` Source roles: target up to ${e.sourcePacket.targetLineLimit} lines; consumer windows center on each use with ${e.sourcePacket.consumerContextLines} context lines; reuse candidates use up to ${e.sourcePacket.reuseLineLimit} lines.`)),e.warnings.length>0&&r.push(...e.warnings.map(s=>` Warning: ${s}`)),r.push(` Use scip-query refs ${t} --full only when a complete direct-consumer set can change the plan.`,` Use scip-query context ${t} --detail only when this packet leaves a named planning uncertainty.`),r}function aw(e){return[...new Set(e)]}function Fp(e){return{complete:!1,totalKnown:!1,returned:cw(e)}}function cw(e){let t=Ft(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+(e.reuseCandidates?.length??0)+t.coverage.analyzedConsumers+t.candidates.length+(e.sourcePacket?.slices.length??0)}function Wp(e){let t=Ft(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,reuseCandidates:e.reuseCandidates?.length??0,affectedConsumersAnalyzed:t.coverage.analyzedConsumers,consumerReuseCandidates:t.candidates.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length,sourceSlices:e.sourcePacket?.slices.length??0},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,fileRisk:e.changeSurface.fileRisk,riskCounts:{high:e.changeSurface.symbols.filter(n=>n.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(n=>n.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(n=>n.riskLevel==="low").length}}:null,history:e.history,affectedConsumerReuse:t}}function Bp(e,t){let n=(e.reuseCandidates??[]).flatMap(c=>[` target ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; ${c.evidenceClassReasons.join("; ")}`]),i=Ft(e),o=i.candidates.flatMap(({candidate:c,consumers:l})=>[` consumer ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; observed from ${l.map(d=>d.shortName).join(", ")}; ${c.evidenceClassReasons.join("; ")}`]),r=i.coverage,s=r.totalConsumers>0?[` Affected-consumer scan: ${r.analyzedConsumers}/${r.totalConsumers} compiler-resolved consumer(s) analyzed; ${r.omittedConsumers} omitted; first ${r.perConsumerSearchLimit} similarity result(s) checked and up to ${r.perConsumerCandidateLimit} usable option(s) kept per consumer.`]:[],a=[...n,...s,...o];return De(je(a,t))}function Gp(e){let t=[`Target: ${e.target}`,`Matched: symbol=${Po(e.matched.symbol)} file=${Po(e.matched.file)} module=${Po(e.matched.module)}`];return e.primaryCallable&&t.push(`Primary callable: ${e.primaryCallable.shortName} ${e.primaryCallable.file}`),t}function Vp(e){if(!e.sourcePacket||e.sourcePacket.slices.length===0)return[];let t=[];for(let n of e.sourcePacket.slices)t.push(` ${n.role.padEnd(15)} ${V(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
|
|
277
|
-
`).map((i,o)=>{let r=n.startLine+o;return` ${n.focusLines?.includes(r)?">":" "}${String(j(r)).padStart(4)} ${i}`})),n.omittedLines>0&&t.push(` ... ${n.omittedLines} more line(s) in this callable`);return e.sourcePacket.omittedSlices>0&&t.push(` ... ${e.sourcePacket.omittedSlices} more candidate slice(s)`),t}function Up(e,t){let n=[];for(let i of e.trace.definitions){let o=i.signature?` -- ${i.signature}`:"";n.push(` ${V(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&n.push(...i.source.split(`
|
|
278
|
-
`).map((r,s)=>` ${String(j(i.startLine+s)).padStart(4)} ${r}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${ge(i.startLine,i.endLine)} ${i.shortName}`)),je(n,t).rows}function lw(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${j(i.line)} in ${i.enclosingShort}`);return De(je(n,t))}function Hp(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(o=>` caller ${o.file} ${o.shortName}`),i=e.callGraph.callees.map(o=>` callee ${o.file} ${o.shortName}`);return De(je([...n,...i],t))}function Qp(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(r=>` producer ${r.file} ${r.shortName}`),i=e.dataflow.consumers.map(r=>` consumer ${r.file} ${r.shortName}`),o=e.dataflow.usageSites.map(r=>` usage ${r.file}:${j(r.line)} in ${r.enclosingShort}`);return De(je([...n,...i,...o],t))}function dw(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return De(je(n,t))}function uw(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${ge(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return De(je(n,t))}function pw(e,t){let n=[],i=-1;for(let o of e.affected)o.depth!==i&&(n.push(` -- Depth ${o.depth} --`),i=o.depth),n.push(` ${o.file} ${o.shortName}`);return De(je(n,t))}function mw(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(i=>`${i.kind}: ${i.detail}`).join("; ")}`),n.push(...e.changeSurface.symbols.map(i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"",r=i.riskReasons??[],s=r.length===0?"":` [why: ${r.map(a=>`${a.kind}: ${a.detail}`).join("; ")}]`;return` ${ge(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}${s}`}))),e.complexity&&(n.push(` Complexity: ${V(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}`)),De(je(n,t))}function Kp(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function zp(e){let t=e.warnings.map(i=>` ${i}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(i=>i.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.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."),e.reuseCandidates?.some(i=>i.actionTier==="direct")&&t.push(" A direct reuse option requires a responsibility and behavior comparison. Reuse the existing owner when they match. Current wiring or reachability alone does not justify separate ownership; rejection needs a concrete behavioral or boundary difference."),Ft(e).candidates.length>0&&t.push(" An affected-consumer reuse option can own surrounding behavior that target-only comparison cannot see. Compare each direct option before editing, and keep duplicate ownership only for a concrete behavioral or boundary difference."),t}function Ft(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function je(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function De(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Po(e){return e?"yes":"no"}import{existsSync as fn}from"fs";import{existsSync as hw,mkdtempSync as fw,rmSync as gw}from"fs";import{tmpdir as yw}from"os";import{dirname as Lo,join as bw}from"path";import{performance as Jp}from"perf_hooks";import{spawnSync as vw}from"child_process";var Sw=12e4,Zp="v1.8.0",ww=`https://github.com/tlaplus/tlaplus/releases/download/${Zp}/tla2tools.jar`,$w="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function ui(e){let t=e.spawn??vw,n=Rw(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 i=e.timeoutMs??Sw,o=Jp.now(),r;try{r=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:i,killSignal:"SIGKILL",maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])gw(l,{recursive:!0,force:!0})}let s=Math.round(Jp.now()-o),a=r.error?.name==="ETIMEDOUT"||r.signal==="SIGTERM"&&s>=i,c=a?"timed-out":r.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:r.status,signal:r.signal,timedOut:a,diagnostics:xw(c,r.stdout??"",r.stderr??""),stdout:r.stdout??"",stderr:r.stderr??""}}function Rw(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"&&it(Yp(e),t)){let r=Yp(e);return it(r,t)?{checker:"apalache",command:[r,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Lo(e.specPath)}:di("apalache",`Apalache binary is not available: ${r}`)}let i=jo(e),o=it("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return di(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!o)return di(n==="sany"?"sany":"tlc","java is not available on PATH");let r=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(r==="sany")return{checker:r,command:["java","-cp",i,"tla2sany.SANY",e.specPath],cwd:Lo(e.specPath)};let s=e.metaDir??fw(bw(yw(),"scip-tla-tlc-"));return{checker:r,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Lo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return di("none",`unknown checker mode: ${n}`)}function Yp(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function jo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,em(t)].filter(i=>typeof i=="string"&&i.length>0).find(i=>hw(i))??null}function em(e=process.env){return Za("tla2tools.jar",e)}async function tm(e={}){let t=e.cachePath??em(e.env),n=e.expectedSha256??$w,i=e.version??Zp,o=e.url??ww;return{...await ec({cachePath:t,url:o,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:i,url:o}}function xw(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 i=[...Xp(n),...Xp(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(o=>({severity:"error",message:o}))}function Xp(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function di(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Cw}from"crypto";var im=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),om=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),rm=new Set(["readFileSync","existsSync","statSync"]),kw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Ew=/^\s*SELECT\b/i;function sm(e){return kw.test(e)?"write":Ew.test(e)?"read":null}var Tw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Iw(e,t){let n=e.match(Tw);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${wt(t)}\\b`).test(i)}function am(e,t,n,i=[],o=[]){let r=[],s=Lw(e,t,r),a=s.aliases,c=jw(t),l=Mw(t),d=Nw(t),m=qw(e,t,r),h=Ww(e,t,r);n&&_w(t,n,o,r);let p=new Map((n?.actions??[]).map($=>[$.name,$])),f=new Set(m.flatMap($=>$.referents.map(L=>L.match?.symbol).filter(Boolean))),g=new Set((h?.referents??[]).map($=>$.match?.symbol).filter(Boolean)),y=Bw(e,t,m,a,c,l,d,f,g,r,p),v=Uw(e,m,a,c,l,d,r,p);return Qw(e,m,r),Kw(t,i,r),{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:No(m.flatMap($=>$.referents))+No(s.referents)+No(h?.referents??[]),staticWrites:y,staticReads:v,waivers:h$(t),checkedInvariants:[...o],traceStepsChecked:i.length,findings:r,findingGroups:Aw(r)}}function Aw(e){let t=new Map;for(let n of e){let i=`${n.category}:${n.modelElement??"-"}`,o=t.get(i);o||(o={groupKey:i,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(i,o)),o.count+=1,o.findingIds.push(n.id),o.severity=Pw(o.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||pi(i.severity)-pi(n.severity)||n.groupKey.localeCompare(i.groupKey))}function Pw(e,t){return pi(t)>pi(e)?t:e}function pi(e){return e==="error"?2:e==="warning"?1:0}function Lw(e,t,n){let i=[],o=[];for(let[r,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=fi(e,l,n,r);o.push(d);let m=d.match;if(!m){c||n.push(Q("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:l,message:`TLA+ variable ${r} 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.${r}.code to a live symbol, or remove the variable from the model mapping.`}));continue}c$(e,r,l,m,n,c),s.aliases.length===0&&a.add(rr(m.symbol))}for(let l of a)i.push({variable:r,alias:l})}return{aliases:m$(i),referents:o}}function jw(e){let t=[];for(let[n,i]of Object.entries(e.variables))i.resource&&t.push({variable:n,path:i.resource.path});return t}function Mw(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.statements??[])t.push({variable:n,pattern:o.pattern,regex:yn(o.pattern,`variables.${n}.statements pattern`)});return t}function Nw(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.ormCalls??[]){let{write:r,read:s}=go(o);t.push({variable:n,table:o.table,writeMethods:new Set(r),readMethods:new Set(s)})}return t}function Ow(e,t,n,i,o,r){return cm(e,t,(s,a,c)=>kt(e,s,a,c,n,i,o,r))}function Dw(e,t,n,i,o,r){return cm(e,t,(s,a,c)=>hi(e,s,a,c,n,i,o,r))}function cm(e,t,n){let i=Ht(e,t,{semantic:!1});if(!i)return[];let o=[],r=new Set;for(let s of i.callees){if(r.has(s.symbol))continue;r.add(s.symbol);let a=wn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))o.push({...c,via:s.shortName})}return o}function qw(e,t,n){return Object.entries(t.actions).map(([i,o])=>{let r=o.code.map(s=>{let a=yo(s),c="error"in a?s:a.ref,d=fi(e,c,n,i).match;return d?(l$(e,i,s,d,n),"error"in a||!a.window?{ref:s,match:d}:Fw(a.window,d)?(n.push(Q("invalid-line-window","error","compiler-symbol",{modelElement:i,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${i} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${oe(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${oe(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.${i}.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(Q("missing-referent","error","compiler-symbol",{modelElement:i,codeRef:s,message:`TLA+ action ${i} 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.${i}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:i,mapping:o,referents:r}})}function Fw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Ww(e,t,n){let i=t.init;if(!i)return;let o=!!i.waive,r=i.codeRefs.map(s=>{let a=fi(e,s,n,"Init"),c=a.match;return c?d$(e,s,c,n,o):o||n.push(Q("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:i,referents:r}}function _w(e,t,n,i){let o=new Set(t.variables),r=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))o.has(a)||i.push(Q("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))r.has(a)||i.push(Q("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(nm({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:i,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),nm({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:i,file:t.path}))}for(let a of e.invariants)s.has(a)||i.push(Q("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function nm(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),i=e.isWaived??(()=>!1);for(let o of t)n.has(o)||i(o)||e.findings.push(Q(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"} ${o}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${o} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${o} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let o of n)t.has(o)||i(o)||e.findings.push(Q(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${o}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${o}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Bw(e,t,n,i,o,r,s,a,c,l,d){let m=[];for(let p of n){let f=[];for(let g of p.referents){if(!g.match)continue;let y=g.window??{startLine:g.match.startLine,endLine:g.match.endLine},v=kt(e,g.match.relativePath,y.startLine,y.endLine,i,o,r,s);f.push(...v),m.push(...v);let $=new Set(p.mapping.writes),L=Ow(e,g.match.symbol,i,o,r,s).filter(_=>$.has(_.variable));f.push(...L),m.push(...L)}Vw(p,f,l,d.get(p.name))}let h=t.unmappedWriteScope==="actions"?[]:r$(e,t);for(let p of h)for(let f of kt(e,p,0,Number.POSITIVE_INFINITY,i,o,r,s))m.push(f),Gw(f)&&(f.enclosingSymbol&&(a.has(f.enclosingSymbol)||c.has(f.enclosingSymbol))||l.push(Q("unmapped-write","error","static-action",{modelElement:f.variable,codeRef:f.enclosingSymbol??`${f.file}:${f.line+1}`,file:f.file,startLine:f.line,endLine:f.line,message:`Modeled variable ${f.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${f.target} at ${f.file}:${f.line+1}.`,f.enclosingShort?`The write is inside ${f.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${f.variable} from the modeled slice if it is intentionally out of scope.`})));return qo(m)}function Gw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function Vw(e,t,n,i){let o=new Set(e.mapping.writes),r=new Set(t.map(a=>a.variable)),s=new Set(i?.writes??[]);for(let a of t)i&&!s.has(a.variable)&&!mn(e,"write",a.variable)&&n.push(Q("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}${mi(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${i.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.`})),!o.has(a.variable)&&!mn(e,"write",a.variable)&&n.push(Q("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}${mi(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 o)!r.has(a)&&!mn(e,"write",a)&&n.push(Q("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 Uw(e,t,n,i,o,r,s,a){let c=[];for(let l of t){let d=[];for(let m of l.referents){if(!m.match)continue;let h=m.window??{startLine:m.match.startLine,endLine:m.match.endLine},p=hi(e,m.match.relativePath,h.startLine,h.endLine,n,i,o,r);d.push(...p),c.push(...p);let f=new Set(l.mapping.reads),g=Dw(e,m.match.symbol,n,i,o,r).filter(y=>f.has(y.variable));d.push(...g),c.push(...g)}Hw(l,d,s,a.get(l.name))}return Fo(c)}function Hw(e,t,n,i){let o=new Set(e.mapping.reads),r=new Set(t.map(a=>a.variable)),s=new Set(i?.reads??[]);for(let a of t)i&&!s.has(a.variable)&&n.push(Q("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}${mi(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${i.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.`})),!o.has(a.variable)&&!mn(e,"read",a.variable)&&n.push(Q("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}${mi(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 o)!r.has(a)&&!mn(e,"read",a)&&n.push(Q("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 Qw(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let o=i.mapping.calls.map(s=>fi(e,s,n,i.name));for(let s of o)s.match||n.push(Q("missing-referent","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,message:`actions.${i.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.${i.name}.calls to a live symbol or remove the stale call expectation.`}));let r=new Set(o.map(s=>s.match?.symbol).filter(Boolean));for(let s of i.referents){if(!s.match)continue;let a=Ht(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of r)c.has(l)||n.push(Q("missing-call","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${i.name} no longer calls ${oe(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${i.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function Kw(e,t,n){for(let[i,o]of t.entries()){let r=e.actions[o.action];if(!r){n.push(Q("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} uses action ${o.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.${o.action} to the mapping, or fix the trace action name.`}));continue}let s=p$(o),a=new Set(r.writes);for(let c of s)a.has(c)||n.push(Q("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} changed ${c}, but action ${o.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${o.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function kt(e,t,n,i,o,r=[],s=[],a=[]){let c=zw(e,t,n,i,o,r,s,a);return c||i$(e,t,n,i,o,r,s,a)}function hi(e,t,n,i,o,r=[],s=[],a=[]){let c=Jw(e,t,n,i,o,r,s,a);return c||o$(e,t,n,i,o,r,s,a)}function zw(e,t,n,i,o,r=[],s=[],a=[]){let c=Si(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){Yw(e,t,m,o,l),lm(e,t,m,r,"write",l),dm(e,t,m,s,"write",l),um(e,t,m,a,"write",l);for(let h of m.children)d(h)}};return d(c.rootNode),qo(l)}function Jw(e,t,n,i,o,r=[],s=[],a=[]){let c=Si(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){e$(e,t,m,o,l),lm(e,t,m,r,"read",l),dm(e,t,m,s,"read",l),um(e,t,m,a,"read",l);for(let h of m.children)d(h)}};return d(c.rootNode),Fo(l)}function Yw(e,t,n,i,o){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let r=n.childForFieldName("left")??n.namedChild(0);r&&pn(e,t,r,"assignment",i,o);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let r=n.childForFieldName("key")??n.namedChild(0);r&&pn(e,t,r,"object-field",i,o);return}if(n.type==="update_expression"){let r=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);r&&pn(e,t,r,"update",i,o);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let r=n.namedChild(0);r&&pn(e,t,r,"delete",i,o);return}if(n.type==="call_expression"){let r=n.childForFieldName("function")??n.namedChild(0);if(!r||!mm(r))return;pn(e,t,r,"mutation-call",i,o)}}}function lm(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Oo(s):null;if(!a||!(o==="write"?om:rm).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let m=d.text;for(let h of i){if(!m.includes(h.path))continue;let p=Ze(e,t,n.startPosition.row);r.push({variable:h.variable,alias:h.path,file:t,line:n.startPosition.row,target:`${a}(${m})`,kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?oe(p.symbol):void 0})}}function Oo(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 dm(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=Xw(a);if(c!==null&&sm(c)===o)for(let l of i){if(!l.regex.test(c))continue;let d=Ze(e,t,n.startPosition.row),m=n.childForFieldName("function")??n.namedChild(0),h=(m&&Oo(m))??"call";r.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${h}(${Zw(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?oe(d.symbol):void 0})}}}function Xw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Zw(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function um(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Oo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let m of i){if(!pm(m,a,d,o))continue;let h=Ze(e,t,n.startPosition.row);r.push({variable:m.variable,alias:m.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:h?.symbol,enclosingShort:h?oe(h.symbol):void 0})}}function pm(e,t,n,i){return n!==e.table?!1:i==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function e$(e,t,n,i,o){if(!(!t$(n)||n$(n)))for(let r of i){if(n.text!==r.alias)continue;let s=Ze(e,t,n.startPosition.row);o.push({variable:r.variable,alias:r.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?oe(s.symbol):void 0})}}function t$(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function n$(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&&Mo(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&&Mo(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&mm(n)&&Mo(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 Mo(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function mm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&im.has(t.text))}function pn(e,t,n,i,o,r){for(let s of o){if(!u$(s.alias,n.text))continue;let a=Ze(e,t,n.startPosition.row);r.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:i,enclosingSymbol:a?.symbol,enclosingShort:a?oe(a.symbol):void 0})}}function i$(e,t,n,i,o,r=[],s=[],a=[]){let l=St(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let h=Math.max(0,n);h<=m;h+=1){let p=l[h]??"";for(let f of o){if(Iw(p,f.alias))continue;let g=wt(f.alias);if(!new RegExp(`(?:\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${g}\\b\\s*\\.\\s*(?:${[...im].join("|")})\\s*\\(|\\b${g}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(p))continue;let v=Ze(e,t,h);d.push({variable:f.variable,alias:f.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:v?.symbol,enclosingShort:v?oe(v.symbol):void 0})}hm(e,t,h,p,r,om,d),fm(e,t,h,p,s,"write",d),gm(e,t,h,p,a,"write",d)}return qo(d)}function o$(e,t,n,i,o,r=[],s=[],a=[]){let l=St(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let h=Math.max(0,n);h<=m;h+=1){let p=l[h]??"";for(let f of o){let g=wt(f.alias);if(!new RegExp(`\\b${g}\\b`).test(p)||new RegExp(`\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(p))continue;let y=Ze(e,t,h);d.push({variable:f.variable,alias:f.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?oe(y.symbol):void 0})}hm(e,t,h,p,r,rm,d),fm(e,t,h,p,s,"read",d),gm(e,t,h,p,a,"read",d)}return Fo(d)}function hm(e,t,n,i,o,r,s){if(o.length!==0)for(let a of r){let c=i.indexOf(`${a}(`);if(c===-1)continue;let l=i.slice(c+a.length);for(let d of o){if(!l.includes(d.path))continue;let m=Ze(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:i.trim(),kind:"resource",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function fm(e,t,n,i,o,r,s){if(o.length!==0&&sm(i)===r)for(let a of o){if(!a.regex.test(i))continue;let c=Ze(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:i.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?oe(c.symbol):void 0})}}function gm(e,t,n,i,o,r,s){if(o.length!==0)for(let a of i.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of o){if(!pm(d,c,l,r))continue;let m=Ze(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:i.trim(),kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function r$(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(o=>o.relative_path).filter(o=>n.some(r=>o.includes(r)))}function fi(e,t,n,i){let o=wn(e,t),r=o.match??(t.includes("#")?wn(e,t.replace("#","/")).match:null);return o.match&&o.total>1&&!s$(t)&&n.push(Q("ambiguous-referent","warning","compiler-symbol",{modelElement:i,codeRef:t,file:o.match.relativePath,startLine:o.match.startLine,endLine:o.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${oe(o.match.symbol)}.`,why:[`${o.total} indexed definitions share this lookup shape.`,a$(o.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:r}}function s$(e){return/[/#:]/.test(e)}function a$(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function c$(e,t,n,i,o,r=!1){let s=Do(e,i);if(s===null||f$.has(s)||r)return;let a=Wo.has(s);o.push(Q("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Ut(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${Ut(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function l$(e,t,n,i,o){let r=Do(e,i);r===null||ym.has(r)||Wo.has(r)&&o.push(Q("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${Ut(r)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function d$(e,t,n,i,o){let r=Do(e,n);r===null||ym.has(r)||o||Wo.has(r)&&i.push(Q("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 ${oe(n.symbol)} with SCIP kind ${Ut(r)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Do(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ze(e,t,n){return Sn(e,t).filter(o=>o.startLine<=n&&o.endLine>=n).sort((o,r)=>o.endLine-o.startLine-(r.endLine-r.startLine))[0]??null}function u$(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${wt(e)}([^A-Za-z0-9_$]|$)`).test(t)}function p$(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 qo(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function Fo(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function m$(e){let t=new Set;return e.filter(n=>{let i=`${n.variable}:${n.alias}`;return t.has(i)?!1:(t.add(i),!0)})}function No(e){return e.filter(t=>t.match).length}function mi(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function mn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function h$(e){let t=Object.entries(e.actions).flatMap(([r,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:r,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:r,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([r,s])=>{let a=s.waive;return a?[{kind:"referent",variable:r,reason:a.reason,legacy:!1}]:[]}),i=e.init?.waive,o=i?[{kind:"referent",variable:"Init",reason:i.reason,legacy:!1}]:[];return[...t,...n,...o]}var Wo=new Set(dr()),ym=new Set(lr()),f$=new Set(ur());function Q(e,t,n,i){let o=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${Cw("sha1").update(o).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{basename as g$,join as y$}from"path";var _o=/^[A-Za-z_][A-Za-z0-9_]*$/;function bm(e,t,n={}){let i=[],o=Sn(e,t,{includeClassMemberFallbacks:!0});if(o.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=St(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=E=>E.symbol.trimEnd().endsWith("()."),c=o.filter(E=>!a(E)&&!E.isTypeLike&&E.parentTypeName===null&&_o.test(E.leaf)),l=c.map(E=>({variable:E.leaf,alias:E.leaf})),d=l.length>0?kt(e,t,0,Number.POSITIVE_INFINITY,l):[],m=new Set(d.map(E=>E.variable)),h=c.filter(E=>m.has(E.leaf)?!0:S$(s,E)),p=null,f;if(h.length>0)f=o.filter(E=>a(E)&&E.parentTypeName===null);else{if(p=b$(e,t,o,a),!p){let E=o.some(B=>!a(B)&&!B.isTypeLike&&B.parentTypeName!==null&&_o.test(B.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 `+(E?"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.")}h=p.fields,f=p.methods,i.push(`state scoped to class ${p.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let g=h.map(E=>w$(E,s,t,i,p?.className)),y=g.map(E=>({variable:E.name,alias:E.leaf})),v=[],$=new Set;for(let E of f){let B=kt(e,t,E.startLine,E.endLine,y);if(B.length===0)continue;let J=hi(e,t,E.startLine,E.endLine,y),F=C$(vm(E.leaf),$);v.push({name:F,leaf:E.leaf,codeRef:v$(t,E,p?.className),startLine:E.startLine,writes:[...new Set(B.map(Y=>Y.variable))].sort(),reads:[...new Set(J.map(Y=>Y.variable))].sort()})}v.length===0&&i.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 L=n.moduleName??k$(t),_=n.specDir??y$("specs",L),I=E$(L,g,v,t),T=T$(),W=I$(L,_,t,g,v);return{moduleName:L,file:t,variables:g,actions:v,warnings:i,spec:I,cfg:T,map:W}}function b$(e,t,n,i){let o=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!_o.test(s.leaf))continue;let a=o.get(s.parentTypeName);a?a.push(s):o.set(s.parentTypeName,[s])}let r=null;for(let[s,a]of o){let c=n.filter(h=>i(h)&&h.parentTypeName===s),l=a.map(h=>({variable:h.leaf,alias:h.leaf})),d=new Set;for(let h of c)for(let p of kt(e,t,h.startLine,h.endLine,l))d.add(p.variable);let m=a.filter(h=>d.has(h.leaf));m.length!==0&&(!r||m.length>r.fields.length)&&(r={className:s,fields:m,methods:c})}return r}function v$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function S$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function w$(e,t,n,i,o){let r=$$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=R$(e.leaf,r);return a||i.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||i.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:o?`${n}/${o}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function $$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function R$(e,t){let i=t.match(new RegExp(`\\b${wt(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,r=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=x$(i);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(i)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(i)||/^(Array|ReadonlyArray)</.test(i))&&(a="sequence",s=null)}let c=null;if(r){let l=r.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(r)?c=r.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(r)?c=r.match(/^-?\d+/)[0]:/^\[\s*\]/.test(r)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function x$(e){let t=e.split("|").map(i=>i.trim());if(t.length<2)return null;let n=[];for(let i of t){let o=i.match(/^['"]([^'"]*)['"]$/);if(!o)return null;n.push(o[1])}return n}function vm(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function C$(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function k$(e){let n=g$(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return vm(n||"Model")}function E$(e,t,n,i){let o=t.map(s=>s.name),r=[];r.push(`---- MODULE ${e} ----`),r.push(`\\* Scaffolded by 'scip-query tla scaffold ${i}'.`),r.push("\\* Draft evidence tier: state from the static write scan, domains from"),r.push("\\* declared types, actions from top-level callables that write state."),r.push("\\* Review every TODO before trusting a green model-check run."),r.push("EXTENDS Naturals, Sequences, TLC"),r.push(""),r.push(`VARIABLES ${o.join(", ")}`),r.push(""),r.push(`vars == <<${o.join(", ")}>>`),r.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';r.push(`${s.name}Domain == ${a}`)}r.push(""),r.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;r.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}r.push("");for(let s of n){let a=o.filter(c=>!s.writes.includes(c));r.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),r.push(`${s.name} ==`),r.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(m=>m.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;r.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&r.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),r.push("")}if(r.push("Next =="),n.length===0)r.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())r.push(` \\/ ${a.name}`);r.push(""),r.push("Spec == Init /\\ [][Next]_vars"),r.push(""),r.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?r.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):r.push(` /\\ ${s.name} \\in ${s.name}Domain`);return r.push("===="),r.push(""),r.join(`
|
|
279
|
-
`)}function T$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
|
|
280
|
-
`)}function I$(e,t,n,i,o){let r={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(o.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(r,null,2)}
|
|
281
|
-
`}function Sm(e,t){let n=Object.keys(t.variables),i=Object.entries(t.actions).map(([o,r])=>{let s=r.code[0]??"",a=s?cr(e,s):null;return{action:o,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:r.writes}});return{recorderSource:A$(n),wiring:i,variables:n}}function A$(e){return`/**
|
|
282
|
-
* Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
|
|
283
|
-
*
|
|
284
|
-
* Usage inside a mapped action (record the model-visible slice around the
|
|
285
|
-
* mutation):
|
|
286
|
-
*
|
|
287
|
-
* import { tlaRecord } from './scip-tla-recorder.js';
|
|
288
|
-
* export function enqueue(job: string) {
|
|
289
|
-
* const before = snapshot();
|
|
290
|
-
* queue.push(job);
|
|
291
|
-
* tlaRecord('Enqueue', before, snapshot());
|
|
292
|
-
* }
|
|
293
|
-
*
|
|
294
|
-
* where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
|
|
295
|
-
* each field with the real runtime value, e.g.
|
|
296
|
-
* const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
|
|
297
|
-
*
|
|
298
|
-
* Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
|
|
299
|
-
* wiring is safe to leave in place. The output is a JSON array compatible
|
|
300
|
-
* with 'scip-query tla trace-check --trace <path>'.
|
|
301
|
-
*/
|
|
302
|
-
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
303
|
-
|
|
304
|
-
interface TlaTraceStep {
|
|
305
|
-
action: string;
|
|
306
|
-
before: Record<string, unknown>;
|
|
307
|
-
after: Record<string, unknown>;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const tracePath = process.env['SCIP_TLA_TRACE'];
|
|
311
|
-
const TRACE_MAX_BYTES = 16 * 1024 * 1024;
|
|
312
|
-
const TRACE_MAX_STEPS = 100_000;
|
|
313
|
-
|
|
314
|
-
export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
|
|
315
|
-
if (!tracePath) return;
|
|
316
|
-
let steps: TlaTraceStep[] = [];
|
|
317
|
-
try {
|
|
318
|
-
const size = statSync(tracePath).size;
|
|
319
|
-
if (size > TRACE_MAX_BYTES) throw new Error(\`TLA trace exceeds \${TRACE_MAX_BYTES} bytes\`);
|
|
320
|
-
steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
|
|
321
|
-
if (!Array.isArray(steps)) steps = [];
|
|
322
|
-
} catch (error) {
|
|
323
|
-
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
324
|
-
}
|
|
325
|
-
if (steps.length >= TRACE_MAX_STEPS) throw new Error(\`TLA trace exceeds \${TRACE_MAX_STEPS} steps\`);
|
|
326
|
-
steps.push({ action, before, after });
|
|
327
|
-
const payload = JSON.stringify(steps, null, 2);
|
|
328
|
-
const payloadBytes = Buffer.byteLength(payload);
|
|
329
|
-
if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
|
|
330
|
-
writeFileSync(tracePath, payload);
|
|
331
|
-
}
|
|
332
|
-
`}import{copyFileSync as P$,mkdtempSync as L$,readdirSync as j$,rmSync as M$,writeFileSync as wm}from"fs";import{tmpdir as N$}from"os";import{basename as O$,dirname as D$,join as hn}from"path";function gi(e,t){let n=new Map;for(let i of t)n.set(i.action,(n.get(i.action)??0)+1);return e.map(i=>({action:i,stepsObserved:n.get(i)??0}))}function q$(e,t,n,i="Next"){if(n.length===0)return{error:"trace has no steps"};let o=[],r=n[0];if(!r.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...r.before},c=g=>{let y={};for(let[v,$]of Object.entries(g)){if(!t.includes(v))continue;let L=W$($);L!==void 0&&(y[v]=L)}return y};s.push(c(a));for(let g of n){if(g.before)for(let[y,v]of Object.entries(g.before))y in a||(a[y]=v);Object.assign(a,g.after??{}),s.push(c(a))}let l=t.filter(g=>s.every(y=>g in y)),d=t.filter(g=>!l.includes(g));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&o.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let m=`${e}Trace`,h=s.map(g=>` [${l.map(y=>`${y} |-> ${Rm(g[y])}`).join(", ")}]`).join(`,
|
|
333
|
-
`),p=[`---- MODULE ${m} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${i}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",h,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(g=>` /\\ ${g} = TraceStates[1].${g}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${i}`,...l.map(g=>` /\\ ${g}' = TraceStates[traceIdx + 1].${g}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
|
|
334
|
-
`),f=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
|
|
335
|
-
`);return{moduleName:m,moduleText:p,cfgText:f,variables:l,skippedVariables:d,states:s.length,warnings:o}}function $m(e){let t=e.mappedActions??[],n=q$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:gi(t,[])};let i=L$(hn(N$(),"scip-tla-trace-"));try{let o=D$(e.specPath);for(let d of j$(o))d.endsWith(".tla")&&P$(hn(o,d),hn(i,d));let r=hn(i,`${n.moduleName}.tla`),s=hn(i,`${n.moduleName}.cfg`);wm(r,n.moduleText),wm(s,n.cfgText);let a=ui({...e.toolOptions,specPath:r,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:gi(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:gi(t,e.steps)};let c=F$(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:gi(t,l)}}finally{M$(i,{recursive:!0,force:!0})}}function F$(e,t){let n=null;for(let r of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(r[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let i=n-1,o=t[i];return{divergedAtState:n,divergedStep:{index:i,action:o?.action??"unknown"}}}function W$(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 Rm(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>Rm(t)).join(", ")}>>`}function xm(e){return O$(e).replace(/\.tla$/i,"")}import{mkdirSync as km,writeFileSync as Em}from"fs";import{dirname as _$,join as Wt}from"path";var B$=async(...e)=>{let{args:t,opts:n}=Ya(e),i=M(t,0);if(i==="fetch-tools"){let r=await tm();if(b(n,"json")){P("tla",t,n,r);return}console.log(`tla2tools.jar ${r.status}: ${r.path}`),console.log(`Version: ${r.version}`),console.log(`SHA-256: ${r.sha256}`);return}if(i==="scaffold"){let r=H(t,1);if(!r)throw new Error("tla scaffold requires a target source file");Ne(s=>G$(s,t,n,r));return}if(i==="instrument"){let r=H(t,1);Ne(s=>V$(s,t,n,r));return}if(i==="trace-check"){let r=H(t,1);if(!r)throw new Error("tla trace-check requires a spec path");Ne(s=>U$(s,t,n,r));return}if(i!=="verify")throw new Error(`unknown tla operation: ${i}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let o=H(t,1);if(!o)throw new Error("tla verify requires a spec path");Ne(r=>K$(r,t,n,o))};function G$(e,t,n,i){let o=e.config.projectRoot,r=bm(e,i,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Wt("specs",r.moduleName),a=Pe(o,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Wt(a,`${r.moduleName}.tla`),body:r.spec},{path:Wt(a,`${r.moduleName}.cfg`),body:r.cfg},{path:Wt(a,`${r.moduleName}.scip-tla.json`),body:r.map}];for(let d of l)if(!c&&fn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);km(a,{recursive:!0});for(let d of l)Em(d.path,d.body);if(b(n,"json")){P("tla",t,n,{operation:"scaffold",moduleName:r.moduleName,target:i,written:l.map(d=>d.path),variables:r.variables,actions:r.actions,warnings:r.warnings});return}console.log(`Scaffolded ${r.moduleName} from ${i} (draft \u2014 review every TODO):`);for(let d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${r.variables.length}): ${r.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${r.actions.length}): ${r.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of r.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${Wt(s,`${r.moduleName}.tla`)}'.`)}function V$(e,t,n,i){let o=e.config.projectRoot,r=w(n,"map")??(i?oi(i):void 0);if(!r)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=ii(o,r);if(!s.loaded)throw new Error(s.errors.join(`
|
|
336
|
-
`));let{contract:a,mapDir:c}=s.loaded,l=Sm(e,a),d=w(n,"out")??Wt(c,"scip-tla-recorder.ts"),m=Pe(o,d);if(!m)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&fn(m))throw new Error(`refusing to overwrite ${m} (pass --force to replace the recorder)`);if(km(_$(m),{recursive:!0}),Em(m,l.recorderSource),b(n,"json")){P("tla",t,n,{operation:"instrument",recorder:m,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${m}`),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 h of l.wiring){let p=h.file?`${h.file}:${h.line}`:`UNRESOLVED (${h.codeRef})`;console.log(` - ${h.action} -> ${p} writes: ${h.writes.join(", ")||"-"}`)}}function U$(e,t,n,i){let o=e.config.projectRoot,r=Pe(o,i);if(!r||!fn(r))throw new Error(`TLA+ spec not found: ${i}`);let s=w(n,"map")??oi(i),a=ii(o,s);if(!a.loaded)throw new Error(a.errors.join(`
|
|
337
|
-
`));let{contract:c}=a.loaded,l=O(n,"trace"),m=vo(o,[...c.traces,...l]).flatMap(f=>bo(o,f).steps);if(m.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let h=$m({specPath:r,baseModuleName:xm(r),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:m,nextOperator:w(n,"next"),toolOptions:{projectRoot:o,tlaToolsJar:w(n,"tlaTools"),timeoutMs:K(n,"timeoutMs")}}),p=h.status==="accepted"||h.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){P("tla",t,n,{operation:"trace-check",...h,exitCode:p}),process.exitCode=p;return}if(console.log(`TLA+ trace-check: ${r}`),console.log(`Trace: ${m.length} step(s) -> ${h.states} pinned state(s)`),h.generation){console.log(`Pinned variables: ${h.generation.variables.join(", ")}`);for(let f of h.generation.warnings)console.log(`WARNING: ${f}`)}console.log(`${h.status.toUpperCase()}: ${h.detail}`),b(n,"coverage")&&H$(h.actionCoverage),process.exitCode=p}function H$(e){if(e.length===0)return;let t=e.filter(i=>i.stepsObserved>0),n=e.filter(i=>i.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let i of t)console.log(` - ${i.action}: ${i.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(i=>i.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function Q$(e,t,n,i){let o=w(i,"map");if(o)return{mapArg:o};let r=oi(t),s=Pe(e,r);if(s&&fn(s))return{mapArg:r};let a=Tu(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:r}}function K$(e,t,n,i){let o=e.config.projectRoot,r=Pe(o,i);if(!r||!fn(r))throw new Error(`TLA+ spec not found: ${i}`);let{mapArg:s,mappingDiscoveredBy:a}=Q$(o,i,r,n),c=ii(o,s);if(!c.loaded)throw new Error(c.errors.join(`
|
|
338
|
-
`));let{contract:l,mapPath:d,mapDir:m}=c.loaded,h=w(n,"config")??l.config,p=Ru(o,m,h),f=J$(w(n,"checker")??"auto"),g=w(n,"tlaTools"),y=z$(o,i,r,g)??xu(o,i),v=ku(p),$=O(n,"trace"),_=vo(o,[...l.traces,...$]).map(F=>({tracePath:F,...bo(o,F)})),I=_.flatMap(F=>F.steps),T=new Set($),W=_.filter(F=>T.has(F.tracePath)).flatMap(F=>F.errors),E=am(e,l,y,I,v);for(let F of[...c.errors,...W])E.findings.push({id:`TLA-CONTRACT-${E.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 B=ui({projectRoot:o,specPath:r,configPath:p??void 0,checker:f,tlaToolsJar:g,apalacheBin:w(n,"apalache"),length:k(n,"length",10),timeoutMs:K(n,"timeoutMs")});B.status==="skipped"&&f!=="none"&&E.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:B.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 J={operation:"verify",specPath:r,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...p?{configPath:p}:{},checker:B,conformance:E,exitCode:Y$(B,E,b(n,"allowUnknown"))};if(b(n,"json")){P("tla",t,n,J),process.exitCode=J.exitCode;return}X$(J,b(n,"full")),process.exitCode=J.exitCode}function z$(e,t,n,i){let o=jo({projectRoot:e,specPath:n,tlaToolsJar:i,checker:"sany"});if(!o)return null;let r=mu({specPath:n,jarPath:o});return r?Cu(e,t,r):null}var Tm=[{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:be("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",z("repository-observation",[{when:{kind:"argument",index:0,equals:"scaffold"},role:"mutation"},{when:{kind:"argument",index:0,equals:"instrument"},role:"mutation"},{when:{kind:"argument",index:0,equals:"fetch-tools"},role:"composite"}])),options:x([u("--map <file>","scip-query TLA mapping JSON file"),u("--config <file>","TLA+ checker config file"),u("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),u("--tla-tools <jar>","Path to tla2tools.jar"),u("--apalache <binary>","Path to apalache-mc binary"),u("--length <n>","Bounded checker length for Apalache",S,10),u("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",pe),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",U,[]),u("--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"),u("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),u("--allow-unknown","Exit zero when only unknown findings remain"),u("--out <path>","Output directory (scaffold) or file (instrument)"),u("--module-name <name>","Module name for scaffolded specs"),u("--force","Overwrite existing scaffold/instrument output"),u("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:R("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:B$}];function J$(e){if(!$u(e))throw new Error(`unknown checker mode: ${e}`);return e}function Y$(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(i=>i.severity==="error")||!n&&t.findings.some(i=>i.evidence==="unknown")?1:0}var Cm=3;function X$(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 r of e.checker.diagnostics)console.log(` [${r.severity}] ${r.message}`);let n=e.conformance.findings.filter(r=>r.severity==="error"),i=e.conformance.findings.filter(r=>r.evidence==="unknown"),o=eR(e);console.log(`
|
|
339
|
-
Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${o}`);for(let r of tR(e))console.log(`WARNING: ${r}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let r of e.conformance.waivers){let s=r.legacy?" legacy":"",a=r.action?`${r.action} ${r.kind}`:`variable ${r.kind}`;console.log(` - ${a} ${r.variable}:${s} ${r.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), ${i.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let r of e.conformance.findings)Im(r);return}Z$(e.conformance)}function Z$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
|
|
340
|
-
Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
|
|
341
|
-
[${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let o of n.findingIds.slice(0,Cm)){let r=t.get(o);r&&Im(r)}let i=n.count-Cm;i>0&&console.log(` ... and ${i} more in this group (use --full to show all)`)}}function eR(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,i=e.conformance.waivers.filter(s=>s.kind==="read").length,o=e.conformance.waivers.filter(s=>s.kind==="referent").length,r=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, ${i} waived`,`calls: ${r===0?"checked":`${r} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...o>0?[`referents: ${o} waived`]:[]].join(" | ")}function tR(e){let t=[],n=e.conformance.waivers.filter(o=>o.kind==="write").length,i=e.conformance.waivers.filter(o=>o.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."),i>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 Im(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${V(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
|
|
342
|
-
[${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 Am=["stats","files","session","inspect","search","anchors","methods","refs","trace","evidence","evidence-source","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","dependency-depth","deep-chains","hierarchy","entrypoints","entry-map","system-map","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","co-change","recent-duplicates","doc-drift","unused-params","incomplete-migration","tla","context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","reference-neighborhood","dataflow","value-flow","dependence-slice","reference-reachability","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],nR=[ap,qp,pp,si,hp,_p,Tm,mp],Pm=nR.flat(),iR=new Map(Pm.map(e=>[e.id,e]));for(let e of Pm)if(!Am.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Lm=Am.map(e=>oR(e));function oR(e){let t=iR.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var dA=[Wa,{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:be("Did indexed source changes preserve the repository architecture policy?","architecture policy decision and enforced finding identities",[],"complete","diff",z("repository-observation")),description:"Internal architecture-only Stop hook",renderShape:"custom",handler:Dd},{id:"reindex",command:"reindex",agent:be("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository",z("composite")),description:"Index the codebase and convert to SQLite",options:x([u("-l, --language <lang>","Index only this language (can be repeated)",U,[]),u("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),u("--force","Rebuild even if source inputs are unchanged"),u("--allow-partial","Write an incomplete index when one or more detected languages fail"),u("--allow-expensive-rebuild","Explicitly permit a whole-project indexer when incremental and shared-generation paths are unavailable"),u("--trust-project-tools","Permit reviewed indexers from this repository for this run"),u("--install-missing","Install missing global tools at reviewed immutable versions for this run"),u("--indexer-concurrency <n>","Number of language indexers to run at once",pe)]),renderShape:"custom",docs:R("Indexing",["scip-query reindex"]),handler:qd},{id:"augment-sources",command:"augment-sources",agent:be("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository",z("composite")),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:R("Indexing"),handler:Fd},{id:"augment-vue",command:"augment-vue",agent:be("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository",z("composite")),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[u("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:R("Indexing"),handler:Wd},...Lm,{id:Jt,command:Jt,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--json","Emit the private worker envelope without transport pagination"),u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:_d},{id:"diff-impact",command:"diff-impact",agent:C("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Map changed symbols and downstream consumers from the current git diff",options:x([u("--base <ref>","Git ref to diff against (default: HEAD)")]),claims:Je(["index-generation","live-workspace"],[X("changed-files","changedFiles[]","repository-source"),X("changed-symbols","changedSymbols[]","compiler-graph"),X("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:R("Impact"),handler:Bd},{id:Kt,command:Kt,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[u("--json","Emit the private worker envelope without transport pagination"),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Gd},{id:zt,command:zt,description:"Internal health semantic prewarm worker",hidden:!0,options:[u("--json","Emit the private worker envelope without transport pagination"),u("-s, --scope <path>","Limit to files matching path"),u("--full","Materialize complete semantic evidence"),u("--shard-index <n>","Warm only this zero-based slice of the indexed files"),u("--shard-count <n>","Number of parallel prewarm slices")],renderShape:"custom",handler:Vd},{id:"health",command:"health",agent:be("Where has this repository accumulated drift, duplication, complexity, or cleanup pressure?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository",z("repository-observation",[{when:{kind:"option",name:"writeBaseline",equals:!0},role:"composite"}])),description:"Composite repository health report with React, Vue, and general cleanup findings",options:x([u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes"),u("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),u("--write-baseline","Snapshot current finding identities to the baseline file")]),claims:Je(["index-generation","live-workspace","process"],[Ga("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),X("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:R("Health",["scip-query health --json","scip-query health --baseline"]),handler:Ud},{id:"install-skills",command:"install-skills",agent:be("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",z("mutation")),description:`Install skills (${Lc.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:R("Maintenance"),handler:Hd},{id:"check-deps",command:"check-deps",agent:C("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository",z("environment-observation")),description:"Check whether scip-query and the detected language indexers are runnable",renderShape:"custom",docs:R("Maintenance"),handler:Qd},{id:"capabilities",command:"capabilities",agent:C("Which repository-mapping and analysis capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository",z("environment-observation")),description:"Report which mapping and analysis capabilities are available in this project",options:x([u("--matrix","Add exhaustive provider and language support details")]),renderShape:"custom",docs:R("Maintenance"),handler:Kd},{id:"init",command:"init",agent:be("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository",z("mutation")),description:"Create a .scipquery.json configuration file for this project",renderShape:"custom",docs:R("Maintenance"),handler:zd},{id:"config-validate",command:"config-validate",agent:C("Is this project configuration valid and internally consistent?","validation diagnostics with configuration paths",[],"complete","repository"),description:"Validate .scipquery.json, structured suppressions, architecture, and coupling groups",options:x(),claims:Ba("repository-source",["live-workspace"]),renderShape:"custom",docs:R("Maintenance",["scip-query config-validate"]),handler:Jd},{id:"suppress",command:"suppress <id>",agent:be("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete",void 0,z("mutation")),description:"Record an accepted finding under .scipquery/suppressions with a required reason",options:x([u("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),u("--reason-code <code>","Required adjudication code"),u("--evidence <kind:referent>","Required counterevidence; repeat for more evidence",U,[]),u("--check <check>","Optional detector name to narrow the suppression"),u("--file <path>","Optional file path to narrow the suppression"),u("--expires-at <iso>","Optional ISO date after which the suppression expires"),u("--replace <revision>","Replace a prior decision with this exact SHA-256 revision")]),renderShape:"custom",docs:R("Maintenance"),handler:Yd},{id:"doctor",command:"doctor",agent:C("Why is scip-query unhealthy or unavailable in this project?","configuration, freshness, dependency, and capability diagnostics",[],"complete","repository",z("environment-observation")),description:"Diagnose configuration, index freshness, dependencies, and project capabilities",options:x(),renderShape:"custom",docs:R("Maintenance"),handler:Xd},{id:"setup",command:"setup",agent:be("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository",z("composite")),description:"Install skills, write agent guidance, refresh the index, and report readiness",options:x([u("--guided","Require and open the interactive terminal checklist"),u("--yes","Accept recommended setup defaults without prompting"),u("--no-skills","Skip user-level agent skill installation"),u("--no-parsers","Skip Tree-sitter AST parser installation and repair"),u("--install-missing","Install missing global tools at reviewed immutable versions"),u("--health","Run the optional full health report and write its dossier"),{flags:"--no-health",description:"Compatibility inverse of --health",hidden:!0},u("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:R("Maintenance",["scip-query setup","scip-query setup --health","scip-query setup --install-missing","scip-query setup --json"]),handler:tu},{id:"setup-agent",command:"setup-agent",agent:be("Can concise project guidance for scip-query be written?","written, unchanged, and skipped agent instruction files",[],"complete","repository",z("mutation")),description:"Write concise scip-query mapping and cleanup guidance to AGENTS.md and CLAUDE.md",renderShape:"custom",docs:R("Maintenance",["scip-query setup-agent"]),handler:eu},{id:"uninstall",command:"uninstall",agent:be("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository",z("mutation",[{when:{kind:"option",name:"dryRun",equals:!0},role:"repository-preview"}])),description:"Remove selected scip-query-owned skills or project guidance",options:x([u("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),u("--project","Remove managed AGENTS.md and CLAUDE.md blocks"),u("--dry-run","List what would be removed without changing files"),u("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:R("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:nu},{id:"watch",command:"watch",agent:be("What is the watcher doing, or can background services be started, stopped, or pruned?","watcher state, generation, activity, and errors",[],"complete","repository",z("composite",[{when:{kind:"option",name:"status",equals:!0},role:"environment-observation"}])),description:"Watch in the foreground or manage the project refresh service",options:x([u("--daemon","Make sure that the background service is running"),u("--status","Show the watcher state"),u("--stop","Stop the watcher for this project"),u("--prune","Stop watcher services whose owned worktree roots no longer exist"),u("--debounce <ms>","Milliseconds after the last change",ze),u("--cooldown <ms>","Minimum milliseconds between indexes",ze),u("--git-poll <ms>","Milliseconds between Git state checks",ze),u("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",ze)]),renderShape:"custom",docs:R("Maintenance"),handler:iu},{id:"status",command:"status",agent:C("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, and watcher state",[],"complete","repository",z("environment-observation")),description:"Show index status for this project",options:x([{...u("--capabilities","Compatibility: include a concise capability-readiness summary"),hidden:!0}]),renderShape:"custom",docs:R("Maintenance"),handler:su}];export{dA as commandDescriptors};
|
|
343
|
-
//# sourceMappingURL=command-descriptors-7BKH53Y3.js.map
|