scip-query 0.23.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 +491 -2
- package/README.md +111 -122
- 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-CUtj8V2I.d.ts +19 -0
- 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-EG2CPZMJ.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-6I6L7Z62.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-ILTDAWEF.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-JTQVMR42.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-WIWY3CRX.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-M2O5NY6W.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-XBGWL66K.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-T3I6NHBH.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-VF5JZICY.js +2 -0
- 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-X6RMKHJQ.js +81 -0
- package/dist/{chunk-4ILJCCXV.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-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
- package/dist/chunk-ZO4YXUT6.js +4 -0
- package/dist/{chunk-HYO3NP5Q.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/frontend-profile-roles-D7eCum8P.d.ts +10 -0
- package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
- 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 +3 -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.d.ts +20 -2
- 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.d.ts +2 -0
- 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 +29 -2
- 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 +17 -65
- 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.d.ts +9 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +19 -3
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +22 -3
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +17 -3
- 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 +23 -7
- 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 +55 -12
- 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 +70 -13
- package/docs/analyzer-inventory.md +2 -2
- package/docs/locality-analyzer-design.md +9 -9
- 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-XI2CSWEY.js +0 -2
- package/dist/call-graph-UONR6JR5.js +0 -2
- package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
- package/dist/chunk-26CT72HM.js +0 -2
- package/dist/chunk-2E7CX53V.js +0 -2
- package/dist/chunk-2GRUZAQF.js +0 -43
- package/dist/chunk-2LDBDR6J.js +0 -29
- package/dist/chunk-2OOY75BW.js +0 -2
- package/dist/chunk-2R3V3PSD.js +0 -4
- package/dist/chunk-2WC2OEDO.js +0 -4
- package/dist/chunk-35NLDRZC.js +0 -2
- package/dist/chunk-3AF4TUFK.js +0 -3
- package/dist/chunk-3D3QG236.js +0 -2
- package/dist/chunk-3FHOF22C.js +0 -21
- package/dist/chunk-3JKSW6LJ.js +0 -2
- package/dist/chunk-3L2ZBPEX.js +0 -133
- package/dist/chunk-3PJABJSU.js +0 -2
- package/dist/chunk-3SVF22I5.js +0 -2
- package/dist/chunk-3WR4E3A3.js +0 -3
- package/dist/chunk-4FTZ4P5G.js +0 -2
- package/dist/chunk-4UX2F3JX.js +0 -2
- package/dist/chunk-4WNW27SX.js +0 -2
- package/dist/chunk-5ENOG4VP.js +0 -61
- package/dist/chunk-64BFSI5I.js +0 -2
- package/dist/chunk-66DVSJQG.js +0 -455
- package/dist/chunk-6HFCYNYE.js +0 -9
- package/dist/chunk-6PQNKL3G.js +0 -3
- package/dist/chunk-6V5CNXL6.js +0 -2
- package/dist/chunk-6VVV4WRR.js +0 -4
- package/dist/chunk-7BWFZPPZ.js +0 -2
- package/dist/chunk-7CYG22FH.js +0 -2
- package/dist/chunk-7F45LJKI.js +0 -2
- package/dist/chunk-7IWV2EG3.js +0 -3
- package/dist/chunk-7KCZELVM.js +0 -2
- package/dist/chunk-AFHTBORT.js +0 -2
- package/dist/chunk-AVRYW5OZ.js +0 -2
- package/dist/chunk-B3X6KU75.js +0 -2
- package/dist/chunk-B5D7QPBE.js +0 -4
- package/dist/chunk-BBCIS4DX.js +0 -16
- package/dist/chunk-BDUVI7TO.js +0 -3
- package/dist/chunk-BE7ZZTMC.js +0 -2
- package/dist/chunk-BHVUJOCQ.js +0 -3
- package/dist/chunk-BJT7LSPK.js +0 -3
- package/dist/chunk-BKVWUP7Y.js +0 -2
- package/dist/chunk-BQGB4HBD.js +0 -2
- package/dist/chunk-BRV7PIFF.js +0 -2
- package/dist/chunk-CEEZJXEF.js +0 -2
- package/dist/chunk-CIYLO6SI.js +0 -7
- package/dist/chunk-CJZXN4NU.js +0 -2
- package/dist/chunk-CNO7TOKL.js +0 -2
- package/dist/chunk-COF23M5F.js +0 -2
- package/dist/chunk-CWFP7GM5.js +0 -2
- package/dist/chunk-D2DHWI3D.js +0 -2
- package/dist/chunk-D4N5SQ2M.js +0 -4
- package/dist/chunk-DBRSYFXR.js +0 -2
- package/dist/chunk-DHUIOLDT.js +0 -2
- package/dist/chunk-DIRJWYBM.js +0 -6
- package/dist/chunk-DIUFNHRJ.js +0 -35
- package/dist/chunk-DRENNWRG.js +0 -2
- package/dist/chunk-DTZCKZEU.js +0 -4
- package/dist/chunk-DULC3QFP.js +0 -5
- package/dist/chunk-DYGHBZ2N.js +0 -16
- package/dist/chunk-E5R6AQ73.js +0 -40
- package/dist/chunk-E73UNJTF.js +0 -38
- package/dist/chunk-EKV5HX33.js +0 -2
- package/dist/chunk-EQHFIL6T.js +0 -3
- package/dist/chunk-ESIQ66Z7.js +0 -2
- package/dist/chunk-EVFUMY4R.js +0 -3
- package/dist/chunk-F7DY272B.js +0 -2
- package/dist/chunk-FBN2FGXG.js +0 -2
- package/dist/chunk-FDLOBR6P.js +0 -4
- package/dist/chunk-FESCRNVV.js +0 -5
- package/dist/chunk-FFRKR4EQ.js +0 -2
- package/dist/chunk-FGA2U4OR.js +0 -8
- package/dist/chunk-FIQRSHVM.js +0 -2
- package/dist/chunk-FPYLNQPT.js +0 -2
- package/dist/chunk-FRUSVINH.js +0 -2
- package/dist/chunk-GSP44ENC.js +0 -2
- package/dist/chunk-GUFSG5TX.js +0 -2
- package/dist/chunk-GYIZ4NXB.js +0 -2
- package/dist/chunk-GZIUDL6G.js +0 -2
- package/dist/chunk-H5EXS3HM.js +0 -2
- package/dist/chunk-HCXEQRFF.js +0 -18
- package/dist/chunk-HEHOQQKH.js +0 -2
- package/dist/chunk-HKGFPJ4T.js +0 -4
- package/dist/chunk-HLZTEXRA.js +0 -2
- package/dist/chunk-HOENASQM.js +0 -3
- package/dist/chunk-HVF5VBG6.js +0 -2
- package/dist/chunk-I55I7XXP.js +0 -2
- package/dist/chunk-IDFEUFKS.js +0 -2
- package/dist/chunk-IHGQTTVW.js +0 -2
- package/dist/chunk-IICPE7B2.js +0 -20
- package/dist/chunk-IL676XCC.js +0 -18
- package/dist/chunk-IW5XQG5G.js +0 -2
- package/dist/chunk-IZDPJ2QI.js +0 -2
- package/dist/chunk-J66VOFW6.js +0 -5
- package/dist/chunk-JFMEXGFE.js +0 -2
- package/dist/chunk-JGKUET5J.js +0 -3
- package/dist/chunk-JS4PGXMV.js +0 -3
- package/dist/chunk-JWTGMPIT.js +0 -80
- package/dist/chunk-JYR66JN5.js +0 -5
- package/dist/chunk-KFOYCQAJ.js +0 -9
- package/dist/chunk-KLFEXGQA.js +0 -2
- package/dist/chunk-KMVGRIO2.js +0 -2
- package/dist/chunk-KYSDI3GE.js +0 -5
- package/dist/chunk-L6PJPETJ.js +0 -29
- package/dist/chunk-LDVT66YM.js +0 -2
- package/dist/chunk-LEECKFCJ.js +0 -2
- package/dist/chunk-LMZ5PRUV.js +0 -2
- package/dist/chunk-LQRQN2XA.js +0 -2
- package/dist/chunk-LXABEJX3.js +0 -2
- package/dist/chunk-MNV5FSBW.js +0 -3
- package/dist/chunk-MPQ4OTBM.js +0 -2
- package/dist/chunk-MTDBHTSF.js +0 -2
- package/dist/chunk-MV3CDXPI.js +0 -38
- package/dist/chunk-MWN53KRN.js +0 -60
- package/dist/chunk-MXNGIEPU.js +0 -3
- package/dist/chunk-N2ZSIIGR.js +0 -117
- package/dist/chunk-N5B2NILC.js +0 -5
- package/dist/chunk-NJITK2GP.js +0 -2
- package/dist/chunk-NOGJXYFO.js +0 -2
- package/dist/chunk-NOYBFVJA.js +0 -554
- package/dist/chunk-NWQXSFFU.js +0 -3
- package/dist/chunk-ODDUPDP7.js +0 -13
- package/dist/chunk-OLIWTZI3.js +0 -3
- package/dist/chunk-OLNV6I6U.js +0 -2
- package/dist/chunk-OR2E3AGZ.js +0 -2
- package/dist/chunk-OSR2GEHQ.js +0 -2
- package/dist/chunk-OSSESPDX.js +0 -3
- package/dist/chunk-OWOOWNJ5.js +0 -7
- package/dist/chunk-P42EIXTA.js +0 -2
- package/dist/chunk-PJFGPYTU.js +0 -2
- package/dist/chunk-PP7KNN7L.js +0 -2
- package/dist/chunk-PU7T5QYQ.js +0 -2
- package/dist/chunk-PWWAJSKV.js +0 -74
- package/dist/chunk-PZL5T7SU.js +0 -73
- package/dist/chunk-QBE3YX64.js +0 -23
- package/dist/chunk-QGVTFRY2.js +0 -7
- package/dist/chunk-QOJONDS7.js +0 -2
- package/dist/chunk-QU5XRYB5.js +0 -4
- package/dist/chunk-QUU5OBVK.js +0 -11
- package/dist/chunk-RBLQNW26.js +0 -20
- package/dist/chunk-RTQ7NEKG.js +0 -81
- package/dist/chunk-SQXRS7BG.js +0 -4
- package/dist/chunk-SSK6LDPC.js +0 -2
- package/dist/chunk-SZHGTCPP.js +0 -7
- package/dist/chunk-T4N4P2K5.js +0 -16
- package/dist/chunk-TA3QKLLU.js +0 -2
- package/dist/chunk-TEBQMNVI.js +0 -43
- package/dist/chunk-TPFHAQ2G.js +0 -2
- package/dist/chunk-TQPCBMWT.js +0 -5
- package/dist/chunk-TQZV7KV4.js +0 -2
- package/dist/chunk-TRNAEQ6P.js +0 -3
- package/dist/chunk-TY7CRN3Z.js +0 -2
- package/dist/chunk-UHFYCMZO.js +0 -35
- package/dist/chunk-UICY4GTQ.js +0 -7
- package/dist/chunk-UVGEWT4Y.js +0 -26
- package/dist/chunk-UXW33INU.js +0 -29
- package/dist/chunk-VMPRET3I.js +0 -5
- package/dist/chunk-VNLGKHS6.js +0 -6
- package/dist/chunk-VQILFTEH.js +0 -2
- package/dist/chunk-VUPHCS7Y.js +0 -57
- package/dist/chunk-VVZSBTSU.js +0 -23
- package/dist/chunk-VZRNID6A.js +0 -2
- package/dist/chunk-W5OXRYGE.js +0 -7
- package/dist/chunk-W6STWDQI.js +0 -57
- package/dist/chunk-W7CXK74K.js +0 -2
- package/dist/chunk-WB3WYIRE.js +0 -4
- package/dist/chunk-WDNVY4E7.js +0 -20
- package/dist/chunk-WK46TNUM.js +0 -3
- package/dist/chunk-WNTFFKAX.js +0 -12
- package/dist/chunk-WOIKCX6A.js +0 -2
- package/dist/chunk-WUN6KBHV.js +0 -2
- package/dist/chunk-WYCTJDVR.js +0 -2
- package/dist/chunk-WYPL7GF7.js +0 -2
- package/dist/chunk-XDAUYDFT.js +0 -2
- package/dist/chunk-XDQMU3BT.js +0 -2
- package/dist/chunk-XFA4SSO3.js +0 -3
- package/dist/chunk-XGZEP6GR.js +0 -8
- package/dist/chunk-XPDPNWTQ.js +0 -368
- package/dist/chunk-XRYABF57.js +0 -8
- package/dist/chunk-YBGKCQIS.js +0 -2
- package/dist/chunk-YEN6CYC7.js +0 -16
- package/dist/chunk-YF5IB2LF.js +0 -2
- package/dist/chunk-YI2AWIHC.js +0 -3
- package/dist/chunk-YPWBKGFU.js +0 -2
- package/dist/chunk-YPWHBBIS.js +0 -2
- package/dist/chunk-YSH6U3L4.js +0 -3
- package/dist/chunk-YU5DZUZI.js +0 -10
- package/dist/chunk-YWO5DDRC.js +0 -16
- package/dist/chunk-Z4CDXYNQ.js +0 -2
- package/dist/chunk-ZF5KHH7C.js +0 -2
- package/dist/chunk-ZOHS7AQV.js +0 -21
- package/dist/chunk-ZTI4SBFV.js +0 -3
- package/dist/code-MI6F2TTU.js +0 -2
- package/dist/code-result-json-FXALY4HE.js +0 -2
- package/dist/command-descriptors-P34VABY5.js +0 -343
- package/dist/dataflow-4KEMJPC6.js +0 -2
- package/dist/dependence-slice-R7FPWD5M.js +0 -2
- package/dist/deps-7EMQUYUT.js +0 -2
- package/dist/direct-navigation-6YO234F2.js +0 -3
- package/dist/entry-map-KOOLR26E.js +0 -2
- package/dist/files-OPIPJIGZ.js +0 -2
- package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
- package/dist/hierarchy-QPD2CAER.js +0 -2
- package/dist/imports-M6HUXRXC.js +0 -2
- package/dist/members-I5MEFOCT.js +0 -2
- package/dist/methods-5JYGGHXA.js +0 -2
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
- package/dist/output-continuation-command-UPQAAKBP.js +0 -3
- package/dist/output-pagination-3OFL2MJV.js +0 -19
- package/dist/project-reindex-UKKQ5PLS.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 -52
- 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 -63
- 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 -34
- package/dist/queries/wrapper-candidates.js +0 -2
- package/dist/refs-PSU4JZZW.js +0 -2
- package/dist/refs-pagination-JG6CJMRC.js +0 -2
- package/dist/slice-HYRATV64.js +0 -2
- package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
- package/dist/stats-OOJ74B32.js +0 -2
- package/dist/surface-VTGDYWF5.js +0 -2
- package/dist/symbol-resolution-WD5EU5JE.js +0 -2
- package/dist/system-LRQNFOR2.js +0 -2
- package/dist/trace-F4B6OLL4.js +0 -2
- package/dist/value-flow-VRPZY72V.js +0 -2
- package/skills/concrete-plan/SKILL.md +0 -8
- package/skills/concrete-plan/agents/openai.yaml +0 -4
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as Ys,b as Xs,c as Zs,d as ea,e as zn,f as ta,g as It,h as na,i as ia,l as ra,m as at,n as on,o as sn,p as oa,r as sa,s as aa,t as ca,u as la,v as da,x as ua,y as an}from"./chunk-L7GFM3NP.js";import{a as Cs}from"./chunk-XHMN6ZX7.js";import"./chunk-B56T42J3.js";import{A as Ws,a as Hn,b as B,c as g,d as Ie,e as F,f as ce,g as c,h as Es,i as Ps,j as b,k as f,l as re,m as Is,n as T,o as ot,p as Ke,q as S,r as ne,s as Et,t as Xt,u as As,v as Zt,w as Qn,x as Ae,y as de,z as ue}from"./chunk-EJVTR244.js";import{A as D,B as $,C as P,D as Ns,E as x,F as Os,G as N,a as ae,b as W,i as H,j as Q,k as js,l as Ts,m as Ls,n as st,o as Vn,p as Ms,q as we,r as qs,s as le,t as Ds,u as E,w as q,x as y,y as j,z as m}from"./chunk-EYK3ZAO2.js";import{$ as ro,$a as rs,A as Lr,Aa as To,B as Mr,Ba as Lo,C as qr,Ca as Mo,D as Dr,Da as qo,E as Nr,Ea as Do,Eb as ys,F as Or,Fa as No,G as Wr,Ga as Oo,H as Fr,Ha as Wo,I as _r,Ia as Fo,Ib as bs,J as Br,Ja as _o,Jb as Yt,K as Gr,Ka as Bo,Kb as O,L as Ur,La as Go,Lb as ie,M as Hr,Ma as Uo,Mb as L,N as Vr,Nb as wt,O as nt,Oa as Ho,Ob as w,P as Qe,Pa as Vo,Pb as $t,Q as Qr,Qa as Qo,Qb as kt,R as Jr,Ra as Jo,Rb as Ct,S as zr,Sa as zo,Sb as Pe,T as Kr,Ta as Ko,U as Yr,Ua as Yo,Ub as Ss,V as Xr,Va as Xo,Vb as vs,W as Zr,Wa as Zo,Wb as Rs,X as eo,Xa as es,Xb as xs,Y as to,Ya as ts,Yb as ws,Z as no,Za as ns,Zb as $s,_ as io,_a as is,a as St,aa as oo,ab as it,b as sr,ba as so,bb as Z,bc as rt,c as ar,ca as ao,cb as Je,cc as ks,d as Ne,da as co,db as xe,e as cr,ea as lo,eb as ss,f as Ut,fa as uo,fb as as,g as Sr,ga as po,gb as cs,h as Vt,ha as mo,hb as ls,i as xr,ia as ho,j as wr,ja as go,jb as ee,k as $r,ka as fo,kb as ps,la as yo,lb as _,ma as bo,n as kr,na as So,o as Cr,oa as vo,ob as te,p as Pr,pa as Ro,pb as Un,q as Ir,qa as xo,ra as wo,sa as $o,t as xt,ta as ko,tb as ms,u as Qt,ua as Co,ub as ze,v as Ar,va as Eo,vb as hs,w as Ve,wa as Po,x as Bn,xa as Io,xb as U,y as jr,ya as Ao,yb as gs,z as Tr,za as jo}from"./chunk-JYWEX7RR.js";import{a as en,b as Pt,c as Jn,d as Fs,e as _s,f as Bs,g as tn,h as Gs,i as Us,j as nn,k as Hs,l as rn,m as Vs,n as Qs,o as Js,p as zs,q as Ks,r as pa}from"./chunk-CFYMZFXT.js";import{$ as zi,Ae as Dn,B as Ui,Be as Nn,Ce as ur,Db as ir,De as On,Fa as tt,Fe as pr,G as Hi,Ga as Ln,Ge as mr,He as hr,Ia as tr,Ie as gr,If as os,J as Tn,Je as Wn,Jf as Jt,K as Vi,Ke as Fn,Le as _n,Me as fr,O as Qi,Pe as yr,Qb as Ft,R as Ji,Rb as rr,Re as Ht,Se as br,We as vr,Xe as Rr,_ as be,a as jn,aa as Ki,ba as Yi,bb as nr,be as vt,c as Wi,cg as Gn,ea as Se,fb as Wt,ga as Xi,gg as ds,hc as or,hg as us,l as Fi,m as _i,mf as Er,n as Bi,na as Zi,ne as _t,oe as Bt,pe as lr,qe as Gt,re as ve,s as He,se as X,t as G,te as dr,uf as Re,va as er,ve as Rt,we as Mn,wg as fs,xe as qn,xg as zt,yg as Kt,z as Gi}from"./chunk-OZCJXZK6.js";import{existsSync as Mt}from"fs";import{dirname as zf,join as vl}from"path";import{execFileSync as dp}from"child_process";import{createRequire as gu}from"module";var fu=gu(import.meta.url);function ma(e,t=[]){let n=yu(),i=Sr(e,t),r=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i,reason:"ts-morph is not installed"}}function yu(){try{return fu.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as At,spawnSync as bu}from"child_process";import{existsSync as $e,mkdtempSync as Su,readdirSync as vu,rmSync as ha,symlinkSync as Ru,writeFileSync as xu}from"fs";import{tmpdir as wu}from"os";import{join as z}from"path";var $u=3e5,ku=12,ya=3e4,Yn=1024*1024,Cu={readWorkingTreeStatus(e){return At("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:ya,maxBuffer:Yn,killSignal:"SIGKILL"})}};function ba(e,t,n={}){let i=Du(e,n.workingTreeRuntime),r=i.state==="known"?i.files:[],o=qu(t,i),s=Xn(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:o,dirtyWorkingTree:r,batches:[]};let a=Au(t,s),l=n.timeoutMs??$u,d=[],u=new Map,p;try{p=va(e,"scip-cleanup-verify-")}catch(h){return{checkers:s.map(v=>v.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:o,dirtyWorkingTree:r,unavailableReason:Wu(h),batches:[]}}try{Ou(e,p.root);for(let v of s)u.set(v.label,ka(v,p.root,l).rawErrors);let h=Ra(p.root);for(let v of t.batches){h(v);let k=cp(s,p.root,l,u,v.depth);if(!k)d.push({depth:v.depth,status:"verified"});else{d.push(k);break}}}finally{p.dispose()}return{checkers:s.map(h=>h.label),uncoveredFiles:a,baselineErrors:[...u.values()].reduce((h,v)=>h+v.length,0),workingTree:i,dirtyOverlap:o,dirtyWorkingTree:r,batches:d}}function Eu(e,t,n){let i=Pu(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 Pu(e,t){let n=Iu(e),i=new Map,r=[];for(let o of t){let s=Sa(o),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&r.push(o)}return r}function Iu(e){let t=new Map;for(let n of e){let i=Sa(n);t.set(i,(t.get(i)??0)+1)}return t}function Au(e,t){let n=new Set(t.flatMap(r=>r.coversExtensions));return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>{let o=r.slice(r.lastIndexOf("."));return!n.has(o)}).sort()}function Sa(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var ga=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],ju=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Xn(e){let t=[];if($e(z(e,"tsconfig.json"))){let n=z(e,"node_modules",".bin","tsc");t.push($e(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:ga,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:ga,strength:"reference-aware"})}if($e(z(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=>$e(z(e,n)))){let n=Tu();n&&t.push(n)}if(ju.some(n=>$e(z(e,n)))){let n=Lu(e);n&&t.push(n)}for(let n of Mu(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:z(e,n,"..","target")}});return t}function Tu(){return vt("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"}:vt("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Lu(e){let t=z(e,"node_modules",".bin","clj-kondo");return $e(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Wt],strength:"reference-aware"}:vt("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Wt],strength:"reference-aware"}:vt("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Wt],strength:"reference-aware"}:null}function Mu(e){let t=[];if($e(z(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=vu(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||$e(z(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function qu(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>n.has(r)).sort()}function Du(e,t=Cu){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:Nu(n)}}}function Nu(e){let t=e&&typeof e=="object"?e:{};return t.code==="ETIMEDOUT"||t.killed===!0?`git status timed out after ${ya}ms`:lp(t)?`git status exceeded its ${Yn}-byte output limit`:typeof t.signal=="string"&&t.signal!==""?`git status was terminated by ${t.signal}`:typeof t.status=="number"?`git status exited with status ${t.status}`:ap(t,e)}function Ou(e,t){for(let n of["node_modules"]){let i=z(e,n),r=z(t,n);if($e(i)&&!$e(r))try{Ru(i,r,"junction")}catch{}}}function va(e,t){let n=Su(z(wu(),t)),i=z(n,"checkout");try{let r=At("git",["-C",e,"rev-parse","--verify","HEAD"],{encoding:"utf-8",timeout:3e4,maxBuffer:Yn,killSignal:"SIGKILL"}).trim();return At("git",["clone","--quiet","--no-checkout","--shared","--",e,i],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),At("git",["-C",i,"checkout","--quiet","--detach","--force",r],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),{root:i,dispose(){ha(n,{recursive:!0,force:!0})}}}catch(r){throw ha(n,{recursive:!0,force:!0}),r}}function Wu(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 Ra(e){let t=new Map,n=new Map;return i=>{let r=new Set;for(let o of i.entries){let s=n.get(o.file)??[];s.push({start:o.startLine,end:o.endLine}),n.set(o.file,s),r.add(o.file)}for(let o of r){let s=z(e,o),a=t.get(o);a===void 0&&(a=He(s,{maxBytes:Bi,inputKind:"cleanup verification source file"}),t.set(o,a)),xu(s,Bu(a,n.get(o),{rust:o.endsWith(".rs")}))}}}function Fu(e,t={}){let n=e.flatMap(i=>i.entries.map(r=>({batch:i.depth,file:r.file,startLine:r.startLine,endLine:r.endLine,loc:r.loc,symbol:r.shortName})));return{dryRun:t.dryRun===!0,batches:e.length,symbols:n.length,loc:e.reduce((i,r)=>i+r.loc,0),files:[...new Set(n.map(i=>i.file))],filesEmptied:[...new Set(e.flatMap(i=>i.filesEmptied))],targets:n}}function _u(e,t,n={}){let i=Fu(t,n);if(!i.dryRun){let r=Ra(e);for(let o of t)r(o)}return i}function xa(e,t){let n=va(e,"scip-cleanup-patch-");try{return _u(n.root,t),At("git",["-C",n.root,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{n.dispose()}}function wa(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 $a(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 r=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)r.has(o.depth)||i.push(`Batch ${o.depth} is not verified by the detected checker(s).`);return i}function Bu(e,t,n={}){let i=e.split(`
|
|
4
|
+
`),r=(n.rust===!0?Gu(e):ir(e)).split(`
|
|
5
|
+
`),o=new Set;for(let s of t){let a=Uu(i,s.start),l=Vu(r,a,Math.min(s.end,i.length-1));for(let d=a;d<=l&&d<i.length;d++)o.add(d)}return i.filter((s,a)=>!o.has(a)).join(`
|
|
6
|
+
`)}function Gu(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 Uu(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 Hu=200;function Vu(e,t,n){let i=0;for(let r=t;r<e.length;r++){if(i+=op(e[r]??""),r>=n&&i<=0)return r;if(r-n>Hu)break}return n}function ka(e,t,n){let i=bu(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),r=`${i.stdout??""}
|
|
7
|
+
${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:fa(r)};let o=Qu(e.label,r),s=o.diagnostics.length>0?o.diagnostics:i.error?[{file:"",message:String(i.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:i.status,rawErrors:s.map(rp),diagnostics:s,parseBasis:o.parseBasis,outputTail:fa(r)}}function Qu(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Ju(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:zu(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Ku(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Zu(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:ep(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:np(t),parseBasis:"clj-kondo-json"}:{diagnostics:ip(t),parseBasis:"heuristic"}}function Ju(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 zu(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 Ku(e){let t=Ca(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){let r=Yu(i);r&&n.push(r)}return n}function Yu(e){if(!e||typeof e!="object")return null;let t=e,n=t.location,i=n&&typeof n=="object"?n:{},r=typeof t.filename=="string"?t.filename:"",o=typeof t.message=="string"?t.message:"";return!r&&!o?null:Xu(t,i,r,o)}function Xu(e,t,n,i){return{file:n,line:typeof t.row=="number"?t.row:void 0,column:typeof t.column=="number"?t.column:void 0,code:typeof e.code=="string"?e.code:void 0,message:i,parseBasis:"ruff-json"}}function Zu(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 ep(e){let t=[];for(let n of e.split(`
|
|
8
|
+
`)){if(!n.trim().startsWith("{"))continue;let i=Kn(n);if(!i||typeof i!="object")continue;let r=i;if(r.reason!=="compiler-message")continue;let o=r.message;if(!o||typeof o!="object")continue;let s=o;s.level==="error"&&t.push(tp(s))}return t}function tp(e){let n=(Array.isArray(e.spans)?e.spans:[]).find(r=>!!r&&typeof r=="object"&&r.is_primary===!0),i=e.code;return{file:typeof n?.file_name=="string"?n.file_name:"",line:typeof n?.line_start=="number"?n.line_start:void 0,column:typeof n?.column_start=="number"?n.column_start:void 0,code:i&&typeof i=="object"&&typeof i.code=="string"?String(i.code):void 0,message:typeof e.message=="string"?e.message:"",parseBasis:"cargo-json"}}function np(e){let t=Ca(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let i=[];for(let r of n){let o=sp(r);o&&i.push(o)}return i}function ip(e){return e.split(`
|
|
9
|
+
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function rp(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 Ca(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Kn(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?Kn(t.slice(n)):null}function Kn(e){try{return JSON.parse(e)}catch{return null}}function fa(e,t=10){return e.split(`
|
|
10
|
+
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}function op(e){let t=0;for(let n of e)n==="("||n==="["||n==="{"?t+=1:(n===")"||n==="]"||n==="}")&&(t-=1);return t}function sp(e){if(!e||typeof e!="object")return null;let t=e;return t.level!=="error"?null:{file:typeof t.filename=="string"?t.filename:"",line:typeof t.row=="number"?t.row:void 0,column:typeof t.col=="number"?t.col:void 0,code:typeof t.type=="string"?t.type:void 0,message:typeof t.message=="string"?t.message:"",parseBasis:"clj-kondo-json"}}function ap(e,t){let n=typeof e.message=="string"?e.message.replaceAll(/\s+/g," ").trim().slice(0,240):String(t).replaceAll(/\s+/g," ").trim().slice(0,240);return n===""?"git status failed for an unknown reason":`git status failed: ${n}`}function cp(e,t,n,i,r){let o=null;for(let s of e){let a=ka(s,t,n),l=Eu(a,i.get(s.label)??[],a.rawErrors);if(l.status==="failed"){let d=l.errors.length>0?l.errors:a.outputTail;o={depth:r,status:"failed",reason:`${s.label}: ${l.reason}`,errors:d.slice(0,ku)};break}}return o}function lp(e){return e.code==="ENOBUFS"||typeof e.message=="string"&&/maxBuffer|stdout.*buffer/i.test(e.message)}var Pa={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"]},up={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"},pp={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 ke(e,t){let n=t.languages??Jt(e),i=n.map(a=>{let l=_t(tn(a),e);return{...l,language:a,resolvedBinary:l.resolvedBinary??void 0}}),r=Ep(e,n,t),o=ei({semantics:r},"typescript"),s=Xn(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:r,semantic:o,checkers:s,gitAvailable:Ap(e)}}function ct(e,t={}){let n=e.indexers.filter(l=>l.runnable).length,i=mp(e,t,n),r=i!=="unavailable",o=e.languages.map(l=>wp(e,l,{hasIndexedGraph:kp(l,t),runtimeProbe:t.runtimeProbe})),s=o.map(l=>l.cleanupVerification.status),a=hp(s);return{languages:e.languages,matrix:o,relations:gp(o,r),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.`},...Sp(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(l=>`${l.language}: ${l.cleanupVerification.status} (${l.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-impact",label:"Git change mapping",status:e.gitAvailable&&r?"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 mp(e,t,n){return e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial"}function hp(e){return e.length===0||e.every(t=>t==="unavailable")?"unavailable":e.every(t=>t==="available")?"available":"partial"}function gp(e,t){return Ys.map(n=>{let i=Ar.flatMap(o=>{let s=o.relations.filter(a=>a.family===n.family);return s.length===0?[]:[fp(o,s,e,t)]}),r=Zn(i.map(o=>o.status));return{...n,status:r,providerCapabilities:i,reason:r==="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.":r==="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 fp(e,t,n,i){let r=n.map(a=>yp(e,t,a,i)),o=Zn(r.map(a=>a.status)),s=r.filter(a=>a.status!=="unsupported").map(a=>a.language);return{id:e.id,label:e.label,status:o,requirements:e.requirements,subtypes:t.map(a=>a.subtype),languages:r,reason:s.length===0?`Unavailable: requires ${e.requirements.join(", ")}.`:`${o} support for ${s.join(", ")}; analytical ceiling is declared per subtype.`}}function yp(e,t,n,i){let r=e.requirements.filter(s=>!bp(s,n,i));if(r.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${r.join(", ")}.`};let o=Zn(t.map(s=>s.supportCeiling));return{language:n.language,status:o,reason:`${e.label} is available; subtype coverage is ${o}.`}}function bp(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 Zn(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 Sp(e){return vp(e).map(t=>{let n=ei(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Rp(t)} semantic provider`,status:i,evidence:"semantic",reason:xp(t,n)}})}function vp(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of ja(e))t.add(n.language);return[...t].sort((n,i)=>Ea(n)-Ea(i))}function Ea(e){return e==="typescript"?0:1}function Rp(e){return e==="typescript"?"TypeScript":"Rust"}function xp(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 wp(e,t,n){let i=e.indexers.find(u=>u.language===t),r=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=r!=="unavailable",s=Cp(t,n.runtimeProbe),a=Pp(e,t),l=Ip(e,t),d=l.length===0?"unavailable":l.every(u=>u.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:$p(r,i,t)},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:d,evidence:"checker",reason:l.length>0?l.map(u=>u.label).join(", "):`No detected checker covers ${Pa[t].join(", ")} files.`}}}function $p(e,t,n){return e==="available"?`${t?.binaryLabel??n} is runnable${t?.resolvedBinary?` at ${t.resolvedBinary}`:""}.`:e==="partial"?`An indexed ${n} graph is present, but ${t?.binaryLabel??n} is not currently runnable for refresh.`:t?.note??`${n} indexing is not runnable in this project.`}function kp(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Cp(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 jp(t);let n=Aa(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)??Ia(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 Ia(e){let t=up[e];return t?Ft(t):Aa(e)==="regex-only"?"regex":"unavailable"}function Aa(e){let t=pp[e],n=t?or(t):null;return n?.imports??n?.exports??n?.reExports??null}function Ep(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...ma(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let r=cr(e);i.push({language:"rust",available:r.available,dependencyAvailable:r.dependencyAvailable,resolvedBinary:r.resolvedBinary,reason:r.available?r.note:r.reason})}return i}function ja(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ei(e,t){return ja(e).find(n=>n.language===t)}function Pp(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=ei(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 Ip(e,t){let n=new Set(Pa[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function Ap(e){try{return dp("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}function jp(e){return(e?.("clojure")??Ia("clojure"))==="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."}}import Km from"better-sqlite3";import K from"process";import{rmSync as lc}from"fs";import{resolve as Ym}from"path";import{pathToFileURL as Xm}from"url";import{statSync as Tp,watch as Lp}from"fs";function Ta(e){let t=!1,n=!1,i,r=[],o=[...new Set(e)],s=new Map,a=p=>{try{return Tp(p).mtimeMs}catch{return null}},l=()=>{for(let p of o)s.set(p,a(p))},d=()=>o.some(p=>a(p)!==s.get(p));l();let u=()=>{n=!0;let p=i;i=void 0,p?.()};for(let p of o)try{let h=Lp(p,{persistent:!1},u);h.on("error",()=>{}),r.push(h)}catch{}return{wait(p){return t||p<=0?(n=!1,Promise.resolve()):new Promise(h=>{let v=setTimeout(()=>{i===k&&(i=void 0),h()},p),k=()=>{clearTimeout(v),i===k&&(i=void 0),h()};i=k,(n||t||d())&&(n=!1,l(),k())})},close(){if(!t){t=!0;for(let p of r)try{p.close()}catch{}r.length=0}u()}}}import{lstatSync as Mp}from"fs";function Ma(e,t){let n=cn(e);if(n.kind!=="directory")throw new Error(`Watcher root is not a directory: ${e}`);if(!t)return{projectRoot:e,projectDirectory:n};let i=cn(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 qa(e){try{if(!La(e.projectDirectory,cn(e.projectRoot)))return!1;let t=e.gitControlDirectory;return!t||La(t.identity,cn(t.path))}catch{return!1}}function cn(e){let t=Mp(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 La(e,t){return e.device===t.device&&e.inode===t.inode&&e.birthtimeNs===t.birthtimeNs&&e.kind===t.kind}import{fileURLToPath as Dp}from"url";import{existsSync as oi,lstatSync as Np,statSync as Ga,watch as Op}from"fs";import{EventEmitter as Wp}from"events";import{basename as Fp,dirname as Ua,isAbsolute as si,join as pe,relative as Ha,resolve as Va}from"path";import{watch as _p}from"chokidar";import Bp from"ignore";function ti(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}var Qa=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;publicationObservationInvalidated=!1;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=xe(t.config),this.outputDb=t.outputDb??pe(Ki(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=ym(this.projectRoot,Ua(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;let n=Qp(t);this.onStatus=n.onStatus,this.onReindexComplete=n.onReindexComplete,this.onReindexError=n.onReindexError,this.onRefreshSuppressed=n.onRefreshSuppressed,this.onError=n.onError,this.clock=n.clock,Ja.set(this,bm(t.stopTimeoutMs??Qa,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??am(),this.subscriptionFactory=t.subscriptionFactory??Xp,this.budgetInspector=t.budgetInspector??Hs,this.publishedGeneration=t.publishedGeneration??Re,this.indexFreshness=t.indexFreshness??fm,this.lastObservedGeneration=this.readPublishedGeneration(),Vp(this,t),this.gitignoreFilter=os(t.projectRoot),this.extraIgnore=Bp(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),ii(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,dn(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=[...dn(this).closures],r=Up(this),o=this.clock.now()+r;return this.stopPromise=this.finishStop(t,i,n,o,r).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=ni(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,r)=>this.isIgnoredWatchPath(i,r?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(i,r)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(i,r)}),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||!um(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(r=>r!==t),Hp(dn(this),t,r=>this.onError(r));try{this.startSourceWatcher(!0)}catch(r){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;if(Wa(i,this.localCacheWatchPath))return!0;let r=n?`${i}/`:i;return this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t,n){let i=this.relativeWatchPath(n);if(Pm(i)||Wa(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||Im(i))return;i===".scipquery.json"&&Xa(this,this.projectRoot);let r=Za(this,t,i);r!==null&&(r||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:i},r?[{path:i,kind:r}]:void 0,r!==void 0))}relativeWatchPath(t){let n=si(t)?t:pe(this.projectRoot,t);return Ha(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,i=!1){this.publicationObservationInvalidated=!0,this.pendingTrigger=ni(this.pendingTrigger,t),i||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let o of n??[])this.recordPendingChange(o);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let o=this.activeOperation;o&<.get(this)!==o&&(lt.set(this,o),o.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 r=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcilePublishedIndex())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let l=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:l,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,l-this.wallNow())));return}let i=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&i<this.watchConfig.cooldownMs){let l=this.watchConfig.cooldownMs-i;this.dirty=!0;let d=this.wallNow()+l;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},l);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let r=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(r,n,o));this.activeOperation=a,a.completion.then(l=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),ln.set(this,0),this.stopped)return;if(lt.get(this)===a){if(this.restorePendingChangeJournal(o),this.dirty){let u=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:u,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}ii(this),this.lastObservedGeneration=this.readPublishedGeneration();let d=!1;try{d=this.onReindexComplete(l,r,{pendingChanges:this.dirty})===!0}catch(u){this.onError(u instanceof Error?u:new Error(String(u)))}if(this.dirty&&!this.stopped){if(d){let p=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(p),this.setStatus({state:"idle"});return}let u=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:u,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(l=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let d=l instanceof Error?l:new Error(String(l));this.restorePendingChangeJournal(o);let u=Ka(d),p=0;if(u?(p=(ln.get(this)??0)+1,ln.set(this,p),this.dirty=!0,this.pendingTrigger=ni(this.pendingTrigger,r)):ln.set(this,0),!u&<.get(this)!==a&&(this.onReindexError(d,r),this.onError(d)),this.dirty){let h=u?sm(this.watchConfig.cooldownMs,p):this.watchConfig.cooldownMs,v=this.wallNow()+h;this.setStatus({state:"cooldown",until:v,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),lt.get(this)===a&<.delete(this)})}async finishStop(t,n,i,r,o){let s=[],a=t.map(async h=>{try{await h.close()}catch(v){s.push(`watch subscription close failed: ${String(v)}`)}});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 l=a.length,d=a.map(h=>h.finally(()=>{l-=1})),u=await Gp(d,r,this.clock),p=dn(this);return s.push(...p.errors),p.errors=[],u?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${l} operation(s) still pending`),Promise.all(d).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=lm(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=Re(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),i=this.pendingChangesComplete,r=this.pendingChangesIncompleteReason;t||(i=!1,r??="accepted-generation-unavailable");let o={version:1,baseGeneration:t,complete:i,...r?{incompleteReason:r}:{},entries:n};return ti(o)||(o={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),o}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([o,s])=>({path:o,kind:s})),i=this.pendingChangesComplete,r=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let o of t.entries)this.recordPendingChange(o);i||this.markPendingChangesIncomplete(r??"failed-reindex");for(let o of n)this.recordPendingChange(o)}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&&(je(this).stagedIndexEntries=Ba(this.projectRoot,je(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.reconcilePublishedIndex())&&(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}}reconcilePublishedIndex(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting")||!this.hasFreshPublishedIndex())return!1;let n=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),ii(this),this.onRefreshSuppressed({...n,detail:`the published index matches current source${n.detail?` (${n.detail})`:""}`}),this.setStatus({state:"idle"}),!0}hasFreshPublishedIndex(){let t=this.readPublishedGeneration();if(t===null||t===this.lastObservedGeneration&&!this.publicationObservationInvalidated)return!1;let n;try{n=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}return(n==="fresh"||n==="stale")&&(this.lastObservedGeneration=t,this.publicationObservationInvalidated=!1),n==="fresh"}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!n||this.stopped||(this.lastGitState=n,!t))return;let i=t.head!==n.head,r=Am(t,n);if(!i&&!r)return;let o=je(this),s=o.stagedIndexEntries,a=Ba(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let l=xm(this.projectRoot,o.gitReader,t,n,s,a,i,r),d=null;if(l!==null&&(d=jm(this,this.projectRoot,l),d.length===0))return;let u=d?.map(h=>({path:h,kind:oi(pe(this.projectRoot,h))?"change":"delete"})),p=Cm(i,r,n.indexPath);this.scheduleReindex({...p,detail:Em(p.detail,d)},u,u!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??pm(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=mm(t.gitDir);return n?_a(n,t.indexPath):null}readGitStateFromGit(){let t=je(this).gitReader,n=Tn(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=Vi(this.projectRoot,n);return _a(Tn(this.projectRoot,["rev-parse","--verify","HEAD"],t),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Gp(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),r=Math.max(0,t-n.now()),o=null,s=new Promise(l=>{o=n.setTimeout(()=>l(!1),r)}),a=await Promise.race([i,s]);return a&&o&&n.clearTimeout(o),a}var Na=new WeakMap,Ja=new WeakMap,za=new WeakMap,lt=new WeakMap,ln=new WeakMap;function dn(e){let t=Na.get(e);if(t)return t;let n={closures:new Set,errors:[]};return Na.set(e,n),n}function Up(e){return Ja.get(e)??Qa}function je(e){let t=za.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Hp(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(r=>{let o=`watch subscription close failed during polling fallback: ${String(r)}`;e.errors.push(o),n(new Error(o))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function Vp(e,t){za.set(e,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Gi,languages:Ya(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null})}function Qp(e){return{onStatus:e.onStatus??(()=>{}),onReindexComplete:e.onReindexComplete??(()=>{}),onReindexError:e.onReindexError??(()=>{}),onRefreshSuppressed:e.onRefreshSuppressed??(()=>{}),onError:e.onError??(t=>console.error(t.message)),clock:e.clock??Yp}}function Jp(e,t=ve){let{projectRoot:n,config:i,languages:r,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:l,indexerConcurrency:d,trigger:u}=e,p=Z(n),h=Object.keys(p).length>0?p:i,v=Se(n,h),k=h.indexer?.typescript,R=h.indexer?.clojure,C=t(process.pid);if(!C)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:Dp(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:v.indexPath,SCIP_REINDEX_OUTPUT_DB:v.dbPath,...zp(h,k,R,{languages:r,indexerConcurrency:d,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:l}),SCIP_REINDEX_TRIGGER_KIND:u.kind,SCIP_REINDEX_TRIGGER_DETAIL:u.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?ti(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(C)}}}function zp(e,t,n,i){let{languages:r,indexerConcurrency:o,pnpmWorkspaces:s,typescriptProjectMode:a,typescriptProjects:l,clojureConfigPath:d}=i;return{SCIP_REINDEX_LANGUAGES:(e.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(e.indexerConcurrency??o??""),SCIP_REINDEX_PNPM_WORKSPACES:t?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:Kp(t,a,l),SCIP_REINDEX_CLOJURE_CONFIG_PATH:n?.configPath??d??""}}function Kp(e,t,n){return JSON.stringify({projectMode:e?.projectMode??t,projects:e?.projects??n??[],maxHeapMb:e?.maxHeapMb})}var Yp={now:X,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Xp=(e,t)=>Zp(process.platform,t.usePolling)?new ri(e):_p(e,t);function Zp(e,t){return e==="darwin"&&t!==!0}var jt=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},ri=class{events=new Wp;watcher;constructor(t){this.watcher=Op(t,{recursive:!0},(n,i)=>{if(i===null){this.events.emit("error",new jt("Recursive source watcher omitted the changed path."));return}let r=pe(t,i.toString());this.events.emit("all",em(n,r),r)}),this.watcher.on("error",n=>{this.events.emit("error",new jt(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function em(e,t){return e==="change"?"change":oi(t)?Ga(t).isDirectory()?"addDir":"add":"unlink"}var tm=15*6e4,nm=1e3,im=64*1024;function rm(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Oa(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 om(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function Ka(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function sm(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function am(e={}){let t=e.timeoutMs??tm,n=e.terminationGraceMs??nm,i=e.maxOutputBytes??im,r=e.resolveLaunch??Jp;return{start(o){let s=r(o),a=new AbortController,l=rm(),d=!1,u=Kt({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(p=>{if(l={stdoutTail:p.stdout,stderrTail:p.stderr,stdoutTruncated:p.stdoutTruncated,stderrTruncated:p.stderrTruncated},p.status!==0){let h=Oa(new Error(`Reindex worker exited with ${p.signal?`signal ${p.signal}`:`code ${p.status}`}`),l);throw p.status===75?om(h):new Error(h)}return p.durationMs}).catch(p=>{throw Ka(p)?p:(p instanceof zt&&(l={stdoutTail:p.stdout,stderrTail:p.stderr,stdoutTruncated:p.stdoutTruncated,stderrTruncated:p.stderrTruncated}),new Error(Oa(p,l),{cause:p}))}).finally(()=>{d=!0});return{completion:u,async cancel(){d||a.abort();try{await u}catch{}return{state:"exited",diagnostics:l}},diagnostics:()=>l}}}}function ni(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 cm(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function lm(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function dm(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function um(e){return e instanceof jt||dm(e)}var ai=/^[0-9a-f]{40,64}$/i;function Wa(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 pm(e){let t=pe(e,".git");try{let n=Np(t),i;if(n.isDirectory())i=t;else if(n.isFile()){let r=/^gitdir:\s*(.+)\s*$/m.exec(G(t,"Git directory marker"));if(!r?.[1])return null;let o=r[1].trim();i=si(o)?o:Va(e,o)}else return null;return oi(i)?{gitDir:i,indexPath:pe(i,"index")}:null}catch{return null}}function mm(e){let t;try{t=G(pe(e,"HEAD"),"Git HEAD").trim()}catch{return}if(ai.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let i=hm(e);return Fa(e,n)??Fa(i,n)??gm(i,n)}function hm(e){try{let t=G(pe(e,"commondir"),"Git common-directory marker").trim();return t?si(t)?t:Va(e,t):e}catch{return e}}function Fa(e,t){try{let n=G(pe(e,t),"Git reference").trim();return ai.test(n)?n.toLowerCase():void 0}catch{return}}function gm(e,t){try{for(let n of G(pe(e,"packed-refs"),"Git packed references").split(`
|
|
12
|
+
`)){if(n.startsWith("#")||n.startsWith("^"))continue;let i=n.indexOf(" ");if(i===-1)continue;let r=n.slice(0,i);if(n.slice(i+1).trim()===t&&ai.test(r))return r.toLowerCase()}}catch{return}}function fm(e,t,n){let i=Ua(n);return ee(e,t,{dbPath:n,metaPath:pe(i,"meta.json"),cacheDir:i}).state}function _a(e,t){let n={head:e,indexPath:t};try{let i=Ga(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function ym(e,t){let n=Ha(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function bm(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function Ya(e){return e&&e.length>0?[...e]:tt}function Xa(e,t){try{let n=je(e);n.config=Z(t),n.languages=Ya(n.config.languages)}catch{je(e).languages=tt}}function Za(e,t,n){let i=je(e);if(jn(n,i.languages)==="other")return null;let o=cm(t);return n===".scipquery.json"||Qi(n)?(i.typeScriptInputPaths=null,o):Sm(n,i.languages)?Tm(e,i.typeScriptInputPaths,n,o):o}function ii(e){let t=je(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=vm(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??ec(e)}function ec(e){let t=je(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,i=Ji(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=i,i}catch{return t.typeScriptInputPaths=null,null}}function Sm(e,t){if(!t.includes("typescript"))return!1;let n=jn(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function vm(e,t,n){try{let i=tr(G(Se(e,t).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let r=Wi(i.metadata.fingerprint);return!r||!Rm(r,n,t)?null:new Set(r.files.map(o=>o.path))}catch{return null}}function Rm(e,t,n){let i=er(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 xm(e,t,n,i,r,o,s,a){let l=new Set;if(s){if(!n.head||!i.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(d.kind!=="success")return null;for(let u of wm(d.output))l.add(u)}if(a){if(r===null||o===null)return null;for(let d of km(r,o))l.add(d)}return[...l].sort()}function Ba(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?$m(n.output):null}function wm(e){return e.split("\0").filter(t=>t.length>0)}function $m(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 r=t[i],o=t[i+1];if(!r.startsWith(":")||!o)return null;n.set(o,r)}return n}function km(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function Cm(e,t,n){return e&&t?{kind:"watch-git-state",detail:"HEAD and index changed"}:e?{kind:"watch-git-head",detail:"HEAD changed"}:{kind:"watch-git-index",detail:n??"index changed"}}function Em(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}function Pm(e){return!e||e===".."||e.startsWith("../")}function Im(e){return e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||Fp(e).startsWith(Gs)}function Am(e,t){return e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize}function jm(e,t,n){return n.includes(".scipquery.json")&&Xa(e,t),n.filter(i=>Za(e,"add",i)!==null)}function Tm(e,t,n,i){if(!t)return i;let r=t.has(n);if(i!=="add")return r?i:null;if(r)return"change";let o=ec(e);return o?o.has(n)?"add":null:i}import{fileURLToPath as Lm}from"url";var pn=class{constructor(t){this.opts=t}opts;running;cancellation;closed=!1;cleanupFailure;start(){if(this.closed||this.running||this.cleanupFailure)return;let t=new AbortController;this.cancellation=t,this.running=this.sweep(t.signal).catch(n=>{let i=n instanceof Error?n:new Error(String(n));if(i instanceof zt&&!i.reaped&&(this.cleanupFailure=i),!t.signal.aborted)try{this.opts.onError(i)}catch(r){this.cleanupFailure=r instanceof Error?r:new Error(String(r))}}).finally(()=>{this.running=void 0})}async close(){if(this.closed=!0,this.cancellation?.abort(),await this.running,this.cleanupFailure)throw this.cleanupFailure}async sweep(t){let n=await(this.opts.run??Kt)({command:process.execPath,args:["--max-old-space-size=512",Lm(this.opts.workerUrl??new URL("./repository-cache-worker.js",import.meta.url)),this.opts.projectRoot,this.opts.cliVersion],label:"repository cache maintenance",timeoutMs:fs.analysis,maxStdoutBytes:8192,maxStderrBytes:8192,signal:t});if(n.status!==0)throw new Error(`Repository cache maintenance exited with ${n.status??n.signal}: ${n.stderr.trim()}`)}};var mn=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=It(t)}initializeAfterOwnershipAcquired(){let t=ta(this.root),n=na(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:n}}observeLegacyRequest(t,n){Xs(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=Zs(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(Mm(i)),!0}catch(r){throw zn(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),r}}completeActive(){return this.active?(ea(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(zn(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=It(this.root)}};function Mm(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 Wm}from"os";import{randomUUID as Fm}from"crypto";import{rmSync as _m}from"fs";import{Worker as Bm}from"worker_threads";var hn=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(r){this.closed=!0,this.options.onFatal(ci(r))}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(r){this.failActiveAfterTermination(li(r),!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=qm(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 r=this.active,o;try{o=Nm(this.options,r,i)}catch(s){this.closed=!0,this.clearTimer(r.timer),this.options.onFatal(ci(s));return}this.releaseActive(r),o?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 r=(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 l=this.ensureWorker();i.timer=this.deadlineTimer(i.request),l.postMessage({kind:"request",...i.request});return}catch(l){let d=`Cold Worker retry failed: ${li(l)}`;if(i.workerFailureReasons.push(d),t=`${t} ${d}`,!await this.terminateWorker())return}}let a=Om(i.workerFailureReasons,t);try{this.options.onReject(i.request,a)}catch(l){this.closed=!0,this.options.onFatal(ci(l));return}this.releaseActive(i)})();this.activeFailure=r;try{await r}finally{this.activeFailure===r&&(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: ${li(i)}`,{cause:i})),!1}finally{n===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function qm(e){if(!e||typeof e!="object")return null;let t=e;return t.kind!=="response"||typeof t.requestId!="string"||!("status"in t)||!Dm(t)?null:t}function ci(e){return e instanceof Error?e:new Error(String(e))}function li(e){return e instanceof Error?e.message:String(e)}function Dm(e){if(e.ok===!0){if(!("result"in e)||"error"in e)return!1}else if(e.ok===!1){if("result"in e||typeof e.error!="string")return!1}else return!1;return!0}function Nm(e,t,n){return e.onStatus(n.status),n.ok?e.onComplete(t.request,n.result,n.status):e.onReject(t.request,n.error,n.status),e.retireAfterResponse?.(n.status)??!1}function Om(e,t){return e.length===0?t:[...new Set([...e,t])].join(" Cold Worker retry: ")}var Gm=6e4,Um=10*6e4;function tc(e){let t=e.maxActiveSessions??8,n=e.workerSoftMemoryMb??ac(e.workerHeapMb),i=()=>({protocolVersion:rn,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 ic({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:i,parseEnvelope:Qs,createWorker:()=>cc(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath,maxActiveSessions:t,softMemoryLimitMb:n}),complete(r,o,s,a){Wn(e.paths,r,{ok:!0,protocolVersion:rn,id:o.id,baseGeneration:o.baseGeneration,response:s},{nowMs:a,limits:e.limits})},reject(r,o,s,a){Fn(e.paths,r,{ok:!1,protocolVersion:rn,id:o,error:s},s,{nowMs:a,limits:e.limits})},idleTtlMs:e.workerIdleMs??Um,maxWorkerFailureRetries:1,retireAfterResponse:r=>r.retireRequested===!0,statusWhenWorkerAbsent:r=>({...r,state:"idle",activeSessions:0,heapUsedBytes:0,retireRequested:!1}),onBusy:e.onBusy,onFatal:e.onFatal})}function nc(e){let t=e.workerSoftMemoryMb??ac(e.workerHeapMb),n=()=>({protocolVersion:Vt,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0,softMemoryLimitBytes:t*1024*1024,retireRequested:!1});return ic({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:n,parseEnvelope:wr,createWorker:()=>cc(e,{kind:"semantic",projectRoot:e.projectRoot,softMemoryLimitMb:t}),complete(i,r,o,s){Wn(e.paths,i,{ok:!0,protocolVersion:Vt,id:r.id,generation:r.generation,response:o},{nowMs:s,limits:e.limits})},reject(i,r,o,s){Fn(e.paths,i,{ok:!1,protocolVersion:Vt,id:r,error:o},o,{nowMs:s,limits:e.limits})},idleTtlMs:Gm,maxWorkerFailureRetries:1,retireAfterResponse:i=>i.retireRequested===!0,statusWhenWorkerAbsent:i=>({...i,state:"idle",heapUsedBytes:0,retireRequested:!1}),onBusy:e.onBusy,onFatal:e.onFatal})}function ic(e){let t=e.now??Date.now,n=ve(process.pid),i={pid:process.pid,...n?{processIdentity:n}:{}},r=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${Fm()}`,o={...e.limits,maxBatch:1},s=null,a=e.initialStatus(),l=!1,d=v=>{l=!0,e.onFatal(v)},u=new hn({name:e.name,createWorker:e.createWorker,now:t,idleTtlMs:e.idleTtlMs,maxWorkerFailureRetries:e.maxWorkerFailureRetries,retireAfterResponse:e.retireAfterResponse,onComplete(v,k,R){let C=p(v.requestId);a=R;let V=t();try{e.complete(C.claim,C.envelope,k,V)}catch(J){if(!(J instanceof Nn))throw J;try{e.reject(C.claim,C.envelope.id,J.message,V)}catch(Ee){if(!(Ee instanceof Nn))throw Ee;_m(C.claim.path,{force:!0})}}h(C)},onReject(v,k,R){let C=p(v.requestId);R!==void 0&&(a=R),e.reject(C.claim,C.envelope.id,k,t()),h(C)},onStatus(v){a=v},onFatal:d});return{poll(){if(l||!u.canAccept())return 0;let v=hr(e.paths,{ownerId:r,nowMs:t(),limits:o,owner:i,liveness:{isProcessAlive:Bt,readProcessIdentity:ve}})[0];if(!v)return 0;let k=v.requestId;try{let R=e.parseEnvelope(gr(v,o));if(k=R.id,R.id!==v.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(R.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(s={claim:v,envelope:R},e.onBusy?.(R.deadlineAtMs),!u.start({requestId:R.id,deadlineAtMs:R.deadlineAtMs,payload:R}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(R){let C=zm(R);try{e.reject(v,k,C,t()),s?.claim===v&&h(s)}catch(V){d(Jm(V))}}return 1},status(){return{...u.hasWorker()||!e.statusWhenWorkerAbsent?a:e.statusWhenWorkerAbsent(a),mailbox:fr(e.paths)}},async close(v){await u.close(v)}};function p(v){let k=s;if(!k||k.envelope.id!==v)throw new Error(`${e.name} parent lost the active mailbox claim.`);return k}function h(v){s===v&&(s=null,e.onBusy?.(void 0))}}var rc=6144;function oc(){let e=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(e)&&e>0?e:rc}var Hm=.6;function sc(e,t=Vm()){let n=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);if(Number.isFinite(n)&&n>0)return n;let i=Math.ceil(vr+e*Rr),r=Math.floor(t*Hm/(1024*1024));return Math.max(rc,Math.min(i,r))}function Vm(e=Qm,t=Wm()){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 Qm(e){try{return He(e,{maxBytes:_i,inputKind:"cgroup memory limit"})}catch{return null}}function ac(e){return Math.max(1,Math.floor((e??oc())*.9))}function cc(e,t){if(e.createWorker)return e.createWorker(t);let n=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new Bm(n,{workerData:t,resourceLimits:{maxOldGenerationSizeMb:e.workerHeapMb??oc()}})}function Jm(e){return e instanceof Error?e:new Error(String(e))}function zm(e){return e instanceof Error?e.message:String(e)}var dc=2e3,Zm=5e3,eh=5e3,th=6e4,nh=10,ih=50,rh=1e4;function oh(e,t=1){return dr(e,t,nh,ih,rh,8)}function sh(e,t){let n;return{begin(){return n||(t.requestStop(),t.closeWake(),n=e.stop(),n.catch(()=>{})),n}}}async function ah(e,t){let n=t.processIndexRequests(),i=t.processSemanticRequests(),r=n+i,o=r>0?0:e+1;if(t.afterMailboxPoll({indexRequests:n,semanticRequests:i,processedRequests:r}),t.shouldStop())return{indexRequests:n,semanticRequests:i,processedRequests:r,consecutiveIdlePolls:o,stopped:!0};let s=oh(r,o);return await t.wait(s),{indexRequests:n,semanticRequests:i,processedRequests:r,consecutiveIdlePolls:o,stopped:!1,delayMs:s}}function ch(e){return e==="fresh"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}function lh(e){oa(e.statePath,{version:1,protocolVersion:yr,pid:K.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 dh(e){let t=0,n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY;function s(a){let l=sa(e.activityPath);l&&e.updateObservedActivity(l.atMs,a),l?.refreshRequestedAtMs!==void 0&&l.refreshRequestedAtMs>t&&(t=l.refreshRequestedAtMs,e.refreshCoordinator.observeLegacyRequest(l.refreshRequestedAtMs,l.refreshDetail??"stale index observed by a legacy command"))}return({processedRequests:a})=>{let l=X();if(l-i>=eh&&(i=l,!qa(e.worktreeLiveness))){e.requestStop();return}l-o>=th&&(o=l,_n(e.indexMailboxPaths),_n(e.semanticMailboxPaths)),l-r>=da&&(r=l,e.requestCacheSweep()),l-n>=Zm&&(n=l,s(l)),e.refreshCoordinator.poll(e.watcherStatus(),d=>{e.recordActivity(),e.requestRefresh(d)}),a>0&&(e.recordActivity(),e.persistState(!0,"visibility")),e.persistState()}}async function uh(e){let t,n=0,i=!1,r,o;K.once("SIGINT",e.stopSignal),K.once("SIGTERM",e.stopSignal);try{e.watcher.start();let s=e.initializeFreshness();for(e.recordActivity(),e.markReady(),e.persistState(!0),t=setInterval(()=>{try{e.persistState()}catch(a){i=!0,r=a;try{e.stopSignal()}catch(l){r=new AggregateError([a,l],"Watch heartbeat and stop request both failed.")}}},dc),t.unref?.(),s&&e.requestRefresh(s);!i&&!e.stopRequested();){let a=await ah(n,{processIndexRequests:e.processIndexRequests,processSemanticRequests:e.processSemanticRequests,afterMailboxPoll:e.afterMailboxPoll,shouldStop:e.shouldStop,wait:e.wait});if(n=a.consecutiveIdlePolls,a.stopped)break}}catch(s){i=!0,r=s}finally{K.off("SIGINT",e.stopSignal),K.off("SIGTERM",e.stopSignal),t!==void 0&&clearInterval(t),o=await ph(e)}vh(e,i,r,o)}async function ph(e){let[t,n]=await Promise.allSettled([Promise.resolve().then(()=>e.shutdown.begin()),Promise.resolve().then(()=>e.closeLanes())]),i=[t,n].flatMap(r=>r.status==="rejected"?[r.reason instanceof Error?r.reason.message:String(r.reason)]:[]);try{return mh(e,t.status==="fulfilled"?t.value:{state:"degraded",reasons:[]},i)}catch(r){return r instanceof Error?r:new Error(String(r))}}function mh(e,t,n=[]){let i=[...n,...t.state==="stopped"?[]:t.reasons],r=e.mailboxFatalError();if(r&&i.push(r.message),i.length>0)return e.finalizeDegraded(i);e.finalizeStopped()}function hh(e){try{let t=new Km(e,{readonly:!0,fileMustExist:!0});try{return t.prepare("SELECT count(*) AS documents FROM documents").get().documents}finally{t.close()}}catch{return 0}}function gh(e){let t=e.config.indexer?.typescript,n=t?.workerHeapMb??sc(hh(e.dbPath)),i=nc({paths:e.semanticPaths,projectRoot:e.projectRoot,workerHeapMb:n,onBusy:e.onSemanticBusy,onFatal:e.onFatal}),r=tc({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:r}}async function di(e,t,n={}){let i=ra(e,t),r=i.projectRoot,o=i.worktreeKind==="git"?fh(r,i.worktreeId):void 0,s=Ma(r,o),a=Z(r);a.watch={...a.watch,...n};let l=xe(a);if(!l.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let d=Se(r,a),u=Ht(d.cacheDir),p=ve(K.pid),h=aa(u.lockPath,r,{readProcessIdentity:R=>R===K.pid?p:ve(R)});if(!h.acquired)return;let v=!1,k;try{let R=new mn(u.refreshRequestsPath,{retryDelayMs:Math.max(1e3,l.cooldownMs)});R.initializeAfterOwnershipAcquired();let C=Date.now(),V=X(),J=C,Ee=V,qe={state:"idle"},Fe,Xe,se,fe,De=nn(d.dbPath),_e=!1,Nt=!1,ft=Number.NEGATIVE_INFINITY,yt,Be,ye=xr(d.cacheDir),Ge=Vs(d.cacheDir);On(ye),On(Ge);let bt=Ta([Ge.pendingDir,Ge.legacyRequestDir,ye.pendingDir,ye.legacyRequestDir,u.refreshRequestsPath]);k=()=>bt.close();let M=(I=!1,Ue=I?"durable":"visibility")=>{if(!Nt)return;let An=Date.now(),et=X();!I&&et-ft<dc||(ft=et,lh({statePath:u.statePath,durability:Ue,processIdentity:p,projectRoot:r,worktreeId:i.worktreeId,cliVersion:t,startedAtMs:C,nowMs:An,lastActivityAtMs:J,idleTimeoutMs:l.idleTimeoutMs,watcherStatus:qe,indexGeneration:Fe,lastRefresh:Xe,lastError:se,reindexActivity:De,refreshCoordinator:R,semanticLane:Pn,indexLane:In,semanticBusyUntilMs:yt,indexBusyUntilMs:Be}))},Ze=()=>{J=Date.now(),Ee=X()},Ni=new pn({projectRoot:r,cliVersion:t,onError(I){se={at:new Date().toISOString(),message:I.message},M(!0,"visibility")}}),pu=I=>{Ze(),fe??=I,se={at:new Date().toISOString(),message:I.message},M(!0,"visibility")},{semanticLane:Pn,indexLane:In}=gh({semanticPaths:ye,indexPaths:Ge,projectRoot:r,dbPath:d.dbPath,config:a,onSemanticBusy(I){yt=I===void 0?void 0:I+5e3,M(!0,"visibility")},onIndexBusy(I){Be=I===void 0?void 0:I+5e3,M(!0,"visibility")},onFatal:pu}),Ot=new un({projectRoot:r,config:{...a,watch:l},outputDb:d.dbPath,languages:a.languages,onStatus(I){qe=I,I.state!=="idle"&&(Fe=void 0),I.state!=="idle"&&Ze(),M(!0)},onReindexComplete(I,Ue,An){Ze();let et=An?.pendingChanges!==!1?ee(r,a,d):ps(d);return Xe=et.lastRefresh,Fe=et.state==="fresh"?Re(d.dbPath)??void 0:void 0,De=nn(d.dbPath),R.completeActive(),se=void 0,M(!0),et.state==="fresh"},onReindexError(){R.failActive()},onRefreshSuppressed(I){let Ue=Us(d.dbPath,I);Ue.state==="failed"&&(se={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${Ue.reason}`},M(!0,"visibility")),De=nn(d.dbPath)},onError(I){Ze(),Fe=void 0,se={at:new Date().toISOString(),message:I.message},M(!0)}}),Oi=sh(Ot,{requestStop(){_e=!0},closeWake(){bt.close()}}),mu=()=>{Oi.begin()},hu=dh({worktreeLiveness:s,indexMailboxPaths:Ge,semanticMailboxPaths:ye,requestCacheSweep:()=>Ni.start(),activityPath:u.activityPath,refreshCoordinator:R,watcherStatus:()=>qe,requestRefresh:I=>Ot.requestRefresh({kind:"watch-demand",detail:I},{immediate:!0}),requestStop:()=>{_e=!0},recordActivity:Ze,updateObservedActivity(I,Ue){I<=J||(J=I,Ee=Ue)},persistState:M});v=!0,await uh({watcher:Ot,shutdown:Oi,stopSignal:mu,initializeFreshness(){let I=ee(r,a,d);return Xe=I.lastRefresh,Fe=I.state==="fresh"?Re(d.dbPath)??void 0:void 0,ch(I.state)},markReady:()=>{Nt=!0},recordActivity:Ze,persistState:M,requestRefresh:I=>Ot.requestRefresh(I,{immediate:!0}),stopRequested:()=>_e,processIndexRequests:()=>In.poll(),processSemanticRequests:()=>Pn.poll(),afterMailboxPoll:hu,shouldStop:()=>_e||fe!==void 0||la({watcher:qe,lastActivityAtMs:Ee,nowMs:X(),idleTimeoutMs:l.idleTimeoutMs}),wait:I=>bt.wait(I),closeLanes:()=>Promise.all([Pn.close("TypeScript semantic service stopped before completing the request."),In.close("TypeScript index service stopped before completing the request."),Ni.close()]).then(()=>{}),mailboxFatalError:()=>fe,finalizeStopped(){try{lc(u.statePath,{force:!0})}finally{try{lc(u.activityPath,{force:!0})}finally{h.release()}}},finalizeDegraded(I){return se={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${I.join("; ")}`},M(!0),new Error(se.message)}})}finally{if(!v)try{k?.()}finally{h.release()}}}function fh(e,t){let n=Hi(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 yh(e,t={report:n=>console.error(n),exit:n=>K.exit(n)}){return t.report(`watch-service: ${ys(e instanceof Error?e.message:String(e))}`),t.exit(1)}var bh=K.argv[1]?Xm(Ym(K.argv[1])).href:null;if(bh===import.meta.url){let e=K.argv[2],t=K.argv[3],n=Sh(K.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),K.exitCode=1;else try{await di(e,t,n)}catch(i){yh(i)}}function Sh(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function vh(e,t,n,i){let r=e.mailboxFatalError();if(!t&&r&&(t=!0,n=r),t&&i)throw new AggregateError([n,i],"Watch service execution and shutdown both failed.");if(t)throw n;if(i)throw i}import{execFileSync as Rh}from"child_process";import{existsSync as fn,lstatSync as xh,realpathSync as pc}from"fs";import{dirname as wh,join as Oe}from"path";var uc=["- `scip-query system --source [module]` \u2014 Module files and dependencies; --source adds a first-use inventory, exports, policy and findings without an index","- `scip-query context <target>` \u2014 Compiler-backed context for a symbol, file, or module","- `scip-query evidence` \u2014 Traverse selected typed relationships around exact referents; recover source separately when needed","- `scip-query health` \u2014 Find concrete TS/JS complexity, duplication, and dependency issues without an index","- `scip-query review` \u2014 Review current TS/JS changes against a Git commit, including new and untracked functions","- `scip-query diff-impact` \u2014 Map changed symbols and downstream consumers from the current git diff","- `scip-query architecture` \u2014 Evaluate project-owned architectural boundaries and dependency rules","- Use `capabilities --matrix` only when a named claim depends on uncertain provider support."],gn=[{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 observed static caller counts",evidenceCeiling:"Source/compiler-grounded entry evidence and observed static 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.","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, optional same-file call closure, file export surfaces, and omitted-local ledgers",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 Te="<!-- scip-query:agent-setup:begin -->",dt="<!-- scip-query:agent-setup:end -->",$h="# scip-query:agent-setup",ui=[".codex/hooks.json",".claude/settings.local.json"],mc="# scip-query:local-agent-hooks:begin",hc="# scip-query:local-agent-hooks:end",Sc="hook-architecture-stop";function vc(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 yn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return kh(e,n),t.architectureHook!==!1&&Ph(e,n,t.architectureHook),n}function Rc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return fc(e,"AGENTS.md",t,n),xc(e,"CLAUDE.md")?n.unchanged.push("CLAUDE.md"):fc(e,"CLAUDE.md",t,n),Ih(e,t,n),Eh(e,t,n),n}function kh(e,t){let n=[Te,"## scip-query","","Use ordinary file tools for source search and reading. Use scip-query for code relationships, module structure, quality findings and change impact.","",...uc,"- Before a substantial change, identify the existing implementation path, comparable features, shared owners and affected consumers. Document reuse and extension choices in the plan. Confirm behavior with ordinary source reads and tests.","- Use `context` for reuse/impact candidates and `evidence` for a specific relationship question. Existing file:line locations are valid roots; symbol lookup and `outline` are optional when parsed identity or nesting helps. Avoid repeating source through `code` or `inspect` when ordinary file tools already establish it.","- Example: `scip-query evidence --at src/service.ts:42 --edge execution --direction incoming --depth 1 --max-edges 30` finds caller evidence. Use outgoing execution for callees, dataflow for values, runtime for handoffs, or dependencies for imports. Batch related roots; choose other families only for a named question.","- Exact observations are facts within their supported scope; derived observations are computed; candidates need confirmation. Containment does not establish business ownership. Material missing, stale or unsupported evidence prevents stronger claims and claims of absence.","- After a nontrivial edit use `scip-query review --base HEAD` and `scip-query diff-impact`. Check `architecture` when module dependencies changed; use `health --indexed` only for a relevant specialist question. Confirm findings before fixing them and preserve behavior in tests.","- Read saved results selectively with normal file tools. Use `--json --json-output <path>` for programmatic filtering. A displayed excerpt is enough only for facts it establishes; recover omitted details when they could change the decision. Do not drain pages or read whole files merely because they exist.","- Load `$scip-query` with the workflow needed: `$scip-explore`, `$scip-plan`, `$scip-architecture-review`, `$scip-integrity-audit`, or `$scip-setup`. Skip workflow ceremony for a simple lookup. Respect disabled watchers and configured rebuild policy.","- Commit relevant `.scipquery/suppressions/*.json` records with justified changes. Do not lower thresholds or widen architecture rules to clear a report. Do not commit local agent-tool settings.",dt].join(`
|
|
13
|
+
`);if(gc(e,"AGENTS.md",n,t),xc(e,"CLAUDE.md")){t.unchanged.push("CLAUDE.md");return}let i=[Te,"@AGENTS.md",dt].join(`
|
|
14
|
+
`);gc(e,"CLAUDE.md",i,t,r=>r.includes("@AGENTS.md")&&!r.includes(Te))}function xc(e,t){let n=Oe(e,t);try{return xh(n).isSymbolicLink()?pc(n)===pc(Oe(e,"AGENTS.md")):!1}catch{return!1}}function gc(e,t,n,i,r){let o=Oe(e,t),s=!1,a=pi(o,t,i,l=>{if(r?.(l.text))return s=!0,{kind:"unchanged"};let d=Ch(l.text,n);return d===l.text?{kind:"unchanged"}:{kind:"write",text:d,...l.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?i.unchanged.push(t):i.written.push(t))}function fc(e,t,n,i){let r=Oe(e,t);if(n.dryRun){if(!fn(r)){i.unchanged.push(t);return}try{let s=G(r,"agent instruction file");s.includes(Te)?(yc(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 o=pi(r,t,i,s=>{if(!s.revision.exists||!s.text.includes(Te))return{kind:"unchanged"};let a=yc(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});o&&(o.changed?i.removed.push(t):i.unchanged.push(t))}function Ch(e,t){if(wc(e)==="present"){let i=new RegExp(`${Te}[\\s\\S]*?${dt}`);return e.replace(i,t)}return e.length>0?`${e.replace(/\n*$/,`
|
|
15
|
+
|
|
16
|
+
`)}${t}
|
|
17
|
+
`:`${t}
|
|
18
|
+
`}function yc(e){wc(e);let t=new RegExp(`${Te}[\\s\\S]*?${dt}`),n=e.replace(t,"").replace(/\n{3,}/g,`
|
|
19
|
+
|
|
20
|
+
`).trim();return n.length===0?"":`${n}
|
|
21
|
+
`}function wc(e){let t=e.split(Te).length-1,n=e.split(dt).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(Te)<e.indexOf(dt))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function pi(e,t,n,i){try{return it(e,i,{maxRetries:0})}catch(r){n.skipped.push({target:t,reason:r instanceof Error?r.message:String(r)});return}}function Eh(e,t,n){let i=".git/hooks/pre-commit",r=Oe(e,i);if(!fn(r)){n.unchanged.push(i);return}if(!G(r,"pre-commit hook").includes($h)){n.skipped.push({target:i,reason:"pre-commit hook is not managed by scip-query"});return}if(t.dryRun){n.removed.push(i);return}pi(r,i,n,()=>({kind:"delete"}))?.changed&&n.removed.push(i)}function Ph(e,t,n={}){let i=(n.inspectReadiness??Ah)(e);if(i.state==="not-configured")return;if(i.state==="blocked"){t.skipped.push({target:"architecture Stop hook",reason:i.reason});return}let r=n.commandPrefix??"scip-query";for(let o of ui){if(Pc(e,o)){t.skipped.push({target:o,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}Cc(Oe(e,o),o,t,s=>jh(s,r))}Mh(e,t)}function Ih(e,t={},n){for(let i of ui){let r=Oe(e,i);if(fn(r)){if(Pc(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 o=Lh(r);JSON.stringify(bc(o))!==JSON.stringify(o)&&n.removed.push(i)}catch(o){n.skipped.push({target:i,reason:bn(o)})}continue}Cc(r,i,n,bc,!0)}}}function Ah(e){let t=Z(e);if(!t.architecture||t.architecture.boundaries.length===0)return{state:"not-configured"};let n=Se(e,t),i=ee(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 r;try{r=ms(e);let o=Qe(nt(r));return o.length>0?{state:"blocked",reason:`the current architecture baseline has ${o.length} enforced violation(s); make the declared policy clean before installing the Stop hook`}:{state:"ready"}}catch(o){return{state:"blocked",reason:bn(o)}}finally{r?.close()}}function jh(e,t="scip-query"){let n=$c(e.hooks),i=Array.isArray(n.Stop)?n.Stop:[];return{...e,hooks:{...n,Stop:[...kc(i),{hooks:[{type:"command",command:`${t} ${Sc}`,timeout:120,statusMessage:"Checking architecture boundaries"}]}]}}}function bc(e){let t=$c(e.hooks),n=Array.isArray(t.Stop)?t.Stop:[],i=kc(n),r={...t};i.length>0?r.Stop=i:delete r.Stop;let o={...e};return Object.keys(r).length>0?o.hooks=r:delete o.hooks,o}function $c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function kc(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Th(n)):[]})).filter(t=>t.hooks.length>0)}function Th(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&new RegExp(`(?:^|\\s)${Sc}$`,"u").test(t)}function Cc(e,t,n,i,r=!1){try{it(e,s=>{let a=s.revision.exists?Ec(s.text,e):{},l=i(a);return JSON.stringify(l)===JSON.stringify(a)?{kind:"unchanged"}:r&&Object.keys(l).length===0?{kind:"delete"}:{kind:"write",text:`${JSON.stringify(l,null,2)}
|
|
22
|
+
`,mode:384}}).changed?"written"in n?n.written.push(t):n.removed.push(t):r||n.unchanged.push(t)}catch(o){n.skipped.push({target:t,reason:bn(o)})}}function Lh(e){return Ec(G(e,"agent hook settings"),e)}function Ec(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 Pc(e,t){try{return Rh("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function Mh(e,t){let n=Oe(e,".git","info","exclude");if(!fn(wh(n))){t.skipped.push({target:".git/info/exclude",reason:"Git metadata was not found; local hook files may appear as untracked"});return}try{it(n,i=>{let r=new RegExp(`${mc}[\\s\\S]*?${hc}\\n?`,"gu"),o=i.text.replace(r,"").replace(/\n*$/u,""),s=[mc,...ui.map(l=>`/${l}`),hc].join(`
|
|
23
|
+
`),a=`${o}${o?`
|
|
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:bn(i)})}}function bn(e){return e instanceof Error?e.message:String(e)}import{existsSync as mg}from"fs";import{randomUUID as hg}from"crypto";import{existsSync as hi,mkdirSync as Ac,rmSync as qh}from"fs";import{homedir as Dh}from"os";import{dirname as jc,isAbsolute as Nh,join as Sn,relative as Ic,resolve as Oh}from"path";function Tc(e,t){return t?Oh(e,t):Sn(e,"docs","scip-query")}function Lc(e,t,n={}){let i=Sn(Tc(e,n.dossierDir),"health-dossier.attempt.json"),r=Wh(i);Ac(jc(i),{recursive:!0});let o=`${JSON.stringify(t,null,2)}
|
|
27
|
+
`;return hi(i)?Mn(i,o,{durability:"durable"}):qn(i,o,{durability:"durable"}),{attemptPath:i,attempt:t,interrupted:r}}function Mc(e){qh(e.attemptPath,{force:!0})}function Wh(e){if(!hi(e))return null;try{let t=JSON.parse(G(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 qc(e,t={}){let n=Tc(e.projectRoot,t.dossierDir),i={markdownPath:Sn(n,"health-dossier.md"),jsonPath:Sn(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},r=Jh({...e,generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return Hh(i.markdownPath,Fh(r),i),Vh(i.jsonPath,r,i),i}catch(o){return{...i,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Fh(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health report: ${gi(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","",..._h(e),"","## Blocked Or Unavailable Checks","",...Bh(e),"","## Setup Checks: Operation Results and Readiness","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} [${n.basis??"unspecified basis"}] \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...Gh(e),"","## JSON","",`Machine-readable report: \`${Uh(e)}\``,""].join(`
|
|
28
|
+
`)}`}function _h(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 Bh(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 Gh(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 gi(e){return e.available?"available; findings require source confirmation":`unavailable (${e.unavailableReason??"not checked"})`}function Uh(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Hh(e,t,n){Dc(e,t,n,"health dossier Markdown",i=>i===t)}function Vh(e,t,n){let i=`${JSON.stringify(t,null,2)}
|
|
29
|
+
`;Dc(e,i,n,"health dossier JSON",r=>Qh(r,i))}function Dc(e,t,n,i,r){Ac(jc(e),{recursive:!0});let o=hi(e)?G(e,i):null;if(o!==null&&r(o)){n.unchanged.push(e);return}o===null?qn(e,t,{durability:"durable"}):Mn(e,t,{durability:"durable"}),n.written.push(e)}function Qh(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 Jh(e,t){return mi(e,t)}function mi(e,t){return typeof e=="string"?zh(e,t):Array.isArray(e)?e.map(n=>mi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,mi(i,t)])):e}function zh(e,t){if(e===t)return".";if(!Nh(e))return e;let n=Ic(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Ic(Dh(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{existsSync as vn,mkdirSync as Kh,symlinkSync as Yh,readlinkSync as fi,unlinkSync as yi,readdirSync as Nc}from"fs";import{join as Ce,dirname as ut,resolve as We,relative as Xh,isAbsolute as Zh}from"path";import{homedir as Oc,platform as eg}from"os";import{fileURLToPath as Wc}from"url";var tg=eg()==="win32",Fc=["scip-query","scip-explore","scip-plan","scip-architecture-review","scip-integrity-audit","scip-setup"],ng=Fc;var _c=Fc;function Rn(e={}){let t=e.quiet?()=>{}:console.log,n=Wc(import.meta.url),i=We(ut(n),"..","skills"),r=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Oc(),o=[Ce(r,".claude","skills"),Ce(r,".codex","skills"),Ce(r,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of o){let l=ut(a);if(!vn(l))continue;Kh(a,{recursive:!0});let d=Gc(a);rg(a,i,d,s,t);for(let u of e.all?_c:ng)ig(a,i,d,u,s,t)}return s}function ig(e,t,n,i,r,o){let s=Ce(t,i),a=Ce(e,i);if(!vn(s)){r.skipped.push(`${n}/${i}`);return}let l=null;try{l=We(ut(a),fi(a))}catch{if(vn(a)){r.skipped.push(`${n}/${i}`),o(` skip: ${i} \u2192 ${n} (exists, not a symlink)`);return}}if(l===We(s)){r.alreadyLinked.push(`${n}/${i}`),o(` ok: ${i} \u2192 ${n} (already linked)`);return}if(l&&!bi(l,t)){r.skipped.push(`${n}/${i}`),o(` skip: ${i} \u2192 ${n} (symlink outside this scip-query package)`);return}l&&yi(a),Yh(s,a,tg?"junction":"dir"),r.installed.push(`${n}/${i}`),o(` done: ${i} \u2192 ${n}`)}function rg(e,t,n,i,r){let o=new Set(_c);for(let s of Nc(e)){if(o.has(s))continue;let a=Ce(e,s),l;try{l=We(ut(a),fi(a))}catch{continue}bi(l,t)&&(yi(a),i.pruned.push(`${n}/${s}`),r(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Bc(e={}){let t=Wc(import.meta.url),n=We(ut(t),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Oc(),r=[Ce(i,".claude","skills"),Ce(i,".codex","skills"),Ce(i,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of r){if(!vn(s))continue;let a=Gc(s);for(let l of Nc(s))og(s,l,n,a,e,o)}return o}function og(e,t,n,i,r,o){let s=Ce(e,t),a;try{let l=fi(s);a=We(ut(s),l)}catch{o.left.push(`${i}/${t} (not a symlink)`);return}if(!bi(a,n)){o.left.push(`${i}/${t} (symlink outside scip-query package)`);return}if(o.removed.push(`${i}/${t}`),!r.dryRun)try{yi(s)}catch(l){o.skipped.push(`${i}/${t} (${l instanceof Error?l.message:String(l)})`)}}function bi(e,t){let n=Xh(We(t),We(e));return n===""||!n.startsWith("..")&&!Zh(n)}function Gc(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as sg}from"child_process";import{dirname as Uc,join as ag,resolve as cg}from"path";import{fileURLToPath as lg}from"url";var Tt={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 dg(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let r of Tt[i]?.packages??[])n.add(r);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function xn(e){return[...new Set(e.filter(t=>Tt[t]!==void 0))].sort()}function Hc(e,t=Qc){let n=xn(e),i=n.filter(r=>t.probe(Tt[r].ast));return{supportedLanguages:n,available:i,missing:n.filter(r=>!i.includes(r))}}function Vc(e,t={}){let n=t.runtime??Qc,i=t.packageRoot??ug(),r=xn(e),o=r.filter(p=>n.probe(Tt[p].ast)),s=r.filter(p=>!o.includes(p));if(s.length===0)return{supportedLanguages:r,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=pg(i),l=dg(s,a),d=n.install(i,l);d.ok&&n.resetProbe();let u=r.filter(p=>n.probe(Tt[p].ast));return{supportedLanguages:r,availableBefore:o,installed:d.ok?l:[],availableAfter:u,unavailable:r.filter(p=>!u.includes(p)),attempted:!0,...d.error?{error:d.error}:{}}}function ug(){let e=Uc(lg(import.meta.url));for(;;){let t=ag(e,"package.json");try{if(JSON.parse(G(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=Uc(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function pg(e){return JSON.parse(G(cg(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var Qc={probe:e=>Ft(e)==="ast",resetProbe:rr,install:(e,t)=>{let n=sg(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 Jc(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 zc(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 Kc(e={}){let t=[],n=te(),{projectRoot:i,paths:r,dbPath:o}=n,{config:s,existingConfigDiagnostics:a,collaborationConfig:l,languageConfig:d,automaticRefreshConfig:u,scipCliInstalled:p}=gg(n,e,t);bg(p,e.installIndexers===!0,t);let h=Sg(e.installSkills!==!1,t),v=u?Je(s,{projectRoot:i}):a,k=vg(v,t),R=Rg(i,s,t),C=xg(R.languages,e.installAstParsers===!0,t),V=wg(i,R,e.installIndexers===!0,t),J=ke(i,s),Ee=await Pg({projectRoot:i,paths:r,config:s,readiness:J,configHasErrors:k,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),qe=Ee.reindexResult,Fe=Ee.freshness,Xe=xe(s),se=Ig({projectRoot:i,cacheDir:r.cacheDir,watchConfig:Xe,readiness:J,configHasErrors:k,reindexResult:qe,postReindexFreshness:Fe,steps:t}),fe=ke(i,s),De=ct(fe),_e=ee(i,s,r);A(t,{id:"capabilities",label:"Capability matrix",status:of(De),message:sf(De)});let Nt=$g(i,r,e,t),ft=e.runHealth===!0?await ef(r.dbPath,t):tf(t),yt=kg(i,fe.languages,t),Be=Cg(i,e.noAgentGuidance===!0,t),ye=jg({reindexResult:qe,readiness:fe,capabilities:De,freshness:_e,health:ft,healthSelected:e.runHealth===!0,agentResult:Be,watchConfig:Xe,watchService:se,rustSemanticSession:yt,steps:t});A(t,{id:"smoke-tests",label:"Setup smoke tests",status:Gg(ye),message:Ug(ye),details:ye.map(M=>`${M.command}: ${M.status} - ${M.evidence}`)});let Ge={repository:[...new Set([...[l,d,u].flatMap(M=>M?.changed?[M.configPath]:[]),...Be?.written??[]])],checkout:[],user:[...h.installed,...C.installed,...V.filter(M=>M.attempted).map(M=>`${M.binaryLabel} installer`)]},bt={projectRoot:i,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:p,languages:fe.languages,steps:t,skills:h,astParsers:C,initialReadiness:R,indexerRemediation:V,readiness:fe,capabilities:De,freshness:_e,reindex:qe,automaticRefreshConfig:u,watchService:se,rustSemanticSession:yt,health:ft,smokeTests:ye,healthDossier:null,setupAgent:Be,changeScopes:Ge,filesWritten:Be?.written??[],verdict:Ri(t,fe)};return Eg(bt,e,Nt)}function gg(e,t,n){let{projectRoot:i}=e,r=t.automaticRefresh??e.config.watch?.enabled??!0,o=Je(e.config,{projectRoot:i}),s=fg(i,e.config,o.some(k=>k.level==="error")),a=s.change?.config??e.config,l=t.languages?cs(i,a,t.languages):null,d=l?.config??a,u=Je(d,{projectRoot:i}),p=yg(i,d,r,u.some(k=>k.level==="error")),h=p.change?.config??d,v=Pt();return A(n,s.step),A(n,p.step),{config:h,existingConfigDiagnostics:u,collaborationConfig:s.change,languageConfig:l,automaticRefreshConfig:p.change,scipCliInstalled:v}}function fg(e,t,n){let i=null,r=null;if(!n&&!t.collaborationDomainId)try{i=as(e,t)}catch(s){r=pt(s)}let o={id:"collaboration-domain-config",label:"Collaboration domain",status:r!==null?"failed":n?"skipped":"ok",message:r??(n?"Skipped because the existing project config has validation errors.":i?.changed?"Generated the committed identity shared by merge-intended branches, clones, and forks.":"The committed collaboration-domain identity is already present."),...i?{details:[i.configPath]}:{}};return{change:i,step:o}}function yg(e,t,n,i){let r=null,o=null;if(!i&&t.watch?.enabled!==n)try{r=ls(e,t,n)}catch(a){o=pt(a)}let s={id:"automatic-indexing-config",label:"Automatic indexing config",status:o!==null?"failed":i||!n?"skipped":"ok",message:lf(o,i,n,r),...r?{details:[r.configPath]}:{}};return{change:r,step:s}}function bg(e,t,n){let i=en();A(n,{id:"scip-cli",label:"scip CLI",status:e||!i?"ok":"warn",message:e?"scip CLI is available.":i?t?"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)."})}function Sg(e,t){let n=e?Rn({quiet:!0}):{installed:[],skipped:[],alreadyLinked:[],pruned:[]};return A(t,{id:"skills",label:"Agent skills",status:e?n.skipped.length>0?"warn":"ok":"skipped",message:e?`${n.installed.length} installed, ${n.alreadyLinked.length} already linked, ${n.pruned.length} pruned, ${n.skipped.length} skipped.`:"Skipped by setup choice.",details:[...n.pruned.map(i=>`Pruned ${i}`),...n.skipped.map(i=>`Skipped ${i}`)]}),n}function vg(e,t){let n=e.filter(i=>i.level==="error");return A(t,{id:"config",label:"Project config",status:n.length>0?"failed":e.length>0?"warn":"ok",message:e.length===0?"Config OK.":`${e.length} diagnostic(s), ${n.length} error(s).`,details:e.map(i=>`${i.level.toUpperCase()} ${i.path}: ${i.message}`)}),n.length>0}function Rg(e,t,n){let i=ke(e,t);return A(n,{id:"readiness",label:"Indexer readiness",status:i.languages.length===0?"failed":i.indexers.some(r=>!r.runnable)?"warn":"ok",message:i.languages.length===0?"No supported project languages detected.":`Detected languages: ${i.languages.join(", ")}`,details:i.indexers.map(r=>`${r.runnable?"OK":r.installed?"WARN":"MISSING"} ${r.language}: ${r.binaryLabel}${r.note?` - ${r.note}`:""}`)}),i}function xg(e,t,n){let i;if(t)return i=Vc(e),df(n,i),i;let r=Hc(e);return i={supportedLanguages:r.supportedLanguages,availableBefore:r.available,installed:[],availableAfter:r.available,unavailable:r.missing,attempted:!1},A(n,{id:"ast-parsers",label:"AST parser packages",status:r.missing.length===0?"ok":"skipped",message:r.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":r.missing.length===0?`${r.available.length}/${r.supportedLanguages.length} selected language parser(s) available; nothing to install.`:"Skipped because installing missing parser packages requires explicit consent.",details:r.missing.length>0?[`Missing: ${r.missing.join(", ")}`]:[]}),i}function wg(e,t,n,i){let r=n?Xg(e,t,i):[];if(!n){let o=t.indexers.filter(s=>!s.runnable);A(i,o.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:o.map(s=>`Missing ${s.language}: ${s.binaryLabel}`)})}return r}function $g(e,t,n,i){n.onStatus?.(n.runHealth===!0?"Running optional full health audit\u2026":"Skipping optional full health audit.");let r=n.runHealth===!0?Lc(e,{runId:hg(),startedAt:new Date().toISOString(),indexGeneration:Re(t.dbPath)},{dossierDir:n.dossierDir}):null;return r?.interrupted&&A(i,{id:"health-dossier-attempt",label:"Previous health audit",status:"warn",message:`A health audit started at ${r.interrupted.startedAt} (index generation ${r.interrupted.indexGeneration??"unavailable"}) did not complete; the dossier it would have written was never published.`,details:[r.attemptPath]}),r}function kg(e,t,n){let i=t.includes("rust")?Ut(e,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;return A(n,{id:"rust-semantic-session",label:"Rust semantic session",status:i===null?"skipped":i.valid?"ok":"failed",optional:i===null,message:i===null?"Skipped because Rust was not detected.":`${i.transport}/${i.state} selected from ${i.source}; ${i.fallback} fallback; opt out with ${i.optOut}.`}),i}function Cg(e,t,n){let i=null;try{t?A(n,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(i=yn(e),A(n,{id:"agent-guidance",label:"Project agent guidance",status:i.skipped.length>0?"warn":"ok",message:`${i.written.length} written, ${i.unchanged.length} already wired, ${i.skipped.length} skipped.`,details:i.skipped.map(r=>`Skipped ${r.target}: ${r.reason}`)}))}catch(r){A(n,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:pt(r)})}return i}function Eg(e,t,n){let{steps:i,readiness:r}=e;if(t.runHealth!==!0)return A(i,{id:"health-dossier",label:"Health dossier",status:"skipped",optional:!0,message:"Skipped because the optional health audit was not selected."}),e.verdict=Ri(i,r),e;n&&(e.indexGeneration=n.attempt.indexGeneration,e.attempt={...n.attempt,completedAt:new Date().toISOString()});let o=qc(e,{dossierDir:t.dossierDir});return n&&o.status!=="failed"&&Mc(n),e.healthDossier=o,e.changeScopes.repository.push(...o.written),e.filesWritten=[...e.filesWritten,...o.written],A(i,{id:"health-dossier",label:"Health dossier",status:o.status==="failed"?"failed":"ok",message:o.status==="failed"?o.error:`${o.written.length} written, ${o.unchanged.length} unchanged.`,details:[o.markdownPath,o.jsonPath]}),e.verdict=Ri(i,r),e}async function Pg(e){if(e.readiness.languages.length===0||e.configHasErrors)return A(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 r=0,o=!1;for(let s=0;s<2;s+=1){if(n=await Ks({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)}}),r+=n.durationMs,o||=!n.reused,i=ee(e.projectRoot,e.config,e.paths),uf(s,n,i)){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.");A(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(r/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(r){A(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:pt(r),details:t})}return{reindexResult:n,freshness:i}}function Ig(e){let t=cf(e);if(t===null&&!e.watchConfig.autoStart)return A(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 A(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",optional:t.optional,message:t.reason}),null;try{let n=on({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:be,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let i=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return A(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 A(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:pt(n)}),null}}function Yc(e){console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health report: ${gi(e.health)}`),console.log(""),Ag(e.health),e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),Si("Repository records (commit)",e.changeScopes.repository),Si("Checkout preferences (do not commit)",e.changeScopes.checkout),Si("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("Setup checks (operation results and readiness):");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} [${t.basis}] ${t.command} - ${t.evidence}`);pf(e)}function Ag(e){if(!e.available)console.log("Items that need attention: not evaluated; health report unavailable.");else if(e.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.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.unavailableReason&&console.log(`Health pass: ${e.unavailableReason}`),e.warnings.length>0){console.log("Health warnings:");for(let t of e.warnings)console.log(` - ${t}`)}}function Si(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function jg(e){let t=[Tg(e),Lg(e),Mg(e),qg(e),Dg(e),Ng(e),Og(e),Wg(e),Fg(e),_g(e),Bg(e)],n=new Set(["capabilities","capability-matrix","diff-impact","cleanup-verification"]);return t.map(i=>({...i,basis:n.has(i.id)?"readiness":"operation-result"}))}function Tg(e){let t=e.steps.find(n=>n.id==="reindex");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."}}function Lg(e){return{id:"status",command:"scip-query status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`}}function Mg(e){return{id:"config-validate",command:"scip-query config-validate",status:Hg(e.steps),evidence:Vg(e.steps)}}function qg(e){return{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."}}function Dg(e){return{id:"capability-matrix",command:"scip-query capabilities --matrix",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?Qg(e.capabilities):"No detected languages produced capability rows."}}function Ng(e){return{id:"health",command:"scip-query health --indexed --full",status:e.health.available?"pass":"unavailable",optional:!e.healthSelected,evidence:e.health.available?`Health report available: ${e.health.issuesNeedAttention.length} review candidate(s).`:e.health.unavailableReason??"Health report was not available."}}function Og(e){return{id:"diff-impact",command:"scip-query diff-impact --json",status:Jg(e.readiness,e.freshness),evidence:zg(e.readiness,e.freshness)}}function Wg(e){return{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Kg(e.capabilities),evidence:Yg(e.capabilities)}}function Fg(e){let t=e.steps.find(n=>n.id==="watch-refresh");return{id:"watch-refresh",command:"scip-query status --json",status:t?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",...t?.optional===!0?{optional:!0}:{},evidence:t?.message??"Watch refresh policy was not evaluated."}}function _g(e){return{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}.`}}function Bg(e){let t=e.steps.find(n=>n.id==="agent-guidance");return{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:t?.message??"Project agent guidance was not written."}}function Gg(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable"&&t.optional!==!0)?"warn":"ok"}function Ug(e){let t=e.filter(r=>r.status==="pass").length,n=e.filter(r=>r.status==="unavailable").length,i=e.filter(r=>r.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function Hg(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Vg(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Qg(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 Jg(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function zg(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 Kg(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function Yg(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(r=>r.cleanupVerification.status==="available").length,n=e.matrix.filter(r=>r.cleanupVerification.status==="partial").length,i=e.matrix.filter(r=>r.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function Xg(e,t,n){let i=[];if(t.languages.length===0)return A(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers)s.runnable||i.push(af(e,s));if(i.length===0)return A(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let r=i.filter(s=>!s.after.runnable),o=i.filter(s=>s.attempted);return A(n,{id:"indexer-remediation",label:"Indexer remediation",status:r.length>0?"warn":"ok",message:r.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${r.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function Zg(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function ef(e,t){if(!mg(e)){let n="Skipped because no SQLite index database exists yet.";return A(t,{id:"health",label:"Health audit",status:"skipped",message:n}),vi(n)}try{let n=await vs({full:!0,json:!0});return A(t,{id:"health",label:"Health audit",status:"ok",message:`Health report available: ${n.actions.length} review candidate(s).`}),nf(n)}catch(n){let i=pt(n);return A(t,{id:"health",label:"Health audit",status:"failed",message:i}),vi(i)}}function tf(e){let t="Indexed health skipped by setup choice; run `scip-query health` for current-source scanning or `scip-query health --indexed --full` for the indexed specialists.";return A(e,{id:"health",label:"Health audit",status:"skipped",optional:!0,message:t}),vi(t)}function nf(e){return{available:!0,issuesNeedAttention:e.actions.map(rf),warnings:e.warnings??[]}}function rf(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 vi(e){return{available:!1,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ri(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 of(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 sf(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 A(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function pt(e){return e instanceof Error?e.message:String(e)}function af(e,t){let n=tn(t.language),i=[],r=!t.installed&&!!n.installMethods?.length,o=!1;r?o=Js(n,a=>i.push(a)):t.installed?i.push(t.note??`${t.binaryLabel} is installed but is not runnable.`):n.installMethods?.length||i.push(`No auto-install method is configured for ${t.binaryLabel}.`);let s=Zg(_t(n,e));return{language:t.language,binaryLabel:t.binaryLabel,attempted:r,installed:o,before:t,after:s,messages:i,recovery:s.runnable?void 0:s.note??s.installUrl??`Install ${t.binaryLabel} and put it on PATH.`}}function cf(e){return 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}}function lf(e,t,n,i){return e??(t?"Skipped because the existing project config has validation errors.":n?i?.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.")}function df(e,t){A(e,{id:"ast-parsers",label:"AST parser packages",status:t.unavailable.length>0?"warn":"ok",message:t.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${t.availableAfter.length}/${t.supportedLanguages.length} selected language parser(s) available${t.installed.length>0?`; installed ${t.installed.join(", ")}`:""}.`,details:[...t.unavailable.length>0?[`Unavailable: ${t.unavailable.join(", ")}`]:[],...t.error?[t.error]:[]]})}function uf(e,t,n){return e===0&&t.skipped.length===0&&n.state==="stale"}function pf(e){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}`)}}}import{emitKeypressEvents as mf}from"readline";function hf(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function gf(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 r=new Set(e.selected);return r.has(i)?r.delete(i):r.add(i),{...e,selected:r}}async function Xc(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=hf(e);mf(t);let r=t.isRaw;t.setRawMode(!0),t.resume();let o=(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,l)=>{let d=l===i.cursor?"\u203A":" ",u=i.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${d} ${u} ${a.label} [${a.scope}]\x1B[K
|
|
33
|
+
`)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let l=(u,p)=>{if(p.ctrl&&p.name==="c"){d(),a(new Error("Setup cancelled."));return}if(p.name==="return"||p.name==="enter"){d(),n.write(`
|
|
34
|
+
`),s(i.selected);return}let h=p.name==="up"?"up":p.name==="down"?"down":p.name==="space"?"toggle":null;h&&(i=gf(i,h,e),o())},d=()=>{t.off("keypress",l)};t.on("keypress",l)})}finally{t.setRawMode(!!r),t.pause()}}import{existsSync as ff}from"fs";import{join as xi}from"path";function Zc(e,t={}){let n=[],i=e.dryRun?"would ":"";return e.global&&yf(n,e.global,i,t.verbose),e.project&&bf(n,e.project,i),(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 yf(e,t,n,i){for(let r of t.removed)e.push(` ${n}remove: ${r}`);if(i)for(let r of t.left)e.push(` left: ${r}`);else if(t.left.length>0){let r=t.left.length===1?"entry":"entries";e.push(` left: ${t.left.length} unrelated global skill ${r} (use --verbose to list)`)}for(let r of t.skipped)e.push(` skip: ${r}`)}function bf(e,t,n){for(let i of t.agentSetup.removed)e.push(` ${n}remove: ${i}`);for(let i of t.agentSetup.unchanged)e.push(` ok: ${i} (no managed block)`);for(let i of t.agentSetup.skipped)e.push(` skip: ${i.target} \u2014 ${i.reason}`);for(let i of t.left)e.push(` left: ${i}`)}function wi(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 el(e){let t=wi(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=Bc({dryRun:e.dryRun,homeDir:e.homeDir})),t.project&&(n.project=Sf(e.projectRoot,{dryRun:e.dryRun})),n}function Sf(e,t={}){return{agentSetup:Rc(e,{dryRun:t.dryRun}),left:vf(e)}}function vf(e){return[[".scipquery.json",xi(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",xi(e,".scipquery","suppressions")],["docs/scip-query/",xi(e,"docs","scip-query")]].filter(([,t])=>ff(t)).map(([t])=>t)}import{existsSync as tl,lstatSync as Rf,readdirSync as xf}from"fs";import{join as nl}from"path";function ol(e={}){let t=nl(e.cacheRoot??Yi(),"projects"),n={projectsDirectory:t,scannedCacheDirs:0,ownedCacheDirs:0,retainedRoots:0,orphanedRoots:0,stoppedServices:0,alreadyStoppedServices:0,skipped:[],failures:[]};if(!il(t))return n;let i=e.rootIsCurrent??il,r=e.stopService??sn;for(let o of xf(t,{withFileTypes:!0}).sort((s,a)=>s.name.localeCompare(a.name))){let s=nl(t,o.name);if(n.scannedCacheDirs+=1,!o.isDirectory()||o.isSymbolicLink()){n.skipped.push({cacheDir:s,message:"not a regular cache directory"});continue}kf(s,n,i,r)}return n}function wf(e,t){let n=Ht(e),i=br(n.statePath),r=ca(n.lockPath);if(tl(n.statePath)&&!i)throw new Error("watch state exists but is not a valid ownership record");if(tl(n.lockPath)&&!r)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(r&&r.projectRoot!==t)throw new Error("watch lock belongs to a different project root");$f(i,r)}function $f(e,t){if(e&&t&&e.pid!==t.pid)throw new Error("watch state and lock name different process owners");if(e?.processIdentity&&t?.processIdentity&&!Gt(e.processIdentity,t.processIdentity))throw new Error("watch state and lock name different process identities")}function il(e){try{let t=Rf(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){let n=t.code;if(n==="ENOENT"||n==="ENOTDIR")return!1;throw t}}function rl(e){return e instanceof Error?e.message:String(e)}function kf(e,t,n,i){let r;try{r=Xi(e).record.canonicalProjectRoot,t.ownedCacheDirs+=1}catch(o){t.skipped.push({cacheDir:e,message:rl(o)});return}if(n(r)){t.retainedRoots+=1;return}try{if(wf(e,r),n(r)){t.retainedRoots+=1;return}t.orphanedRoots+=1,i({projectRoot:r,cacheDir:e,cliVersion:"orphan-prune"}).disposition==="stopped"?t.stoppedServices+=1:t.alreadyStoppedServices+=1}catch(o){t.failures.push({cacheDir:e,projectRoot:r,message:rl(o)})}}function sl(e){cl(e,"health")}function al(e){cl(e,"review")}function cl(e,t){let n=N(e),{projectRoot:i}=te(),r=rs(i,{...t==="review"?{base:y(n,"base")??"HEAD"}:{},coverage:y(n,"coverage"),scope:y(n,"scope"),includeTests:m(n,"includeTests"),includeReferences:m(n,"includeReferences"),includeGenerated:m(n,"includeGenerated"),maxFiles:j(n,"maxFiles")});m(n,"json")?x(t,[],n,r):Cf(r,m(n,"full")?1/0:j(n,"limit")??(t==="health"?5:20)),m(n,"check")&&(r.coverage.status==="incomplete"?process.exitCode=2:r.blockingFindingIds.length&&(process.exitCode=1))}function Cf(e,t=e.mode==="health"?5:20){Ef(e),e.mode==="review"&&If(e),console.log(`Blocking findings: ${e.blockingFindingIds.length}; raw findings remain visible below.`),e.mode==="health"&&t!==1/0?(jf(e,t),console.log(`
|
|
35
|
+
Module evidence: ${e.modules.length} groups with findings. Use scip-query system --source <path-or-group> for files, dependencies and consumers.`)):(Tf(e,t),Af(e,t)),Pf(e,t===1/0),e.affectedFiles.length&&console.log(`
|
|
36
|
+
Affected importers (${e.affectedFiles.length}):
|
|
37
|
+
${e.affectedFiles.map(n=>` ${n}`).join(`
|
|
38
|
+
`)}`),e.coverage.problems.length&&console.log(`
|
|
39
|
+
Unresolved coverage:
|
|
40
|
+
${e.coverage.problems.map(n=>` ${n}`).join(`
|
|
41
|
+
`)}`)}function Ef(e){console.log(`${e.mode==="review"?"Change review":"Source health"} \u2014 current source, ${e.coverage.analyzedFiles}/${e.coverage.eligibleFiles} eligible files, ${e.coverage.analyzedFunctions} functions`),e.base&&console.log(`Base: ${e.base}`),e.coverage.status==="incomplete"&&console.log("Source scan incomplete; see unresolved files below."),e.coverage.unresolvedImports>0&&console.log(`${e.coverage.unresolvedImports} internal imports unresolved or ambiguous.`),e.architecture.configured||console.log("No architecture rules configured.");let t=e.coverage.testCoverage;if(t.requested){console.log(`Test coverage: ${t.available} available, ${t.unavailable} unavailable measurements.`);for(let n of t.reasons)console.log(` ${n}`)}}function Pf(e,t){let n=0;for(let i of e.suppressionDecisions){if(i.outcome==="unmatched"&&!t){n+=1;continue}console.log(`Suppression ${i.outcome}: ${i.id??i.check??"unknown target"}${i.reasons.length?` \u2014 ${i.reasons.join("; ")}`:""}`)}n&&console.log(`Unmatched suppressions: ${n}; no current finding matched in this scope. Use --full for decisions and reasons.`)}function If(e){console.log(`
|
|
42
|
+
Changed source: ${e.changedFiles.length} files; ${e.functions.length} function records.`),e.configurationChanges.length&&console.log(`Changed configuration: ${e.configurationChanges.join(", ")}`),e.relationshipChangedFiles.length&&console.log(`Changed import relationships: ${e.relationshipChangedFiles.join(", ")}`);for(let t of e.functions){let n=t.after??t.before,i=t.before&&t.after?`cyclomatic ${t.before.cyclomatic} \u2192 ${t.after.cyclomatic}, cognitive ${t.before.cognitive} \u2192 ${t.after.cognitive}`:`cyclomatic ${n.cyclomatic}, cognitive ${n.cognitive}`,r=n.coverage.status==="available"?`coverage ${Math.round(n.coverage.fraction*100)}%, CRAP ${n.coverage.crap}`:`CRAP unavailable: ${n.coverage.reason}`;console.log(` ${t.status} ${n.file}:${n.startLine} ${n.name} \u2014 ${i}; ${r}`)}}function Af(e,t){console.log(`
|
|
43
|
+
Findings: ${e.findings.length} (${Math.min(t,e.findings.length)} shown)`);for(let n of e.findings.slice(0,t))ll(n,t)}function ll(e,t){console.log(` [${e.status?`${e.status}; `:""}${e.evidence}] ${e.rule}: ${e.summary}`);for(let n of e.sites.slice(0,t===1/0?1/0:3))console.log(` ${n.file}:${n.line}${n.name?` ${n.name}`:""}`);if(t===1/0)for(let n of e.details)console.log(` ${n}`);else console.log(` ${e.sites.length} total sites; ${e.details.length} supporting details available with --full.`)}function jf(e,t){let n=[["broken-dependency","Broken dependencies"],["architecture","Architecture findings"],["dependency-cycle","Dependency components"],["complexity","Complexity findings"],["crap","Complexity and coverage risk"],["duplication","Duplication candidates"],["responsibility","Responsibility candidates"]];console.log(`
|
|
44
|
+
Finding shortlists: --limit applies separately to each category; categories are not a design grade.`);for(let[i,r]of n){let o=e.findings.filter(a=>a.rule===i);if(!o.length)continue;let s=i==="complexity"?"; greatest threshold exceedance first":"";console.log(`
|
|
45
|
+
${r}: ${o.length} (${Math.min(t,o.length)} shown${s}).`);for(let a of o.slice(0,t))ll(a,t)}e.findings.length||console.log("No findings from the covered source.")}function Tf(e,t){console.log(`
|
|
46
|
+
Planning subjects: ${e.modules.length} groups with ${e.findings.length} underlying findings (${Math.min(t,e.modules.length)} groups shown).`);let n=new Map(e.findings.map(i=>[i.id,i]));for(let i of Mf(e).slice(0,t))console.log(` ${i.id} [${i.basis}]: ${i.files.length} files, ${i.consumers.length} external consumer files, ${i.dependencies.length} external dependency files, ${i.findingIds.length} findings.`),console.log(` Files: ${$i(i.files,t,"")}`),console.log(` Consumers: ${$i(i.consumers,t,"none observed")}`),console.log(` Dependencies: ${$i(i.dependencies,t,"none observed")}`),Lf(i,n)}function $i(e,t,n){return(e.slice(0,t===1/0?1/0:3).join(", ")||n)+(e.length>3&&t!==1/0?" \u2026":"")}function Lf(e,t){for(let n of e.primaryFindingIds.slice(0,3)){let i=t.get(n);console.log(` [${i.evidence}${i.status?"; "+i.status:""}] ${i.rule}: ${i.summary}`);for(let r of i.sites.slice(0,2))console.log(` ${r.file}:${r.line}${r.name?" "+r.name:""}`)}}function Mf(e){let t=new Map(e.modules.flatMap(r=>r.primaryFindingIds.map(o=>[o,r]))),n=new Set,i=new Set;for(let r of e.findings){let o=t.get(r.id);o&&!n.has(r.rule)&&(i.add(o),n.add(r.rule))}return[...i,...e.modules.filter(r=>!i.has(r))]}function dl(e,t){let n=qf(t);return{...e,warnings:[...e.warnings??[],...n],capabilities:t}}function qf(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 Df}from"crypto";import{relative as Nf}from"path";function hl(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(r=>r!==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 Lt=class extends Error{constructor(n,i,r){super(`${n} ${r?`Current revision: ${r}. Retry with --replace ${r} after reviewing it.`:"The suppression file was left untouched."}`);this.path=i;this.currentRevision=r;this.name="SuppressionWriteConflictError"}path;currentRevision};function gl(e,t,n,i,r){if(!Ln.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${Ln.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let o=n.map(s=>Bf(e,s,i));return{kind:"automated-adjudication",reasonCode:t,decidedBy:"agent",policyVersion:1,...r?{observation:r}:{},evidence:o,invalidateOn:{targetContentChange:o.some(s=>s.contentHash!==void 0),detectorMajorChange:!0}}}function fl(e,t,n={}){let i=n instanceof Date?{now:n}:n,r=Wf(t),o=Ff(i.expectedRevision),s=Xo(e,r),a=i.now??new Date,l="unchanged",d=it(s,u=>{if(!u.revision.exists){if(o)throw new Lt(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return l="created",{kind:"write",text:ml(ul(r,void 0,a,i.toolVersion))}}let p=Of(u,e);if(_f(p.suppression,r))return l="unchanged",{kind:"unchanged"};if(!o)throw new Lt(`A different suppression decision already exists at ${s}.`,s,u.revision.hash);if(o!==u.revision.hash)throw new Lt(`Suppression ${s} changed after the revision you reviewed.`,s,u.revision.hash);return l="replaced",{kind:"write",text:ml(ul(r,p.suppression,a,i.toolVersion))}},{maxRetries:0,onBeforeCommit:u=>{i.onBeforeCommit?.(u),Yo(e,s)}});return{path:s,disposition:l,revision:d.current.revision.hash}}function Of(e,t){let n;try{n=JSON.parse(e.text)}catch(o){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:o})}let i=Nf(zo(t),e.path).replaceAll("\\","/").slice(0,-5),r=Zo(n,i);if("error"in r)throw new Error(`Cannot update ${e.path}: ${r.error}.`);return r}function ul(e,t,n,i=be){let r=n.toISOString(),{decision:o,createdAt:s,...a}=e,l={kind:Vo,suppressionIdentity:Ko(e),writer:{tool:"scip-query",version:i},...a,createdAt:t?.createdAt??s??r,...t?{updatedAt:r}:{}};return o?{...l,schemaVersion:Jo,decision:o}:{...l,schemaVersion:Qo}}function Wf(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(Gf(n,i),e.decision!==void 0&&!Ho(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 Ff(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 _f(e,t){return JSON.stringify(pl(e))===JSON.stringify(pl(t))}function pl(e){let{createdAt:t,...n}=e;return n}function ml(e){return`${JSON.stringify(e,null,2)}
|
|
47
|
+
`}function Bf(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 r=t.slice(0,i),o=t.slice(i+1).trim();if(r==="graph"){if(!o.startsWith("scip-query "))throw new Error("graph suppression evidence must name the exact scip-query command that produced it");return{kind:r,referent:o,claim:n}}if(r!=="source"&&r!=="config"&&r!=="test")throw new Error(`unsupported suppression evidence kind ${JSON.stringify(r)}`);let s=Fi(o),a=Zi(e,s);return{kind:r,referent:s,claim:n,contentHash:Df("sha256").update(a).digest("hex")}}function Gf(e,t){if(!e&&!t)throw new Error("suppression requires an id or a check")}import{execFileSync as Uf}from"child_process";var Hf={changedPaths:Qf,indexedPaths:e=>nr(e,{includeIgnored:!1}),architectureFindings:e=>Qe(nt(e))},Vf=/\.(?:[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 bl(e,t,n=Hf){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 r=new Set(n.indexedPaths(t)),o=i.filter(a=>r.has(a)||Vf.test(a));if(o.length===0)return{kind:"allow",checkedSourceFiles:[],findings:[]};let s=n.architectureFindings(t);return s.length===0?{kind:"allow",checkedSourceFiles:o,findings:[]}:{kind:"block",checkedSourceFiles:o,findings:s,reason:`scip-query found ${s.length} enforced architecture violation(s):
|
|
48
|
+
${s.map(a=>`- ${a}`).join(`
|
|
49
|
+
`)}
|
|
50
|
+
|
|
51
|
+
Inspect the boundary graph with: scip-query architecture`}}function Sl(e){return e.kind==="block"?{decision:"block",reason:e.reason}:{}}function Qf(e){let t=yl(e,["diff","--name-only","-z","--diff-filter=ACDMRTUXB","HEAD","--"]),n=yl(e,["ls-files","-z","--others","--exclude-standard","--"]);return[...new Set([...t,...n])].sort()}function yl(e,t){try{return Uf("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:10*1024*1024,killSignal:"SIGKILL"}).split("\0").filter(Boolean)}catch(n){throw new Error(`Could not inspect changed files for the architecture Stop hook: ${Jf(n)}`,{cause:n})}}function Jf(e){return e instanceof Error?e.message:String(e)}var Kf=new Set(tt),$l=H(({db:e})=>{try{let t=bl(_(),e);process.stdout.write(`${JSON.stringify(Sl(t))}
|
|
52
|
+
`)}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})}
|
|
53
|
+
`)}});function Yf(e){let t=e.filter(n=>!Kf.has(n));if(t.length>0)throw new Error(`Unknown language: ${t.join(", ")}. Supported languages: ${tt.join(", ")}.`);return[...new Set(e)]}async function kl(e){let t=N(e),n=_(),i=Z(n),r=Se(n,i),o=m(t,"json");try{let s=Yf(D(t,"language")),a=await pa(n,i,r,{languages:s.length>0?s:i.languages,force:m(t,"force"),allowPartial:m(t,"allowPartial"),allowExpensiveRebuild:m(t,"allowExpensiveRebuild"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:m(t,"installMissing"),trustProjectTools:m(t,"trustProjectTools"),indexerConcurrency:j(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{onStatus:console.log}});if(o){x("reindex",[],t,a);return}By(a)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}async function Cl(){let e=_(),t=Un(e);try{let n=await Gn(t,i=>Fs({projectRoot:e,dbPath:i,onStatus:r=>console.log(r)}));console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function El(e){let t=N(e),n=_(),i=Un(n);try{let r=await Gn(i,o=>zs({projectRoot:n,dbPath:o,tsconfig:y(t,"project")??"frontend/tsconfig.scip.json",onStatus:s=>console.log(s)}));console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}; not-inserted identifier tokens: ${r.skippedReferences}; synthetic symbols: ${r.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${r.skippedReferenceReasons["no-definition"]}; same-file definition ${r.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${r.skippedReferenceReasons["unindexed-definition"]}; missing source ${r.skippedReferenceReasons["missing-source-file"]}; missing service script ${r.skippedReferenceReasons["missing-service-script"]}. Samples: ${r.skippedReferenceSamples.length} omitted, ${r.resolvedReferenceSamples.length} resolved.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function Pl(e){let t=N(e),n=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]");if(!Array.isArray(n)||!n.every(i=>typeof i=="string"&&i.length>0))throw new Error("SCIP_QUERY_DIFF_IMPACT_FILES must be a JSON array of nonempty file paths.");ze(i=>{let r=fo(i,{base:y(t,"base")}),o=yo(i,n,r.changedFiles,r.changedRanges);Yt(Ct,o)})}async function Il(e){let t=N(e);try{let n=await ws({base:y(t,"base")});if(m(t,"json")){x("diff-impact",[],t,n.result,{observationReceipt:n.observationReceipt});return}$s(n.result)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Al(e,t){let n=N(t);if(typeof e!="string"||e.length===0)throw new Error("At least one health phase is required.");let i=[];for(let r of e.split(",")){if(!Mo.includes(r))throw new Error(`Unknown health phase: ${r}`);i.includes(r)||i.push(r)}ze(r=>{let o={scope:y(n,"scope"),full:m(n,"full")},s=i.length===1?qo(r,i[0],o):Do(r,i,o);Yt($t,s)})}async function jl(e){let t=N(e),n=Xf(t);await hs(async i=>{let r=await Ss(i,{scope:y(t,"scope"),full:m(t,"full"),...n?{shard:n}:{}});Yt(kt,r)})}function Xf(e){let t=y(e,"shardIndex"),n=y(e,"shardCount");if(t===void 0&&n===void 0)return;let i=Rl(t),r=Rl(n);if(i===void 0||r===void 0||r<1||i>=r)throw new Error("Prewarm requires both --shard-index and --shard-count, with 0 <= index < count and positive count.");return{index:i,count:r}}function Rl(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}async function Tl(e){let t=N(e);if(Zf(t),m(t,"writeBaseline")||m(t,"baseline")){ey(t);return}if(!m(t,"indexed")){sl(e);return}try{let n=await Rs({scope:y(t,"scope"),full:m(t,"full"),json:m(t,"json")}),{projectRoot:i,config:r,dbPath:o}=te(),s=ct(ke(i,r),{hasIndexedGraph:Mt(o)}),a=dl(n.result,s);if(m(t,"json")){x("health",[],t,a,{observationReceipt:n.observationReceipt});return}xs(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Zf(e){if(m(e,"baseline")&&m(e,"writeBaseline"))throw new Error("Choose --baseline to compare or --write-baseline to replace the snapshot, not both.");if(["indexed","baseline","writeBaseline"].some(t=>m(e,t))){let t=["coverage","includeTests","includeReferences","includeGenerated","maxFiles","limit","check"].find(n=>e[n]!==void 0&&e[n]!==!1);if(t)throw new Error(`The ${t} option belongs to current-source health; do not combine it with --indexed or indexed baseline options.`)}}function ey(e){let t=y(e,"scope");ze(n=>{if(m(e,"writeBaseline")){let r=Ao(n,{scope:t});m(e,"json")?x("health",[],e,r):console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=jo(n,{scope:t});if(m(e,"json")){x("health",[],e,i),i.newFindings.length>0&&(process.exitCode=1);return}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 r of i.newFindings)console.log(` + ${r}`);process.exitCode=1})}function Ll(e){let t=N(e),n=Rn({all:m(t,"all")}),i=n.installed.length+n.alreadyLinked.length;console.log(`
|
|
54
|
+
${n.installed.length} installed, ${n.alreadyLinked.length} already linked, ${n.pruned.length} pruned, ${n.skipped.length} skipped.`),i>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function Ml(){let e=ty(),t=_(),n=Z(t),i=ke(t,n);if(i.languages.length===0){console.log(`
|
|
55
|
+
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}let r=ny(i);e=e||r,iy(i),process.exitCode=e?1:0}function ty(){let e=!1;return Pt()?console.log("scip CLI: installed"):en()?(Jn(),e=!0):console.log("scip CLI: not installed (not required; SCIP is converted to SQLite in-process unless SCIP_QUERY_SQLITE_CONVERTER=scip-cli)."),e}function ny(e){let t=!1;console.log(`
|
|
56
|
+
Detected languages: ${e.languages.join(", ")}`),console.log(`
|
|
57
|
+
Indexer readiness:`);for(let n of e.indexers){let i=n.runnable?" OK":n.installed?" WARN":" MISSING",r=n.resolvedBinary?` (${n.resolvedBinary})`:"";console.log(`${i} ${n.language}: ${n.binaryLabel}${r}`),n.note&&console.log(` ${n.note}`),!n.installed&&n.installUrl&&console.log(` install: ${n.installUrl}`),n.runnable||(t=!0)}return t}function iy(e){let t=zl(e);t.length>0&&console.log(`
|
|
58
|
+
Semantic provider readiness:`);for(let n of t){let i=n.available?" OK":n.dependencyAvailable?" WARN":" MISSING";console.log(`${i} ${n.language}: ${Ay(n)}${Kl(n)}`),n.reason&&console.log(` ${n.reason}`)}}function ql(e){ry(e)}function ry(e){let t=N(e),{projectRoot:n,config:i,paths:r,dbPath:o}=te(),s=ke(n,i),a=ee(n,i,r),l=ct(s,{hasIndexedGraph:Mt(o)&&a.state!=="missing"});if(m(t,"json")){x("capabilities",[],t,{...l,explorationControls:gn,relationshipQuestions:an(),unavailableRelationshipFrontiers:Qt});return}qy(l,{matrix:m(t,"matrix")})}function Dl(){let e=_(),t=Jt(e),n=ss(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 Nl(e){let t=N(e),n=_(),i=Z(n),r=es(n),o=[...Je(i,{projectRoot:n}),...r.compatibility.issues.map(s=>({level:"error",path:s.path,message:s.reason}))];if(m(t,"json"))x("config-validate",[],t,{diagnostics:o});else if(o.length===0)console.log("Config OK.");else for(let s of o)console.log(`${s.level.toUpperCase()} ${s.path}: ${s.message}`);o.some(s=>s.level==="error")&&(process.exitCode=1)}function Ol(e,t){let n=N(t),i=y(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let r=y(n,"reasonCode"),o=D(n,"evidence");if(!r||o.length===0){console.error("error: suppress requires --reason-code <code> and at least one --evidence <source|config|test|graph>:<referent> so automatic adjudication has inspectable counterevidence."),process.exitCode=1;return}try{let s=_(),a=(()=>{if(o.some(u=>u.startsWith("graph:")))try{return ze(()=>bs())}catch{return}})(),l={id:String(e),check:y(n,"check"),file:y(n,"file"),reason:i,expiresAt:y(n,"expiresAt"),decision:gl(s,r,o,i,a)},d=fl(s,l,{expectedRevision:y(n,"replace")});if(m(n,"json")){x("suppress",[String(e)],n,d);return}for(let u of hl(d,l))console.log(u)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}function Wl(e){let t=N(e),{report:n,hasIndexerProblems:i,hasErrors:r}=Fl("doctor");m(t,"json")?x("doctor",[],t,n):$y(n,i),process.exitCode=r?1:0}function Fl(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=te(),o=Je(n,{projectRoot:t}),s=ke(t,n),a=ee(t,n,i),l=Mt(r),d=ct(s,{hasIndexedGraph:l&&a.state!=="missing"}),u=ua(t,n,i),p=s.indexers.some(k=>!k.runnable),h=o.some(k=>k.level==="error")||p||a.state==="missing"||a.state==="stale",v=o.some(k=>k.level==="error")||p||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:r,configuredDbPath:i.dbPath,exists:l,configDiagnostics:o,readiness:s,freshness:a,capabilities:d,sharedCache:u,ok:!h},hasIndexerProblems:p,hasErrors:v}}function _l(e){N(e);let t=_(),n=yn(t);for(let r of n.written)console.log(` done: ${r}`);for(let r of n.unchanged)console.log(` ok: ${r} (already wired)`);for(let r of n.skipped)console.log(` skip: ${r.target} \u2014 ${r.reason}`);let i=vc(n);i.verdict==="ready"?console.log(`
|
|
59
|
+
Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
|
|
60
|
+
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(`
|
|
61
|
+
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 Bl(e){let t=N(e);try{let n=m(t,"guided"),i=m(t,"yes"),r=m(t,"json");Jc({guided:n,yes:i,json:r,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let o=Fy(t,i),s=_y(r,i);(n||s)&&(o=await oy(o,{json:r})),r||(o.onStatus=l=>console.log(` ${l}`));let a=await Kc(o);r?x("setup",[],t,a):Yc(a),process.exitCode=a.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function oy(e,t){let{projectRoot:n,config:i}=te(),r=ke(n,i),o=zc({files:sy(n),watchEnabled:xe(i).enabled,readiness:r}),s=r.languages.map(p=>({id:`language:${p}`,scope:"project",label:`Index ${p}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(p=>({id:p.id,scope:p.scope==="repository"?"project":p.scope,label:p.label,reason:p.reason,selected:p.recommended})),l=xn(r.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...l.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${l.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 d=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,u=d?await Xc([...s,...a]):new Set([...ay(o.actions),...s.map(p=>p.id),...e.runHealth===!0?["run-health-analysis"]:[]]);return d&&cy(o.actions,u),Gy(e,u,o,r,d)}function sy(e){return{agentsMd:Mt(vl(e,"AGENTS.md")),claudeMd:Mt(vl(e,"CLAUDE.md"))}}function ay(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function cy(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let i=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${i.length>0?i.join(", "):"none"}`)}}function Gl(e){let t=N(e),n=wi({global:m(t,"global"),project:m(t,"project"),dryRun:m(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let i=el({projectRoot:_(),global:n.global,project:n.project,dryRun:m(t,"dryRun")});if(m(t,"json")){x("uninstall",[],t,i);return}for(let r of Zc(i,{verbose:m(t,"verbose")}))console.log(r)}var ly=[{option:"debounce",flag:"--debounce",field:"debounceMs",allowZero:!1},{option:"cooldown",flag:"--cooldown",field:"cooldownMs",allowZero:!0},{option:"gitPoll",flag:"--git-poll",field:"gitPollMs",allowZero:!1},{option:"idleTimeout",flag:"--idle-timeout",field:"idleTimeoutMs",allowZero:!0}];function dy(e){let t=ly.map(a=>({...a,value:j(e,a.option)})),n=["daemon","status","stop","prune"].filter(a=>m(e,a)),i=m(e,"json"),r=n.at(0)??"foreground";if(n.length>1)return{error:"choose only one of --daemon, --status, --stop, or --prune."};if(i&&r==="foreground")return{error:"--json requires --daemon, --status, --stop, or --prune."};let o=t.filter(a=>a.value!==void 0),s=uy(r,o);return s?{error:s}:{mode:r,json:i,provided:o}}function uy(e,t){if(["status","stop","prune"].includes(e)&&t.length>0)return`timing options (${t.map(i=>i.flag).join(", ")}) only apply when starting a foreground or daemon watcher; ${e==="prune"?"--prune does":"--status and --stop do"} not accept them.`;let n=t.find(({value:i,allowZero:r})=>!Number.isInteger(i)||(r?i<0:i<=0));return n?`${n.flag} requires ${n.allowZero?"a non-negative":"a positive"} integer.`:null}function py(e){let t=_(),n=Z(t),i={};for(let{field:s,value:a}of e)i[s]=a;e.length>0&&Object.assign(n.watch??={},i);let r=xe(n);n.watch=r;let o=Se(t,n);return{projectRoot:t,watchConfig:r,controllerOptions:{projectRoot:t,cacheDir:o.cacheDir,cliVersion:be,watchOverrides:i}}}async function Ul(e){let t=N(e),n=dy(t);if("error"in n){console.error(`error: ${n.error}`),process.exitCode=1;return}let{mode:i,json:r,provided:o}=n;if(i==="prune"){fy(t,r);return}let s=py(o);if(i==="status"){let a=Hl(at(s.controllerOptions),s.watchConfig.enabled);r?x("watch",[],t,a):Vl(a);return}if(i==="stop"){my(s,t,r);return}if(!s.watchConfig.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}i==="daemon"?hy(s,t,r,o):await gy(s)}function my(e,t,n){let{controllerOptions:i}=e;try{let r=sn(i);n?x("watch",[],t,r):console.log(r.disposition==="stopped"?`Stopped watch service${r.pid?` (pid ${r.pid})`:""}.`:"Watch service is already stopped.")}catch(r){console.error(`error: ${r instanceof Error?r.message:String(r)}`),process.exitCode=1}}function hy(e,t,n,i){let{controllerOptions:r,projectRoot:o}=e;try{if(i.length>0){let a=at(r);if(a.classification.kind==="live")throw new Error(`watch service pid ${a.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 s=on(r);n?x("watch",[],t,s):(console.log(`${s.disposition==="started"?"Started":"Reused"} watch service for ${o} (pid ${s.state.pid}).`),i.length>0&&console.log(`Process-local timing overrides: ${i.map(({flag:a,value:l})=>`${a}=${l}`).join(", ")}. These were not written to .scipquery.json.`))}catch(s){console.error(`error: ${s instanceof Error?s.message:String(s)}`),process.exitCode=1}}async function gy(e){let{projectRoot:t,watchConfig:n,controllerOptions:{watchOverrides:i}}=e;console.log(`Watching ${t}`),console.log(`Debounce: ${n.debounceMs}ms | Cooldown: ${n.cooldownMs}ms | Git poll: ${n.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
|
|
62
|
+
`);try{await di(t,be,i),console.log(`
|
|
63
|
+
Stopped.`)}catch(r){console.error(`
|
|
64
|
+
Watch error: ${r instanceof Error?r.message:String(r)}`),process.exitCode=1}}function fy(e,t){try{let n=ol();if(t)x("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 Hl(e,t=!0){let{classification:n}=e,i=It(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 wy(n)}}function Vl(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),xl(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";console.log(`Watch service: ${e.state} [${e.mode}]${t}`),yy(e),"reindexActivity"in e&&e.reindexActivity&&by(e.reindexActivity),"refreshRequests"in e&&e.refreshRequests&&xl(e.refreshRequests),xy(e)}function yy(e){Oy(e),"watcher"in e&&e.watcher&&console.log(`Watcher: ${gs(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}`)}function by(e){vy(e),(e.reflinkedBytes!==void 0||e.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${U(e.reflinkedBytes??0)} reflinked, ${U(e.fallbackCopiedBytes??0)} byte-copied`),Ry(e),Sy(e)}function Sy(e){e.confidence&&e.confidence!=="complete"&&console.log(`Reindex evidence: ${e.recordsRead??0} record(s) read, ${e.invalidRecords??0} invalid, ${e.readErrors??0} read error(s), ${e.ignoredPartialTailBytes??0} incomplete byte(s) ignored`)}function vy(e){console.log(`Recorded reindex activity (${e.windowStartedAt} to ${e.windowEndedAt}): ${e.runs} run(s) (${e.rebuilt} rebuilt, ${e.reused} reused, ${e.failed} failed), ${e.suppressed} redundant refresh(es) suppressed, ${U(e.estimatedWriteBytes??e.estimatedLogicalOutputBytes)} estimated writes (${U(e.estimatedLogicalOutputBytes)} logical output)${e.confidence&&e.confidence!=="complete"?` [${e.confidence} evidence]`:""}`)}function Ry(e){for(let[t,n]of Object.entries(e.byLanguage??{}).sort(([i],[r])=>i.localeCompare(r)))n&&console.log(`Reindex language ${t}: ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused), ${U(n.producedOutputBytes)} produced, ${Ty(n.durationMs)} cumulative indexer time`);e.languageAttribution&&e.languageAttribution!=="complete"&&console.log(`Reindex language attribution: ${e.languageAttribution}; ${e.unattributedRuns??0} completed run(s) unattributed, ${e.invalidLanguageDetails??0} invalid detail(s) ignored`)}function xy(e){if("typescriptSemantic"in e&&e.typescriptSemantic){let t=e.typescriptSemantic;console.log(`TypeScript semantics: ${t.state} (${t.projectsCreated} Projects, ${t.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let t=e.typescriptIndex,n=t.activeSessions===void 0||t.maxActiveSessions===void 0?"":`, ${t.activeSessions}/${t.maxActiveSessions} warm sessions`;console.log(`TypeScript index: ${t.state} (${t.initializations} warmups, ${t.programUpdates} updates, ${t.requests} requests${n}${t.sessionsEvicted?`, ${t.sessionsEvicted} evicted`:""})`),Wy(t)}}function xl(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function wy(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Ql(e){let t=N(e),{report:n}=Fl("status"),i=xe(Z(n.projectRoot)).enabled,r=Hl(at({projectRoot:n.projectRoot,cacheDir:zf(n.configuredDbPath),cliVersion:be}),i),o=_s(n.dbPath),s=us(n.dbPath,n.freshness.metaPath),a=ds(n.dbPath),l=Ut(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(m(t,"json")){x("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,localGenerations:a,rustSemanticSession:l,watchService:r,stats:Ly(n.exists)});return}ky(n,{affectedSetShadow:o,capabilities:m(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:l,watchService:r})}function $y(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})`:""}`),Jl(e.capabilities)}function ky(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)`),Uy(e.readiness),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: ${jy(e.freshness.lastRefresh)}`),Vl(t.watchService),Cy(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"),Ey(t.sqliteGeneration),Iy(t.localGenerations),console.log(`Shadow: ${Bs(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),My(e.exists),t.capabilities&&(console.log(""),Jl(e.capabilities),console.log("Run `scip-query capabilities` for the semantic control manual."))}function Jl(e){let t=wl(e.capabilities),n=wl(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 wl(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 Cy(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), ${U(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${U(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),Hy(e)}function Ey(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=Py(t);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 Py(e){return e?[e.affectedDocumentCount===void 0?null:`${e.affectedDocumentCount} affected`,e.changedDocumentCount===void 0?null:`${e.changedDocumentCount} changed`,e.producerDurationMs===void 0?null:`${e.producerDurationMs.toFixed(0)}ms producer`,`${e.converterDurationMs.toFixed(0)}ms convert`,e.patchDurationMs===void 0?null:`${e.patchDurationMs.toFixed(0)}ms patch`,`${e.scipCompanion??"current"} SCIP companion`].filter(t=>t!==null).join(", "):"no publication metrics"}function Iy(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${U(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${U(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 zl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ay(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Kl(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function jy(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 Ty(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function Ly(e){if(e)return ze(t=>{let n=St(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function My(e){e&&ze(t=>{let n=St(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${U(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function qy(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
|
|
65
|
+
Primary controls:`);for(let n of gn)console.log(` ${n.stage.toUpperCase().padEnd(8)} scip-query ${n.command} [${n.outputCost}] \u2014 ${n.question}`);console.log(`
|
|
66
|
+
Relationship controls:`);for(let n of an()){let r=e.relations.find(o=>o.family===n.family)?.status??"unsupported";console.log(` ${r.toUpperCase().padEnd(11)} ${n.family} ${n.direction} \u2014 ${n.question}`)}if(console.log(`
|
|
67
|
+
Strengths: ${Object.keys(xt).join(", ")}. Unavailable analyses: ${Qt.map(n=>n.id).join(", ")}.`),console.log(`
|
|
68
|
+
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}Dy(e),Ny(e)}function Dy(e){console.log(`
|
|
69
|
+
Control contracts:`);for(let t of gn)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(`
|
|
70
|
+
Relationship contracts:`);for(let t of an()){let i=e.relations.find(r=>r.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(`
|
|
71
|
+
Evidence strength legend:`);for(let[t,n]of Object.entries(xt))console.log(` ${t.toUpperCase().padEnd(11)} ${n}`);console.log(`
|
|
72
|
+
Explicitly unavailable relationship analyses:`);for(let t of Qt)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 Ny(e){console.log(`
|
|
73
|
+
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(`
|
|
74
|
+
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(`
|
|
75
|
+
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 Oy(e){if("projectRoot"in e&&e.projectRoot){let t="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${t}`)}}function Wy(e){e.heapUsedBytes!==void 0&&console.log(`TypeScript index memory: ${U(e.heapUsedBytes)}${e.heapLimitBytes===void 0?"":` / ${U(e.heapLimitBytes)} heap`}${e.softMemoryLimitBytes===void 0?"":`; ${U(e.softMemoryLimitBytes)} retirement mark`}${e.retireRequested?"; retirement requested":""}`)}function Fy(e,t){let n=m(e,"installMissing");return{dossierDir:y(e,"dossierDir"),runHealth:e.health===!0,installSkills:e.skills!==!1,installIndexers:n,installAstParsers:n&&e.parsers!==!1,...t?{automaticRefresh:!0}:{}}}function _y(e,t){return!e&&!t&&process.stdin.isTTY&&process.stdout.isTTY}function By(e){if(e.skipped.length>0){let t=e.languages.length>0?e.languages.join(", "):"none";console.log(`Reindex partial: available language output ${t}; ${e.skipped.length} skipped in ${(e.durationMs/1e3).toFixed(1)}s.`);for(let n of e.skipped)console.log(` skip: ${n.language} \u2014 ${n.reason}`)}else console.log(`${e.reused?"Reused":"Indexed"} ${e.languages.join(", ")} in ${(e.durationMs/1e3).toFixed(1)}s`)}function Gy(e,t,n,i,r){let o=t.has("create-agent-guidance")||t.has("update-agent-guidance"),s=n.actions.some(l=>l.id==="enable-automatic-refresh"),a=n.actions.some(l=>l.id==="install-indexers");return{...e,...s?{automaticRefresh:t.has("enable-automatic-refresh")}:{},noAgentGuidance:!o,...a?{installIndexers:r?t.has("install-indexers"):e.installIndexers===!0}:{},languages:i.languages.filter(l=>t.has(`language:${l}`)),installSkills:t.has("install-agent-skills"),installAstParsers:r?t.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:t.has("run-health-analysis")}}function Uy(e){for(let t of zl(e)){let n=t.available?"available":t.dependencyAvailable?"fallback":"unavailable",i=t.language==="typescript"?"TS sem:":`${t.language} sem:`;console.log(`${i.padEnd(9)}${n}${Kl(t)}`),t.reason&&console.log(`${t.language} note: ${t.reason}`)}}function Hy(e){e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${U(e.cleanup.deletedBytes??0)} removed`)}function mt(e){return{...e,options:b(e.options)}}function Le({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,...d}){let u=mt(d);return{...u,renderShape:"list",handler:js({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l})}}function wn({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,headers:d,dashWidths:u,...p}){let h=mt(p);return{...h,renderShape:"table",handler:Ts({commandName:h.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,headers:d,dashWidths:u})}}function Yl({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,key:d,...u}){let p=mt(u);return{...p,renderShape:"grouped-by-file",handler:Ls({commandName:p.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,key:d})}}function Xl({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,...d}){let u=mt(d);return{...u,renderShape:"sectioned-report",handler:Vn({commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,toJson:o,coverage:s,agentResult:a,after:l})}}function Zl({query:e,precomputed:t,emptyMessage:n,heuristicLabel:i,sections:r,before:o,toJson:s,coverage:a,agentResult:l,after:d,...u}){let p=mt(u),h={commandName:p.id,emptyMessage:n,heuristicLabel:i,sections:r,before:o,toJson:s,coverage:a,agentResult:l,after:d},v=Vn({...h,query:e});return{...p,renderShape:"sectioned-report",handler:Ms(h,t,v)}}function qt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,toJson:o,coverage:s,agentResult:a,after:l,...d}){let u=mt(d);return{...u,budget:u.budget??"semantic",renderShape:"sectioned-report",handler:qs(u.id,{commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,toJson:o,coverage:s,agentResult:a,after:l})}}function ed(e,t,n,i,r={count:e.length,loc:i}){let o=r.count===e.length&&r.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${r.count}, ${i} of ${r.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let d of e){let u=s.get(d.relativePath)??[];u.push(d),s.set(d.relativePath,u)}let a=[...s.entries()].map(([d,u])=>({file:d,bucket:u,totalLoc:u.reduce((p,h)=>p+h.loc,0)})).sort((d,u)=>u.totalLoc-d.totalLoc||d.file.localeCompare(u.file)),l=!0;for(let{file:d,bucket:u}of a){l||console.log(""),l=!1,console.log(` ${d}`),u.sort((p,h)=>p.startLine-h.startLine);for(let p of u){let h=p.implicitUsageReason?` [implicit usage: ${p.implicitUsageReason}]`:"";console.log(` ${ie(p.startLine,p.endLine)} (${p.loc} LOC) ${p.shortName}${h}`)}}}var Qy=20,nd=Q("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:q(t,0)||void 0,minLoc:$(n,"minLoc",1),includeTests:m(n,"includeTests"),skipBarrels:m(n,"skipBarrels"),includeMembers:m(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=Mr(e,r),s=m(n,"full"),a=Jy(o.symbols,m(n,"onlyDead"),m(n,"onlyInternal"),s),[l,d,u]=a,p=l.shown,h=d.shown,v=u.shown,k={total:p.length+h.length+v.length,deadCode:p.length,fileInternal:h.length,implicitUsage:v.length,loc:l.loc+d.loc+u.loc};if(m(n,"json")){x("dead",t,n,{...o,shown:{deadCode:p,fileInternal:h,implicitUsage:v},shownCounts:k,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:i.analysisBudget});return}zy(a,s,k.total)});function ki(e,t,n,i,r,o){let s=t?e:[],a=n?s:s.slice(0,Qy);return{enabled:t,title:i,description:r,totalLabel:o,shown:s,displayed:a,loc:s.reduce((l,d)=>l+d.loc,0),displayLoc:a.reduce((l,d)=>l+d.loc,0)}}function Jy(e,t,n,i){return[ki(e.filter(r=>r.kind==="dead-code"),!n,i,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
76
|
+
Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,"dead code"),ki(e.filter(r=>r.kind==="file-internal"),!t,i,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
77
|
+
single-use helper, an abstraction-in-progress, or a callback registered
|
|
78
|
+
through a framework path that static analysis cannot trace (signal
|
|
79
|
+
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
80
|
+
review case by case.`,"file-internal"),ki(e.filter(r=>r.kind==="implicit-usage"),!t&&!n,i,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
|
|
81
|
+
consumer that the static reference graph cannot trace. Investigation
|
|
82
|
+
signals only \u2014 not deletion candidates and not counted as dead code.`,"implicit usage")]}function zy(e,t,n){if(n===0){w.empty("No matching dead-code symbols found.");return}let i=!1;for(let o of e)o.shown.length!==0&&(i&&console.log(""),ed(o.displayed,o.title,o.description,o.displayLoc,{count:o.shown.length,loc:o.loc}),!t&&o.shown.length>o.displayed.length&&console.log(`
|
|
83
|
+
Showing top ${o.displayed.length} by LOC. Re-run with --full for the remaining ${o.shown.length-o.displayed.length}.`),i=!0);let r=e.filter(o=>o.enabled).map(o=>`${o.shown.length} ${o.totalLabel} (${o.loc} LOC)`);console.log(`
|
|
84
|
+
\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: ${n} symbols \u2014 ${r.join(" + ")}`)}var id=le("unused-imports",{query:({db:e,args:t,budget:n})=>Or(e,E(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
85
|
+
${e.length} unused import(s)`)}),rd=Q("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=po(e,{target:q(t,0)||void 0,scope:y(n,"scope"),minConsumers:$(n,"minConsumers",1),limit:P(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(m(n,"json")){x("locality-candidates",t,n,r,{analysisBudget:i.analysisBudget});return}if(r.length===0)return w.empty("No locality candidates found.");Pe("locality candidates");for(let o of r)Ky(o);console.log(`
|
|
86
|
+
${r.length} locality candidate(s) found.`)});function Ky(e){let t=e.sourceUnit.kind==="symbol"&&e.sourceUnit.startLine!==void 0&&e.sourceUnit.endLine!==void 0?L(e.sourceUnit.file,e.sourceUnit.startLine,e.sourceUnit.endLine):e.sourceUnit.file;console.log(`
|
|
87
|
+
${t} ${e.sourceUnit.shortName}`),console.log(` Current directory: ${e.currentDirectory}; tier: ${e.recommendedTier}; action: ${e.actionTier}`),console.log(` Consumer coverage: ${e.consumerCoverage}; consumers: ${e.consumerFiles.length}`),e.nearestCommonDirectory&&console.log(` Nearest common directory: ${e.nearestCommonDirectory}`),e.suggestedHome&&console.log(` Suggested home: ${e.suggestedHome}`),e.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${e.whyNoSuggestedHome}`),e.boundaryMarkers.length>0&&console.log(` Boundary markers: ${e.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${e.recommendation}`),Yy(e.consumerFiles);for(let n of e.counterevidence)console.log(` - counterevidence: ${n}`)}function Yy(e){if(e.length>0){for(let t of e.slice(0,8))console.log(` - consumer: ${t}`);e.length>8&&console.log(` - ... ${e.length-8} more consumer(s)`)}}var od=le("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>xo(e,{scope:y(t,"scope"),maxLoc:$(t,"maxLoc",15),limit:P(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${L(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
88
|
+
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
89
|
+
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
90
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
91
|
+
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
92
|
+
${e.length} passthrough candidate(s).`)});function Xy(e){let t=process.stderr.isTTY?2e3:3e4,n=Date.now(),i=n,r=!1;return{report:o=>{let s=Date.now();s-i<t||o.evaluated>=o.scanned||(i=s,r=!0,console.error(`${e}: ${o.evaluated}/${o.scanned} candidates scanned, ${o.matched} finding(s), ${Math.round((s-n)/1e3)}s elapsed`))},finish:()=>{r&&console.error(`${e}: scan complete in ${Math.round((Date.now()-n)/1e3)}s`)}}}var sd=Q("slice-cohesion",({db:e,args:t,opts:n,budget:i})=>{let r=q(t,0)||void 0,o=j(n,"scanLimit"),s=Xy("slice-cohesion"),a=null,l=Lo(e,{symbol:r,scope:y(n,"scope"),minLoc:$(n,"minLoc",12),minStatements:$(n,"minStatements",10),minClusterUnits:$(n,"minCluster",4),limit:P(n,"limit",20),scanLimit:o??i.scanLimit,onProgress:s.report,onProfile:d=>{a=d}});if(s.finish(),m(n,"json")){let u=Zy(r,a,l.length);x("slice-cohesion",t,n,l,{coverage:u,...r?{}:{analysisBudget:i.analysisBudget}});return}if(l.length===0)return w.empty(r?`No sliceable TypeScript function matched ${r}.`:"No low-cohesion functions found.");Pe("slice-cohesion candidates"),!r&&i.analysisBudget&&console.log(`Bounded scan: at most ${i.analysisBudget.scanLimit} candidates, largest first; the count below is not repository-wide.
|
|
93
|
+
`);for(let d of l)eb(d,!!r);console.log(`
|
|
94
|
+
${l.length} slice-cohesion candidate(s).`)});function Zy(e,t,n){return e||!t?{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}:t.scanLimitApplied?{complete:!1,totalKnown:!1,returned:n}:t.resultLimitApplied?{complete:!1,totalKnown:!0,returned:n,total:t.matchedResults,omitted:t.matchedResults-n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}}function eb(e,t){let n=e.clusters.filter(i=>i.role==="extraction");console.log(`
|
|
95
|
+
${L(e.relativePath,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC, ${e.statementCount} statements, ${e.archetype}${e.operational?", operational":""})`),console.log(` ${e.actionTier}; local model ${e.coverage.status}; ${n.length} extraction(s), ${n.filter(i=>i.narrow).length} narrow; ${e.tierReason}`),console.log(` Recommendation: ${wt(e.recommendation,600)}`);for(let i of e.evidenceReasons)console.log(` - ${wt(i,300)}`);t&&tb(e)}function tb(e){console.log(" Outputs:");for(let t of e.outputs)console.log(` ${t.id} [${t.kind}${t.guard?", guard":""}${t.hook?", hook":""}] slice ${t.sliceSize} statement(s)`);console.log(" Clusters:"),e.clusters.forEach((t,n)=>{let i=t.role==="remainder"?" (stays in place)":t.inputs.length>0?`; parameters${t.narrow?"":" (wide)"} ${t.inputs.join(", ")}`:"; no parameters";console.log(` ${n+1}. ${t.kind}, ${t.role}: ${t.units.length} statement(s) producing ${t.outputs.join(", ")}${i}`)}),console.log(" Statements:");for(let t of e.units??[])console.log(` ${String(t.index).padStart(3)} ${t.kind.padEnd(11)} ${ie(t.startLine,t.endLine)} ${wt(t.label,100)}`)}var ad=we("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(m(n,"plan")){let o=q(t,0),s=q(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:no(e,o,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let r=q(t,0);return r?{mode:"target",rows:to(e,r,{minSimilarity:$(n,"minSimilarity",.4),limit:P(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:io(e,{minSimilarity:$(n,"minSimilarity",.4),limit:P(n,"limit",20),scope:y(n,"scope"),minCallees:$(n,"minCallees",4),crossFileOnly:m(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;ub(t);return}if(e.mode==="target"){w.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",r=n==="source-tokens"?"Only tokens in":"Only in",o=[`
|
|
96
|
+
${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&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${r} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${r} B: ${t.uniqueToB.join(", ")}`),o.join(`
|
|
97
|
+
`)});return}w.list(e.rows,t=>`
|
|
98
|
+
${Math.round(t.similarity*100)}% similar:
|
|
99
|
+
A: ${t.shortNameA} (${t.fileA})
|
|
100
|
+
B: ${t.shortNameB} (${t.fileB})
|
|
101
|
+
Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
|
|
102
|
+
Recommendation: ${t.recommendation}
|
|
103
|
+
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
104
|
+
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
105
|
+
${e.rows.length} similar pair(s) found.`)}}),cd=st({commandName:"similar-files",query:({db:e,args:t,opts:n})=>ro(e,{minSimilarity:$(n,"minSimilarity",.5),limit:P(n,"limit",20),scope:y(n,"scope"),minDeps:j(n,"minDeps"),filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
106
|
+
${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(`
|
|
107
|
+
`)}),console.log(`
|
|
108
|
+
${e.length} similar pair(s) found.`)}}),ld=we("drift",{query:({db:e,args:t,opts:n,budget:i})=>Io(e,{scope:q(t,0),minDeviation:$(n,"minDeviation",5),semantic:i.semantic,includePatternDeviations:m(n,"patterns"),includeArchitecture:m(n,"architecture"),limit:P(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),w.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}`:"",r=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&r.push(` ${t.detail}`),r.join(`
|
|
109
|
+
`)},t=>t.file),e.architecture&&pb(e.architecture),console.log(`
|
|
110
|
+
${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)`:""}`)}}),dd=le("similar-signatures",{query:({db:e,opts:t,budget:n})=>Wo(e,{scope:y(t,"scope"),minLoc:$(t,"minLoc",3),maxShapeFrequency:$(t,"maxShapeFrequency",12),limit:P(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
|
|
111
|
+
Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(r=>` ${L(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
|
|
112
|
+
`);return`${n}
|
|
113
|
+
${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
114
|
+
${e.length} group(s) found.`)}),td=[],ud=le("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>{let i=eo(e,{scope:y(t,"scope"),maxLoc:$(t,"maxLoc",15),minLoc:$(t,"minLoc",3),limit:P(t,"limit",20),scanLimit:n.scanLimit});return td=i.exclusions,i.groups},format:e=>{let t=`
|
|
115
|
+
Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,r)=>` ${(r===0?"canonical":"duplicate").padEnd(9)} ${L(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
116
|
+
`);return`${t}
|
|
117
|
+
${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>{for(let t of td)console.log(`Policy exclusion: ${t.count} ${t.detail}`);console.log(`
|
|
118
|
+
${e.length} group(s) found.`)}}),pd=le("twin-drift",{query:({db:e,opts:t,budget:n})=>Ro(e,{scope:y(t,"scope"),minSimilarity:$(t,"minSimilarity",.3),includeHomonyms:m(t,"includeHomonyms"),limit:P(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
119
|
+
${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(r=>` ${L(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
|
|
120
|
+
`),i=e.firstDivergentTokens?`
|
|
121
|
+
first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
|
|
122
|
+
${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
|
|
123
|
+
${e.length} group(s) found.`)}),md=le("not-implemented",{query:({db:e,opts:t,budget:n})=>wo(e,{scope:y(t,"scope"),limit:P(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${L(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
|
|
124
|
+
${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
|
|
125
|
+
${e.length} reachable placeholder stub(s).`)}),hd=le("decorative-checkers",{query:({db:e,opts:t,budget:n})=>$o(e,{scope:y(t,"scope"),limit:P(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${L(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(`
|
|
126
|
+
${e.length} decorative checker candidate(s).`)}),gd=Q("test-quality",({db:e,args:t,opts:n,budget:i})=>{let r=ko(e,{scope:y(n,"scope"),limit:P(n,"limit",30),scanLimit:i.scanLimit,rotDays:j(n,"rotDays")});if(m(n,"json")){x("test-quality",t,n,r,{analysisBudget:i.analysisBudget});return}if(Pe("test-quality findings"),r.assertionFree.length+r.skipped.length+r.mockEcho.length===0){w.empty("No test-quality findings.");return}r.assertionFree.length>0&&(console.log(`
|
|
127
|
+
ASSERTION-FREE (${r.assertionFree.length})`),w.list(r.assertionFree,s=>` ${L(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),r.skipped.length>0&&(console.log(`
|
|
128
|
+
SKIPPED (${r.skipped.length})`),w.list(r.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),r.mockEcho.length>0&&(console.log(`
|
|
129
|
+
MOCK-ECHO (${r.mockEcho.length})`),w.list(r.mockEcho,s=>` ${L(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
|
|
130
|
+
${r.assertionFree.length} assertion-free, ${r.skipped.length} skipped, ${r.mockEcho.length} mock-echo.`)}),fd=Q("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=go(e,{scope:y(n,"scope"),minLoc:$(n,"minLoc",1),maxDepth:$(n,"maxDepth",5),scanLimit:i.scanLimit}),o=_(),s=m(n,"patch"),a=m(n,"json"),l=m(n,"verify")||s;if(s&&!m(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){x("cleanup-plan",t,n,r,{analysisBudget:i.analysisBudget});return}return w.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let d=wa(r),u=l?ba(o,r):void 0;if(a){x("cleanup-plan",t,n,{result:r,verification:u},{analysisBudget:i.analysisBudget});return}if(s){nb(o,r,d,u);return}ib(r),u&&rb(u)});function nb(e,t,n,i){let r=$a(i,n);if(r.length>0){for(let s of r)console.error(`error: ${s}`);process.exitCode=1;return}let o=xa(e,n);if(o.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${n.length} verified batch(es), ${t.totalLoc} LOC.`),console.log(o)}function ib(e){console.log(`Cleanup plan: ${e.totalSymbols} symbol(s), ${e.totalLoc} LOC across ${e.batches.length} batch(es).`),console.log(`Review external consumers, runtime effects, and tests before applying candidates. A checker pass only establishes checker compatibility.
|
|
131
|
+
`);for(let t of e.batches){let n=t.depth===0?`\u2500\u2500 Batch 0: initial no-observed-use candidates ( ${t.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${t.depth}: candidate after batch ${t.depth-1} (cascade, ${t.loc} LOC) \u2500\u2500`;console.log(n);for(let i of t.entries)console.log(` ${i.file}:${i.startLine+1}-${i.endLine+1} ${i.shortName} (${i.loc} LOC)`);t.filesEmptied.length>0&&console.log(` -> all indexed definitions selected: ${t.filesEmptied.join(", ")}`),console.log("")}if(e.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let t of e.blocked)console.log(` ${t.shortName} (${t.file}) blocked by ${t.blockingFiles.join(", ")}`)}}function rb(e){if(console.log(`
|
|
132
|
+
Verifying batches against the project checker (isolated snapshot of committed HEAD)...`),e.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 i of e.checkers)console.log(` Checker: ${i}`);if(e.unavailableReason){console.log(` UNAVAILABLE: ${e.unavailableReason}.`);return}ob(e);let t=sb(e.checkers),n=ab(e.checkers);for(let i of e.batches)if(i.status==="verified")console.log(` Batch ${i.depth}: VERIFIED (${t})${n}`);else{console.log(` Batch ${i.depth}: FAILED${i.reason?` (${i.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let r of i.errors??[])console.log(` ${r}`)}}function ob(e){if(e.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${e.uncoveredFiles.join(", ")}`),e.baselineErrors>0&&console.log(` Baseline has ${e.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),e.workingTree.state==="unavailable"&&console.log(` WARNING: working-tree inspection unavailable: ${e.workingTree.reason}`),e.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${e.dirtyOverlap.join(", ")}`),e.dirtyWorkingTree.length>0){let t=e.dirtyWorkingTree.slice(0,5),n=e.dirtyWorkingTree.length-t.length;console.log(` WARNING: verification ran at HEAD; ${e.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${t.join(", ")}${n>0?`, ... ${n} more`:""}`)}}function sb(e){return e.join(", ")}function ab(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var yd=Q("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=m(n,"full"),o=Co(e,{windowCommits:$(n,"window",100),minSimilarity:j(n,"minSimilarity"),limit:P(n,"limit",30),scope:y(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded"});if(m(n,"json")){x("recent-duplicates",t,n,o,{analysisBudget:i.analysisBudget});return}if(!o.available)return w.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return w.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Pe("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
|
|
133
|
+
`),db(o.rootCauseGroups);for(let s of o.findings){let a=s.sharedEvidence.slice(0,16).join(", ");s.kind==="echo"?(console.log(` ${Math.round(s.similarity*100)}% ECHO ${s.domain} ${s.echoFile} ${s.echoSymbol} (added ${s.echoAgeCommits} commits ago)`),console.log(` duplicates established ${s.establishedFile} ${s.establishedSymbol}`)):(console.log(` ${Math.round(s.similarity*100)}% TWIN ${s.domain} ${s.echoFile} ${s.echoSymbol}`),console.log(` and ${s.establishedFile} ${s.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${s.basis}`),a.length>0&&console.log(` shared: ${a}`)}console.log(`
|
|
134
|
+
${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),bd=H(({db:e,args:t,opts:n})=>{let i=m(n,"full"),r=vo(e,{doc:t[0]===void 0?void 0:E(t,0),limit:P(n,"limit",20),minCoupling:$(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(m(n,"json")){x("doc-drift",t,n,r);return}if(!r.available)return w.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return w.empty(`No drifting docs found across ${r.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Pe("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
|
|
135
|
+
`);for(let o of r.findings)cb(o);console.log(`
|
|
136
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)});function cb(e){let t=e.snapshotExcluded?" [snapshot (excluded by policy)]":"",n=e.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${e.staleness} ${e.doc}${t}${n}`);for(let i of e.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${i} \u2014 that file no longer exists`);for(let i of e.subjects.slice(0,4))lb(i)}function lb(e){let t=e.evidence==="both"?`referenced by doc + coupled ${e.coChanges}x`:e.evidence==="reference"?"referenced by doc":`coupled ${e.coChanges}x historically`;console.log(` ${e.changesSinceDocUpdate} change(s) since doc update ${e.file} (${t}; ${e.actionTier}/${e.docIntent})`);let n=e.docIntentReasons[0];n&&console.log(` intent: ${n}`);let i=e.citationContexts?.[0];i&&console.log(` cited claim: ${wt(i)}`)}var Sd=le("unused-params",{query:({db:e,opts:t,budget:n})=>To(e,{scope:y(t,"scope"),limit:P(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${L(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
137
|
+
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(`
|
|
138
|
+
${e.length} function(s) with trailing unused parameters.`)});function db(e){let t=e?.filter(n=>n.count>1)??[];if(t.length>0){console.log(`Root-cause groups (${t.length}):`);for(let n of t)console.log(` ${n.count} pair(s) ${n.kind.toUpperCase()} ${n.domain} ${Math.round(n.maxSimilarity*100)}% max`),n.establishedFile&&n.establishedSymbol&&console.log(` established: ${n.establishedFile} ${n.establishedSymbol}`),console.log(` files: ${n.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${n.recommendation}`);console.log("")}}function ub(e){let t=e.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
|
|
139
|
+
${Math.round(e.similarity*100)}% ${t}
|
|
140
|
+
`),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)`),console.log(` Evidence class: ${e.evidenceClass} (tier: ${e.actionTier})`),console.log(` Recommendation: ${e.recommendation}
|
|
141
|
+
`),console.log(` Shared evidence (${e.sharedEvidence.length}):`);for(let n of e.sharedEvidence)console.log(` ${n}`);if(e.uniqueToA.length>0){console.log(`
|
|
142
|
+
Unique to A (${e.uniqueToA.length}):`);for(let n of e.uniqueToA)console.log(` ${n}`)}if(e.uniqueToB.length>0){console.log(`
|
|
143
|
+
Unique to B (${e.uniqueToB.length}):`);for(let n of e.uniqueToB)console.log(` ${n}`)}console.log(`
|
|
144
|
+
Strategy: ${e.consolidationStrategy}`)}function pb(e){let t=e.edges.filter(n=>n.policyStatus==="undeclared").length;if(console.log(`
|
|
145
|
+
Architecture context: ${e.coverage.mappedFiles}/${e.coverage.totalFiles} file(s) mapped; ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared; ${t} undeclared boundary edge(s).`),e.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${e.reciprocalPairs.length}):`);for(let n of e.reciprocalPairs)console.log(` ${n.boundaries[0]} <-> ${n.boundaries[1]}`)}if(e.cycles.length>0){console.log(` Connected boundary groups (${e.cycles.length}):`);for(let n of e.cycles){let i=n.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${n.boundaries.join(", ")} }${i}`)}}}var vd=we("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>oo(e,{minSimilarity:$(n,"minSimilarity",.62),minTokens:$(n,"minTokens",8),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
146
|
+
${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(`
|
|
147
|
+
`)}),console.log(`
|
|
148
|
+
${e.length} duplicated React component pair(s) found.`)}}),Rd=we("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>so(e,{minSimilarity:$(n,"minSimilarity",.45),minSharedBehaviors:$(n,"minSharedBehaviors",6),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
149
|
+
${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(`
|
|
150
|
+
`)}),console.log(`
|
|
151
|
+
${e.length} React hook candidate pair(s) found.`)}}),xd=we("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>ao(e,{minComponentLines:$(n,"minComponentLines",300),minFileLines:$(n,"minFileLines",800),minJsxTokens:$(n,"minJsxTokens",80),minBehaviorTokens:$(n,"minBehaviorTokens",40),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{w.list(e,t=>[`
|
|
152
|
+
${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(`
|
|
153
|
+
`)),console.log(`
|
|
154
|
+
${e.length} large React component(s) found.`)}}),wd=we("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>co(e,{minSimilarity:$(n,"minSimilarity",.62),minTokens:$(n,"minTokens",8),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
155
|
+
${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(`
|
|
156
|
+
`)}),console.log(`
|
|
157
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),$d=we("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>lo(e,{minSimilarity:$(n,"minSimilarity",.45),minSharedBehaviors:$(n,"minSharedBehaviors",6),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
158
|
+
${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(`
|
|
159
|
+
`)}),console.log(`
|
|
160
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),kd=we("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>uo(e,{minTotalLines:m(n,"reviewThresholds")&&Ns(n,"minTotalLines")==="default"?300:$(n,"minTotalLines",800),minTemplateLines:$(n,"minTemplateLines",300),minScriptLines:$(n,"minScriptLines",300),minStyleLines:$(n,"minStyleLines",500),limit:P(n,"limit",20),scope:y(n,"scope"),scanLimit:i.scanLimit,filePattern:q(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{w.list(e,t=>{let n=[`
|
|
161
|
+
${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(`
|
|
162
|
+
`)}),console.log(`
|
|
163
|
+
${e.length} large Vue view pressure file(s) found.`)}});function he(e){return{docs:f("Cleanup"),...e}}function Y({heuristicLabel:e,...t}){return he({...t,heuristic:{label:e}})}var $n=[he({id:"unused-params",command:"unused-params",agent:S("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:b([c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Maximum findings",g,30),c("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:f("Cleanup",["scip-query unused-params -s src/services"]),handler:Sd}),he({id:"cleanup-plan",command:"cleanup-plan",agent:S("Which unused-code candidates form deletion batches in dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository",W("repository-preview")),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--min-loc <n>","Only include symbols >= N lines",g,1),c("--max-depth <n>","Maximum cascade depth",g,5),c("--verify","Apply batches in an isolated HEAD snapshot and run the project checker (tsc / cargo check)"),c("--patch","With --verify, print the compiler-verified deletion patch to stdout"),c("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:f("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:fd}),he({id:"recent-duplicates",command:"recent-duplicates",agent:S("Which recently added files contain code similar to code in older files?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Similarity candidates in recently added files, oriented by file age; function creation time is not known",options:b([c("--window <n>",'How many commits back counts as "recent"',g,100),c("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ce),c("-n, --limit <n>","Maximum findings",g,30),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:f("Cleanup",["scip-query recent-duplicates --window 50"]),handler:yd}),he({id:"doc-drift",command:"doc-drift [doc]",agent:S("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:b([c("-n, --limit <n>","Maximum docs to report",g,20),c("--min-coupling <n>","Minimum historical co-changes to track a subject",g,3),c("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:f("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:bd}),he({id:"dead",command:"dead [scope]",agent:S("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:b([c("--min-loc <n>","Only show symbols >= N lines",g,1),c("--include-tests","Include definitions from test files (test references always count)"),c("--skip-barrels","Ignore refs from barrel re-export files"),c("--include-members","Include class members"),c("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),c("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:f("Cleanup",["scip-query dead --min-loc 10"]),handler:nd}),he({id:"unused-imports",command:"unused-imports <file>",agent:S("Which imports in this file are unused?","unused local binding candidates and their files",["file"],"bounded"),description:"Find imports not referenced in the same file",options:b([c("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:id}),Y({id:"similar",command:"similar [symbol] [other]",agent:S("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:b([c("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",ce,.4),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--min-callees <n>","Minimum callees to consider",g,4),c("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),c("--plan","Render a consolidation preview for two symbols"),c("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:ad}),Y({id:"similar-files",command:"similar-files [file]",agent:S("Which files reference similar sets of dependencies?","file pairs with filtered dependency-set overlap; conceptual ownership requires review",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:b([c("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ce,.5),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--min-deps <n>","Minimum dependencies after excluding globally common dependencies (default 4, or 1 with a file)",g),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:cd}),Y({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:S("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:b([c("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ce,.62),c("--min-tokens <n>","Minimum structural tokens to consider",g,8),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:vd}),Y({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:S("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:b([c("--min-similarity <n>","Minimum behavior similarity (0-1)",ce,.45),c("--min-shared-behaviors <n>","Minimum shared behavior tokens",g,6),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Rd}),Y({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:S("Which React components exceed the selected line or vocabulary thresholds?","component identities, line counts, and distinct JSX/behavior token counts",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:b([c("--min-component-lines <n>","Minimum component lines",g,300),c("--min-file-lines <n>","Minimum file lines",g,800),c("--min-jsx-tokens <n>","Minimum JSX structure tokens",g,80),c("--min-behavior-tokens <n>","Minimum behavior tokens",g,40),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:xd}),Y({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:S("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:b([c("--min-similarity <n>","Minimum template similarity (0-1)",ce,.62),c("--min-tokens <n>","Minimum structural tokens to consider",g,8),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:wd}),Y({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:S("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:b([c("--min-similarity <n>","Minimum behavior similarity (0-1)",ce,.45),c("--min-shared-behaviors <n>","Minimum shared behavior tokens",g,6),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:$d}),Y({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:S("Which Vue views exceed selected template, script, style, or delegated-code line thresholds?","view identities and measured line counts; responsibility boundaries require review",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:b([c("--min-total-lines <n>","Minimum component plus one-hop delegated composable lines",g,800),c("--min-template-lines <n>","Minimum template lines",g,300),c("--min-script-lines <n>","Minimum script lines",g,300),c("--min-style-lines <n>","Minimum style lines",g,500),c("--review-thresholds","Use lower review thresholds without changing health scoring"),c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:kd}),Y({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:S("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:b([c("-s, --scope <path>","Limit scan mode to files matching path"),c("--min-consumers <n>","Minimum consumers in scan mode",g,1),c("-n, --limit <n>","Number of results",g,20),c("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:f("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:rd}),Y({id:"drift",command:"drift [module]",agent:S("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:b([c("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",F,5),c("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),c("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),c("-n, --limit <n>","Number of results",g,50),c("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:ld}),Y({id:"passthrough-candidates",command:"passthrough-candidates",agent:S("Which small callables appear to forward to a single target?","callable identities, forwarding targets, and source evidence",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--max-loc <n>","Maximum LOC for candidates",g,15),c("-n, --limit <n>","Number of results",g,30),c("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:od}),Y({id:"slice-cohesion",command:"slice-cohesion [symbol]",agent:{...S("Which functions compute several independent results in one body, and where are the local slices disjoint?","per-function backward-slice partitions, outputs, observed input names, and analysis gaps; extraction safety requires source review",["symbol"],"bounded","repository"),resultUnits:{kind:"rows"}},description:"Find low-cohesion candidates from backward slices: outputs whose statements never meet are separate local computations",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--min-loc <n>","Minimum function LOC to scan",g,12),c("--min-statements <n>","Minimum counted statements before a partition is reported",g,10),c("--min-cluster <n>","Minimum statements in an extractable cluster",g,4),c("-n, --limit <n>","Number of results to print (cannot be combined with --full)",g,20),c("--scan-limit <n>","Maximum candidates to analyze, largest first; bounds the work, unlike --limit",g),c("--full","Analyze every candidate on large indexes (cannot be combined with --limit)")]),heuristicLabel:"slice-cohesion candidates",budget:"candidate-scan",renderShape:"custom",handler:sd}),Yl({id:"redundant-reexports",command:"redundant-reexports",agent:S("Which re-export declarations have no resolved local source consumers?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find re-export candidates with no resolved local source imports or re-exports; external use is unknown",options:[c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Number of results",g,30),c("--full","Run unbounded analysis on large indexes")],docs:f("Cleanup"),query:({db:e,opts:t})=>Oo(e,{scope:y(t,"scope"),limit:P(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
164
|
+
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
165
|
+
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
166
|
+
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
167
|
+
${e.length} redundant re-export(s).`)}),he({id:"duplicate-bodies",command:"duplicate-bodies",agent:S("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:b([c("-s, --scope <path>","Limit to files matching path"),c("--max-loc <n>","Maximum LOC per function body",g,15),c("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",g,3),c("-n, --limit <n>","Number of groups",g,20),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:ud}),he({id:"twin-drift",command:"twin-drift",agent:S("Which similarly named functions have matching or divergent normalized bodies?","function groups with name, token, and divergence evidence; shared responsibility requires review",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",ce,.3),c("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),c("-n, --limit <n>","Number of groups",g,20),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:pd}),Y({id:"not-implemented",command:"not-implemented",agent:S("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),description:"Placeholder candidates with observed consumer or entry-surface evidence: throw-stub, TODO plus default return, or empty body",options:b([c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Number of results",g,30),c("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"placeholder stub candidates",budget:"candidate-scan",renderShape:"list",docs:f("Cleanup",["scip-query not-implemented -s src/services"]),handler:md}),Y({id:"decorative-checkers",command:"decorative-checkers",agent:S("Which checker-named callables lack detected local failure syntax?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Checker candidates lacking detected explicit failure syntax; implicit exceptions and property effects are not proved absent",options:b([c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Number of results",g,30),c("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:f("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:hd}),he({id:"test-quality",command:"test-quality",agent:S("Which test bodies lack detected assertions, remain skipped, or repeat mock literals?","test identities with assertion, skip-age, and mock-literal 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:b([c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Maximum findings per sub-check",g,30),c("--rot-days <n>","Skips older than this many days are reported as rot",g,60),c("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:f("Cleanup",["scip-query test-quality -s tests/queries"]),handler:gd}),he({id:"similar-signatures",command:"similar-signatures",agent:S("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Group functions by normalized signature text; shared type identity or responsibility is not established",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--min-loc <n>","Minimum LOC per function",g,3),c("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",g,12),c("-n, --limit <n>","Number of groups",g,20),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:dd})];var mb=H(({db:e,args:t,opts:n})=>{let i=St(e);if(m(n,"json")){x("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definition mentions: ${i.definitions}`),console.log(`Reference mentions: ${i.references}`),console.log(`Index size: ${U(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Database modified: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Cd=[{id:"stats",command:"stats",description:"Show index statistics",agent:S("How many rows does the current index contain, and when was its database file modified?","document, symbol, definition-mention, reference-mention, file-size, and modification-time totals",[],"complete","repository"),options:b(),renderShape:"custom",docs:f("Core"),handler:mb}];var hb=Ds("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Qr(e,{limit:P(t,"limit",20),scope:y(t,"scope"),minFanIn:$(t,"minFanIn",2),minFanOut:$(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),gb=H(({db:e,args:t,opts:n})=>{let i=q(t,0),r=P(n,"limit",30);if(i){let l=Fr(e,i);if(m(n,"json")){x("fan-in",t,n,{mode:"symbol",symbol:i,rows:l});return}if(l.length===0)return w.empty(`No fan-in for ${i}.`);w.list(l,d=>` ${String(d.count).padStart(4)} files ${d.name}`);return}let o=Br(e,{limit:r,scope:y(n,"scope")});if(m(n,"json")){x("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let l of o)s.set(l.name,(s.get(l.name)??0)+1);let a=new Set([...s].filter(([,l])=>l>1).map(([l])=>l));w.table(["files","symbol"],o.map(l=>` ${String(l.count).padStart(5)} ${l.name}${a.has(l.name)?` [${l.definedIn}]`:""}`))}),fb=H(({db:e,args:t,opts:n})=>{let i=q(t,0),r=P(n,"limit",30);if(i){let s=_r(e,i);if(m(n,"json")){x("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return w.empty(`No fan-out for ${i}.`);w.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Gr(e,{limit:r,scope:y(n,"scope")});if(m(n,"json")){x("fan-out",t,n,{mode:"top",rows:o});return}w.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),yb=H(({db:e,args:t,opts:n})=>{let i=q(t,0),r=q(t,1),o=P(n,"limit",20);if(!!i!=!!r)throw new Error("Supply both files for pair coupling, or neither for ranking.");if(i&&r){let a=Ur(e,i,r);if(m(n,"json")){x("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=Hr(e,{limit:o,scope:y(n,"scope")});if(m(n,"json")){x("coupling",t,n,{mode:"top",rows:s});return}w.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}`))}),bb=st({commandName:"cycles",query:({db:e,opts:t})=>Vr(e,{scope:y(t,"scope"),maxDepth:$(t,"maxDepth",10),edgeBasis:m(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(`
|
|
168
|
+
Component ${t+1} (${i.length} files; ${n.classification??n.kind}; one witness follows):`);for(let r=0;r<n.path.length;r++){let o=r<n.path.length-1?" \u2192":" (cycle witness)";console.log(` ${n.path[r]}${o}`)}i.length>new Set(n.path.slice(0,-1)).size&&console.log(` Full component: ${i.join(", ")}`)}console.log(`
|
|
169
|
+
${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),Sb=st({commandName:"architecture",query:({db:e,opts:t})=>nt(e,{scope:y(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{vb(e),Rb(e),xb(e),wb(e),$b(e),kb(e),Cb(e),Eb(e)},after:e=>{Qe(e).length>0&&(process.exitCode=1)}});function vb(e){let t=Qe(e);for(let n of e.coverage.limitations??[])console.log(`Scope limitation: ${n}`);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(e.configured?e.coverage.scope?"No configured violation observed in this scoped projection; repository-wide checks remain unevaluated.":"Configured architecture checks passed; undeclared dependency directions remain unknown.":"No architecture policy is configured."):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.dependencyRoles&&console.log(`${e.dependencyRoles.excludedTestEdges} test-related file edges excluded from production groups. ${e.dependencyRoles.cycleMeaning}`)}function Rb(e){if(e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0){let t=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}${t}`)}if(e.coverage.ambiguousFiles.length>0){let t=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}${t}`);for(let n of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${n.file} -> ${n.boundaries.join(", ")}`)}}function xb(e){if(e.forbiddenEdges.length>0){console.log(`
|
|
170
|
+
Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
|
|
171
|
+
No forbidden dependency edges found.`);if(e.testForbiddenEdges?.length){console.log(`
|
|
172
|
+
Test imports violating explicit boundary rows (${e.testForbiddenEdges.length}):`);for(let t of e.testForbiddenEdges)console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} test-related dependencies`)}if(e.staleAllowances.length>0){let t=e.policyCoverage.requiresMinimalPolicy?" [violates requireMinimalPolicy]":"";console.log(`
|
|
173
|
+
Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.${t}`);for(let n of e.staleAllowances)console.log(` ${n.from} -> ${n.to}`)}}function wb(e){if(e.boundaryLimits.length>0){console.log(`
|
|
174
|
+
Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
|
|
175
|
+
Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}}function $b(e){if(e.fragileEdges.length>0){console.log(`
|
|
176
|
+
Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}}function kb(e){if(e.coarseBoundaries.length>0){console.log(`
|
|
177
|
+
Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let i of n.examples.slice(0,3))console.log(` ${i.fromFile} -> ${i.toFile}`)}}}}function Cb(e){if(e.edges.length>0){console.log(`
|
|
178
|
+
Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
|
|
179
|
+
Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}}function Eb(e){if(e.cycles.length>0){console.log(`
|
|
180
|
+
Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n} [${t.origin??"group origin unavailable"}]`),t.fileCycleMembers?.length&&console.log(` file-cycle members (types included): ${t.fileCycleMembers.join(", ")}`);for(let i of t.narrowestEdges)console.log(` inspect ${i.from} -> ${i.to}: ${i.fileEdgeCount} file edge(s)`)}}}function Pb(){return st({commandName:"dependency-depth",query:({db:e,opts:t})=>Kr(e,{limit:P(t,"limit",10),scope:y(t,"scope"),minDepth:$(t,"minDepth",3),edgeBasis:m(t,"importsOnly")?"imports":"symbol-references"}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
|
|
181
|
+
Chain ${t+1} (condensed depth ${e[t].depth}; ${e[t].edgeBasis}):`);for(let n of e[t].components){let i=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${i}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}})}var Ib=Pb(),Ab=H(({db:e,args:t,opts:n})=>{let i=q(t,0),r=Xr(e,{search:i,scope:y(n,"scope")});if(m(n,"json")){x("entrypoints",t,n,r,{coverage:{complete:!0,totalKnown:!0,returned:r.length,total:r.length,omitted:0}});return}if(r.length===0){console.log(i?`No detected entry candidate matched ${JSON.stringify(i)}.`:"No entry candidates were detected by the available providers.");return}w.list(r,o=>`[${o.confidence}] ${o.file}:${O(o.startLine)} ${o.shortName} \u2014 ${o.evidence.join(", ")}; static callers=${o.observedCallerCount}`)}),jb=H(({db:e,args:t,opts:n})=>{let i=E(t,0),r=Zr(e,i,{expand:D(n,"expand")});if(r.kind!=="matched"&&(process.exitCode=1),m(n,"json")){x("entry-map",t,n,r,{coverage:r.kind==="matched"?{complete:!0,totalKnown:!0,returned:r.regions.length,total:r.regions.length,omitted:0}:{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0}});return}if(r.kind!=="matched")return Tb(r,i);Lb(r)});function Tb(e,t){if(e.kind==="missing")return process.exitCode=1,w.empty(`No symbol matched '${t}'.`);if(e.kind==="ambiguous"){process.exitCode=1,console.error(`'${t}' is ambiguous across ${e.total} definitions:`);for(let n of e.candidates)console.error(` ${n.relativePath}:${O(n.startLine)} ${n.shortName}`),console.error(` symbol: ${n.symbol}`);return}if(e.kind==="not-entry")return process.exitCode=1,w.empty(`${e.shortName} (${e.file}) is not a detected entry point. ${e.reason}`)}function Lb(e){console.log(`Entry: ${e.entry.shortName} (${e.entry.file})`),console.log(`Evidence: ${e.entry.evidence.join(", ")}
|
|
182
|
+
`),console.log("\u2550\u2550\u2550 COLLAPSED FILE REGIONS \u2550\u2550\u2550");for(let t of e.regions){let n=t.expanded?"expanded":`expand with --expand '${t.id}'`;console.log(` depth ${t.minDepth} ${t.id}
|
|
183
|
+
${t.symbolCount} symbol(s); ${t.internalEdgeCount} internal edge(s); ${t.externalCallCount} unresolved/external call(s); ${t.incomingRegionIds.length} incoming region(s); ${t.outgoingRegionIds.length} outgoing region(s)
|
|
184
|
+
${n}`)}if(e.regionEdges.length>0){console.log(`
|
|
185
|
+
\u2550\u2550\u2550 CROSS-REGION CALLS \u2550\u2550\u2550`);for(let t of e.regionEdges)console.log(` ${t.fromRegionId} \u2192 ${t.toRegionId} (${t.callCount} edge(s); ${t.evidence.join(", ")})
|
|
186
|
+
${t.fromSymbols.join(", ")} \u2192 ${t.toSymbols.join(", ")}`)}Mb(e),e.unmatchedExpansions.length>0&&console.error(`
|
|
187
|
+
Unmatched expansion id(s): ${e.unmatchedExpansions.join(", ")}`),console.log(`
|
|
188
|
+
Coverage: ${e.coverage.symbolCount} symbol(s), ${e.coverage.symbolEdgeCount} call edge(s), ${e.coverage.regionCount} region(s), ${e.coverage.externalCallCount} unresolved/external call(s).`),console.log("Complete within indexed static call edges; dynamic dispatch is not represented.")}function Mb(e){let t=e.regions.filter(n=>n.expanded);if(t.length>0){console.log(`
|
|
189
|
+
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`);for(let n of t){console.log(` ${n.id}`);for(let i of n.symbols)console.log(` depth ${i.depth} ${i.shortName}
|
|
190
|
+
${i.symbol}`);for(let i of n.internalEdges)console.log(` call ${i.fromShortName} \u2192 ${i.toShortName} (${i.source})`);for(let i of n.externalCalls)console.log(` unresolved/external ${i.fromShortName} \u2192 ${i.toShortName} (${i.reportedFile}; ${i.source})`)}}}var Ed=[wn({id:"hotspots",command:"hotspots",description:"Rank symbols by referencing chunks, or incoming evidence rows when SCIP mentions are unavailable",agent:S("Which symbols have the most observed cross-file reference evidence?","ranked symbol identities with explicit evidence basis and counting units",[],"bounded","repository"),options:[c("-n, --limit <n>","Number of results",g,30),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")],docs:f("Graph"),headers:["count","files","unit","symbol"],query:({db:e,opts:t})=>qr(e,{limit:P(t,"limit",30),scope:y(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.countUnit} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:{...Ke("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",ae,Et(["symbol","construct"],["Entry-point detection reports evidenced external roots and candidates; it does not establish task relevance."])),resultUnits:{kind:"field",field:"rows"}},options:b([c("-n, --limit <n>","Number of results for top mode",g,30),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:f("Graph"),handler:gb},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:S("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:b([c("-n, --limit <n>","Number of results for top mode",g,30),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:f("Graph"),handler:fb},{id:"coupling",command:"coupling [file1] [file2]",description:"Count shared-symbol coupling between two files, or rank file pairs by that metric",agent:S("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:b([c("-n, --limit <n>","Number of results for top mode",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:f("Graph"),handler:yb},{id:"cycles",command:"cycles",description:"Find every cyclic file-dependency component and show one deterministic witness for each",agent:S("Which file dependency cycles exist?","dependency-cycle file chains",[],"complete","repository"),options:b([c("-s, --scope <path>","Limit to files matching path"),c("--imports-only","Analyze resolved imports and re-exports, including type-only dependencies, instead of all symbol references"),c("--max-depth <n>","Deprecated compatibility option; SCC detection no longer truncates by depth",g,10)]),renderShape:"custom",docs:f("Graph"),handler:bb},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:S("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:b([c("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",claims:re(["index-generation","live-workspace"],[T("declared-policy","boundaries","repository-source"),T("dependency-observations","edges","compiler-graph"),T("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:f("Graph",["scip-query architecture --json"]),handler:Sb},{id:"bottlenecks",command:"bottlenecks",description:"Rank coordination hubs by incoming evidence files \xD7 outgoing cross-file callable targets",agent:S("Which callable symbols are high-connectivity coordination hubs?","ranked callable symbols with incoming evidence-file and outgoing callable-target counts",[],"bounded","repository"),options:b([c("-n, --limit <n>","Number of results",g,20),c("-s, --scope <path>","Limit to files matching path"),c("--min-fan-in <n>","Minimum fan-in",g,2),c("--min-fan-out <n>","Minimum fan-out",g,2),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:f("Graph"),handler:hb},{id:"dependency-depth",command:"dependency-depth",description:"Find longest paths through the SCC-condensed file dependency graph",agent:S("Which file dependency paths have the greatest condensed depth?","ranked component paths with full cycle membership, edge basis, and condensed depth",[],"bounded","repository"),options:b([c("-n, --limit <n>","Number of paths to show",g,10),c("-s, --scope <path>","Limit to files matching path"),c("--min-depth <n>","Minimum condensed component depth",g,3),c("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),c("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:f("Graph"),handler:Ib},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...Ke("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and observed static caller counts",["pattern"],"complete","repository",ae,Et(["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 observed static 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:b([c("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:f("Graph",["scip-query entrypoints","scip-query entrypoints work-session"]),handler:Ab},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...Ke("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,ae,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:b([c("--expand <region-id>","Expand one file region; repeat to expand several together",B,[])]),renderShape:"custom",docs:f("Graph",["scip-query entry-map start","scip-query entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:jb},qt({id:"call-graph",command:"call-graph <symbol>",description:"Show static may-call edges with exact/candidate evidence and explicit blind spots",agent:S("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:[c("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:f("Graph"),query:({db:e,args:t,budget:n})=>$r(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:ue(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(de(t,String(n[0])),console.log(`Symbol: ${e.shortName}
|
|
191
|
+
`))},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 qb=Q("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=E(t,0),o=Eo(e,r,{semantic:i.semantic});if(m(n,"json")){x("complexity",t,n,Ae(e,r,o,"complexity"),{analysisBudget:i.analysisBudget});return}if(!o)return w.empty(ue(e,r,"Symbol not found."));de(e,r),console.log(`${L(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
|
|
192
|
+
`),console.log(` LOC: ${o.loc}`),console.log(` Branches: ${o.branches}`),console.log(` Cyclomatic estimate: ${o.cyclomaticEstimate}`),console.log(` Metric rules: ${o.metricRules}`),console.log(` Callees: ${o.calleeCount}`),console.log(` Candidate targets: ${o.candidateCalleeCount}`),console.log(` Referencing files: ${o.fanIn}`),console.log(` External callees: ${o.fanOut}`)}),Pd=[{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:S("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:b([c("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:f("Health"),handler:qb}];function kn(e){let t=e.riskLevel==="high"?" *** HIGH RISK ***":e.riskLevel==="medium"?" * medium risk *":"",n=e.riskReasons??[],i=n.length===0?"":` [why: ${n.map(r=>`${r.kind}: ${r.detail}`).join("; ")}]`;return` ${ie(e.startLine,e.endLine)} ${e.shortName} [${e.externalConsumers} consumers]${t}${i}`}var Db=H(({db:e,args:t,opts:n})=>{let i=E(t,0),r=m(n,"full"),o=j(n,"maxDepth");if(r&&o!==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=mo(e,i,{maxDepth:r?Number.MAX_SAFE_INTEGER:o,scope:y(n,"scope")}),a=s.rows;if(m(n,"json")){x("affected",t,n,{...Ae(e,i,a,"affected"),coverage:s.coverage});return}if(a.length===0)return w.empty(ue(e,i,"No possible impacts found in the bounded reverse caller/reference closure."));de(e,i);let l=-1;for(let d of a)d.depth!==l&&(console.log(`
|
|
193
|
+
\u2500\u2500 Depth ${d.depth} \u2500\u2500`),l=d.depth),console.log(` ${d.file} ${d.shortName}`);console.log(`
|
|
194
|
+
${a.length} possible-impact symbol(s) across ${new Set(a.map(d=>d.file)).size} files; reachability does not prove breakage.`),console.log(` coverage: ${s.coverage.status} \u2014 ${s.coverage.reasons.join(" ")}`)}),Nb=Q("co-change",({db:e,args:t,opts:n,budget:i})=>{let r=t[0]===void 0?void 0:E(t,0),o=m(n,"full"),s=So(e,r,{minTogether:$(n,"minTogether",4),limit:P(n,"limit",30),includeLinked:n.all===!0,scanLimit:i.scanLimit,historyMode:o?"full":"bounded"});if(m(n,"json")){x("co-change",t,n,s,{analysisBudget:i.analysisBudget});return}if(!s.available)return w.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return w.empty(r?`No co-change partners found for ${r} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Pe("co-change candidates"),console.log(r?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
|
|
195
|
+
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
|
|
196
|
+
`),Ub(r,s.findings);for(let a of s.findings)Bb(a);console.log(`
|
|
197
|
+
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Ob(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Wb(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(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var Fb=Q("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=ho(e,E(t,0),{semantic:i.semantic});if(m(n,"json")){x("change-surface",t,n,r,{analysisBudget:i.analysisBudget});return}if(!r)return w.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}`),r.fileRisk&&r.fileRisk.reasons.length>0&&console.log(`File risk factors (${r.fileRisk.coverage} metadata): ${r.fileRisk.reasons.map(o=>`${o.kind}: ${o.detail}`).join("; ")}`),console.log(""),w.list(r.symbols,kn)}),_b=Q("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let r=bo(e,{base:y(n,"base"),minContainment:$(n,"minContainment",.7),maxHelpers:j(n,"maxHelpers"),limit:P(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(m(n,"json")){x("incomplete-migration",t,n,r,{analysisBudget:i.analysisBudget}),(!r.available||r.findings.length>0)&&(process.exitCode=1);return}if(!r.available){console.error(`error: ${r.note??"Required Git history is unavailable."}`),process.exitCode=1;return}if(r.changedFiles.length===0)return w.empty(`No changes vs ${r.base}.`);console.log(`Incomplete migrations vs ${r.base}: ${r.changedFiles.length} changed file(s), ${r.helpersChecked} new helper(s) scored.`),r.note&&console.log(` note: ${r.note}`);for(let o of r.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(r.findings.length===0){console.log(`
|
|
198
|
+
No incomplete migrations detected.`);return}Pe("incomplete migration candidates"),Gb(r.findings),console.log(`
|
|
199
|
+
${r.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),Id=[{id:"affected",command:"affected <symbol>",description:"Conservative reverse caller/reference closure of symbols that may be impacted by a change",agent:S("Which downstream symbols are statically reachable as possible change impacts?","possible-impact symbol identities, files, and traversal depths; not predicted failures",["symbol"],"bounded"),options:b([c("--full","Traverse without the default depth and per-frontier caller caps"),c("--max-depth <n>","Maximum traversal depth (default: 5)",g),c("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:f("Impact"),handler:Db},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: consumers, published API, operational roots, and explained change risk",agent:S("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:b([c("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:f("Impact"),handler:Fb},{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:S("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:b([c("--base <ref>","Git ref to diff against (default: HEAD)"),c("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ce,.7),c("--max-helpers <n>","Maximum new helpers to score (default: all)",g),c("-n, --limit <n>","Maximum findings to report",g,20),c("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:f("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:_b},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:S("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:b([c("--min-together <n>","Minimum commits where both files changed",g,4),c("-n, --limit <n>","Maximum pairs to report",g,30),c("--all","Include pairs that already have a dependency edge"),c("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},claims:re(["index-generation","live-workspace"],[T("historical-pairs","findings[]","change-history"),T("structural-link-classification","findings[].structurallyLinked","compiler-graph")]),renderShape:"custom",docs:f("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:Nb}];function Bb(e){let t=e.structurallyLinked?" [dep edge]":"",n=` [${e.partnerClass}]`,i=` [${e.commitScope}/${e.recency}]`;console.log(` ${e.together}x (${Math.round(e.confidence*100)}%) ${e.fileA} <-> ${e.fileB}${n}${i}${t}`),console.log(` history: ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent; last ${Ob(e.lastTogetherAt)}`),console.log(` subjects: ${Wb(e.subjectContext)}`),e.declaredCouplingSuggestion&&console.log(` declare coupling: ${e.declaredCouplingSuggestion.name} (${e.declaredCouplingSuggestion.reason})`)}function Gb(e){for(let t of e){console.log(`
|
|
200
|
+
${t.helperShortName} (${t.helperFile})`),console.log(` helper shape: ${t.helperShape} (${t.specificHelperCalleeCount}/${t.helperCalleeCount} specific callees)`),console.log(` wired into: ${t.migratedFiles.join(", ")}`);for(let n of t.leftovers)console.log(` un-migrated: ${Math.round(n.containment*100)}% helper / ${Math.round(n.siteCoverage*100)}% site [${n.migrationScope}] ${n.shortName} (${n.file})`),console.log(` scope: ${n.migrationScopeReasons.join("; ")}`),n.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${n.uniqueSiteCalleeCount}`),console.log(` shared: ${n.sharedCallees.join(", ")}`)}}function Ub(e,t){e&&t.some(n=>n.structurallyLinked||n.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
|
|
201
|
+
`)}import{spawn as Hb}from"child_process";import{createHash as Ii,randomUUID as Vb}from"crypto";import{existsSync as Pi,realpathSync as Qb}from"fs";import{tmpdir as Jb}from"os";import{join as Ai,resolve as Dt}from"path";import{fileURLToPath as zb}from"url";var Ye=27,Kb=1e3,Yb=2*Kb,Xb=4,Cn=4,Ci=5,Zb=3,eS=4,tS=3,nS=8,Ad=3e4,iS=5e3,Td=5,rS=10,oS=1,sS=5,Ld=64*1024*1024,aS=new Map([["dependence-slice",tS],["call-graph",Zb],["system",eS],["refs",Ci],["imports",Ci],["unused-imports",Ci],["imported-by",Cn],["hierarchy",Cn],["by-kind",Cn],["kind-counts",Cn]]),cS={maxItems:64,maxBytes:128*1024*1024,maxItemBytes:Ld,maxBatch:1,responseRetentionMs:6e4};function Md(e,t,n={},i={}){return lS(e,r=>({kind:"source-search",expectedGeneration:r,pattern:t,options:n}),SS,"search result",i)}function lS(e,t,n,i,r){if(!wS(r.allowDefault===!0))return null;try{let o=r.allowDefault===!0&&process.env.SCIP_QUERY_QUERY_SERVICE!=="1",s=o?Ui(e):void 0,a=te(e,s);if(!Pi(a.dbPath))return null;let l=Re(a.dbPath);if(!l||o&&!dS(a,s,l))return null;let d=gS({projectRoot:a.projectRoot,dbPath:a.dbPath,generationIdentity:l,configurationIdentity:Rt(a.config)},t(l),n,i);return{result:d.result,generationIdentity:l,observationReceipt:d.observationReceipt}}catch(o){return ES(o),null}}function dS(e,t,n){if(e.config.watch?.enabled!==!0)return!1;try{return ia(at({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:be,gitContext:t}))===n}catch{return!1}}function qd(e){return Ii("sha256").update(Rt({kind:"scip-query-service-mailbox",protocolVersion:Ye,sessionDir:Dt(e)})).digest("hex")}function Dd(e){let t=Ai(e,"server.json");try{let n=JSON.parse(He(t,{maxBytes:65536,inputKind:"query service state"}));if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,r=i.processIdentity===void 0?void 0:lr(i.processIdentity);return!uS(i,e)||!pS(i,r)||!mS(i)?null:{protocolVersion:Ye,sessionIdentity:i.sessionIdentity,pid:i.pid,...r?{processIdentity:r}:{},generation:i.generation,heartbeatAtMs:i.heartbeatAtMs}}catch{return null}}function uS(e,t){return e.protocolVersion===Ye&&typeof e.sessionIdentity=="string"&&e.sessionIdentity===qd(t)}function pS(e,t){return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&(e.processIdentity===void 0||!!(t&&t.pid===e.pid))}function mS(e){return typeof e.generation=="string"&&typeof e.heartbeatAtMs=="number"&&Number.isFinite(e.heartbeatAtMs)}function Nd(e,t=Date.now()){if(!Bt(e.pid))return!1;let n=t-e.heartbeatAtMs;if(n>=0&&n<=Yb||!e.processIdentity)return!0;let i=ve(e.pid);return i!==null&&Gt(e.processIdentity,i)}function hS(e){let t=e<rS;return{intervalMs:t?oS:Td,checkServerState:!t||e%sS===0}}function gS(e,t,n,i){let r=xS();if(!Pi(r))throw new Error("Query service server executable is unavailable.");let o=Math.abs(process.pid)%kS(t),s=RS(e,r,o),a=ur(s),l=Date.now(),d=l+Ad,u=X()+Ad,p=Vb(),h=fS(p,t),v=pr(h),k=qd(s),R=mr(a,{mailboxVersion:Dn,protocolVersion:Ye,id:v,operationKey:h,clientId:p,enqueuedAtMs:l,deadlineAtMs:d,sessionIdentity:k,request:t},{nowMs:l,limits:cS,durability:"visibility"});jd(s,e.projectRoot,r,u);let C=0;for(;X()<=u;){if(Pi(R.responsePath))return yS(He(R.responsePath,{maxBytes:Ld,inputKind:"query service response"}),{id:v,operationKey:h,clientId:p,deadlineAtMs:R.authoritativeDeadlineAtMs,generation:e.generationIdentity},n,i);let V=hS(C);if(V.checkServerState){let J=Dd(s);(!J||!Nd(J))&&jd(s,e.projectRoot,r,u)}Wd(V.intervalMs),C+=1}throw new Error("Persistent query service timed out.")}function fS(e,t){return Ii("sha256").update(Rt({namespace:"query-service-v18",payload:{clientId:e,request:t}})).digest("hex")}function jd(e,t,n,i){if(Ei(e))return;let r=Math.min(i,X()+iS),o=Er(Ai(e,"startup.lock"),{kind:"query-service-startup",detail:{projectRoot:Dt(t)},directoryDurability:"recoverable"});try{if(o.kind==="acquired"&&!Ei(e)){let s=Od();Hb(process.execPath,[n,e,t],{cwd:t,detached:!s,stdio:s?["ignore","ignore","inherit"]:"ignore",env:{...process.env,SCIP_QUERY_QUERY_SERVICE_SERVER:"1"}}).unref()}for(;X()<=r;){if(Ei(e))return;Wd(Td)}}finally{o.kind==="acquired"&&o.lock.release()}throw new Error("Persistent query service did not become ready within 5s.")}function yS(e,t,n,i){let r=JSON.parse(e);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid query service response.");let o=r;if(bS(o,t),o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"Persistent query service rejected the request.");if(o.generation!==t.generation)throw new Error("Persistent query service generation changed.");if(!n(o.result))throw new Error(`Persistent query service returned an invalid ${i}.`);let s=Uo(o.observationReceipt);if(s.kind!=="supported")throw new Error("Persistent query service returned an invalid observation receipt.");return{ok:!0,protocolVersion:Ye,id:t.id,generation:t.generation,result:o.result,observationReceipt:s.receipt}}function bS(e,t){if(e.mailboxVersion!==Dn||e.protocolVersion!==Ye||e.id!==t.id||e.operationKey!==t.operationKey||e.clientId!==t.clientId||e.deadlineAtMs!==t.deadlineAtMs)throw new Error("Query service response identity does not match the request.")}function SS(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)&&vS(t)}function vS(e){return typeof e.matchingLines=="number"&&Number.isSafeInteger(e.matchingLines)&&e.matchingLines>=0&&typeof e.omittedMatches=="number"&&Number.isSafeInteger(e.omittedMatches)&&e.omittedMatches>=0&&typeof e.scannedFiles=="number"&&Number.isSafeInteger(e.scannedFiles)&&e.scannedFiles>=0}function RS(e,t,n){let i=CS(e.projectRoot),r=Ii("sha256").update(Rt({protocolVersion:Ye,projectRoot:i,dbPath:Dt(e.dbPath),serverPath:Dt(t),buildIdentity:zi(),configurationIdentity:e.configurationIdentity,lane:n})).digest("hex");return Ai(Jb(),"scip-query-query-service",r)}function xS(){return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER_PATH??zb(new URL("./query-service-server.js",import.meta.url))}function wS(e){let t=process.env.SCIP_QUERY_QUERY_SERVICE;return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER!=="1"&&t!=="0"&&(t==="1"||e)}function Od(){return process.env.SCIP_QUERY_QUERY_SERVICE_DEBUG==="1"}function $S(){let e=Number(process.env.SCIP_QUERY_QUERY_SERVICE_POOL_SIZE);return Number.isInteger(e)&&e>=1&&e<=nS?e:Xb}function kS(e){let t=$S(),n=aS.get(e.kind);return n===void 0?t:Math.min(t,n)}function CS(e){try{return Qb.native(e)}catch{return Dt(e)}}function Wd(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ei(e){let t=Dd(e);return!!(t&&Nd(t))}function ES(e){Od()&&console.error(`query-service fallback: ${e instanceof Error?e.message:String(e)}`)}function ji(e,t,n={}){let i=ts(e,n),r=is(i),o=Go([...i.files.keys()],r.imports,r.findings,i.project.architecture),s=PS(o,t),a=new Set(s.flatMap(R=>R.files)),l=Bo(r.imports),d=[...r.problems,...i.project.problems,...ns(e,i,n)];t&&!s.length&&d.push(`Selector ${JSON.stringify(t)} matches no captured module; use system --source to inspect group IDs and exclusions.`),(l.resolutions.missing||l.resolutions.ambiguous)&&d.push("Internal imports are missing or ambiguous; inspect coverage.dependencies.unresolved.");let u=Fd(r.exports),p=r.imports.filter(R=>a.has(R.file)||R.target&&a.has(R.target)),h=new Map(p.map((R,C)=>[R,C])),v=Fd(p),k=IS(p);return{mode:"source-system",current:i.fingerprint,selector:t,totalModules:o.length,imports:p,modules:s.map(R=>({...R,exports:R.files.flatMap(C=>u.get(C)??[]),importIds:R.files.flatMap(C=>v.get(C)??[]).map(C=>h.get(C)),incomingImportIds:R.files.flatMap(C=>k.get(C)??[]).filter(C=>!R.files.includes(C.file)).map(C=>h.get(C))})),edges:AS(o,_o(p,i.project.architecture),h).filter(R=>s.some(C=>C.id===R.from||C.id===R.to)),findings:r.findings.filter(R=>R.sites.some(C=>a.has(C.file))),architecture:Fo(r.architecture),coverage:{status:d.length?"incomplete":"accounted",capturedFiles:i.files.size,eligibleFiles:i.eligibleFiles,excludedFiles:i.excludedFiles,exclusions:i.exclusions,dependencies:l,problems:d,limits:["Current TS/JS source and captured project configuration; no index or executed behavior is implied. Parse, resource and configuration failures are reported in problems.","Import IDs index the imports table in this report; each observation is stored once. IDs are not portable between reports.","Groups include files without findings. Unambiguous configured boundaries take precedence over provisional directories; membership does not establish business responsibility. A path selects whole groups containing matching files.","Module edges and dependency/consumer summaries are observed internal production imports, including type, dynamic and CommonJS relationships; their syntax and roles remain explicit. They are not runtime execution paths. Only static value imports participate in production file-cycle findings.","Export declarations are parsed source locations, not a complete resolved public API. Wildcard re-exports are not expanded; CommonJS exports, class member interfaces, external consumers, runtime registration and invocation coverage are not established. Use indexed surface/evidence and exact source when those facts matter.","Nonliteral dynamic imports, custom loaders, runtime handoffs and shared external resources are not resolved. Coverage can be accounted for while these relationships remain unknown.","Tests, generated/reference copies, declarations, unsupported languages and managed output are excluded by default; exclusion counts and opt-in source roles are reported. No architecture grade or module depth score is computed."]}}}function PS(e,t){if(!t||t===".")return e;let n=e.find(r=>r.id===t);if(n)return[n];let i=t.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/$/,"");return e.filter(r=>r.files.some(o=>o===i||o.startsWith(i+"/")))}function Fd(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function IS(e){let t=new Map;for(let n of e){if(n.resolution!=="internal"||!n.target)continue;let i=t.get(n.target)??[];i.push(n),t.set(n.target,i)}return t}function AS(e,t,n){let i=new Map(e.flatMap(o=>o.files.map(s=>[s,o.id]))),r=new Map;for(let o of t){if(o.resolution!=="internal"||!o.target)continue;let s=i.get(o.file),a=i.get(o.target);if(!s||!a||s===a)continue;let l=JSON.stringify([s,a]),d=r.get(l)??{from:s,to:a,importIds:[]};d.importIds.push(n.get(o)),r.set(l,d)}return[...r.values()].sort((o,s)=>o.from.localeCompare(s.from)||o.to.localeCompare(s.to))}function Bd(e){return{...e,command:"system [module]",description:"Module files and dependencies; --source adds a first-use inventory, exports, policy and findings without an index",agent:e.agent?{...e.agent,coverage:"bounded",scope:"repository",answers:[...e.agent.answers,"With --source, which current module groups, imports, export declarations, policy constraints and candidates are observed without an index?"],returns:[...e.agent.returns,"current-source module inventory including groups without findings; explicit coverage and grammar-level export declarations"]}:void 0,claims:re(["index-generation","live-workspace"],[T("indexed-symbols","symbols[]","compiler-graph"),T("indexed-dependencies","dependsOn[]","compiler-graph"),T("indexed-consumers","dependedOnBy[]","compiler-graph"),T("source-modules","modules[]","repository-source"),T("source-dependencies","edges[]","repository-source"),T("source-imports","imports[]","repository-source"),ot("source-findings","findings[]","evidence",{derived:"repository-source",candidate:"heuristic"}),T("source-coverage","coverage","repository-source")]),options:b([...e.options??[],{flags:"--source",description:"Inspect current TS/JS module evidence; omit module for a repository inventory"},{flags:"--include-tests",description:"Include tests, fixtures and benchmarks in source mode"},{flags:"--include-references",description:"Include reference/vendor source in source mode"},{flags:"--include-generated",description:"Include generated source in source mode"},{flags:"--max-files <n>",description:"Source file limit (default: 10000)",parser:F},{flags:"-n, --limit <n>",description:"Source groups and relationship rows to display (default: 20)",parser:F},{flags:"--full",description:"Display all source groups, export declarations, imports and findings"}]),handler:(...t)=>{let{args:n,opts:i}=Os(t);if(!m(i,"source")){if(!n[0])throw new Error("Choose system <module> for indexed evidence or system --source for a current-source inventory.");for(let r of["includeTests","includeReferences","includeGenerated","maxFiles","limit","full"])if(i[r]!==void 0&&i[r]!==!1)throw new Error(`${r} requires system --source.`);return e.handler(...t)}jS(n,i)}}}function jS(e,t){let n=typeof e[0]=="string"?E(e,0):void 0,i=ji(_(),n,{includeTests:m(t,"includeTests"),includeReferences:m(t,"includeReferences"),includeGenerated:m(t,"includeGenerated"),maxFiles:j(t,"maxFiles")});if(m(t,"json"))x("system",n?[n]:[],t,i,{coverage:i.coverage.status==="incomplete"?{complete:!1,totalKnown:!1,returned:1}:{complete:!0,totalKnown:!0,returned:1,total:1,omitted:0}});else{let r=_d(n,t);LS(i,m(t,"full")?1/0:j(t,"limit")??20,r,o=>_d(o,t))}}function TS(e){return"'"+e.replaceAll("'","'\\''")+"'"}function _d(e,t){let n=["--source"];e&&n.push(TS(e));for(let[r,o]of[["includeTests","--include-tests"],["includeReferences","--include-references"],["includeGenerated","--include-generated"]])m(t,r)&&n.push(o);let i=j(t,"maxFiles");return i!==void 0&&n.push("--max-files",String(i)),"scip-query system "+n.join(" ")}function LS(e,t,n,i){console.log(`Module evidence \u2014 current source: ${e.coverage.capturedFiles}/${e.coverage.eligibleFiles} eligible files; ${e.modules.length}/${e.totalModules} groups selected.`),MS(e),console.log(`
|
|
202
|
+
Module groups (${Math.min(t,e.modules.length)}/${e.modules.length} shown):`);for(let r of e.modules.slice(0,t))NS(r,e.imports,t,i,e.selector!==void 0||t===1/0);qS(e,t),DS(e,t),(e.modules.length>t||e.edges.length>t||e.findings.length>t)&&console.log(`More rows: ${n} --full`);for(let r of e.coverage.problems)console.log(`Unresolved: ${r}`);for(let r of e.coverage.dependencies.unresolved.slice(0,t))console.log(`Unresolved import: ${En(r)}`)}function MS(e){e.coverage.status==="incomplete"&&console.log("Source scan incomplete; see unresolved files below.");let t=e.architecture;console.log(t.configured?`Architecture: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} files mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency rows declared. Missing rows: ${t.policyCoverage.missingRows.join(", ")||"none"}.`:"Architecture: no configured boundaries or dependency policy; directory groups are provisional.")}function qS(e,t){if(e.edges.length!==0){console.log(`
|
|
203
|
+
Cross-group production dependencies (${Math.min(t,e.edges.length)}/${e.edges.length} shown):`);for(let n of e.edges.slice(0,t)){console.log(` ${n.from} -> ${n.to}: ${n.importIds.length} import sites`);for(let i of n.importIds.slice(0,t===1/0?1/0:2))console.log(` ${En(e.imports[i])}`)}}}function DS(e,t){if(e.findings.length!==0){console.log(`
|
|
204
|
+
Related findings (${Math.min(t,e.findings.length)}/${e.findings.length} shown; candidates require review):`);for(let n of e.findings.slice(0,t))if(console.log(` [${n.evidence}] ${n.rule}: ${n.summary}`),t===1/0)for(let i of n.sites)console.log(` ${i.file}:${i.line}`)}}function NS(e,t,n,i,r){let o=n===1/0?1/0:3;if(console.log(` ${e.id} [${e.basis}]: ${e.files.length} files; ${e.exports.length} export declarations; ${e.dependencies.length} production dependency files; ${e.consumers.length} production consumer files; ${e.findingIds.length} findings.`),!!r){console.log(` Files (${Math.min(o,e.files.length)}/${e.files.length}): ${e.files.slice(0,o).join(", ")}`),console.log(` Source exports (${Math.min(o,e.exports.length)}/${e.exports.length}; symbol consumers require indexed surface):`);for(let s of e.exports.slice(0,o))console.log(` ${s.file}:${s.startLine} ${s.syntax}: ${s.names.join(", ")}${s.from?` from ${JSON.stringify(s.from)}`:""}`);console.log(` Imports (${Math.min(o,e.importIds.length)}/${e.importIds.length}):`);for(let s of e.importIds.slice(0,o))console.log(` ${En(t[s])}`);console.log(` Incoming imports (${Math.min(o,e.incomingImportIds.length)}/${e.incomingImportIds.length}):`);for(let s of e.incomingImportIds.slice(0,o))console.log(` ${En(t[s])}`);console.log(` Group: ${i(e.id)} --full`)}}function En(e){return`${e.file}:${e.line} -> ${e.target??e.specifier} [${e.syntax}; ${e.kind}; ${e.role}; ${e.resolution}]`}function OS(e){let t=m(e,"full"),n=P(e,"limit",12);return t?void 0:n}function Gd(e){return{scope:y(e,"scope"),context:$(e,"context",2),limit:P(e,"limit",6),regexp:m(e,"regexp"),ignoreCase:m(e,"ignoreCase"),ranking:"structural"}}function WS(e){let t=y(e,"view")??"source";if(t!=="source"&&t!=="behavior")throw new Error(`Unknown inspect view: ${t}. Use source or behavior.`);return t}function FS(e,t,n){return e.find(i=>i.relativePath===t&&i.line===n)?.sourceKind}function _S(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 BS(e){return e?[Ud("Reference-absence claims",e.referenceAbsence),Ud("Callsite-argument claims",e.callsitePredicates)]:[]}function Ud(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(`
|
|
205
|
+
`)}var Ti=["definition","references","callers","callees","dependencies","consumers"],Mi=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function Hd(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Ti];let n=t.filter(i=>!Ti.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Ti.join(", ")}, or all.`);return[...new Set(t)]}function GS(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Ve];let n=t.filter(i=>!Ve.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${Ve.join(", ")}, or all.`);return[...new Set(t)]}function US(e){if(e!==void 0){if(Bn.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${Bn.join(", ")}.`)}}function HS(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 VS(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function QS(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("="),r=n.slice(0,i),o=n.slice(i+1);if(i<=0||!Mi.includes(r))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Mi.join(", ")}.`);if(Object.hasOwn(t,r))throw new Error(`Duplicate inspect evidence budget: ${r}.`);if(!/^\d+$/u.test(o))throw new Error(`Inspect evidence budget ${r} must be a non-negative safe integer; received ${o}.`);let s=Number(o);if(!Number.isSafeInteger(s))throw new Error(`Inspect evidence budget ${r} must be a non-negative safe integer; received ${o}.`);t[r]=s}return t}function JS(e){let t=e.matches.map(r=>KS(e,r)),n=t.reduce((r,o)=>r+o.shortenedLines,0),i=Math.max(0,e.matchingLines-e.matches.length);return[{title:`Matches (${e.matches.length}/${e.matchingLines} shown)`,rows:t.map(r=>r.text),preserveRowNewlines:!0},{title:"Limits",rows:[...qi(e)?[]:["Text scan incomplete: unreadable or oversized files may contain additional matches."],...n>0?[`${n} source line(s) shortened.`]:[],...i>0?[`${i} additional matching line(s); use --scope <path> or --full.`]:[]],skipIfEmpty:!0}]}var Me=320,zS=1200;function KS(e,t){let n=t.source.split(`
|
|
206
|
+
`);if(!(n.some(p=>p.length>Me)||t.source.length>zS)){let p=t.ownerShort?` in ${t.ownerShort}`:"";return{text:rt({relativePath:t.relativePath,startLine:t.startLine,source:t.source,sessionPolicy:"preview",focusLines:new Set([t.focusLine]),ownerSymbol:t.ownerShort??void 0,headerSuffix:p}),shortenedLines:0,omittedContextLines:0}}let o=t.ownerShort?` in ${t.ownerShort}`:"",s=Math.max(0,Math.min(n.length-1,t.focusLine-t.startLine)),a=n[s]??"",l=a.length>Me?1:0,d=` >${String(O(t.focusLine)).padStart(5)} ${YS(e,a)}`,u=Math.max(0,n.length-1);return{text:[` ${L(t.relativePath,t.startLine,t.endLine)}${o}`,d,...u>0?[` \u2026[${u} nonfocus context line(s) omitted]`]:[]].join(`
|
|
207
|
+
`),shortenedLines:l,omittedContextLines:u}}function YS(e,t){if(t.length<=Me)return t;let n=XS(e,t);if(n<0){let d=Me/2,u=t.length-Me;return`${t.slice(0,d)}\u2026[${u} characters omitted]\u2026${t.slice(-d)}`}let i=e.mode==="literal"?Math.min(e.pattern.length,Me):1,r=n-Math.floor((Me-i)/2),o=Math.max(0,Math.min(r,t.length-Me)),s=o+Me,a=o>0?`\u2026[${o} characters omitted]\u2026`:"",l=s<t.length?`\u2026[${t.length-s} characters omitted]\u2026`:"";return`${a}${t.slice(o,s)}${l}`}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 qi(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function ZS(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 zd(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??zd(e)}function ev(e){let t=["scip-query inspect"];for(let i of D(e,"search"))t.push(`--search ${Ne(i)}`);for(let i of D(e,"symbol"))t.push(`--symbol ${Ne(i)}`);for(let i of D(e,"at"))t.push(`--at ${Ne(i)}`);let n=y(e,"scope");return n&&t.push(`--scope ${Ne(n)}`),t.push("--view behavior"),t.join(" ")}function tv(e,t){if(!(e.view!=="source"||m(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: ${ev(t)}`,"Narrow to smaller exact selectors, or rerun with --allow-large-source only when the omitted syntax itself can change the decision."].join(`
|
|
208
|
+
`))}function nv(e,t){if(e.view!=="behavior"||m(t,"allowLargeBehavior"))return;let n=(e.omissionGroups??[]).filter(o=>o.sourceCharacters>2e4&&o.roles.some(s=>s==="location"||s==="definition"));if(n.length===0&&(e.returnedViewCharacters??0)<=2e4)return;let i=n.flatMap(o=>o.anchors).map(o=>`${o.relativePath}:${O(o.line)}`),r=i.length>0?i.join(", "):D(t,"at").join(", ");throw new Error(["INSPECT BEHAVIOR FOCUS REQUIRED",`The selector set resolves to behavioral constructs above the ${2e4}-character evidence ceiling${r?` (${r})`:""}.`,"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(`
|
|
209
|
+
`))}function iv(e){let t=[rv(e)];return(e.omittedMatches>0||(e.omittedUnits??0)>0)&&(t.push(` Withheld: ${e.omittedMatches} matching line(s), ${e.omittedFiles??0} file(s) with no materialized match, and ${e.omittedUnits??0} materialized unit(s) outside the packet ceiling.`),ov(e,t),e.exactFollowup&&t.push(` Expand this selector completely only if omitted matches can change the decision: ${e.exactFollowup}`)),t.join(`
|
|
210
|
+
`)}function rv(e){return` ${e.pattern}: ${e.returnedMatches}/${e.matchingLines} matching line(s) materialized across ${e.returnedFiles??0}/${e.matchingFiles??0} file(s); ${e.selectedUnits??0}/${e.candidateUnits??0} deduplicated unit(s) selected`}function ov(e,t){(e.scopeHints?.length??0)>0&&(t.push(" Highest-coverage scopes available for focused expansion:"),t.push(...(e.scopeHints??[]).map(n=>` ${n.scope}: ${n.returnedMatches}/${n.matchingLines} matching line(s) materialized; ${n.exactFollowup}`)),(e.omittedScopeHints??0)>0&&t.push(` ... ${e.omittedScopeHints} additional matching scope(s).`))}function sv(e,t=!1){let n=e.units??[],i=e.searches.filter(u=>u.matchingLines===0).map(iv),r=e.locations.filter(u=>!u.matched).map(u=>` ${u.matched?"matched":"missing"} ${u.target}`),o=n.map(uv),s=t?Rv(e.bindingClosure):[],a=(e.omissionGroups??[]).map(pv),l=e.evidence.flatMap(u=>{let p=hv(u,"inspect");return p?[` ${p}`]:[]}),d=av(e);return[{title:"Unresolved selectors",skipIfEmpty:!0,rows:[...i.map(u=>` search ${u.trimStart()}`),...r.map(u=>` location ${u.trimStart()}`),...l.map(u=>` symbol ${u.trimStart()}`)]},{title:"OBSERVED FACTS",rows:[...o,...s],preserveRowNewlines:!0,skipIfEmpty:!0},{title:"Limits",rows:d,skipIfEmpty:!0},{title:"RECOVERY",rows:a,skipIfEmpty:!0}]}function av(e){let t=e.packetCoverage;return!t||t.mode==="complete"?[]:cv(e,t)}function cv(e,t){return[` ${t.mode==="complete"?"Complete":"Ranked bounded"} semantic packet: ${t.returnedUnits}/${t.candidateUnits} materialized unit(s), ${e.returnedLines??0} underlying source line(s), and ${e.returnedViewCharacters??e.returnedCharacters??0} displayed evidence character(s).`,` Selection ceiling: ${t.maxUnits} unit(s) or ${t.maxCharacters} displayed evidence character(s); syntax units are never clipped.`,` Exact symbol/location evidence: ${t.exactSelectorsComplete?"complete within materialized compiler evidence":"some lower-ranked units withheld"}.`,...t.channels?[` Evidence channels: ${dv(t.channels)}.`]:[],...t.omittedUnits>0?[` Withheld materialized units by role: ${lv(t.omittedByRole)}.`]:[],...t.expansionCommand?[` Expand the complete selector set only if omitted evidence can change the decision: ${t.expansionCommand}`]:[]]}function lv(e){return Object.entries(e).map(([t,n])=>`${t}=${n}`).join(", ")}function dv(e){return Mi.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 uv(e){switch(e.kind){case"source":{let t=e.ownerShort?` in ${e.ownerShort}`:"";if(e.behavior){let r=Ev(e,e.behavior);return[` ${L(e.relativePath,e.startLine,e.endLine)}${t}`,` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`,ks({kind:"unit",identity:`inspect-behavior:${e.relativePath}:${e.startLine}:${e.endLine}`,content:r.join(`
|
|
211
|
+
`),label:e.ownerShort??`${e.relativePath}:${O(e.startLine)}`,indent:" "})].join(`
|
|
212
|
+
`)}let n=rt({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=Kd(e.runtimeFacts??[]);return i.length>0?`${n}
|
|
213
|
+
${i.join(`
|
|
214
|
+
`)}`:n}case"path":return[` ${e.relationship}`,` ${e.roles.join(", ")} edge source was not located. Follow up exactly: ${e.exactFollowup}`].join(`
|
|
215
|
+
`);default:return mv(e)}}function Kd(e){return e.map(t=>{let n=t.keyParts.map(i=>`${i.name}=${i.value}`).join(", ")||"no resolved key";return` runtime L${O(t.line)} [${t.strength}] ${t.action} (${t.role}; ${t.resolution}) ${n}; proof=${t.derivation.rule}`})}function pv(e){let t=e.anchors.slice(0,4).map(n=>{let i=n.ownerShort?` in ${n.ownerShort}`:"",r=n.behaviorSignals.length>0?` [${n.behaviorSignals.join(",")}]`:"";return` ${n.relativePath}:${O(n.line)}${i}${r}`});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(`
|
|
216
|
+
`)}function mv(e){throw new Error(`Unhandled source inspection unit: ${JSON.stringify(e)}`)}function hv(e,t="evidence"){if(e.kind==="missing")return`No definition matched '${e.query}'.`;if(e.kind!=="ambiguous")return;let n=e.candidates.map(o=>{let s=`'${o.symbol.replaceAll("'","'\\''")}'`;return t==="inspect"?` scip-query inspect --symbol ${s}`:` scip-query evidence ${s}`}).join(`
|
|
217
|
+
`),i=e.candidates.length,r=i<e.total?` Showing the highest-ranked ${i}; narrow by path or`:"";return`Target '${e.query}' is ambiguous across ${e.total} definitions.${r} run one listed exact command:
|
|
218
|
+
${n}`}function Vd(e){if(e.kind!=="matched")return[];let t=e.definition?[rt({relativePath:e.definition.relativePath,startLine:e.definition.startLine,source:e.definition.source,sessionPolicy:"exact-unit",ownerSymbol:e.definition.shortName,headerSuffix:` ${e.definition.shortName}`})]:[],n=e.referenceWindows.map(r=>{let o=r.references.map(s=>`${O(s.line)} in ${s.enclosingShort} [${_S(FS(e.referenceEvidence,r.relativePath,s.line))}]`).join(", ");return rt({relativePath:r.relativePath,startLine:r.startLine,source:r.source,sessionPolicy:"preview",focusLines:new Set(r.references.map(s=>s.line)),headerSuffix:` references: ${o}`})}),i=r=>r.map(o=>rt({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"preview",ownerSymbol:o.shortName,headerSuffix:` ${o.shortName} [${o.evidenceStrength}]${o.omittedLines>0?` (${o.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(r=>` ${r.relativePath}`),skipIfEmpty:!0},{title:"CONSUMERS",rows:e.consumers.map(r=>` ${r.relativePath}`),skipIfEmpty:!0},{title:"CLAIM SUPPORT",rows:BS(e.claimSupport),skipIfEmpty:!0}]}function gv(e,t=!1){if(e.kind!=="graph-packet")return Vd(e);let n=e.graph.selection??{direction:"both",subtypes:[],connecting:!1,inventoryOnly:!1,foldIds:[]},i=Pv(e.graph),r=Ve.flatMap(u=>{let p=e.graph.edges.filter(h=>h.family===u);return p.length===0?[]:[` ${u} (${p.length})`,...p.map(h=>` ${vv(h)}`)]}),o=fv(e.graph,n,t),s=bv(e.graph.folds??[]),a=e.graph.coverage,l=e.source.flatMap(u=>u.kind!=="matched"?[{title:`SOURCE SELECTOR \u2014 ${u.query}`,rows:[` [${u.kind}]`]}]:Vd(u).map(p=>({...p,title:`${u.shortName} \u2014 ${p.title}`}))),d=[...s,...a.omittedEdges>0&&s.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:`${e.graph.families.join(", ")} ${n.direction} (depth ${a.maxDepth})`,rows:i},{rows:[...o,...r],skipIfEmpty:!0},...l,{title:"Provider details",rows:t?Sv(e.graph.edges):[],skipIfEmpty:!0},{title:"Limits",rows:yv(a,t),skipIfEmpty:!0},{title:"RECOVERY",rows:d,skipIfEmpty:!0}]}function fv(e,t,n){let i=(t.inventoryOnly||n?e.inventory??[]:[]).map(r=>` inventory ${r.family}/${r.subtype}: incoming=${r.incoming}; outgoing=${r.outgoing}; both=${r.both}`);return i.length>0&&i.unshift(" Distinct reachable edges by direction:"),i}function yv(e,t){return[...e.omittedEdges>0?[`${e.omittedEdges} matching relationship(s) omitted; ${e.returnedEdges} shown.`]:[],...e.status==="incomplete"?[e.explanation]:[],...e.unsupportedFrontiers>0?[`${e.unsupportedFrontiers} unresolved relationship group(s); do not infer absence. Use --detail for provider limits.`]:[],...e.rejectedRelationships?[`${e.rejectedRelationships} unsupported relationship(s) withheld.`]:[],...t?Yd(e.blindSpots).map(n=>`Unavailable: ${n}`):[]]}function bv(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],r=i.length===1?i[0]:`${i.length} subtypes`;return` ${n.id} ${n.family}/${r} ${n.edgeCount} edge(s), ${n.nodeIds.length} node(s), ${n.mode} @ ${n.region??"unscoped"}`})]}function Sv(e){let t=Yd(e.map(r=>r.evidenceStrength)),n=t.length===0?[" No relationships were materialized, so no edge evidence strength is claimed."]:t.map(r=>` ${r}: ${xt[r]}`),i=new Map;for(let r of e){let o=(r.evidenceConstituents??r.evidenceMethods.map(a=>({method:a,strength:r.evidenceStrength}))).map(a=>`${a.method}=${a.strength}`).join(", "),s=`${r.family}/${r.subtype}\0${r.providerId}\0${r.evidenceStrength}\0${o}`;i.set(s,` ${r.family}/${r.subtype} [${r.evidenceStrength}] provider=${r.providerId}; ceiling=${r.supportCeiling}; constituents=${o||"none reported"}; establishes=${r.establishes}; does-not-establish=${r.nonClaims.join(" ")||"no additional provider non-claim"}`)}return[...n,...i.values()]}function Yd(e){return[...new Set(e)]}function vv(e){let t=e.context?Object.entries(e.context).filter(([,r])=>r!==void 0).map(([r,o])=>`${r}=${Qd(o)}`):[],n=e.attributes?Object.entries(e.attributes).map(([r,o])=>`${r}=${Qd(o)}`):[],i=[...t,...n];return`[${e.evidenceStrength}] ${Jd(e.from)} -> ${Jd(e.to)} \u2014 ${e.subtype}${i.length>0?`; ${i.join(", ")}`:""}`}function Qd(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}function Jd(e){let t=e.location?` @ ${L(e.location.file,e.location.line,e.location.endLine??e.location.line)}`:"";return`${e.label}${t}`}function Rv(e){if(!e)return[];let t=[];for(let n of e.inline)t.push(` inline ${n.name} @ ${L(n.relativePath,n.startLine,n.endLine)}`,` ${n.source??""}`);return t}var xv=le("imports",{query:({db:e,args:t,budget:n})=>Dr(e,E(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile} [${e.evidence}]`,emptyMessage:()=>"No imports observed by the available index and source providers."}),wv=H(({db:e,args:t,opts:n})=>{let i=E(t,0),r=No(e,i,{direction:m(n,"forward")?"forward":"backward",variable:y(n,"variable"),column:j(n,"column"),maxDepth:j(n,"depth"),maxEdges:$(n,"maxEdges",200)});if(r.resolution!=="matched"&&(process.exitCode=1),m(n,"json")){x("dependence-slice",t,n,r);return}console.log(`${r.direction} function-local slice at ${i}: ${r.resolution}`);let o=s=>`${s.line+1}:${s.column+1} ${s.kind} ${s.name}`;if(r.resolution==="ambiguous")console.log("Choose one occurrence with --variable and --column (one-based):"),w.list(r.candidates,s=>` ${o(s)}`);else{w.list(r.points,a=>` ${o(a)}`);let s=new Map(r.points.map(a=>[a.id,a]));w.list(r.edges,a=>` ${a.kind}: ${o(s.get(a.fromPointId))} -> ${o(s.get(a.toPointId))}`)}console.log(`Coverage: ${r.coverage.status}; ${r.coverage.basis}; ${r.coverage.omittedEdges} edge(s) omitted; depth limited: ${r.coverage.depthLimited}.`),console.log("This is local dependency evidence. Calls, heap effects, and closure invocation order require separate inspection.");for(let s of r.coverage.model.unsupported)console.log(` Gap: ${s}`)}),$v=H(({db:e,args:t,opts:n})=>{let i=E(t,0),r=Ir(e,{className:i});if(m(n,"json")){x("methods",t,n,r,{coverage:kv(r)}),r.kind!=="matched"&&(process.exitCode=1);return}if(r.kind==="matched"){w.list(r.methods,o=>` ${ie(o.startLine,o.endLine)} ${o.name}`);return}w.empty(Cv(r)),process.exitCode=1});function kv(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 Cv(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}:${O(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 Xd=[...Ws,Le({id:"files",command:"files <pattern>",description:"Find current project files matching a path pattern",agent:S("Which current project files match this path pattern?","matching file paths",["pattern"],"complete"),docs:f("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>sr(e,E(t,0)),format:e=>e.relativePath}),qt({id:"inspect",command:"inspect",description:"Batch related searches, symbols, and source locations into one deduplicated source packet",options:[c("--bindings","Also display referenced literal values outside requested source"),c("--search <text>","Find this literal text; repeat for related anchors",B,[]),c("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",B,[]),c("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",B,[]),c("-s, --scope <path>","Limit literal searches to indexed paths matching this text"),c("-C, --context <n>","Fallback lines around a match with no syntax unit",Ie,6),c("-n, --limit <n>","Set matching lines materialized per search (default 12)",F),c("--max-units <n>","Set the ranked packet unit ceiling (default 48)",F),c("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",F),c("--view <view>","Render exact source, or raw/normalized behavior chosen by token cost with complete statement accounting (source or behavior; default source)"),c("--allow-large-source",`Explicitly allow an exact-source packet above the ${2e4}-character safety ceiling`),c("--allow-large-behavior",`Explicitly allow a behavioral construct above the ${2e4}-character focus ceiling`),c("--unit-lines <n>","Deprecated compatibility option; inspect now returns complete syntax units",F),c("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",F),c("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",B,[]),c("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",B,[]),c("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...Ke("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",ae,As(["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:f("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})=>{let i=m(t,"full"),r=Pr(e,{searches:D(t,"search"),symbols:D(t,"symbol"),locations:D(t,"at"),scope:y(t,"scope"),context:$(t,"context",6),searchLimit:OS(t),maxUnits:j(t,"maxUnits"),maxCharacters:j(t,"maxCharacters"),view:WS(t),full:i,unitLines:j(t,"unitLines"),totalLines:j(t,"totalLines"),evidence:{parts:Hd(D(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:QS(D(t,"evidenceBudget"))});return nv(r,t),tv(r,t),r},coverage:(e,{budget:t})=>{let n=e.searches.reduce((r,o)=>r+o.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:(e,{opts:t})=>sv(e,m(t,"bindings"))}),Zl({id:"search",command:"search <exact-text>",description:"Find current text matches with exact locations and optional compiler owners",options:[c("-s, --scope <path>","Limit the search to current project paths matching this text"),c("-C, --context <n>","Source lines before and after each representative match",Ie,Hn.context),c("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",F,Hn.limit),c("--full","Materialize source for every match after deliberately narrowing broad selectors"),c("--regexp","Treat the search text as a bounded regular expression"),c("-i, --ignore-case","Ignore case")],agent:{...Ke("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,ae,Et(["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:f("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,E(t,0),Gd(n)),precomputed:({args:e,opts:t})=>Md(_(),E(e,0),Gd(t)),emptyMessage:e=>e.matchingLines===0?`${qi(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=zd(e).length;return qi(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:ZS(e,Li(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:Li(e).map(t=>`${t.relativePath}:${O(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:JS}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:b(),agent:{...S("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:f("Navigation"),renderShape:"list",handler:$v},qt({id:"evidence",command:"evidence",description:"Traverse selected typed relationships around exact referents; recover source separately when needed",options:[c("--symbol <symbol>","Add an exact compiler symbol; repeat to batch",B,[]),c("--at <file:line>","Add the construct owning an exact source location; repeat to batch",B,[]),c("--search <literal>","Add an exact source or runtime literal; repeat to batch",B,[]),c("--view <view>","Select causal, structure, or complete graph evidence"),c("--edge <family>","Select execution, runtime, dataflow, state, temporal, contract, identity, ownership, dependencies, or all; repeat or comma-separate",B,[]),c("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),c("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",B,[]),c("--connecting","Return deterministic shortest paths connecting the resolved roots"),c("--detail","Include relationship inventory and full provider limitations"),c("--inventory-only","Count relationships by family, subtype, and direction without rendering edges"),c("--fold <id>","Materialize an exact recoverable fold from the same projection; repeat to batch",B,[]),c("--depth <n>","Required maximum graph traversal depth",Ie),c("--max-edges <n>","Required maximum typed relationships to render",F),{...c("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",B,[]),hidden:!0},c("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ae,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:Ve,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:"dependence-slice",distinction:"dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."}]},docs:f("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=D(t,"symbol"),i=D(t,"at"),r=D(t,"search"),o=US(y(t,"view")),s=GS(D(t,"edge")),a=HS(y(t,"direction")),l=VS(D(t,"subtype")),d=m(t,"connecting"),u=m(t,"inventoryOnly"),p=D(t,"fold"),h=j(t,"depth"),v=j(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(!u&&v===void 0)throw new Error("Materialized graph evidence requires an explicit finite --max-edges <n>.");let k=Hd(D(t,"include")),R=[...n,...i],C=k===void 0?null:{parts:k,selectors:R.length,command:["scip-query inspect",...n.map(V=>`--symbol ${Ne(V)}`),...i.map(V=>`--at ${Ne(V)}`),"--view source",`--include ${Ne(k.join(","))}`].join(" ")};return{kind:"graph-packet",graph:jr(e,{symbols:n,locations:i,searches:r},{view:o,families:s,direction:a,subtypes:l,connecting:d,inventoryOnly:u,foldIds:p,maxDepth:h,maxEdges:v??1}),source:[],sourceRecovery:C}},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(o=>o.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:(e,{opts:t})=>gv(e,m(t,"detail"))}),Le({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:S("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:f("Navigation"),query:({db:e,args:t})=>kr(e,E(t,0)),format:e=>e.relativePath}),Le({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:S("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:f("Navigation"),query:({db:e,args:t})=>Cr(e,E(t,0)),format:e=>e.relativePath}),Bd(Xl({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[Es()],agent:{operation:ae,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:f("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Tr(e,E(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=>` ${L(t.relativePath,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}`)}]})),Le({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:S("Which indexed symbols have observed references from files outside this module?","consumer paths and consumed symbol identities",["module"],"complete"),docs:f("Navigation"),query:({db:e,args:t})=>Lr(e,E(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:S("Which symbols does this file import?","observed imported bindings, source files, and provider evidence; source candidates may lack compiler identity",["file"],"bounded"),options:b([c("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:f("Navigation"),handler:xv},Le({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:S("Which files have observed imports of this symbol?","importing file paths with indexed or source-candidate evidence; indirect re-export resolution may be unavailable",["symbol"],"bounded"),docs:f("Navigation"),query:({db:e,args:t})=>Nr(e,E(t,0)),format:e=>` ${e.fromFile} [${e.evidence}]`}),Le({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:S("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:f("Navigation"),query:({db:e,args:t})=>Wr(e,E(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>de(t,E(n,0)),emptyMessage:({db:e,args:t})=>ue(e,E(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Ae(t,E(n,0),e,"members")}),Le({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:S("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[c("-s, --scope <path>","Limit to files matching path"),c("-n, --limit <n>","Number of results",g,100),c("--full","Run unbounded analysis on large indexes")],docs:f("Navigation"),query:({db:e,args:t,opts:n})=>Jr(e,E(t,0),{scope:y(n,"scope"),limit:P(n,"limit",100)}),format:e=>` ${L(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${E(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
219
|
+
${e.length} symbol(s)`)}),wn({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:S("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[c("-s, --scope <path>","Limit to files matching path")],docs:f("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>zr(e,{scope:y(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Le({id:"hierarchy",command:"hierarchy <symbol>",description:"Show indexed lexical owners of a symbol (method \u2192 class \u2192 module)",agent:S("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:f("Navigation"),query:({db:e,args:t})=>Yr(e,E(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>de(t,E(n,0)),emptyMessage:({db:e,args:t})=>ue(e,E(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Ae(t,E(n,0),e,"hierarchy")}),{id:"dependence-slice",command:"dependence-slice <file:line>",description:"Slice one variable occurrence through function-local value and control dependencies",agent:S("What proved program dependencies can affect this criterion, or be affected by it?","exact local source points, dependency edges, criterion ambiguity, and model limits",[["symbol","path"]],"bounded"),options:b([c("--forward","Compute a forward slice. Default is backward."),c("--variable <name>","Exact variable name at the criterion line"),c("--column <n>","One-based source column selecting one occurrence",g),c("--depth <n>","Limit dependence hops; default follows the complete local graph",g),c("--max-edges <n>","Maximum dependence edges rendered",g,200)]),renderShape:"custom",docs:f("Navigation"),handler:wv}];function Ev(e,t){let n=t.coverage;return[` representation: ${n.omittedStatements>0?"partial behavioral outline":n.copiedStatements===n.sourceStatements?"verbatim source unit (not compressed)":"statement-complete behavioral outline"}`,` ${t.constructKind}: ${t.signature}`,...t.lines.map(r=>` L${O(r.line)}${r.endLine>r.line?`-${O(r.endLine)}`:""} ${" ".repeat(r.depth)}${r.text}${r.copied?" [verbatim]":""}`),...t.testCases.length>0?[` related test cases: ${t.testCases.join("; ")}`]:[],...Kd(e.runtimeFacts??[]),` coverage: ${n.representedStatements}/${n.sourceStatements} source statement(s) represented; ${n.copiedStatements} verbatim; ${n.omittedStatements} omitted; ${t.outlineCharacters}/${t.rawCharacters} estimated characters`]}function Pv(e){return[...e.targets.map(t=>{let n=t.omittedCandidates>0?`; ${t.omittedCandidates} candidate(s) omitted`:"";return` selector [${t.status}] ${t.kind} ${t.query}${n}`})]}var Iv=Q("context",({db:e,args:t,opts:n,budget:i})=>{let r=P(n,"limit",20),o=te(e.config.projectRoot).gitContext?.headCommit,s=Po(e,E(t,0),{semantic:i.semantic,impactDepth:$(n,"impactDepth",3),scope:y(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(m(n,"json")){x("context",t,n,{...Qn(e,E(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:Zd(s),agentResult:eu(s)});return}return w.empty(ue(e,E(t,0)))}if(m(n,"json")){x("context",t,n,Uv(e,t,s),{analysisBudget:i.analysisBudget,coverage:Zd(s),agentResult:eu(s)});return}s.matched.symbol&&de(e,s.primaryCallable?.symbol??E(t,0));let a=m(n,"detail")?jv(s,r):Av(s,E(t,0),r,$(n,"impactDepth",3));w.sectionedReport(a)}),tu=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:Ps([c("--impact-depth <n>","Maximum affected traversal depth",g,3),c("-s, --scope <path>","Limit downstream impact to files matching path"),c("-n, --limit <n>","Rows per section",g,20),c("--detail","Render every planning component instead of the compact decision packet"),c("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",claims:re(["index-generation","live-workspace"],[T("compiler-graph","trace","compiler-graph"),T("change-history","history","change-history"),T("planning-notes","warnings[]","heuristic")]),agent:{operation:ae,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","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 also includes reference and call relationships, history, and reuse signals."}]},renderShape:"custom",docs:f("Exploration",["scip-query context parseSymbol"]),handler:Iv}];function Av(e,t,n,i){return[{title:"TARGET",rows:iu(e)},{title:"CURRENT RELATIONSHIPS",rows:Tv(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:Lv(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:nu(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:Mv(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:qv(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:ru(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:Dv(e,t,i)}]}function jv(e,t){return[{title:"TARGET",rows:iu(e)},{title:"DEFINITIONS",rows:ou(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:Wv(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:su(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:nu(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:ru(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Fv(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:_v(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Bv(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:Gv(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:au(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:cu(e),skipIfEmpty:!0}]}function Tv(e,t){return ge(oe([...ou(e,Math.min(t,12)),...su(e,t)],t))}function Lv(e,t){let n=e.trace.referencedBy.map(r=>` direct ${r.relativePath}:${O(r.line)} ${r.enclosingShort}`),i=e.affected.map(r=>` depth ${r.depth} ${r.file} ${r.shortName}`);return ge(oe(Nv([...n,...i]),t))}function Mv(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}`,...au(e),...cu(e)];return ge(oe(n,t))}function qv(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)??[],...gt(e).candidates.map(({candidate:i})=>i.fileB)];return ge(oe([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function Dv(e,t,n){let i=gt(e).coverage,r=[` Direct compiler references observed: ${e.trace.referencedBy.length}.`,` Downstream impact is bounded at depth ${n}.`,` Affected-consumer reuse scan: ${i.analyzedConsumers}/${i.totalConsumers} analyzed; ${i.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(o=>` Warning: ${o}`)),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 Nv(e){return[...new Set(e)]}function Zd(e){return{complete:!1,totalKnown:!1,returned:Ov(e)}}function Ov(e){let t=gt(e);return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.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 eu(e){let t=gt(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,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 nu(e,t){let n=(e.reuseCandidates??[]).flatMap(l=>[` target ${Math.round(l.similarity*100)}% ${l.evidenceClass} ${l.shortNameB} ${l.fileB}`,` basis=${l.similarityBasis??"unknown"}; ${l.evidenceClassReasons.join("; ")}`]),i=gt(e),r=i.candidates.flatMap(({candidate:l,consumers:d})=>[` consumer ${Math.round(l.similarity*100)}% ${l.evidenceClass} ${l.shortNameB} ${l.fileB}`,` basis=${l.similarityBasis??"unknown"}; observed from ${d.map(u=>u.shortName).join(", ")}; ${l.evidenceClassReasons.join("; ")}`]),o=i.coverage,s=o.totalConsumers>0?[` Affected-consumer scan: ${o.analyzedConsumers}/${o.totalConsumers} compiler-resolved consumer(s) analyzed; ${o.omittedConsumers} omitted; first ${o.perConsumerSearchLimit} similarity result(s) checked and up to ${o.perConsumerCandidateLimit} usable option(s) kept per consumer.`]:[],a=[...n,...s,...r];return ge(oe(a,t))}function iu(e){let t=[`Target: ${e.target}`,`Matched: symbol=${Di(e.matched.symbol)} file=${Di(e.matched.file)} module=${Di(e.matched.module)}`];return e.primaryCallable&&t.push(`Primary callable: ${e.primaryCallable.shortName} ${e.primaryCallable.file}`),t}function ru(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)} ${L(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
|
|
220
|
+
`).map((i,r)=>{let o=n.startLine+r;return` ${n.focusLines?.includes(o)?">":" "}${String(O(o)).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 ou(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${L(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
|
|
221
|
+
`).map((o,s)=>` ${String(O(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${ie(i.startLine,i.endLine)} ${i.shortName}`)),oe(n,t).rows}function Wv(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${O(i.line)} in ${i.enclosingShort}`);return ge(oe(n,t))}function su(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(r=>` caller ${r.file} ${r.shortName}`),i=e.callGraph.callees.map(r=>` callee ${r.file} ${r.shortName}`);return ge(oe([...n,...i],t))}function Fv(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 ge(oe(n,t))}function _v(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${ie(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return ge(oe(n,t))}function Bv(e,t){let n=[],i=-1;for(let r of e.affected)r.depth!==i&&(n.push(` -- Depth ${r.depth} --`),i=r.depth),n.push(` ${r.file} ${r.shortName}`);return ge(oe(n,t))}function Gv(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(kn))),e.complexity&&(n.push(` Complexity: ${L(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(` Metric rules: ${e.complexity.metricRules}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Candidate targets: ${e.complexity.candidateCalleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),ge(oe(n,t))}function au(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 cu(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."),gt(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 gt(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function oe(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function ge(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Di(e){return e?"yes":"no"}function Uv(e,t,n){let i=n.primaryCallable?.symbol??E(t,0);return n.matched.symbol?{...Qn(e,i),...n}:n}var lu=["stats","files","session","inspect","search","methods","refs","evidence","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","bottlenecks","by-kind","kind-counts","dependency-depth","hierarchy","entrypoints","entry-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","locality-candidates","affected","change-surface","cleanup-plan","co-change","recent-duplicates","doc-drift","unused-params","incomplete-migration","context","drift","passthrough-candidates","slice-cohesion","code","complexity","dependence-slice","redundant-reexports","duplicate-bodies","twin-drift","not-implemented","decorative-checkers","test-quality","similar-signatures"],Hv=[Cd,Xd,Ed,$n,Id,tu,Pd],du=Hv.flat(),Vv=new Map(du.map(e=>[e.id,e]));for(let e of du)if(!lu.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var uu=lu.map(e=>Qv(e));function Qv(e){let t=Vv.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var uE=[Cs,{id:"review",command:"review",agent:S("What did this diff change in function complexity, duplication, dependencies, and declared architecture?","all changed source functions, before/after metrics, exact finding sites, source freshness and coverage limits",[],"bounded","diff"),description:"Review current TS/JS changes against a Git commit, including new and untracked functions",options:b([c("--base <ref>","Git commit to compare with current files (default HEAD)"),c("--coverage <path>","Source-matched Istanbul coverage artifact from record-review-coverage.mjs"),c("-s, --scope <path>","Show changes under this exact file or directory; comparison still scans repository peers"),c("--include-tests","Also analyze tests, fixtures and benchmarks"),c("--include-references","Also analyze reference source and vendored copies"),c("--include-generated","Also analyze generated source"),c("--max-files <n>","Maximum eligible source files per snapshot (default 10000)",F),c("--limit <n>","Maximum displayed findings (default 20; function changes are always listed)",F),c("--full","Display every finding in the analyzed source snapshots"),c("--check","Exit 1 for introduced/worsened derived findings, 2 for incomplete source coverage; candidates require review")]),claims:re(["live-workspace"],[ot("findings","findings[]","evidence",{derived:"repository-source",candidate:"heuristic"}),T("changed-functions","functions[]","repository-source"),T("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:f("Health",["scip-query review --base HEAD","scip-query review --include-tests"]),handler:al},{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:ne("Did indexed source changes preserve the repository architecture policy?","architecture policy decision and enforced finding identities",[],"complete","diff",W("repository-observation")),description:"Internal architecture-only Stop hook",renderShape:"custom",handler:$l},{id:"reindex",command:"reindex",agent:ne("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository",W("composite")),description:"Index the codebase and convert to SQLite",options:b([c("-l, --language <lang>","Index only this language (can be repeated)",B,[]),c("--force","Rebuild even if source inputs are unchanged"),c("--allow-partial","Write an incomplete index when one or more detected languages fail"),c("--allow-expensive-rebuild","Explicitly permit a whole-project indexer when incremental and shared-generation paths are unavailable"),c("--trust-project-tools","Permit reviewed indexers from this repository for this run"),c("--install-missing","Install missing global tools at reviewed immutable versions for this run"),c("--indexer-concurrency <n>","Number of language indexers to run at once",F)]),renderShape:"custom",docs:f("Indexing",["scip-query reindex"]),handler:kl},{id:"augment-sources",command:"augment-sources",agent:ne("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository",W("composite")),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:f("Indexing"),handler:Cl},{id:"augment-vue",command:"augment-vue",agent:ne("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository",W("composite")),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[c("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:f("Indexing"),handler:El},...uu,{id:Ct,command:Ct,description:"Internal diff-impact batch worker",hidden:!0,options:[c("--json","Emit the private worker envelope without transport pagination"),c("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Pl},{id:"diff-impact",command:"diff-impact",agent:S("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:b([c("--base <ref>","Git ref to diff against (default: HEAD)")]),claims:re(["index-generation","live-workspace"],[T("changed-files","changedFiles[]","repository-source"),T("changed-symbols","changedSymbols[]","compiler-graph"),T("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:f("Impact"),handler:Il},{id:$t,command:$t,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[c("--json","Emit the private worker envelope without transport pagination"),c("-s, --scope <path>","Limit to files matching path"),c("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Al},{id:kt,command:kt,description:"Internal health semantic prewarm worker",hidden:!0,options:[c("--json","Emit the private worker envelope without transport pagination"),c("-s, --scope <path>","Limit to files matching path"),c("--full","Materialize complete semantic evidence"),c("--shard-index <n>","Warm only this zero-based slice of the indexed files"),c("--shard-count <n>","Number of parallel prewarm slices")],renderShape:"custom",handler:jl},{id:"health",command:"health",agent:ne("Where has this repository accumulated drift, duplication, complexity, or cleanup pressure?","concrete source findings and coverage limits; optional indexed specialist findings and baselines",[],"bounded","repository",W("repository-observation",[{when:{kind:"option",name:"writeBaseline",equals:!0},role:"composite"}])),description:"Find concrete TS/JS complexity, duplication, and dependency issues without an index",options:b([c("-s, --scope <path>","Limit to files matching path"),c("--full","Display all source findings; with --indexed, run unbounded candidate analyses"),c("--indexed","Run the specialist indexed report including React, Vue, drift and cleanup candidates"),c("--coverage <path>","Source-matched Istanbul coverage artifact"),c("--include-tests","Also analyze tests, fixtures and benchmarks"),c("--include-references","Also analyze reference source and vendored copies"),c("--include-generated","Also analyze generated source"),c("--max-files <n>","Maximum eligible source files (default 10000)",F),c("--limit <n>","Maximum source findings per category (default 5; --full shows every finding and suppression decision)",F),c("--check","Exit 1 for derived source findings, 2 for incomplete source coverage"),c("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),c("--write-baseline","Snapshot current finding identities to the baseline file")]),claims:re(["index-generation","live-workspace","process"],[ot("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),ot("source-findings","findings[]","evidence",{derived:"repository-source",candidate:"heuristic"}),T("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:f("Health",["scip-query health --json","scip-query health --baseline"]),handler:Tl},{id:"install-skills",command:"install-skills",agent:ne("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",W("mutation")),description:"Install the six agent workflows into Claude Code, Codex, and shared agent roots",options:[{flags:"--all",description:"Compatibility option: all six workflows are installed by default"}],renderShape:"custom",docs:f("Maintenance"),handler:Ll},{id:"check-deps",command:"check-deps",agent:S("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository",W("environment-observation")),description:"Check whether scip-query and the detected language indexers are runnable",renderShape:"custom",docs:f("Maintenance"),handler:Ml},{id:"capabilities",command:"capabilities",agent:S("Which repository-mapping and analysis capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository",W("environment-observation")),description:"Report which mapping and analysis capabilities are available in this project",options:b([c("--matrix","Add exhaustive provider and language support details")]),renderShape:"custom",docs:f("Maintenance"),handler:ql},{id:"init",command:"init",agent:ne("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository",W("mutation")),description:"Create a .scipquery.json configuration file for this project",renderShape:"custom",docs:f("Maintenance"),handler:Dl},{id:"config-validate",command:"config-validate",agent:S("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:b(),claims:Is("repository-source",["live-workspace"]),renderShape:"custom",docs:f("Maintenance",["scip-query config-validate"]),handler:Nl},{id:"suppress",command:"suppress <id>",agent:ne("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete",void 0,W("mutation")),description:"Record an accepted finding under .scipquery/suppressions with a required reason",options:b([c("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),c("--reason-code <code>","Required adjudication code"),c("--evidence <kind:referent>","Required counterevidence; repeat for more evidence",B,[]),c("--check <check>","Optional detector name to narrow the suppression"),c("--file <path>","Optional file path to narrow the suppression"),c("--expires-at <iso>","Optional ISO date after which the suppression expires"),c("--replace <revision>","Replace a prior decision with this exact SHA-256 revision")]),renderShape:"custom",docs:f("Maintenance"),handler:Ol},{id:"doctor",command:"doctor",agent:S("Why is scip-query unhealthy or unavailable in this project?","configuration, freshness, dependency, and capability diagnostics",[],"complete","repository",W("environment-observation")),description:"Diagnose configuration, index freshness, dependencies, and project capabilities",options:b(),renderShape:"custom",docs:f("Maintenance"),handler:Wl},{id:"setup",command:"setup",agent:ne("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository",W("composite")),description:"Install skills, write agent guidance, refresh the index, and report readiness",options:b([c("--guided","Require and open the interactive terminal checklist"),c("--yes","Accept recommended setup defaults without prompting"),c("--no-skills","Skip user-level agent skill installation"),c("--no-parsers","Skip Tree-sitter AST parser installation and repair"),c("--install-missing","Install missing global tools at reviewed immutable versions"),c("--health","Run optional indexed health specialists and write their dossier; use health for an index-free source scan"),{flags:"--no-health",description:"Compatibility inverse of --health",hidden:!0},c("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:f("Maintenance",["scip-query setup","scip-query setup --health","scip-query setup --install-missing","scip-query setup --json"]),handler:Bl},{id:"setup-agent",command:"setup-agent",agent:ne("Can concise project guidance for scip-query be written?","written, unchanged, and skipped agent instruction files",[],"complete","repository",W("mutation")),description:"Write concise scip-query mapping and cleanup guidance to AGENTS.md and CLAUDE.md",renderShape:"custom",docs:f("Maintenance",["scip-query setup-agent"]),handler:_l},{id:"uninstall",command:"uninstall",agent:ne("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository",W("mutation",[{when:{kind:"option",name:"dryRun",equals:!0},role:"repository-preview"}])),description:"Remove selected scip-query-owned skills or project guidance",options:b([c("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),c("--project","Remove managed AGENTS.md and CLAUDE.md blocks"),c("--dry-run","List what would be removed without changing files"),c("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:f("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Gl},{id:"watch",command:"watch",agent:ne("What is the watcher doing, or can background services be started, stopped, or pruned?","watcher state, generation, activity, and errors",[],"complete","repository",W("composite",[{when:{kind:"option",name:"status",equals:!0},role:"environment-observation"}])),description:"Watch in the foreground or manage the project refresh service",options:b([c("--daemon","Make sure that the background service is running"),c("--status","Show the watcher state"),c("--stop","Stop the watcher for this project"),c("--prune","Stop watcher services whose owned worktree roots no longer exist"),c("--debounce <ms>","Milliseconds after the last change",Ie),c("--cooldown <ms>","Minimum milliseconds between indexes",Ie),c("--git-poll <ms>","Milliseconds between Git state checks",Ie),c("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",Ie)]),renderShape:"custom",docs:f("Maintenance"),handler:Ul},{id:"status",command:"status",agent:S("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, and watcher state",[],"complete","repository",W("environment-observation")),description:"Show index status for this project",options:b([{...c("--capabilities","Compatibility: include a concise capability-readiness summary"),hidden:!0}]),renderShape:"custom",docs:f("Maintenance"),handler:Ql}];export{uE as commandDescriptors};
|
|
222
|
+
//# sourceMappingURL=command-descriptors-HEEMDHTU.js.map
|