codebaseiq 0.2.0 → 0.3.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 +44 -2
- package/README.md +1 -1
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-2DMVFAY7.js → chunk-23C5AD3B.js} +2 -2
- package/dist/{chunk-WH5SYOMD.js → chunk-2E6OUPCF.js} +2 -2
- package/dist/{chunk-RWKEXCHU.js → chunk-2EDX3JT5.js} +2 -2
- package/dist/chunk-2I2UHZET.js +2 -0
- package/dist/{chunk-CSZOQ7YO.js → chunk-2OMXFE64.js} +2 -2
- package/dist/{chunk-EXMVF3JR.js → chunk-2PRONPAS.js} +3 -3
- package/dist/{chunk-5WXOEJ4G.js → chunk-356EZBIP.js} +2 -2
- package/dist/{chunk-A7XQT7MH.js → chunk-36JC5BG2.js} +2 -2
- package/dist/{chunk-RRPK327J.js → chunk-3RR2K7EZ.js} +2 -2
- package/dist/{chunk-3NUZVLR7.js → chunk-3RSBGWGL.js} +2 -2
- package/dist/{chunk-MTMF4N7F.js → chunk-3VJ3OCRE.js} +2 -2
- package/dist/{chunk-IBM3F2BJ.js → chunk-4LK5OIPW.js} +2 -2
- package/dist/{chunk-FQA3KIFX.js → chunk-5DSL3NT2.js} +2 -2
- package/dist/{chunk-IYBIBMPF.js → chunk-5FWR5HLG.js} +2 -2
- package/dist/{chunk-CIVYHK7U.js → chunk-5IC2WZAL.js} +2 -2
- package/dist/{chunk-PARCKE3Q.js → chunk-5IZRKWTZ.js} +2 -2
- package/dist/{chunk-HHBBGWES.js → chunk-5LL4KEHO.js} +2 -2
- package/dist/chunk-5T44HG5Y.js +88 -0
- package/dist/{chunk-YFQPWKHR.js → chunk-5ZI2PPI7.js} +2 -2
- package/dist/{chunk-T3YFIJ5P.js → chunk-67VJAYVR.js} +2 -2
- package/dist/{chunk-DKJXK3HA.js → chunk-6BF3VYEF.js} +2 -2
- package/dist/chunk-6JMAVFL4.js +3 -0
- package/dist/chunk-6O3KXIDL.js +2 -0
- package/dist/{chunk-OJFLPVBP.js → chunk-6VREELBC.js} +2 -2
- package/dist/chunk-6WAPPQ5F.js +82 -0
- package/dist/{chunk-QLTFXVUI.js → chunk-75KJGYX7.js} +2 -2
- package/dist/{chunk-PLZXWZHY.js → chunk-7GAK2F3H.js} +2 -2
- package/dist/{chunk-X5I2BQGX.js → chunk-7JELP5YE.js} +2 -2
- package/dist/{chunk-W3FK73MD.js → chunk-7UCDGXRW.js} +2 -2
- package/dist/{chunk-CMXW7MFV.js → chunk-AEXQYQD7.js} +2 -2
- package/dist/{chunk-PHPQ24UG.js → chunk-AQI4N64O.js} +2 -2
- package/dist/{chunk-XUJM6474.js → chunk-AURCQHSG.js} +2 -2
- package/dist/{chunk-EM5UHLAM.js → chunk-BBP7HVBJ.js} +2 -2
- package/dist/{chunk-57KFVPVZ.js → chunk-BFBIMTCJ.js} +2 -2
- package/dist/{chunk-VVCBMH5O.js → chunk-BGGB5N53.js} +2 -2
- package/dist/{chunk-ZOEDRCR4.js → chunk-BRQL7AFJ.js} +2 -2
- package/dist/{chunk-KDYQQJ6X.js → chunk-BWL3PMPT.js} +2 -2
- package/dist/{chunk-M7LAIM77.js → chunk-C6WKPKCF.js} +2 -2
- package/dist/{chunk-2F5ERMNI.js → chunk-C7OUW52M.js} +2 -2
- package/dist/{chunk-N3Q3AWGW.js → chunk-C7QWUBR2.js} +96 -96
- package/dist/{chunk-BX2U3QQV.js → chunk-CCIYWXX6.js} +2 -2
- package/dist/{chunk-3AC56WAR.js → chunk-CIYA2KZN.js} +2 -2
- package/dist/{chunk-35YYZD3D.js → chunk-CR3OG6SQ.js} +2 -2
- package/dist/{chunk-VYZQZ4ZN.js → chunk-CVHOQONG.js} +2 -2
- package/dist/{chunk-4IFISPQW.js → chunk-CW6AXOLR.js} +2 -2
- package/dist/{chunk-NDGTJHQN.js → chunk-D53LWANR.js} +2 -2
- package/dist/{chunk-VCWAJPXQ.js → chunk-D7AZAOZX.js} +2 -2
- package/dist/{chunk-ACZDU5GK.js → chunk-D7DOB27N.js} +7 -7
- package/dist/{chunk-CDWSLAPN.js → chunk-DAKIGMIK.js} +2 -2
- package/dist/chunk-DDN2F6GB.js +2 -0
- package/dist/{chunk-L3YSDLNB.js → chunk-DVWO7RBC.js} +2 -2
- package/dist/{chunk-KNV5VFDV.js → chunk-E52K4L2W.js} +2 -2
- package/dist/chunk-EIBGSU2R.js +2 -0
- package/dist/chunk-EQNMD62X.js +51 -0
- package/dist/{chunk-LY2NB5XR.js → chunk-EXZ7VLRY.js} +2 -2
- package/dist/{chunk-YIOQJ45A.js → chunk-F3QSL4W2.js} +2 -2
- package/dist/{chunk-JOALNFY3.js → chunk-F74LZWCE.js} +2 -2
- package/dist/{chunk-ZB3V5QM7.js → chunk-FEIZXBLH.js} +2 -2
- package/dist/{chunk-NJA4MMBD.js → chunk-FH5WG4LE.js} +2 -2
- package/dist/{chunk-MRGTCMDK.js → chunk-FOZ74V56.js} +2 -2
- package/dist/{chunk-S5SKXCND.js → chunk-FQTIFWLR.js} +2 -2
- package/dist/chunk-FTTV7IRX.js +355 -0
- package/dist/chunk-FWQGH2N2.js +2 -0
- package/dist/{chunk-PFPHS4NO.js → chunk-GDHWOA57.js} +2 -2
- package/dist/{chunk-H3CKAL6P.js → chunk-GIDCP7KV.js} +2 -2
- package/dist/{chunk-6SDEQTVY.js → chunk-GL6UTNUB.js} +2 -2
- package/dist/{chunk-37TKC6MB.js → chunk-GP7C5VAE.js} +2 -2
- package/dist/{chunk-U24M5RQM.js → chunk-GQLDYCWS.js} +2 -2
- package/dist/{chunk-I5FCDTK2.js → chunk-GQXXOS55.js} +2 -2
- package/dist/{chunk-NTRW52UR.js → chunk-GUFPEFBG.js} +2 -2
- package/dist/{chunk-B2E3HZ2A.js → chunk-GV2CEZCW.js} +2 -2
- package/dist/{chunk-AM5SUGHF.js → chunk-GVAF222T.js} +2 -2
- package/dist/{chunk-TAJ6UGCO.js → chunk-GWYZVVKY.js} +3 -3
- package/dist/{chunk-NK76RSB6.js → chunk-HENP2O4A.js} +2 -2
- package/dist/{chunk-VG55NFXF.js → chunk-HINZQKSY.js} +2 -2
- package/dist/{chunk-6OVNYYY4.js → chunk-HQA7EBSK.js} +2 -2
- package/dist/{chunk-DLC6JDN7.js → chunk-HVFB3PME.js} +2 -2
- package/dist/{chunk-FY5V4V4F.js → chunk-I22IZYDI.js} +2 -2
- package/dist/{chunk-RVYLJDXC.js → chunk-ICUL7XRT.js} +2 -2
- package/dist/{chunk-QVHZB75Z.js → chunk-IHSLIIL3.js} +2 -2
- package/dist/{chunk-PNVZIJ57.js → chunk-ITSJMNUD.js} +2 -2
- package/dist/{chunk-XNUWRTYM.js → chunk-IZDPGOZR.js} +2 -2
- package/dist/chunk-J3GLP7Q5.js +3 -0
- package/dist/{chunk-BH5CE4LN.js → chunk-J7AMBVWF.js} +2 -2
- package/dist/{chunk-YXJ4IAHH.js → chunk-JCMFBF4Z.js} +2 -2
- package/dist/{chunk-ZJZQ7Q2Q.js → chunk-JFIA2JI3.js} +2 -2
- package/dist/{chunk-FIXYHQ3W.js → chunk-JLZLLLW5.js} +2 -2
- package/dist/{chunk-2E6BTWER.js → chunk-JSNTHRLQ.js} +2 -2
- package/dist/{chunk-77GHPR2R.js → chunk-JX6ZWDOS.js} +2 -2
- package/dist/{chunk-SRY26ITJ.js → chunk-JYI7CV25.js} +2 -2
- package/dist/chunk-K7JLSGCJ.js +8 -0
- package/dist/{chunk-DFPAZXLU.js → chunk-KPZGTB2O.js} +2 -2
- package/dist/{chunk-7Z7HCZ7J.js → chunk-LKUTSP4G.js} +2 -2
- package/dist/{chunk-HIEXRDJF.js → chunk-LMTSB3TB.js} +2 -2
- package/dist/{chunk-BLKYYQ7C.js → chunk-LONKINMJ.js} +95 -95
- package/dist/{chunk-SF34QLK2.js → chunk-LQHYYIOB.js} +2 -2
- package/dist/{chunk-HBQGKMM3.js → chunk-LZSQ6X7E.js} +2 -2
- package/dist/{chunk-RCPZOPV6.js → chunk-M2Y6PCFE.js} +2 -2
- package/dist/{chunk-WJOQC4P7.js → chunk-MEUHIDI3.js} +2 -2
- package/dist/{chunk-MT5W4DUG.js → chunk-MHWMEZDA.js} +2 -2
- package/dist/{chunk-FLLXYUOL.js → chunk-MQW6SJ4P.js} +2 -2
- package/dist/{chunk-57KEZDPT.js → chunk-MSI3K7PJ.js} +2 -2
- package/dist/chunk-MVRGB4KJ.js +278 -0
- package/dist/{chunk-27PHVDKL.js → chunk-MZNMASFM.js} +2 -2
- package/dist/{chunk-DVYG3JTA.js → chunk-NBCQZSGR.js} +2 -2
- package/dist/{chunk-NIO346UL.js → chunk-NBZKSTXP.js} +2 -2
- package/dist/{chunk-UWB5WMC2.js → chunk-NCJILOAK.js} +2 -2
- package/dist/{chunk-JN5LIBT3.js → chunk-NDKOVQFG.js} +2 -2
- package/dist/{chunk-W6C6QTXJ.js → chunk-NEWHKGVD.js} +2 -2
- package/dist/{chunk-HBXZAGY6.js → chunk-O2M3VNDY.js} +2 -2
- package/dist/chunk-OFGOOL6U.js +3 -0
- package/dist/{chunk-FEBLLMTL.js → chunk-OQUCBKOI.js} +2 -2
- package/dist/{chunk-5IO2APSS.js → chunk-P4NVCOM7.js} +2 -2
- package/dist/{chunk-SJZQ2PTZ.js → chunk-PFC44E6D.js} +2 -2
- package/dist/{chunk-LAGDJXFY.js → chunk-PHNCEUXX.js} +2 -2
- package/dist/{chunk-HYKSLTAR.js → chunk-PTQPPPG2.js} +2 -2
- package/dist/{chunk-5XEVXVTK.js → chunk-PUVNH4PO.js} +2 -2
- package/dist/chunk-Q23IMHXS.js +343 -0
- package/dist/{chunk-YYFV32WR.js → chunk-Q3ZCQY2Y.js} +2 -2
- package/dist/{chunk-OMBRP7BB.js → chunk-Q4XEU3UH.js} +2 -2
- package/dist/{chunk-I645ZF75.js → chunk-QEOWONKY.js} +2 -2
- package/dist/{chunk-JXHLB7TP.js → chunk-QMOZZ2VX.js} +2 -2
- package/dist/{chunk-2VKB5CMA.js → chunk-RCIGX23V.js} +2 -2
- package/dist/{chunk-J24VICI5.js → chunk-RIYJ4L33.js} +2 -2
- package/dist/{chunk-M4EVGA5S.js → chunk-RJVAPMHF.js} +3 -3
- package/dist/chunk-SB7NASHU.js +2 -0
- package/dist/{chunk-3XFJUWJE.js → chunk-SGMNWYTH.js} +2 -2
- package/dist/chunk-SMDIEDM4.js +27 -0
- package/dist/{chunk-IOVPAZWP.js → chunk-SX72EVMY.js} +2 -2
- package/dist/{chunk-WO47BIPY.js → chunk-T5X7DK6C.js} +2 -2
- package/dist/{chunk-CZEIHYMP.js → chunk-T6MQNNAC.js} +2 -2
- package/dist/chunk-T75DS2E6.js +21 -0
- package/dist/{chunk-57GCCPLS.js → chunk-TEANKHUU.js} +2 -2
- package/dist/{chunk-T55YPJGB.js → chunk-TJBOJUVN.js} +2 -2
- package/dist/{chunk-I2KP4AGR.js → chunk-TJWVT4DO.js} +2 -2
- package/dist/{chunk-KM4QRWI5.js → chunk-TNJGTQWO.js} +2 -2
- package/dist/{chunk-EFFMFK7C.js → chunk-TOTWJZIX.js} +2 -2
- package/dist/{chunk-QMGWSEPL.js → chunk-TPO7XC5Z.js} +2 -2
- package/dist/{chunk-54K6556S.js → chunk-U33PMPNW.js} +2 -2
- package/dist/{chunk-GXVDTHFC.js → chunk-U7NUXDQO.js} +2 -2
- package/dist/chunk-UC2FD2PS.js +4 -0
- package/dist/{chunk-TUTSO7UZ.js → chunk-UQE4XFSA.js} +2 -2
- package/dist/{chunk-4O52YNKL.js → chunk-UQYQBLJX.js} +2 -2
- package/dist/{chunk-FPDL2TUB.js → chunk-USOAJHY7.js} +2 -2
- package/dist/{chunk-JUO3Z644.js → chunk-UW6KD57C.js} +2 -2
- package/dist/{chunk-VLTUX4IF.js → chunk-VGWZ4MOY.js} +2 -2
- package/dist/{chunk-U2XX3BT4.js → chunk-VWYGCMV5.js} +2 -2
- package/dist/{chunk-IWAMYGPN.js → chunk-W7YLRXZE.js} +2 -2
- package/dist/{chunk-QKVTWODE.js → chunk-WK2IQJPK.js} +2 -2
- package/dist/{chunk-S64NCE2Z.js → chunk-WWCV4E6J.js} +2 -2
- package/dist/{chunk-IVJJNVSX.js → chunk-XMJ53WG4.js} +2 -2
- package/dist/{chunk-IGYAZPRX.js → chunk-XN3EKMLI.js} +2 -2
- package/dist/{chunk-FWY2PRIF.js → chunk-XQAVQVIL.js} +2 -2
- package/dist/{chunk-JYX5UZSZ.js → chunk-XQPPURLQ.js} +2 -2
- package/dist/{chunk-4AOOSCZ7.js → chunk-YHPG3S2U.js} +2 -2
- package/dist/{chunk-5BDK6QC3.js → chunk-YRKP7PM7.js} +2 -2
- package/dist/{chunk-4NHWNAWQ.js → chunk-YT4DVWUV.js} +2 -2
- package/dist/{chunk-5NJPH3QZ.js → chunk-YTJHCGYB.js} +2 -2
- package/dist/chunk-Z35GOVEH.js +2 -0
- package/dist/{chunk-K5G7SPAG.js → chunk-Z6RL7XOE.js} +4 -4
- package/dist/{chunk-OVKZM2XI.js → chunk-ZAFGY22Q.js} +2 -2
- package/dist/{chunk-A67HT5FR.js → chunk-ZB4C5TTR.js} +2 -2
- package/dist/{chunk-CWMHWD56.js → chunk-ZNH33XIB.js} +2 -2
- package/dist/{chunk-ZNQCR656.js → chunk-ZQ62NNKN.js} +2 -2
- package/dist/{cli-context-XEPPF4RX.js → cli-context-FJL2JHOE.js} +2 -2
- package/dist/{cli-context-TSADTXLB.js → cli-context-PQNWHMCQ.js} +2 -2
- package/dist/{cli-program-KJGQEM72.js → cli-program-UO7PZD6V.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{code-CDe-mIjx.d.ts → code-DfX3xeWy.d.ts} +1 -1
- package/dist/{code-viewer-YGDON6SY.js → code-viewer-KIXEYQNJ.js} +2 -2
- package/dist/{code-viewer-ZCTHXQ5C.js → code-viewer-VHLBLIUM.js} +2 -2
- package/dist/{command-descriptors-5VAB2MZX.js → command-descriptors-F5P2V3NW.js} +129 -129
- package/dist/{command-descriptors-EAHKIRAG.js → command-descriptors-YCLATF5I.js} +130 -130
- package/dist/{db-DmRNdCtm.d.ts → db-BoG_PWYH.d.ts} +1 -1
- package/dist/direct-navigation-4XJTXIDT.js +2 -0
- package/dist/direct-navigation-J5MVYYAD.js +3 -0
- package/dist/{graph-evidence-Bs54NWws.d.ts → graph-evidence-D1jx1Cql.d.ts} +1 -1
- package/dist/{health-BnzbSLCE.d.ts → health-DkYBS5BI.d.ts} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/invocation-command-descriptors-RWV4VAI4.js +2 -0
- package/dist/invocation-command-descriptors-U76PN7IY.js +3 -0
- package/dist/{scip-cli-BRFKkHQn.d.ts → maintenance-types-CdL5eQii.d.ts} +1 -20
- package/dist/output-continuation-command-BL25S26S.js +3 -0
- package/dist/output-continuation-command-BTETTXEC.js +2 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-CRJU3IFG.js +2 -0
- package/dist/project-reindex-TQFCOA2O.js +3 -0
- package/dist/queries/affected.d.ts +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/anchors.d.ts +1 -1
- package/dist/queries/anchors.js +1 -1
- package/dist/queries/architecture.d.ts +1 -1
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +1 -1
- package/dist/queries/context.js +1 -1
- package/dist/queries/convergence.d.ts +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/dependence-slice.d.ts +2 -2
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.d.ts +1 -1
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.d.ts +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +1 -1
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.d.ts +2 -2
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/extract-candidates.d.ts +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +1 -1
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +2 -2
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +1 -1
- 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 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +4 -4
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +1 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +1 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/reference-neighborhood.d.ts +1 -1
- package/dist/queries/reference-neighborhood.js +1 -1
- package/dist/queries/reference-reachability.d.ts +1 -1
- package/dist/queries/reference-reachability.js +1 -1
- package/dist/queries/refs.d.ts +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/source-inspection.d.ts +3 -3
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.d.ts +1 -1
- package/dist/queries/source-search.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +1 -1
- package/dist/queries/surface.d.ts +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system-map.d.ts +1 -1
- package/dist/queries/system-map.js +1 -1
- package/dist/queries/system.d.ts +1 -1
- 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/trace.d.ts +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/value-flow.d.ts +2 -2
- package/dist/queries/value-flow.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +2 -2
- package/dist/reindex.d.ts +2 -4
- package/dist/reindex.js +71 -32
- package/dist/runtime.d.ts +1 -2
- package/dist/runtime.js +3 -3
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/sentinel-ensure-command-OSWGCFFL.js +3 -0
- package/dist/sentinel-ensure-command-SPW7XQLB.js +2 -0
- package/dist/sentinel-worker.js +1 -1
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +2 -2
- package/docs/INDEX_GENERATIONS.md +2 -2
- package/docs/NPM_RELEASE.md +323 -0
- package/docs/schemas/npm-release-state.schema.json +4 -13
- package/package.json +3 -11
- package/dist/chunk-2Q2LW5JW.js +0 -14
- package/dist/chunk-327YK6TB.js +0 -4
- package/dist/chunk-347TXATM.js +0 -2
- package/dist/chunk-36WRYYTE.js +0 -3
- package/dist/chunk-6OAHRI2D.js +0 -6
- package/dist/chunk-6URCE5QY.js +0 -2
- package/dist/chunk-6ZV5EDUT.js +0 -5
- package/dist/chunk-7R64XY4Y.js +0 -12
- package/dist/chunk-CANBLFVQ.js +0 -15
- package/dist/chunk-CCRZLRWJ.js +0 -2
- package/dist/chunk-G2XUZCF2.js +0 -88
- package/dist/chunk-H5QXP63L.js +0 -2
- package/dist/chunk-HCMQZPEO.js +0 -2
- package/dist/chunk-IEL6Q5W3.js +0 -308
- package/dist/chunk-IGQQUENU.js +0 -109
- package/dist/chunk-K2O7SBAU.js +0 -2
- package/dist/chunk-QVWDQTMG.js +0 -2
- package/dist/chunk-RJWAB4VR.js +0 -345
- package/dist/chunk-VCL7FK3E.js +0 -3
- package/dist/chunk-WOOTEWQT.js +0 -239
- package/dist/chunk-XYLV727H.js +0 -21
- package/dist/chunk-YMGZZEW4.js +0 -2
- package/dist/direct-navigation-B3SGOOBW.js +0 -2
- package/dist/direct-navigation-ZL362KXF.js +0 -3
- package/dist/invocation-command-descriptors-CSUGUHTT.js +0 -2
- package/dist/invocation-command-descriptors-PPVZOIE5.js +0 -3
- package/dist/output-continuation-command-FTVVBVSN.js +0 -2
- package/dist/output-continuation-command-ITPRC3YV.js +0 -3
- package/dist/project-reindex-7HZSLLLY.js +0 -3
- package/dist/project-reindex-NGM3DYBN.js +0 -2
- package/dist/sentinel-ensure-command-KYYULCFU.js +0 -2
- package/dist/sentinel-ensure-command-RIZA3RY7.js +0 -3
- package/docs/WINDOWS_SIDECAR_RELEASE.md +0 -424
- package/docs/schemas/windows-sidecar-provenance.schema.json +0 -137
- package/scripts/build-codebaseiq-windows.mjs +0 -197
- package/scripts/codebaseiq-windows-provenance.mjs +0 -364
- package/scripts/verify-codebaseiq-windows.mjs +0 -29
|
@@ -1,88 +1,88 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as Ga}from"./chunk-YYFV32WR.js";import{a as Va,c as Rn}from"./chunk-362QOSFD.js";import{a as Ha}from"./chunk-ZJZQ7Q2Q.js";import{a as ca}from"./chunk-VYZQZ4ZN.js";import{a as fa,b as ba,c as ya,e as wa}from"./chunk-WO47BIPY.js";import{a as F,b as w,c as Te,d as ne,e as Le,f as d,g as ui,h as xa,i as C,j as R,k as qe,l as Ra,m as X,n as Ca,o as Ie,p as k,q as le,r as gt,s as It,t as pi,u as lt,v as de,w as ue,x as $e,y as Nt,z as Ia}from"./chunk-FPDL2TUB.js";import{A as E,B as D,C as ja,D as P,E as wn,F as re,a as ce,b as K,i as Y,j as te,k as ka,l as Ea,m as Ta,n as ze,o as La,p as be,q as Pa,r as Se,s as Aa,t as N,v as G,w as $,x as U,y,z as A}from"./chunk-FIXYHQ3W.js";import{a as sr,e as tt,f as Rt,h as ar,i as ai}from"./chunk-PHPQ24UG.js";import{a as Dt,b as mi,c as Na,d as Da,e as Oa,f as xn,g as Ma,h as qa,i as Fa,j as Ba,k as Wa,l as _a,m as Ua}from"./chunk-IEL6Q5W3.js";import{a as Cn,b as kn}from"./chunk-FQA3KIFX.js";import{a as hn,b as la,c as fn,d as da,e as ua,f as pa,h as ma,i as ga,j as ha,k as bn,l as yn,m as vn,n as va,r as Sn,s as $n,t as Sa,v as $a}from"./chunk-CIVYHK7U.js";import{$ as Kr,$a as Ks,A as Cr,Aa as Ss,B as kr,Ba as $s,C as Er,Ca as ws,D as Tr,Da as xs,Ea as Rs,F as Pr,Fa as Cs,G as li,Ga as ks,H as Ar,Ha as Es,I as jr,Ia as Ts,J as Ir,Ja as Ls,Ka as Ps,L as Nr,La as As,M as Dr,Ma as js,N as Or,Na as Is,O as Mr,Oa as Ns,P as qr,Pa as Ds,Q as Fr,Qa as Os,R as Br,Ra as Ms,S as Wr,Sa as qs,T as _r,Ta as Fs,U as Vr,Ua as Bs,V as Gr,Va as Ws,W as Ur,Wa as _s,Xa as Vs,Y as Hr,Ya as Gs,Z as gn,Za as Us,_ as Pt,_a as Hs,a as I,aa as zr,ab as zs,b as fe,ba as Jr,bb as Js,c as V,ca as Qr,cb as Qs,d as sn,da as Xr,db as Xs,e as T,ea as Yr,eb as Ys,f as kt,fa as Zr,fb as ta,g as gr,ga as es,gb as na,h as hr,ha as ts,hb as di,i as fr,ia as ns,ib as At,j as yr,ja as is,jb as jt,k as pn,ka as os,kb as je,l as vr,la as rs,m as Et,ma as ss,mb as ia,n as Sr,na as as,nb as oa,o as $r,oa as cs,ob as ra,pa as ls,pb as sa,qa as ds,qb as aa,ra as us,sa as ps,t as wr,ta as ms,u as Tt,ua as gs,va as hs,wa as fs,xa as bs,y as xr,ya as ys,z as Rr,za as vs}from"./chunk-N3Q3AWGW.js";import{a as Lt,b as mn,d as Lr,f as Ke}from"./chunk-B2OB55RR.js";import{b as rr}from"./chunk-XZEE23VG.js";import{A as et,B as qo,C as Fo,D as Bo,E as Wo,F as _o,G as Vo,I as Go,J as Uo,K as mt,L as Ho,M as ct,S as Jo,T as Qo,U as Xo,V as Yo,W as Zo,X as er,Y as tr,Z as nr,_ as pe,a as xt,b as ti,ba as ge,c as ni,ca as ri,g as jo,ga as ir,h as Io,ha as or,i as No,j as Do,ka as Ee,ma as he,na as si,o as ii,u as Oo,v as on,w as Mo,x as oi,y as Ae,z as st}from"./chunk-W3FK73MD.js";import"./chunk-EN4AHLL3.js";import{A as lr,G as cn,Ga as mr,H as dr,Ha as dn,I as ci,Lb as Zs,Mb as ea,_ as ur,bb as He,eb as br,ga as oe,ha as pr,k as cr,nb as un,p as an,ta as ln,z as Ct}from"./chunk-RJWAB4VR.js";import{c as $o}from"./chunk-D62CTZX6.js";import{$ as Ao,Aa as zo,Ba as ie,Ca as me,E as ko,F as Eo,J as To,T as Lo,U as Po,a as wo,b as ei,j as rt,k as xo,l as Ue,n as nn,o as Ro,pa as at,r as wt,va as rn,z as Co,za as Ko}from"./chunk-G2XUZCF2.js";import{A as Zn,b as vo,g as St,h as en,k as tn,l as ot,q as ke,r as pt,y as So,z as $t}from"./chunk-DUKHVPU5.js";import{existsSync as En,mkdirSync as kp,symlinkSync as Ep,readlinkSync as gi,unlinkSync as hi,readdirSync as Ka}from"fs";import{join as Fe,dirname as Ot,resolve as nt,relative as Tp,isAbsolute as Lp}from"path";import{homedir as Tn,platform as Pp}from"os";import{fileURLToPath as za}from"url";var Ap=Pp()==="win32",Ln=["codebaseiq","codebaseiq-explore","concrete-plan"];function Pn(e={}){let t=e.quiet?()=>{}:console.log,n=za(import.meta.url),i=nt(Ot(n),"..","skills"),o=[Fe(Tn(),".claude","skills"),Fe(Tn(),".codex","skills"),Fe(Tn(),".agents","skills")],r={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of o){let a=Ot(s);if(!En(a))continue;kp(s,{recursive:!0});let c=Xa(s);jp(s,i,c,r,t);for(let l of Ln){let u=Fe(i,l),m=Fe(s,l);if(!En(u)){r.skipped.push(`${c}/${l}`);continue}if(En(m)){try{let g=gi(m);if(nt(g)===nt(u)){r.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{r.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}hi(m)}Ep(u,m,Ap?"junction":"dir"),r.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return r}function jp(e,t,n,i,o){let r=new Set(Ln);for(let s of Ka(e)){if(r.has(s))continue;let a=Fe(e,s),c;try{c=nt(Ot(a),gi(a))}catch{continue}Qa(c,t)&&(hi(a),i.pruned.push(`${n}/${s}`),o(` prune: ${s} \u2192 ${n} (removed stale codebaseiq skill link)`))}}function Ja(e={}){let t=za(import.meta.url),n=nt(Ot(t),"..","skills"),i=e.homeDir??Tn(),o=[Fe(i,".claude","skills"),Fe(i,".codex","skills"),Fe(i,".agents","skills")],r={removed:[],left:[],skipped:[]};for(let s of o){if(!En(s))continue;let a=Xa(s);for(let c of Ka(s)){let l=Fe(s,c),u;try{let m=gi(l);u=nt(Ot(l),m)}catch{r.left.push(`${a}/${c} (not a symlink)`);continue}if(!Qa(u,n)){r.left.push(`${a}/${c} (symlink outside codebaseiq package)`);continue}if(r.removed.push(`${a}/${c}`),!e.dryRun)try{hi(l)}catch(m){r.skipped.push(`${a}/${c} (${m instanceof Error?m.message:String(m)})`)}}}return r}function Qa(e,t){let n=Tp(nt(t),nt(e));return n===""||!n.startsWith("..")&&!Lp(n)}function Xa(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as _t}from"fs";import{dirname as Ii,join as ji}from"path";import{execFileSync as Sm}from"child_process";import{createRequire as Ip}from"module";var Np=Ip(import.meta.url);function Ya(e,t=[]){let n=Dp(),i=vr(e,t),o=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i,reason:"ts-morph is not installed"}}function Dp(){try{return Np.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Mt,spawnSync as Op}from"child_process";import{existsSync as Ne,mkdtempSync as Mp,readdirSync as qp,rmSync as Za,symlinkSync as Fp,writeFileSync as Bp}from"fs";import{tmpdir as Wp}from"os";import{join as ye}from"path";var _p=3e5,Vp=12,ic=3e4,bi=1024*1024,Gp={readWorkingTreeStatus(e){return Mt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:ic,maxBuffer:bi,windowsHide:!0,killSignal:"SIGKILL"})}};function oc(e,t,n={}){let i=em(e,n.workingTreeRuntime),o=i.state==="known"?i.files:[],r=Zp(t,i),s=yi(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:[]};let a=zp(t,s),c=n.timeoutMs??_p,l=[],u=new Map,m;try{m=sc(e,"scip-cleanup-verify-")}catch(g){return{checkers:s.map(p=>p.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,unavailableReason:im(g),batches:[]}}try{nm(e,m.root);for(let g of s)u.set(g.label,tc(g,m.root,c).rawErrors);for(let g of t.batches){ac(m.root,g);let p=null;for(let h of s){let f=tc(h,m.root,c),b=Up(f,u.get(h.label)??[],f.rawErrors);if(b.status==="failed"){let v=b.errors.length>0?b.errors:f.outputTail;p={depth:g.depth,status:"failed",reason:`${h.label}: ${b.reason}`,errors:v.slice(0,Vp)};break}}if(!p)l.push({depth:g.depth,status:"verified"});else{l.push(p);break}}}finally{m.dispose()}return{checkers:s.map(g=>g.label),uncoveredFiles:a,baselineErrors:[...u.values()].reduce((g,p)=>g+p.length,0),workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:l}}function Up(e,t,n){let i=Hp(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 Hp(e,t){let n=Kp(e),i=new Map,o=[];for(let r of t){let s=rc(r),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&o.push(r)}return o}function Kp(e){let t=new Map;for(let n of e){let i=rc(n);t.set(i,(t.get(i)??0)+1)}return t}function zp(e,t){let n=new Set(t.flatMap(o=>o.coversExtensions));return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>{let r=o.slice(o.lastIndexOf("."));return!n.has(r)}).sort()}function rc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var ec=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Jp=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function yi(e){let t=[];if(Ne(ye(e,"tsconfig.json"))){let n=ye(e,"node_modules",".bin","tsc");t.push(Ne(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:ec,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:ec,strength:"reference-aware"})}if(Ne(ye(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>Ne(ye(e,n)))){let n=Qp();n&&t.push(n)}if(Jp.some(n=>Ne(ye(e,n)))){let n=Xp(e);n&&t.push(n)}for(let n of Yp(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:ye(e,n,"..","target")}});return t}function Qp(){return He("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"}:He("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Xp(e){let t=ye(e,"node_modules",".bin","clj-kondo");return Ne(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...an],strength:"reference-aware"}:He("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...an],strength:"reference-aware"}:He("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...an],strength:"reference-aware"}:null}function Yp(e){let t=[];if(Ne(ye(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=qp(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||Ne(ye(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function Zp(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>n.has(o)).sort()}function em(e,t=Gp){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:
|
|
4
|
-
`),o=(n.rust===!0?
|
|
5
|
-
`),r=new Set;for(let s of t){let a=
|
|
6
|
-
`)}function
|
|
7
|
-
${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:
|
|
8
|
-
`)){if(!n.trim().startsWith("{"))continue;let i=
|
|
9
|
-
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function
|
|
10
|
-
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var gc={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"]},$m={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"},wm={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 Be(e,t){let n=t.languages??rn(e),i=n.map(a=>{let c=un(xn(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),o=Om(e,n,t),r=Si({semantics:o},"typescript"),s=yi(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:o,semantic:r,checkers:s,gitAvailable:Fm(e),...xm(e,t)}}function xm(e,t){try{let n=mt(e,t),i=bn(e),o=Object.fromEntries(i.hosts.map(r=>[r.host,r.missing.length===0?"installed":r.events.length>0?"partial":"none"]));return{agentIntegrations:{builder:{mode:n.mode,chain:n.chain.map(No)},sentinel:{enabled:t.sentinel?.enabled===!0,hooks:o,delivery:vn(nn(e,t))}}}}catch{return{}}}function ht(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",o=i!=="unavailable",r=e.languages.map(c=>Im(e,c,{hasIndexedGraph:Nm(c,t),runtimeProbe:t.runtimeProbe})),s=r.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:r,relations:Cm(r,o),capabilities:[{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...Lm(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?r.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-impact",label:"Git change mapping",status:e.gitAvailable&&o?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-symbol and downstream-consumer mapping.":"Git is unavailable or the project root is not a git worktree."},...Rm(e.agentIntegrations)]}}function Rm(e){if(!e)return[];let{builder:t,sentinel:n}=e,i=Object.entries(n.hooks).map(([s,a])=>`${s}=${a}`).join(", "),o=Object.entries(n.delivery).map(([s,a])=>`${s}=${a}`).join(", "),r=Object.values(n.hooks).some(s=>s!=="none");return[{id:"symbol-builder",label:"Symbol builder",status:t.chain.length===0?"unavailable":"partial",evidence:"heuristic",reason:`mode ${t.mode}; chain ${t.chain.join(", ")||"(empty)"}; not probed; run doctor`},{id:"sentinel",label:"Trailing sentinel",status:n.enabled?r?"available":"partial":"unavailable",evidence:"heuristic",reason:n.enabled?`enabled; hooks ${i}; delivery ${o}`:`disabled; hooks ${i}; enable with codebaseiq setup --sentinel`}]}function Cm(e,t){return Va.map(n=>{let i=Lr.flatMap(r=>{let s=r.relations.filter(a=>a.family===n.family);return s.length===0?[]:[km(r,s,e,t)]}),o=vi(i.map(r=>r.status));return{...n,status:o,providerCapabilities:i,reason:o==="unsupported"?t?"The current project has no available provider for this relationship family.":"An indexed graph is required before this relationship family can be queried.":o==="exact"?"Exact within indexed compiler/source identity coverage; dynamic or unindexed constructs remain outside scope.":"Supported by bounded static providers; unresolved and unsupported constructs remain explicitly reported."}})}function km(e,t,n,i){let o=n.map(a=>Em(e,t,a,i)),r=vi(o.map(a=>a.status)),s=o.filter(a=>a.status!=="unsupported").map(a=>a.language);return{id:e.id,label:e.label,status:r,requirements:e.requirements,subtypes:t.map(a=>a.subtype),languages:o,reason:s.length===0?`Unavailable: requires ${e.requirements.join(", ")}.`:`${r} support for ${s.join(", ")}; analytical ceiling is declared per subtype.`}}function Em(e,t,n,i){let o=e.requirements.filter(s=>!Tm(s,n,i));if(o.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${o.join(", ")}.`};let r=vi(t.map(s=>s.supportCeiling));return{language:n.language,status:r,reason:`${e.label} is available; subtype coverage is ${r}.`}}function Tm(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 vi(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 Lm(e){return Pm(e).map(t=>{let n=Si(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Am(t)} semantic provider`,status:i,evidence:"semantic",reason:jm(t,n)}})}function Pm(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of fc(e))t.add(n.language);return[...t].sort((n,i)=>pc(n)-pc(i))}function pc(e){return e==="typescript"?0:1}function Am(e){return e==="typescript"?"TypeScript":"Rust"}function jm(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 Im(e,t,n){let i=e.indexers.find(u=>u.language===t),o=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",r=o!=="unavailable",s=Dm(t,n.runtimeProbe),a=Mm(e,t),c=qm(e,t),l=c.length===0?"unavailable":c.every(u=>u.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:o,evidence:"graph-fact",reason:o==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:o==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:r?s.status:"unavailable",evidence:"heuristic",reason:r?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(u=>u.label).join(", "):`No detected checker covers ${gc[t].join(", ")} files.`}}}function Nm(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Dm(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??mc(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=hc(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)??mc(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 mc(e){let t=$m[e];return t?cn(t):hc(e)==="regex-only"?"regex":"unavailable"}function hc(e){let t=wm[e],n=t?ur(t):null;return n?.imports??n?.exports??n?.reExports??null}function Om(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...Ya(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let o=yr(e);i.push({language:"rust",available:o.available,dependencyAvailable:o.dependencyAvailable,resolvedBinary:o.resolvedBinary,reason:o.available?o.note:o.reason})}return i}function fc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Si(e,t){return fc(e).find(n=>n.language===t)}function Mm(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=Si(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 qm(e,t){let n=new Set(gc[t]);return e.checkers.filter(i=>i.coversExtensions.some(o=>n.has(o)))}function Fm(e){try{return Sm("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",windowsHide:!0,timeout:1e4}),!0}catch{return!1}}import{statSync as bc}from"fs";import{basename as Bm,isAbsolute as Wm,join as qt,relative as _m}from"path";import{fileURLToPath as Vm}from"url";import{watch as Gm}from"chokidar";import Um from"ignore";var Rc=5e3,jn=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onFileChanged;onBulkChange;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;reindexInFlight=!1;lastReindexEnd=0;fileChangeTimer=null;pendingFileChanges=new Set;bulkChangePending=!1;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;observationEpoch=0;changeSequence=0;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=et(t.config),this.outputDb=t.outputDb??qt(nn(this.projectRoot,t.config),"index.db"),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onFileChanged=t.onFileChanged,this.onBulkChange=t.onBulkChange;let n=t.onError??(i=>console.error(i.message));this.onError=i=>{this.observationEpoch+=1,n(i)},this.clock=t.clock??Qm,Cc.set(this,sg(t.stopTimeoutMs??Rc,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??og(),this.subscriptionFactory=t.subscriptionFactory??Xm,this.budgetInspector=t.budgetInspector??Fa,kc.set(this,{gitReader:t.gitReader??vo,languages:Ec(t.languages??t.config.languages),stagedIndexEntries:null,gitSignalPaths:null,lastGitSignal:null}),this.gitignoreFilter=Ao(t.projectRoot),this.extraIgnore=Um(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,An(this).errors=[],this.sourcePollingFallbackStarted=!1,this.observationEpoch+=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.clearFileChangeWindow();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...An(this).closures],o=Km(this),r=this.clock.now()+o;return this.stopPromise=this.finishStop(t,i,n,r,o).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}observation(){return{epoch:this.observationEpoch,changeSequence:this.changeSequence}}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Sc(this.pendingTrigger,t),this.changedFiles+=1,this.changeSequence+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,o)=>this.isIgnoredWatchPath(i,o?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,o)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(o)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!rg(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.observationEpoch+=1,this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(o=>o!==t),zm(An(this),t,o=>this.onError(o));try{this.startSourceWatcher(!0)}catch(o){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(o)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let o=n?`${i}/`:i;return o===".git/"||o.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(o)||this.extraIgnore.ignores(o)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Bm(n).startsWith(Ma)||(n===".codebaseiq.json"&&$c(this,this.projectRoot),wc(this,n)&&(this.noteFileChange(n),this.scheduleReindex({kind:"watch-source",detail:n})))}noteFileChange(t){!this.onFileChanged&&!this.onBulkChange||(this.bulkChangePending||(this.pendingFileChanges.add(t),this.pendingFileChanges.size>Zm&&(this.pendingFileChanges.clear(),this.bulkChangePending=!0)),this.fileChangeTimer??=this.clock.setTimeout(()=>this.flushFileChangeWindow(),Ym))}flushFileChangeWindow(){if(this.fileChangeTimer=null,this.stopped)return;let t=[...this.pendingFileChanges],n=this.bulkChangePending;this.pendingFileChanges.clear(),this.bulkChangePending=!1;try{n?this.onBulkChange?.():this.onFileChanged?.(t)}catch{}}clearFileChangeWindow(){this.fileChangeTimer&&(this.clock.clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingFileChanges.clear(),this.bulkChangePending=!1}relativeWatchPath(t){let n=Wm(t)?t:qt(this.projectRoot,t);return _m(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=Sc(this.pendingTrigger,t),this.changedFiles++,this.changeSequence+=1,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.inspectBudget();if(t.state==="paused"){this.dirty=!0;let s=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:s,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,s-this.wallNow())));return}let n=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&n<this.watchConfig.cooldownMs){let s=this.watchConfig.cooldownMs-n;this.dirty=!0;let a=this.wallNow()+s;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},s);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.wallNow();this.setStatus({state:"indexing",startedAt:o});let r=this.reindexRunner.start(this.reindexRequest(i));this.activeOperation=r,r.completion.then(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(s,i)===!0}catch(c){this.onError(c instanceof Error?c:new Error(String(c)))}if(this.dirty&&!this.stopped){if(a){let l=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(l),this.setStatus({state:"idle"});return}let c=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:c,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=s instanceof Error?s:new Error(String(s));this.onReindexError(a,i),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===r&&(this.activeOperation=null)})}async finishStop(t,n,i,o,r){let s=[],a=t.map(async g=>{try{await g.close()}catch(p){s.push(`watch subscription close failed: ${String(p)}`)}});a.push(...n),i&&a.push((async()=>{try{let g=await i.cancel();g.state==="degraded"&&s.push(g.reason)}catch(g){s.push(`reindex cancellation failed: ${g instanceof Error?g.message:String(g)}`)}})());let c=a.length,l=a.map(g=>g.finally(()=>{c-=1})),u=await Hm(l,o,this.clock),m=An(this);return s.push(...m.errors),m.errors=[],u?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${r}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){if(this.lastGitState=this.readGitState(),!this.lastGitState)return;let t=We(this);t.gitSignalPaths=this.resolveGitSignalPaths(),t.lastGitSignal=this.gitActivitySignal(),t.stagedIndexEntries=xc(this.projectRoot,t.gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.()}resolveGitSignalPaths(){let t=We(this).gitReader,n=St(this.projectRoot,["rev-parse","--git-dir"],t),i=St(this.projectRoot,["rev-parse","--git-common-dir"],t);if(!n)return null;let o=en(this.projectRoot,n),r=i?en(this.projectRoot,i):o,s=this.lastGitState?.indexPath;return[qt(o,"HEAD"),qt(r,"packed-refs"),qt(r,"refs","heads"),...s?[s]:[]]}gitActivitySignal(){let t=We(this).gitSignalPaths;if(!t)return null;let n="";for(let i of t)try{let o=bc(i);n+=`${i}:${o.mtimeMs}:${o.size};`}catch{n+=`${i}:absent;`}return n}pollGitState(){let t=this.gitActivitySignal();if(t!==null){if(t===We(this).lastGitSignal)return;We(this).lastGitSignal=t}let n=this.lastGitState,i=this.readGitState();if(!n||!i||this.stopped){this.lastGitState=i;return}this.lastGitState=i;let o=n.head!==i.head,r=n.indexPath!==i.indexPath||n.indexMtimeMs!==i.indexMtimeMs||n.indexSize!==i.indexSize;if(!o&&!r)return;let s=We(this),a=s.stagedIndexEntries,c=xc(this.projectRoot,s.gitReader);s.stagedIndexEntries=c;let l=ag(this.projectRoot,s.gitReader,n,i,a,c,o,r),u=null;l!==null&&(l.includes(".codebaseiq.json")&&$c(this,this.projectRoot),u=l.filter(m=>wc(this,m)),u.length===0)||(o&&r?this.scheduleReindex({kind:"watch-git-state",detail:$i("HEAD and index changed",u)}):o?this.scheduleReindex({kind:"watch-git-head",detail:$i("HEAD changed",u)}):r&&this.scheduleReindex({kind:"watch-git-index",detail:$i(i.indexPath??"index changed",u)}))}readGitState(){let t=We(this).gitReader,n=St(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=en(this.projectRoot,n),o={head:St(this.projectRoot,["rev-parse","--verify","HEAD"],t),indexPath:i};try{let r=bc(i);o.indexMtimeMs=r.mtimeMs,o.indexSize=r.size}catch{o.indexMtimeMs=void 0,o.indexSize=void 0}return o}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Hm(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),o=Math.max(0,t-n.now()),r=null,s=new Promise(c=>{r=n.setTimeout(()=>c(!1),o)}),a=await Promise.race([i,s]);return a&&r&&n.clearTimeout(r),a}var yc=new WeakMap,Cc=new WeakMap,kc=new WeakMap;function An(e){let t=yc.get(e);if(t)return t;let n={closures:new Set,errors:[]};return yc.set(e,n),n}function Km(e){return Cc.get(e)??Rc}function We(e){let t=kc.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function zm(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(o=>{let r=`watch subscription close failed during polling fallback: ${String(o)}`;e.errors.push(r),n(new Error(r))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function Jm(e,t=So){let{projectRoot:n,config:i,languages:o,pnpmWorkspaces:r,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:l,trigger:u}=e,m=Ae(n),g=Object.keys(m).length>0?m:i,p=wt(n,g),h=g.indexer?.typescript,f=g.indexer?.clojure,b=t(process.pid);if(!b)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:Vm(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(g.languages??o)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(g.indexerConcurrency??l??""),SCIP_REINDEX_PNPM_WORKSPACES:h?.pnpmWorkspaces??r?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:h?.projectMode??s,projects:h?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:u.kind,SCIP_REINDEX_TRIGGER_DETAIL:u.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(b)}}}var Qm={now:To,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Xm=(e,t)=>Gm(e,t),Ym=120,Zm=200,eg=15*6e4,tg=1e3,ng=64*1024;function ig(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function vc(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
|
|
12
|
-
`)}`}function
|
|
13
|
-
`,o=Pc(e)?pt(e,"health dossier JSON"):null;if(o&&Rg(o,i)){n.unchanged.push(e);return}jc(e,i),n.written.push(e)}function Rg(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function Cg(e,t){return xi(e,t)}function xi(e,t){return typeof e=="string"?kg(e,t):Array.isArray(e)?e.map(n=>xi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,xi(i,t)])):e}function kg(e,t){if(e===t)return".";if(!pg(e))return e;let n=Tc(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Tc(ug(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as Eg}from"child_process";import{dirname as Dc,join as Tg,resolve as Lg}from"path";import{fileURLToPath as Pg}from"url";var In={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 Ag(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let o of In[i]?.packages??[])n.add(o);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function Ci(e){return[...new Set(e.filter(t=>In[t]!==void 0))].sort()}function Oc(e,t={}){let n=t.runtime??Ng,i=t.packageRoot??jg(),o=Ci(e),r=o.filter(m=>n.probe(In[m].ast)),s=o.filter(m=>!r.includes(m));if(s.length===0)return{supportedLanguages:o,availableBefore:r,installed:[],availableAfter:r,unavailable:[],attempted:!1};let a=Ig(i),c=Ag(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let u=o.filter(m=>n.probe(In[m].ast));return{supportedLanguages:o,availableBefore:r,installed:l.ok?c:[],availableAfter:u,unavailable:o.filter(m=>!u.includes(m)),attempted:!0,...l.error?{error:l.error}:{}}}function jg(){let e=Dc(Pg(import.meta.url));for(;;){let t=Tg(e,"package.json");try{if(JSON.parse(pt(t,"AST parser package manifest")).name==="codebaseiq")return e}catch{}let n=Dc(e);if(n===e)throw new Error("Unable to locate the installed codebaseiq package root.");e=n}}function Ig(e){return JSON.parse(pt(Lg(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var Ng={probe:e=>cn(e)==="ast",resetProbe:dr,install:(e,t)=>{let n=Eg(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",windowsHide:!0,maxBuffer:10485760});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function Bc(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 Wc(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:"codebaseiq 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:"codebaseiq 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:"codebaseiq 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:"codebaseiq setup --install-missing"}),{actions:t}}async function _c(e={}){let t=Bg(e),n=Wg(e),i=[],o=ge(),{projectRoot:r,paths:s,dbPath:a}=o,c=n?.enabled?!0:e.automaticRefresh??o.config.watch?.enabled??!0,u=st(o.config,{projectRoot:r}).filter(q=>q.level==="error"),m=null,g=null;if(u.length===0&&!o.config.collaborationDomainId)try{m=Fo(r,o.config)}catch(q){g=Je(q)}let p=m?.config??o.config,h=e.languages?Bo(r,p,e.languages):null,f=h?.config??p,b=st(f,{projectRoot:r}),v=b.filter(q=>q.level==="error"),S=null,L=null;if(v.length===0&&f.watch?.enabled!==c)try{S=Wo(r,f,c)}catch(q){L=Je(q)}let W=Dt();B(i,{id:"collaboration-domain-config",label:"Collaboration domain",status:g!==null?"failed":u.length>0?"skipped":"ok",message:g??(u.length>0?"Skipped because the existing project config has validation errors.":m?.changed?"Generated the committed identity shared by merge-intended branches, clones, and forks.":"The committed collaboration-domain identity is already present."),...m?{details:[m.configPath]}:{}}),B(i,{id:"automatic-indexing-config",label:"Automatic indexing config",status:L!==null?"failed":v.length>0||!c?"skipped":"ok",message:L??(v.length>0?"Skipped because the existing project config has validation errors.":c?S?.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."),...S?{details:[S.configPath]}:{}});let H=v.length>0,j=S?.config??f,_=t?Hg({plan:t,projectRoot:r,config:j,configHasErrors:H,steps:i}):null,x=n?Kg({plan:n,projectRoot:r,cacheDir:s.cacheDir,config:_?.config??j,configHasErrors:H,steps:i}):null,M=x?.config??_?.config??j,J=zg({projectRoot:r,install:e.sentinel!==!1&&M.sentinel?.enabled===!0,remove:e.sentinel===!1,steps:i});B(i,{id:"scip-cli",label:"scip CLI",status:W?"ok":"warn",message:W?"scip CLI is available.":"scip CLI is not available; installation requires explicit --install-missing consent."});let O=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Pn({quiet:!0});B(i,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":O.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${O.installed.length} installed, ${O.alreadyLinked.length} already linked, ${O.pruned.length} pruned, ${O.skipped.length} skipped.`,details:[...O.pruned.map(q=>`Pruned ${q}`),...O.skipped.map(q=>`Skipped ${q}`)]});let Q=M===f?b:st(M,{projectRoot:r}),Xt=Q.filter(q=>q.level==="error");B(i,{id:"config",label:"Project config",status:Xt.length>0?"failed":Q.length>0?"warn":"ok",message:Q.length===0?"Config OK.":`${Q.length} diagnostic(s), ${Xt.length} error(s).`,details:Q.map(q=>`${q.level.toUpperCase()} ${q.path}: ${q.message}`)});let Ye=Be(r,M);B(i,{id:"readiness",label:"Indexer readiness",status:Ye.languages.length===0?"failed":Ye.indexers.some(q=>!q.runnable)?"warn":"ok",message:Ye.languages.length===0?"No supported project languages detected.":`Detected languages: ${Ye.languages.join(", ")}`,details:Ye.indexers.map(q=>`${q.runnable?"OK":q.installed?"WARN":"MISSING"} ${q.language}: ${q.binaryLabel}${q.note?` - ${q.note}`:""}`)});let Ce=e.installAstParsers!==!0?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Oc(Ye.languages);B(i,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers!==!0?"skipped":Ce.unavailable.length>0?"warn":"ok",message:e.installAstParsers!==!0?"Skipped because installing missing parser packages requires explicit consent.":Ce.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${Ce.availableAfter.length}/${Ce.supportedLanguages.length} selected language parser(s) available${Ce.installed.length>0?`; installed ${Ce.installed.join(", ")}`:""}.`,details:[...Ce.unavailable.length>0?[`Unavailable: ${Ce.unavailable.join(", ")}`]:[],...Ce.error?[Ce.error]:[]]});let uo=e.installIndexers===!0,po=uo?ah(r,Ye,i):[];uo||B(i,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent."});let mo=Be(r,M),go=await Jg({projectRoot:r,paths:s,config:M,readiness:mo,configHasErrors:Xt.length>0,steps:i,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),Qn=go.reindexResult,Rp=go.freshness,ho=et(M),fo=Qg({projectRoot:r,cacheDir:s.cacheDir,watchConfig:ho,readiness:mo,configHasErrors:Xt.length>0,reindexResult:Qn,postReindexFreshness:Rp,steps:i}),Ze=Be(r,M),Yt=ht(Ze),bo=ct(r,M,s);B(i,{id:"capabilities",label:"Capability matrix",status:mh(Yt),message:gh(Yt)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let yo=e.runHealth===!1?dh(i):await lh(s.dbPath,i),De=Ze.languages.includes("rust")?pn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;B(i,{id:"rust-semantic-session",label:"Rust semantic session",status:De===null?"skipped":De.valid?"ok":"failed",message:De===null?"Skipped because Rust was not detected.":`${De.transport}/${De.state} selected from ${De.source}; ${De.fallback} fallback; opt out with ${De.optOut}.`});let Oe=null;try{e.noAgentGuidance?B(i,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Oe=fn(r),B(i,{id:"agent-guidance",label:"Project agent guidance",status:Oe.skipped.length>0?"warn":"ok",message:`${Oe.written.length} written, ${Oe.unchanged.length} already wired, ${Oe.skipped.length} skipped.`,details:Oe.skipped.map(q=>`Skipped ${q.target}: ${q.reason}`)}))}catch(q){B(i,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Je(q)})}let Zt=Xg({reindexResult:Qn,readiness:Ze,capabilities:Yt,freshness:bo,health:yo,agentResult:Oe,watchConfig:ho,watchService:fo,rustSemanticSession:De,steps:i});B(i,{id:"smoke-tests",label:"Setup smoke tests",status:Yg(Zt),message:Zg(Zt),details:Zt.map(q=>`${q.command}: ${q.status} - ${q.evidence}`)});let it=_?.write??null,Xn=x?.configWrite??null,Yn=x?.settingsWrite??null,Cp={repository:[...h?.changed?[h.configPath]:[],...S?.changed?[S.configPath]:[],...it?.changed&&it.scope==="project"?[it.path]:[],...Xn?.changed?[Xn.configPath]:[],...Oe?.written??[]],checkout:[...it?.changed&&it.scope==="local"?[it.path]:[],...J?.files??[]],user:[...Yn?.changed?[Yn.path]:[],...J?.binaryPath?[J.binaryPath]:[],...O.installed,...Ce.installed,...po.filter(q=>q.attempted).map(q=>`${q.binaryLabel} installer`)]},Ge={projectRoot:r,dbPath:a,configuredDbPath:s.dbPath,scipCliInstalled:W,languages:Ze.languages,steps:i,skills:O,astParsers:Ce,initialReadiness:Ye,indexerRemediation:po,readiness:Ze,capabilities:Yt,freshness:bo,reindex:Qn,automaticRefreshConfig:S,watchService:fo,rustSemanticSession:De,health:yo,smokeTests:Zt,healthDossier:null,setupAgent:Oe,builderConfig:it,sentinelConfig:Xn,sentinelSettings:Yn,sentinelRequested:M.sentinel?.enabled===!0,sentinelHooks:J,changeScopes:Cp,filesWritten:Oe?.written??[],verdict:Ei(i,Ze)};if(e.runHealth===!1)return B(i,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ge.verdict=Ei(i,Ze),Ge;let Me=Nc(Ge,{dossierDir:e.dossierDir});return Ge.healthDossier=Me,Ge.changeScopes.repository.push(...Me.written),Ge.filesWritten=[...Ge.filesWritten,...Me.written],B(i,{id:"health-dossier",label:"Health dossier",status:Me.status==="failed"?"failed":"ok",message:Me.status==="failed"?Me.error:`${Me.written.length} written, ${Me.unchanged.length} unchanged.`,details:[Me.markdownPath,Me.jsonPath]}),Ge.verdict=Ei(i,Ze),Ge}var Og=["local","project"],Li=["claude","codex"],Mg={claude:jo,codex:Io},qg=/^([A-Za-z0-9_.-]{1,64})=(https?:\/\/\S+)$/,Fg=/^https?:\/\/[^/?#]*@|[?#]/;function Bg(e){let t=e.embeddingsEndpoints??[];if(e.builderMode===void 0&&t.length===0&&e.embeddingsModel===void 0&&e.agentCommand===void 0&&e.builderScope===void 0)return null;let n=e.builderMode===void 0?void 0:Ft(xt,e.builderMode,"--builder-mode"),i=e.builderModeIfUnset===void 0?void 0:Ft(xt,e.builderModeIfUnset,"--builder-mode"),o=e.builderScope===void 0?"local":Ft(Og,e.builderScope,"--builder-scope"),r=e.agentCommand===void 0?void 0:Ft(Li,e.agentCommand,"--agent-command");if(t.length>0&&!e.embeddingsModel)throw new Error("--embeddings-endpoint requires --embeddings-model.");if(t.length===0&&e.embeddingsModel!==void 0)throw new Error("--embeddings-model requires --embeddings-endpoint.");let s=t.map(c=>Vg(c,e.embeddingsModel??"")),a=new Set;for(let{name:c}of s){if(a.has(c))throw new Error(`--embeddings-endpoint names must be unique; "${c}" repeats.`);a.add(c)}if(o==="project"&&r!==void 0)throw new Error("--agent-command is a per-developer setting; use --builder-scope local.");if(n===void 0&&s.length===0&&r===void 0)throw new Error("--builder-scope needs --builder-mode, --embeddings-endpoint, or --agent-command.");return{scope:o,...n?{mode:n}:{},...i?{defaultMode:i}:{},endpoints:s,...r?{agentCommand:r}:{}}}function Wg(e){let t=_g(e.sentinelLive);if(t.length>0&&e.sentinel===!1)throw new Error("--sentinel-live cannot be combined with --no-sentinel.");let n=e.sentinel??(t.length>0?!0:void 0);return n===void 0?null:{enabled:n,liveFamilies:t}}function _g(e){if(e===void 0||e===!1)return[];if(e===!0)return[...ii];let t=e.split(",").map(n=>Ft(ii,n.trim(),"--sentinel-live"));return[...new Set(t)]}function Ft(e,t,n){let i=e.find(o=>o===t);if(i===void 0)throw new Error(`${n} must be one of ${e.join(", ")}; got "${t}".`);return i}function Vg(e,t){let n=qg.exec(e);if(!n)throw new Error(`--embeddings-endpoint must look like <name>=<http(s) url>; got "${e}".`);let i=n[1],o=n[2];if(!Gg(o))throw new Error(`--embeddings-endpoint "${i}" must be a bare http(s) URL without credentials, query, or fragment; keep tokens in the apiKeyEnv variable.`);return{name:i,baseUrl:o,model:t}}function Gg(e){try{let t=new URL(e);return!t.username&&!t.password&&!Fg.test(e)}catch{return!1}}function Mc(e,t,n){let i={...e};if(t.mode)i.mode=t.mode;else if(e?.mode===void 0&&n?.mode===void 0){let o=t.defaultMode??(t.endpoints.length>0?"auto":void 0);o&&(i.mode=o)}if(t.endpoints.length>0&&(i.embeddings={...e?.embeddings,endpoints:qc(e?.embeddings?.endpoints,t.endpoints)}),t.agentCommand){let o={name:t.agentCommand,argv:[...Mg[t.agentCommand]]};i.agent={...e?.agent,commands:qc(e?.agent?.commands,[o])}}return{builder:i,warnings:Ug(i,t,n)}}function Ug(e,t,n){if(t.endpoints.length===0)return[];let i=[];(e.mode??n?.mode??"agent")==="agent"&&i.push("Builder mode is agent, so the new embeddings endpoint(s) are not tried; use --builder-mode auto.");let o=e.chain??n?.chain,r=t.endpoints.map(s=>`embeddings:${s.name}`).filter(s=>!o?.includes(s));return o&&r.length>0&&i.push(`The provider chain [${o.join(", ")}] does not include ${r.join(", ")}; add it to builder.chain.`),i}function qc(e,t){let n=[...e??[]];for(let i of t){let o=n.findIndex(r=>r.name===i.name);o===-1?n.push(i):n[o]={...n[o],...i}}return n}function Fc(e){let t=Do(e).filter(n=>n.level==="error");if(t.length>0)throw new Error(`Invalid builder settings: ${t.map(n=>`${n.path}: ${n.message}`).join("; ")}`);return e}function Hg(e){let{plan:t,projectRoot:n,config:i,steps:o}=e,r={id:"builder-config",label:"Symbol builder config"};try{if(t.scope==="project"){if(e.configHasErrors)return B(o,{...r,status:"skipped",message:"Skipped because the existing project config has validation errors."}),{config:i,write:null};let m=Mc(i.builder,t),g=_o(n,i,Fc(m.builder));return B(o,{...r,status:m.warnings.length>0?"warn":"ok",message:[g.changed?"Wrote builder defaults to the project config; credentials and agent commands stay per-developer.":"Builder defaults in the project config are already current.",...m.warnings].join(" "),details:[g.configPath]}),{config:g.config,write:{scope:"project",path:g.configPath,changed:g.changed}}}let s=Go(n),a=s.diagnostics.filter(m=>m.level==="error");if(a.length>0)throw new Error(`The per-developer builder config has errors and was left untouched: ${a.map(m=>m.message).join("; ")}`);let c=Mc(s.config,t,i.builder),l=Uo(n,Fc(c.builder)),u={written:[],unchanged:[],skipped:[]};return pa(n,u),B(o,{...r,status:u.skipped.length>0||c.warnings.length>0?"warn":"ok",message:[l.changed?`Wrote per-developer builder settings${u.skipped.length>0?"":"; the file is excluded from Git"}.`:"Per-developer builder settings are already current.",...c.warnings].join(" "),details:[l.path,...u.skipped.map(m=>`Skipped ${m.target}: ${m.reason}`)]}),{config:i,write:{scope:"local",...l}}}catch(s){return B(o,{...r,status:"failed",message:Je(s)}),{config:i,write:null}}}function Kg(e){let{plan:t,projectRoot:n,cacheDir:i,config:o,steps:r}=e,s={id:"sentinel-config",label:"Trailing sentinel config"};if(e.configHasErrors)return B(r,{...s,status:"skipped",message:"Skipped because the existing project config has validation errors."}),{config:o,configWrite:null,settingsWrite:null};let a=null,c=null;try{a=Vo(n,o,t.enabled),t.liveFamilies.length>0&&(c=Ho(i,t.liveFamilies)),B(r,{...s,status:"ok",message:t.enabled?`Enabled the trailing sentinel for this project${t.liveFamilies.length>0?`; per-user delivery is live for ${t.liveFamilies.join(", ")}`:""}.`:"Disabled the trailing sentinel for this project.",details:[a.configPath,...c?[c.path]:[]]})}catch(l){B(r,{...s,status:"failed",message:Je(l)})}return{config:a?.config??o,configWrite:a,settingsWrite:c}}function zg(e){let{projectRoot:t,steps:n}=e,i={id:"sentinel-hooks",label:"Trailing sentinel hooks"};try{if(e.install){let o=ma(t),s=[...o.written,...o.unchanged].includes(".codex/hooks.json")?yn(t)?.hooks.filter(c=>!c.trusted).length??0:0,a=o.binary.state==="installed"&&o.binary.changed?o.binary.script:null;return B(n,{...i,status:o.skipped.length>0?"warn":"ok",message:o.binary.state==="skipped"?`Skipped: ${o.binary.reason}.`:[`${o.written.length} written, ${o.unchanged.length} already current.`,s>0?`Open Codex once in this project and approve the ${s} sentinel hook(s); Codex does not run hooks you have not approved.`:"",...o.notices].filter(Boolean).join(" "),details:[...o.written,...a?[a]:[],...o.skipped.map(c=>`Skipped ${c.target}: ${c.reason}`)]}),{action:"install",files:o.written,unchanged:o.unchanged,skipped:o.skipped,binaryPath:a,codexAwaitingApproval:s}}if(e.remove){let o=ga(t);return B(n,{...i,status:o.skipped.length>0?"warn":"ok",message:o.removed.length>0?`Removed the sentinel hooks from ${o.removed.length} file(s).`:"No sentinel hooks were installed.",details:[...o.removed,...o.skipped.map(r=>`Skipped ${r.target}: ${r.reason}`)]}),{action:"remove",files:o.removed,unchanged:o.unchanged,skipped:o.skipped,binaryPath:null,codexAwaitingApproval:0}}}catch(o){B(n,{...i,status:"failed",message:Je(o)})}return null}async function Jg(e){if(e.readiness.languages.length===0||e.configHasErrors)return B(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,i=null;try{let o=0,r=!1;for(let s=0;s<2;s+=1){if(n=await _a({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,installMissing:e.installMissing,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"codebaseiq setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),o+=n.durationMs,r||=!n.reused,i=ct(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&i.state==="stale"){t.push(`Index inputs changed during the first build (${i.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");B(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${r?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(o/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(o){B(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Je(o),details:t})}return{reindexResult:n,freshness:i}}function Qg(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return B(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=$n({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ue,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 B(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 B(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Je(n)}),null}}function Vc(e){if(console.log("codebaseiq setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ri(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),ki("Repository records (commit)",e.changeScopes.repository),ki("Checkout preferences (do not commit)",e.changeScopes.checkout),ki("User environment",e.changeScopes.user),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function ki(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Xg(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"codebaseiq reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"codebaseiq status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"codebaseiq config-validate",status:eh(e.steps),evidence:th(e.steps)},{id:"capabilities",command:"codebaseiq capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"codebaseiq capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?nh(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"codebaseiq health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"codebaseiq diff-impact --json",status:ih(e.readiness,e.freshness),evidence:oh(e.readiness,e.freshness)},{id:"cleanup-verification",command:"codebaseiq cleanup-plan --verify",status:rh(e.capabilities),evidence:sh(e.capabilities)},{id:"watch-refresh",command:"codebaseiq status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"codebaseiq status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"codebaseiq setup-agent",status:e.agentResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:n?.message??"Project agent guidance was not written."}]}function Yg(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Zg(e){let t=e.filter(o=>o.status==="pass").length,n=e.filter(o=>o.status==="unavailable").length,i=e.filter(o=>o.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function eh(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function th(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function nh(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 ih(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function oh(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 rh(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function sh(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(o=>o.cleanupVerification.status==="available").length,n=e.matrix.filter(o=>o.cleanupVerification.status==="partial").length,i=e.matrix.filter(o=>o.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function ah(e,t,n){let i=[];if(t.languages.length===0)return B(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=xn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Ba(a,g=>c.push(g)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let m=ch(un(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:m,messages:c,recovery:m.runnable?void 0:m.note??m.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return B(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let o=i.filter(s=>!s.after.runnable),r=i.filter(s=>s.attempted);return B(n,{id:"indexer-remediation",label:"Indexer remediation",status:o.length>0?"warn":"ok",message:o.length===0?`${r.length} install attempt(s); all detected indexers are runnable.`:`${r.length} install attempt(s); ${o.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function ch(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function lh(e,t){if(!Dg(e)){let n="Skipped because no SQLite index database exists yet.";return B(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Ti(n)}try{let n=await ia({full:!0,json:!0});return B(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),uh(n)}catch(n){let i=Je(n);return B(t,{id:"health",label:"Health audit",status:"failed",message:i}),Ti(i)}}function dh(e){let t="Skipped by setup choice; run `codebaseiq health --full` when wanted.";return B(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Ti(t)}function uh(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(ph),warnings:e.warnings??[]}}function ph(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 Ti(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ei(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function mh(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 gh(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 B(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Je(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as wh}from"readline";var hh=[{baseUrl:"http://127.0.0.1:8080/v1",listUrl:"http://127.0.0.1:8080/v1/models",server:"llama.cpp",format:"openai",confirmedBy:"llamacpp"},{baseUrl:"http://127.0.0.1:1234/v1",listUrl:"http://127.0.0.1:1234/v1/models",server:"lm-studio",format:"openai"},{baseUrl:"http://127.0.0.1:11434/v1",listUrl:"http://127.0.0.1:11434/api/tags",server:"ollama",format:"ollama"}],fh=300,bh=1024*1024,yh=/embed|nomic|bge|minilm|e5/i;async function Gc(e={}){let t=e.fetchImpl??fetch,n=e.timeoutMs??fh;return(await Promise.all(hh.map(o=>vh(o,t,n)))).filter(o=>o!==void 0)}async function vh(e,t,n){try{let i=await t(e.listUrl,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(n)});if(!i.ok)return;let o=await $h(i);if(o===void 0)return;let r=Sh(JSON.parse(o),e.format);return r?{baseUrl:e.baseUrl,server:e.confirmedBy===void 0||r.owners.includes(e.confirmedBy)?e.server:"unknown",models:r.models,embeddingModels:r.models.filter(s=>yh.test(s))}:void 0}catch{return}}function Sh(e,t){if(typeof e!="object"||e===null)return;let n=e[t==="ollama"?"models":"data"];if(!Array.isArray(n))return;let i=[],o=[];for(let r of n){if(typeof r!="object"||r===null)continue;let s=r,a=t==="ollama"?s.name:s.id;typeof a=="string"&&a!==""&&i.push(a),typeof s.owned_by=="string"&&o.push(s.owned_by)}return{models:i,owners:o}}async function $h(e){let t=e.body?.getReader();if(!t)return;let n=[],i=0;for(;;){let{done:o,value:r}=await t.read();if(o)return Buffer.concat(n).toString("utf8");if(i+=r.byteLength,i>bh){await t.cancel();return}n.push(r)}}function xh(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Rh(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let i=n[e.cursor]?.id;if(!i)return e;let o=new Set(e.selected);return o.has(i)?o.delete(i):o.add(i),{...e,selected:o}}async function Uc(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=xh(e);wh(t);let o=t.isRaw;t.setRawMode(!0),t.resume();let r=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`codebaseiq setup
|
|
2
|
+
import{b as Wa}from"./chunk-Q3ZCQY2Y.js";import{a as Ba,c as wn}from"./chunk-362QOSFD.js";import{a as Va}from"./chunk-JFIA2JI3.js";import{a as ra}from"./chunk-CVHOQONG.js";import{a as ma,b as ga,c as ha,e as va}from"./chunk-T5X7DK6C.js";import{a as q,b as x,c as Te,d as ne,e as Le,f as d,g as li,h as Sa,i as C,j as R,k as qe,l as $a,m as Q,n as wa,o as Ie,p as k,q as le,r as gt,s as It,t as di,u as lt,v as de,w as ue,x as $e,y as Nt,z as Pa}from"./chunk-USOAJHY7.js";import{A as E,B as D,C as La,D as P,E as Sn,F as re,a as ce,b as z,i as X,j as te,k as xa,l as Ra,m as Ca,n as ze,o as ka,p as be,q as Ea,r as Se,s as Ta,t as N,v as G,w as $,x as K,y,z as A}from"./chunk-JLZLLLW5.js";import{a as ir,e as tt,f as Rt,h as or,i as ri}from"./chunk-AQI4N64O.js";import{a as Aa,b as ja,c as Ia,d as $n,e as Na,f as Da,g as Oa,h as Ma,i as qa,j as Fa,k as _a}from"./chunk-Q23IMHXS.js";import{a as xn,b as Rn}from"./chunk-5DSL3NT2.js";import{a as mn,b as sa,c as gn,d as aa,e as ca,f as la,h as da,i as ua,j as pa,k as hn,l as fn,m as bn,n as fa,r as yn,s as vn,t as ba,v as ya}from"./chunk-5IC2WZAL.js";import{$ as Gr,$a as Gs,A as wr,Aa as bs,B as xr,Ba as ys,C as Rr,Ca as vs,D as Cr,Da as Ss,Ea as $s,F as Er,Fa as ws,G as ai,Ga as xs,H as Tr,Ha as Rs,I as Lr,Ia as Cs,J as Pr,Ja as ks,Ka as Es,L as Ar,La as Ts,M as jr,Ma as Ls,N as Ir,Na as Ps,O as Nr,Oa as As,P as Dr,Pa as js,Q as Or,Qa as Is,R as Mr,Ra as Ns,S as qr,Sa as Ds,T as Fr,Ta as Os,U as Br,Ua as Ms,V as Wr,Va as qs,W as _r,Wa as Fs,Xa as Bs,Y as Vr,Ya as Ws,Z as pn,Za as _s,_ as Pt,_a as Vs,a as I,aa as Ur,ab as Us,b as fe,ba as Hr,bb as Hs,c as V,ca as Kr,cb as Ks,d as on,da as zr,db as zs,e as T,ea as Jr,eb as Js,f as kt,fa as Qr,fb as Ys,g as ur,ga as Xr,gb as Zs,h as pr,ha as Yr,hb as ci,i as mr,ia as Zr,ib as At,j as hr,ja as es,jb as jt,k as dn,ka as ts,kb as je,l as fr,la as ns,m as Et,ma as is,mb as ea,n as br,na as os,nb as ta,o as yr,oa as rs,ob as na,pa as ss,pb as ia,qa as as,qb as oa,ra as cs,sa as ls,t as vr,ta as ds,u as Tt,ua as us,va as ps,wa as ms,xa as gs,y as Sr,ya as hs,z as $r,za as fs}from"./chunk-C7QWUBR2.js";import{a as Lt,b as un,d as kr,f as Ke}from"./chunk-B2OB55RR.js";import{b as nr}from"./chunk-XZEE23VG.js";import{A as et,B as Do,C as Oo,D as Mo,E as qo,F as Fo,G as Bo,I as Wo,J as _o,K as mt,L as Vo,M as ct,S as Ho,T as Ko,U as zo,V as Jo,W as Qo,X as Xo,Y as Yo,Z as Zo,_ as pe,a as xt,b as Zn,ba as ge,c as ei,ca as ii,g as Lo,ga as er,h as Po,ha as tr,i as Ao,j as jo,ka as Ee,ma as he,na as oi,o as ti,u as Io,v as tn,w as No,x as ni,y as Ae,z as st}from"./chunk-7UCDGXRW.js";import"./chunk-EN4AHLL3.js";import{A as sr,G as sn,Ga as dr,H as ar,Ha as cn,I as si,Pb as Qs,Qb as Xs,_ as cr,bb as He,eb as gr,ga as oe,ha as lr,k as rr,nb as ln,p as rn,ta as an,z as Ct}from"./chunk-FTTV7IRX.js";import{c as yo}from"./chunk-D62CTZX6.js";import{$ as To,Aa as Uo,Ba as ie,Ca as me,E as xo,F as Ro,J as Co,T as ko,U as Eo,a as vo,b as Yn,j as rt,k as So,l as Ue,n as en,o as $o,pa as at,r as wt,va as nn,z as wo,za as Go}from"./chunk-5T44HG5Y.js";import{A as Xn,b as fo,g as St,h as Yt,k as Zt,l as ot,q as ke,r as pt,y as bo,z as $t}from"./chunk-DUKHVPU5.js";import{existsSync as Cn,mkdirSync as xp,symlinkSync as Rp,readlinkSync as ui,unlinkSync as pi,readdirSync as Ga}from"fs";import{join as Fe,dirname as Dt,resolve as nt,relative as Cp,isAbsolute as kp}from"path";import{homedir as kn,platform as Ep}from"os";import{fileURLToPath as Ua}from"url";var Tp=Ep()==="win32",En=["codebaseiq","codebaseiq-explore","concrete-plan"];function Tn(e={}){let t=e.quiet?()=>{}:console.log,n=Ua(import.meta.url),i=nt(Dt(n),"..","skills"),o=[Fe(kn(),".claude","skills"),Fe(kn(),".codex","skills"),Fe(kn(),".agents","skills")],r={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of o){let a=Dt(s);if(!Cn(a))continue;xp(s,{recursive:!0});let c=za(s);Lp(s,i,c,r,t);for(let l of En){let u=Fe(i,l),m=Fe(s,l);if(!Cn(u)){r.skipped.push(`${c}/${l}`);continue}if(Cn(m)){try{let g=ui(m);if(nt(g)===nt(u)){r.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{r.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}pi(m)}Rp(u,m,Tp?"junction":"dir"),r.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return r}function Lp(e,t,n,i,o){let r=new Set(En);for(let s of Ga(e)){if(r.has(s))continue;let a=Fe(e,s),c;try{c=nt(Dt(a),ui(a))}catch{continue}Ka(c,t)&&(pi(a),i.pruned.push(`${n}/${s}`),o(` prune: ${s} \u2192 ${n} (removed stale codebaseiq skill link)`))}}function Ha(e={}){let t=Ua(import.meta.url),n=nt(Dt(t),"..","skills"),i=e.homeDir??kn(),o=[Fe(i,".claude","skills"),Fe(i,".codex","skills"),Fe(i,".agents","skills")],r={removed:[],left:[],skipped:[]};for(let s of o){if(!Cn(s))continue;let a=za(s);for(let c of Ga(s)){let l=Fe(s,c),u;try{let m=ui(l);u=nt(Dt(l),m)}catch{r.left.push(`${a}/${c} (not a symlink)`);continue}if(!Ka(u,n)){r.left.push(`${a}/${c} (symlink outside codebaseiq package)`);continue}if(r.removed.push(`${a}/${c}`),!e.dryRun)try{pi(l)}catch(m){r.skipped.push(`${a}/${c} (${m instanceof Error?m.message:String(m)})`)}}}return r}function Ka(e,t){let n=Cp(nt(t),nt(e));return n===""||!n.startsWith("..")&&!kp(n)}function za(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as Wt}from"fs";import{dirname as Pi,join as Li}from"path";import{execFileSync as bm}from"child_process";import{createRequire as Pp}from"module";var Ap=Pp(import.meta.url);function Ja(e,t=[]){let n=jp(),i=fr(e,t),o=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i,reason:"ts-morph is not installed"}}function jp(){try{return Ap.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Ot,spawnSync as Ip}from"child_process";import{existsSync as Ne,mkdtempSync as Np,readdirSync as Dp,rmSync as Qa,symlinkSync as Op,writeFileSync as Mp}from"fs";import{tmpdir as qp}from"os";import{join as ye}from"path";var Fp=3e5,Bp=12,ec=3e4,gi=1024*1024,Wp={readWorkingTreeStatus(e){return Ot("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:ec,maxBuffer:gi,windowsHide:!0,killSignal:"SIGKILL"})}};function tc(e,t,n={}){let i=Xp(e,n.workingTreeRuntime),o=i.state==="known"?i.files:[],r=Qp(t,i),s=hi(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:[]};let a=Up(t,s),c=n.timeoutMs??Fp,l=[],u=new Map,m;try{m=ic(e,"scip-cleanup-verify-")}catch(g){return{checkers:s.map(p=>p.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,unavailableReason:em(g),batches:[]}}try{Zp(e,m.root);for(let g of s)u.set(g.label,Ya(g,m.root,c).rawErrors);for(let g of t.batches){oc(m.root,g);let p=null;for(let h of s){let f=Ya(h,m.root,c),b=_p(f,u.get(h.label)??[],f.rawErrors);if(b.status==="failed"){let v=b.errors.length>0?b.errors:f.outputTail;p={depth:g.depth,status:"failed",reason:`${h.label}: ${b.reason}`,errors:v.slice(0,Bp)};break}}if(!p)l.push({depth:g.depth,status:"verified"});else{l.push(p);break}}}finally{m.dispose()}return{checkers:s.map(g=>g.label),uncoveredFiles:a,baselineErrors:[...u.values()].reduce((g,p)=>g+p.length,0),workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:l}}function _p(e,t,n){let i=Vp(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 Vp(e,t){let n=Gp(e),i=new Map,o=[];for(let r of t){let s=nc(r),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&o.push(r)}return o}function Gp(e){let t=new Map;for(let n of e){let i=nc(n);t.set(i,(t.get(i)??0)+1)}return t}function Up(e,t){let n=new Set(t.flatMap(o=>o.coversExtensions));return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>{let r=o.slice(o.lastIndexOf("."));return!n.has(r)}).sort()}function nc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Xa=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Hp=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function hi(e){let t=[];if(Ne(ye(e,"tsconfig.json"))){let n=ye(e,"node_modules",".bin","tsc");t.push(Ne(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Xa,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Xa,strength:"reference-aware"})}if(Ne(ye(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>Ne(ye(e,n)))){let n=Kp();n&&t.push(n)}if(Hp.some(n=>Ne(ye(e,n)))){let n=zp(e);n&&t.push(n)}for(let n of Jp(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:ye(e,n,"..","target")}});return t}function Kp(){return He("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"}:He("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function zp(e){let t=ye(e,"node_modules",".bin","clj-kondo");return Ne(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...rn],strength:"reference-aware"}:He("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...rn],strength:"reference-aware"}:He("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...rn],strength:"reference-aware"}:null}function Jp(e){let t=[];if(Ne(ye(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Dp(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||Ne(ye(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function Qp(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>n.has(o)).sort()}function Xp(e,t=Wp){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:Yp(n)}}}function Yp(e){let t=e&&typeof e=="object"?e:{};if(t.code==="ETIMEDOUT"||t.killed===!0)return`git status timed out after ${ec}ms`;if(t.code==="ENOBUFS"||typeof t.message=="string"&&/maxBuffer|stdout.*buffer/i.test(t.message))return`git status exceeded its ${gi}-byte output limit`;if(typeof t.signal=="string"&&t.signal!=="")return`git status was terminated by ${t.signal}`;if(typeof t.status=="number")return`git status exited with status ${t.status}`;let n=typeof t.message=="string"?t.message.replaceAll(/\s+/g," ").trim().slice(0,240):String(e).replaceAll(/\s+/g," ").trim().slice(0,240);return n===""?"git status failed for an unknown reason":`git status failed: ${n}`}function Zp(e,t){for(let n of["node_modules"]){let i=ye(e,n),o=ye(t,n);if(Ne(i)&&!Ne(o))try{Op(i,o,"junction")}catch{}}}function ic(e,t){let n=Np(ye(qp(),t)),i=ye(n,"checkout");try{let o=Ot("git",["-C",e,"rev-parse","--verify","HEAD"],{encoding:"utf-8",timeout:3e4,maxBuffer:gi,killSignal:"SIGKILL"}).trim();return Ot("git",["clone","--quiet","--no-checkout","--shared","--",e,i],{stdio:"ignore",windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"}),Ot("git",["-C",i,"checkout","--quiet","--detach","--force",o],{stdio:"ignore",windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"}),{root:i,dispose(){Qa(n,{recursive:!0,force:!0})}}}catch(o){throw Qa(n,{recursive:!0,force:!0}),o}}function em(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 oc(e,t){let n=new Map;for(let i of t.entries){let o=n.get(i.file)??[];o.push({start:i.startLine,end:i.endLine}),n.set(i.file,o)}for(let[i,o]of n){let r=ye(e,i);if(!Ne(r))continue;let s=ke(r,{maxBytes:ot,inputKind:"cleanup verification source file"});Mp(r,im(s,o,{rust:i.endsWith(".rs")}))}}function tm(e,t={}){let n=e.flatMap(i=>i.entries.map(o=>({batch:i.depth,file:o.file,startLine:o.startLine,endLine:o.endLine,loc:o.loc,symbol:o.shortName})));return{dryRun:t.dryRun===!0,batches:e.length,symbols:n.length,loc:e.reduce((i,o)=>i+o.loc,0),files:[...new Set(n.map(i=>i.file))],filesEmptied:[...new Set(e.flatMap(i=>i.filesEmptied))],targets:n}}function nm(e,t,n={}){let i=tm(t,n);if(!i.dryRun)for(let o of t)oc(e,o);return i}function rc(e,t){let n=ic(e,"scip-cleanup-patch-");try{return nm(n.root,t),Ot("git",["-C",n.root,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}finally{n.dispose()}}function sc(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 ac(e,t,n={}){if(e.unavailableReason)return[`Cleanup verification is unavailable: ${e.unavailableReason}.`];let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowUnknownWorkingTree&&e.workingTree.state==="unavailable"&&i.push(`Working-tree inspection is unavailable: ${e.workingTree.reason}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let o=new Set(e.batches.filter(r=>r.status==="verified").map(r=>r.depth));for(let r of t)o.has(r.depth)||i.push(`Batch ${r.depth} is not verified by the detected checker(s).`);return i}function im(e,t,n={}){let i=e.split(`
|
|
4
|
+
`),o=(n.rust===!0?om(e):sr(e)).split(`
|
|
5
|
+
`),r=new Set;for(let s of t){let a=rm(i,s.start),c=am(o,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)r.add(l)}return i.filter((s,a)=>!r.has(a)).join(`
|
|
6
|
+
`)}function om(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 rm(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 sm=200;function am(e,t,n){let i=0;for(let o=t;o<e.length;o++){for(let r of e[o]??"")r==="("||r==="["||r==="{"?i+=1:(r===")"||r==="]"||r==="}")&&(i-=1);if(o>=n&&i<=0)return o;if(o-n>sm)break}return n}function Ya(e,t,n){let i=Ip(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",windowsHide:!0,env:e.env??process.env,maxBuffer:33554432}),o=`${i.stdout??""}
|
|
7
|
+
${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:Za(o)};let r=cm(e.label,o),s=r.diagnostics.length>0?r.diagnostics:i.error?[{file:"",message:String(i.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:i.status,rawErrors:s.map(fm),diagnostics:s,parseBasis:r.parseBasis,outputTail:Za(o)}}function cm(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:lm(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:dm(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=um(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:pm(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:mm(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:gm(t),parseBasis:"clj-kondo-json"}:{diagnostics:hm(t),parseBasis:"heuristic"}}function lm(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 dm(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 um(e){let t=cc(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=i,r=o.location,s=r&&typeof r=="object"?r:{},a=typeof o.filename=="string"?o.filename:"",c=typeof o.message=="string"?o.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof o.code=="string"?o.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function pm(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 mm(e){let t=[];for(let n of e.split(`
|
|
8
|
+
`)){if(!n.trim().startsWith("{"))continue;let i=mi(n);if(!i||typeof i!="object")continue;let o=i;if(o.reason!=="compiler-message")continue;let r=o.message;if(!r||typeof r!="object")continue;let s=r;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(m=>!!m&&typeof m=="object"&&m.is_primary===!0),u=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:u&&typeof u=="object"&&typeof u.code=="string"?String(u.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function gm(e){let t=cc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!o||typeof o!="object")continue;let r=o;r.level==="error"&&i.push({file:typeof r.filename=="string"?r.filename:"",line:typeof r.row=="number"?r.row:void 0,column:typeof r.col=="number"?r.col:void 0,code:typeof r.type=="string"?r.type:void 0,message:typeof r.message=="string"?r.message:"",parseBasis:"clj-kondo-json"})}return i}function hm(e){return e.split(`
|
|
9
|
+
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function fm(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 cc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return mi(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?mi(t.slice(n)):null}function mi(e){try{return JSON.parse(e)}catch{return null}}function Za(e,t=10){return e.split(`
|
|
10
|
+
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var uc={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"]},ym={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"},vm={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 Be(e,t){let n=t.languages??nn(e),i=n.map(a=>{let c=ln($n(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),o=Im(e,n,t),r=bi({semantics:o},"typescript"),s=hi(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:o,semantic:r,checkers:s,gitAvailable:Om(e),...Sm(e,t)}}function Sm(e,t){try{let n=mt(e,t),i=hn(e),o=Object.fromEntries(i.hosts.map(r=>[r.host,r.missing.length===0?"installed":r.events.length>0?"partial":"none"]));return{agentIntegrations:{builder:{mode:n.mode,chain:n.chain.map(Ao)},sentinel:{enabled:t.sentinel?.enabled===!0,hooks:o,delivery:bn(en(e,t))}}}}catch{return{}}}function ht(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",o=i!=="unavailable",r=e.languages.map(c=>Pm(e,c,{hasIndexedGraph:Am(c,t),runtimeProbe:t.runtimeProbe})),s=r.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:r,relations:wm(r,o),capabilities:[{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...km(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?r.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-impact",label:"Git change mapping",status:e.gitAvailable&&o?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-symbol and downstream-consumer mapping.":"Git is unavailable or the project root is not a git worktree."},...$m(e.agentIntegrations)]}}function $m(e){if(!e)return[];let{builder:t,sentinel:n}=e,i=Object.entries(n.hooks).map(([s,a])=>`${s}=${a}`).join(", "),o=Object.entries(n.delivery).map(([s,a])=>`${s}=${a}`).join(", "),r=Object.values(n.hooks).some(s=>s!=="none");return[{id:"symbol-builder",label:"Symbol builder",status:t.chain.length===0?"unavailable":"partial",evidence:"heuristic",reason:`mode ${t.mode}; chain ${t.chain.join(", ")||"(empty)"}; not probed; run doctor`},{id:"sentinel",label:"Trailing sentinel",status:n.enabled?r?"available":"partial":"unavailable",evidence:"heuristic",reason:n.enabled?`enabled; hooks ${i}; delivery ${o}`:`disabled; hooks ${i}; enable with codebaseiq setup --sentinel`}]}function wm(e,t){return Ba.map(n=>{let i=kr.flatMap(r=>{let s=r.relations.filter(a=>a.family===n.family);return s.length===0?[]:[xm(r,s,e,t)]}),o=fi(i.map(r=>r.status));return{...n,status:o,providerCapabilities:i,reason:o==="unsupported"?t?"The current project has no available provider for this relationship family.":"An indexed graph is required before this relationship family can be queried.":o==="exact"?"Exact within indexed compiler/source identity coverage; dynamic or unindexed constructs remain outside scope.":"Supported by bounded static providers; unresolved and unsupported constructs remain explicitly reported."}})}function xm(e,t,n,i){let o=n.map(a=>Rm(e,t,a,i)),r=fi(o.map(a=>a.status)),s=o.filter(a=>a.status!=="unsupported").map(a=>a.language);return{id:e.id,label:e.label,status:r,requirements:e.requirements,subtypes:t.map(a=>a.subtype),languages:o,reason:s.length===0?`Unavailable: requires ${e.requirements.join(", ")}.`:`${r} support for ${s.join(", ")}; analytical ceiling is declared per subtype.`}}function Rm(e,t,n,i){let o=e.requirements.filter(s=>!Cm(s,n,i));if(o.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${o.join(", ")}.`};let r=fi(t.map(s=>s.supportCeiling));return{language:n.language,status:r,reason:`${e.label} is available; subtype coverage is ${r}.`}}function Cm(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 fi(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 km(e){return Em(e).map(t=>{let n=bi(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Tm(t)} semantic provider`,status:i,evidence:"semantic",reason:Lm(t,n)}})}function Em(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of mc(e))t.add(n.language);return[...t].sort((n,i)=>lc(n)-lc(i))}function lc(e){return e==="typescript"?0:1}function Tm(e){return e==="typescript"?"TypeScript":"Rust"}function Lm(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 Pm(e,t,n){let i=e.indexers.find(u=>u.language===t),o=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",r=o!=="unavailable",s=jm(t,n.runtimeProbe),a=Nm(e,t),c=Dm(e,t),l=c.length===0?"unavailable":c.every(u=>u.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:o,evidence:"graph-fact",reason:o==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:o==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:r?s.status:"unavailable",evidence:"heuristic",reason:r?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(u=>u.label).join(", "):`No detected checker covers ${uc[t].join(", ")} files.`}}}function Am(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function jm(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??dc(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=pc(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)??dc(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 dc(e){let t=ym[e];return t?sn(t):pc(e)==="regex-only"?"regex":"unavailable"}function pc(e){let t=vm[e],n=t?cr(t):null;return n?.imports??n?.exports??n?.reExports??null}function Im(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...Ja(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let o=hr(e);i.push({language:"rust",available:o.available,dependencyAvailable:o.dependencyAvailable,resolvedBinary:o.resolvedBinary,reason:o.available?o.note:o.reason})}return i}function mc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function bi(e,t){return mc(e).find(n=>n.language===t)}function Nm(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=bi(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 Dm(e,t){let n=new Set(uc[t]);return e.checkers.filter(i=>i.coversExtensions.some(o=>n.has(o)))}function Om(e){try{return bm("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",windowsHide:!0,timeout:1e4}),!0}catch{return!1}}import{statSync as gc}from"fs";import{basename as Mm,isAbsolute as qm,join as Mt,relative as Fm}from"path";import{fileURLToPath as Bm}from"url";import{watch as Wm}from"chokidar";import _m from"ignore";var $c=5e3,Pn=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onFileChanged;onBulkChange;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;reindexInFlight=!1;lastReindexEnd=0;fileChangeTimer=null;pendingFileChanges=new Set;bulkChangePending=!1;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;observationEpoch=0;changeSequence=0;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=et(t.config),this.outputDb=t.outputDb??Mt(en(this.projectRoot,t.config),"index.db"),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onFileChanged=t.onFileChanged,this.onBulkChange=t.onBulkChange;let n=t.onError??(i=>console.error(i.message));this.onError=i=>{this.observationEpoch+=1,n(i)},this.clock=t.clock??Km,wc.set(this,ig(t.stopTimeoutMs??$c,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??tg(),this.subscriptionFactory=t.subscriptionFactory??zm,this.budgetInspector=t.budgetInspector??Oa,xc.set(this,{gitReader:t.gitReader??fo,languages:Rc(t.languages??t.config.languages),stagedIndexEntries:null,gitSignalPaths:null,lastGitSignal:null}),this.gitignoreFilter=To(t.projectRoot),this.extraIgnore=_m(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Ln(this).errors=[],this.sourcePollingFallbackStarted=!1,this.observationEpoch+=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.clearFileChangeWindow();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Ln(this).closures],o=Gm(this),r=this.clock.now()+o;return this.stopPromise=this.finishStop(t,i,n,r,o).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}observation(){return{epoch:this.observationEpoch,changeSequence:this.changeSequence}}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=bc(this.pendingTrigger,t),this.changedFiles+=1,this.changeSequence+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,o)=>this.isIgnoredWatchPath(i,o?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,o)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(o)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!ng(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.observationEpoch+=1,this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(o=>o!==t),Um(Ln(this),t,o=>this.onError(o));try{this.startSourceWatcher(!0)}catch(o){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(o)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let o=n?`${i}/`:i;return o===".git/"||o.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(o)||this.extraIgnore.ignores(o)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Mm(n).startsWith(Na)||(n===".codebaseiq.json"&&yc(this,this.projectRoot),vc(this,n)&&(this.noteFileChange(n),this.scheduleReindex({kind:"watch-source",detail:n})))}noteFileChange(t){!this.onFileChanged&&!this.onBulkChange||(this.bulkChangePending||(this.pendingFileChanges.add(t),this.pendingFileChanges.size>Qm&&(this.pendingFileChanges.clear(),this.bulkChangePending=!0)),this.fileChangeTimer??=this.clock.setTimeout(()=>this.flushFileChangeWindow(),Jm))}flushFileChangeWindow(){if(this.fileChangeTimer=null,this.stopped)return;let t=[...this.pendingFileChanges],n=this.bulkChangePending;this.pendingFileChanges.clear(),this.bulkChangePending=!1;try{n?this.onBulkChange?.():this.onFileChanged?.(t)}catch{}}clearFileChangeWindow(){this.fileChangeTimer&&(this.clock.clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingFileChanges.clear(),this.bulkChangePending=!1}relativeWatchPath(t){let n=qm(t)?t:Mt(this.projectRoot,t);return Fm(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=bc(this.pendingTrigger,t),this.changedFiles++,this.changeSequence+=1,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.inspectBudget();if(t.state==="paused"){this.dirty=!0;let s=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:s,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,s-this.wallNow())));return}let n=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&n<this.watchConfig.cooldownMs){let s=this.watchConfig.cooldownMs-n;this.dirty=!0;let a=this.wallNow()+s;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},s);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.wallNow();this.setStatus({state:"indexing",startedAt:o});let r=this.reindexRunner.start(this.reindexRequest(i));this.activeOperation=r,r.completion.then(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(s,i)===!0}catch(c){this.onError(c instanceof Error?c:new Error(String(c)))}if(this.dirty&&!this.stopped){if(a){let l=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(l),this.setStatus({state:"idle"});return}let c=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:c,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=s instanceof Error?s:new Error(String(s));this.onReindexError(a,i),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===r&&(this.activeOperation=null)})}async finishStop(t,n,i,o,r){let s=[],a=t.map(async g=>{try{await g.close()}catch(p){s.push(`watch subscription close failed: ${String(p)}`)}});a.push(...n),i&&a.push((async()=>{try{let g=await i.cancel();g.state==="degraded"&&s.push(g.reason)}catch(g){s.push(`reindex cancellation failed: ${g instanceof Error?g.message:String(g)}`)}})());let c=a.length,l=a.map(g=>g.finally(()=>{c-=1})),u=await Vm(l,o,this.clock),m=Ln(this);return s.push(...m.errors),m.errors=[],u?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${r}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){if(this.lastGitState=this.readGitState(),!this.lastGitState)return;let t=We(this);t.gitSignalPaths=this.resolveGitSignalPaths(),t.lastGitSignal=this.gitActivitySignal(),t.stagedIndexEntries=Sc(this.projectRoot,t.gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.()}resolveGitSignalPaths(){let t=We(this).gitReader,n=St(this.projectRoot,["rev-parse","--git-dir"],t),i=St(this.projectRoot,["rev-parse","--git-common-dir"],t);if(!n)return null;let o=Yt(this.projectRoot,n),r=i?Yt(this.projectRoot,i):o,s=this.lastGitState?.indexPath;return[Mt(o,"HEAD"),Mt(r,"packed-refs"),Mt(r,"refs","heads"),...s?[s]:[]]}gitActivitySignal(){let t=We(this).gitSignalPaths;if(!t)return null;let n="";for(let i of t)try{let o=gc(i);n+=`${i}:${o.mtimeMs}:${o.size};`}catch{n+=`${i}:absent;`}return n}pollGitState(){let t=this.gitActivitySignal();if(t!==null){if(t===We(this).lastGitSignal)return;We(this).lastGitSignal=t}let n=this.lastGitState,i=this.readGitState();if(!n||!i||this.stopped){this.lastGitState=i;return}this.lastGitState=i;let o=n.head!==i.head,r=n.indexPath!==i.indexPath||n.indexMtimeMs!==i.indexMtimeMs||n.indexSize!==i.indexSize;if(!o&&!r)return;let s=We(this),a=s.stagedIndexEntries,c=Sc(this.projectRoot,s.gitReader);s.stagedIndexEntries=c;let l=og(this.projectRoot,s.gitReader,n,i,a,c,o,r),u=null;l!==null&&(l.includes(".codebaseiq.json")&&yc(this,this.projectRoot),u=l.filter(m=>vc(this,m)),u.length===0)||(o&&r?this.scheduleReindex({kind:"watch-git-state",detail:yi("HEAD and index changed",u)}):o?this.scheduleReindex({kind:"watch-git-head",detail:yi("HEAD changed",u)}):r&&this.scheduleReindex({kind:"watch-git-index",detail:yi(i.indexPath??"index changed",u)}))}readGitState(){let t=We(this).gitReader,n=St(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=Yt(this.projectRoot,n),o={head:St(this.projectRoot,["rev-parse","--verify","HEAD"],t),indexPath:i};try{let r=gc(i);o.indexMtimeMs=r.mtimeMs,o.indexSize=r.size}catch{o.indexMtimeMs=void 0,o.indexSize=void 0}return o}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Vm(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),o=Math.max(0,t-n.now()),r=null,s=new Promise(c=>{r=n.setTimeout(()=>c(!1),o)}),a=await Promise.race([i,s]);return a&&r&&n.clearTimeout(r),a}var hc=new WeakMap,wc=new WeakMap,xc=new WeakMap;function Ln(e){let t=hc.get(e);if(t)return t;let n={closures:new Set,errors:[]};return hc.set(e,n),n}function Gm(e){return wc.get(e)??$c}function We(e){let t=xc.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Um(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(o=>{let r=`watch subscription close failed during polling fallback: ${String(o)}`;e.errors.push(r),n(new Error(r))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function Hm(e,t=bo){let{projectRoot:n,config:i,languages:o,pnpmWorkspaces:r,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:l,trigger:u}=e,m=Ae(n),g=Object.keys(m).length>0?m:i,p=wt(n,g),h=g.indexer?.typescript,f=g.indexer?.clojure,b=t(process.pid);if(!b)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:Bm(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(g.languages??o)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(g.indexerConcurrency??l??""),SCIP_REINDEX_PNPM_WORKSPACES:h?.pnpmWorkspaces??r?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:h?.projectMode??s,projects:h?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:u.kind,SCIP_REINDEX_TRIGGER_DETAIL:u.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(b)}}}var Km={now:Co,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},zm=(e,t)=>Wm(e,t),Jm=120,Qm=200,Xm=15*6e4,Ym=1e3,Zm=64*1024;function eg(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function fc(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 tg(e={}){let t=e.timeoutMs??Xm,n=e.terminationGraceMs??Ym,i=e.maxOutputBytes??Zm,o=e.resolveLaunch??Hm;return{start(r){let s=o(r),a=new AbortController,c=eg(),l=!1,u=Xs({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(m=>{if(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated},m.status!==0)throw new Error(fc(new Error(`Reindex worker exited with ${m.signal?`signal ${m.signal}`:`code ${m.status}`}`),c));return m.durationMs}).catch(m=>{throw m instanceof Qs&&(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated}),new Error(fc(m,c),{cause:m})}).finally(()=>{l=!0});return{completion:u,async cancel(){l||a.abort();try{await u}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function bc(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 ng(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function ig(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function Rc(e){return e&&e.length>0?[...e]:$t}function yc(e,t){try{We(e).languages=Rc(Ae(t).languages)}catch{We(e).languages=$t}}function vc(e,t){return wo(t,We(e).languages)!=="other"}function og(e,t,n,i,o,r,s,a){let c=new Set;if(s){if(!n.head||!i.head)return null;let l=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(l.kind!=="success")return null;for(let u of rg(l.output))c.add(u)}if(a){if(o===null||r===null)return null;for(let l of ag(o,r))c.add(l)}return[...c].sort()}function Sc(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?sg(n.output):null}function rg(e){return e.split("\0").filter(t=>t.length>0)}function sg(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let o=t[i],r=t[i+1];if(!o.startsWith(":")||!r)return null;n.set(r,o)}return n}function ag(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function yi(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as jg}from"fs";import{existsSync as Ec,mkdirSync as Tc,writeFileSync as Lc}from"fs";import{homedir as cg}from"os";import{dirname as Pc,isAbsolute as lg,join as vi,relative as Cc,resolve as dg}from"path";function Ac(e,t={}){let n=t.dossierDir?dg(e.projectRoot,t.dossierDir):vi(e.projectRoot,"docs","codebaseiq"),i={markdownPath:vi(n,"health-dossier.md"),jsonPath:vi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},o=wg({...mg(e),generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return vg(i.markdownPath,gg(o),i),Sg(i.jsonPath,o,i),i}catch(r){return{...i,status:"failed",error:r instanceof Error?r.message:String(r)}}}var ug=new Set(["symbol-builder","sentinel"]),pg=new Set(["builder-config","sentinel-config","sentinel-hooks"]);function mg(e){let{sentinelHooks:t,...n}=e;return{...n,steps:e.steps.filter(i=>i.id===void 0||!pg.has(i.id)),...e.readiness?{readiness:kc(e.readiness)}:{},...e.initialReadiness?{initialReadiness:kc(e.initialReadiness)}:{},...e.capabilities?.capabilities?{capabilities:{...e.capabilities,capabilities:e.capabilities.capabilities.filter(i=>!ug.has(i.id))}}:{}}}function kc(e){let{agentIntegrations:t,...n}=e;return n}function gg(e){return`${["# codebaseiq Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${$i(e.health)}`,"","## Items That Need Attention","",...hg(e),"","## Blocked Or Unavailable Checks","",...fg(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...bg(e),"","## JSON","",`Machine-readable report: \`${yg(e)}\``,""].join(`
|
|
12
|
+
`)}`}function hg(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 fg(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 bg(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 $i(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function yg(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/codebaseiq/health-dossier.json"}function vg(e,t,n){if(Tc(Pc(e),{recursive:!0}),(Ec(e)?pt(e,"health dossier Markdown"):null)===t){n.unchanged.push(e);return}Lc(e,t),n.written.push(e)}function Sg(e,t,n){Tc(Pc(e),{recursive:!0});let i=`${JSON.stringify(t,null,2)}
|
|
13
|
+
`,o=Ec(e)?pt(e,"health dossier JSON"):null;if(o&&$g(o,i)){n.unchanged.push(e);return}Lc(e,i),n.written.push(e)}function $g(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function wg(e,t){return Si(e,t)}function Si(e,t){return typeof e=="string"?xg(e,t):Array.isArray(e)?e.map(n=>Si(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,Si(i,t)])):e}function xg(e,t){if(e===t)return".";if(!lg(e))return e;let n=Cc(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Cc(cg(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as Rg}from"child_process";import{dirname as jc,join as Cg,resolve as kg}from"path";import{fileURLToPath as Eg}from"url";var An={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function Tg(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let o of An[i]?.packages??[])n.add(o);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function wi(e){return[...new Set(e.filter(t=>An[t]!==void 0))].sort()}function Ic(e,t={}){let n=t.runtime??Ag,i=t.packageRoot??Lg(),o=wi(e),r=o.filter(m=>n.probe(An[m].ast)),s=o.filter(m=>!r.includes(m));if(s.length===0)return{supportedLanguages:o,availableBefore:r,installed:[],availableAfter:r,unavailable:[],attempted:!1};let a=Pg(i),c=Tg(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let u=o.filter(m=>n.probe(An[m].ast));return{supportedLanguages:o,availableBefore:r,installed:l.ok?c:[],availableAfter:u,unavailable:o.filter(m=>!u.includes(m)),attempted:!0,...l.error?{error:l.error}:{}}}function Lg(){let e=jc(Eg(import.meta.url));for(;;){let t=Cg(e,"package.json");try{if(JSON.parse(pt(t,"AST parser package manifest")).name==="codebaseiq")return e}catch{}let n=jc(e);if(n===e)throw new Error("Unable to locate the installed codebaseiq package root.");e=n}}function Pg(e){return JSON.parse(pt(kg(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var Ag={probe:e=>sn(e)==="ast",resetProbe:ar,install:(e,t)=>{let n=Rg(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",windowsHide:!0,maxBuffer:10485760});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function Mc(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 qc(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:"codebaseiq 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:"codebaseiq 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:"codebaseiq 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:"codebaseiq setup --install-missing"}),{actions:t}}async function Fc(e={}){let t=Mg(e),n=qg(e),i=[],o=ge(),{projectRoot:r,paths:s,dbPath:a}=o,c=n?.enabled?!0:e.automaticRefresh??o.config.watch?.enabled??!0,u=st(o.config,{projectRoot:r}).filter(M=>M.level==="error"),m=null,g=null;if(u.length===0&&!o.config.collaborationDomainId)try{m=Oo(r,o.config)}catch(M){g=Je(M)}let p=m?.config??o.config,h=e.languages?Mo(r,p,e.languages):null,f=h?.config??p,b=st(f,{projectRoot:r}),v=b.filter(M=>M.level==="error"),S=null,L=null;if(v.length===0&&f.watch?.enabled!==c)try{S=qo(r,f,c)}catch(M){L=Je(M)}F(i,{id:"collaboration-domain-config",label:"Collaboration domain",status:g!==null?"failed":u.length>0?"skipped":"ok",message:g??(u.length>0?"Skipped because the existing project config has validation errors.":m?.changed?"Generated the committed identity shared by merge-intended branches, clones, and forks.":"The committed collaboration-domain identity is already present."),...m?{details:[m.configPath]}:{}}),F(i,{id:"automatic-indexing-config",label:"Automatic indexing config",status:L!==null?"failed":v.length>0||!c?"skipped":"ok",message:L??(v.length>0?"Skipped because the existing project config has validation errors.":c?S?.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."),...S?{details:[S.configPath]}:{}});let B=v.length>0,H=S?.config??f,j=t?Vg({plan:t,projectRoot:r,config:H,configHasErrors:B,steps:i}):null,W=n?Gg({plan:n,projectRoot:r,cacheDir:s.cacheDir,config:j?.config??H,configHasErrors:B,steps:i}):null,w=W?.config??j?.config??H,_=Ug({projectRoot:r,install:e.sentinel!==!1&&w.sentinel?.enabled===!0,remove:e.sentinel===!1,steps:i}),U=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Tn({quiet:!0});F(i,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":U.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${U.installed.length} installed, ${U.alreadyLinked.length} already linked, ${U.pruned.length} pruned, ${U.skipped.length} skipped.`,details:[...U.pruned.map(M=>`Pruned ${M}`),...U.skipped.map(M=>`Skipped ${M}`)]});let O=w===f?b:st(w,{projectRoot:r}),ee=O.filter(M=>M.level==="error");F(i,{id:"config",label:"Project config",status:ee.length>0?"failed":O.length>0?"warn":"ok",message:O.length===0?"Config OK.":`${O.length} diagnostic(s), ${ee.length} error(s).`,details:O.map(M=>`${M.level.toUpperCase()} ${M.path}: ${M.message}`)});let Ye=Be(r,w);F(i,{id:"readiness",label:"Indexer readiness",status:Ye.languages.length===0?"failed":Ye.indexers.some(M=>!M.runnable)?"warn":"ok",message:Ye.languages.length===0?"No supported project languages detected.":`Detected languages: ${Ye.languages.join(", ")}`,details:Ye.indexers.map(M=>`${M.runnable?"OK":M.installed?"WARN":"MISSING"} ${M.language}: ${M.binaryLabel}${M.note?` - ${M.note}`:""}`)});let Ce=e.installAstParsers!==!0?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Ic(Ye.languages);F(i,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers!==!0?"skipped":Ce.unavailable.length>0?"warn":"ok",message:e.installAstParsers!==!0?"Skipped because installing missing parser packages requires explicit consent.":Ce.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${Ce.availableAfter.length}/${Ce.supportedLanguages.length} selected language parser(s) available${Ce.installed.length>0?`; installed ${Ce.installed.join(", ")}`:""}.`,details:[...Ce.unavailable.length>0?[`Unavailable: ${Ce.unavailable.join(", ")}`]:[],...Ce.error?[Ce.error]:[]]});let ao=e.installIndexers===!0,co=ao?oh(r,Ye,i):[];ao||F(i,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent."});let lo=Be(r,w),uo=await Hg({projectRoot:r,paths:s,config:w,readiness:lo,configHasErrors:ee.length>0,steps:i,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),zn=uo.reindexResult,$p=uo.freshness,po=et(w),mo=Kg({projectRoot:r,cacheDir:s.cacheDir,watchConfig:po,readiness:lo,configHasErrors:ee.length>0,reindexResult:zn,postReindexFreshness:$p,steps:i}),Ze=Be(r,w),Qt=ht(Ze),go=ct(r,w,s);F(i,{id:"capabilities",label:"Capability matrix",status:dh(Qt),message:uh(Qt)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let ho=e.runHealth===!1?ah(i):await sh(s.dbPath,i),De=Ze.languages.includes("rust")?dn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;F(i,{id:"rust-semantic-session",label:"Rust semantic session",status:De===null?"skipped":De.valid?"ok":"failed",message:De===null?"Skipped because Rust was not detected.":`${De.transport}/${De.state} selected from ${De.source}; ${De.fallback} fallback; opt out with ${De.optOut}.`});let Oe=null;try{e.noAgentGuidance?F(i,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Oe=gn(r),F(i,{id:"agent-guidance",label:"Project agent guidance",status:Oe.skipped.length>0?"warn":"ok",message:`${Oe.written.length} written, ${Oe.unchanged.length} already wired, ${Oe.skipped.length} skipped.`,details:Oe.skipped.map(M=>`Skipped ${M.target}: ${M.reason}`)}))}catch(M){F(i,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Je(M)})}let Xt=zg({reindexResult:zn,readiness:Ze,capabilities:Qt,freshness:go,health:ho,agentResult:Oe,watchConfig:po,watchService:mo,rustSemanticSession:De,steps:i});F(i,{id:"smoke-tests",label:"Setup smoke tests",status:Jg(Xt),message:Qg(Xt),details:Xt.map(M=>`${M.command}: ${M.status} - ${M.evidence}`)});let it=j?.write??null,Jn=W?.configWrite??null,Qn=W?.settingsWrite??null,wp={repository:[...h?.changed?[h.configPath]:[],...S?.changed?[S.configPath]:[],...it?.changed&&it.scope==="project"?[it.path]:[],...Jn?.changed?[Jn.configPath]:[],...Oe?.written??[]],checkout:[...it?.changed&&it.scope==="local"?[it.path]:[],..._?.files??[]],user:[...Qn?.changed?[Qn.path]:[],..._?.binaryPath?[_.binaryPath]:[],...U.installed,...Ce.installed,...co.filter(M=>M.attempted).map(M=>`${M.binaryLabel} installer`)]},Ge={projectRoot:r,dbPath:a,configuredDbPath:s.dbPath,languages:Ze.languages,steps:i,skills:U,astParsers:Ce,initialReadiness:Ye,indexerRemediation:co,readiness:Ze,capabilities:Qt,freshness:go,reindex:zn,automaticRefreshConfig:S,watchService:mo,rustSemanticSession:De,health:ho,smokeTests:Xt,healthDossier:null,setupAgent:Oe,builderConfig:it,sentinelConfig:Jn,sentinelSettings:Qn,sentinelRequested:w.sentinel?.enabled===!0,sentinelHooks:_,changeScopes:wp,filesWritten:Oe?.written??[],verdict:Ri(i,Ze)};if(e.runHealth===!1)return F(i,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ge.verdict=Ri(i,Ze),Ge;let Me=Ac(Ge,{dossierDir:e.dossierDir});return Ge.healthDossier=Me,Ge.changeScopes.repository.push(...Me.written),Ge.filesWritten=[...Ge.filesWritten,...Me.written],F(i,{id:"health-dossier",label:"Health dossier",status:Me.status==="failed"?"failed":"ok",message:Me.status==="failed"?Me.error:`${Me.written.length} written, ${Me.unchanged.length} unchanged.`,details:[Me.markdownPath,Me.jsonPath]}),Ge.verdict=Ri(i,Ze),Ge}var Ig=["local","project"],ki=["claude","codex"],Ng={claude:Lo,codex:Po},Dg=/^([A-Za-z0-9_.-]{1,64})=(https?:\/\/\S+)$/,Og=/^https?:\/\/[^/?#]*@|[?#]/;function Mg(e){let t=e.embeddingsEndpoints??[];if(e.builderMode===void 0&&t.length===0&&e.embeddingsModel===void 0&&e.agentCommand===void 0&&e.builderScope===void 0)return null;let n=e.builderMode===void 0?void 0:qt(xt,e.builderMode,"--builder-mode"),i=e.builderModeIfUnset===void 0?void 0:qt(xt,e.builderModeIfUnset,"--builder-mode"),o=e.builderScope===void 0?"local":qt(Ig,e.builderScope,"--builder-scope"),r=e.agentCommand===void 0?void 0:qt(ki,e.agentCommand,"--agent-command");if(t.length>0&&!e.embeddingsModel)throw new Error("--embeddings-endpoint requires --embeddings-model.");if(t.length===0&&e.embeddingsModel!==void 0)throw new Error("--embeddings-model requires --embeddings-endpoint.");let s=t.map(c=>Bg(c,e.embeddingsModel??"")),a=new Set;for(let{name:c}of s){if(a.has(c))throw new Error(`--embeddings-endpoint names must be unique; "${c}" repeats.`);a.add(c)}if(o==="project"&&r!==void 0)throw new Error("--agent-command is a per-developer setting; use --builder-scope local.");if(n===void 0&&s.length===0&&r===void 0)throw new Error("--builder-scope needs --builder-mode, --embeddings-endpoint, or --agent-command.");return{scope:o,...n?{mode:n}:{},...i?{defaultMode:i}:{},endpoints:s,...r?{agentCommand:r}:{}}}function qg(e){let t=Fg(e.sentinelLive);if(t.length>0&&e.sentinel===!1)throw new Error("--sentinel-live cannot be combined with --no-sentinel.");let n=e.sentinel??(t.length>0?!0:void 0);return n===void 0?null:{enabled:n,liveFamilies:t}}function Fg(e){if(e===void 0||e===!1)return[];if(e===!0)return[...ti];let t=e.split(",").map(n=>qt(ti,n.trim(),"--sentinel-live"));return[...new Set(t)]}function qt(e,t,n){let i=e.find(o=>o===t);if(i===void 0)throw new Error(`${n} must be one of ${e.join(", ")}; got "${t}".`);return i}function Bg(e,t){let n=Dg.exec(e);if(!n)throw new Error(`--embeddings-endpoint must look like <name>=<http(s) url>; got "${e}".`);let i=n[1],o=n[2];if(!Wg(o))throw new Error(`--embeddings-endpoint "${i}" must be a bare http(s) URL without credentials, query, or fragment; keep tokens in the apiKeyEnv variable.`);return{name:i,baseUrl:o,model:t}}function Wg(e){try{let t=new URL(e);return!t.username&&!t.password&&!Og.test(e)}catch{return!1}}function Nc(e,t,n){let i={...e};if(t.mode)i.mode=t.mode;else if(e?.mode===void 0&&n?.mode===void 0){let o=t.defaultMode??(t.endpoints.length>0?"auto":void 0);o&&(i.mode=o)}if(t.endpoints.length>0&&(i.embeddings={...e?.embeddings,endpoints:Dc(e?.embeddings?.endpoints,t.endpoints)}),t.agentCommand){let o={name:t.agentCommand,argv:[...Ng[t.agentCommand]]};i.agent={...e?.agent,commands:Dc(e?.agent?.commands,[o])}}return{builder:i,warnings:_g(i,t,n)}}function _g(e,t,n){if(t.endpoints.length===0)return[];let i=[];(e.mode??n?.mode??"agent")==="agent"&&i.push("Builder mode is agent, so the new embeddings endpoint(s) are not tried; use --builder-mode auto.");let o=e.chain??n?.chain,r=t.endpoints.map(s=>`embeddings:${s.name}`).filter(s=>!o?.includes(s));return o&&r.length>0&&i.push(`The provider chain [${o.join(", ")}] does not include ${r.join(", ")}; add it to builder.chain.`),i}function Dc(e,t){let n=[...e??[]];for(let i of t){let o=n.findIndex(r=>r.name===i.name);o===-1?n.push(i):n[o]={...n[o],...i}}return n}function Oc(e){let t=jo(e).filter(n=>n.level==="error");if(t.length>0)throw new Error(`Invalid builder settings: ${t.map(n=>`${n.path}: ${n.message}`).join("; ")}`);return e}function Vg(e){let{plan:t,projectRoot:n,config:i,steps:o}=e,r={id:"builder-config",label:"Symbol builder config"};try{if(t.scope==="project"){if(e.configHasErrors)return F(o,{...r,status:"skipped",message:"Skipped because the existing project config has validation errors."}),{config:i,write:null};let m=Nc(i.builder,t),g=Fo(n,i,Oc(m.builder));return F(o,{...r,status:m.warnings.length>0?"warn":"ok",message:[g.changed?"Wrote builder defaults to the project config; credentials and agent commands stay per-developer.":"Builder defaults in the project config are already current.",...m.warnings].join(" "),details:[g.configPath]}),{config:g.config,write:{scope:"project",path:g.configPath,changed:g.changed}}}let s=Wo(n),a=s.diagnostics.filter(m=>m.level==="error");if(a.length>0)throw new Error(`The per-developer builder config has errors and was left untouched: ${a.map(m=>m.message).join("; ")}`);let c=Nc(s.config,t,i.builder),l=_o(n,Oc(c.builder)),u={written:[],unchanged:[],skipped:[]};return la(n,u),F(o,{...r,status:u.skipped.length>0||c.warnings.length>0?"warn":"ok",message:[l.changed?`Wrote per-developer builder settings${u.skipped.length>0?"":"; the file is excluded from Git"}.`:"Per-developer builder settings are already current.",...c.warnings].join(" "),details:[l.path,...u.skipped.map(m=>`Skipped ${m.target}: ${m.reason}`)]}),{config:i,write:{scope:"local",...l}}}catch(s){return F(o,{...r,status:"failed",message:Je(s)}),{config:i,write:null}}}function Gg(e){let{plan:t,projectRoot:n,cacheDir:i,config:o,steps:r}=e,s={id:"sentinel-config",label:"Trailing sentinel config"};if(e.configHasErrors)return F(r,{...s,status:"skipped",message:"Skipped because the existing project config has validation errors."}),{config:o,configWrite:null,settingsWrite:null};let a=null,c=null;try{a=Bo(n,o,t.enabled),t.liveFamilies.length>0&&(c=Vo(i,t.liveFamilies)),F(r,{...s,status:"ok",message:t.enabled?`Enabled the trailing sentinel for this project${t.liveFamilies.length>0?`; per-user delivery is live for ${t.liveFamilies.join(", ")}`:""}.`:"Disabled the trailing sentinel for this project.",details:[a.configPath,...c?[c.path]:[]]})}catch(l){F(r,{...s,status:"failed",message:Je(l)})}return{config:a?.config??o,configWrite:a,settingsWrite:c}}function Ug(e){let{projectRoot:t,steps:n}=e,i={id:"sentinel-hooks",label:"Trailing sentinel hooks"};try{if(e.install){let o=da(t),s=[...o.written,...o.unchanged].includes(".codex/hooks.json")?fn(t)?.hooks.filter(c=>!c.trusted).length??0:0,a=o.binary.state==="installed"&&o.binary.changed?o.binary.script:null;return F(n,{...i,status:o.skipped.length>0?"warn":"ok",message:o.binary.state==="skipped"?`Skipped: ${o.binary.reason}.`:[`${o.written.length} written, ${o.unchanged.length} already current.`,s>0?`Open Codex once in this project and approve the ${s} sentinel hook(s); Codex does not run hooks you have not approved.`:"",...o.notices].filter(Boolean).join(" "),details:[...o.written,...a?[a]:[],...o.skipped.map(c=>`Skipped ${c.target}: ${c.reason}`)]}),{action:"install",files:o.written,unchanged:o.unchanged,skipped:o.skipped,binaryPath:a,codexAwaitingApproval:s}}if(e.remove){let o=ua(t);return F(n,{...i,status:o.skipped.length>0?"warn":"ok",message:o.removed.length>0?`Removed the sentinel hooks from ${o.removed.length} file(s).`:"No sentinel hooks were installed.",details:[...o.removed,...o.skipped.map(r=>`Skipped ${r.target}: ${r.reason}`)]}),{action:"remove",files:o.removed,unchanged:o.unchanged,skipped:o.skipped,binaryPath:null,codexAwaitingApproval:0}}}catch(o){F(n,{...i,status:"failed",message:Je(o)})}return null}async function Hg(e){if(e.readiness.languages.length===0||e.configHasErrors)return F(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,i=null;try{let o=0,r=!1;for(let s=0;s<2;s+=1){if(n=await Fa({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,installMissing:e.installMissing,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"codebaseiq setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),o+=n.durationMs,r||=!n.reused,i=ct(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&i.state==="stale"){t.push(`Index inputs changed during the first build (${i.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");F(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${r?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(o/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(o){F(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Je(o),details:t})}return{reindexResult:n,freshness:i}}function Kg(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=vn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ue,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 F(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Je(n)}),null}}function Bc(e){if(console.log("codebaseiq setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${$i(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),xi("Repository records (commit)",e.changeScopes.repository),xi("Checkout preferences (do not commit)",e.changeScopes.checkout),xi("User environment",e.changeScopes.user),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function xi(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function zg(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"codebaseiq reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"codebaseiq status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"codebaseiq config-validate",status:Xg(e.steps),evidence:Yg(e.steps)},{id:"capabilities",command:"codebaseiq capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"codebaseiq capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?Zg(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"codebaseiq health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"codebaseiq diff-impact --json",status:eh(e.readiness,e.freshness),evidence:th(e.readiness,e.freshness)},{id:"cleanup-verification",command:"codebaseiq cleanup-plan --verify",status:nh(e.capabilities),evidence:ih(e.capabilities)},{id:"watch-refresh",command:"codebaseiq status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"codebaseiq status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"codebaseiq setup-agent",status:e.agentResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:n?.message??"Project agent guidance was not written."}]}function Jg(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Qg(e){let t=e.filter(o=>o.status==="pass").length,n=e.filter(o=>o.status==="unavailable").length,i=e.filter(o=>o.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function Xg(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Yg(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Zg(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 eh(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function th(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 nh(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function ih(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(o=>o.cleanupVerification.status==="available").length,n=e.matrix.filter(o=>o.cleanupVerification.status==="partial").length,i=e.matrix.filter(o=>o.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function oh(e,t,n){let i=[];if(t.languages.length===0)return F(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=$n(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Ma(a,g=>c.push(g)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let m=rh(ln(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:m,messages:c,recovery:m.runnable?void 0:m.note??m.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return F(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let o=i.filter(s=>!s.after.runnable),r=i.filter(s=>s.attempted);return F(n,{id:"indexer-remediation",label:"Indexer remediation",status:o.length>0?"warn":"ok",message:o.length===0?`${r.length} install attempt(s); all detected indexers are runnable.`:`${r.length} install attempt(s); ${o.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function rh(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function sh(e,t){if(!jg(e)){let n="Skipped because no SQLite index database exists yet.";return F(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Ci(n)}try{let n=await ea({full:!0,json:!0});return F(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),ch(n)}catch(n){let i=Je(n);return F(t,{id:"health",label:"Health audit",status:"failed",message:i}),Ci(i)}}function ah(e){let t="Skipped by setup choice; run `codebaseiq health --full` when wanted.";return F(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Ci(t)}function ch(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(lh),warnings:e.warnings??[]}}function lh(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 Ci(e){return{score:null,riskScore:null,hygieneScore:null,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")?"partial":"ready"}function dh(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 uh(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 F(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Je(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as vh}from"readline";var ph=[{baseUrl:"http://127.0.0.1:8080/v1",listUrl:"http://127.0.0.1:8080/v1/models",server:"llama.cpp",format:"openai",confirmedBy:"llamacpp"},{baseUrl:"http://127.0.0.1:1234/v1",listUrl:"http://127.0.0.1:1234/v1/models",server:"lm-studio",format:"openai"},{baseUrl:"http://127.0.0.1:11434/v1",listUrl:"http://127.0.0.1:11434/api/tags",server:"ollama",format:"ollama"}],mh=300,gh=1024*1024,hh=/embed|nomic|bge|minilm|e5/i;async function Wc(e={}){let t=e.fetchImpl??fetch,n=e.timeoutMs??mh;return(await Promise.all(ph.map(o=>fh(o,t,n)))).filter(o=>o!==void 0)}async function fh(e,t,n){try{let i=await t(e.listUrl,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(n)});if(!i.ok)return;let o=await yh(i);if(o===void 0)return;let r=bh(JSON.parse(o),e.format);return r?{baseUrl:e.baseUrl,server:e.confirmedBy===void 0||r.owners.includes(e.confirmedBy)?e.server:"unknown",models:r.models,embeddingModels:r.models.filter(s=>hh.test(s))}:void 0}catch{return}}function bh(e,t){if(typeof e!="object"||e===null)return;let n=e[t==="ollama"?"models":"data"];if(!Array.isArray(n))return;let i=[],o=[];for(let r of n){if(typeof r!="object"||r===null)continue;let s=r,a=t==="ollama"?s.name:s.id;typeof a=="string"&&a!==""&&i.push(a),typeof s.owned_by=="string"&&o.push(s.owned_by)}return{models:i,owners:o}}async function yh(e){let t=e.body?.getReader();if(!t)return;let n=[],i=0;for(;;){let{done:o,value:r}=await t.read();if(o)return Buffer.concat(n).toString("utf8");if(i+=r.byteLength,i>gh){await t.cancel();return}n.push(r)}}function Sh(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function $h(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let i=n[e.cursor]?.id;if(!i)return e;let o=new Set(e.selected);return o.has(i)?o.delete(i):o.add(i),{...e,selected:o}}async function _c(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=Sh(e);vh(t);let o=t.isRaw;t.setRawMode(!0),t.resume();let r=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`codebaseiq setup
|
|
14
14
|
`),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
|
|
15
15
|
|
|
16
16
|
`),e.forEach((a,c)=>{let l=c===i.cursor?"\u203A":" ",u=i.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${u} ${a.label} [${a.scope}]\x1B[K
|
|
17
17
|
`)}),n.write("\x1B[K")};r(!0);try{return await new Promise((s,a)=>{let c=(u,m)=>{if(m.ctrl&&m.name==="c"){l(),a(new Error("Setup cancelled."));return}if(m.name==="return"||m.name==="enter"){l(),n.write(`
|
|
18
|
-
`),s(i.selected);return}let g=m.name==="up"?"up":m.name==="down"?"down":m.name==="space"?"toggle":null;g&&(i
|
|
19
|
-
`}function
|
|
18
|
+
`),s(i.selected);return}let g=m.name==="up"?"up":m.name==="down"?"down":m.name==="space"?"toggle":null;g&&(i=$h(i,g,e),r())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!o),t.pause()}}var Vc="configure-builder-agent",Gc="configure-builder-embeddings",Uc="enable-sentinel",wh="local",Hc="Embeddings server on another machine? Re-run: codebaseiq setup --embeddings-endpoint homelab=http://<host>:<port>/v1 --embeddings-model <model>",xh={resolveExecutable:e=>gr(e),detectEmbeddingServers:Wc};async function Kc(e,t=xh){let n=t.detectEmbeddingServers(),i;for(let s of e){let a=t.resolveExecutable(s);if(a!==null){i={name:s,path:a};break}}let o=(await n).find(s=>s.embeddingModels.length>0),r=o?.embeddingModels[0];return{...i?{agent:i}:{},...o&&r!==void 0?{embeddings:{baseUrl:o.baseUrl,model:r}}:{}}}function zc(e,t){let n=[];return e.agent&&t.agentCommand===void 0&&n.push({id:Vc,scope:"checkout",label:`Agent probes via ${e.agent.name} (found at ${e.agent.path})`,reason:"Lets the symbol builder turn a description into search probes with your agent CLI.",selected:!0}),e.embeddings&&(t.embeddingsEndpoints?.length??0)===0&&n.push({id:Gc,scope:"checkout",label:`Embeddings via local server (detected: ${e.embeddings.baseUrl}, model ${e.embeddings.model})`,reason:"Ranks existing symbols against a description with the embeddings server already running here.",selected:!1}),t.sentinel===void 0&&(t.sentinelLive===void 0||t.sentinelLive===!1)&&n.push({id:Uc,scope:"project",label:"Trailing sentinel for agent sessions (shadow mode)",reason:"Watches agent edits for copies of existing code and unwired additions; findings are only recorded at first.",selected:!1}),n}function Jc(e,t,n){let i=(e.embeddingsEndpoints?.length??0)>0,o=e.agentCommand===void 0&&n.has(Vc)?t.agent:void 0,r=!i&&n.has(Gc)?t.embeddings:void 0,s=o!==void 0||e.agentCommand!==void 0,a=r!==void 0||i;return{...e,...o?{agentCommand:o.name}:{},...r?{embeddingsEndpoints:[`${wh}=${r.baseUrl}`],embeddingsModel:r.model}:{},...(o||r)&&e.builderMode===void 0?{builderModeIfUnset:a?s?"auto":"embeddings":"agent"}:{},...e.sentinel===void 0&&n.has(Uc)?{sentinel:!0}:{}}}import{existsSync as Rh}from"fs";import{join as Ft}from"path";function Qc(e,t={}){let n=[],i=e.dryRun?"would ":"";if(e.global){for(let r of e.global.removed)n.push(` ${i}remove: ${r}`);if(t.verbose)for(let r of e.global.left)n.push(` left: ${r}`);else if(e.global.left.length>0){let r=e.global.left.length===1?"entry":"entries";n.push(` left: ${e.global.left.length} unrelated global skill ${r} (use --verbose to list)`)}for(let r of e.global.skipped)n.push(` skip: ${r}`)}if(e.sentinel){for(let r of e.sentinel.removed)n.push(` ${i}remove: ${r}`);for(let r of e.sentinel.skipped)n.push(` skip: ${r.target} \u2014 ${r.reason}`)}if(e.project){for(let r of e.project.agentSetup.removed)n.push(` ${i}remove: ${r}`);for(let r of e.project.agentSetup.unchanged)n.push(` ok: ${r} (no managed block)`);for(let r of e.project.agentSetup.skipped)n.push(` skip: ${r.target} \u2014 ${r.reason}`);for(let r of e.project.left)n.push(` left: ${r}`)}return(e.global?.removed.length??0)+(e.sentinel?.removed.length??0)+(e.project?.agentSetup.removed.length??0)===0&&n.push(e.dryRun?"No codebaseiq-owned files would be removed.":"No codebaseiq-owned files removed."),n}function Ei(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 Xc(e){let t=Ei(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=Ha({dryRun:e.dryRun,homeDir:e.homeDir}),n.sentinel=pa({dryRun:e.dryRun,...e.homeDir?{cacheRoot:Ft(e.homeDir,".cache","codebaseiq")}:{}})),t.project&&(n.project=Ch(e.projectRoot,{dryRun:e.dryRun})),n}function Ch(e,t={}){return{agentSetup:aa(e,{dryRun:t.dryRun}),left:kh(e)}}function kh(e){return[[".codebaseiq.json",Ft(e,".codebaseiq.json")],[ni,Ft(e,ni)],[".codebaseiq/suppressions/ (repository records)",Ft(e,".codebaseiq","suppressions")],["docs/codebaseiq/",Ft(e,"docs","codebaseiq")]].filter(([,t])=>Rh(t)).map(([t])=>t)}var Yc={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function Zc(e,t){let n=Eh(t);return{...e,warnings:[...e.warnings??[],Yc.note,...n],capabilities:t,scoreInterpretation:Yc}}function Eh(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 Th}from"crypto";import{basename as Lh,join as Ph}from"path";function il(e,t){let n=[t.id?`finding ${t.id}`:void 0,t.check?`check ${t.check}`:void 0,t.file?`file ${t.file}`:void 0].filter(o=>o!==void 0),i=t.decision;return[`Suppression ${e.disposition} at ${e.path}.`,` scope: ${n.join("; ")}`,` reason code: ${i?.reasonCode??"legacy/manual"}`,` counterevidence: ${i?.evidence.length??0} item(s)`,` expires: ${t.expiresAt??"none \u2014 no time limit; evidence invalidation still applies"}`,` revision: ${e.revision}`]}var Bt=class extends Error{constructor(n,i,o){super(`${n} ${o?`Current revision: ${o}. Retry with --replace ${o} after reviewing it.`:"The suppression file was left untouched."}`);this.path=i;this.currentRevision=o;this.name="SuppressionWriteConflictError"}path;currentRevision};function ol(e,t,n,i,o){if(!Xn.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${Xn.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let r=n.map(s=>Oh(e,s,i));return{kind:"automated-adjudication",reasonCode:t,decidedBy:"agent",policyVersion:1,...o?{observation:o}:{},evidence:r,invalidateOn:{targetContentChange:r.some(s=>s.contentHash!==void 0),detectorMajorChange:!0}}}function rl(e,t,n={}){let i=n instanceof Date?{now:n}:n,o=jh(t),r=Ih(i.expectedRevision),s=Ph(Jo(e),Qo(o)),a=i.now??new Date,c="unchanged",l=No(s,u=>{if(!u.revision.exists){if(r)throw new Bt(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:nl(el(o,void 0,a,i.toolVersion))}}let m=Ah(u);if(Nh(m.suppression,o))return c="unchanged",{kind:"unchanged"};if(!r)throw new Bt(`A different suppression decision already exists at ${s}.`,s,u.revision.hash);if(r!==u.revision.hash)throw new Bt(`Suppression ${s} changed after the revision you reviewed.`,s,u.revision.hash);return c="replaced",{kind:"write",text:nl(el(o,m.suppression,a,i.toolVersion))}},{maxRetries:0,onBeforeCommit:i.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function Ah(e){let t;try{t=JSON.parse(e.text)}catch(i){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:i})}let n=Yo(t,Dh(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function el(e,t,n,i=Ue){let o=n.toISOString(),{decision:r,createdAt:s,...a}=e,c={kind:Ho,suppressionIdentity:Xo(e),writer:{tool:"codebaseiq",version:i},...a,createdAt:t?.createdAt??s??o,...t?{updatedAt:o}:{}};return r?{...c,schemaVersion:zo,decision:r}:{...c,schemaVersion:Ko}}function jh(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),i=e.check?.trim();if(!n&&!i)throw new Error("suppression requires an id or a check");if(e.decision!==void 0&&!Io(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 Ih(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 Nh(e,t){return JSON.stringify(tl(e))===JSON.stringify(tl(t))}function tl(e){let{createdAt:t,...n}=e;return n}function Dh(e){let t=Lh(e);return t.endsWith(".json")?t.slice(0,-5):t}function nl(e){return`${JSON.stringify(e,null,2)}
|
|
19
|
+
`}function Oh(e,t,n){let i=t.indexOf(":");if(i<=0||i===t.length-1)throw new Error("--evidence must use <source|config|test|graph>:<referent>");let o=t.slice(0,i),r=t.slice(i+1).trim();if(o==="graph"){if(!r.startsWith("codebaseiq "))throw new Error("graph suppression evidence must name the exact codebaseiq command that produced it");return{kind:o,referent:r,claim:n}}if(o!=="source"&&o!=="config"&&o!=="test")throw new Error(`unsupported suppression evidence kind ${JSON.stringify(o)}`);let s=So(r),a=at(e,s);return{kind:o,referent:s,claim:n,contentHash:Th("sha256").update(a).digest("hex")}}import{execFileSync as Mh}from"child_process";var qh=500,Fh=1024*1024,Bh={changedPaths:Vh,indexedPaths:e=>rr(e,{includeIgnored:!1}),architectureFindings:e=>Pt(pn(e))},Wh=/\.(?:[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 al(e,t,n=Bh,i={}){let o=n.changedPaths(e);if(o.includes(".codebaseiq.json"))return{kind:"block",checkedSourceFiles:[],findings:[],reason:"Architecture policy changed in the same worktree as the implementation. Keep .codebaseiq.json policy changes in a separate reviewed change, then stop again."};let r=new Set(n.indexedPaths(t)),s=o.filter(u=>r.has(u)||Wh.test(u));if(s.length===0)return{kind:"allow",checkedSourceFiles:[],findings:[]};let a=i.indexGeneration?{indexGeneration:i.indexGeneration}:{},c=n.architectureFindings(t);if(c.length===0)return{kind:"allow",checkedSourceFiles:s,findings:[],...a};let l=i.indexGeneration?` from index generation ${i.indexGeneration} (may predate the latest edits)`:"";return{kind:"block",checkedSourceFiles:s,findings:c,...a,reason:`codebaseiq found ${c.length} enforced architecture violation(s)${l}:
|
|
20
20
|
${c.map(u=>`- ${u}`).join(`
|
|
21
21
|
`)}
|
|
22
22
|
|
|
23
|
-
Inspect the boundary graph with: codebaseiq architecture`}}function
|
|
24
|
-
`);return}
|
|
23
|
+
Inspect the boundary graph with: codebaseiq architecture`}}function cl(e,t={}){if(e.isTTY)return Promise.resolve({stopHookActive:!1});let n=t.maxBytes??Fh;return new Promise(i=>{let o=[],r=0,s=!1,a=()=>{s||(s=!0,clearTimeout(l),e.removeListener("data",c),e.removeListener("end",a),e.removeListener("error",a),e.pause(),i(_h(Buffer.concat(o).toString("utf8"))))},c=u=>{let m=Buffer.from(u);r+=m.byteLength,r>n?a():o.push(m)},l=setTimeout(a,t.timeoutMs??qh);e.on("data",c),e.on("end",a),e.on("error",a)})}function _h(e){try{let t=JSON.parse(e);return{stopHookActive:(typeof t=="object"&&t!==null&&t.stop_hook_active)===!0}}catch{return{stopHookActive:!1}}}function ll(e){return e.kind==="block"?{decision:"block",reason:e.reason}:{}}function Vh(e){let t=sl(e,["diff","--name-only","--diff-filter=ACMRTUXB","HEAD","--"]),n=sl(e,["ls-files","--others","--exclude-standard","--"]);return[...new Set([...t,...n])].sort()}function sl(e,t){try{return Mh("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:15e3,maxBuffer:10*1024*1024,killSignal:"SIGKILL"}).split(/\r?\n/u).map(n=>n.trim()).filter(Boolean)}catch(n){throw new Error(`Could not inspect changed files for the architecture Stop hook: ${Gh(n)}`,{cause:n})}}function Gh(e){return e instanceof Error?e.message:String(e)}import{existsSync as Uh}from"fs";var Hh=new Set(["unreachable","misconfigured","degraded"]);async function dl(e,t={}){let{projectRoot:n,config:i}=e;try{let o=mt(n,i),{paths:r,dbPath:s}=ge(n),a=t.openIndex??(()=>Uh(s)?tr(n):void 0),c,l="no index yet; run codebaseiq reindex";try{c=a()}catch(g){l=`the index could not be opened: ${g instanceof Error?g.message:String(g)}`}let u=[];if(c===void 0)for(let g of o.endpoints)u.push({provider:`embeddings:${g.name}`,state:"skipped",detail:l});let m=Rn({settings:c===void 0?{...o,endpoints:[]}:o,storeRoot:xn(r.cacheDir),languages:i.languages??[],openDb:()=>c,...t.env?{env:t.env}:{}});try{u.push(...await m.providerStatus())}finally{m.close(),c?.close()}return Kh(u)}catch(o){return{lines:[],warnings:[`the symbol builder providers could not be checked: ${o instanceof Error?o.message:String(o)}`]}}}function Kh(e){return e.length===0?{lines:["(no providers configured)"],warnings:[]}:{lines:e.map(t=>`${t.provider} ${t.state}: ${t.detail}`),warnings:e.filter(t=>Hh.has(t.state)).map(t=>`${t.provider} is ${t.state}; reuse cannot use it until that is fixed`)}}import{existsSync as Ti}from"fs";import{delimiter as zh,join as Jh}from"path";var Qh=()=>({cliVersion:Ue,cacheRoot:$o(),env:process.env,isProcessAlive:ha,readRecord:(e,t)=>{try{return ga(e,ma(t))}catch{return}}});function ul(e,t,n,i={}){let o={...Qh(),...i},r=hn(e,{cacheRoot:o.cacheRoot}),s=t.sentinel?.enabled===!0;if(!s&&r.hosts.every(S=>S.events.length===0))return;let a=[],{version:c,cliTarget:l}=r.binary,u={path:r.binary.script,present:r.binary.present,...c?{version:c}:{},matchesCli:r.binary.present&&c===o.cliVersion,...l?{cliTarget:l}:{}},m=u.present&&l!==void 0&&Ti(l);u.present?(u.matchesCli||a.push(`the hook binary is version ${c??"unknown"} but the CLI is ${o.cliVersion}; run codebaseiq setup to refresh it`),s&&!m&&a.push(l?`the hook binary starts the service with ${l}, which does not exist; run codebaseiq setup`:"the hook binary records no CLI to start the service with; run codebaseiq setup")):a.push(`the hook binary is missing at ${u.path}; run codebaseiq setup`);let g=Yh("node",o.env);g||a.push("node was not found on PATH; Claude Code starts the hooks as `node`");let p=r.hosts.map(S=>Xh(S));for(let S of r.hosts){S.events.length===0&&s?a.push(`${S.host} hooks are not installed in ${S.file}; run codebaseiq setup`):S.events.length>0&&S.missing.length>0&&a.push(`${S.host} hooks lack ${S.missing.join(", ")} in ${S.file}; run codebaseiq setup`);for(let L of S.scripts.filter(B=>!Ti(B)))a.push(`${S.host} hooks point at ${L}, which does not exist; run codebaseiq setup`)}s||a.push("sentinel hooks are installed but sentinel.enabled is not true, so they do nothing");let h=fn(e,{codexHome:o.codexHome}),f=h?.hooks.filter(S=>!S.trusted)??[];h&&f.length>0&&a.push(`${f.length} of ${h.hooks.length} Codex hooks are not approved in ${h.configPath}; open Codex once in this project and approve them`);let b=o.readRecord(o.cacheRoot,e),v=b!==void 0&&o.isProcessAlive(b.pid);return{enabled:s,binary:u,node:{found:g!==void 0,...g?{path:g}:{}},hosts:p,...h?{codex:{configPath:h.configPath,approved:h.hooks.length-f.length,unapproved:f.map(S=>S.event)}}:{},service:{running:v,startable:m,...b&&v?{pid:b.pid,version:b.serviceVersion,versionMatches:b.serviceVersion===o.cliVersion}:{}},delivery:bn(n),warnings:a}}function Xh(e){return{host:e.host,file:e.file,installed:e.events.length>0&&e.missing.length===0,events:e.events,missing:e.missing}}function pl(e){let t=Object.entries(e.delivery).map(([o,r])=>`${o}=${r}`).join(", "),n=[` Sentinel: ${e.enabled?"enabled":"disabled"} (delivery ${t})`];n.push(` Hook binary: ${e.binary.path}${e.binary.present?` (version ${e.binary.version??"unknown"})`:" (missing)"}`);for(let o of e.hosts){let r=o.installed?"installed":o.events.length>0?"incomplete":"not installed",s=o.host==="codex"&&e.codex?`; ${e.codex.approved} of ${e.codex.approved+e.codex.unapproved.length} approved in Codex (presence check only; Codex may still ask to re-approve a changed hook)`:"";n.push(` ${o.host} hooks: ${r}${s}`)}let i=e.service.startable?", restarts on the next agent session":"";e.service.running?n.push(` Service: running (pid ${e.service.pid}, version ${e.service.version}${e.service.versionMatches?"":`; differs from the CLI${i}`})`):e.enabled?e.service.startable?n.push(" Service: not running: starts on the next agent session"):n.push(" Service: not running: no hook can start it; run codebaseiq setup"):n.push(" Service: not running");for(let o of e.warnings)n.push(` WARN ${o}`);return n}function Yh(e,t,n=process.platform){let i=(t.PATH??t.Path??"").split(zh).filter(Boolean),o=n==="win32"?(t.PATHEXT??".EXE;.CMD").split(";").filter(Boolean):[""];for(let r of i)for(let s of o){let a=Jh(r,`${e}${s}`);if(Ti(a))return a}}var Zh=new Set($t);async function bl(...e){if((await cl(process.stdin)).stopHookActive){process.stdout.write(`${JSON.stringify({})}
|
|
24
|
+
`);return}ef(...e)}var ef=X(({db:e})=>{try{let t=pe(),n=ca("hook-architecture-stop",Ae(t)),i=al(t,e,void 0,n?{indexGeneration:e.generation.identity.slice(0,12)}:{});process.stdout.write(`${JSON.stringify(ll(i))}
|
|
25
25
|
`)}catch(t){let n=`codebaseiq 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})}
|
|
26
|
-
`)}});function
|
|
27
|
-
${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function
|
|
26
|
+
`)}});function tf(e){return e.filter(t=>Zh.has(t))}async function yl(e){let t=re(e),n=pe(),i=Ae(n),o=wt(n,i),r=y(t,"json");try{let s=tf(A(t,"language")),a=await _a(n,i,o,{languages:s.length>0?s:i.languages,force:y(t,"force"),allowPartial:y(t,"allowPartial"),skipAutoInstall:process.env.CODEBASEIQ_SKIP_AUTO_INSTALL==="1",installMissing:y(t,"installMissing"),trustProjectTools:y(t,"trustProjectTools"),indexerConcurrency:K(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"codebaseiq reindex"},...r?{onStatus:()=>{}}:{onStatus:console.log}});if(r){P("reindex",[],t,a);return}if(a.skipped.length>0){let c=a.languages.length>0?a.languages.join(", "):"none";console.log(`Reindex partial: available language output ${c}; ${a.skipped.length} skipped in ${(a.durationMs/1e3).toFixed(1)}s.`);for(let l of a.skipped)console.log(` skip: ${l.language} \u2014 ${l.reason}`)}else console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){if(console.error(`error: ${s instanceof Error?s.message:s}`),process.env.CODEBASEIQ_DEBUG)for(let a=s;a instanceof Error;a=a.cause)console.error(a.stack??a.message),a.cause instanceof Error&&console.error("caused by:");process.exit(1)}}function vl(){let e=pe(),t=ii(e);try{let n=Aa({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Sl(e){let t=re(e),n=pe(),i=ii(n);try{let o=await qa({projectRoot:n,dbPath:i,tsconfig:$(t,"project")??"frontend/tsconfig.scip.json",onStatus:r=>console.log(r)});console.log(`Vue files: ${o.vueFiles}; resolved references: ${o.resolvedReferences}; inserted mentions: ${o.insertedMentions}; not-inserted identifier tokens: ${o.skippedReferences}; synthetic symbols: ${o.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${o.skippedReferenceReasons["no-definition"]}; same-file definition ${o.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${o.skippedReferenceReasons["unindexed-definition"]}; missing source ${o.skippedReferenceReasons["missing-source-file"]}; missing service script ${o.skippedReferenceReasons["missing-service-script"]}. Samples: ${o.skippedReferenceSamples.length} omitted, ${o.resolvedReferenceSamples.length} resolved.`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function $l(e){let t=re(e);Ee(n=>{let i=JSON.parse(process.env.CODEBASEIQ_DIFF_IMPACT_FILES??"[]"),o=gs(n,{base:$(t,"base")}),r=hs(n,i,o.changedFiles,o.changedRanges);ci(jt,r)})}async function wl(e){let t=re(e);try{let n=await ia({base:$(t,"base")});if(y(t,"json")){P("diff-impact",[],t,n.result,{observationReceipt:n.observationReceipt});return}oa(n.result)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function xl(e,t){let n=re(t),i=String(e).split(",").filter(o=>o.length>0);Ee(o=>{let r=[];for(let c of i)Ws.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),r.push(c);let s={scope:$(n,"scope"),full:y(n,"full")},a=r.length===1?_s(o,r[0],s):Vs(o,r,s);ci(At,a)})}async function Rl(e){let t=re(e);if(y(t,"writeBaseline")||y(t,"baseline")){nf(t);return}try{let n=await ta({scope:$(t,"scope"),full:y(t,"full"),json:y(t,"json")}),{projectRoot:i,config:o,dbPath:r}=ge(),s=ht(Be(i,o),{hasIndexedGraph:Wt(r)}),a=Zc(n.result,s);if(y(t,"json")){P("health",[],t,a,{observationReceipt:n.observationReceipt});return}na(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function nf(e){let t=$(e,"scope");Ee(n=>{if(y(e,"writeBaseline")){let o=Ms(n,{scope:t});console.log(`Baseline written to ${o.path} (${o.findingCount} finding(s)).`);return}let i=qs(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let o of i.newFindings)console.log(` + ${o}`);process.exitCode=1})}function Cl(){let e=Tn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
27
|
+
${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function kl(){let e=!1,t=pe(),n=Ae(t),i=Be(t,n);if(i.languages.length===0){console.log(`
|
|
28
28
|
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
29
29
|
Detected languages: ${i.languages.join(", ")}`),console.log(`
|
|
30
|
-
Indexer readiness:`);for(let r of i.indexers){let s=r.runnable?" OK":r.installed?" WARN":" MISSING",a=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${s} ${r.language}: ${r.binaryLabel}${a}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}let o=
|
|
31
|
-
Semantic provider readiness:`);for(let r of o){let s=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${r.language}: ${
|
|
30
|
+
Indexer readiness:`);for(let r of i.indexers){let s=r.runnable?" OK":r.installed?" WARN":" MISSING",a=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${s} ${r.language}: ${r.binaryLabel}${a}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}let o=Wl(i);o.length>0&&console.log(`
|
|
31
|
+
Semantic provider readiness:`);for(let r of o){let s=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${r.language}: ${hf(r)}${_l(r)}`),r.reason&&console.log(` ${r.reason}`)}process.exitCode=e?1:0}function El(e){of(e)}function of(e){let t=re(e),{projectRoot:n,config:i,paths:o,dbPath:r}=ge(),s=Be(n,i),a=ct(n,i,o),c=ht(s,{hasIndexedGraph:Wt(r)&&a.state!=="missing"});if(y(t,"json")){P("capabilities",[],t,{...c,explorationControls:mn,relationshipQuestions:wn(),unavailableRelationshipFrontiers:un});return}Sf(c,{matrix:y(t,"matrix")})}function Tl(){let e=pe(),t=nn(e),n=Do(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 Ll(e){let t=re(e),n=pe(),i=Ae(n),o=Zo(n),r=[...st(i,{projectRoot:n}),...o.compatibility.issues.map(s=>({level:"error",path:s.path,message:s.reason}))];if(y(t,"json"))P("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let s of r)console.log(`${s.level.toUpperCase()} ${s.path}: ${s.message}`);r.some(s=>s.level==="error")&&(process.exitCode=1)}function Pl(e,t){let n=re(t),i=$(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let o=$(n,"reasonCode"),r=A(n,"evidence");if(!o||r.length===0){console.error("error: suppress requires --reason-code <code> and at least one --evidence <source|config|test|graph>:<referent> so automatic adjudication has inspectable counterevidence."),process.exitCode=1;return}try{let s=pe(),a=(()=>{try{return Ee(()=>Zs())}catch{return}})(),c={id:String(e),check:$(n,"check"),file:$(n,"file"),reason:i,expiresAt:$(n,"expiresAt"),decision:ol(s,o,r,i,a)},l=rl(s,c,{expectedRevision:$(n,"replace")});if(y(n,"json")){P("suppress",[String(e)],n,l);return}for(let u of il(l,c))console.log(u)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}var ml={builderStatus:dl};async function Al(e){let t=re(e),{report:n,hasIndexerProblems:i,hasErrors:o}=jl("doctor"),r=Ae(n.projectRoot),s=ul(n.projectRoot,r,Pi(n.configuredDbPath)),a=ml.builderStatus?await ml.builderStatus({projectRoot:n.projectRoot,config:r}):void 0;if(y(t,"json"))P("doctor",[],t,{...n,...s?{sentinel:s}:{},...a?{builder:a}:{}});else{if(df(n,i),s)for(let c of pl(s))console.log(c);if(a){console.log(" Symbol builder:");for(let c of a.lines)console.log(` ${c}`);for(let c of a.warnings??[])console.log(` WARN ${c}`)}}process.exitCode=o?1:0}function jl(e){let{projectRoot:t,config:n,paths:i,dbPath:o}=ge(),r=st(n,{projectRoot:t}),s=Be(t,n),a=ct(t,n,i),c=Wt(o),l=ht(s,{hasIndexedGraph:c&&a.state!=="missing"}),u=Wa(t,n,i),m=s.indexers.some(h=>!h.runnable),g=r.some(h=>h.level==="error")||m||a.state==="missing"||a.state==="stale",p=r.some(h=>h.level==="error")||m||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:o,configuredDbPath:i.dbPath,exists:c,configDiagnostics:r,readiness:s,freshness:a,capabilities:l,sharedCache:u,ok:!g},hasIndexerProblems:m,hasErrors:p}}function Il(e){re(e);let t=pe(),n=gn(t);for(let o of n.written)console.log(` done: ${o}`);for(let o of n.unchanged)console.log(` ok: ${o} (already wired)`);for(let o of n.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);let i=sa(n);i.verdict==="ready"?console.log(`
|
|
32
32
|
Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
|
|
33
33
|
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(`
|
|
34
|
-
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
|
|
35
|
-
`);let m=l?await
|
|
36
|
-
Reindex complete in ${(
|
|
37
|
-
Watch warning: suppressed-refresh telemetry was not recorded: ${
|
|
38
|
-
Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:
|
|
39
|
-
Watch error: ${
|
|
40
|
-
`),H.start();let j=!1,
|
|
41
|
-
Unable to stop safely: ${
|
|
42
|
-
Stopped.`),process.exit(0)}))};process.on("SIGINT",_),process.on("SIGTERM",_)}function Bl(e,t=!0){let{classification:n}=e,i=va(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 pf(n)}}function Wl(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),bl(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${si(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${he(n.estimatedWriteBytes??n.estimatedLogicalOutputBytes)} estimated writes (${he(n.estimatedLogicalOutputBytes)} logical output)${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),(n.reflinkedBytes!==void 0||n.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${he(n.reflinkedBytes??0)} reflinked, ${he(n.fallbackCopiedBytes??0)} byte-copied`);for(let[i,o]of Object.entries(n.byLanguage??{}).sort(([r],[s])=>r.localeCompare(s)))o&&console.log(`Reindex language ${i}: ${o.runs} run(s) (${o.rebuilt} rebuilt, ${o.reused} reused), ${he(o.producedOutputBytes)} produced, ${Sf(o.durationMs)} cumulative indexer time`);n.languageAttribution&&n.languageAttribution!=="complete"&&console.log(`Reindex language attribution: ${n.languageAttribution}; ${n.unattributedRuns??0} completed run(s) unattributed, ${n.invalidLanguageDetails??0} invalid detail(s) ignored`),n.confidence&&n.confidence!=="complete"&&console.log(`Reindex evidence: ${n.recordsRead??0} record(s) read, ${n.invalidRecords??0} invalid, ${n.readErrors??0} read error(s), ${n.ignoredPartialTailBytes??0} incomplete byte(s) ignored`)}if("refreshRequests"in e&&e.refreshRequests&&bl(e.refreshRequests),"typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function bl(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function pf(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function _l(e){let t=re(e),{report:n}=Dl("status"),i=et(Ae(n.projectRoot)).enabled,o=Bl(Sn({projectRoot:n.projectRoot,cacheDir:Ii(n.configuredDbPath),cliVersion:Ue}),i),r=Da(n.dbPath),s=zo(n.dbPath,n.freshness.metaPath),a=Ko(n.dbPath),c=pn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(y(t,"json")){P("status",[],t,{...n,affectedSetShadow:r,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o,stats:$f(n.exists)});return}gf(n,{affectedSetShadow:r,capabilities:y(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o})}function mf(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})`:""}`),Vl(e.capabilities)}function gf(e,t){console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`);for(let n of Gl(e.readiness)){let i=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",o=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${o.padEnd(9)}${i}${Ul(n)}`),n.reason&&console.log(`${n.language} note: ${n.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${vf(e.freshness.lastRefresh)}`),Wl(t.watchService),hf(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"),ff(t.sqliteGeneration),bf(t.localGenerations),console.log(`Shadow: ${Oa(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),wf(e.exists),t.capabilities&&(console.log(""),Vl(e.capabilities),console.log("Run `codebaseiq capabilities` for the semantic control manual."))}var yl=new Set(["symbol-builder","sentinel"]);function Vl(e){let t=e.capabilities.filter(r=>!yl.has(r.id)),n=e.capabilities.filter(r=>yl.has(r.id)),i=vl(t),o=vl(e.relations);console.log(` Languages: ${e.languages.join(", ")||"(none detected)"}`),console.log(` Analysis readiness: ${i.available} available, ${i.partial} partial, ${i.unavailable} unavailable`),n.length>0&&console.log(` Agent integrations: ${n.map(r=>`${r.label} ${r.status}`).join(", ")}`),console.log(` Relationship providers: ${o.available} available, ${o.partial} partial, ${o.unavailable} unavailable`)}function vl(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 hf(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), ${he(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${he(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${he(e.cleanup.deletedBytes??0)} removed`)}function ff(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",i=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(o=>o!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${i})`),console.log(`DB layout: ${e.generation.artifactSet==="immutable-v1"?"immutable artifact set; stable paths are mirrors":"legacy stable paths"}`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function bf(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${he(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${he(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 Gl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function yf(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Ul(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function vf(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 Sf(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function $f(e){if(e)return Ee(t=>{let n=Et(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function wf(e){e&&Ee(t=>{let n=Et(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${he(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function xf(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
|
|
43
|
-
Primary controls:`);for(let n of
|
|
44
|
-
Relationship controls:`);for(let n of
|
|
45
|
-
Strengths: ${Object.keys(Lt).join(", ")}. Unavailable analyses: ${
|
|
46
|
-
The agent chooses a question, family, and direction; this command reports support and does not infer intent.`),!t.matrix){console.log("Run `codebaseiq capabilities --matrix` only when a named claim needs contract or provider details.");return}
|
|
47
|
-
Control contracts:`);for(let t of
|
|
48
|
-
Relationship contracts:`);for(let t of
|
|
34
|
+
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 Nl(e){let t=re(e);try{let n=y(t,"guided"),i=y(t,"yes"),o=y(t,"json");Mc({guided:n,yes:i,json:o,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let r=y(t,"installMissing"),s={dossierDir:$(t,"dossierDir"),runHealth:i?!1:t.health!==!1,installSkills:t.skills!==!1,installIndexers:r,installAstParsers:r&&t.parsers!==!1,...i?{automaticRefresh:!0}:{},builderMode:$(t,"builderMode"),embeddingsEndpoints:A(t,"embeddingsEndpoint"),embeddingsModel:$(t,"embeddingsModel"),agentCommand:$(t,"agentCommand"),builderScope:$(t,"builderScope"),sentinel:typeof t.sentinel=="boolean"?t.sentinel:void 0,sentinelLive:$(t,"sentinelLive")??y(t,"sentinelLive")},a=!o&&!i&&process.stdin.isTTY&&process.stdout.isTTY;(n||a)&&(s=await rf(s,{json:o})),o||(s.onStatus=l=>console.log(` ${l}`));let c=await Fc(s);o?P("setup",[],t,c):Bc(c),process.exitCode=c.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function rf(e,t){let{projectRoot:n,config:i}=ge(),o=Be(n,i),r=qc({files:sf(n),watchEnabled:et(i).enabled,readiness:o}),s=o.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=r.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=wi(o.languages),l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,u=l?await Kc(ki):{};a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes codebaseiq workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],...l?zc(u,e):[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1}),l&&console.log(`${Hc}
|
|
35
|
+
`);let m=l?await _c([...s,...a]):new Set([...af(r.actions),...s.map(f=>f.id)]);l&&cf(r.actions,m);let g=m.has("create-agent-guidance")||m.has("update-agent-guidance"),p=r.actions.some(f=>f.id==="enable-automatic-refresh"),h=r.actions.some(f=>f.id==="install-indexers");return{...Jc(e,u,m),...p?{automaticRefresh:m.has("enable-automatic-refresh")}:{},noAgentGuidance:!g,...h?{installIndexers:l?m.has("install-indexers"):e.installIndexers===!0}:{},languages:o.languages.filter(f=>m.has(`language:${f}`)),installSkills:m.has("install-agent-skills"),installAstParsers:l?m.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:m.has("run-health-analysis")}}function sf(e){return{agentsMd:Wt(Li(e,"AGENTS.md")),claudeMd:Wt(Li(e,"CLAUDE.md"))}}function af(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function cf(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let i=e.filter(r=>r.scope===n&&t.has(r.id)).map(r=>r.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${i.length>0?i.join(", "):"none"}`)}}function Dl(e){let t=re(e),n=Ei({global:y(t,"global"),project:y(t,"project"),dryRun:y(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let i=Xc({projectRoot:pe(),global:n.global,project:n.project,dryRun:y(t,"dryRun")});if(y(t,"json")){P("uninstall",[],t,i);return}for(let o of Qc(i,{verbose:y(t,"verbose")}))console.log(o)}function Ol(e){let t=re(e),n=pe(),i=Ae(n),o=K(t,"debounce"),r=K(t,"cooldown"),s=K(t,"gitPoll"),a=K(t,"idleTimeout"),c=y(t,"daemon"),l=y(t,"status"),u=y(t,"stop"),m=y(t,"json"),g=[c,l,u].filter(Boolean).length;if(g>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(m&&g===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let h=[["--debounce",o],["--cooldown",r],["--git-poll",s],["--idle-timeout",a]].filter(([,w])=>w!==void 0);if((l||u)&&h.length>0){console.error(`error: timing options (${h.map(([w])=>w).join(", ")}) only apply when starting a foreground or daemon watcher; --status and --stop do not accept them.`),process.exitCode=1;return}let f=[["--debounce",o,!1],["--cooldown",r,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,w,_])=>w!==void 0&&(!Number.isInteger(w)||(_?Number(w)<0:Number(w)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let b={...o===void 0?{}:{debounceMs:o},...r===void 0?{}:{cooldownMs:r},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};o&&((i.watch??={}).debounceMs=o),r!==void 0&&((i.watch??={}).cooldownMs=r),s&&((i.watch??={}).gitPollMs=s),a!==void 0&&((i.watch??={}).idleTimeoutMs=a);let v=et(i);i.watch=v;let S=wt(n,i),L={projectRoot:n,cacheDir:S.cacheDir,cliVersion:Ue,watchOverrides:b};if(l){let w=Ml(yn(L),v.enabled);m?P("watch",[],t,w):ql(w);return}if(u){try{let w=ba(L);m?P("watch",[],t,w):console.log(w.disposition==="stopped"?`Stopped watch service${w.pid?` (pid ${w.pid})`:""}.`:"Watch service is already stopped.")}catch(w){console.error(`error: ${w instanceof Error?w.message:String(w)}`),process.exitCode=1}return}if(!v.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .codebaseiq.json to start it.'),process.exitCode=1;return}if(c){try{if(h.length>0){let _=yn(L);if(_.classification.kind==="live")throw new Error(`watch service pid ${_.classification.state.pid} is already running. Timing options only apply when the process starts; run "codebaseiq watch --stop", then repeat this daemon command.`)}let w=vn(L);m?P("watch",[],t,w):(console.log(`${w.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${w.state.pid}).`),h.length>0&&console.log(`Process-local timing overrides: ${h.map(([_,U])=>`${_}=${U}`).join(", ")}. These were not written to .codebaseiq.json.`))}catch(w){console.error(`error: ${w instanceof Error?w.message:String(w)}`),process.exitCode=1}return}let B=ya(Li(Pi(S.dbPath),yo),n);if(!B.acquired){console.error(B.message),process.exitCode=1;return}let H=new Pn({projectRoot:n,config:i,outputDb:S.dbPath,languages:i.languages,onStatus:w=>{process.stdout.write(`\r\x1B[K${nr(oi(w))}`)},onReindexComplete:w=>(console.log(`
|
|
36
|
+
Reindex complete in ${(w/1e3).toFixed(1)}s`),ct(n,i,S).state==="fresh"),onRefreshSuppressed:w=>{let _=Da(S.dbPath,w);_.state==="failed"&&console.error(`
|
|
37
|
+
Watch warning: suppressed-refresh telemetry was not recorded: ${_.reason}`),console.log(`
|
|
38
|
+
Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:w=>{console.error(`
|
|
39
|
+
Watch error: ${w.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${v.debounceMs}ms | Cooldown: ${v.cooldownMs}ms | Git poll: ${v.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
|
|
40
|
+
`),H.start();let j=!1,W=()=>{j||(j=!0,H.stop().then(w=>{if(w.state==="degraded"){j=!1,console.error(`
|
|
41
|
+
Unable to stop safely: ${w.reasons.join("; ")}`);return}B.release(),console.log(`
|
|
42
|
+
Stopped.`),process.exit(0)}))};process.on("SIGINT",W),process.on("SIGTERM",W)}function Ml(e,t=!0){let{classification:n}=e,i=fa(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 lf(n)}}function ql(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),gl(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${oi(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${he(n.estimatedWriteBytes??n.estimatedLogicalOutputBytes)} estimated writes (${he(n.estimatedLogicalOutputBytes)} logical output)${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),(n.reflinkedBytes!==void 0||n.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${he(n.reflinkedBytes??0)} reflinked, ${he(n.fallbackCopiedBytes??0)} byte-copied`);for(let[i,o]of Object.entries(n.byLanguage??{}).sort(([r],[s])=>r.localeCompare(s)))o&&console.log(`Reindex language ${i}: ${o.runs} run(s) (${o.rebuilt} rebuilt, ${o.reused} reused), ${he(o.producedOutputBytes)} produced, ${bf(o.durationMs)} cumulative indexer time`);n.languageAttribution&&n.languageAttribution!=="complete"&&console.log(`Reindex language attribution: ${n.languageAttribution}; ${n.unattributedRuns??0} completed run(s) unattributed, ${n.invalidLanguageDetails??0} invalid detail(s) ignored`),n.confidence&&n.confidence!=="complete"&&console.log(`Reindex evidence: ${n.recordsRead??0} record(s) read, ${n.invalidRecords??0} invalid, ${n.readErrors??0} read error(s), ${n.ignoredPartialTailBytes??0} incomplete byte(s) ignored`)}if("refreshRequests"in e&&e.refreshRequests&&gl(e.refreshRequests),"typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function gl(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function lf(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Fl(e){let t=re(e),{report:n}=jl("status"),i=et(Ae(n.projectRoot)).enabled,o=Ml(yn({projectRoot:n.projectRoot,cacheDir:Pi(n.configuredDbPath),cliVersion:Ue}),i),r=ja(n.dbPath),s=Uo(n.dbPath,n.freshness.metaPath),a=Go(n.dbPath),c=dn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(y(t,"json")){P("status",[],t,{...n,affectedSetShadow:r,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o,stats:yf(n.exists)});return}uf(n,{affectedSetShadow:r,capabilities:y(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o})}function df(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})`:""}`),Bl(e.capabilities)}function uf(e,t){console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`);for(let n of Wl(e.readiness)){let i=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",o=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${o.padEnd(9)}${i}${_l(n)}`),n.reason&&console.log(`${n.language} note: ${n.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${ff(e.freshness.lastRefresh)}`),ql(t.watchService),pf(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"),mf(t.sqliteGeneration),gf(t.localGenerations),console.log(`Shadow: ${Ia(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),vf(e.exists),t.capabilities&&(console.log(""),Bl(e.capabilities),console.log("Run `codebaseiq capabilities` for the semantic control manual."))}var hl=new Set(["symbol-builder","sentinel"]);function Bl(e){let t=e.capabilities.filter(r=>!hl.has(r.id)),n=e.capabilities.filter(r=>hl.has(r.id)),i=fl(t),o=fl(e.relations);console.log(` Languages: ${e.languages.join(", ")||"(none detected)"}`),console.log(` Analysis readiness: ${i.available} available, ${i.partial} partial, ${i.unavailable} unavailable`),n.length>0&&console.log(` Agent integrations: ${n.map(r=>`${r.label} ${r.status}`).join(", ")}`),console.log(` Relationship providers: ${o.available} available, ${o.partial} partial, ${o.unavailable} unavailable`)}function fl(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 pf(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), ${he(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${he(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${he(e.cleanup.deletedBytes??0)} removed`)}function mf(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",i=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(o=>o!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${i})`),console.log(`DB layout: ${e.generation.artifactSet==="immutable-v1"?"immutable artifact set; stable paths are mirrors":"legacy stable paths"}`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function gf(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${he(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${he(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 Wl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function hf(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function _l(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function ff(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 bf(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function yf(e){if(e)return Ee(t=>{let n=Et(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function vf(e){e&&Ee(t=>{let n=Et(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${he(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function Sf(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
|
|
43
|
+
Primary controls:`);for(let n of mn)console.log(` ${n.stage.toUpperCase().padEnd(8)} codebaseiq ${n.command} [${n.outputCost}] \u2014 ${n.question}`);console.log(`
|
|
44
|
+
Relationship controls:`);for(let n of wn()){let o=e.relations.find(r=>r.family===n.family)?.status??"unsupported";console.log(` ${o.toUpperCase().padEnd(11)} ${n.family} ${n.direction} \u2014 ${n.question}`)}if(console.log(`
|
|
45
|
+
Strengths: ${Object.keys(Lt).join(", ")}. Unavailable analyses: ${un.map(n=>n.id).join(", ")}.`),console.log(`
|
|
46
|
+
The agent chooses a question, family, and direction; this command reports support and does not infer intent.`),!t.matrix){console.log("Run `codebaseiq capabilities --matrix` only when a named claim needs contract or provider details.");return}$f(e),wf(e)}function $f(e){console.log(`
|
|
47
|
+
Control contracts:`);for(let t of mn)console.log(` codebaseiq ${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(`
|
|
48
|
+
Relationship contracts:`);for(let t of wn()){let i=e.relations.find(o=>o.family===t.family)?.status??"unsupported";console.log(` ${i.toUpperCase().padEnd(11)} ${t.family} ${t.direction}`),console.log(` Establishes: ${t.establishes}`),console.log(` Strengths: ${t.evidenceStrengths.join(", ")||"none registered"}`),console.log(` Provider ceilings: ${t.supportCeilings.join(", ")||"none registered"}`),console.log(` Does not establish: ${t.nonClaim}`)}console.log(`
|
|
49
49
|
Evidence strength legend:`);for(let[t,n]of Object.entries(Lt))console.log(` ${t.toUpperCase().padEnd(11)} ${n}`);console.log(`
|
|
50
|
-
Explicitly unavailable relationship analyses:`);for(let t of
|
|
50
|
+
Explicitly unavailable relationship analyses:`);for(let t of un)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 wf(e){console.log(`
|
|
51
51
|
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(`
|
|
52
52
|
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(`
|
|
53
|
-
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}`)}}}async function
|
|
53
|
+
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}`)}}}async function Vl(){let e=pe(),{paths:t}=ge(e),n=await Va({projectRoot:e,cacheDir:t.cacheDir});if(n.kind!=="ok"){console.log(`state: ${n.kind}`),console.log(`reason: ${n.reason}`),process.exitCode=1;return}console.log("state: ok"),console.log(`roundTripMs: ${n.roundTripMs.toFixed(3)}`),console.log(`serverPid: ${n.pong.serverPid}`),console.log(`cliVersion: ${n.pong.cliVersion}`),n.pong.indexGeneration&&console.log(`indexGeneration: ${n.pong.indexGeneration}`)}var zl=["reuse","rework","compose"],ji=5,Jl=9e4,Rf=2147483647,Ai=64*1024,Cf=160,kf={reuse:"These match the probes by name or callees and no named blocker applies.",rework:"These are relevant, but a named blocker stops reuse as written.",compose:"These are part of the task: a probed call target, one concept of several, or a callee of a stronger candidate."},Ef={reuse:"These rank closest to the best vector hit and no named blocker applies.",rework:"These rank close to the best vector hit, but a named blocker stops reuse as written.",compose:"These are small utilities used across several files that rank near the best vector hit or score well on their own."};function Tf(e){return{term:A(e,"term"),name:A(e,"name"),calls:A(e,"calls"),param:A(e,"param"),returns:A(e,"returns"),kind:A(e,"kind"),probes:$(e,"probes"),mode:Gl(xt,$(e,"mode"),"--mode"),endpoint:$(e,"endpoint"),agent:$(e,"agent"),bucket:Gl(zl,$(e,"bucket"),"--bucket"),limit:D(e,"limit",ji),full:y(e,"full"),scope:$(e,"scope"),providers:y(e,"providers"),refreshEmbeddings:y(e,"refreshEmbeddings"),timeout:Math.min(E(e,"timeout",Jl),Rf)}}function Gl(e,t,n){if(t===void 0)return;let i=e.find(o=>o===t);if(!i)throw new Error(`${n} must be one of ${e.join(", ")}.`);return i}async function Lf(e,t){let n={terms:e.term.map(r=>r.split("|")),names:e.name,calls:e.calls,params:e.param,returns:e.returns,kinds:e.kind},i=Object.values(n).some(r=>r.length>0);if(e.probes===void 0)return i?Ul(ei(n)):null;if(i)throw new Error("--probes cannot be combined with --term, --name, --calls, --param, --returns, or --kind.");let o;try{o=JSON.parse(await t(e.probes))}catch(r){throw new Error(`--probes ${e.probes} is not readable JSON: ${r instanceof Error?r.message:r}`,{cause:r})}return Ul(ei(o))}function Ul(e){if(e.probes.kinds.length>0&&!Zn(e.probes))throw new Error("a --kind filter needs at least one --term, --name, --calls, --param or --returns");return e}async function Pf(e){if(e!=="-")return ke(e,{maxBytes:Ai,inputKind:"builder probes file"});let t=[],n=0;for await(let i of process.stdin){let o=Buffer.from(i);if(n+=o.byteLength,n>Ai)throw new Error(`standard input is larger than ${Ai} bytes`);t.push(o)}return Buffer.concat(t).toString("utf8")}function Af(e,t){if(t.endpoint===void 0&&t.agent===void 0)return e;let n=e.endpoints.filter(o=>o.name===t.endpoint),i=e.agents.filter(o=>o.name===t.agent);if(t.endpoint!==void 0&&n.length===0)throw new Error(Hl("embeddings endpoint",t.endpoint,e.endpoints));if(t.agent!==void 0&&i.length===0)throw new Error(Hl("agent command",t.agent,e.agents));return{...e,mode:t.mode??(n.length>0&&i.length>0?"auto":n.length>0?"embeddings":"agent"),endpoints:n,agents:i,chain:[...n.map(o=>({kind:"embeddings",name:o.name})),...i.map(o=>({kind:"agent",name:o.name}))]}}function Hl(e,t,n){let i=n.map(o=>o.name).join(", ");return`No ${e} named "${t}" is configured${i?` (configured: ${i})`:""}.`}function jf(e,t){let n=["codebaseiq","reuse"],i=(o,r)=>{for(let s of r)n.push(o,ir(s,{omitSafeQuotes:!0,platform:"linux"}))};return i("--term",e.terms.map(o=>o.join("|"))),i("--name",e.names),i("--calls",e.calls),i("--param",e.params),i("--returns",e.returns),i("--kind",e.kinds),t.scope!==void 0&&i("--scope",[t.scope]),t.bucket!==void 0&&i("--bucket",[t.bucket]),t.full?n.push("--full"):t.limit!==ji&&i("--limit",[String(t.limit)]),n.join(" ")}function If(e,t){let{corpusUnits:n,embeddedUnits:i,note:o}=e.coverage,r=e.provider.startsWith("embeddings:")||e.candidates.some(l=>l.scoreBasis==="cosine")?Ef:kf,s=[`provider: ${e.provider}`];for(let l of e.fallbacksTried)s.push(` not used: ${l.provider} - ${l.reason}`);s.push(`coverage: ${n} candidate units${i===void 0?"":`, ${i} embedded`}${o?`; ${o}`:""}`);let a=[{title:"PROVIDER",rows:s}];e.probes&&a.push({title:"PROBES",rows:Nf(e,t.rerun)});for(let l of e.provider==="none"?[]:t.bucket?[t.bucket]:zl){let u=e.candidates.filter(m=>m.bucket===l);a.push({title:`${l.toUpperCase()} (${u.length})`,explanation:r[l],rows:u.length>0?u.flatMap(Df):["(none)"]})}t.diagnostics.length>0&&a.push({title:"PROBE DIAGNOSTICS",rows:t.diagnostics.map(l=>`${l.path||"probes"}: ${l.message}`)});let c=e.candidates[0];return c&&a.push({rows:[`Confirm a candidate before reusing it, for example: codebaseiq code ${c.file}:${c.line}`]}),a}function Nf(e,t){let n=e.probes,i=[];n.terms.length>0&&i.push(`terms: ${n.terms.map(o=>o.join("|")).join(", ")}`);for(let[o,r]of[["names",n.names],["calls",n.calls],["params",n.params],["returns",n.returns],["kinds",n.kinds]])r.length>0&&i.push(`${o}: ${r.join(", ")}`);for(let o of e.unresolvedProbes)i.push(`unresolved: ${o.probe} (${o.status})`);return t&&i.push(`rerun: ${t}`),i}function Df(e){let t=[`${e.name} ${e.file}:${e.line} [${e.tier}, ${e.scoreBasis} ${e.score}]`];e.signature&&t.push(` ${on(e.signature,Cf)}`);for(let n of e.why)t.push(` - ${n}`);return t}function Of(e){let t=Math.max(...e.map(i=>i.provider.length),8),n=(i,o,r,s)=>[i.padEnd(t),o.padEnd(12),r.padEnd(8),s].join(" ");return[n("PROVIDER","STATE","COVERAGE","DETAIL"),...e.map(i=>n(i.provider,i.state,i.coverage===void 0?"-":`${Math.round(i.coverage*100)}%`,i.detail))]}function Mf(e){let t=e.generation.metadataRaw;return(t?Ro(xo(t))?.indexedLanguages:void 0)??[]}function Kl(e){let t=[`${e.provider}: embedded ${e.embedded} new units, ${Math.round(e.coverage*100)}% of the corpus now has vectors`];return e.budgetExhausted&&t.push("stopped at the time budget; run again to continue"),e.note&&t.push(e.note),t.join("; ")}function qf(e){return e instanceof Error?e.message:String(e)}function Ff(e){let t=new AbortController,n=setTimeout(()=>t.abort(new Error(`reuse timed out after ${e} ms`)),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}async function Bf(...e){let{args:t,opts:n}=Sn(e),i=Tf(n),o=y(n,"json"),r=G(t,0)?.trim()||void 0,s=await Lf(i,Pf);if(r===void 0&&s===null&&!i.providers&&!i.refreshEmbeddings)throw new Error("Give a description, probes (--term, --name, --calls, --param, --returns, --kind or --probes), --providers, or --refresh-embeddings.");let a=ge(),c=Af(mt(a.projectRoot,a.config,i.mode?{mode:i.mode}:{}),i),l=er(),u;try{u=Rn({settings:c,storeRoot:xn(a.paths.cacheDir),languages:Mf(l),openDb:()=>l});let m=Ys({projectRoot:a.projectRoot,db:l,observedSourceKinds:["index-generation"]}),g=Ff(i.timeout),p;try{let{signal:b}=g;if(i.providers){let v=await u.providerStatus({signal:b});o?P("reuse",t,n,{providers:v},{observationReceipt:m}):T.sectionedReport([{title:"PROVIDERS",rows:Of(v)}]);return}if(i.refreshEmbeddings){let v=r===void 0&&s===null,S;try{S=await u.refreshEmbeddings({endpoint:i.endpoint,endsAt:Date.now()+i.timeout,signal:b})}catch(L){if(v||b.aborted)throw L;console.error(`embeddings refresh failed, continuing with the query: ${qf(L)}`)}if(S&&v){o?P("reuse",t,n,{refresh:S},{observationReceipt:m}):console.log(Kl(S));return}S&&console.error(Kl(S))}p=await u.query({description:r,probes:s?.probes,limit:i.limit,scope:i.scope,bucket:i.bucket},{signal:b})}finally{g.clear()}let h=s?.diagnostics??[];if(p.provider==="none"&&(process.exitCode=1),o){let b=h.length>0?{...p,probeDiagnostics:h}:p;P("reuse",t,n,b,{observationReceipt:m});return}je("symbol builder candidates");let f=p.probes&&Zn(p.probes)?jf(p.probes,i):null;T.sectionedReport(If(p,{bucket:i.bucket,rerun:f,diagnostics:h}))}finally{u?.close(),l.close()}}var Ql=[{id:"reuse",command:"reuse [description]",description:"Heuristic reuse candidates for code about to be written: existing symbols matching your probes or a described intent",helpAfter:`Pass probes you choose (--term, --name, --calls, --param, --returns, --kind, or --probes <file>) or a description.
|
|
54
54
|
A description is turned into probes by a configured agent command or ranked by an embeddings endpoint (the "builder" block of
|
|
55
|
-
.codebaseiq.json and .codebaseiq.local.json); inside an agent session pass probes instead. Use --providers to see which are available.`,options:C([d("--term <group>",'Concept group; "|" separates interchangeable words, as in retry|reattempt; repeat for more groups',F,[]),d("--name <identifier>","Identifier existing code might already use; repeat for more",F,[]),d("--calls <callee>","Function the new code would call; repeat for more",F,[]),d("--param <word>","Word expected in the parameter list; repeat for more",F,[]),d("--returns <word>","Word expected in the return type; repeat for more",F,[]),d("--kind <kind>","Restrict to function, method, class, interface, or type; repeat for more",F,[]),d("--probes <file>","Read probes as JSON from a file, or from standard input when the value is -"),d("--mode <mode>","Provider mode for a description: agent, embeddings, or auto"),d("--endpoint <name>","Use only this embeddings endpoint"),d("--agent <name>","Use only this agent command"),d("--bucket <bucket>","Show only reuse, rework, or compose candidates"),d("-n, --limit <n>","Candidates per bucket",ne,Di),d("--full","Return every candidate in each bucket instead of the first --limit"),d("-s, --scope <path>","Limit candidates to files matching path"),d("--providers","Show the state of each configured provider instead of searching"),d("--refresh-embeddings","Embed code that has no vector yet; with no description or probes, only refresh"),d("--timeout <ms>","Give up after this many milliseconds",ne,Yl)]),heuristic:{label:"symbol builder candidates"},budget:"candidate-scan",renderShape:"custom",agent:{...Ie("Does indexed code already provide, nearly provide, or help compose what I am about to write?","candidate symbols grouped as reuse, rework, or compose with file, line, signature, tier, and observed facts",["pattern"],"bounded","repository",ce,lt("Match caller-chosen probes, or the probes or vector ranking a configured provider derives from a description, against indexed definitions.","Candidate symbols bucketed by named blockers and importability, with the provider, its fallbacks, and its coverage.",["Candidates match the probes or the provider output; their order does not establish task relevance, behavioral equivalence, or the absence of other reusable code."],void 0,{outputCost:"bounded",frontierClosure:["code","evidence","inspect"]})),resultUnits:{kind:"field",field:"candidates"},contrasts:[{command:"similar",distinction:"similar compares callables that already exist; reuse starts from code you have not written yet."},{command:"search",distinction:"search finds exact text; reuse matches meaning through probes the caller chooses."}]},docs:R("Exploration",['codebaseiq reuse --term "retry|reattempt" --calls sleep --returns promise','codebaseiq reuse "retry a flaky request with backoff"',"codebaseiq reuse --providers"]),handler:Vf}];function Vt(e){return{...e,options:C(e.options)}}function Qe({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=Vt(l);return{...u,renderShape:"list",handler:ka({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c})}}function ed({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:u,...m}){let g=Vt(m);return{...g,renderShape:"table",handler:Ea({commandName:g.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:u})}}function td({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l,...u}){let m=Vt(u);return{...m,renderShape:"grouped-by-file",handler:Ta({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l})}}function Nn({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=Vt(l);return{...u,renderShape:"sectioned-report",handler:La({commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}function dt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=Vt(l);return{...u,budget:u.budget??"semantic",renderShape:"sectioned-report",handler:Pa(u.id,{commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}import{existsSync as Sb,mkdirSync as $b,writeFileSync as wb}from"fs";import{dirname as xb,relative as Rb}from"path";import{existsSync as Xe,readdirSync as zf}from"fs";import{basename as Jf,dirname as cd,isAbsolute as ld,join as Qf,relative as Xf,resolve as Gt,sep as Yf}from"path";import{spawnSync as Gf}from"child_process";import{dirname as Uf}from"path";function id(e){let n=(e.spawnSync??Gf)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:Uf(e.specPath),maxBuffer:1024*1024*32,windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let i=n.stdout??"";return i.includes("<?xml")?i:null}function od(e){let t=Kf(e),n=new Map,i=new Map,o=[],r=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?i.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(o.push(a),r.set(a.uid,a));let s=[];for(let a of o){let c=rd(a.block,n,i,r,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:o.map(a=>a.uniquename).sort(),actions:s}}var Hf=8;function Kf(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let i of e.matchAll(n)){let o=i.index,r=e.indexOf("</entry>",o),s=e.slice(o,r<0?e.length:r),a=Oi(s,"uniquename"),c=Oi(s,"kind"),l=Oi(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:nd(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:nd(l),block:s})}return t}function rd(e,t,n,i,o,r,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],u="read";for(let[,m,g]of l){if(m==="BuiltInKindRef"){let p=n.get(g)??"";p==="'"?u="write-next":p==="UNCHANGED"?u="unchanged-run":u==="unchanged-run"&&p==="$Tuple"||u!=="write-next"&&(u="read");continue}if(m==="OpDeclNodeRef"){let p=t.get(g);if(!p)continue;u==="write-next"?(c.add(p),u="read"):u==="unchanged-run"||a.add(p);continue}if(m==="UserDefinedOpKindRef"){u==="unchanged-run"&&(u="read");let p=i.get(g);if(p&&s<Hf&&!r.has(p.uid)&&p.filename===o){let h=rd(p.block,t,n,i,o,new Set([...r,p.uid]),s+1);for(let f of h.reads)a.add(f);for(let f of h.writes)c.add(f)}continue}u==="unchanged-run"&&(u="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function Oi(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function nd(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var dd=["update","insert","delete"],ud=["select","query","findFirst","findMany"],Mi=new Set([...dd,...ud]);function qi(e){let t=e.methods&&e.methods.length>0?e.methods:[...Mi],n=new Set(dd),i=new Set(ud);return{write:t.filter(o=>n.has(o)),read:t.filter(o=>i.has(o))}}var Zf=/^(.*)@L(\d+)-L(\d+)$/;function Fi(e){let t=e.match(Zf);if(!t)return{ref:e};let n=t[1],i=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return n?i<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:o<i?{error:`codeRef "${e}" line window end (L${o}) is before its start (L${i})`}:{ref:n,window:{startLine:i,endLine:o}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var eb=new Set(["auto","sany","tlc","apalache","none"]),On=/^[A-Za-z_][A-Za-z0-9_]*$/;function pd(e){return eb.has(e)}function Mn(e,t){let n=[],i=we(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!Xe(i))return{errors:[`map file not found: ${t}`]};let o;try{o=JSON.parse(ke(i,{inputKind:"TLA mapping",maxBytes:tn}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let r=tb(o,n);return r?{loaded:{contract:r,mapPath:i,mapDir:cd(i)},errors:n}:{errors:n}}function we(e,t){if(!t)return null;let n=ld(t)?Gt(t):Gt(e,t);return rt(e,n)?n:null}function md(e,t,n){if(!n)return null;if(ld(n)){let s=Gt(n);return rt(e,s)?s:null}let i=Gt(e,n);if(rt(e,i)&&Xe(i))return i;let o=Gt(t,n);if(rt(e,o)&&Xe(o))return o;let r=rt(e,i)?i:o;return rt(e,r)?r:null}function gd(e,t){let n=we(e,t);if(!n||!Xe(n))return null;let i=ke(n,{inputKind:"TLA module",maxBytes:ot});return{path:n,modelParse:"regex-fallback",text:i,variables:hb(i),operators:fb(i),actions:[]}}function hd(e,t,n){let i=we(e,t);if(!i||!Xe(i))return null;let o=ke(i,{inputKind:"TLA module",maxBytes:ot}),r=od(n);return{path:i,modelParse:"sany",text:o,variables:r.variables,operators:r.operators,actions:r.actions}}function Bi(e,t){let n=we(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Xe(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(ke(n,{inputKind:"TLA trace",maxBytes:ot})),o=Array.isArray(i)?i:ie(i)&&Array.isArray(i.steps)?i.steps:null;if(!o)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let r=[],s=[];for(let[a,c]of o.entries()){if(!ie(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}r.push({action:c.action,before:ie(c.before)?c.before:void 0,after:ie(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:r,errors:s}}catch(i){let o=i instanceof Error?i.message:String(i);return{steps:[],errors:[`trace file is not valid JSON: ${o}`]}}}function Wi(e,t){let n=new Set,i=[];for(let o of t){let r=we(e,o)??o;n.has(r)||(n.add(r),i.push(o))}return i}function tb(e,t){if(!ie(e))return t.push("map file must contain a JSON object"),null;let n=ab(e.variables,t);sb(n,t);let i=mb(e.actions,n,t),o=nb(e.init,t);ob(o,i,t);let r={module:ad(e.module,"module",t),config:ad(e.config,"config",t),scope:me(e.scope)??[],variables:n,actions:i,...o?{init:o}:{},invariants:me(e.invariants)??[],traces:me(e.traces)??[],unmappedWriteScope:rb(e.unmappedWriteScope,t)};return yb(e.scope,t),t.length===0?r:null}function nb(e,t){if(e===void 0)return;if(!ie(e)){t.push("init must be an object when present");return}let n=me(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=ib(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function ib(e,t){if(e===void 0)return;if(!ie(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function ob(e,t,n){if(!e)return;let i=new Set(e.codeRefs),o=new Set;for(let r of Object.values(t))for(let s of r.code)i.has(s)&&o.add(s);o.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...o].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function rb(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function sb(e,t){Dn(e,t,"alias",n=>n.aliases),Dn(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Dn(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),Dn(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:o,read:r}=qi(i);return[...o,...r].map(s=>`${i.table}:${s}`)}))}function Dn(e,t,n,i){let o=new Map;for(let[r,s]of Object.entries(e))for(let a of i(s)){let c=o.get(a);c?c.push(r):o.set(a,[r])}for(let[r,s]of o)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${r}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function ab(e,t){if(!ie(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[i,o]of Object.entries(e)){if(!On.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!ie(o)){t.push(`variables.${i} must be an object`);continue}let r=bd(o.code);if(!r||r.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=me(o.aliases)??[],a=lb(o.resource,i,t),c=db(o.statements,i,t),l=ub(o.ormCalls,i,t),u=pb(o.waive,i,t),m=cb(o.selfAlias,i,t),g=m?[...new Set([i,...s])]:[...new Set(s)];m===!1&&g.length===0&&!a&&!c&&!l&&!u&&t.push(`variables.${i}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${i} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${i}.waive with a reason`),n[i]={code:r,aliases:g,projection:typeof o.projection=="string"?o.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...u?{waive:u}:{},...m===!1?{selfAlias:!1}:{}}}return n}function cb(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function lb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.resource must be an object when present`);return}let i=typeof e.path=="string"?e.path.trim():"";if(!i){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:i}}function db(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.statements[${r}] must be an object`);return}let s=typeof o.pattern=="string"?o.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${r}].pattern must be a non-empty string`);return}try{on(s,`variables.${t}.statements[${r}].pattern`)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${r}].pattern is not a valid regular expression: ${c}`);return}i.push({pattern:s})}),i.length>0?i:void 0}function ub(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.ormCalls[${r}] must be an object`);return}let s=typeof o.table=="string"?o.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${r}].table must be a non-empty string`);return}if(o.methods===void 0){i.push({table:s});return}let a=me(o.methods);if(!a){n.push(`variables.${t}.ormCalls[${r}].methods must be an array of strings when present`);return}let c=a.filter(l=>!Mi.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${r}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...Mi].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function pb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.waive must be an object when present`);return}let i=typeof e.reason=="string"?e.reason.trim():"";if(!i){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:i}}function mb(e,t,n){if(!ie(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let i=new Set(Object.keys(t)),o={};for(let[r,s]of Object.entries(e)){if(!On.test(r)){n.push(`invalid TLA+ action name: ${r}`);continue}if(!ie(s)){n.push(`actions.${r} must be an object`);continue}let a=bd(s.code);if(!a||a.length===0){n.push(`actions.${r}.code must name at least one TypeScript referent`);continue}for(let g of a){let p=Fi(g);"error"in p&&n.push(`actions.${r}.code: ${p.error}`)}let c=me(s.reads)??[],l=me(s.writes)??[],u=me(s.calls)??[];for(let g of[...c,...l])i.has(g)||n.push(`actions.${r} references unknown variable: ${g}`);let m=gb(s.waive,s.allowUnknown===!0,c,l,i,r,n);o[r]={code:a,reads:c,writes:l,calls:u,...m?{waive:m}:{}}}return o}function gb(e,t,n,i,o,r,s){if(ie(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${r}.waive.reason must be a non-empty string`);let c=me(e.reads)??[],l=me(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${r}.waive must list reads or writes`),sd(r,"reads",c,o,s),sd(r,"writes",l,o,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${r}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(i)],reason:"legacy allowUnknown",legacy:!0}}function sd(e,t,n,i,o){for(let r of n)i.has(r)||o.push(`actions.${e}.waive.${t} references unknown variable: ${r}`)}function hb(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let i=n[1]??"";for(let o of i.split(",")){let r=o.trim();On.test(r)&&t.add(r)}}return[...t].sort()}function fb(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var bb=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function fd(e){if(!e||!Xe(e))return[];let t=ke(e,{inputKind:"TLA checker configuration",maxBytes:tn}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let o of t.split(/[\s,]+/))if(o){if(bb.has(o)){i=o==="INVARIANT"||o==="INVARIANTS";continue}i&&On.test(o)&&n.add(o)}return[...n].sort()}function ad(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function bd(e){return typeof e=="string"?[e]:me(e)}function yb(e,t){e!==void 0&&(me(e)||t.push("scope must be an array of strings when present"))}function qn(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var vb=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function yd(e,t){if(!Xe(t))return{status:"none"};let i=ke(t,{inputKind:"TLA module",maxBytes:ot}).match(vb)?.[1],o=Xf(e,t).split(Yf).join("/"),r=Jf(t),s=new Set([i,o,r,r.replace(/\.tla$/i,"")].filter(u=>!!u)),a=cd(t);if(!Xe(a))return{status:"none"};let c=[];for(let u of zf(a)){if(!u.endsWith(".scip-tla.json"))continue;let m=Qf(a,u),g;try{g=JSON.parse(ke(m,{inputKind:"TLA mapping candidate",maxBytes:tn}))}catch{continue}ie(g)&&typeof g.module=="string"&&s.has(g.module)&&c.push(m)}c.sort();let l=i??o;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function Fn(e,t,n,i,o={count:e.length,loc:i}){let r=o.count===e.length&&o.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${o.count}, ${i} of ${o.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${r}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let u=s.get(l.relativePath)??[];u.push(l),s.set(l.relativePath,u)}let a=[...s.entries()].map(([l,u])=>({file:l,bucket:u,totalLoc:u.reduce((m,g)=>m+g.loc,0)})).sort((l,u)=>u.totalLoc-l.totalLoc||l.file.localeCompare(u.file)),c=!0;for(let{file:l,bucket:u}of a){c||console.log(""),c=!1,console.log(` ${l}`),u.sort((m,g)=>m.startLine-g.startLine);for(let m of u){let g=m.implicitUsageReason?` [implicit usage: ${m.implicitUsageReason}]`:"";console.log(` ${fe(m.startLine,m.endLine)} (${m.loc} LOC) ${m.shortName}${g}`)}}}function Ut(e,t,n){if(n.rows.length>0)return;let i=Ht(n.coverage);return i?`No ${e} could be ranked with complete semantic evidence. ${i} Missing evidence is not evidence of absence.`:t}function Ht(e){let t=e.semanticEvidence;if(!t.enabled||t.status==="complete"||t.status==="disabled")return;let n=[t.incompleteSymbolCount>0?`${t.incompleteSymbolCount} incomplete`:"",t.unavailableSymbolCount>0?`${t.unavailableSymbolCount} unavailable`:""].filter(Boolean);return n.length>0?`${n.join(" and ")} symbol(s) were excluded.`:`Semantic evidence coverage was ${t.status}.`}var _i=20,vd=te("dead",({db:e,args:t,opts:n,budget:i})=>{let o={scope:G(t,0)||void 0,minLoc:E(n,"minLoc",1),includeTests:y(n,"includeTests"),skipBarrels:y(n,"skipBarrels"),includeMembers:y(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},r=Nr(e,o),s=r.symbols.filter(O=>O.kind==="dead-code"),a=r.symbols.filter(O=>O.kind==="file-internal"),c=r.symbols.filter(O=>O.kind==="implicit-usage"),l=!y(n,"onlyInternal"),u=!y(n,"onlyDead"),m=!y(n,"onlyDead")&&!y(n,"onlyInternal"),g=l?s:[],p=u?a:[],h=m?c:[],f=g.reduce((O,Q)=>O+Q.loc,0),b=p.reduce((O,Q)=>O+Q.loc,0),v=h.reduce((O,Q)=>O+Q.loc,0),S=y(n,"full"),L=S?g:g.slice(0,_i),W=S?p:p.slice(0,_i),H=S?h:h.slice(0,_i),j=L.reduce((O,Q)=>O+Q.loc,0),_=W.reduce((O,Q)=>O+Q.loc,0),x=H.reduce((O,Q)=>O+Q.loc,0),M={total:g.length+p.length+h.length,deadCode:g.length,fileInternal:p.length,implicitUsage:h.length,loc:f+b+v};if(y(n,"json")){P("dead",t,n,{...r,shown:{deadCode:g,fileInternal:p,implicitUsage:h},shownCounts:M,totals:{total:r.counts.total,deadCode:r.counts.deadCode,fileInternal:r.counts.fileInternal,implicitUsage:r.counts.implicitUsage,loc:r.counts.loc}},{analysisBudget:i.analysisBudget});return}if(g.length===0&&p.length===0&&h.length===0){T.empty("No matching dead-code symbols found.");return}g.length>0&&(Fn(L,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
55
|
+
.codebaseiq.json and .codebaseiq.local.json); inside an agent session pass probes instead. Use --providers to see which are available.`,options:C([d("--term <group>",'Concept group; "|" separates interchangeable words, as in retry|reattempt; repeat for more groups',q,[]),d("--name <identifier>","Identifier existing code might already use; repeat for more",q,[]),d("--calls <callee>","Function the new code would call; repeat for more",q,[]),d("--param <word>","Word expected in the parameter list; repeat for more",q,[]),d("--returns <word>","Word expected in the return type; repeat for more",q,[]),d("--kind <kind>","Restrict to function, method, class, interface, or type; repeat for more",q,[]),d("--probes <file>","Read probes as JSON from a file, or from standard input when the value is -"),d("--mode <mode>","Provider mode for a description: agent, embeddings, or auto"),d("--endpoint <name>","Use only this embeddings endpoint"),d("--agent <name>","Use only this agent command"),d("--bucket <bucket>","Show only reuse, rework, or compose candidates"),d("-n, --limit <n>","Candidates per bucket",ne,ji),d("--full","Return every candidate in each bucket instead of the first --limit"),d("-s, --scope <path>","Limit candidates to files matching path"),d("--providers","Show the state of each configured provider instead of searching"),d("--refresh-embeddings","Embed code that has no vector yet; with no description or probes, only refresh"),d("--timeout <ms>","Give up after this many milliseconds",ne,Jl)]),heuristic:{label:"symbol builder candidates"},budget:"candidate-scan",renderShape:"custom",agent:{...Ie("Does indexed code already provide, nearly provide, or help compose what I am about to write?","candidate symbols grouped as reuse, rework, or compose with file, line, signature, tier, and observed facts",["pattern"],"bounded","repository",ce,lt("Match caller-chosen probes, or the probes or vector ranking a configured provider derives from a description, against indexed definitions.","Candidate symbols bucketed by named blockers and importability, with the provider, its fallbacks, and its coverage.",["Candidates match the probes or the provider output; their order does not establish task relevance, behavioral equivalence, or the absence of other reusable code."],void 0,{outputCost:"bounded",frontierClosure:["code","evidence","inspect"]})),resultUnits:{kind:"field",field:"candidates"},contrasts:[{command:"similar",distinction:"similar compares callables that already exist; reuse starts from code you have not written yet."},{command:"search",distinction:"search finds exact text; reuse matches meaning through probes the caller chooses."}]},docs:R("Exploration",['codebaseiq reuse --term "retry|reattempt" --calls sleep --returns promise','codebaseiq reuse "retry a flaky request with backoff"',"codebaseiq reuse --providers"]),handler:Bf}];function _t(e){return{...e,options:C(e.options)}}function Qe({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=_t(l);return{...u,renderShape:"list",handler:xa({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c})}}function Xl({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:u,...m}){let g=_t(m);return{...g,renderShape:"table",handler:Ra({commandName:g.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:u})}}function Yl({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l,...u}){let m=_t(u);return{...m,renderShape:"grouped-by-file",handler:Ca({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l})}}function jn({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=_t(l);return{...u,renderShape:"sectioned-report",handler:ka({commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}function dt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let u=_t(l);return{...u,budget:u.budget??"semantic",renderShape:"sectioned-report",handler:Ea(u.id,{commandName:u.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}import{existsSync as bb,mkdirSync as yb,writeFileSync as vb}from"fs";import{dirname as Sb,relative as $b}from"path";import{existsSync as Xe,readdirSync as Uf}from"fs";import{basename as Hf,dirname as rd,isAbsolute as sd,join as Kf,relative as zf,resolve as Vt,sep as Jf}from"path";import{spawnSync as Wf}from"child_process";import{dirname as _f}from"path";function ed(e){let n=(e.spawnSync??Wf)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:_f(e.specPath),maxBuffer:1024*1024*32,windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let i=n.stdout??"";return i.includes("<?xml")?i:null}function td(e){let t=Gf(e),n=new Map,i=new Map,o=[],r=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?i.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(o.push(a),r.set(a.uid,a));let s=[];for(let a of o){let c=nd(a.block,n,i,r,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:o.map(a=>a.uniquename).sort(),actions:s}}var Vf=8;function Gf(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let i of e.matchAll(n)){let o=i.index,r=e.indexOf("</entry>",o),s=e.slice(o,r<0?e.length:r),a=Ii(s,"uniquename"),c=Ii(s,"kind"),l=Ii(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:Zl(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Zl(l),block:s})}return t}function nd(e,t,n,i,o,r,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],u="read";for(let[,m,g]of l){if(m==="BuiltInKindRef"){let p=n.get(g)??"";p==="'"?u="write-next":p==="UNCHANGED"?u="unchanged-run":u==="unchanged-run"&&p==="$Tuple"||u!=="write-next"&&(u="read");continue}if(m==="OpDeclNodeRef"){let p=t.get(g);if(!p)continue;u==="write-next"?(c.add(p),u="read"):u==="unchanged-run"||a.add(p);continue}if(m==="UserDefinedOpKindRef"){u==="unchanged-run"&&(u="read");let p=i.get(g);if(p&&s<Vf&&!r.has(p.uid)&&p.filename===o){let h=nd(p.block,t,n,i,o,new Set([...r,p.uid]),s+1);for(let f of h.reads)a.add(f);for(let f of h.writes)c.add(f)}continue}u==="unchanged-run"&&(u="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function Ii(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Zl(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var ad=["update","insert","delete"],cd=["select","query","findFirst","findMany"],Ni=new Set([...ad,...cd]);function Di(e){let t=e.methods&&e.methods.length>0?e.methods:[...Ni],n=new Set(ad),i=new Set(cd);return{write:t.filter(o=>n.has(o)),read:t.filter(o=>i.has(o))}}var Qf=/^(.*)@L(\d+)-L(\d+)$/;function Oi(e){let t=e.match(Qf);if(!t)return{ref:e};let n=t[1],i=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return n?i<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:o<i?{error:`codeRef "${e}" line window end (L${o}) is before its start (L${i})`}:{ref:n,window:{startLine:i,endLine:o}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var Xf=new Set(["auto","sany","tlc","apalache","none"]),Nn=/^[A-Za-z_][A-Za-z0-9_]*$/;function ld(e){return Xf.has(e)}function Dn(e,t){let n=[],i=we(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!Xe(i))return{errors:[`map file not found: ${t}`]};let o;try{o=JSON.parse(ke(i,{inputKind:"TLA mapping",maxBytes:Zt}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let r=Yf(o,n);return r?{loaded:{contract:r,mapPath:i,mapDir:rd(i)},errors:n}:{errors:n}}function we(e,t){if(!t)return null;let n=sd(t)?Vt(t):Vt(e,t);return rt(e,n)?n:null}function dd(e,t,n){if(!n)return null;if(sd(n)){let s=Vt(n);return rt(e,s)?s:null}let i=Vt(e,n);if(rt(e,i)&&Xe(i))return i;let o=Vt(t,n);if(rt(e,o)&&Xe(o))return o;let r=rt(e,i)?i:o;return rt(e,r)?r:null}function ud(e,t){let n=we(e,t);if(!n||!Xe(n))return null;let i=ke(n,{inputKind:"TLA module",maxBytes:ot});return{path:n,modelParse:"regex-fallback",text:i,variables:pb(i),operators:mb(i),actions:[]}}function pd(e,t,n){let i=we(e,t);if(!i||!Xe(i))return null;let o=ke(i,{inputKind:"TLA module",maxBytes:ot}),r=td(n);return{path:i,modelParse:"sany",text:o,variables:r.variables,operators:r.operators,actions:r.actions}}function Mi(e,t){let n=we(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Xe(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(ke(n,{inputKind:"TLA trace",maxBytes:ot})),o=Array.isArray(i)?i:ie(i)&&Array.isArray(i.steps)?i.steps:null;if(!o)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let r=[],s=[];for(let[a,c]of o.entries()){if(!ie(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}r.push({action:c.action,before:ie(c.before)?c.before:void 0,after:ie(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:r,errors:s}}catch(i){let o=i instanceof Error?i.message:String(i);return{steps:[],errors:[`trace file is not valid JSON: ${o}`]}}}function qi(e,t){let n=new Set,i=[];for(let o of t){let r=we(e,o)??o;n.has(r)||(n.add(r),i.push(o))}return i}function Yf(e,t){if(!ie(e))return t.push("map file must contain a JSON object"),null;let n=ob(e.variables,t);ib(n,t);let i=db(e.actions,n,t),o=Zf(e.init,t);tb(o,i,t);let r={module:od(e.module,"module",t),config:od(e.config,"config",t),scope:me(e.scope)??[],variables:n,actions:i,...o?{init:o}:{},invariants:me(e.invariants)??[],traces:me(e.traces)??[],unmappedWriteScope:nb(e.unmappedWriteScope,t)};return hb(e.scope,t),t.length===0?r:null}function Zf(e,t){if(e===void 0)return;if(!ie(e)){t.push("init must be an object when present");return}let n=me(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=eb(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function eb(e,t){if(e===void 0)return;if(!ie(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function tb(e,t,n){if(!e)return;let i=new Set(e.codeRefs),o=new Set;for(let r of Object.values(t))for(let s of r.code)i.has(s)&&o.add(s);o.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...o].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function nb(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function ib(e,t){In(e,t,"alias",n=>n.aliases),In(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),In(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),In(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:o,read:r}=Di(i);return[...o,...r].map(s=>`${i.table}:${s}`)}))}function In(e,t,n,i){let o=new Map;for(let[r,s]of Object.entries(e))for(let a of i(s)){let c=o.get(a);c?c.push(r):o.set(a,[r])}for(let[r,s]of o)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${r}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function ob(e,t){if(!ie(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[i,o]of Object.entries(e)){if(!Nn.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!ie(o)){t.push(`variables.${i} must be an object`);continue}let r=gd(o.code);if(!r||r.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=me(o.aliases)??[],a=sb(o.resource,i,t),c=ab(o.statements,i,t),l=cb(o.ormCalls,i,t),u=lb(o.waive,i,t),m=rb(o.selfAlias,i,t),g=m?[...new Set([i,...s])]:[...new Set(s)];m===!1&&g.length===0&&!a&&!c&&!l&&!u&&t.push(`variables.${i}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${i} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${i}.waive with a reason`),n[i]={code:r,aliases:g,projection:typeof o.projection=="string"?o.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...u?{waive:u}:{},...m===!1?{selfAlias:!1}:{}}}return n}function rb(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function sb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.resource must be an object when present`);return}let i=typeof e.path=="string"?e.path.trim():"";if(!i){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:i}}function ab(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.statements[${r}] must be an object`);return}let s=typeof o.pattern=="string"?o.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${r}].pattern must be a non-empty string`);return}try{tn(s,`variables.${t}.statements[${r}].pattern`)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${r}].pattern is not a valid regular expression: ${c}`);return}i.push({pattern:s})}),i.length>0?i:void 0}function cb(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.ormCalls[${r}] must be an object`);return}let s=typeof o.table=="string"?o.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${r}].table must be a non-empty string`);return}if(o.methods===void 0){i.push({table:s});return}let a=me(o.methods);if(!a){n.push(`variables.${t}.ormCalls[${r}].methods must be an array of strings when present`);return}let c=a.filter(l=>!Ni.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${r}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...Ni].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function lb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.waive must be an object when present`);return}let i=typeof e.reason=="string"?e.reason.trim():"";if(!i){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:i}}function db(e,t,n){if(!ie(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let i=new Set(Object.keys(t)),o={};for(let[r,s]of Object.entries(e)){if(!Nn.test(r)){n.push(`invalid TLA+ action name: ${r}`);continue}if(!ie(s)){n.push(`actions.${r} must be an object`);continue}let a=gd(s.code);if(!a||a.length===0){n.push(`actions.${r}.code must name at least one TypeScript referent`);continue}for(let g of a){let p=Oi(g);"error"in p&&n.push(`actions.${r}.code: ${p.error}`)}let c=me(s.reads)??[],l=me(s.writes)??[],u=me(s.calls)??[];for(let g of[...c,...l])i.has(g)||n.push(`actions.${r} references unknown variable: ${g}`);let m=ub(s.waive,s.allowUnknown===!0,c,l,i,r,n);o[r]={code:a,reads:c,writes:l,calls:u,...m?{waive:m}:{}}}return o}function ub(e,t,n,i,o,r,s){if(ie(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${r}.waive.reason must be a non-empty string`);let c=me(e.reads)??[],l=me(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${r}.waive must list reads or writes`),id(r,"reads",c,o,s),id(r,"writes",l,o,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${r}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(i)],reason:"legacy allowUnknown",legacy:!0}}function id(e,t,n,i,o){for(let r of n)i.has(r)||o.push(`actions.${e}.waive.${t} references unknown variable: ${r}`)}function pb(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let i=n[1]??"";for(let o of i.split(",")){let r=o.trim();Nn.test(r)&&t.add(r)}}return[...t].sort()}function mb(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var gb=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function md(e){if(!e||!Xe(e))return[];let t=ke(e,{inputKind:"TLA checker configuration",maxBytes:Zt}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let o of t.split(/[\s,]+/))if(o){if(gb.has(o)){i=o==="INVARIANT"||o==="INVARIANTS";continue}i&&Nn.test(o)&&n.add(o)}return[...n].sort()}function od(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function gd(e){return typeof e=="string"?[e]:me(e)}function hb(e,t){e!==void 0&&(me(e)||t.push("scope must be an array of strings when present"))}function On(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var fb=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function hd(e,t){if(!Xe(t))return{status:"none"};let i=ke(t,{inputKind:"TLA module",maxBytes:ot}).match(fb)?.[1],o=zf(e,t).split(Jf).join("/"),r=Hf(t),s=new Set([i,o,r,r.replace(/\.tla$/i,"")].filter(u=>!!u)),a=rd(t);if(!Xe(a))return{status:"none"};let c=[];for(let u of Uf(a)){if(!u.endsWith(".scip-tla.json"))continue;let m=Kf(a,u),g;try{g=JSON.parse(ke(m,{inputKind:"TLA mapping candidate",maxBytes:Zt}))}catch{continue}ie(g)&&typeof g.module=="string"&&s.has(g.module)&&c.push(m)}c.sort();let l=i??o;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function Mn(e,t,n,i,o={count:e.length,loc:i}){let r=o.count===e.length&&o.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${o.count}, ${i} of ${o.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${r}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let u=s.get(l.relativePath)??[];u.push(l),s.set(l.relativePath,u)}let a=[...s.entries()].map(([l,u])=>({file:l,bucket:u,totalLoc:u.reduce((m,g)=>m+g.loc,0)})).sort((l,u)=>u.totalLoc-l.totalLoc||l.file.localeCompare(u.file)),c=!0;for(let{file:l,bucket:u}of a){c||console.log(""),c=!1,console.log(` ${l}`),u.sort((m,g)=>m.startLine-g.startLine);for(let m of u){let g=m.implicitUsageReason?` [implicit usage: ${m.implicitUsageReason}]`:"";console.log(` ${fe(m.startLine,m.endLine)} (${m.loc} LOC) ${m.shortName}${g}`)}}}function Gt(e,t,n){if(n.rows.length>0)return;let i=Ut(n.coverage);return i?`No ${e} could be ranked with complete semantic evidence. ${i} Missing evidence is not evidence of absence.`:t}function Ut(e){let t=e.semanticEvidence;if(!t.enabled||t.status==="complete"||t.status==="disabled")return;let n=[t.incompleteSymbolCount>0?`${t.incompleteSymbolCount} incomplete`:"",t.unavailableSymbolCount>0?`${t.unavailableSymbolCount} unavailable`:""].filter(Boolean);return n.length>0?`${n.join(" and ")} symbol(s) were excluded.`:`Semantic evidence coverage was ${t.status}.`}var Fi=20,fd=te("dead",({db:e,args:t,opts:n,budget:i})=>{let o={scope:G(t,0)||void 0,minLoc:E(n,"minLoc",1),includeTests:y(n,"includeTests"),skipBarrels:y(n,"skipBarrels"),includeMembers:y(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},r=Ar(e,o),s=r.symbols.filter(O=>O.kind==="dead-code"),a=r.symbols.filter(O=>O.kind==="file-internal"),c=r.symbols.filter(O=>O.kind==="implicit-usage"),l=!y(n,"onlyInternal"),u=!y(n,"onlyDead"),m=!y(n,"onlyDead")&&!y(n,"onlyInternal"),g=l?s:[],p=u?a:[],h=m?c:[],f=g.reduce((O,ee)=>O+ee.loc,0),b=p.reduce((O,ee)=>O+ee.loc,0),v=h.reduce((O,ee)=>O+ee.loc,0),S=y(n,"full"),L=S?g:g.slice(0,Fi),B=S?p:p.slice(0,Fi),H=S?h:h.slice(0,Fi),j=L.reduce((O,ee)=>O+ee.loc,0),W=B.reduce((O,ee)=>O+ee.loc,0),w=H.reduce((O,ee)=>O+ee.loc,0),_={total:g.length+p.length+h.length,deadCode:g.length,fileInternal:p.length,implicitUsage:h.length,loc:f+b+v};if(y(n,"json")){P("dead",t,n,{...r,shown:{deadCode:g,fileInternal:p,implicitUsage:h},shownCounts:_,totals:{total:r.counts.total,deadCode:r.counts.deadCode,fileInternal:r.counts.fileInternal,implicitUsage:r.counts.implicitUsage,loc:r.counts.loc}},{analysisBudget:i.analysisBudget});return}if(g.length===0&&p.length===0&&h.length===0){T.empty("No matching dead-code symbols found.");return}g.length>0&&(Mn(L,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
56
56
|
Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,j,{count:g.length,loc:f}),!S&&g.length>L.length&&console.log(`
|
|
57
|
-
Showing top ${L.length} by LOC. Re-run with --full for the remaining ${g.length-L.length}.`)),p.length>0&&(g.length>0&&console.log(""),
|
|
57
|
+
Showing top ${L.length} by LOC. Re-run with --full for the remaining ${g.length-L.length}.`)),p.length>0&&(g.length>0&&console.log(""),Mn(B,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
58
58
|
single-use helper, an abstraction-in-progress, or a callback registered
|
|
59
59
|
through a framework path that static analysis cannot trace (signal
|
|
60
60
|
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
61
|
-
review case by case.`,
|
|
62
|
-
Showing top ${
|
|
61
|
+
review case by case.`,W,{count:p.length,loc:b}),!S&&p.length>B.length&&console.log(`
|
|
62
|
+
Showing top ${B.length} by LOC. Re-run with --full for the remaining ${p.length-B.length}.`)),h.length>0&&((g.length>0||p.length>0)&&console.log(""),Mn(H,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
|
|
63
63
|
consumer that the static reference graph cannot trace. Investigation
|
|
64
|
-
signals only \u2014 not deletion candidates and not counted as dead code.`,
|
|
65
|
-
Showing top ${H.length} by LOC. Re-run with --full for the remaining ${h.length-H.length}.`));let
|
|
66
|
-
\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: ${g.length+p.length+h.length} symbols \u2014 ${
|
|
67
|
-
${e.length} unused import(s)`)})
|
|
68
|
-
${e.length} isolated symbol(s)`)}),
|
|
64
|
+
signals only \u2014 not deletion candidates and not counted as dead code.`,w,{count:h.length,loc:v}),!S&&h.length>H.length&&console.log(`
|
|
65
|
+
Showing top ${H.length} by LOC. Re-run with --full for the remaining ${h.length-H.length}.`));let U=[];l&&U.push(`${g.length} dead code (${f} LOC)`),u&&U.push(`${p.length} file-internal (${b} LOC)`),m&&U.push(`${h.length} implicit usage (${v} LOC)`),console.log(`
|
|
66
|
+
\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: ${g.length+p.length+h.length} symbols \u2014 ${U.join(" + ")}`)}),bd=Se("unused-imports",{query:({db:e,args:t,budget:n})=>Dr(e,N(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
67
|
+
${e.length} unused import(s)`)}),yd=Ta("isolated",{query:({db:e,opts:t,budget:n})=>Ur(e,{scope:$(t,"scope"),minLoc:E(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${fe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
|
|
68
|
+
${e.length} isolated symbol(s)`)}),vd=te("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=ls(e,{scope:$(n,"scope"),minLoc:E(n,"minLoc",10),minCallees:E(n,"minCallees",6),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(y(n,"json")){P("extract-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return T.empty("No extraction candidates found.");je("extraction candidates");for(let r of o){console.log(`
|
|
69
69
|
${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC, ${r.totalCallees} callees)`),console.log(` Kind: ${r.extractionKind}; tier: ${r.actionTier}`),console.log(` Recommendation: ${r.recommendation}`);for(let s of r.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<r.clusters.length;s++){let a=r.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
|
|
70
|
-
${o.length} extraction candidate(s) found.`)}),
|
|
70
|
+
${o.length} extraction candidate(s) found.`)}),Sd=te("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=ds(e,{target:G(t,0)||void 0,scope:$(n,"scope"),minConsumers:E(n,"minConsumers",1),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(y(n,"json")){P("locality-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return T.empty("No locality candidates found.");je("locality candidates");for(let r of o){let s=r.sourceUnit.kind==="symbol"&&r.sourceUnit.startLine!==void 0&&r.sourceUnit.endLine!==void 0?V(r.sourceUnit.file,r.sourceUnit.startLine,r.sourceUnit.endLine):r.sourceUnit.file;if(console.log(`
|
|
71
71
|
${s} ${r.sourceUnit.shortName}`),console.log(` Current directory: ${r.currentDirectory}; tier: ${r.recommendedTier}; action: ${r.actionTier}`),console.log(` Consumer coverage: ${r.consumerCoverage}; consumers: ${r.consumerFiles.length}`),r.nearestCommonOwner&&console.log(` Nearest common owner: ${r.nearestCommonOwner}`),r.suggestedHome&&console.log(` Suggested home: ${r.suggestedHome}`),r.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${r.whyNoSuggestedHome}`),r.boundaryMarkers.length>0&&console.log(` Boundary markers: ${r.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${r.recommendation}`),r.consumerFiles.length>0){for(let a of r.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);r.consumerFiles.length>8&&console.log(` - ... ${r.consumerFiles.length-8} more consumer(s)`)}for(let a of r.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
|
|
72
|
-
${o.length} locality candidate(s) found.`)})
|
|
72
|
+
${o.length} locality candidate(s) found.`)}),$d=Se("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Os(e,{scope:$(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
73
73
|
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
74
74
|
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
75
|
-
${e.length} wrapper candidate(s).`)}),
|
|
75
|
+
${e.length} wrapper candidate(s).`)}),wd=Se("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>$s(e,{scope:$(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
76
76
|
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
77
77
|
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
78
78
|
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
79
79
|
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
80
|
-
${e.length} passthrough candidate(s).`)}),
|
|
80
|
+
${e.length} passthrough candidate(s).`)}),xd=Se("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Ds(e,{scope:$(t,"scope"),minLoc:E(t,"minLoc",3),limit:D(t,"limit",30),includeLowConfidence:y(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
81
81
|
${e.reason}
|
|
82
82
|
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
83
83
|
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
84
|
-
${e.length} stale abstraction(s).`)}),
|
|
85
|
-
`)},render:e=>T.table(["score"," LOC","fan-in","fan-out","callees","symbol"],e.rows.map(t=>` ${t.score.toFixed(1).padStart(5)} ${String(t.loc).padStart(4)} ${String(t.fanIn).padStart(6)} ${String(t.fanOut).padStart(7)} ${String(t.calleeCount).padStart(7)} ${t.shortName}`),[5,4,6,7,7,6])}),
|
|
84
|
+
${e.length} stale abstraction(s).`)}),Rd=be("complexity-hotspots",{resultSchemaVersion:2,query:({db:e,opts:t,budget:n})=>Bs(e,{scope:$(t,"scope"),minLoc:E(t,"minLoc",10),limit:D(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),emptyMessage:e=>Gt("complexity hotspots","No complexity hotspots found.",e),heuristicLabel:"complexity hotspot candidates",before:e=>{let t=Ut(e.coverage);t&&console.log(`Semantic ranking coverage degraded: ${t} Missing evidence may change this ranking.
|
|
85
|
+
`)},render:e=>T.table(["score"," LOC","fan-in","fan-out","callees","symbol"],e.rows.map(t=>` ${t.score.toFixed(1).padStart(5)} ${String(t.loc).padStart(4)} ${String(t.fanIn).padStart(6)} ${String(t.fanOut).padStart(7)} ${String(t.calleeCount).padStart(7)} ${t.shortName}`),[5,4,6,7,7,6])}),Cd=be("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(y(n,"plan")){let r=G(t,0),s=G(t,1);if(!r||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Zr(e,r,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let o=G(t,0);return o?{mode:"target",rows:Yr(e,o,{minSimilarity:E(n,"minSimilarity",.4),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:es(e,{minSimilarity:E(n,"minSimilarity",.4),limit:D(n,"limit",20),scope:$(n,"scope"),minCallees:E(n,"minCallees",4),crossFileOnly:y(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
|
|
86
86
|
${Math.round(t.similarity*100)}% ${n}
|
|
87
87
|
`),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
|
|
88
88
|
`),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let i of t.sharedEvidence)console.log(` ${i}`);if(t.uniqueToA.length>0){console.log(`
|
|
@@ -98,76 +98,76 @@ ${Math.round(t.similarity*100)}% similar:
|
|
|
98
98
|
Recommendation: ${t.recommendation}
|
|
99
99
|
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
100
100
|
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
101
|
-
${e.rows.length} similar pair(s) found.`)}}),
|
|
101
|
+
${e.rows.length} similar pair(s) found.`)}}),kd=ze({commandName:"similar-files",query:({db:e,args:t,opts:n})=>ts(e,{minSimilarity:E(n,"minSimilarity",.5),limit:D(n,"limit",20),scope:$(n,"scope"),minDeps:K(n,"minDeps"),filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
102
102
|
${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(`
|
|
103
103
|
`)}),console.log(`
|
|
104
|
-
${e.length} similar pair(s) found.`)}}),
|
|
104
|
+
${e.length} similar pair(s) found.`)}}),Ed=ze({commandName:"similar-chains",query:({db:e,opts:t})=>cs(e,{minSimilarity:E(t,"minSimilarity",.5),limit:D(t,"limit",15),scope:$(t,"scope"),minChainLength:E(t,"minLength",3),maxChainLength:E(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
|
|
105
105
|
\u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
|
|
106
|
-
${e.length} similar chain pair(s) found.`)}}),
|
|
106
|
+
${e.length} similar chain pair(s) found.`)}}),Td=be("drift",{query:({db:e,args:t,opts:n,budget:i})=>Ns(e,{scope:G(t,0),minDeviation:E(n,"minDeviation",5),semantic:i.semantic,includePatternDeviations:y(n,"patterns"),includeArchitecture:y(n,"architecture"),limit:D(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),T.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",o=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&o.push(` ${t.detail}`),o.join(`
|
|
107
107
|
`)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(i=>i.policyStatus==="undeclared").length;if(console.log(`
|
|
108
108
|
Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let i of t.reciprocalPairs)console.log(` ${i.boundaries[0]} <-> ${i.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let i of t.cycles){let o=i.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${i.boundaries.join(", ")} }${o}`)}}}console.log(`
|
|
109
|
-
${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)`:""}`)}}),
|
|
109
|
+
${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)`:""}`)}}),Ld=be("convergence",{query:({db:e,args:t,budget:n})=>Gs(e,N(t,0),N(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
|
|
110
110
|
${Math.round(e.similarity*100)}% callee overlap
|
|
111
111
|
`),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)
|
|
112
112
|
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
113
113
|
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
114
114
|
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
115
|
-
Strategy: ${e.consolidationStrategy}`)}}}),
|
|
115
|
+
Strategy: ${e.consolidationStrategy}`)}}}),Pd=Se("similar-signatures",{query:({db:e,opts:t,budget:n})=>Js(e,{scope:$(t,"scope"),minLoc:E(t,"minLoc",3),maxShapeFrequency:E(t,"maxShapeFrequency",12),limit:D(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
|
|
116
116
|
Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
117
117
|
`);return`${n}
|
|
118
118
|
${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
119
|
-
${e.length} group(s) found.`)}),
|
|
119
|
+
${e.length} group(s) found.`)}),Ad=Se("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>vs(e,{scope:$(t,"scope"),maxLoc:E(t,"maxLoc",15),minLoc:E(t,"minLoc",3),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
120
120
|
Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,o)=>` ${(o===0?"canonical":"duplicate").padEnd(9)} ${V(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
121
121
|
`);return`${t}
|
|
122
122
|
${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
|
|
123
|
-
${e.length} group(s) found.`)}),
|
|
123
|
+
${e.length} group(s) found.`)}),jd=Se("twin-drift",{query:({db:e,opts:t,budget:n})=>Ss(e,{scope:$(t,"scope"),minSimilarity:E(t,"minSimilarity",.3),includeHomonyms:y(t,"includeHomonyms"),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
124
124
|
${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
125
125
|
`),i=e.firstDivergentTokens?`
|
|
126
126
|
first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
|
|
127
127
|
${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
|
|
128
|
-
${e.length} group(s) found.`)}),
|
|
128
|
+
${e.length} group(s) found.`)}),Id=Se("not-implemented",{query:({db:e,opts:t,budget:n})=>Rs(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
|
|
129
129
|
${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
|
|
130
|
-
${e.length} reachable placeholder stub(s).`)}),
|
|
131
|
-
${e.length} decorative checker candidate(s).`)}),
|
|
130
|
+
${e.length} reachable placeholder stub(s).`)}),Nd=Se("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Cs(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
|
|
131
|
+
${e.length} decorative checker candidate(s).`)}),Dd=te("test-quality",({db:e,args:t,opts:n,budget:i})=>{let o=ks(e,{scope:$(n,"scope"),limit:D(n,"limit",30),scanLimit:i.scanLimit,rotDays:K(n,"rotDays")});if(y(n,"json")){P("test-quality",t,n,o,{analysisBudget:i.analysisBudget});return}if(je("test-quality findings"),o.assertionFree.length+o.skipped.length+o.mockEcho.length===0){T.empty("No test-quality findings.");return}o.assertionFree.length>0&&(console.log(`
|
|
132
132
|
ASSERTION-FREE (${o.assertionFree.length})`),T.list(o.assertionFree,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),o.skipped.length>0&&(console.log(`
|
|
133
133
|
SKIPPED (${o.skipped.length})`),T.list(o.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),o.mockEcho.length>0&&(console.log(`
|
|
134
134
|
MOCK-ECHO (${o.mockEcho.length})`),T.list(o.mockEcho,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
|
|
135
|
-
${o.assertionFree.length} assertion-free, ${o.skipped.length} skipped, ${o.mockEcho.length} mock-echo.`)}),
|
|
135
|
+
${o.assertionFree.length} assertion-free, ${o.skipped.length} skipped, ${o.mockEcho.length} mock-echo.`)}),Od=ze({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let i=N(t,0),o=N(t,1),r=$(n,"out")??ws(i,o),s=we(e.config.projectRoot,r);if(!s)throw new Error(`twin-ab output path escapes the project root: ${r}`);let a=xs(e,{refA:i,refB:o,outFile:s});if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=$b(e.config.projectRoot,s);if(!y(n,"force")&&bb(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return yb(Sb(s),{recursive:!0}),vb(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
|
|
136
136
|
Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${V(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${V(e.b.file,e.b.startLine,e.b.startLine)})`);let t=e.signatureCompatible===null?"unknown":e.signatureCompatible?"compatible":"MISMATCH";console.log(` Signature compatibility: ${t}`),console.log(`
|
|
137
|
-
Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),
|
|
137
|
+
Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),Md=te("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let o=ms(e,{scope:$(n,"scope"),minLoc:E(n,"minLoc",1),maxDepth:E(n,"maxDepth",5),scanLimit:i.scanLimit}),r=pe(),s=y(n,"patch"),a=y(n,"json"),c=y(n,"verify")||s;if(s&&!y(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(o.batches.length===0){if(a){P("cleanup-plan",t,n,o,{analysisBudget:i.analysisBudget});return}return T.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=sc(o),u=c?tc(r,o):void 0;if(a){P("cleanup-plan",t,n,{result:o,verification:u},{analysisBudget:i.analysisBudget});return}if(s){let m=ac(u,l);if(m.length>0){for(let p of m)console.error(`error: ${p}`);process.exitCode=1;return}let g=rc(r,l);if(g.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${o.totalLoc} LOC.`),console.log(g);return}console.log(`Cleanup plan: ${o.totalSymbols} symbol(s), ${o.totalLoc} LOC across ${o.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
|
|
138
138
|
`);for(let m of o.batches){let g=m.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${m.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${m.depth}: dead once batch ${m.depth-1} lands (cascade, ${m.loc} LOC) \u2500\u2500`;console.log(g);for(let p of m.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);m.filesEmptied.length>0&&console.log(` -> empties: ${m.filesEmptied.join(", ")}`),console.log("")}if(o.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let m of o.blocked)console.log(` ${m.shortName} (${m.file}) blocked by ${m.blockingFiles.join(", ")}`)}if(u){if(console.log(`
|
|
139
|
-
Verifying batches against the project checker (isolated snapshot of committed HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let p of u.checkers)console.log(` Checker: ${p}`);if(u.unavailableReason){console.log(` UNAVAILABLE: ${u.unavailableReason}.`);return}if(u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.workingTree.state==="unavailable"&&console.log(` WARNING: working-tree inspection unavailable: ${u.workingTree.reason}`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`),u.dirtyWorkingTree.length>0){let p=u.dirtyWorkingTree.slice(0,5),h=u.dirtyWorkingTree.length-p.length;console.log(` WARNING: verification ran at HEAD; ${u.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${p.join(", ")}${h>0?`, ... ${h} more`:""}`)}let m=
|
|
139
|
+
Verifying batches against the project checker (isolated snapshot of committed HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let p of u.checkers)console.log(` Checker: ${p}`);if(u.unavailableReason){console.log(` UNAVAILABLE: ${u.unavailableReason}.`);return}if(u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.workingTree.state==="unavailable"&&console.log(` WARNING: working-tree inspection unavailable: ${u.workingTree.reason}`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`),u.dirtyWorkingTree.length>0){let p=u.dirtyWorkingTree.slice(0,5),h=u.dirtyWorkingTree.length-p.length;console.log(` WARNING: verification ran at HEAD; ${u.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${p.join(", ")}${h>0?`, ... ${h} more`:""}`)}let m=wb(u.checkers),g=xb(u.checkers);for(let p of u.batches)if(p.status==="verified")console.log(` Batch ${p.depth}: VERIFIED (${m})${g}`);else{console.log(` Batch ${p.depth}: FAILED${p.reason?` (${p.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let h of p.errors??[])console.log(` ${h}`)}}});function wb(e){return e.join(", ")}function xb(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var qd=te("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let o=y(n,"full"),r=Es(e,{windowCommits:E(n,"window",100),minSimilarity:K(n,"minSimilarity"),limit:D(n,"limit",30),scope:$(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:o?"full":"bounded"});if(y(n,"json")){P("recent-duplicates",t,n,r,{analysisBudget:i.analysisBudget});return}if(!r.available)return T.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return T.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);je("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
|
|
140
140
|
`);let s=r.rootCauseGroups?.filter(a=>a.count>1)??[];if(s.length>0){console.log(`Root-cause groups (${s.length}):`);for(let a of s)console.log(` ${a.count} pair(s) ${a.kind.toUpperCase()} ${a.domain} ${Math.round(a.maxSimilarity*100)}% max`),a.establishedFile&&a.establishedSymbol&&console.log(` established: ${a.establishedFile} ${a.establishedSymbol}`),console.log(` files: ${a.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${a.recommendation}`);console.log("")}for(let a of r.findings){let c=a.sharedEvidence.slice(0,16).join(", ");a.kind==="echo"?(console.log(` ${Math.round(a.similarity*100)}% ECHO ${a.domain} ${a.echoFile} ${a.echoSymbol} (added ${a.echoAgeCommits} commits ago)`),console.log(` duplicates established ${a.establishedFile} ${a.establishedSymbol}`)):(console.log(` ${Math.round(a.similarity*100)}% TWIN ${a.domain} ${a.echoFile} ${a.echoSymbol}`),console.log(` and ${a.establishedFile} ${a.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${a.basis}`),c.length>0&&console.log(` shared: ${c}`)}console.log(`
|
|
141
|
-
${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),
|
|
142
|
-
`);for(let r of o.findings){let s=r.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=r.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${r.staleness} ${r.doc}${s}${a}`);for(let c of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of r.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let u=c.docIntentReasons[0];u&&console.log(` intent: ${u}`);let m=c.citationContexts?.[0];m&&console.log(` cited claim: ${
|
|
143
|
-
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),
|
|
141
|
+
${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Fd=X(({db:e,args:t,opts:n})=>{let i=y(n,"full"),o=ys(e,{doc:t[0]===void 0?void 0:N(t,0),limit:D(n,"limit",20),minCoupling:E(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(y(n,"json")){P("doc-drift",t,n,o);return}if(!o.available)return T.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return T.empty(`No drifting docs found across ${o.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);je("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${o.docsScanned} docs scanned, ${o.commitsAnalyzed} commits analyzed):
|
|
142
|
+
`);for(let r of o.findings){let s=r.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=r.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${r.staleness} ${r.doc}${s}${a}`);for(let c of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of r.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let u=c.docIntentReasons[0];u&&console.log(` intent: ${u}`);let m=c.citationContexts?.[0];m&&console.log(` cited claim: ${on(m)}`)}}console.log(`
|
|
143
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Bd=Se("unused-params",{query:({db:e,opts:t,budget:n})=>Fs(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
144
144
|
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(`
|
|
145
|
-
${e.length} function(s) with trailing unused parameters.`)});var
|
|
145
|
+
${e.length} function(s) with trailing unused parameters.`)});var Wd=be("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>ns(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
146
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
147
|
`)}),console.log(`
|
|
148
|
-
${e.length} duplicated React component pair(s) found.`)}}),
|
|
148
|
+
${e.length} duplicated React component pair(s) found.`)}}),_d=be("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>is(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
149
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
150
|
`)}),console.log(`
|
|
151
|
-
${e.length} React hook candidate pair(s) found.`)}}),
|
|
151
|
+
${e.length} React hook candidate pair(s) found.`)}}),Vd=be("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>os(e,{minComponentLines:E(n,"minComponentLines",300),minFileLines:E(n,"minFileLines",800),minJsxTokens:E(n,"minJsxTokens",80),minBehaviorTokens:E(n,"minBehaviorTokens",40),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{T.list(e,t=>[`
|
|
152
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
153
|
`)),console.log(`
|
|
154
|
-
${e.length} large React component(s) found.`)}}),
|
|
154
|
+
${e.length} large React component(s) found.`)}}),Gd=be("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>rs(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
155
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
156
|
`)}),console.log(`
|
|
157
|
-
${e.length} duplicated Vue component pair(s) found.`)}}),
|
|
157
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),Ud=be("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>ss(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
158
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
159
|
`)}),console.log(`
|
|
160
|
-
${e.length} Vue composable candidate pair(s) found.`)}}),
|
|
160
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),Hd=be("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>as(e,{minTotalLines:y(n,"reviewThresholds")&&La(n,"minTotalLines")==="default"?300:E(n,"minTotalLines",800),minTemplateLines:E(n,"minTemplateLines",300),minScriptLines:E(n,"minScriptLines",300),minStyleLines:E(n,"minStyleLines",500),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:G(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{T.list(e,t=>{let n=[`
|
|
161
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
162
|
`)}),console.log(`
|
|
163
|
-
${e.length} large Vue view pressure file(s) found.`)}});function ve(e){return{docs:R("Cleanup"),...e}}function se({heuristicLabel:e,...t}){return ve({...t,heuristic:{label:e}})}var Bn=[ve({id:"unused-params",command:"unused-params",agent:k("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:C([d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Maximum findings",w,30),d("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:R("Cleanup",["codebaseiq unused-params -s src/services"]),handler:Vd}),ve({id:"cleanup-plan",command:"cleanup-plan",agent:k("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository",K("repository-preview")),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Only include symbols >= N lines",w,1),d("--max-depth <n>","Maximum cascade depth",w,5),d("--verify","Apply batches in an isolated HEAD snapshot and run the project checker (tsc / cargo check)"),d("--patch","With --verify, print the compiler-verified deletion patch to stdout"),d("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq cleanup-plan --min-loc 3","codebaseiq cleanup-plan --verify"]),handler:Bd}),ve({id:"recent-duplicates",command:"recent-duplicates",agent:k("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:C([d("--window <n>",'How many commits back counts as "recent"',w,100),d("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Le),d("-n, --limit <n>","Maximum findings",w,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:R("Cleanup",["codebaseiq recent-duplicates --window 50"]),handler:Wd}),ve({id:"doc-drift",command:"doc-drift [doc]",agent:k("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:C([d("-n, --limit <n>","Maximum docs to report",w,20),d("--min-coupling <n>","Minimum historical co-changes to track a subject",w,3),d("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:R("Cleanup",["codebaseiq doc-drift","codebaseiq doc-drift AGENTS.md"]),handler:_d}),ve({id:"dead",command:"dead [scope]",agent:k("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:C([d("--min-loc <n>","Only show symbols >= N lines",w,1),d("--include-tests","Include definitions from test files (test references always count)"),d("--skip-barrels","Ignore refs from barrel re-export files"),d("--include-members","Include class members"),d("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),d("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq dead --min-loc 10"]),handler:vd}),ve({id:"unused-imports",command:"unused-imports <file>",agent:k("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Sd}),ve({id:"isolated",command:"isolated",agent:k("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum lines of code",w,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:$d}),se({id:"similar",command:"similar [symbol] [other]",agent:k("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:C([d("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",Le,.4),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-callees <n>","Minimum callees to consider",w,4),d("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),d("--plan","Render a consolidation preview for two symbols"),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Td}),se({id:"similar-files",command:"similar-files [file]",agent:k("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:C([d("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Le,.5),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-deps <n>","Minimum dependencies to consider",w),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Ld}),se({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Le,.62),d("--min-tokens <n>","Minimum structural tokens to consider",w,8),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Gd}),se({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum behavior similarity (0-1)",Le,.45),d("--min-shared-behaviors <n>","Minimum shared behavior tokens",w,6),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Ud}),se({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:k("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:C([d("--min-component-lines <n>","Minimum component lines",w,300),d("--min-file-lines <n>","Minimum file lines",w,800),d("--min-jsx-tokens <n>","Minimum JSX structure tokens",w,80),d("--min-behavior-tokens <n>","Minimum behavior tokens",w,40),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Hd}),se({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum template similarity (0-1)",Le,.62),d("--min-tokens <n>","Minimum structural tokens to consider",w,8),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Kd}),se({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum behavior similarity (0-1)",Le,.45),d("--min-shared-behaviors <n>","Minimum shared behavior tokens",w,6),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:zd}),se({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:k("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:C([d("--min-total-lines <n>","Minimum total component lines",w,800),d("--min-template-lines <n>","Minimum template lines",w,300),d("--min-script-lines <n>","Minimum script lines",w,300),d("--min-style-lines <n>","Minimum style lines",w,500),d("--review-thresholds","Use lower review thresholds without changing health scoring"),d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Jd}),se({id:"similar-chains",command:"similar-chains",agent:k("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:C([d("--min-similarity <n>","Minimum chain similarity (0-1)",Le,.5),d("-n, --limit <n>","Number of results",w,15),d("-s, --scope <path>","Limit to files matching path"),d("--min-length <n>","Minimum chain length",w,3),d("--max-length <n>","Maximum chain length",w,8),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Pd}),se({id:"extract-candidates",command:"extract-candidates",agent:k("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum function LOC",w,10),d("--min-callees <n>","Minimum callees to analyze",w,6),d("-n, --limit <n>","Number of results",w,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:wd}),se({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:k("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:C([d("-s, --scope <path>","Limit scan mode to files matching path"),d("--min-consumers <n>","Minimum consumers in scan mode",w,1),d("-n, --limit <n>","Number of results",w,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq locality-candidates","codebaseiq locality-candidates formatName --json","codebaseiq locality-candidates src/shared/date.ts"]),handler:xd}),se({id:"drift",command:"drift [module]",agent:k("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:C([d("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",ne,5),d("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),d("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),d("-n, --limit <n>","Number of results",w,50),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Ad}),se({id:"wrapper-candidates",command:"wrapper-candidates",agent:k("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC for candidates",w,15),d("-n, --limit <n>","Number of results",w,30),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Rd}),se({id:"passthrough-candidates",command:"passthrough-candidates",agent:k("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC for candidates",w,15),d("-n, --limit <n>","Number of results",w,30),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Cd}),se({id:"stale-abstractions",command:"stale-abstractions",agent:k("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum LOC",w,3),d("-n, --limit <n>","Number of results",w,30),d("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:kd}),se({id:"complexity-hotspots",command:"complexity-hotspots",agent:{...k("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum LOC",w,10),d("-n, --limit <n>","Number of results",w,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Ed}),ve({id:"convergence",command:"convergence <symbol1> <symbol2>",hidden:!0,agent:k("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:jd}),td({id:"redundant-reexports",command:"redundant-reexports",agent:k("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",w,30),d("--full","Run unbounded analysis on large indexes")],docs:R("Cleanup"),query:({db:e,opts:t})=>Qs(e,{scope:$(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
163
|
+
${e.length} large Vue view pressure file(s) found.`)}});function ve(e){return{docs:R("Cleanup"),...e}}function se({heuristicLabel:e,...t}){return ve({...t,heuristic:{label:e}})}var qn=[ve({id:"unused-params",command:"unused-params",agent:k("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:C([d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Maximum findings",x,30),d("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:R("Cleanup",["codebaseiq unused-params -s src/services"]),handler:Bd}),ve({id:"cleanup-plan",command:"cleanup-plan",agent:k("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository",z("repository-preview")),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Only include symbols >= N lines",x,1),d("--max-depth <n>","Maximum cascade depth",x,5),d("--verify","Apply batches in an isolated HEAD snapshot and run the project checker (tsc / cargo check)"),d("--patch","With --verify, print the compiler-verified deletion patch to stdout"),d("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq cleanup-plan --min-loc 3","codebaseiq cleanup-plan --verify"]),handler:Md}),ve({id:"recent-duplicates",command:"recent-duplicates",agent:k("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:C([d("--window <n>",'How many commits back counts as "recent"',x,100),d("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Le),d("-n, --limit <n>","Maximum findings",x,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:R("Cleanup",["codebaseiq recent-duplicates --window 50"]),handler:qd}),ve({id:"doc-drift",command:"doc-drift [doc]",agent:k("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:C([d("-n, --limit <n>","Maximum docs to report",x,20),d("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),d("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:R("Cleanup",["codebaseiq doc-drift","codebaseiq doc-drift AGENTS.md"]),handler:Fd}),ve({id:"dead",command:"dead [scope]",agent:k("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:C([d("--min-loc <n>","Only show symbols >= N lines",x,1),d("--include-tests","Include definitions from test files (test references always count)"),d("--skip-barrels","Ignore refs from barrel re-export files"),d("--include-members","Include class members"),d("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),d("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq dead --min-loc 10"]),handler:fd}),ve({id:"unused-imports",command:"unused-imports <file>",agent:k("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:bd}),ve({id:"isolated",command:"isolated",agent:k("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum lines of code",x,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:yd}),se({id:"similar",command:"similar [symbol] [other]",agent:k("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:C([d("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",Le,.4),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-callees <n>","Minimum callees to consider",x,4),d("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),d("--plan","Render a consolidation preview for two symbols"),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Cd}),se({id:"similar-files",command:"similar-files [file]",agent:k("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:C([d("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Le,.5),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-deps <n>","Minimum dependencies to consider",x),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:kd}),se({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Le,.62),d("--min-tokens <n>","Minimum structural tokens to consider",x,8),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Wd}),se({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum behavior similarity (0-1)",Le,.45),d("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:_d}),se({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:k("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:C([d("--min-component-lines <n>","Minimum component lines",x,300),d("--min-file-lines <n>","Minimum file lines",x,800),d("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),d("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Vd}),se({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum template similarity (0-1)",Le,.62),d("--min-tokens <n>","Minimum structural tokens to consider",x,8),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Gd}),se({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:k("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:C([d("--min-similarity <n>","Minimum behavior similarity (0-1)",Le,.45),d("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Ud}),se({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:k("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:C([d("--min-total-lines <n>","Minimum total component lines",x,800),d("--min-template-lines <n>","Minimum template lines",x,300),d("--min-script-lines <n>","Minimum script lines",x,300),d("--min-style-lines <n>","Minimum style lines",x,500),d("--review-thresholds","Use lower review thresholds without changing health scoring"),d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Hd}),se({id:"similar-chains",command:"similar-chains",agent:k("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:C([d("--min-similarity <n>","Minimum chain similarity (0-1)",Le,.5),d("-n, --limit <n>","Number of results",x,15),d("-s, --scope <path>","Limit to files matching path"),d("--min-length <n>","Minimum chain length",x,3),d("--max-length <n>","Maximum chain length",x,8),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Ed}),se({id:"extract-candidates",command:"extract-candidates",agent:k("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum function LOC",x,10),d("--min-callees <n>","Minimum callees to analyze",x,6),d("-n, --limit <n>","Number of results",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:vd}),se({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:k("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:C([d("-s, --scope <path>","Limit scan mode to files matching path"),d("--min-consumers <n>","Minimum consumers in scan mode",x,1),d("-n, --limit <n>","Number of results",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["codebaseiq locality-candidates","codebaseiq locality-candidates formatName --json","codebaseiq locality-candidates src/shared/date.ts"]),handler:Sd}),se({id:"drift",command:"drift [module]",agent:k("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:C([d("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",ne,5),d("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),d("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),d("-n, --limit <n>","Number of results",x,50),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Td}),se({id:"wrapper-candidates",command:"wrapper-candidates",agent:k("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC for candidates",x,15),d("-n, --limit <n>","Number of results",x,30),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:$d}),se({id:"passthrough-candidates",command:"passthrough-candidates",agent:k("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC for candidates",x,15),d("-n, --limit <n>","Number of results",x,30),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:wd}),se({id:"stale-abstractions",command:"stale-abstractions",agent:k("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum LOC",x,3),d("-n, --limit <n>","Number of results",x,30),d("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:xd}),se({id:"complexity-hotspots",command:"complexity-hotspots",agent:{...k("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum LOC",x,10),d("-n, --limit <n>","Number of results",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Rd}),ve({id:"convergence",command:"convergence <symbol1> <symbol2>",hidden:!0,agent:k("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Ld}),Yl({id:"redundant-reexports",command:"redundant-reexports",agent:k("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",x,30),d("--full","Run unbounded analysis on large indexes")],docs:R("Cleanup"),query:({db:e,opts:t})=>Ks(e,{scope:$(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
164
164
|
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
165
165
|
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
166
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).`)}),ve({id:"duplicate-bodies",command:"duplicate-bodies",agent:k("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:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC per function body",
|
|
168
|
-
`)}var
|
|
167
|
+
${e.length} redundant re-export(s).`)}),ve({id:"duplicate-bodies",command:"duplicate-bodies",agent:k("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:C([d("-s, --scope <path>","Limit to files matching path"),d("--max-loc <n>","Maximum LOC per function body",x,15),d("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),d("-n, --limit <n>","Number of groups",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:Ad}),ve({id:"twin-drift",command:"twin-drift",agent:k("Which same-concept twin implementations have drifted?","twin symbol pairs, history, and divergence evidence",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",Le,.3),d("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),d("-n, --limit <n>","Number of groups",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:jd}),se({id:"not-implemented",command:"not-implemented",agent:k("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:C([d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",x,30),d("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["codebaseiq not-implemented -s src/services"]),handler:Id}),se({id:"decorative-checkers",command:"decorative-checkers",agent:k("Which validation checks cannot meaningfully fail?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:C([d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",x,30),d("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["codebaseiq decorative-checkers -s src/services"]),handler:Nd}),ve({id:"test-quality",command:"test-quality",agent:k("Which tests have weak assertions or poor production-code reach?","test identities with assertion and reachability evidence",[],"bounded","repository"),description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:C([d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Maximum findings per sub-check",x,30),d("--rot-days <n>","Skips older than this many days are reported as rot",x,60),d("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:R("Cleanup",["codebaseiq test-quality -s tests/queries"]),handler:Dd}),ve({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:k("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete",void 0,z("mutation")),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (cleanup integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:C([d("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),d("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:R("Cleanup",["codebaseiq twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Od}),ve({id:"similar-signatures",command:"similar-signatures",agent:k("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Find functions with near-identical type signatures (same shape)",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--min-loc <n>","Minimum LOC per function",x,3),d("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),d("-n, --limit <n>","Number of groups",x,20),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Pd})];var Rb=X(({db:e,args:t,opts:n})=>{let i=Et(e);if(y(n,"json")){P("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${he(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Kd=[{id:"stats",command:"stats",description:"Show index statistics",agent:k("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:C(),renderShape:"custom",docs:R("Core"),handler:Rb}];var Cb=ze({commandName:"hotspots",resultSchemaVersion:2,query:({db:e,opts:t})=>jr(e,{limit:D(t,"limit",30),scope:$(t,"scope")}),emptyMessage:e=>Gt("reference hotspots","No reference hotspots found.",e),before:e=>Zd(e.coverage),render:e=>T.table(["refs","files","symbol"],e.rows.map(t=>` ${String(t.refCount).padStart(4)} ${String(t.fileCount).padStart(5)} ${t.shortName}`))}),kb=be("bottlenecks",{resultSchemaVersion:2,query:({db:e,opts:t,budget:n})=>Gr(e,{limit:D(t,"limit",20),scope:$(t,"scope"),minFanIn:E(t,"minFanIn",2),minFanOut:E(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),emptyMessage:e=>Gt("bottlenecks","No bottlenecks found.",e),before:e=>Zd(e.coverage),render:e=>T.table(["tier","risk","score","fan-in","fan-out","symbol"],e.rows.map(t=>` ${t.actionTier.padEnd(6)} ${t.riskKind.padEnd(20)} ${String(t.score).padStart(5)} ${String(t.fanIn).padStart(6)} ${String(t.fanOut).padStart(7)} ${t.shortName}`))});function Zd(e){let t=Ut(e);t&&console.log(`Semantic ranking coverage degraded: ${t} Missing evidence may change this ranking.
|
|
168
|
+
`)}var Eb=X(({db:e,args:t,opts:n})=>{let i=G(t,0),o=D(n,"limit",30);if(i){let c=Mr(e,i);if(y(n,"json")){P("fan-in",t,n,{mode:"symbol",symbol:i,rows:c});return}if(c.length===0)return T.empty(`No fan-in for ${i}.`);T.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let r=Fr(e,{limit:o,scope:$(n,"scope")});if(y(n,"json")){P("fan-in",t,n,{mode:"top",rows:r});return}let s=new Map;for(let c of r)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));T.table(["files","symbol"],r.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Tb=X(({db:e,args:t,opts:n})=>{let i=G(t,0),o=D(n,"limit",30);if(i){let s=qr(e,i);if(y(n,"json")){P("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return T.empty(`No fan-out for ${i}.`);T.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let r=Br(e,{limit:o,scope:$(n,"scope")});if(y(n,"json")){P("fan-out",t,n,{mode:"top",rows:r});return}T.table(["symbols","file"],r.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),Lb=X(({db:e,args:t,opts:n})=>{let i=G(t,0),o=G(t,1),r=D(n,"limit",20);if(i&&o){let a=Wr(e,i,o);if(y(n,"json")){P("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=_r(e,{limit:r,scope:$(n,"scope")});if(y(n,"json")){P("coupling",t,n,{mode:"top",rows:s});return}T.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}`))}),Pb=ze({commandName:"cycles",query:({db:e,opts:t})=>Vr(e,{scope:$(t,"scope"),maxDepth:E(t,"maxDepth",10),edgeBasis:y(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(`
|
|
169
169
|
Component ${t+1} (${i.length} files; ${n.classification??n.kind}; one witness follows):`);for(let o=0;o<n.path.length;o++){let r=o<n.path.length-1?" \u2192":" (cycle witness)";console.log(` ${n.path[o]}${r}`)}i.length>new Set(n.path.slice(0,-1)).size&&console.log(` Full component: ${i.join(", ")}`)}console.log(`
|
|
170
|
-
${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),
|
|
170
|
+
${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),Ab=ze({commandName:"architecture",query:({db:e,opts:t})=>pn(e,{scope:$(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .codebaseiq.json.",render:e=>{let t=Pt(e);if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),t.length===0?console.log("Architecture policy passed."):console.log(`Architecture policy failed with ${t.length} enforced finding(s). Update the code or narrow the declared policy before treating the structure as clean.`),e.policyCoverage.missingRows.length>0){let n=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${n}`)}if(e.coverage.unmappedFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}${n}`)}if(e.coverage.ambiguousFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}${n}`);for(let i of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${i.file} -> ${i.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
|
|
171
171
|
Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let n of e.forbiddenEdges){console.log(` ${n.from} -> ${n.to}: ${n.fileEdgeCount} file edge(s), ${n.importerCount} importer(s), ${n.importedFileCount} imported file(s)`);for(let i of n.examples)console.log(` ${i.fromFile} -> ${i.toFile}`)}}else console.log(`
|
|
172
172
|
No forbidden dependency edges found.`);if(e.staleAllowances.length>0){let n=e.policyCoverage.requiresMinimalPolicy?" [violates requireMinimalPolicy]":"";console.log(`
|
|
173
173
|
Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.${n}`);for(let i of e.staleAllowances)console.log(` ${i.from} -> ${i.to}`)}if(e.boundaryLimits.length>0){console.log(`
|
|
@@ -177,8 +177,8 @@ Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): th
|
|
|
177
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 n of e.coarseBoundaries){console.log(` ${n.boundary}: ${n.subUnits.join(" <-> ")}`);for(let i of n.narrowestEdges){console.log(` narrowest: ${i.from} -> ${i.to} (${i.fileEdgeCount} file edge(s))`);for(let o of i.examples.slice(0,3))console.log(` ${o.fromFile} -> ${o.toFile}`)}}}if(e.edges.length>0){console.log(`
|
|
178
178
|
Boundary graph (${e.edges.length} directed edge(s)):`);for(let n of e.edges)console.log(` ${n.from} -> ${n.to} ${n.policyStatus.padEnd(10)} ${n.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
|
|
179
179
|
Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let n of e.reciprocalPairs)console.log(` ${n.boundaries[0]} <-> ${n.boundaries[1]} ${n.forward.fileEdgeCount}/${n.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
|
|
180
|
-
Strongly connected boundary groups (${e.cycles.length}):`);for(let n of e.cycles){let i=n.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${n.boundaries.join(", ")} }${i}`);for(let o of n.narrowestEdges)console.log(` inspect ${o.from} -> ${o.to}: ${o.fileEdgeCount} file edge(s)`)}}},after:e=>{Pt(e).length>0&&(process.exitCode=1)}});function
|
|
181
|
-
Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of t[n].components){let o=i.length===1?i[0]:`{ ${i.join(", ")} } (cycle)`;console.log(` \u2192 ${o}`)}console.log(` Tier: ${t[n].actionTier} Risk: ${t[n].chainKind}`),console.log(` Recommendation: ${t[n].recommendation}`),console.log(` Evidence: ${t[n].evidenceReasons.join("; ")}`)}}})}var
|
|
180
|
+
Strongly connected boundary groups (${e.cycles.length}):`);for(let n of e.cycles){let i=n.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${n.boundaries.join(", ")} }${i}`);for(let o of n.narrowestEdges)console.log(` inspect ${o.from} -> ${o.to}: ${o.fileEdgeCount} file edge(s)`)}}},after:e=>{Pt(e).length>0&&(process.exitCode=1)}});function eu(e){return ze({commandName:e,query:({db:t,opts:n})=>zr(t,{limit:D(n,"limit",10),scope:$(n,"scope"),minDepth:E(n,"minDepth",3),edgeBasis:y(n,"importsOnly")?"imports":"symbol-references"}),emptyMessage:t=>t.length===0?"No deep chains found.":void 0,render:t=>{for(let n=0;n<t.length;n++){console.log(`
|
|
181
|
+
Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of t[n].components){let o=i.length===1?i[0]:`{ ${i.join(", ")} } (cycle)`;console.log(` \u2192 ${o}`)}console.log(` Tier: ${t[n].actionTier} Risk: ${t[n].chainKind}`),console.log(` Recommendation: ${t[n].recommendation}`),console.log(` Evidence: ${t[n].evidenceReasons.join("; ")}`)}}})}var jb=eu("deep-chains"),Ib=eu("dependency-depth"),Nb=X(({db:e,args:t,opts:n})=>{let i=G(t,0),o=Qr(e,{search:i,scope:$(n,"scope")});if(y(n,"json")){P("entrypoints",t,n,o,{coverage:{complete:!0,totalKnown:!0,returned:o.length,total:o.length,omitted:0}});return}let r=$(n,"scope");if(console.log(`\u2550\u2550\u2550 REQUEST \u2550\u2550\u2550
|
|
182
182
|
text=${i?JSON.stringify(i):"<all>"}; scope=${r??"<repository>"}`),o.length===0){console.log(`
|
|
183
183
|
\u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550
|
|
184
184
|
${i?`No detected entry candidate matched ${JSON.stringify(i)}.`:"No entry candidates were detected."}`),console.log(`
|
|
@@ -194,7 +194,7 @@ Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of
|
|
|
194
194
|
\u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
|
|
195
195
|
${o.length} entry candidate(s); complete within indexed detector evidence.`),console.log(`
|
|
196
196
|
\u2550\u2550\u2550 RECOVERY \u2550\u2550\u2550
|
|
197
|
-
Any printed exact symbol can be projected with codebaseiq evidence using the family and direction required by the material question.`)}),
|
|
197
|
+
Any printed exact symbol can be projected with codebaseiq evidence using the family and direction required by the material question.`)}),Db=X(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Xr(e,i,{expand:A(n,"expand")});if(y(n,"json")){P("entry-map",t,n,o,{coverage:o.kind==="matched"?{complete:!0,totalKnown:!0,returned:o.regions.length,total:o.regions.length,omitted:0}:{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0}});return}if(o.kind==="missing")return process.exitCode=1,T.empty(`No symbol matched '${i}'.`);if(o.kind==="ambiguous"){process.exitCode=1,console.error(`'${i}' is ambiguous across ${o.total} definitions:`);for(let s of o.candidates)console.error(` ${s.relativePath}:${I(s.startLine)} ${s.shortName}`),console.error(` symbol: ${s.symbol}`);return}if(o.kind==="not-entry")return process.exitCode=1,T.empty(`${o.shortName} (${o.file}) is not a detected entry point. ${o.reason}`);console.log(`Entry: ${o.entry.shortName} (${o.entry.file})`),console.log(`Evidence: ${o.entry.evidence.join(", ")}
|
|
198
198
|
`),console.log("\u2550\u2550\u2550 COLLAPSED FILE REGIONS \u2550\u2550\u2550");for(let s of o.regions){let a=s.expanded?"expanded":`expand with --expand '${s.id}'`;console.log(` depth ${s.minDepth} ${s.id}
|
|
199
199
|
${s.symbolCount} symbol(s); ${s.internalEdgeCount} internal edge(s); ${s.externalCallCount} unresolved/external call(s); ${s.incomingRegionIds.length} incoming region(s); ${s.outgoingRegionIds.length} outgoing region(s)
|
|
200
200
|
${a}`)}if(o.regionEdges.length>0){console.log(`
|
|
@@ -203,75 +203,75 @@ Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of
|
|
|
203
203
|
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`);for(let s of r){console.log(` ${s.id}`);for(let a of s.symbols)console.log(` depth ${a.depth} ${a.shortName}
|
|
204
204
|
${a.symbol}`);for(let a of s.internalEdges)console.log(` call ${a.fromShortName} \u2192 ${a.toShortName} (${a.source})`);for(let a of s.externalCalls)console.log(` unresolved/external ${a.fromShortName} \u2192 ${a.toShortName} (${a.reportedFile}; ${a.source})`)}}o.unmatchedExpansions.length>0&&console.error(`
|
|
205
205
|
Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
|
|
206
|
-
Coverage: ${o.coverage.symbolCount} symbol(s), ${o.coverage.symbolEdgeCount} call edge(s), ${o.coverage.regionCount} region(s), ${o.coverage.externalCallCount} unresolved/external call(s).`),console.log("Complete within indexed static call edges; dynamic dispatch is not represented.")}),
|
|
207
|
-
\u2550\u2550\u2550 QUERY CONNECTOR GRAPH \u2550\u2550\u2550`),console.log(` ${h.length}/${o.topology.nodes.length} node(s) selected; ${f.length} typed connector edge(s); ${b.length} reversible frontier group(s).`),o.topology.completion&&console.log(` [${o.topology.completion.status}] ${o.topology.completion.explanation}`);for(let j of o.topology.paths){let
|
|
206
|
+
Coverage: ${o.coverage.symbolCount} symbol(s), ${o.coverage.symbolEdgeCount} call edge(s), ${o.coverage.regionCount} region(s), ${o.coverage.externalCallCount} unresolved/external call(s).`),console.log("Complete within indexed static call edges; dynamic dispatch is not represented.")}),Ob=X(({db:e,args:t,opts:n})=>{let i=A(n,"selectionTerm"),o=Er(e,{searches:A(n,"search"),symbols:A(n,"symbol"),behaviorFocusLocations:A(n,"focusAt").map(Bb),maxDepth:E(n,"depth",5),expand:A(n,"expand"),relations:A(n,"relation"),evidenceFloor:$(n,"evidenceFloor"),sourceScopes:A(n,"sourceScope"),maxTopologyCharacters:E(n,"topologyCharacters",12e3),topologyFrontiers:A(n,"frontier"),routeIds:A(n,"route"),fullLiteralTraversal:y(n,"fullLiteralTraversal"),selectionTerms:i});if(i.length>0&&!y(n,"json")&&console.error("Deprecated: --selection-term is accepted as a no-op; graph selection is explicit and query-neutral."),y(n,"json")){P("system-map",t,n,o,{coverage:{complete:!1,totalKnown:!1,returned:o.regions.length}});return}if(y(n,"gapRecoveryOnly")){Mb(o.nextAnchors,A(n,"gapCallee"));return}let r=new Set(o.presentation.regionIds),s=new Set(o.presentation.relationKeys),a=o.regions.filter(p=>r.has(p.id)),c=o.regionRelations.filter(p=>s.has(`${p.fromRegionId}\0${p.toRegionId}`)),l=a.some(p=>p.expanded),u=!!(o.behavior&&o.behavior.steps.length>0);console.log("\u2550\u2550\u2550 EXPLICIT ANCHORS \u2550\u2550\u2550");for(let p of o.anchors){let h=p.kind==="literal"?`${p.matchingLines??0} matching line(s); ${p.seedMatchingLines??0} materialized source seed(s), ${p.matchOnlyLines??0} match-only, ${p.withheldMatchingLines??0} withheld before traversal`:`${p.totalSymbolCandidates??0} candidate definition(s)`;console.log(` [${p.status}] ${p.kind} ${p.query} \u2014 ${h}`),(p.seedRegionIds??[]).length>0&&console.log(` traversal seed regions: ${p.seedRegionIds.join(", ")}`),(p.matchOnlyRegionIds??[]).length>0&&console.log(` retained match-only regions: ${p.matchOnlyRegionIds.join(", ")}`);for(let f of p.representativeMatches??[]){let b=f.ownerShortName?` ${ae(f.ownerShortName)}`:"";console.log(` representative: ${f.file}:${I(f.line)}${b} \u2014 ${f.sourceLine.slice(0,160)}`)}for(let f of p.narrowingCommands??[])console.log(` narrow exactly: ${f}`);if(p.exhaustiveTraversalCommand&&console.log(` exhaustive recovery: ${p.exhaustiveTraversalCommand}`),p.kind==="symbol"&&p.matchedRegionIds.length>0&&console.log(` regions: ${p.matchedRegionIds.join(", ")}`),!l){let f=u?(p.symbolCandidates??[]).slice(0,3):p.symbolCandidates??[];for(let b of f)console.log(` ${b.relativePath}:${I(b.startLine)} ${ae(b.shortName)}`)}(p.omittedSymbolCandidates??0)>0&&console.log(` ${p.omittedSymbolCandidates} additional candidate(s) omitted by symbol resolution.`)}if(o.topology){let p=new Map(o.topology.nodes.map(j=>[j.id,j])),h=o.topology.nodes.filter(j=>j.disposition==="emitted"),f=o.topology.edges.filter(j=>j.disposition==="emitted"&&j.kind!=="structural-membership"&&j.fromNodeId!==j.toNodeId),b=o.topology.frontiers.filter(j=>j.disposition==="folded");console.log(`
|
|
207
|
+
\u2550\u2550\u2550 QUERY CONNECTOR GRAPH \u2550\u2550\u2550`),console.log(` ${h.length}/${o.topology.nodes.length} node(s) selected; ${f.length} typed connector edge(s); ${b.length} reversible frontier group(s).`),o.topology.completion&&console.log(` [${o.topology.completion.status}] ${o.topology.completion.explanation}`);for(let j of o.topology.paths){let W=j.nodeIds.map(w=>p.get(w)?.label??w);console.log(` [${j.status}] ${W.length>0?W.join(" \u2194 "):"no proved connector"}`)}let v=o.topology.routeCatalog;if(v){let j=new Set(v.selectedRouteIds);console.log(` Route catalogue [${v.coverage.status}]: ${v.routes.length} distinct proved public/runtime endpoint route(s); ${v.coverage.enumeration}; depth \u2264 ${v.coverage.maximumDepth}.`);for(let W of v.routes){let w=j.has(W.id)?"; selected":"",_=W.relatedEdgeFamilies.length>0?W.relatedEdgeFamilies.join(","):"control",U=W.nodeIds.map(O=>ae(p.get(O)?.label??O)).join(" \u2192 ");console.log(` [${W.id}; ${W.endpointKind}; ${W.edgeIds.length} edge(s); families ${_}${w}] ${U} @ ${W.endpointLocation.file}:${I(W.endpointLocation.line)}`)}v.coverage.anchorsWithoutRoutes.length>0&&console.log(` [no proved public/runtime route] ${v.coverage.anchorsWithoutRoutes.length} anchor node(s): `+v.coverage.anchorsWithoutRoutes.join(", ")),v.routes.length>0&&v.selectedRouteIds.length===0&&console.log(` Select only routes whose interior behavior is a named missing fact; repeat --route to batch: ${Fb(n,[])} --route '<route-id>'`)}let S=h.filter(j=>typeof j.attributes.upstreamCausalEndpoint=="string");if(S.length>0){console.log(" Upstream causal roots are the earliest source-backed constructs selected on bounded proved paths into the anchors; a traversal root has no earlier proved caller in this query graph and is not necessarily a public application entry.");for(let j of S){let W=j.location?` @ ${j.location.file}:${I(j.location.line)}`:"",w=Number(j.attributes.upstreamCausalDistance??0);console.log(` [${String(j.attributes.upstreamCausalEndpoint)}; ${w} edge(s) to anchor] ${ae(j.label)}${W}`)}}let L=u?4:8;for(let j of f.slice(0,L)){let W=p.get(j.fromNodeId)?.label??j.fromNodeId,w=p.get(j.toNodeId)?.label??j.toNodeId,_=[...new Set(j.evidence.map(U=>U.strength))].join("/");console.log(` ${W} \u2192 ${w} \u2014 ${j.kind} [${_}]`)}f.length>L&&console.log(` +${f.length-L} selected connector edge(s).`);let B=b.slice(0,u?1:2);for(let j of B){let W=j.memberNodeIds.slice(0,2).map(w=>p.get(w)?.label??w).join(", ");console.log(` [folded ${j.id}] ${j.memberCount} node(s), ${j.edgeIds.length} edge(s)${W?` \u2014 ${W}`:""}`)}let H=B.find(j=>j.expansion)?.expansion;if(H&&!u){let j=H.replace(/ --frontier '[^']+'$/u,"");console.log(` Expand shown frontiers together: ${j} ${B.map(W=>`--frontier '${W.id}'`).join(" ")}`)}b.length>B.length&&console.log(` +${b.length-B.length} frontier group(s); all exact members and expansion commands remain in the structured result.`),Wb(o.topology,o.behavior)}if(o.behavior&&o.behavior.steps.length>0){if(console.log(`
|
|
208
208
|
\u2550\u2550\u2550 CONNECTED BEHAVIOR \u2550\u2550\u2550`),console.log(` [${o.behavior.status}] ${o.behavior.steps.length}/${o.behavior.coverage.candidateNodes} selected construct(s); ${o.behavior.transitions.length} evidenced transition(s); ${o.behavior.coverage.withheldStatements} non-connector statement(s) withheld with exact-source recovery.`),o.behavior.coverage.requestedFocusLocations.length>0){console.log(` Question-aligned focus: ${o.behavior.coverage.matchedFocusLocations.length}/${o.behavior.coverage.requestedFocusLocations.length} exact location(s) fell inside selected constructs.`);for(let h of o.behavior.coverage.unmatchedFocusLocations)console.log(` [unmatched focus] ${h.file}:${I(h.line)}`)}console.log(" Read every relevant sibling branch under the explicit anchors before using optional gap recovery; the branch outcomes are jointly required behavior, not alternative search results.");let p=new Map(o.behavior.steps.map(h=>[h.id,h.order+1]));for(let h of o.behavior.steps){let f=h.location?` @ ${h.location.file}:${I(h.location.line)}`:"";if(console.log(` ${h.order+1}. [${h.role}; ${h.kind}] ${ae(h.label)}${f}`),!h.behavior)continue;let b=[` [${h.behavior.kind}; ${h.behavior.constructKind}] ${h.behavior.signature} (${h.behavior.renderedCharacters}/${h.behavior.rawCharacters} chars; ${h.behavior.coverage.representedStatements}/${h.behavior.coverage.sourceStatements} detected behavior statements selected)`];for(let v of h.behavior.lines){let S=v.signals.length>0?` [${v.signals.join(",")}]`:"";b.push(` ${I(v.line)}${S} ${" ".repeat(v.depth)}${v.text}`)}for(let v of h.behavior.supportingDeclarations??[]){let S=v.text.replace(/\s*\n\s*/gu," ");b.push(` [support; ${v.kind}] ${v.label} @ ${v.file}:${I(v.line)} \u2014 ${S}`)}for(let v of h.behavior.omittedSupportingDeclarations??[])b.push(` [support omitted; ${v.reason}] ${v.label} @ ${v.file}:${I(v.line)}-${I(v.endLine)}`);console.log(Rt({kind:"unit",identity:h.nodeId,content:b.join(`
|
|
209
209
|
`),label:ae(h.label),indent:" "}))}if(o.behavior.transitions.length>0){console.log(" Transitions (arrows preserve repository-edge direction):");for(let h of o.behavior.transitions){let f=h.evidence.map(L=>`${L.method}/${L.strength}`).join(", "),b=h.kind==="runtime-boundary"?[...new Set(h.evidence.flatMap(L=>typeof L.identity=="string"&&L.identity.length>0?[L.identity]:[]))]:[],v=p.get(h.fromStepId)??"?",S=p.get(h.toStepId)??"?";console.log(Rt({kind:"edge",identity:h.edgeId,content:` ${v} \u2192 ${S} \u2014 ${h.kind}; path=${h.pathTraversal}; ${f}`+(b.length>0?`; key=${b.join(" | ")}`:""),label:`${v} \u2192 ${S} ${h.kind}`,indent:" "}))}}o.behavior.coverage.omittedNodeIds.length>0&&console.log(` ${o.behavior.coverage.omittedNodeIds.length} bounded emitted construct(s) were not materialized; their identities remain in behavior.coverage.omittedNodeIds.`),o.behavior.exactSourceCommand&&console.log(" Exhaustive exact-source recovery (usually unnecessary; never combine with the drill batch below): "+o.behavior.exactSourceCommand)}if(o.nextAnchors&&o.nextAnchors.candidateAnchors>0){console.log(`
|
|
210
|
-
\u2550\u2550\u2550 ADJACENT RECOVERY INVENTORY \u2550\u2550\u2550`);let p=[...o.nextAnchors.anchors,...o.nextAnchors.withheldAnchors],h=new Map;for(let f of p){let b=`${f.direction}/${f.relationKind}/${f.causalRole}`;h.set(b,(h.get(b)??0)+1)}console.log(` ${o.nextAnchors.candidateAnchors} exact or candidate adjacent target(s) are recoverably folded.`);for(let[f,b]of[...h].sort(([v],[S])=>v.localeCompare(S)))console.log(` ${f}: ${b}`);console.log(` Select a named missing callee without relevance inference: ${
|
|
210
|
+
\u2550\u2550\u2550 ADJACENT RECOVERY INVENTORY \u2550\u2550\u2550`);let p=[...o.nextAnchors.anchors,...o.nextAnchors.withheldAnchors],h=new Map;for(let f of p){let b=`${f.direction}/${f.relationKind}/${f.causalRole}`;h.set(b,(h.get(b)??0)+1)}console.log(` ${o.nextAnchors.candidateAnchors} exact or candidate adjacent target(s) are recoverably folded.`);for(let[f,b]of[...h].sort(([v],[S])=>v.localeCompare(S)))console.log(` ${f}: ${b}`);console.log(` Select a named missing callee without relevance inference: ${qb(n,["<callee-from-connected-behavior>"])}.`)}if(o.regions.length===0)console.log(`
|
|
211
211
|
No structural regions matched the supplied anchors.`);else{console.log(`
|
|
212
212
|
\u2550\u2550\u2550 COLLAPSED SYSTEM REGIONS \u2550\u2550\u2550`);for(let p of a){let h=p.expanded?"expanded":"collapsed",f=p.notableSymbols.slice(0,2);if(l){console.log(` d${p.minDepth} [${h}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}`);continue}if(u){console.log(` d${p.minDepth} [${h}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out`);continue}console.log(` depth ${p.minDepth} [${h}] ${p.id} \u2014 ${p.fileCount} file (${p.sourceFileCount} src/${p.testFileCount} test); ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}
|
|
213
213
|
anchors: ${p.anchorQueries.join(", ")||"none"}; drill: ${f.map(b=>`${ae(b.shortName)} (${b.file})`).join(", ")||"none"}${p.symbolCount>f.length?`; +${p.symbolCount-f.length}`:""}`)}}if(o.presentation.complete||(console.log(`
|
|
214
|
-
\u2550\u2550\u2550 TOPOLOGY WITHHELD MANIFEST \u2550\u2550\u2550`),console.log(` The ${o.presentation.maxCharacters}-character topology budget selected ${o.presentation.regionIds.length}/${o.regions.length} region(s) and ${o.presentation.relationKeys.length}/${o.regionRelations.length} cross-region relation(s).`),o.presentation.omittedRegionIds.length>0&&console.log(` Withheld region ids: ${
|
|
214
|
+
\u2550\u2550\u2550 TOPOLOGY WITHHELD MANIFEST \u2550\u2550\u2550`),console.log(` The ${o.presentation.maxCharacters}-character topology budget selected ${o.presentation.regionIds.length}/${o.regions.length} region(s) and ${o.presentation.relationKeys.length}/${o.regionRelations.length} cross-region relation(s).`),o.presentation.omittedRegionIds.length>0&&console.log(` Withheld region ids: ${Yd(o.presentation.omittedRegionIds,12)}.`),console.log(` Structured JSON retains all facts. Expand the human topology without paging: ${o.presentation.expansionCommand}`)),!l&&!u&&o.expansion?.command&&(console.log(`
|
|
215
215
|
\u2550\u2550\u2550 NEXT ABSTRACTION LEVEL \u2550\u2550\u2550`),o.expansion.command)){let p=o.regions.length-o.expansion.regionCount,h=o.expansion.candidateRegionCount??o.expansion.regionCount,f=o.expansion.omittedRegionIds??[];console.log(` Expand ${o.expansion.regionCount}/${h} ranked traversal-relevant region(s) in one complete child-file summary; ${p} other observed region(s) remain visible above.`),console.log(` Expand together: ${o.expansion.command}`),f.length>0&&console.log(` Withheld traversal-relevant regions: ${f.join(", ")}. Add several --expand selectors to the command when they can change the decision.`)}if(c.length>0){console.log(`
|
|
216
|
-
\u2550\u2550\u2550 CROSS-REGION RELATIONSHIPS \u2550\u2550\u2550`),u||console.log(" Evidence A=AST callsite; M=source candidate (receiver type unproved); S=semantic callee; C=SCIP chunk; K=cross-workspace contract symbol; I=index/source import; R=index/source reference; B=proven runtime-boundary join.");for(let p of c)console.log(` ${
|
|
217
|
-
\u2550\u2550\u2550 UNRESOLVED RUNTIME BOUNDARIES \u2550\u2550\u2550`);let p=
|
|
218
|
-
\u2550\u2550\u2550 EXTERNAL IMPORT BOUNDARIES \u2550\u2550\u2550`),console.log(u?` ${o.externalBoundaries.length} imported external symbol(s) remain accounted in the structured result.`:` ${o.externalBoundaries.length} imported external symbol(s): ${
|
|
219
|
-
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`),console.log(" Every child file is listed. d=depth; S/T/E/B/W=source/test/entry/barrel/worker; sym/hit/rel counts are complete; C/I/R/B=call/import/reference/runtime-boundary; x=connected-region count; final names are ranked symbol@line drill candidates.");for(let p of m)console.log(` ${p.label} (${p.id})`),
|
|
216
|
+
\u2550\u2550\u2550 CROSS-REGION RELATIONSHIPS \u2550\u2550\u2550`),u||console.log(" Evidence A=AST callsite; M=source candidate (receiver type unproved); S=semantic callee; C=SCIP chunk; K=cross-workspace contract symbol; I=index/source import; R=index/source reference; B=proven runtime-boundary join.");for(let p of c)console.log(` ${Jd(p.fromRegionId)} \u2192 ${Jd(p.toRegionId)} \u2014 ${p.relationCount} rel [${p.kinds.join(",")}; ${p.evidence.map(Qb).join(",")}]`)}if(o.boundaryFrontiers.length>0){console.log(`
|
|
217
|
+
\u2550\u2550\u2550 UNRESOLVED RUNTIME BOUNDARIES \u2550\u2550\u2550`);let p=Hb(o.boundaryFrontiers),h=p.slice(0,u?3:8);for(let f of h){let b=f.frontiers.slice(0,u?1:2).map(v=>`${Kb(v.address)} @ ${v.file}:${I(v.line)}`);console.log(` [${f.strength}] ${f.action} \xD7${f.frontiers.length} \u2014 ${b.join("; ")}`),u||console.log(` ${f.reason}`)}p.length>h.length&&console.log(` ${p.length-h.length} additional frontier bucket(s); every observation and reason remains in --json.`),u&&console.log(" These are disclosed candidate observations, not proven connector edges; expand only when a named missing fact crosses one of them.")}o.externalBoundaries.length>0&&(console.log(`
|
|
218
|
+
\u2550\u2550\u2550 EXTERNAL IMPORT BOUNDARIES \u2550\u2550\u2550`),console.log(u?` ${o.externalBoundaries.length} imported external symbol(s) remain accounted in the structured result.`:` ${o.externalBoundaries.length} imported external symbol(s): ${Yd(o.externalBoundaries.map(p=>p.name),12)}. Use --json when the complete external-import list can change the decision.`));let m=a.filter(p=>p.expanded);if(m.length>0){console.log(`
|
|
219
|
+
\u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`),console.log(" Every child file is listed. d=depth; S/T/E/B/W=source/test/entry/barrel/worker; sym/hit/rel counts are complete; C/I/R/B=call/import/reference/runtime-boundary; x=connected-region count; final names are ranked symbol@line drill candidates.");for(let p of m)console.log(` ${p.label} (${p.id})`),Ub(p);o.drilldown?.command&&(console.log(`
|
|
220
220
|
\u2550\u2550\u2550 BATCHED DRILL-DOWN \u2550\u2550\u2550`),console.log(` ${o.drilldown.selectedAnchors}/${o.drilldown.candidateAnchors} coverage-diverse child-file anchor(s) selected${o.drilldown.omittedAnchors>0?`; ${o.drilldown.omittedAnchors} withheld by the ranked drill-down budget and still listed above`:""}.`),console.log(` Inspect the selected behavior together: ${o.drilldown.command}`),o.drilldown.definitionCommand&&console.log(` Full-source escalation for the selected exact units: ${o.drilldown.definitionCommand}`))}o.unmatchedExpansions.length>0&&console.error(`
|
|
221
221
|
Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
|
|
222
222
|
Query plan: relations=${o.coverage.requestedRelationKinds.join(",")}; evidence>=${o.coverage.evidenceFloor}; scopes=${o.coverage.includedSourceScopes.join(",")}.`),console.log(`Query closure: ${o.closure.status}; emitted ${o.closure.emitted.regions} region(s), ${o.closure.emitted.relations} relation(s), and ${o.closure.emitted.runtimeLinks} runtime link(s); withheld ${o.closure.withheld.symbols} symbol(s), ${o.closure.withheld.files} file(s), ${o.closure.withheld.regions} region(s), and ${o.closure.withheld.drillAnchors} drill anchor(s); ${o.closure.ambiguous.anchors} ambiguous anchor(s), ${o.closure.external} external boundary(ies), ${o.closure.unresolved} unresolved runtime frontier(s).`),console.log(` ${o.closure.explanation}`),console.log(`
|
|
223
223
|
Coverage: ${o.coverage.matchedAnchorCount}/${o.coverage.explicitAnchorCount} anchor(s) matched; ${o.regions.length} region(s); depth ${o.coverage.maxTraversalDepth}; ${o.coverage.frontierSymbols} untraversed symbol(s); ${o.coverage.frontierFiles} untraversed file(s); ${o.coverage.supportFilesNotTraversed} visible support file(s) not traversed; ${o.coverage.filteredUnverifiedCallEdges} unverified call edge(s) filtered; ${o.coverage.memberCallCandidateEdges} source-attributed member-call candidate edge(s); ${o.coverage.unresolvedMemberCallsites} unresolved member callsite(s); ${o.coverage.runtimeBoundaryTraversedLinks}/${o.coverage.runtimeBoundaryExactLinks+o.coverage.runtimeBoundaryDerivedLinks} map-relevant proven runtime-boundary link(s) traversed (${o.coverage.repositoryRuntimeBoundaryExactLinks+o.coverage.repositoryRuntimeBoundaryDerivedLinks} repository-wide); ${o.coverage.runtimeBoundaryCandidateLinks} candidate boundary link(s); ${o.coverage.runtimeBoundaryFrontiers} relevant unresolved boundary frontier(s); ${o.coverage.referenceExpansionEligibleSymbols} symbol(s) reverse-expanded and ${o.coverage.referenceExpansionSkippedSymbols} discovered symbol(s) not reverse-expanded.`),o.coverage.symbolCandidateSetsComplete||console.log(`Symbol resolution omitted ${o.coverage.omittedSymbolCandidates} ambiguous candidate(s).`),console.log("Blind spots:");let g=u?o.coverage.blindSpots.slice(0,2):o.coverage.blindSpots;for(let p of g)console.log(` - ${p}`);if(o.coverage.blindSpots.length>g.length&&console.log(` - ${o.coverage.blindSpots.length-g.length} additional disclosed limitation(s) remain in coverage.blindSpots.`),u){let p=new Map([["branch conditions",new Map],["structured payloads",new Map],["terminal outcomes",new Map]]);for(let h of o.behavior?.steps??[])if(!(!h.location||!h.behavior))for(let f of h.behavior.lines){let b=`${h.location.file}:${I(f.line)}`;f.signals.includes("branch")&&p.get("branch conditions")?.set(b,null),f.signals.includes("shape")&&(f.signals.includes("call")||f.signals.includes("mutation")||f.signals.includes("return"))&&p.get("structured payloads")?.set(b,f.text.replace(/\s*\n\s*/gu," ")),(f.signals.includes("return")||f.signals.includes("throw"))&&p.get("terminal outcomes")?.set(b,null)}console.log(`
|
|
224
|
-
\u2550\u2550\u2550 ANSWER EVIDENCE CONTRACT \u2550\u2550\u2550`),console.log(" Before another query, account for each question-relevant condition and outcome already rendered above. Preserve exact ownership/lifetime (including singleton/shared/per-invocation scope), normalization and path rules, invocation arguments, working directory and standard I/O, bounds/defaults, returned fields or instructions, every condition that stops or continues the enclosing loop, policy or dispatch precedence and bypass scope, and rethrown-versus-rendered interruption behavior."),console.log(" Draft audit locations are mechanically derived from selected syntax. For every category material to the question, explicitly account for every listed location:");for(let[h,f]of p)if(f.size!==0)if(h==="structured payloads"){console.log(` Draft audit \u2014 ${h}:`);for(let[b,v]of f)console.log(` ${b} \u2014 ${v??""}`)}else console.log(` Draft audit \u2014 ${h}: ${[...f.keys()].join(", ")}`);console.log(" No causal target is automatically recommended. Use the adjacent recovery inventory only for a named material fact with no rendered evidence; otherwise answer from the map.")}});function
|
|
225
|
-
\u2550\u2550\u2550 CAUSAL CORRIDOR \u2550\u2550\u2550`),console.log(` [${n.status}] ${n.startNodeIds.length} anchor node(s) \u2192 ${n.outcomeNodeIds.length} mechanical outcome(s); ${n.coverage.protectedNodes} protected node(s), ${n.coverage.protectedEdges} protected edge(s).`),console.log(` Starts: ${r(n.startNodeIds)||"none proved"}`),console.log(` Outcomes: ${Kb(n.outcomeNodeIds,e)}`);for(let[p,h]of[...s].sort(([f],[b])=>f.localeCompare(b))){let f=new Map;for(let v of new Set(h)){let S=i.get(v)?.kind??"unknown";f.set(S,(f.get(S)??0)+1)}let b=[...f].sort(([v],[S])=>v.localeCompare(S)).map(([v,S])=>`${v}\xD7${S}`).join(", ");console.log(` [owns] ${r([p])} \u2192 ${new Set(h).size} local construct(s) [${b}]`)}for(let[p,h]of[...l].sort(([f],[b])=>f.localeCompare(b))){let f=[...h].sort(([b],[v])=>b.localeCompare(v)).map(([b,v])=>`${b}\xD7${v}`).join(", ");console.log(` [local-control] ${r([p])} \u2014 ${f}; exact decisions are represented below`)}for(let[p,h]of[...u].sort(([f],[b])=>f.localeCompare(b)))for(let f of[...h.values()].sort((b,v)=>(b.controllerLocation?.file??"").localeCompare(v.controllerLocation?.file??"")||(b.controllerLocation?.line??-1)-(v.controllerLocation?.line??-1)||b.controllerLabel.localeCompare(v.controllerLabel))){let b=[...f.outcomes].sort(([S],[L])=>S.localeCompare(L)).flatMap(([S,L])=>[...L].sort().map(W=>`${S} \u2192 ${W}`)).join("; "),v=f.controllerLocation?` @ ${f.controllerLocation.file}:${I(f.controllerLocation.line)}`:"";console.log(` [local-control] ${r([p])}: ${f.controllerLabel} \u2014 ${b}${v}`)}for(let p of[...g.values()].sort((h,f)=>h.ownerLabel.localeCompare(f.ownerLabel)||h.family.localeCompare(f.family)||h.subtype.localeCompare(f.subtype))){let h=p.family==="control"?`; targets=[${[...p.targetLabels].sort().join(", ")}]`:p.family==="data"&&p.subtype==="constant-to-parameter"?`; values=[${[...p.values].sort().join(", ")}]`:p.family==="data"?`; ${p.targetLabels.size} parameter target(s)`:"",f=p.ownerLocation?` @ ${p.ownerLocation.file}:${I(p.ownerLocation.line)}`:"";console.log(` [${p.family}:${p.subtype}; grouped] ${p.ownerLabel} \u2014 ${p.count} proved edge(s)${h}${f}`)}for(let{edge:p,semantic:h}of m){let f={...h.context??{},...h.attributes??{}},b=Object.entries(f).map(([S,L])=>`${S}=${String(L)}`).join(", "),v=p.evidence.find(S=>S.location)?.location;console.log(` [${h.family}:${h.subtype}] ${r([p.fromNodeId])} \u2192 ${r([p.toNodeId])}${b?`; ${b}`:""}${v?` @ ${v.file}:${I(v.line)}`:""}`)}console.log(` Frontier manifest: ${n.accountedFrontierIds.length} accounted; ${n.unresolvedFrontierIds.length} unsupported; ${n.unresolvedEdgeIds.length} candidate/unknown edge(s).`),g.size>0&&console.log(" Grouped edge identities remain in the structured corridor; inspect a named owner only when that flow is material."),n.status==="incomplete"&&console.log(` ${n.explanation}`)}function Ub(e,t){return e==="control"&&Vi(t)||e==="data"&&["argument-to-parameter","constant-to-parameter"].includes(t)||e==="temporal"&&["await-completion-before","awaits-completion","lexical-successor"].includes(t)}function Hb(e,t){let n=t.get(e),i=typeof n?.attributes.ownerNodeId=="string"?n.attributes.ownerNodeId:null,o=i?t.get(i):null,r=typeof n?.attributes.ownerSymbol=="string"?n.attributes.ownerSymbol:null;return{label:ae(o?.label??r??n?.label??e),location:o?.location??n?.location??null}}function Vi(e){return["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e)}function Kb(e,t){if(e.length===0)return"none proved";let n=new Set(e),i=new Map(t.nodes.map(l=>[l.id,l])),o=new Set,r=new Set,s=0,a=0,c=new Set;for(let l of t.edges)if(n.has(l.toNodeId))for(let u of l.semantics??[])u.family==="state"?(o.add(ae(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):u.family==="control"&&Vi(u.subtype)?(r.add(ae(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):u.family==="control"&&u.subtype==="returns"?(s+=1,c.add(l.toNodeId)):u.family==="control"&&u.subtype==="throws"&&(a+=1,c.add(l.toNodeId));return[r.size>0?`navigation=[${[...r].sort().join(", ")}]`:"",o.size>0?`resources=[${[...o].sort().join(", ")}]`:"",s>0?`return\xD7${s}`:"",a>0?`throw\xD7${a}`:"",e.length>c.size?`other-causal-sink\xD7${e.length-c.size}`:""].filter(Boolean).join("; ")}function Z(e){return`'${e.replaceAll("'","'\\''")}'`}function zb(e){let t=Zd(e.symbols,o=>o.file),n=Zd(e.literalHits,o=>o.file),i=new Map;for(let o of e.relations)for(let r of new Set([o.fromFile,o.toFile])){if(!e.files.some(a=>a.file===r))continue;let s=i.get(r)??[];s.push(o),i.set(r,s)}for(let o of e.files){let r=(t.get(o.file)??[]).sort(ey),s=n.get(o.file)??[],a=i.get(o.file)??[],c=r.slice(0,4),l=[...new Set(a.map(g=>g.kind))].sort(),u=[...new Set(a.flatMap(g=>[g.fromRegionId,g.toRegionId].filter(p=>p!==e.id)))].sort(),m=c.length>0?c.map(g=>`${ae(g.shortName)}@${I(g.startLine)}`).join(", ")+(r.length>c.length?`; +${r.length-c.length}`:""):"none";console.log(` d${o.depth} ${Xb(o.kind)} ${o.file} | sym${r.length} hit${s.length} rel${a.length}${l.length>0?`:${l.map(Yb).join("/")}`:""} x${u.length} | ${m}`);for(let g of s)console.log(` literal ${g.query}@${I(g.line)} ${g.sourceLine}`)}}function ae(e){return e.split(":").at(-1)||e}function Jb(e){let t=new Map;for(let n of e){let i=`${n.strength}\0${n.action}\0${n.reason}`,o=t.get(i)??{action:n.action,strength:n.strength,reason:n.reason,frontiers:[]};o.frontiers.push(n),t.set(i,o)}return[...t.values()].sort((n,i)=>i.frontiers.length-n.frontiers.length||n.action.localeCompare(i.action))}function Qb(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=120?t:`${t.slice(0,117)}...`}function Yd(e){return e.replace(/^region:(?:apps|packages)\//,"")}function Xb(e){return{source:"S",test:"T",entry:"E",barrel:"B",worker:"W"}[e]??e}function Yb(e){return{call:"C","contract-symbol":"K",import:"I",reference:"R","runtime-boundary":"B"}[e]??e}function Zb(e){return e.startsWith("runtime-boundary:")?`B:${e.slice(17)}`:{"ast-callsite":"A","ast-member-import-candidate":"M","compiler-cross-workspace-symbol":"K","semantic-callee":"S","scip-chunk":"C","indexed-or-source-import":"I","indexed-or-source-reference":"R"}[e]??e}function Zd(e,t){let n=new Map;for(let i of e){let o=t(i),r=n.get(o)??[];r.push(i),n.set(o,r)}return n}function ey(e,t){return eu(e.origins)-eu(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function eu(e){return e.includes("symbol-anchor")?0:e.includes("literal-owner")?1:e.some(t=>t.startsWith("boundary-import:"))?2:e.includes("reference-owner")?3:4}function tu(e,t){let n=e.slice(0,t);return`${n.join(", ")}${e.length>n.length?`; ${e.length-n.length} more`:""}`}var ou=[{id:"hotspots",command:"hotspots",description:"Rank symbols by cross-file reference count; a reference metric, not runtime contention",agent:{...k("Which symbols have the most observed cross-file reference evidence?","ranked symbol identities with explicit evidence basis and counting units",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results",w,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),docs:R("Graph"),renderShape:"table",handler:Tb},{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:{...Ie("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",ce,gt(["symbol","construct"],["Entry-point detection reports evidenced external roots and candidates; it does not establish task relevance."])),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results for top mode",w,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Pb},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:k("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:C([d("-n, --limit <n>","Number of results for top mode",w,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Ab},{id:"coupling",command:"coupling [file1] [file2]",description:"Count shared-symbol coupling between two files, or rank file pairs by that metric",agent:k("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:C([d("-n, --limit <n>","Number of results for top mode",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:jb},{id:"cycles",command:"cycles",description:"Find every cyclic file-dependency component and show one deterministic witness for each",agent:k("Which file dependency cycles exist?","dependency-cycle file chains",[],"complete","repository"),options:C([d("-s, --scope <path>","Limit to files matching path"),d("--imports-only","Analyze only resolved file imports instead of all cross-file symbol references"),d("--max-depth <n>","Deprecated compatibility option; SCC detection no longer truncates by depth",w,10)]),renderShape:"custom",docs:R("Graph"),handler:Ib},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:k("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:C([d("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",claims:qe(["index-generation","live-workspace"],[X("declared-policy","boundaries","repository-source"),X("dependency-observations","edges","compiler-graph"),X("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:R("Graph",["codebaseiq architecture --json"]),handler:Nb},{id:"bottlenecks",command:"bottlenecks",description:"Rank coordination hubs by incoming evidence files \xD7 outgoing cross-file callable targets",agent:{...k("Which callable symbols are high-connectivity coordination hubs?","ranked callable symbols with incoming evidence-file and outgoing callable-target counts",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results",w,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-fan-in <n>","Minimum fan-in",w,2),d("--min-fan-out <n>","Minimum fan-out",w,2),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:R("Graph"),handler:Lb},{id:"deep-chains",command:"deep-chains",hidden:!0,description:"Deprecated alias for dependency-depth",agent:k("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:C([d("-n, --limit <n>","Number of chains to show",w,10),d("-s, --scope <path>","Limit to files matching path"),d("--min-depth <n>","Minimum chain depth",w,3),d("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Db},{id:"dependency-depth",command:"dependency-depth",description:"Find longest paths through the SCC-condensed file dependency graph",agent:k("Which file dependency paths have the greatest condensed depth?","ranked component paths with full cycle membership, edge basis, and condensed depth",[],"bounded","repository"),options:C([d("-n, --limit <n>","Number of paths to show",w,10),d("-s, --scope <path>","Limit to files matching path"),d("--min-depth <n>","Minimum condensed component depth",w,3),d("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Ob},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...Ie("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and indexed caller counts",["pattern"],"complete","repository",ce,gt(["symbol","construct"],["A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress.","Entry classification does not establish that the callable executes."],{ranking:"identity-only",manualInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",outputCost:"bounded",frontierClosure:["evidence","inspect","code"]})),contrasts:[{command:"entry-map",distinction:"entrypoints locates possible external roots; entry-map traverses static calls from one selected root."},{command:"search",distinction:"entrypoints classifies callable roots; search only locates exact text and ownership."}]},options:C([d("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Graph",["codebaseiq entrypoints","codebaseiq entrypoints work-session"]),handler:Mb},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...Ie("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,ce,It({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:C([d("--expand <region-id>","Expand one file region; repeat to expand several together",F,[])]),renderShape:"custom",docs:R("Graph",["codebaseiq entry-map start","codebaseiq entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:qb},{id:"system-map",command:"system-map",hidden:!0,description:"Deprecated compatibility view for collapsed regions and legacy route catalogues; use evidence",agent:Ie("Which components and proven compiler or runtime relationships connect these explicit literals or symbols?","all matched anchors, collapsed structural regions, compiler and exact runtime relationships, unresolved boundary frontiers, simultaneous drilldown summaries, and explicit coverage gaps",[],"bounded","repository",ce,It({rootKinds:["text","symbol","construct","runtime-key"],edgeFamilies:Ke,directions:["incoming","outgoing","both"],operations:["reachability","connecting"],compression:["topology"],nonClaims:["Legacy region and next-anchor ranking does not establish task relevance.","Structural region membership does not establish execution."],compatibility:"deprecated"})),options:C([d("--search <literal>","Add an exact indexed-source anchor; repeat to include several",F,[]),d("--symbol <symbol>","Add a symbol anchor; repeat to include several",F,[]),d("--focus-at <file:line>","Focus connected behavior at one exact source location inside a selected construct; repeat to include several",F,[]),d("--depth <n>","Traverse this many relationship levels",w,5),d("--relation <kind>","Traverse one relation family; repeat for call, contract-symbol, import, reference, or runtime-boundary",F,[]),d("--evidence-floor <floor>","Runtime evidence floor: exact or derived"),d("--topology-characters <n>","Soft character budget for the first human topology view; complete JSON facts remain available",w,12e3),d("--source-scope <scope>","Include one source scope; repeat for production, test, fixture, example, generated, script, or unknown",F,[]),d("--full-literal-traversal","Traverse every literal match after deliberately accepting broad-selector expansion"),d("--expand <region-id>","Expand one structural region; repeat to expand several together",F,[]),d("--frontier <frontier-id>","Expand one accounted topology frontier; repeat to expand several together",F,[]),d("--route <route-id>","Select one proved upstream route; repeat to materialize several routes together",F,[]),d("--gap-callee <name>","Resolve one callee already shown in connected behavior; repeat to batch a named gap",F,[]),d("--selection-term <term>","Deprecated no-op retained for command compatibility; query vocabulary no longer changes graph selection",F,[]),d("--gap-recovery-only","Render only the --gap-callee targets and one exact batched recovery command")]),evidence:"mixed",claims:qe(["index-generation","live-workspace"],[X("matched-anchors","anchors","compiler-graph"),X("typed-relations","regionRelations","repository-source"),X("structural-grouping","regions","heuristic"),X("coverage","coverage","repository-source")]),renderShape:"custom",docs:R("Compatibility"),handler:Fb},dt({id:"call-graph",command:"call-graph <symbol>",description:"Show static may-call edges with exact/candidate evidence and explicit blind spots",agent:k("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:[d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:R("Graph"),query:({db:e,args:t,budget:n})=>Tt(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}
|
|
226
|
-
`))},toJson:(e,{db:t,args:n})=>$e(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.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.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
|
|
227
|
-
`),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),
|
|
224
|
+
\u2550\u2550\u2550 ANSWER EVIDENCE CONTRACT \u2550\u2550\u2550`),console.log(" Before another query, account for each question-relevant condition and outcome already rendered above. Preserve exact ownership/lifetime (including singleton/shared/per-invocation scope), normalization and path rules, invocation arguments, working directory and standard I/O, bounds/defaults, returned fields or instructions, every condition that stops or continues the enclosing loop, policy or dispatch precedence and bypass scope, and rethrown-versus-rendered interruption behavior."),console.log(" Draft audit locations are mechanically derived from selected syntax. For every category material to the question, explicitly account for every listed location:");for(let[h,f]of p)if(f.size!==0)if(h==="structured payloads"){console.log(` Draft audit \u2014 ${h}:`);for(let[b,v]of f)console.log(` ${b} \u2014 ${v??""}`)}else console.log(` Draft audit \u2014 ${h}: ${[...f.keys()].join(", ")}`);console.log(" No causal target is automatically recommended. Use the adjacent recovery inventory only for a named material fact with no rendered evidence; otherwise answer from the map.")}});function Mb(e,t){if(console.log("\u2550\u2550\u2550 OPTIONAL GAP RECOVERY (ONLY AFTER NAMING A MISSING FACT) \u2550\u2550\u2550"),!e||e.candidateAnchors===0){console.log(" No causal drill targets were resolved from the connected behavior.");return}if(t.length===0)throw new Error("--gap-recovery-only requires at least one --gap-callee named in connected behavior.");let n=new Set(t.map(zd)),i=[...e.anchors,...e.withheldAnchors].filter(r=>[r.callsite.calleeLeaf,...r.alternatives.map(s=>s.label)].some(s=>n.has(zd(s))));if(i.length===0){console.log(` No resolved target matched ${t.map(Y).join(", ")}. Copy callee names exactly from connected behavior.`);return}console.log(` ${i.length}/${e.candidateAnchors} causal target(s) matched the named callee selector(s); no English intent inferred.`);for(let r of i){let s=r.alternatives[0],a=s?`${ae(s.label)} @ ${s.file}:${I(s.line)}`:r.callsite.calleeLeaf,c=r.callsite.signals.filter(u=>u!=="anchor"&&u!=="call").join(","),l=[r.direction,r.causalRole,r.relationKind].filter(Boolean).join("; ");if(console.log(` [${r.status}; ${r.source}${l?`; ${l}`:""}${c?`; ${c}`:""}] ${a}${r.alternativeCount>1?` \u2014 ${r.alternativeCount} possible identities`:""}`),console.log(` from ${ae(r.fromLabel)} @ ${r.callsite.file}:${I(r.callsite.line)} \u2014 `+r.callsite.text.slice(0,220)),r.alternativeCount>1)for(let u of r.alternatives)console.log(` candidate: ${ae(u.label)} @ ${u.file}:${I(u.line)}`)}let o=new Map;for(let r of i){if(r.alternativeCount!==1)continue;let s=r.alternatives[0];s&&o.set(`${s.file}:${s.line}`,s)}o.size>0&&console.log(` Inspect named targets together: codebaseiq inspect ${[...o.values()].map(r=>`--at ${Y(`${r.file}:${I(r.line)}`)}`).join(" ")} --view behavior`),i.some(r=>r.source==="leaf-identity-candidate"||r.status==="ambiguous")&&console.log(" Identity candidates locate possible definitions but do not prove the receiver-to-callee edge; confirm before making a relationship claim.")}function qb(e,t=A(e,"gapCallee")){let n=["codebaseiq","system-map"];for(let o of A(e,"search"))n.push("--search",Y(o));for(let o of A(e,"symbol"))n.push("--symbol",Y(o));for(let o of A(e,"focusAt"))n.push("--focus-at",Y(o));n.push("--depth",String(E(e,"depth",5)));for(let o of A(e,"relation"))n.push("--relation",Y(o));let i=$(e,"evidenceFloor");i&&n.push("--evidence-floor",Y(i));for(let o of A(e,"sourceScope"))n.push("--source-scope",Y(o));y(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of A(e,"expand"))n.push("--expand",Y(o));for(let o of A(e,"frontier"))n.push("--frontier",Y(o));for(let o of A(e,"route"))n.push("--route",Y(o));for(let o of t)n.push("--gap-callee",Y(o));return n.push("--gap-recovery-only"),n.join(" ")}function Fb(e,t){let n=["codebaseiq","system-map"];for(let o of A(e,"search"))n.push("--search",Y(o));for(let o of A(e,"symbol"))n.push("--symbol",Y(o));for(let o of A(e,"focusAt"))n.push("--focus-at",Y(o));n.push("--depth",String(E(e,"depth",5)));for(let o of A(e,"relation"))n.push("--relation",Y(o));let i=$(e,"evidenceFloor");i&&n.push("--evidence-floor",Y(i));for(let o of A(e,"sourceScope"))n.push("--source-scope",Y(o));y(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of A(e,"expand"))n.push("--expand",Y(o));for(let o of A(e,"frontier"))n.push("--frontier",Y(o));for(let o of t)n.push("--route",Y(o));return n.join(" ")}function zd(e){let t=e.replace(/\(\)$/u,"").replace(/^#/u,"");return(t.slice(Math.max(t.lastIndexOf(":"),t.lastIndexOf("."))+1)||t).toLocaleLowerCase()}function Bb(e){let t=e.match(/^(.+):(\d+)$/u),n=t?Number(t[2]):Number.NaN;if(!t||!Number.isSafeInteger(n)||n<=0)throw new Error(`Invalid --focus-at location '${e}'; expected path:line with a positive line number.`);return{file:t[1],line:n-1}}function Wb(e,t){let n=e.corridor;if(!n)return;let i=new Map(e.nodes.map(p=>[p.id,p])),o=new Map(e.edges.map(p=>[p.id,p])),r=p=>p.map(h=>ae(i.get(h)?.label??h)).join(", "),s=new Map,a=new Map;for(let p of t?.steps??[]){if(!p.location||!p.behavior)continue;let h=a.get(p.location.file)??[];h.push(...p.behavior.lines.map(f=>({line:f.line,endLine:f.endLine}))),a.set(p.location.file,h)}let c=p=>p?.location?(a.get(p.location.file)??[]).some(h=>p.location.line>=h.line&&p.location.line<=h.endLine):!1,l=new Map,u=new Map,m=[],g=new Map;for(let p of n.edgeIds){let h=o.get(p);if(h)for(let f of h.semantics??[])if(f.family==="identity"){let b=s.get(h.fromNodeId)??[];b.push(h.toNodeId),s.set(h.fromNodeId,b)}else if(f.family==="control"&&!Bi(f.subtype)){let b=i.get(h.fromNodeId),v=i.get(h.toNodeId),S=typeof b?.attributes.ownerNodeId=="string"?b.attributes.ownerNodeId:h.fromNodeId;if(c(b)&&c(v)){let j=l.get(S)??new Map;j.set(f.subtype,(j.get(f.subtype)??0)+1),l.set(S,j);continue}let L=u.get(S)??new Map,B=L.get(h.fromNodeId)??{controllerLabel:b?.label??ae(h.fromNodeId),controllerLocation:b?.location?{file:b.location.file,line:b.location.line}:null,outcomes:new Map},H=B.outcomes.get(f.subtype)??new Set;H.add(v?.label??ae(h.toNodeId)),B.outcomes.set(f.subtype,H),L.set(h.fromNodeId,B),u.set(S,L)}else if(_b(f.family,f.subtype)){let b=Vb(h.fromNodeId,i),v=`${f.family}\0${f.subtype}\0${b.label}`,S=g.get(v)??{family:f.family,subtype:f.subtype,ownerLabel:b.label,ownerLocation:b.location,count:0,targetLabels:new Set,values:new Set};S.count+=1,S.targetLabels.add(ae(i.get(h.toNodeId)?.label??h.toNodeId));let L=f.attributes?.value;(typeof L=="string"||typeof L=="number"||typeof L=="boolean")&&S.values.add(String(L)),g.set(v,S)}else m.push({edge:h,semantic:f})}console.log(`
|
|
225
|
+
\u2550\u2550\u2550 CAUSAL CORRIDOR \u2550\u2550\u2550`),console.log(` [${n.status}] ${n.startNodeIds.length} anchor node(s) \u2192 ${n.outcomeNodeIds.length} mechanical outcome(s); ${n.coverage.protectedNodes} protected node(s), ${n.coverage.protectedEdges} protected edge(s).`),console.log(` Starts: ${r(n.startNodeIds)||"none proved"}`),console.log(` Outcomes: ${Gb(n.outcomeNodeIds,e)}`);for(let[p,h]of[...s].sort(([f],[b])=>f.localeCompare(b))){let f=new Map;for(let v of new Set(h)){let S=i.get(v)?.kind??"unknown";f.set(S,(f.get(S)??0)+1)}let b=[...f].sort(([v],[S])=>v.localeCompare(S)).map(([v,S])=>`${v}\xD7${S}`).join(", ");console.log(` [owns] ${r([p])} \u2192 ${new Set(h).size} local construct(s) [${b}]`)}for(let[p,h]of[...l].sort(([f],[b])=>f.localeCompare(b))){let f=[...h].sort(([b],[v])=>b.localeCompare(v)).map(([b,v])=>`${b}\xD7${v}`).join(", ");console.log(` [local-control] ${r([p])} \u2014 ${f}; exact decisions are represented below`)}for(let[p,h]of[...u].sort(([f],[b])=>f.localeCompare(b)))for(let f of[...h.values()].sort((b,v)=>(b.controllerLocation?.file??"").localeCompare(v.controllerLocation?.file??"")||(b.controllerLocation?.line??-1)-(v.controllerLocation?.line??-1)||b.controllerLabel.localeCompare(v.controllerLabel))){let b=[...f.outcomes].sort(([S],[L])=>S.localeCompare(L)).flatMap(([S,L])=>[...L].sort().map(B=>`${S} \u2192 ${B}`)).join("; "),v=f.controllerLocation?` @ ${f.controllerLocation.file}:${I(f.controllerLocation.line)}`:"";console.log(` [local-control] ${r([p])}: ${f.controllerLabel} \u2014 ${b}${v}`)}for(let p of[...g.values()].sort((h,f)=>h.ownerLabel.localeCompare(f.ownerLabel)||h.family.localeCompare(f.family)||h.subtype.localeCompare(f.subtype))){let h=p.family==="control"?`; targets=[${[...p.targetLabels].sort().join(", ")}]`:p.family==="data"&&p.subtype==="constant-to-parameter"?`; values=[${[...p.values].sort().join(", ")}]`:p.family==="data"?`; ${p.targetLabels.size} parameter target(s)`:"",f=p.ownerLocation?` @ ${p.ownerLocation.file}:${I(p.ownerLocation.line)}`:"";console.log(` [${p.family}:${p.subtype}; grouped] ${p.ownerLabel} \u2014 ${p.count} proved edge(s)${h}${f}`)}for(let{edge:p,semantic:h}of m){let f={...h.context??{},...h.attributes??{}},b=Object.entries(f).map(([S,L])=>`${S}=${String(L)}`).join(", "),v=p.evidence.find(S=>S.location)?.location;console.log(` [${h.family}:${h.subtype}] ${r([p.fromNodeId])} \u2192 ${r([p.toNodeId])}${b?`; ${b}`:""}${v?` @ ${v.file}:${I(v.line)}`:""}`)}console.log(` Frontier manifest: ${n.accountedFrontierIds.length} accounted; ${n.unresolvedFrontierIds.length} unsupported; ${n.unresolvedEdgeIds.length} candidate/unknown edge(s).`),g.size>0&&console.log(" Grouped edge identities remain in the structured corridor; inspect a named owner only when that flow is material."),n.status==="incomplete"&&console.log(` ${n.explanation}`)}function _b(e,t){return e==="control"&&Bi(t)||e==="data"&&["argument-to-parameter","constant-to-parameter"].includes(t)||e==="temporal"&&["await-completion-before","awaits-completion","lexical-successor"].includes(t)}function Vb(e,t){let n=t.get(e),i=typeof n?.attributes.ownerNodeId=="string"?n.attributes.ownerNodeId:null,o=i?t.get(i):null,r=typeof n?.attributes.ownerSymbol=="string"?n.attributes.ownerSymbol:null;return{label:ae(o?.label??r??n?.label??e),location:o?.location??n?.location??null}}function Bi(e){return["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e)}function Gb(e,t){if(e.length===0)return"none proved";let n=new Set(e),i=new Map(t.nodes.map(l=>[l.id,l])),o=new Set,r=new Set,s=0,a=0,c=new Set;for(let l of t.edges)if(n.has(l.toNodeId))for(let u of l.semantics??[])u.family==="state"?(o.add(ae(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):u.family==="control"&&Bi(u.subtype)?(r.add(ae(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):u.family==="control"&&u.subtype==="returns"?(s+=1,c.add(l.toNodeId)):u.family==="control"&&u.subtype==="throws"&&(a+=1,c.add(l.toNodeId));return[r.size>0?`navigation=[${[...r].sort().join(", ")}]`:"",o.size>0?`resources=[${[...o].sort().join(", ")}]`:"",s>0?`return\xD7${s}`:"",a>0?`throw\xD7${a}`:"",e.length>c.size?`other-causal-sink\xD7${e.length-c.size}`:""].filter(Boolean).join("; ")}function Y(e){return`'${e.replaceAll("'","'\\''")}'`}function Ub(e){let t=Qd(e.symbols,o=>o.file),n=Qd(e.literalHits,o=>o.file),i=new Map;for(let o of e.relations)for(let r of new Set([o.fromFile,o.toFile])){if(!e.files.some(a=>a.file===r))continue;let s=i.get(r)??[];s.push(o),i.set(r,s)}for(let o of e.files){let r=(t.get(o.file)??[]).sort(Xb),s=n.get(o.file)??[],a=i.get(o.file)??[],c=r.slice(0,4),l=[...new Set(a.map(g=>g.kind))].sort(),u=[...new Set(a.flatMap(g=>[g.fromRegionId,g.toRegionId].filter(p=>p!==e.id)))].sort(),m=c.length>0?c.map(g=>`${ae(g.shortName)}@${I(g.startLine)}`).join(", ")+(r.length>c.length?`; +${r.length-c.length}`:""):"none";console.log(` d${o.depth} ${zb(o.kind)} ${o.file} | sym${r.length} hit${s.length} rel${a.length}${l.length>0?`:${l.map(Jb).join("/")}`:""} x${u.length} | ${m}`);for(let g of s)console.log(` literal ${g.query}@${I(g.line)} ${g.sourceLine}`)}}function ae(e){return e.split(":").at(-1)||e}function Hb(e){let t=new Map;for(let n of e){let i=`${n.strength}\0${n.action}\0${n.reason}`,o=t.get(i)??{action:n.action,strength:n.strength,reason:n.reason,frontiers:[]};o.frontiers.push(n),t.set(i,o)}return[...t.values()].sort((n,i)=>i.frontiers.length-n.frontiers.length||n.action.localeCompare(i.action))}function Kb(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=120?t:`${t.slice(0,117)}...`}function Jd(e){return e.replace(/^region:(?:apps|packages)\//,"")}function zb(e){return{source:"S",test:"T",entry:"E",barrel:"B",worker:"W"}[e]??e}function Jb(e){return{call:"C","contract-symbol":"K",import:"I",reference:"R","runtime-boundary":"B"}[e]??e}function Qb(e){return e.startsWith("runtime-boundary:")?`B:${e.slice(17)}`:{"ast-callsite":"A","ast-member-import-candidate":"M","compiler-cross-workspace-symbol":"K","semantic-callee":"S","scip-chunk":"C","indexed-or-source-import":"I","indexed-or-source-reference":"R"}[e]??e}function Qd(e,t){let n=new Map;for(let i of e){let o=t(i),r=n.get(o)??[];r.push(i),n.set(o,r)}return n}function Xb(e,t){return Xd(e.origins)-Xd(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Xd(e){return e.includes("symbol-anchor")?0:e.includes("literal-owner")?1:e.some(t=>t.startsWith("boundary-import:"))?2:e.includes("reference-owner")?3:4}function Yd(e,t){let n=e.slice(0,t);return`${n.join(", ")}${e.length>n.length?`; ${e.length-n.length} more`:""}`}var tu=[{id:"hotspots",command:"hotspots",description:"Rank symbols by cross-file reference count; a reference metric, not runtime contention",agent:{...k("Which symbols have the most observed cross-file reference evidence?","ranked symbol identities with explicit evidence basis and counting units",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results",x,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),docs:R("Graph"),renderShape:"table",handler:Cb},{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:{...Ie("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",ce,gt(["symbol","construct"],["Entry-point detection reports evidenced external roots and candidates; it does not establish task relevance."])),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results for top mode",x,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Eb},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:k("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:C([d("-n, --limit <n>","Number of results for top mode",x,30),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Tb},{id:"coupling",command:"coupling [file1] [file2]",description:"Count shared-symbol coupling between two files, or rank file pairs by that metric",agent:k("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:C([d("-n, --limit <n>","Number of results for top mode",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Lb},{id:"cycles",command:"cycles",description:"Find every cyclic file-dependency component and show one deterministic witness for each",agent:k("Which file dependency cycles exist?","dependency-cycle file chains",[],"complete","repository"),options:C([d("-s, --scope <path>","Limit to files matching path"),d("--imports-only","Analyze only resolved file imports instead of all cross-file symbol references"),d("--max-depth <n>","Deprecated compatibility option; SCC detection no longer truncates by depth",x,10)]),renderShape:"custom",docs:R("Graph"),handler:Pb},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:k("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:C([d("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",claims:qe(["index-generation","live-workspace"],[Q("declared-policy","boundaries","repository-source"),Q("dependency-observations","edges","compiler-graph"),Q("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:R("Graph",["codebaseiq architecture --json"]),handler:Ab},{id:"bottlenecks",command:"bottlenecks",description:"Rank coordination hubs by incoming evidence files \xD7 outgoing cross-file callable targets",agent:{...k("Which callable symbols are high-connectivity coordination hubs?","ranked callable symbols with incoming evidence-file and outgoing callable-target counts",[],"bounded","repository"),resultUnits:{kind:"field",field:"rows"}},options:C([d("-n, --limit <n>","Number of results",x,20),d("-s, --scope <path>","Limit to files matching path"),d("--min-fan-in <n>","Minimum fan-in",x,2),d("--min-fan-out <n>","Minimum fan-out",x,2),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:R("Graph"),handler:kb},{id:"deep-chains",command:"deep-chains",hidden:!0,description:"Deprecated alias for dependency-depth",agent:k("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:C([d("-n, --limit <n>","Number of chains to show",x,10),d("-s, --scope <path>","Limit to files matching path"),d("--min-depth <n>","Minimum chain depth",x,3),d("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:jb},{id:"dependency-depth",command:"dependency-depth",description:"Find longest paths through the SCC-condensed file dependency graph",agent:k("Which file dependency paths have the greatest condensed depth?","ranked component paths with full cycle membership, edge basis, and condensed depth",[],"bounded","repository"),options:C([d("-n, --limit <n>","Number of paths to show",x,10),d("-s, --scope <path>","Limit to files matching path"),d("--min-depth <n>","Minimum condensed component depth",x,3),d("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),d("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Ib},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...Ie("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and indexed caller counts",["pattern"],"complete","repository",ce,gt(["symbol","construct"],["A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress.","Entry classification does not establish that the callable executes."],{ranking:"identity-only",manualInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",outputCost:"bounded",frontierClosure:["evidence","inspect","code"]})),contrasts:[{command:"entry-map",distinction:"entrypoints locates possible external roots; entry-map traverses static calls from one selected root."},{command:"search",distinction:"entrypoints classifies callable roots; search only locates exact text and ownership."}]},options:C([d("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Graph",["codebaseiq entrypoints","codebaseiq entrypoints work-session"]),handler:Nb},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...Ie("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,ce,It({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:C([d("--expand <region-id>","Expand one file region; repeat to expand several together",q,[])]),renderShape:"custom",docs:R("Graph",["codebaseiq entry-map start","codebaseiq entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:Db},{id:"system-map",command:"system-map",hidden:!0,description:"Deprecated compatibility view for collapsed regions and legacy route catalogues; use evidence",agent:Ie("Which components and proven compiler or runtime relationships connect these explicit literals or symbols?","all matched anchors, collapsed structural regions, compiler and exact runtime relationships, unresolved boundary frontiers, simultaneous drilldown summaries, and explicit coverage gaps",[],"bounded","repository",ce,It({rootKinds:["text","symbol","construct","runtime-key"],edgeFamilies:Ke,directions:["incoming","outgoing","both"],operations:["reachability","connecting"],compression:["topology"],nonClaims:["Legacy region and next-anchor ranking does not establish task relevance.","Structural region membership does not establish execution."],compatibility:"deprecated"})),options:C([d("--search <literal>","Add an exact indexed-source anchor; repeat to include several",q,[]),d("--symbol <symbol>","Add a symbol anchor; repeat to include several",q,[]),d("--focus-at <file:line>","Focus connected behavior at one exact source location inside a selected construct; repeat to include several",q,[]),d("--depth <n>","Traverse this many relationship levels",x,5),d("--relation <kind>","Traverse one relation family; repeat for call, contract-symbol, import, reference, or runtime-boundary",q,[]),d("--evidence-floor <floor>","Runtime evidence floor: exact or derived"),d("--topology-characters <n>","Soft character budget for the first human topology view; complete JSON facts remain available",x,12e3),d("--source-scope <scope>","Include one source scope; repeat for production, test, fixture, example, generated, script, or unknown",q,[]),d("--full-literal-traversal","Traverse every literal match after deliberately accepting broad-selector expansion"),d("--expand <region-id>","Expand one structural region; repeat to expand several together",q,[]),d("--frontier <frontier-id>","Expand one accounted topology frontier; repeat to expand several together",q,[]),d("--route <route-id>","Select one proved upstream route; repeat to materialize several routes together",q,[]),d("--gap-callee <name>","Resolve one callee already shown in connected behavior; repeat to batch a named gap",q,[]),d("--selection-term <term>","Deprecated no-op retained for command compatibility; query vocabulary no longer changes graph selection",q,[]),d("--gap-recovery-only","Render only the --gap-callee targets and one exact batched recovery command")]),evidence:"mixed",claims:qe(["index-generation","live-workspace"],[Q("matched-anchors","anchors","compiler-graph"),Q("typed-relations","regionRelations","repository-source"),Q("structural-grouping","regions","heuristic"),Q("coverage","coverage","repository-source")]),renderShape:"custom",docs:R("Compatibility"),handler:Ob},dt({id:"call-graph",command:"call-graph <symbol>",description:"Show static may-call edges with exact/candidate evidence and explicit blind spots",agent:k("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:[d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:R("Graph"),query:({db:e,args:t,budget:n})=>Tt(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}
|
|
226
|
+
`))},toJson:(e,{db:t,args:n})=>$e(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.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.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 Yb=te("complexity",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=Ts(e,o,{semantic:i.semantic});if(y(n,"json")){P("complexity",t,n,$e(e,o,r,"complexity"),{analysisBudget:i.analysisBudget});return}if(!r)return T.empty(ue(e,o,"Symbol not found."));de(e,o),console.log(`${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
|
|
227
|
+
`),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),Zb=X(({db:e,args:t,opts:n})=>{let i=zs(e,{samples:E(n,"samples",50),scope:$(n,"scope")});if(y(n,"json")){P("self-audit",t,n,i);return}if(!i.available)return T.empty("No semantic or source-backed oracle available to audit against.");let o=i.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${i.sampleSize} symbols; ${o} oracle answered ${Math.round(i.oracleCoverage*100)}%.
|
|
228
228
|
`),console.log(`Agreement with ${o} (file-level):`);for(let r of i.scores){let s=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${s} recall ${r.recall} (${r.comparedSymbols} compared, ${r.skippedOraclePartial} skipped: oracle-partial)`)}if(i.topDisagreements.length>0){console.log(`
|
|
229
|
-
Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),
|
|
229
|
+
Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),nu=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:k("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:C([d("--samples <n>","Number of symbols to sample",x,50),d("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:R("Health",["codebaseiq self-audit --samples 100"]),handler:Zb},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:k("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Health"),handler:Yb}];var ey=X(({db:e,args:t,opts:n})=>{let i=N(t,0),o=y(n,"full"),r=K(n,"maxDepth");if(o&&r!==void 0)throw new Error("--full cannot be combined with --max-depth. Use --full for complete traversal or --max-depth N for a bounded traversal.");let s=us(e,i,{maxDepth:o?Number.MAX_SAFE_INTEGER:r,scope:$(n,"scope")}),a=s.rows;if(y(n,"json")){P("affected",t,n,{...$e(e,i,a,"affected"),coverage:s.coverage});return}if(a.length===0){T.empty(ue(e,i,"No possible impacts found in the bounded reverse caller/reference closure.")),iu(s.coverage);return}de(e,i);let c=-1;for(let l of a)l.depth!==c&&(console.log(`
|
|
230
230
|
\u2500\u2500 Depth ${l.depth} \u2500\u2500`),c=l.depth),console.log(` ${l.file} ${l.shortName}`);console.log(`
|
|
231
|
-
${a.length} possible-impact symbol(s) across ${new Set(a.map(l=>l.file)).size} files; reachability does not prove breakage.`),
|
|
231
|
+
${a.length} possible-impact symbol(s) across ${new Set(a.map(l=>l.file)).size} files; reachability does not prove breakage.`),iu(s.coverage)});function iu(e){console.log(` coverage: ${e.status} (semantic evidence: ${e.semanticEvidence}) \u2014 ${e.reasons.join(" ")}`)}var ty=te("co-change",({db:e,args:t,opts:n,budget:i})=>{let o=t[0]===void 0?void 0:N(t,0),r=y(n,"full"),s=bs(e,o,{minTogether:E(n,"minTogether",4),limit:D(n,"limit",30),includeLinked:n.all===!0,scanLimit:i.scanLimit,historyMode:r?"full":"bounded"});if(y(n,"json")){P("co-change",t,n,s,{analysisBudget:i.analysisBudget});return}if(!s.available)return T.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return T.empty(o?`No co-change partners found for ${o} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);je("co-change candidates"),console.log(o?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
|
|
232
232
|
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
|
|
233
233
|
`),o&&s.findings.some(a=>a.structurallyLinked||a.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
|
|
234
|
-
`);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,u=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${u}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${
|
|
235
|
-
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function
|
|
234
|
+
`);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,u=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${u}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${ny(a.lastTogetherAt)}`),console.log(` subjects: ${iy(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
235
|
+
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function ny(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function iy(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(o=>`"${o}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var oy=te("change-surface",({db:e,args:t,opts:n,budget:i})=>{let o=ps(e,N(t,0),{semantic:i.semantic});if(y(n,"json")){P("change-surface",t,n,o,{analysisBudget:i.analysisBudget});return}if(!o)return T.empty("File not found in index.");console.log(`File: ${o.file}`),console.log(`External consumers: ${o.totalExternalConsumers}`),o.fileRisk&&o.fileRisk.reasons.length>0&&console.log(`File risk factors (${o.fileRisk.coverage} metadata): ${o.fileRisk.reasons.map(r=>`${r.kind}: ${r.detail}`).join("; ")}`),console.log(""),T.list(o.symbols,r=>{let s=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"",a=r.riskReasons??[],c=a.length===0?"":` [why: ${a.map(l=>`${l.kind}: ${l.detail}`).join("; ")}]`;return` ${fe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${s}${c}`})}),ry=te("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let o=fs(e,{base:$(n,"base"),minContainment:E(n,"minContainment",.7),maxHelpers:K(n,"maxHelpers"),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(y(n,"json")){P("incomplete-migration",t,n,o,{analysisBudget:i.analysisBudget}),(!o.available||o.findings.length>0)&&(process.exitCode=1);return}if(!o.available){console.error(`error: ${o.note??"Required Git history is unavailable."}`),process.exitCode=1;return}if(o.changedFiles.length===0)return T.empty(`No changes vs ${o.base}.`);console.log(`Incomplete migrations vs ${o.base}: ${o.changedFiles.length} changed file(s), ${o.helpersChecked} new helper(s) scored.`),o.note&&console.log(` note: ${o.note}`);for(let r of o.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(o.findings.length===0){console.log(`
|
|
236
236
|
No incomplete migrations detected.`);return}je("incomplete migration candidates");for(let r of o.findings){console.log(`
|
|
237
237
|
${r.helperShortName} (${r.helperFile})`),console.log(` helper shape: ${r.helperShape} (${r.specificHelperCalleeCount}/${r.helperCalleeCount} specific callees)`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let s of r.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
|
|
238
|
-
${o.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),
|
|
239
|
-
`)}var Gi=["definition","references","callers","callees","dependencies","consumers"],Hi=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function Ui(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Gi];let n=t.filter(i=>!Gi.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Gi.join(", ")}, or all.`);return[...new Set(t)]}function py(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Ke];let n=t.filter(i=>!Ke.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${Ke.join(", ")}, or all.`);return[...new Set(t)]}function my(e){if(e!==void 0){if(li.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${li.join(", ")}.`)}}function gy(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 hy(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function fy(e){if(e.length===0)return;let t={};for(let n of e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean)){let i=n.lastIndexOf("="),o=n.slice(0,i),r=n.slice(i+1);if(i<=0||!Hi.includes(o))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Hi.join(", ")}.`);if(Object.hasOwn(t,o))throw new Error(`Duplicate inspect evidence budget: ${o}.`);if(!/^\d+$/u.test(r))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);let s=Number(r);if(!Number.isSafeInteger(s))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);t[o]=s}return t}function by(e){let t=Wn(e),n=fu(e,t),i=e.matches.map(l=>{let u=l.ownerShort?` in ${l.ownerShort}`:"";return tt({relativePath:l.relativePath,startLine:l.startLine,source:l.source,sessionPolicy:"preview",focusLines:new Set([l.focusLine]),ownerSymbol:l.ownerShort??void 0,headerSuffix:u})}),o=Sy(t),r=n.mode==="complete"?$y(e,t):[],s=e.textCoverage,a=Ki(e),c=n.mode==="bounded"?vy(e):r.length>0?[` Recover every unmaterialized owning unit in ${r.length} bounded batch command(s):`,...r.map(l=>` ${l}`)," Or inspect any chosen locations together at behavior level: codebaseiq inspect --at 'path:line' --at 'path:line' --view behavior"]:[" Every matching source window was materialized; no drilldown remains."];return[{title:"REQUEST",rows:[` exact-text=${JSON.stringify(e.pattern)}; mode=${e.mode}`]},{title:`OBSERVED MATCH IDENTITIES (${t.length}/${e.matchingLines}, ${n.mode.toUpperCase()})`,rows:o},{title:`OBSERVED SOURCE (${e.matches.length}/${e.matchingLines} WINDOWS)`,rows:i},{title:"EVIDENCE CALIBRATION",rows:[` ${a?"Exact":"Observed"} cardinality comes from current project text scanned at query time.`," Compiler ownership is an aligned semantic overlay; unavailable or stale overlays do not change exact text identity."," Structural ordering and co-occurrence do not establish task relevance or a graph relationship."]},{title:"COVERAGE",rows:[` ${a?"Exact":"Observed"} cardinality: ${e.matchingLines} matching line(s) across ${e.matchingFiles??e.fileCoverage?.length??0} file(s).`,` Identity manifest: ${t.length}/${e.matchingLines} matching line(s); ${n.mode==="complete"?"complete":`${n.omitted} lower-ranked identities withheld before rendering`}.`,` Source materialization: ${e.matches.length}/${e.matchingLines} window(s); ${e.omittedMatches} exact match location(s) were not expanded into source.`,...s?[` Exact text: ${s.scannedTextFiles}/${s.candidateFiles} current project text file(s), ${s.scannedBytes.toLocaleString()} byte(s) scanned at query time.`,` Semantic ownership overlay: ${s.semanticFiles.aligned} aligned, ${s.semanticFiles.stale} stale, ${s.semanticFiles.unavailable} unavailable file(s).`,` Non-text/unreadable exclusions: ${s.skippedBinaryPaths.length} binary, ${s.skippedUnreadablePaths.length} unreadable, ${s.skippedOversizedPaths.length} oversized path(s); exact identities remain in textCoverage.`,...a?[]:[" Text coverage is incomplete: unreadable or oversized text may contain additional matches."]]:[]]},{title:"RECOVERY",rows:c}]}function yy(e){let t=e.groups.flatMap((n,i)=>{let o=n.kind==="shared-callee-owners"?"shared callee":n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?"basis root":"root",r=n.roots.slice(0,6),s=r.map(c=>{let l=c.matches.map(u=>`${u.term}[${u.sources.join("+")}]`).join(", ");return` ${o} ${c.label} \u2014 ${c.file}:${I(c.line)} \u2014 ${l}`}),a=n.relations.map(c=>` ${c.fromLabel} \u2192 ${c.toLabel} [${c.kind}; ${c.strength}; ${c.evidence}; depth ${c.depth}${c.runtimeBoundaryKey?`; ${c.runtimeBoundaryKey}`:""}]`);return[` [${i+1}] ${n.kind}; terms: ${n.matchedTerms.join(", ")||"(structural only)"}`,...n.kind==="shared-callee-owners"?[` map owners: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.omittedCandidateOwners.length>0?[` additional candidate owners: ${n.omittedCandidateOwners.map(c=>c.label).join(", ")}`,...n.ownerRecoveryCommands.map(c=>` additional owner map if those candidates can change the answer: ${c}`)]:[]]:n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?[` map anchors: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.kind==="parallel-paths"?[` shared path vocabulary: ${n.parallelSharedPathTerms?.join(", ")||"(none)"}`,` causal evidence on ${n.parallelConnectedSides??0}/2 independently named path(s); matched orchestration roots on ${n.parallelOrchestrationSides??0}/2; no cross-path edge is claimed.`]:[],...n.upstreamEntries.map(c=>` upstream entry: ${c.name} \u2014 ${c.file}:${I(c.line)}; if command preconditions can change the answer, include this location in the one batched gap inspect after the map.`)]:[],...s,...n.roots.length>r.length?[` ... ${n.roots.length-r.length} additional basis owner(s) retained in the result.`]:[],...a,...n.omittedRelations>0?[` ... ${n.omittedRelations} additional relationship(s) withheld from this compact view.`]:[],` next abstraction (run to completion before any inspect): ${n.systemMapCommand}`]});return[{title:"REQUIRED NEXT STEP",rows:[" Choose one evidence-grounded anchor set below and run its exact next-abstraction system-map command to transport completion."," inspect, code, and evidence are intentionally unavailable until that map completes."]},{title:"NORMALIZED REPOSITORY VOCABULARY",rows:[` matched: ${e.matchedTerms.join(", ")||"(none)"}`,` unmatched: ${e.unmatchedTerms.join(", ")||"(none)"}`]},{title:`EVIDENCE-GROUNDED ANCHOR SETS (${e.groups.length} SHOWN)`,rows:t},{title:"ANCHOR DISCOVERY COVERAGE",rows:[` Repository scan: ${e.scannedFiles} current text file(s), ${e.scannedBytes.toLocaleString()} byte(s).`,` Lexical owners: ${e.candidateRootCount}; structurally analyzed: ${e.analyzedRootCount}; lower-ranked owners not graph-expanded: ${e.omittedRootCount}.`,` Displayed anchor sets: ${e.groups.length}; withheld sets or unanalyzed roots: ${e.omittedGroupCount}.`," cross-boundary-flow joins otherwise separate call groups only when an indexed runtime producer\u2192consumer link and bounded downstream calls connect them; parallel-paths batches disconnected regions only when the query names distinct path vocabulary shared by those regions and does not claim a causal edge; connected-flow follows calls forward from matched owners; shared-callee-owners finds callable owners that converge on common callees without claiming those callees are effects."," Ranking uses repository vocabulary, compiler ownership, and bounded call connectivity; it does not establish task relevance."," Selection gate: reject a set whose roots and matched terms omit an object, branch, or stage named by a material claim. Connectivity cannot make a partial set eligible. Among sets that cover every named part, use the first ranked eligible set; use parallel-paths when no connected-flow covers them together."," Anchor roots are locator evidence, not behavior evidence. Select one set, run its next-abstraction command to transport completion, and only then decide whether source inspection is necessary. Never run a map and inspect concurrently.",...e.recoveryCommand?[` Expand the ranked manifest only if the shown sets cannot establish the requested flow: ${e.recoveryCommand}`]:[" Every candidate owner was structurally analyzed and every resulting anchor set was shown."]]}]}function Ki(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function fu(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 vy(e){let t=e.fileCoverage??[],n=new Map;for(let a of Ji(e)){let c=n.get(a.relativePath)??[];c.push(a),n.set(a.relativePath,c)}let i=t.reduce((a,c)=>{let l=c.relativePath.split("/").slice(0,-1);return Math.max(a,l.length)},1),o=a=>{let c=new Map;for(let l of t){let u=l.relativePath.split("/").slice(0,-1),m=u.length===0?"<root>":u.slice(0,a).join("/"),g=c.get(m)??[];g.push(l),c.set(m,g)}return[...c].sort(([l],[u])=>l.localeCompare(u)).flatMap(([l,u])=>{let m=[...u].sort((p,h)=>p.relativePath.localeCompare(h.relativePath)),g=m.reduce((p,h)=>p+h.matchingLines,0);if(m.length>12){let p=l==="<root>"?`codebaseiq search ${xe(e.pattern)}`:`codebaseiq search ${xe(e.pattern)} --scope ${xe(l)}`;return[` ${l}: ${g} matching line(s) across ${m.length} file(s); expand this structural region with ${p}`]}return[` ${l}: ${g} matching line(s) across ${m.length} file(s)`,...m.map(p=>{let h=[...n.get(p.relativePath)??[]].sort((S,L)=>S.focusLine-L.focusLine).filter((S,L,W)=>W.findIndex(H=>H.ownerSymbol===S.ownerSymbol&&H.ownerStartLine===S.ownerStartLine)===L),f=h.slice(0,2).map(S=>{let L=S.ownerShort??"<file scope>",W=I(S.ownerStartLine??S.focusLine);return`${L} @ ${W}`}),b=Math.max(0,h.length-f.length),v=f.length===0?"":`; exact starting construct(s): ${f.join("; ")}${b>0?`; +${b} more via codebaseiq outline ${xe(p.relativePath)}`:""}`;return` ${p.relativePath}: ${p.matchingLines} match(es)${v}`})]})},r=i,s=o(r);for(;r>1&&s.join(`
|
|
240
|
-
`).length>12e3;)r-=1,s=o(r);return[" Broad selector: identity enumeration stopped before output transport; there is no cursor to drain.",...s.length>0?[` Complete structural file manifest at directory depth ${r}; small regions expose exact starting constructs and large regions remain recoverable as one scope:`,...s]:[]," Choose explicit file/line roots from this manifest or narrow one structural region; the ordering does not infer task relevance."]}function
|
|
241
|
-
`))}function
|
|
242
|
-
`))}function
|
|
243
|
-
`)}),i=e.locations.map(g=>` ${g.matched?"matched":"missing"} ${g.target}`),o=t.map(
|
|
238
|
+
${o.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),ou=[{id:"affected",command:"affected <symbol>",description:"Conservative reverse caller/reference closure of symbols that may be impacted by a change",agent:k("Which downstream symbols are statically reachable as possible change impacts?","possible-impact symbol identities, files, and traversal depths; not predicted failures",["symbol"],"bounded"),options:C([d("--full","Traverse without the default depth and per-frontier caller caps"),d("--max-depth <n>","Maximum traversal depth (default: 5)",x),d("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Impact"),handler:ey},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: consumers, published API, operational roots, and explained change risk",agent:k("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Impact"),handler:oy},{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:k("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:C([d("--base <ref>","Git ref to diff against (default: HEAD)"),d("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Le,.7),d("--max-helpers <n>","Maximum new helpers to score (default: all)",x),d("-n, --limit <n>","Maximum findings to report",x,20),d("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:R("Impact",["codebaseiq incomplete-migration","codebaseiq incomplete-migration --base origin/main"]),handler:ry},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:k("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:C([d("--min-together <n>","Minimum commits where both files changed",x,4),d("-n, --limit <n>","Maximum pairs to report",x,30),d("--all","Include pairs that already have a dependency edge"),d("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},claims:qe(["index-generation","live-workspace"],[Q("historical-pairs","findings[]","change-history"),Q("structural-link-classification","findings[].structurallyLinked","compiler-graph")]),renderShape:"custom",docs:R("Impact",["codebaseiq co-change","codebaseiq co-change src/runtime/config.ts"]),handler:ty}];function sy(e){let t=y(e,"full"),n=D(e,"limit",12);return t?void 0:n}function ay(e){let t=$(e,"view")??"source";if(t!=="source"&&t!=="behavior")throw new Error(`Unknown inspect view: ${t}. Use source or behavior.`);return t}function cy(e){let t=[];for(let o of e.definitions){let r=o.signature?` \u2014 ${o.signature}`:"";o.source?t.push(tt({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"exact-unit",headerSuffix:r,ownerSymbol:o.signature??void 0})):t.push(` ${V(o.relativePath,o.startLine,o.endLine)}${r}`)}let n=[],i="";for(let o of e.referencedBy){o.relativePath!==i&&(i&&n.push(""),n.push(` ${o.relativePath}`),i=o.relativePath);let r=du(e.referenceEvidence,o.relativePath,o.line);n.push(` line ${I(o.line)} in ${o.enclosingShort} [${uu(r)}]`),o.source!==void 0&&o.source!==null&&o.sourceStartLine!==void 0&&o.sourceStartLine!==null&&n.push(tt({relativePath:o.relativePath,startLine:o.sourceStartLine,source:o.source,sessionPolicy:"preview",focusLines:new Set([o.line]),ownerSymbol:o.enclosingShort??void 0,indent:" ",sourceIndent:" "}))}return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n},{title:"CLAIM SUPPORT",rows:pu(e.claimSupport),skipIfEmpty:!0}]}function du(e,t,n){return e.find(i=>i.relativePath===t&&i.line===n)?.sourceKind}function uu(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 pu(e){return e?[ru("Reference-absence claims",e.referenceAbsence),ru("Callsite-argument claims",e.callsitePredicates)]:[]}function ru(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(`
|
|
239
|
+
`)}var Wi=["definition","references","callers","callees","dependencies","consumers"],Vi=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function _i(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Wi];let n=t.filter(i=>!Wi.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Wi.join(", ")}, or all.`);return[...new Set(t)]}function ly(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Ke];let n=t.filter(i=>!Ke.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${Ke.join(", ")}, or all.`);return[...new Set(t)]}function dy(e){if(e!==void 0){if(ai.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${ai.join(", ")}.`)}}function uy(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 py(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function my(e){if(e.length===0)return;let t={};for(let n of e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean)){let i=n.lastIndexOf("="),o=n.slice(0,i),r=n.slice(i+1);if(i<=0||!Vi.includes(o))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Vi.join(", ")}.`);if(Object.hasOwn(t,o))throw new Error(`Duplicate inspect evidence budget: ${o}.`);if(!/^\d+$/u.test(r))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);let s=Number(r);if(!Number.isSafeInteger(s))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);t[o]=s}return t}function gy(e){let t=Fn(e),n=mu(e,t),i=e.matches.map(l=>{let u=l.ownerShort?` in ${l.ownerShort}`:"";return tt({relativePath:l.relativePath,startLine:l.startLine,source:l.source,sessionPolicy:"preview",focusLines:new Set([l.focusLine]),ownerSymbol:l.ownerShort??void 0,headerSuffix:u})}),o=by(t),r=n.mode==="complete"?yy(e,t):[],s=e.textCoverage,a=Gi(e),c=n.mode==="bounded"?fy(e):r.length>0?[` Recover every unmaterialized owning unit in ${r.length} bounded batch command(s):`,...r.map(l=>` ${l}`)," Or inspect any chosen locations together at behavior level: codebaseiq inspect --at 'path:line' --at 'path:line' --view behavior"]:[" Every matching source window was materialized; no drilldown remains."];return[{title:"REQUEST",rows:[` exact-text=${JSON.stringify(e.pattern)}; mode=${e.mode}`]},{title:`OBSERVED MATCH IDENTITIES (${t.length}/${e.matchingLines}, ${n.mode.toUpperCase()})`,rows:o},{title:`OBSERVED SOURCE (${e.matches.length}/${e.matchingLines} WINDOWS)`,rows:i},{title:"EVIDENCE CALIBRATION",rows:[` ${a?"Exact":"Observed"} cardinality comes from current project text scanned at query time.`," Compiler ownership is an aligned semantic overlay; unavailable or stale overlays do not change exact text identity."," Structural ordering and co-occurrence do not establish task relevance or a graph relationship."]},{title:"COVERAGE",rows:[` ${a?"Exact":"Observed"} cardinality: ${e.matchingLines} matching line(s) across ${e.matchingFiles??e.fileCoverage?.length??0} file(s).`,` Identity manifest: ${t.length}/${e.matchingLines} matching line(s); ${n.mode==="complete"?"complete":`${n.omitted} lower-ranked identities withheld before rendering`}.`,` Source materialization: ${e.matches.length}/${e.matchingLines} window(s); ${e.omittedMatches} exact match location(s) were not expanded into source.`,...s?[` Exact text: ${s.scannedTextFiles}/${s.candidateFiles} current project text file(s), ${s.scannedBytes.toLocaleString()} byte(s) scanned at query time.`,` Semantic ownership overlay: ${s.semanticFiles.aligned} aligned, ${s.semanticFiles.stale} stale, ${s.semanticFiles.unavailable} unavailable file(s).`,` Non-text/unreadable exclusions: ${s.skippedBinaryPaths.length} binary, ${s.skippedUnreadablePaths.length} unreadable, ${s.skippedOversizedPaths.length} oversized path(s); exact identities remain in textCoverage.`,...a?[]:[" Text coverage is incomplete: unreadable or oversized text may contain additional matches."]]:[]]},{title:"RECOVERY",rows:c}]}function hy(e){let t=e.groups.flatMap((n,i)=>{let o=n.kind==="shared-callee-owners"?"shared callee":n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?"basis root":"root",r=n.roots.slice(0,6),s=r.map(c=>{let l=c.matches.map(u=>`${u.term}[${u.sources.join("+")}]`).join(", ");return` ${o} ${c.label} \u2014 ${c.file}:${I(c.line)} \u2014 ${l}`}),a=n.relations.map(c=>` ${c.fromLabel} \u2192 ${c.toLabel} [${c.kind}; ${c.strength}; ${c.evidence}; depth ${c.depth}${c.runtimeBoundaryKey?`; ${c.runtimeBoundaryKey}`:""}]`);return[` [${i+1}] ${n.kind}; terms: ${n.matchedTerms.join(", ")||"(structural only)"}`,...n.kind==="shared-callee-owners"?[` map owners: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.omittedCandidateOwners.length>0?[` additional candidate owners: ${n.omittedCandidateOwners.map(c=>c.label).join(", ")}`,...n.ownerRecoveryCommands.map(c=>` additional owner map if those candidates can change the answer: ${c}`)]:[]]:n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?[` map anchors: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.kind==="parallel-paths"?[` shared path vocabulary: ${n.parallelSharedPathTerms?.join(", ")||"(none)"}`,` causal evidence on ${n.parallelConnectedSides??0}/2 independently named path(s); matched orchestration roots on ${n.parallelOrchestrationSides??0}/2; no cross-path edge is claimed.`]:[],...n.upstreamEntries.map(c=>` upstream entry: ${c.name} \u2014 ${c.file}:${I(c.line)}; if command preconditions can change the answer, include this location in the one batched gap inspect after the map.`)]:[],...s,...n.roots.length>r.length?[` ... ${n.roots.length-r.length} additional basis owner(s) retained in the result.`]:[],...a,...n.omittedRelations>0?[` ... ${n.omittedRelations} additional relationship(s) withheld from this compact view.`]:[],` next abstraction (run to completion before any inspect): ${n.systemMapCommand}`]});return[{title:"REQUIRED NEXT STEP",rows:[" Choose one evidence-grounded anchor set below and run its exact next-abstraction system-map command to transport completion."," inspect, code, and evidence are intentionally unavailable until that map completes."]},{title:"NORMALIZED REPOSITORY VOCABULARY",rows:[` matched: ${e.matchedTerms.join(", ")||"(none)"}`,` unmatched: ${e.unmatchedTerms.join(", ")||"(none)"}`]},{title:`EVIDENCE-GROUNDED ANCHOR SETS (${e.groups.length} SHOWN)`,rows:t},{title:"ANCHOR DISCOVERY COVERAGE",rows:[` Repository scan: ${e.scannedFiles} current text file(s), ${e.scannedBytes.toLocaleString()} byte(s).`,` Lexical owners: ${e.candidateRootCount}; structurally analyzed: ${e.analyzedRootCount}; lower-ranked owners not graph-expanded: ${e.omittedRootCount}.`,` Displayed anchor sets: ${e.groups.length}; withheld sets or unanalyzed roots: ${e.omittedGroupCount}.`," cross-boundary-flow joins otherwise separate call groups only when an indexed runtime producer\u2192consumer link and bounded downstream calls connect them; parallel-paths batches disconnected regions only when the query names distinct path vocabulary shared by those regions and does not claim a causal edge; connected-flow follows calls forward from matched owners; shared-callee-owners finds callable owners that converge on common callees without claiming those callees are effects."," Ranking uses repository vocabulary, compiler ownership, and bounded call connectivity; it does not establish task relevance."," Selection gate: reject a set whose roots and matched terms omit an object, branch, or stage named by a material claim. Connectivity cannot make a partial set eligible. Among sets that cover every named part, use the first ranked eligible set; use parallel-paths when no connected-flow covers them together."," Anchor roots are locator evidence, not behavior evidence. Select one set, run its next-abstraction command to transport completion, and only then decide whether source inspection is necessary. Never run a map and inspect concurrently.",...e.recoveryCommand?[` Expand the ranked manifest only if the shown sets cannot establish the requested flow: ${e.recoveryCommand}`]:[" Every candidate owner was structurally analyzed and every resulting anchor set was shown."]]}]}function Gi(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function mu(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 fy(e){let t=e.fileCoverage??[],n=new Map;for(let a of Hi(e)){let c=n.get(a.relativePath)??[];c.push(a),n.set(a.relativePath,c)}let i=t.reduce((a,c)=>{let l=c.relativePath.split("/").slice(0,-1);return Math.max(a,l.length)},1),o=a=>{let c=new Map;for(let l of t){let u=l.relativePath.split("/").slice(0,-1),m=u.length===0?"<root>":u.slice(0,a).join("/"),g=c.get(m)??[];g.push(l),c.set(m,g)}return[...c].sort(([l],[u])=>l.localeCompare(u)).flatMap(([l,u])=>{let m=[...u].sort((p,h)=>p.relativePath.localeCompare(h.relativePath)),g=m.reduce((p,h)=>p+h.matchingLines,0);if(m.length>12){let p=l==="<root>"?`codebaseiq search ${xe(e.pattern)}`:`codebaseiq search ${xe(e.pattern)} --scope ${xe(l)}`;return[` ${l}: ${g} matching line(s) across ${m.length} file(s); expand this structural region with ${p}`]}return[` ${l}: ${g} matching line(s) across ${m.length} file(s)`,...m.map(p=>{let h=[...n.get(p.relativePath)??[]].sort((S,L)=>S.focusLine-L.focusLine).filter((S,L,B)=>B.findIndex(H=>H.ownerSymbol===S.ownerSymbol&&H.ownerStartLine===S.ownerStartLine)===L),f=h.slice(0,2).map(S=>{let L=S.ownerShort??"<file scope>",B=I(S.ownerStartLine??S.focusLine);return`${L} @ ${B}`}),b=Math.max(0,h.length-f.length),v=f.length===0?"":`; exact starting construct(s): ${f.join("; ")}${b>0?`; +${b} more via codebaseiq outline ${xe(p.relativePath)}`:""}`;return` ${p.relativePath}: ${p.matchingLines} match(es)${v}`})]})},r=i,s=o(r);for(;r>1&&s.join(`
|
|
240
|
+
`).length>12e3;)r-=1,s=o(r);return[" Broad selector: identity enumeration stopped before output transport; there is no cursor to drain.",...s.length>0?[` Complete structural file manifest at directory depth ${r}; small regions expose exact starting constructs and large regions remain recoverable as one scope:`,...s]:[]," Choose explicit file/line roots from this manifest or narrow one structural region; the ordering does not infer task relevance."]}function Hi(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 Fn(e){return e.identityManifest??Hi(e)}function by(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return[...t.entries()].flatMap(([n,i])=>{let o=new Map;for(let r of i){let s=r.ownerSymbol??"<file>",a=r.ownerStartLine===null||r.ownerEndLine===null?"":` ${I(r.ownerStartLine)}-${I(r.ownerEndLine)}`,c=o.get(s)??{label:r.ownerShort?`${r.ownerShort}${a}`:"<file scope>",lines:[]};c.lines.push(I(r.focusLine)),o.set(s,c)}return[` ${n} [${i[0].fileKind}; ${i.length} match(es)]`,...[...o.values()].flatMap(r=>gu(r.lines,24).map((s,a)=>` ${a===0?r.label:"\u21B3"} @ ${s.join(",")}`))]})}function yy(e,t){let n=new Set(e.matches.map(o=>su(o))),i=new Set;for(let o of t){if(n.has(su(o)))continue;let r=I(o.ownerStartLine??o.focusLine),s=I(o.ownerEndLine??o.focusLine);i.add(`${o.relativePath}:${r}-${s}`)}return gu([...i],24).map(o=>`codebaseiq code ${o.map(r=>xe(r)).join(" ")}`)}function su(e){return`${e.relativePath}\0${e.focusLine}`}function gu(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function xe(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function vy(e){let t=["codebaseiq inspect"];for(let i of A(e,"search"))t.push(`--search ${xe(i)}`);for(let i of A(e,"symbol"))t.push(`--symbol ${xe(i)}`);for(let i of A(e,"at"))t.push(`--at ${xe(i)}`);let n=$(e,"scope");return n&&t.push(`--scope ${xe(n)}`),t.push("--view behavior"),t.join(" ")}function Sy(e,t){if(!(e.view!=="source"||y(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: ${vy(t)}`,"Narrow to smaller exact selectors, or rerun with --allow-large-source only when the omitted syntax itself can change the decision."].join(`
|
|
241
|
+
`))}function $y(e,t){if(e.view!=="behavior"||y(t,"allowLargeBehavior"))return;let n=(e.omissionGroups??[]).filter(r=>r.sourceCharacters>2e4&&r.roles.some(s=>s==="location"||s==="definition"));if(n.length===0&&(e.returnedViewCharacters??0)<=2e4)return;let i=n.flatMap(r=>r.anchors).map(r=>`${r.relativePath}:${I(r.line)}`),o=i.length>0?i.join(", "):A(t,"at").join(", ");throw new Error(["INSPECT BEHAVIOR FOCUS REQUIRED",`The selector set resolves to behavioral constructs above the ${2e4}-character evidence ceiling${o?` (${o})`:""}.`,"No partial behavior was emitted, and this refusal does not establish an exploration obligation.","Use one or more interior file:line locations already visible in connected behavior, and batch only the named gaps. Do not use --full to turn a broad construct into a focus.","Use --allow-large-behavior only when every statement in the construct can change the decision."].join(`
|
|
242
|
+
`))}function wy(e){let t=e.units??[],n=e.searches.map(g=>{let p=[` ${g.pattern}: ${g.returnedMatches}/${g.matchingLines} matching line(s) materialized across ${g.returnedFiles??0}/${g.matchingFiles??0} file(s); ${g.selectedUnits??0}/${g.candidateUnits??0} deduplicated unit(s) selected`];return(g.omittedMatches>0||(g.omittedUnits??0)>0)&&(p.push(` Withheld: ${g.omittedMatches} matching line(s), ${g.omittedFiles??0} file(s) with no materialized match, and ${g.omittedUnits??0} materialized unit(s) outside the packet ceiling.`),(g.scopeHints?.length??0)>0&&(p.push(" Highest-coverage scopes available for focused expansion:"),p.push(...(g.scopeHints??[]).map(h=>` ${h.scope}: ${h.returnedMatches}/${h.matchingLines} matching line(s) materialized; ${h.exactFollowup}`)),(g.omittedScopeHints??0)>0&&p.push(` ... ${g.omittedScopeHints} additional matching scope(s).`)),g.exactFollowup&&p.push(` Expand this selector completely only if omitted matches can change the decision: ${g.exactFollowup}`)),p.join(`
|
|
243
|
+
`)}),i=e.locations.map(g=>` ${g.matched?"matched":"missing"} ${g.target}`),o=t.map(Ey),r=bu(e.bindingClosure),s=(e.omissionGroups??[]).map(Ty),a=xy(e),c=e.evidence.flatMap(g=>{let p=hu(g,"inspect");return p?[` ${p}`]:[]}),l=e.packetCoverage,u=l?[` ${l.mode==="complete"?"Complete":"Ranked bounded"} semantic packet: ${l.returnedUnits}/${l.candidateUnits} materialized unit(s), ${e.returnedLines??0} underlying source line(s), and ${e.returnedViewCharacters??e.returnedCharacters??0} displayed evidence character(s).`,` Selection ceiling: ${l.maxUnits} unit(s) or ${l.maxCharacters} displayed evidence character(s); syntax units are never clipped.`,` Exact symbol/location evidence: ${l.exactSelectorsComplete?"complete within materialized compiler evidence":"some lower-ranked units withheld"}.`,...l.channels?[` Evidence channels: ${ky(l.channels)}.`]:[],...l.omittedUnits>0?[` Withheld materialized units by role: ${Cy(l.omittedByRole)}.`]:[],...l.expansionCommand?[` Expand the complete selector set only if omitted evidence can change the decision: ${l.expansionCommand}`]:[]," Universal output transport may still page the rendered bytes; transport pages do not change this selection coverage."]:[` Complete semantic packet: ${t.length} deduplicated unit(s), ${e.returnedLines??0} source line(s), and ${e.returnedCharacters??0} source character(s).`],m=e.stoppingSummary?[` ${e.stoppingSummary.queryStatus??e.stoppingSummary.status}: ${e.stoppingSummary.guidance}`,...e.stoppingSummary.openEvidence>0?[` ${e.stoppingSummary.openEvidence} open evidence item(s); ${(e.omissionGroups??[]).length} recoverable omission group(s).`]:[]]:[];return[{title:"REQUEST",rows:[...n.map(g=>` search ${g.trimStart()}`),...i.map(g=>` location ${g.trimStart()}`),...c.map(g=>` symbol ${g.trimStart()}`)]},{title:"OBSERVED FACTS",rows:[...o,...r],skipIfEmpty:!0},{title:"EVIDENCE CALIBRATION",rows:[` view=${e.view}; exact source is current working-tree text; behavioral outlines label whether they are statement-complete, partial, or verbatim source units.`," Source co-location and references do not become executable reachability. Runtime facts retain their displayed strength and resolution."]},{title:"COVERAGE",rows:[...u,...m]},{title:"RECOVERY",rows:[...s,...a],skipIfEmpty:!0}]}function xy(e){let t=e.causalFrontier;if(!t||t.candidateAnchors===0)return[];let n=t.anchors.filter(r=>r.alternativeCount===1),i=[` ${n.length}/${t.candidateAnchors} bounded downstream target(s) are uniquely resolved and visible; these targets are outside the materialized constructs, not evidence already inspected.`];for(let r of n){let s=r.alternatives[0],a=r.callsite.signals.length>0?` [${r.callsite.signals.join(",")}]`:"";i.push(` ${r.direction??"downstream"} ${r.causalRole??"callee"} from ${r.fromLabel} at ${r.callsite.file}:${I(r.callsite.line)}${a}`,` ${s.label} \u2014 ${s.file}:${I(s.line)}`)}let o=Ry([...(e.omissionGroups??[]).flatMap(r=>r.anchors.map(s=>({file:s.relativePath,line:s.line}))),...n.map(r=>({file:r.alternatives[0].file,line:r.alternatives[0].line}))]).slice(0,24);return o.length>0&&i.push(` If any listed target or withheld requested construct remains material, run this one final recovery batch before answering: codebaseiq inspect ${o.map(r=>`--at ${xe(`${r.file}:${I(r.line)}`)}`).join(" ")} --view behavior`),t.omittedAnchors>0&&i.push(` ${t.omittedAnchors} additional downstream target(s) remain accounted in the frontier; use the printed remaining inspect commands only for a named unresolved fact.`),i}function Ry(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}`,n);return[...t.values()]}function Cy(e){return Object.entries(e).map(([t,n])=>`${t}=${n}`).join(", ")}function ky(e){return Vi.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 Ey(e){switch(e.kind){case"source":{let t=e.ownerShort?` in ${e.ownerShort}`:"";if(e.behavior){let o=e.behavior.coverage,s=[` representation: ${o.omittedStatements>0?"partial behavioral outline":o.copiedStatements===o.sourceStatements?"verbatim source unit (not compressed)":"statement-complete behavioral outline"}`,` ${e.behavior.constructKind}: ${e.behavior.signature}`,...e.behavior.lines.map(a=>` L${I(a.line)}${a.endLine>a.line?`-${I(a.endLine)}`:""} ${" ".repeat(a.depth)}${a.text}${a.copied?" [verbatim]":""}`),...e.behavior.testCases.length>0?[` related test cases: ${e.behavior.testCases.join("; ")}`]:[],...au(e.runtimeFacts??[]),` coverage: ${o.representedStatements}/${o.sourceStatements} source statement(s) represented; ${o.copiedStatements} verbatim; ${o.omittedStatements} omitted; ${e.behavior.outlineCharacters}/${e.behavior.rawCharacters} estimated characters`];return[` ${V(e.relativePath,e.startLine,e.endLine)}${t}`,` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`,Rt({kind:"unit",identity:`inspect-behavior:${e.relativePath}:${e.startLine}:${e.endLine}`,content:s.join(`
|
|
244
244
|
`),label:e.ownerShort??`${e.relativePath}:${I(e.startLine)}`,indent:" "})].join(`
|
|
245
|
-
`)}let n=tt({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=
|
|
245
|
+
`)}let n=tt({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=au(e.runtimeFacts??[]);return i.length>0?`${n}
|
|
246
246
|
${i.join(`
|
|
247
247
|
`)}`:n}case"path":return[` ${e.relationship}`,` ${e.roles.join(", ")} edge source was not located. Follow up exactly: ${e.exactFollowup}`].join(`
|
|
248
|
-
`);default:return
|
|
249
|
-
`)}function
|
|
248
|
+
`);default:return Ly(e)}}function au(e){return e.map(t=>{let n=t.keyParts.map(i=>`${i.name}=${i.value}`).join(", ")||"no resolved key";return` runtime L${I(t.line)} [${t.strength}] ${t.action} (${t.role}; ${t.resolution}) ${n}; proof=${t.derivation.rule}`})}function Ty(e){let t=e.anchors.slice(0,4).map(n=>{let i=n.ownerShort?` in ${n.ownerShort}`:"",o=n.behaviorSignals.length>0?` [${n.behaviorSignals.join(",")}]`:"";return` ${n.relativePath}:${I(n.line)}${i}${o}`});return e.anchors.length>t.length&&t.push(` ... ${e.anchors.length-t.length} additional anchor(s) represented by this group.`),[` ${e.id} ${e.scope} \u2014 ${e.candidateUnits} unit(s), ${e.sourceCharacters} source character(s)`,` channel: ${e.channel??"unclassified"}; roles: ${e.roles.join(", ")}; behavior: ${e.behaviorSignals.join(", ")||"not summarized"}`,...t,` Drill into this group together: ${e.drillCommand}`].join(`
|
|
249
|
+
`)}function Ly(e){throw new Error(`Unhandled source inspection unit: ${JSON.stringify(e)}`)}function hu(e,t="evidence"){if(e.kind==="missing")return`No definition matched '${e.query}'.`;if(e.kind!=="ambiguous")return;let n=e.candidates.map(r=>{let s=`'${r.symbol.replaceAll("'","'\\''")}'`;return t==="inspect"?` codebaseiq inspect --symbol ${s}`:` codebaseiq evidence ${s}`}).join(`
|
|
250
250
|
`),i=e.candidates.length,o=i<e.total?` Showing the highest-ranked ${i}; narrow by path or`:"";return`Target '${e.query}' is ambiguous across ${e.total} definitions.${o} run one listed exact command:
|
|
251
|
-
${n}`}function
|
|
251
|
+
${n}`}function Ui(e){if(e.kind!=="matched")return[];let t=e.definition?[tt({relativePath:e.definition.relativePath,startLine:e.definition.startLine,source:e.definition.source,sessionPolicy:"exact-unit",ownerSymbol:e.definition.shortName,headerSuffix:` ${e.definition.shortName}`}),...bu(e.definition.bindingClosure)]:[],n=e.referenceWindows.map(o=>{let r=o.references.map(s=>`${I(s.line)} in ${s.enclosingShort} [${uu(du(e.referenceEvidence,o.relativePath,s.line))}]`).join(", ");return tt({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"preview",focusLines:new Set(o.references.map(s=>s.line)),headerSuffix:` references: ${r}`})}),i=o=>o.map(r=>tt({relativePath:r.relativePath,startLine:r.startLine,source:r.source,sessionPolicy:"preview",ownerSymbol:r.shortName,headerSuffix:` ${r.shortName}${r.omittedLines>0?` (${r.omittedLines} line(s) omitted)`:""}`}));return[{title:"DEFINITION",rows:t,skipIfEmpty:!0},{title:"REFERENCE SITES",rows:n,skipIfEmpty:!0},{title:"CALLERS",rows:i(e.callers),skipIfEmpty:!0},{title:"CALLEES",rows:i(e.callees),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:e.dependencies.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CONSUMERS",rows:e.consumers.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CLAIM SUPPORT",rows:pu(e.claimSupport),skipIfEmpty:!0}]}function Py(e){if(e.kind!=="graph-packet")return Ui(e);let t=e.graph.selection??{direction:"both",subtypes:[],connecting:!1,inventoryOnly:!1,foldIds:[]},n=[` direction=${t.direction}; subtypes=${t.subtypes.length>0?t.subtypes.join(","):"all"}; operation=${t.connecting?"connecting":"reachability"}; materialization=${t.inventoryOnly?"inventory-only":t.foldIds.length>0?`folds(${t.foldIds.join(",")})`:"edges"}`,...e.graph.targets.map(m=>{let g=m.omittedCandidates>0?`; ${m.omittedCandidates} candidate(s) omitted`:"";return` selector [${m.status}] ${m.kind} ${m.query}${g}`})],i=Ke.flatMap(m=>{let g=e.graph.edges.filter(p=>p.family===m);return g.length===0?[]:[` ${m} (${g.length})`,...g.map(p=>` ${Ki(p)}`)]}),o=(e.graph.inventory??[]).map(m=>` inventory ${m.family}/${m.subtype}: incoming=${m.incoming}; outgoing=${m.outgoing}; both=${m.both}`);o.length>0&&o.unshift(" Inventory basis: incoming and outgoing are separately deduplicated reachable-edge sets around the selected roots; both is their deduplicated union, so it need not equal their sum.");let r=Ay(e.graph.folds??[]),s=jy(e.graph.edges),a=e.graph.coverage,c=[` ${a.status}: ${a.returnedEdges}/${a.eligibleEdges} materialized relationship(s); ${a.matchedEdges??a.eligibleEdges} matched the projection; depth <= ${a.maxDepth}; ${a.frontierGroups} accounted frontier group(s); ${a.unsupportedFrontiers} unsupported frontier(s).`,` ${a.explanation}`,...fu(a.blindSpots).map(m=>` Unsupported or unavailable: ${m}`)],l=e.source.flatMap(m=>m.kind!=="matched"?[{title:`SOURCE SELECTOR \u2014 ${m.query}`,rows:[` [${m.kind}]`]}]:Ui(m).map(g=>({...g,title:`${m.shortName} \u2014 ${g.title}`}))),u=[...r,...a.omittedEdges>0&&r.length===0?[` Expand the same selectors only if an omitted relationship is material: add --max-edges ${a.eligibleEdges}.`]:[],...e.sourceRecovery?[` Graph traversal stays graph-sized; ${e.sourceRecovery.selectors} requested source selector(s) were not embedded.`,` Read the named source gap separately: ${e.sourceRecovery.command}`]:[]];return[{title:"REQUEST",rows:n},{title:"OBSERVED FACTS",rows:[...o,...i],skipIfEmpty:!0},...l,{title:"EVIDENCE CALIBRATION",rows:s},{title:"COVERAGE",rows:c},{title:"RECOVERY",rows:u,skipIfEmpty:!0}]}function Ay(e){return e.length===0?[]:[" Rerun the same selectors and bounds with --fold <id>; each ID materializes exactly that folded edge set.",...[...e].sort((n,i)=>n.family.localeCompare(i.family)||(n.region??"").localeCompare(i.region??"")||n.id.localeCompare(i.id)).map(n=>{let i=n.subtypes??[n.subtype],o=i.length===1?i[0]:`${i.length} subtypes`;return` ${n.id} ${n.family}/${o} ${n.edgeCount} edge(s), ${n.nodeIds.length} node(s), ${n.mode} @ ${n.region??"unscoped"}`})]}function jy(e){let t=fu(e.map(o=>o.evidenceStrength)),n=t.length===0?[" No relationships were materialized, so no edge evidence strength is claimed."]:t.map(o=>` ${o}: ${Lt[o]}`),i=new Map;for(let o of e){let r=(o.evidenceConstituents??o.evidenceMethods.map(a=>({method:a,strength:o.evidenceStrength}))).map(a=>`${a.method}=${a.strength}`).join(", "),s=`${o.family}/${o.subtype}\0${o.providerId}\0${o.evidenceStrength}\0${r}`;i.set(s,` ${o.family}/${o.subtype} [${o.evidenceStrength}] provider=${o.providerId}; ceiling=${o.supportCeiling}; constituents=${r||"none reported"}; establishes=${o.establishes}; does-not-establish=${o.nonClaims.join(" ")||"no additional provider non-claim"}`)}return[...n,...i.values()]}function fu(e){return[...new Set(e)]}function Ki(e){let t=e.context?Object.entries(e.context).filter(([,o])=>o!==void 0).map(([o,r])=>`${o}=${cu(r)}`):[],n=e.attributes?Object.entries(e.attributes).map(([o,r])=>`${o}=${cu(r)}`):[],i=[...t,...n];return`[${e.evidenceStrength}] ${lu(e.from)} -> ${lu(e.to)} \u2014 ${e.subtype}${i.length>0?`; ${i.join(", ")}`:""}`}function cu(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}function lu(e){let t=e.location?` @ ${V(e.location.file,e.location.line,e.location.endLine??e.location.line)}`:"";return`${e.label}${t}`}function bu(e){if(!e)return[];let t=[];for(let n of e.inline)t.push(` inline ${n.name} @ ${V(n.relativePath,n.startLine,n.endLine)}`,` ${n.source??""}`);return t}var Iy=Se("imports",{query:({db:e,args:t,budget:n})=>Ir(e,N(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),Ny=te("dataflow",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=Ps(e,o,{semantic:i.semantic});if(y(n,"json")){P("dataflow",t,n,$e(e,o,r,"dataflow"),{analysisBudget:i.analysisBudget});return}if(!r)return T.empty(ue(e,o,"No dataflow found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
|
|
252
252
|
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${I(s.line)}`)}if(r.usageSites.length>0){console.log(`
|
|
253
253
|
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of r.usageSites)console.log(` ${s.file}:${I(s.line)} in ${s.enclosingShort}`)}if(r.producers.length>0){console.log(`
|
|
254
254
|
\u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of r.producers)console.log(` ${s.file} ${s.shortName}`)}if(r.consumers.length>0){console.log(`
|
|
255
|
-
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of r.consumers)console.log(` ${s.file} ${s.shortName}`)}}),
|
|
255
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of r.consumers)console.log(` ${s.file} ${s.shortName}`)}}),Dy=te("reference-neighborhood",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=Ls(e,o,{semantic:i.semantic});if(y(n,"json")){P("reference-neighborhood",t,n,$e(e,o,r,"reference-neighborhood"),{analysisBudget:i.analysisBudget});return}if(!r)return T.empty(ue(e,o,"No reference neighborhood found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
|
|
256
256
|
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINITION \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${I(s.line)}`)}if(r.referenceSites.length>0){console.log(`
|
|
257
257
|
\u2550\u2550\u2550 REFERENCES \u2550\u2550\u2550`);for(let s of r.referenceSites)console.log(` ${s.file}:${I(s.line)} in ${s.enclosingShort}`)}if(r.incomingCalls.length>0){console.log(`
|
|
258
258
|
\u2550\u2550\u2550 INCOMING CALLS \u2550\u2550\u2550`);for(let s of r.incomingCalls)console.log(` ${s.file} ${s.shortName}`)}if(r.outgoingCalls.length>0){console.log(`
|
|
259
|
-
\u2550\u2550\u2550 OUTGOING CALLS \u2550\u2550\u2550`);for(let s of r.outgoingCalls)console.log(` ${s.file} ${s.shortName}`)}}),
|
|
260
|
-
Coverage: ${o.coverage.status}; ${o.coverage.basis}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),
|
|
259
|
+
\u2550\u2550\u2550 OUTGOING CALLS \u2550\u2550\u2550`);for(let s of r.outgoingCalls)console.log(` ${s.file} ${s.shortName}`)}}),Oy=X(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Us(e,{symbols:[i]},{maxDepth:E(n,"depth",2),maxEdges:E(n,"maxEdges",48)});if(y(n,"json")){P("value-flow",t,n,o);return}de(e,i),o.edges.length===0?T.empty("No proved value transfers found. Missing output is not evidence that no value flow exists; inspect coverage."):T.list(o.edges,r=>` ${Ki(r)}`),console.log(`
|
|
260
|
+
Coverage: ${o.coverage.status}; ${o.coverage.basis}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),My=te("slice",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=y(n,"forward")?"forward":"backward",s=js(e,o,{direction:r,maxDepth:E(n,"depth",3),semantic:i.semantic});if(y(n,"json")){P("slice",t,n,$e(e,o,s,"slice"),{analysisBudget:i.analysisBudget});return}if(!s)return T.empty(ue(e,o,"No slice found."));if(de(e,o),console.log(`${s.direction} slice of ${s.shortName}
|
|
261
261
|
`),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}T.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
262
262
|
${a.relationship}`),console.log(`
|
|
263
|
-
${s.connectedSymbols.length} connected symbol(s).`)}),
|
|
263
|
+
${s.connectedSymbols.length} connected symbol(s).`)}),qy=te("reference-reachability",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=y(n,"forward")?"forward":"backward",s=As(e,o,{direction:r,maxDepth:E(n,"depth",3),semantic:i.semantic});if(y(n,"json")){P("reference-reachability",t,n,$e(e,o,s,"reference-reachability"),{analysisBudget:i.analysisBudget});return}if(!s)return T.empty(ue(e,o,"No reference reachability found."));de(e,o),console.log(`${s.direction} reference/call reachability from ${s.shortName}
|
|
264
264
|
`),T.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
265
265
|
${a.relationship}`),console.log(`
|
|
266
|
-
${s.connectedSymbols.length} connected symbol(s).`)}),
|
|
267
|
-
`),o.edges.length===0?T.empty("No proved dependence path found. Missing output is not evidence of absence; inspect coverage."):T.list(o.edges,r=>` depth ${r.traversalDepth} ${r.supporting?"[support] ":""}${
|
|
268
|
-
Coverage: ${o.coverage.status}; ${o.coverage.basis}; ${o.coverage.criterionKind}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),Vy=Y(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Tr(e,{className:i});if(y(n,"json")){P("methods",t,n,o,{coverage:Gy(o)}),o.kind!=="matched"&&(process.exitCode=1);return}if(o.kind==="matched"){T.list(o.methods,r=>` ${fe(r.startLine,r.endLine)} ${r.name}`);return}T.empty(Uy(o)),process.exitCode=1});function Gy(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 Uy(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}:${I(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 $u=[...Ia,Qe({id:"files",command:"files <pattern>",description:"Find current project files matching a path pattern",agent:k("Which current project files match this path pattern?","matching file paths",["pattern"],"complete"),docs:R("Navigation",["codebaseiq files auth"]),query:({db:e,args:t})=>Sr(e,N(t,0)),format:e=>e.relativePath}),dt({id:"inspect",command:"inspect",description:"Batch related searches, symbols, and source locations into one deduplicated source packet",options:[d("--search <text>","Find this literal text; repeat for related anchors",F,[]),d("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",F,[]),d("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",F,[]),d("-s, --scope <path>","Limit literal searches to indexed paths matching this text"),d("-C, --context <n>","Fallback lines around a match with no syntax unit",Te,6),d("-n, --limit <n>","Set matching lines materialized per search (default 12)",ne),d("--max-units <n>","Set the ranked packet unit ceiling (default 48)",ne),d("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",ne),d("--view <view>","Render exact source, or raw/normalized behavior chosen by token cost with complete statement accounting (source or behavior; default source)"),d("--allow-large-source",`Explicitly allow an exact-source packet above the ${2e4}-character safety ceiling`),d("--allow-large-behavior",`Explicitly allow a behavioral construct above the ${2e4}-character focus ceiling`),d("--unit-lines <n>","Deprecated compatibility option; inspect now returns complete syntax units",ne),d("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",ne),d("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",F,[]),d("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",F,[]),d("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...Ie("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",ce,pi(["behavior","construct","exact-source"],["A source packet does not choose which implementation details are relevant to the user task.","A reference mention does not establish executable reachability."],void 0,{manualInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit."})),contrasts:[{command:"code",distinction:"inspect batches bounded behavior or source gaps; code materializes complete exact source."},{command:"evidence",distinction:"inspect reads implementation units; evidence projects typed relationships without source."}]},docs:R("Navigation",["codebaseiq inspect --search sessionStreamEvents --search work_session_stream_events --search 'agent:work_session' --view behavior","codebaseiq inspect --symbol appendEvent --symbol publishEvent --include definition,references,callers,callees","codebaseiq inspect --at src/api.ts:42 --at src/web.tsx:90"]),query:({db:e,opts:t,budget:n})=>{ai(e.config.projectRoot,"inspect",t.session!==!1);let i=y(t,"full"),o=Er(e,{searches:A(t,"search"),symbols:A(t,"symbol"),locations:A(t,"at"),scope:$(t,"scope"),context:E(t,"context",6),searchLimit:ly(t),maxUnits:U(t,"maxUnits"),maxCharacters:U(t,"maxCharacters"),view:dy(t),full:i,unitLines:U(t,"unitLines"),totalLines:U(t,"totalLines"),evidence:{parts:Ui(A(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:fy(A(t,"evidenceBudget"))});return Ry(o,t),xy(o,t),o},coverage:(e,{budget:t})=>{let n=e.searches.reduce((o,r)=>o+r.omittedMatches,0),i=e.units?.length??e.slices.length;return t.analysisBudget||n>0||(e.omittedUnits??0)>0?{complete:!1,totalKnown:!1,returned:i}:{complete:!0,totalKnown:!0,returned:i,total:i,omitted:0}},agentResult:e=>({searches:e.searches,evidence:e.evidence.map(t=>({query:t.query,kind:t.kind})),locations:e.locations,returnedUnits:e.units?.length??e.slices.length,candidateUnits:e.candidateUnits??e.candidateSlices,omittedUnits:e.omittedUnits??e.omittedSlices,view:e.view,omissionGroups:e.omissionGroups,causalFrontier:e.causalFrontier,packetCoverage:e.packetCoverage,stoppingSummary:e.stoppingSummary}),sections:Cy}),Nn({id:"search",command:"search <exact-text>",description:"Count current project text matches and preview a bounded, recoverable identity and source manifest",options:[d("-s, --scope <path>","Limit the search to current project paths matching this text"),d("-C, --context <n>","Source lines before and after each representative match",Te,2),d("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",ne,6),d("--full","Materialize source for every match after deliberately narrowing broad selectors"),d("--regexp","Treat the search text as a bounded regular expression"),d("-i, --ignore-case","Ignore case")],agent:{...Ie("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,ce,gt(["text","symbol","construct","runtime-key"],["Structural source ranking orders exact matches but does not establish task relevance.","A literal co-occurrence does not establish a graph relationship."],{ranking:"identity-only",manualInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned."})),contrasts:[{command:"outline",distinction:"search locates exact text across files; outline enumerates compiler-owned constructs in one known file."}]},docs:R("Navigation",["codebaseiq search 'eventName'","codebaseiq search -- '--config'","codebaseiq search 'send.*event' --regexp --scope src"]),query:({db:e,args:t,opts:n})=>$r(e,N(t,0),{scope:$(n,"scope"),context:E(n,"context",2),limit:D(n,"limit",6),regexp:y(n,"regexp"),ignoreCase:y(n,"ignoreCase"),ranking:"structural"}),emptyMessage:e=>e.matchingLines===0?`${Ki(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=Ji(e).length;return Ki(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:Wn(e).length,totalMatches:e.matchingLines,omittedMatches:fu(e,Wn(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:Wn(e).map(t=>`${t.relativePath}:${I(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:by}),Nn({id:"anchors",command:"anchors <question>",hidden:!0,description:"Deprecated compatibility view for query-vocabulary candidate groups; use exact locators plus evidence",options:[d("-s, --scope <path>","Limit candidate ownership and text evidence to indexed paths matching this text"),d("-n, --limit <n>","Connected anchor sets to return; omitted candidates remain counted",ne,4),d("--full","Analyze every candidate anchor group with semantic enrichment")],agent:Ie("Which small graph-connected code regions contain repository vocabulary from this question?","ranked candidate owners, two-hop compiler call evidence, exact map commands, and an omission ledger",["pattern"],"bounded",void 0,ce,gt(["text","symbol","construct"],["Connected candidate groups are compatibility navigation hints, not inferred task relevance.","Candidate grouping does not establish implementation behavior."],{ranking:"identity-only",compatibility:"deprecated"})),docs:R("Compatibility"),query:({db:e,args:t,opts:n})=>{let i=wr(e,N(t,0),{scope:$(n,"scope"),limit:D(n,"limit",4),full:y(n,"full"),semantic:y(n,"full")});return ar(e.config.projectRoot,i.groups.map(o=>o.systemMapCommand),n.session!==!1),i},emptyMessage:e=>e.candidateRootCount===0?`No compiler-owned repository construct matched the normalized terms: ${e.normalizedTerms.join(", ")}.`:void 0,coverage:e=>e.omittedRootCount===0&&e.omittedGroupCount===0?{complete:!0,totalKnown:!0,returned:e.candidateRootCount,total:e.candidateRootCount,omitted:0}:{complete:!1,totalKnown:!0,returned:e.analyzedRootCount,total:e.candidateRootCount,omitted:e.omittedRootCount},agentResult:e=>({normalizedTerms:e.normalizedTerms,matchedTerms:e.matchedTerms,unmatchedTerms:e.unmatchedTerms,candidateRoots:e.candidateRootCount,analyzedRoots:e.analyzedRootCount,omittedRoots:e.omittedRootCount,omittedAnchorSets:e.omittedGroupCount,anchorSets:e.groups.map(t=>({roots:t.roots.map(n=>({symbol:n.symbol,file:n.file,line:I(n.line),matchedTerms:n.matchedTerms})),keyAnchors:t.keyAnchors.map(n=>({file:n.file,line:I(n.line)})),relations:t.relations,systemMapCommand:t.systemMapCommand})),recoveryCommand:e.recoveryCommand}),sections:yy}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:C(),agent:{...k("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:R("Navigation"),renderShape:"list",handler:Vy},dt({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[d("--full","Run unbounded semantic analysis on large indexes"),ui()],budget:"semantic",agent:{operation:ce,answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",semantic:lt("Resolve one symbol definition and its indexed reference sites.","Definition source and signatures plus referencing files and line numbers.",["Flat reference sites do not establish runtime calls, data flow, or task relevance."]),contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:R("Navigation",["codebaseiq trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Cr(e,N(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ue(t,N(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>de(t,N(n,0)),toJson:(e,{db:t,args:n})=>({...Nt(t,N(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:uy}),dt({id:"evidence",command:"evidence",description:"Traverse selected typed relationships around exact referents; recover source separately when needed",options:[d("--symbol <symbol>","Add an exact compiler symbol; repeat to batch",F,[]),d("--at <file:line>","Add the construct owning an exact source location; repeat to batch",F,[]),d("--search <literal>","Add an exact source or runtime literal; repeat to batch",F,[]),d("--view <view>","Select causal, structure, or complete graph evidence"),d("--edge <family>","Select execution, runtime, dataflow, state, temporal, contract, identity, ownership, dependencies, or all; repeat or comma-separate",F,[]),d("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),d("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",F,[]),d("--connecting","Return deterministic shortest paths connecting the resolved roots"),d("--inventory-only","Count relationships by family, subtype, and direction without rendering edges"),d("--fold <id>","Materialize an exact recoverable fold from the same projection; repeat to batch",F,[]),d("--depth <n>","Required maximum graph traversal depth",Te),d("--max-edges <n>","Required maximum typed relationships to render",ne),{...d("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",F,[]),hidden:!0},d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ce,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:It({rootKinds:["text","symbol","construct","runtime-key","state-resource"],edgeFamilies:Ke,directions:["incoming","outgoing","both"],operations:["adjacency","reachability","connecting","slice"],compression:["none","linear","scc","topology"],nonClaims:["The projection does not infer which relationships are relevant to the user task.","Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims."],manualInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage."}),contrasts:[{command:"refs",distinction:"refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships."},{command:"call-graph",distinction:"call-graph specializes in static calls; evidence can combine execution with other selected families."},{command:"value-flow",distinction:"value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families."},{command:"dependence-slice",distinction:"dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."}]},docs:R("Navigation",["codebaseiq evidence --symbol 'exact-symbol' --edge execution --edge dataflow --direction both --depth 2 --max-edges 32","codebaseiq evidence --symbol 'first' --symbol 'second' --edge runtime --direction both --depth 3 --max-edges 32 --connecting","codebaseiq 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=A(t,"symbol"),i=A(t,"at"),o=A(t,"search"),r=my($(t,"view")),s=py(A(t,"edge")),a=gy($(t,"direction")),c=hy(A(t,"subtype")),l=y(t,"connecting"),u=y(t,"inventoryOnly"),m=A(t,"fold"),g=U(t,"depth"),p=U(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(g===void 0)throw new Error("Graph evidence requires an explicit finite --depth <n>.");if(!u&&p===void 0)throw new Error("Materialized graph evidence requires an explicit finite --max-edges <n>.");let h=Ui(A(t,"include")),f=[...n,...i],b=h===void 0?null:{parts:h,selectors:f.length,command:["codebaseiq inspect",...n.map(v=>`--symbol ${xe(v)}`),...i.map(v=>`--at ${xe(v)}`),"--view source",`--include ${xe(h.join(","))}`].join(" ")};return{kind:"graph-packet",graph:Ar(e,{symbols:n,locations:i,searches:o},{view:r,families:s,direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:m,maxDepth:g,maxEdges:p??1}),source:[],sourceRecovery:b}},before:e=>{e.graph.targets.some(t=>t.status!=="matched")&&(process.exitCode=1)},coverage:e=>{let t=e.graph.edges.length,n=e.graph.targets.every(r=>r.status==="matched"),i=e.sourceRecovery!==null;return e.graph.coverage.status==="accounted"&&n&&!i?{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}:e.graph.coverage.status==="incomplete"||!n||i?{complete:!1,totalKnown:!1,returned:t}:{complete:!1,totalKnown:!0,returned:t,total:t+e.graph.coverage.omittedEdges,omitted:e.graph.coverage.omittedEdges}},agentResult:e=>({view:e.graph.view,families:e.graph.families,selection:e.graph.selection,targets:e.graph.targets,inventory:e.graph.inventory,relationshipCount:e.graph.edges.length,coverage:e.graph.coverage,sourceSelectors:e.source.length,sourceRecovery:e.sourceRecovery}),sections:Iy}),dt({id:"evidence-source",command:"evidence-source <symbol>",description:"Deprecated compatibility path for positional source evidence; use inspect or code",hidden:!0,options:[d("--include <part>","Source parts to include",F,[]),d("-C, --context <n>","Source lines before and after each reference",Te,2),d("--related-source-lines <n>","Maximum source lines for each caller or callee",ne,80),d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ce,answers:["Which legacy definition, reference, caller, callee, dependency, and consumer source surrounds this symbol?"],returns:["deprecated qualified source-evidence packet"],inputs:["symbol"],coverage:"bounded",semantic:pi(["construct","exact-source"],["This compatibility read does not establish graph reachability beyond its rendered evidence."],"deprecated")},docs:R("Compatibility"),query:({db:e,args:t,opts:n,budget:i})=>(ai(e.config.projectRoot,"evidence",n.session!==!1),kr(e,N(t,0),{parts:Ui(A(n,"include")),referenceContext:E(n,"context",2),relatedSourceLines:E(n,"relatedSourceLines",80),semantic:i.semantic})),emptyMessage:e=>yu(e),before:e=>{e.kind!=="matched"&&(process.exitCode=1)},coverage:(e,{budget:t})=>{if(e.kind!=="matched")return{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0};let n=(e.definition?1:0)+e.referenceWindows.reduce((i,o)=>i+o.references.length,0)+e.callers.length+e.callees.length+e.dependencies.length+e.consumers.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>e.kind==="matched"?{symbol:e.symbol,file:e.file,parts:e.parts,referenceSites:e.referenceWindows.reduce((t,n)=>t+n.references.length,0),sourceWindows:e.referenceWindows.length,callers:e.callers.length,callees:e.callees.length,dependencies:e.dependencies.length,consumers:e.consumers.length}:e,sections:zi}),Qe({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:k("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>xr(e,N(t,0)),format:e=>e.relativePath}),Qe({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:k("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Rr(e,N(t,0)),format:e=>e.relativePath}),Nn({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[ui()],agent:{operation:ce,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:lt("Summarize files, documented symbols, and one-hop file reference dependencies for a module selector.","Matched files, documented indexed symbols, dependencies, and reverse dependencies.",["A one-hop module summary does not establish runtime execution or complete transitive behavior."]),contrasts:[{command:"surface",distinction:"system lists documented indexed symbols; surface lists callable symbols that external consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:R("Navigation",["codebaseiq system queries"]),query:({db:e,args:t})=>jr(e,N(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=>` ${fe(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),Qe({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:k("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Ir(e,N(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:k("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Navigation"),handler:Oy},Qe({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:k("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Mr(e,N(t,0)),format:e=>` ${e.fromFile}`}),Qe({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:k("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Fr(e,N(t,0)),format:e=>` ${fe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>ue(e,N(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>$e(t,N(n,0),e,"members")}),Qe({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:k("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",w,100),d("--full","Run unbounded analysis on large indexes")],docs:R("Navigation"),query:({db:e,args:t,opts:n})=>Jr(e,N(t,0),{scope:$(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${V(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${N(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
269
|
-
${e.length} symbol(s)`)}),ed({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:k("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[d("-s, --scope <path>","Limit to files matching path")],docs:R("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Qr(e,{scope:$(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Qe({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:k("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Yr(e,N(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>ue(e,N(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>$e(t,N(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",hidden:!0,description:"Deprecated compatibility alias for a reference/call neighborhood; use value-flow",agent:k("What definitions, references, incoming calls, and outgoing calls surround this symbol?","legacy reference sites and call-neighborhood rows; no value-flow claim",["symbol"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:My},{id:"reference-neighborhood",command:"reference-neighborhood <symbol>",description:"Show definition/reference sites and incoming/outgoing static calls without value-flow claims",agent:k("What exact references and static calls surround this symbol?","definition sites, reference sites, incoming calls, and outgoing calls",["symbol"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:qy},{id:"value-flow",command:"value-flow <symbol>",description:"Show only proved argument/parameter and bounded static-value transfers around a symbol",agent:k("Which values are proved to flow into or through this symbol?","typed value-transfer edges with evidence strength and explicit unsupported relations",["symbol"],"bounded"),options:C([d("--depth <n>","Maximum graph depth",w,2),d("--max-edges <n>","Maximum typed value-transfer edges",w,48)]),renderShape:"custom",docs:R("Navigation"),handler:Fy},{id:"slice",command:"slice <symbol>",hidden:!0,description:"Deprecated compatibility alias for reference/call reachability; use dependence-slice",agent:k("Which calls or reference owners are reachable from this symbol under the legacy traversal?","legacy connected symbols; no program-dependence claim",["symbol"],"bounded"),options:C([d("--forward","Forward slice (what does this affect). Default is backward."),d("--depth <n>","Max transitive depth for backward slice",w,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:By},{id:"reference-reachability",command:"reference-reachability <symbol>",description:"Traverse legacy callee or reference-owner reachability without calling it a program slice",agent:k("Which call/reference nodes are reachable from this symbol?","connected symbols with relationship and traversal depth",["symbol"],"bounded"),options:C([d("--forward","Traverse reference owners. Default traverses callees."),d("--depth <n>","Maximum callee depth",w,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:Wy},{id:"dependence-slice",command:"dependence-slice <symbol-or-location>",description:"Directional slice over proved data/control dependencies with explicit supporting call edges",agent:k("What proved program dependencies can affect this criterion, or be affected by it?","directional dependence edges, supporting connectors, and coverage limits",[["symbol","path"]],"bounded"),options:C([d("--forward","Compute a forward slice. Default is backward."),d("--depth <n>","Maximum dependence traversal depth",w,3),d("--max-edges <n>","Maximum topology edges considered",w,200)]),renderShape:"custom",docs:R("Navigation"),handler:_y}];var Hy=te("context",({db:e,args:t,opts:n,budget:i})=>{let o=D(n,"limit",20),r=ge(e.config.projectRoot).gitContext?.headCommit,s=Os(e,N(t,0),{semantic:i.semantic,impactDepth:E(n,"impactDepth",3),sliceDepth:E(n,"sliceDepth",3),scope:$(n,"scope"),...r?{gitHead:r}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(y(n,"json")){P("context",t,n,{...Nt(e,N(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:wu(s),agentResult:xu(s)});return}return T.empty(ue(e,N(t,0)))}if(y(n,"json")){let c=s.primaryCallable?.symbol??N(t,0);P("context",t,n,s.matched.symbol?{...Nt(e,c),...s}:s,{analysisBudget:i.analysisBudget,coverage:wu(s),agentResult:xu(s)});return}s.matched.symbol&&de(e,s.primaryCallable?.symbol??N(t,0));let a=y(n,"detail")?zy(s,o):Ky(s,N(t,0),o,E(n,"impactDepth",3),E(n,"sliceDepth",3));T.sectionedReport(a)}),Ru=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:xa([d("--impact-depth <n>","Maximum affected traversal depth",w,3),d("--slice-depth <n>","Maximum backward slice depth",w,3),d("-s, --scope <path>","Limit downstream impact to files matching path"),d("-n, --limit <n>","Rows per section",w,20),d("--detail","Render every planning component instead of the compact decision packet"),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",claims:qe(["index-generation","live-workspace"],[X("compiler-graph","trace","compiler-graph"),X("semantic-flow","dataflow","semantic-analysis"),X("change-history","history","change-history"),X("planning-notes","warnings[]","heuristic")]),agent:{operation:ce,answers:["How is this target connected to the rest of the repository?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions","reuse candidates with evidence class and action tier","possible shared owners found from a bounded scan of affected consumers"],inputs:[["symbol","file","module"]],coverage:"bounded",semantic:lt("Assemble bounded compiler, semantic, history, and heuristic context around one explicit target.","A multi-section repository context report with each evidence family kept distinct.",["This composite report does not infer task relevance or prove that every returned candidate affects the requested change."]),contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; context includes flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:R("Exploration",["codebaseiq context parseSymbol"]),handler:Hy}];function Ky(e,t,n,i,o){return[{title:"TARGET",rows:ku(e)},{title:"CURRENT FLOW",rows:Jy(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:Qy(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Cu(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:Xy(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:Yy(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Eu(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:Zy(e,t,i,o)}]}function zy(e,t){return[{title:"TARGET",rows:ku(e)},{title:"DEFINITIONS",rows:Tu(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:nv(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Lu(e,t),skipIfEmpty:!0},{title:"DATAFLOW",rows:Pu(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Cu(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Eu(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:iv(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:ov(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:rv(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:sv(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:Au(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:ju(e),skipIfEmpty:!0}]}function Jy(e,t){return Pe(Re([...Tu(e,Math.min(t,12)),...Lu(e,t),...Pu(e,t)],t))}function Qy(e,t){let n=e.trace.referencedBy.map(o=>` direct ${o.relativePath}:${I(o.line)} ${o.enclosingShort}`),i=e.affected.map(o=>` depth ${o.depth} ${o.file} ${o.shortName}`);return Pe(Re(ev([...n,...i]),t))}function Xy(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),...ju(e)];return Pe(Re(n,t))}function Yy(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)??[],...bt(e).candidates.map(({candidate:i})=>i.fileB)];return Pe(Re([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function Zy(e,t,n,i){let o=bt(e).coverage,r=[` Direct compiler references observed: ${e.trace.referencedBy.length}.`,` Downstream and slice evidence is bounded at impact depth ${n} and slice depth ${i}.`,...e.affectedCoverage?[` Possible-impact coverage: ${e.affectedCoverage.status}; semantic evidence ${e.affectedCoverage.semanticEvidence}.`]:[],` Affected-consumer reuse scan: ${o.analyzedConsumers}/${o.totalConsumers} analyzed; ${o.omittedConsumers} omitted.`];return e.sourcePacket&&(r.push(` Source packet: ${e.sourcePacket.slices.length}/${e.sourcePacket.candidateSlices} slice(s); ${e.sourcePacket.omittedSlices} omitted; at most ${e.sourcePacket.maxSlices} slices, ${e.sourcePacket.maxLinesPerSlice} lines per slice, and ${e.sourcePacket.maxTotalLines} lines total.`),e.sourcePacket.targetLineLimit!==void 0&&e.sourcePacket.consumerContextLines!==void 0&&e.sourcePacket.reuseLineLimit!==void 0&&r.push(` Source roles: target up to ${e.sourcePacket.targetLineLimit} lines; consumer windows center on each use with ${e.sourcePacket.consumerContextLines} context lines; reuse candidates use up to ${e.sourcePacket.reuseLineLimit} lines.`)),e.warnings.length>0&&r.push(...e.warnings.map(s=>` Warning: ${s}`)),r.push(` Use codebaseiq refs ${t} --full only when a complete direct-consumer set can change the plan.`,` Use codebaseiq context ${t} --detail only when this packet leaves a named planning uncertainty.`),r}function ev(e){return[...new Set(e)]}function wu(e){return{complete:!1,totalKnown:!1,returned:tv(e)}}function tv(e){let t=bt(e);return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length+(e.reuseCandidates?.length??0)+t.coverage.analyzedConsumers+t.candidates.length+(e.sourcePacket?.slices.length??0)}function xu(e){let t=bt(e);return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,reuseCandidates:e.reuseCandidates?.length??0,affectedConsumersAnalyzed:t.coverage.analyzedConsumers,consumerReuseCandidates:t.candidates.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length,sourceSlices:e.sourcePacket?.slices.length??0},warnings:e.warnings,affectedCoverage:e.affectedCoverage,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 Cu(e,t){let n=(e.reuseCandidates??[]).flatMap(c=>[` target ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; ${c.evidenceClassReasons.join("; ")}`]),i=bt(e),o=i.candidates.flatMap(({candidate:c,consumers:l})=>[` consumer ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; observed from ${l.map(u=>u.shortName).join(", ")}; ${c.evidenceClassReasons.join("; ")}`]),r=i.coverage,s=r.totalConsumers>0?[` Affected-consumer scan: ${r.analyzedConsumers}/${r.totalConsumers} compiler-resolved consumer(s) analyzed; ${r.omittedConsumers} omitted; first ${r.perConsumerSearchLimit} similarity result(s) checked and up to ${r.perConsumerCandidateLimit} usable option(s) kept per consumer.`]:[],a=[...n,...s,...o];return Pe(Re(a,t))}function ku(e){let t=[`Target: ${e.target}`,`Matched: symbol=${Xi(e.matched.symbol)} file=${Xi(e.matched.file)} module=${Xi(e.matched.module)}`];return e.primaryCallable&&t.push(`Primary callable: ${e.primaryCallable.shortName} ${e.primaryCallable.file}`),t}function Eu(e){if(!e.sourcePacket||e.sourcePacket.slices.length===0)return[];let t=[];for(let n of e.sourcePacket.slices)t.push(` ${n.role.padEnd(15)} ${V(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
|
|
270
|
-
`).map((i,o)=>{let r=n.startLine+o;return` ${n.focusLines?.includes(r)?">":" "}${String(I(r)).padStart(4)} ${i}`})),n.omittedLines>0&&t.push(` ... ${n.omittedLines} more line(s) in this callable`);return e.sourcePacket.omittedSlices>0&&t.push(` ... ${e.sourcePacket.omittedSlices} more candidate slice(s)`),t}function
|
|
271
|
-
`).map((r,s)=>` ${String(I(i.startLine+s)).padStart(4)} ${r}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${fe(i.startLine,i.endLine)} ${i.shortName}`)),Re(n,t).rows}function nv(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${I(i.line)} in ${i.enclosingShort}`);return Pe(Re(n,t))}function Lu(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(o=>` caller ${o.file} ${o.shortName}`),i=e.callGraph.callees.map(o=>` callee ${o.file} ${o.shortName}`);return Pe(Re([...n,...i],t))}function Pu(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(r=>` producer ${r.file} ${r.shortName}`),i=e.dataflow.consumers.map(r=>` consumer ${r.file} ${r.shortName}`),o=e.dataflow.usageSites.map(r=>` usage ${r.file}:${I(r.line)} in ${r.enclosingShort}`);return Pe(Re([...n,...i,...o],t))}function iv(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 Pe(Re(n,t))}function ov(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${fe(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return Pe(Re(n,t))}function rv(e,t){let n=[],i=-1;for(let o of e.affected)o.depth!==i&&(n.push(` -- Depth ${o.depth} --`),i=o.depth),n.push(` ${o.file} ${o.shortName}`);return Pe(Re(n,t))}function sv(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),e.changeSurface.fileRisk&&e.changeSurface.fileRisk.reasons.length>0&&n.push(` File risk factors (${e.changeSurface.fileRisk.coverage} metadata): ${e.changeSurface.fileRisk.reasons.map(i=>`${i.kind}: ${i.detail}`).join("; ")}`),n.push(...e.changeSurface.symbols.map(i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"",r=i.riskReasons??[],s=r.length===0?"":` [why: ${r.map(a=>`${a.kind}: ${a.detail}`).join("; ")}]`;return` ${fe(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}${s}`}))),e.complexity&&(n.push(` Complexity: ${V(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount??"unavailable"}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut??"unavailable"}`)),Pe(Re(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 ju(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."),bt(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 bt(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function Re(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Pe(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Xi(e){return e?"yes":"no"}import{existsSync as Qt}from"fs";import{existsSync as Cv,mkdtempSync as kv,rmSync as Ev}from"fs";import{tmpdir as Tv}from"os";import{dirname as eo,join as Lv}from"path";import{performance as Bu}from"perf_hooks";import{spawnSync as Pv}from"child_process";import{createHash as Du,randomUUID as av}from"crypto";import{closeSync as _n,createReadStream as cv,existsSync as lv,fsyncSync as dv,mkdirSync as uv,openSync as Zi,renameSync as pv,unlinkSync as mv,writeSync as gv}from"fs";import{homedir as hv}from"os";import{dirname as Ou,join as Yi}from"path";var fv=3e5,bv=256*1024*1024;function Mu(e,t=process.env){let n=t.CODEBASEIQ_CACHE_DIR??(t.XDG_CACHE_HOME?Yi(t.XDG_CACHE_HOME,"codebaseiq"):Yi(hv(),".cache","codebaseiq"));return Yi(n,e)}var ee=class extends Error{constructor(n,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function qu(e){let{cachePath:t,url:n,expectedSha256:i}=e,o=e.timeoutMs??fv,r=e.maxBytes??bv,s=e.lockWaitMs??o;yv(o,r,s);let a=vv(n,o,e.signal);try{let c=await Iu(t,i,r,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};uv(Ou(t),{recursive:!0});let l=await Lo(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new ee("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let u=await Iu(t,i,r,a.controller.signal);return u?{status:"cached",path:t,sha256:u}:await Sv(e,a.controller,r)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?yt(a.controller.signal,n):c instanceof ee?c:new ee("stream",`failed to download ${n}: ${Fu(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function yv(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function vv(e,t,n){let i=new AbortController,o=()=>{i.abort(new ee("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",o,{once:!0}),n?.aborted&&o();let r=setTimeout(()=>{i.abort(new ee("timeout",`download of ${e} timed out after ${t}ms`))},t);return r.unref(),{controller:i,timeout:r,detachExternalAbort:()=>n?.removeEventListener("abort",o)}}async function Iu(e,t,n,i){if(!lv(e))return null;let o=Du("sha256"),r=0;try{for await(let a of cv(e,{signal:i})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(r+=c.length,r>n)return null;o.update(c)}}catch{if(i.aborted)throw yt(i,e);return null}let s=o.digest("hex");return s===t?s:null}async function Sv(e,t,n){let i=e.fetchImpl??fetch,o;try{o=await Nu(i(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?yt(t.signal,e.url):new ee("stream",`failed to download ${e.url}: ${Fu(l)}`,{cause:l})}if(!o.ok){let l=new ee("http",`failed to download ${e.url}: HTTP ${o.status}`);throw t.abort(l),l}let r=$v(o,n,e.url);if(!o.body)throw new ee("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${av()}`,a,c=!1;try{a=Zi(s,"wx",384),c=!0;let l=o.body.getReader(),u=Du("sha256"),m=0;for(;;){let{done:p,value:h}=await Nu(l.read(),t.signal);if(p)break;if(!(h instanceof Uint8Array))throw new ee("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(m+=h.byteLength,m>n||r!==void 0&&m>r){let b=new ee("length",`downloaded ${e.url} exceeded its ${r??n} byte limit`);throw t.abort(b),b}let f=Buffer.from(h.buffer,h.byteOffset,h.byteLength);u.update(f),wo(a,f,{writeFile:e.writeImpl??gv},"verified binary staging")}if(r!==void 0&&m!==r)throw new ee("length",`downloaded ${e.url} length mismatch: declared ${r} bytes, received ${m}`);let g=u.digest("hex");if(g!==e.expectedSha256)throw new ee("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${g}`);_n(a),a=void 0;try{wv(s,e.cachePath,e.renameImpl??pv,e.syncImpl??dv)}catch(p){throw new ee("install",`failed to install verified binary at ${e.cachePath}`,{cause:p})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:g}}catch(l){throw t.signal.aborted?yt(t.signal,e.url):l instanceof ee?l:new ee("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{_n(a)}catch{}if(c)try{mv(s)}catch{}}}function $v(e,t,n){let i=e.headers?.get("content-length");if(i==null)return;if(!/^\d+$/.test(i))throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);let o=Number(i);if(!Number.isSafeInteger(o)||o<0)throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);if(o>t)throw new ee("length",`downloaded ${n} declares ${o} bytes, above the ${t} byte limit`);return o}function wv(e,t,n,i){xv(e,i),Po(()=>n(e,t)),Rv(Ou(t),i)}function xv(e,t){let n=Zi(e,process.platform==="win32"?"r+":"r");try{t(n)}finally{_n(n)}}function Rv(e,t){let n;try{n=Zi(e,"r")}catch(i){if(ei(i,process.platform))return;throw i}try{t(n)}catch(i){if(!ei(i,process.platform))throw i}finally{_n(n)}}function Nu(e,t){return t.aborted?Promise.reject(yt(t,"operation")):new Promise((n,i)=>{let o=()=>{t.removeEventListener("abort",o),i(yt(t,"operation"))};t.addEventListener("abort",o,{once:!0}),e.then(r=>{t.removeEventListener("abort",o),n(r)},r=>{t.removeEventListener("abort",o),i(r)})})}function yt(e,t){return e.reason instanceof Error?e.reason:new ee("aborted",`verified binary operation for ${t} was aborted`)}function Fu(e){return e instanceof Error?e.message:String(e)}var Av=12e4,Vu="v1.8.0",jv=`https://github.com/tlaplus/tlaplus/releases/download/${Vu}/tla2tools.jar`,Iv="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Gn(e){let t=e.spawn??Pv,n=Nv(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let i=e.timeoutMs??Av,o=Bu.now(),r;try{r=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:i,killSignal:"SIGKILL",windowsHide:!0,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Ev(l,{recursive:!0,force:!0})}let s=Math.round(Bu.now()-o),a=r.error?.name==="ETIMEDOUT"||r.signal==="SIGTERM"&&s>=i,c=a?"timed-out":r.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:r.status,signal:r.signal,timedOut:a,diagnostics:Dv(c,r.stdout??"",r.stderr??""),stdout:r.stdout??"",stderr:r.stderr??""}}function Nv(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&He(Wu(e),t)){let r=Wu(e);return He(r,t)?{checker:"apalache",command:[r,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:eo(e.specPath)}:Vn("apalache",`Apalache binary is not available: ${r}`)}let i=to(e),o=He("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return Vn(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'codebaseiq tla fetch-tools' or set TLA_TOOLS_JAR");if(!o)return Vn(n==="sany"?"sany":"tlc","java is not available on PATH");let r=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(r==="sany")return{checker:r,command:["java","-cp",i,"tla2sany.SANY",e.specPath],cwd:eo(e.specPath)};let s=e.metaDir??kv(Lv(Tv(),"scip-tla-tlc-"));return{checker:r,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:eo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Vn("none",`unknown checker mode: ${n}`)}function Wu(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function to(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Gu(t)].filter(i=>typeof i=="string"&&i.length>0).find(i=>Cv(i))??null}function Gu(e=process.env){return Mu("tla2tools.jar",e)}async function Uu(e={}){let t=e.cachePath??Gu(e.env),n=e.expectedSha256??Iv,i=e.version??Vu,o=e.url??jv;return{...await qu({cachePath:t,url:o,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:i,url:o}}function Dv(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let i=[..._u(n),..._u(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(o=>({severity:"error",message:o}))}function _u(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Vn(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Ov}from"crypto";var Ku=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),zu=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Ju=new Set(["readFileSync","existsSync","statSync"]),Mv=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,qv=/^\s*SELECT\b/i;function Qu(e){return Mv.test(e)?"write":qv.test(e)?"read":null}var Fv=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Bv(e,t){let n=e.match(Fv);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${Ct(t)}\\b`).test(i)}function Xu(e,t,n,i=[],o=[]){let r=[],s=Vv(e,t,r),a=s.aliases,c=Gv(t),l=Uv(t),u=Hv(t),m=Jv(e,t,r),g=Xv(e,t,r);n&&Yv(t,n,o,r);let p=new Map((n?.actions??[]).map(S=>[S.name,S])),h=new Set(m.flatMap(S=>S.referents.map(L=>L.match?.symbol).filter(Boolean))),f=new Set((g?.referents??[]).map(S=>S.match?.symbol).filter(Boolean)),b=Zv(e,t,m,a,c,l,u,h,f,r,p),v=nS(e,m,a,c,l,u,r,p);return oS(e,m,r),rS(t,i,r),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:io(m.flatMap(S=>S.referents))+io(s.referents)+io(g?.referents??[]),staticWrites:b,staticReads:v,waivers:CS(t),checkedInvariants:[...o],traceStepsChecked:i.length,findings:r,findingGroups:Wv(r)}}function Wv(e){let t=new Map;for(let n of e){let i=`${n.category}:${n.modelElement??"-"}`,o=t.get(i);o||(o={groupKey:i,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(i,o)),o.count+=1,o.findingIds.push(n.id),o.severity=_v(o.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||Un(i.severity)-Un(n.severity)||n.groupKey.localeCompare(i.groupKey))}function _v(e,t){return Un(t)>Un(e)?t:e}function Un(e){return e==="error"?2:e==="warning"?1:0}function Vv(e,t,n){let i=[],o=[];for(let[r,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let u=zn(e,l,n,r);o.push(u);let m=u.match;if(!m){c||n.push(z("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:l,message:`TLA+ variable ${r} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${r}.code to a live symbol, or remove the variable from the model mapping.`}));continue}vS(e,r,l,m,n,c),s.aliases.length===0&&a.add(pr(m.symbol))}for(let l of a)i.push({variable:r,alias:l})}return{aliases:RS(i),referents:o}}function Gv(e){let t=[];for(let[n,i]of Object.entries(e.variables))i.resource&&t.push({variable:n,path:i.resource.path});return t}function Uv(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.statements??[])t.push({variable:n,pattern:o.pattern,regex:on(o.pattern,`variables.${n}.statements pattern`)});return t}function Hv(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.ormCalls??[]){let{write:r,read:s}=qi(o);t.push({variable:n,table:o.table,writeMethods:new Set(r),readMethods:new Set(s)})}return t}function Kv(e,t,n,i,o,r){return Yu(e,t,(s,a,c)=>ut(e,s,a,c,n,i,o,r))}function zv(e,t,n,i,o,r){return Yu(e,t,(s,a,c)=>Kn(e,s,a,c,n,i,o,r))}function Yu(e,t,n){let i=Tt(e,t,{semantic:!1});if(!i)return[];let o=[],r=new Set;for(let s of i.callees){if(r.has(s.symbol))continue;r.add(s.symbol);let a=dn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))o.push({...c,via:s.shortName})}return o}function Jv(e,t,n){return Object.entries(t.actions).map(([i,o])=>{let r=o.code.map(s=>{let a=Fi(s),c="error"in a?s:a.ref,u=zn(e,c,n,i).match;return u?(SS(e,i,s,u,n),"error"in a||!a.window?{ref:s,match:u}:Qv(a.window,u)?(n.push(z("invalid-line-window","error","compiler-symbol",{modelElement:i,codeRef:s,file:u.relativePath,startLine:u.startLine,endLine:u.endLine,message:`TLA+ action ${i} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${oe(u.symbol)}'s actual span L${u.startLine+1}-L${u.endLine+1} in ${u.relativePath}.`,why:[`${s} resolves to ${oe(u.symbol)} at ${u.relativePath}:${u.startLine+1}-${u.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${i}.code to fall within L${u.startLine+1}-L${u.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:u,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(z("missing-referent","error","compiler-symbol",{modelElement:i,codeRef:s,message:`TLA+ action ${i} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${i}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:i,mapping:o,referents:r}})}function Qv(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Xv(e,t,n){let i=t.init;if(!i)return;let o=!!i.waive,r=i.codeRefs.map(s=>{let a=zn(e,s,n,"Init"),c=a.match;return c?$S(e,s,c,n,o):o||n.push(z("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:i,referents:r}}function Yv(e,t,n,i){let o=new Set(t.variables),r=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))o.has(a)||i.push(z("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))r.has(a)||i.push(z("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(Hu({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:i,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),Hu({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:i,file:t.path}))}for(let a of e.invariants)s.has(a)||i.push(z("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function Hu(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),i=e.isWaived??(()=>!1);for(let o of t)n.has(o)||i(o)||e.findings.push(z(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${o} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${o} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let o of n)t.has(o)||i(o)||e.findings.push(z(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${o}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${o}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Zv(e,t,n,i,o,r,s,a,c,l,u){let m=[];for(let p of n){let h=[];for(let f of p.referents){if(!f.match)continue;let b=f.window??{startLine:f.match.startLine,endLine:f.match.endLine},v=ut(e,f.match.relativePath,b.startLine,b.endLine,i,o,r,s);h.push(...v),m.push(...v);let S=new Set(p.mapping.writes),L=Kv(e,f.match.symbol,i,o,r,s).filter(W=>S.has(W.variable));h.push(...L),m.push(...L)}tS(p,h,l,u.get(p.name))}let g=t.unmappedWriteScope==="actions"?[]:fS(e,t);for(let p of g)for(let h of ut(e,p,0,Number.POSITIVE_INFINITY,i,o,r,s))m.push(h),eS(h)&&(h.enclosingSymbol&&(a.has(h.enclosingSymbol)||c.has(h.enclosingSymbol))||l.push(z("unmapped-write","error","static-action",{modelElement:h.variable,codeRef:h.enclosingSymbol??`${h.file}:${h.line+1}`,file:h.file,startLine:h.line,endLine:h.line,message:`Modeled variable ${h.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${h.target} at ${h.file}:${h.line+1}.`,h.enclosingShort?`The write is inside ${h.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${h.variable} from the modeled slice if it is intentionally out of scope.`})));return so(m)}function eS(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function tS(e,t,n,i){let o=new Set(e.mapping.writes),r=new Set(t.map(a=>a.variable)),s=new Set(i?.writes??[]);for(let a of t)i&&!s.has(a.variable)&&!zt(e,"write",a.variable)&&n.push(z("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Hn(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${i.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!o.has(a.variable)&&!zt(e,"write",a.variable)&&n.push(z("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Hn(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of o)!r.has(a)&&!zt(e,"write",a)&&n.push(z("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function nS(e,t,n,i,o,r,s,a){let c=[];for(let l of t){let u=[];for(let m of l.referents){if(!m.match)continue;let g=m.window??{startLine:m.match.startLine,endLine:m.match.endLine},p=Kn(e,m.match.relativePath,g.startLine,g.endLine,n,i,o,r);u.push(...p),c.push(...p);let h=new Set(l.mapping.reads),f=zv(e,m.match.symbol,n,i,o,r).filter(b=>h.has(b.variable));u.push(...f),c.push(...f)}iS(l,u,s,a.get(l.name))}return ao(c)}function iS(e,t,n,i){let o=new Set(e.mapping.reads),r=new Set(t.map(a=>a.variable)),s=new Set(i?.reads??[]);for(let a of t)i&&!s.has(a.variable)&&n.push(z("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Hn(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${i.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!o.has(a.variable)&&!zt(e,"read",a.variable)&&n.push(z("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Hn(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of o)!r.has(a)&&!zt(e,"read",a)&&n.push(z("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function oS(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let o=i.mapping.calls.map(s=>zn(e,s,n,i.name));for(let s of o)s.match||n.push(z("missing-referent","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,message:`actions.${i.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${i.name}.calls to a live symbol or remove the stale call expectation.`}));let r=new Set(o.map(s=>s.match?.symbol).filter(Boolean));for(let s of i.referents){if(!s.match)continue;let a=Tt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of r)c.has(l)||n.push(z("missing-call","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${i.name} no longer calls ${oe(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${i.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function rS(e,t,n){for(let[i,o]of t.entries()){let r=e.actions[o.action];if(!r){n.push(z("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} uses action ${o.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${o.action} to the mapping, or fix the trace action name.`}));continue}let s=xS(o),a=new Set(r.writes);for(let c of s)a.has(c)||n.push(z("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} changed ${c}, but action ${o.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${o.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function ut(e,t,n,i,o,r=[],s=[],a=[]){let c=sS(e,t,n,i,o,r,s,a);return c||gS(e,t,n,i,o,r,s,a)}function Kn(e,t,n,i,o,r=[],s=[],a=[]){let c=aS(e,t,n,i,o,r,s,a);return c||hS(e,t,n,i,o,r,s,a)}function sS(e,t,n,i,o,r=[],s=[],a=[]){let c=ci(e,t);if(!c)return null;let l=[],u=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){cS(e,t,m,o,l),Zu(e,t,m,r,"write",l),ep(e,t,m,s,"write",l),tp(e,t,m,a,"write",l);for(let g of m.children)u(g)}};return u(c.rootNode),so(l)}function aS(e,t,n,i,o,r=[],s=[],a=[]){let c=ci(e,t);if(!c)return null;let l=[],u=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){uS(e,t,m,o,l),Zu(e,t,m,r,"read",l),ep(e,t,m,s,"read",l),tp(e,t,m,a,"read",l);for(let g of m.children)u(g)}};return u(c.rootNode),ao(l)}function cS(e,t,n,i,o){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let r=n.childForFieldName("left")??n.namedChild(0);r&&Kt(e,t,r,"assignment",i,o);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let r=n.childForFieldName("key")??n.namedChild(0);r&&Kt(e,t,r,"object-field",i,o);return}if(n.type==="update_expression"){let r=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);r&&Kt(e,t,r,"update",i,o);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let r=n.namedChild(0);r&&Kt(e,t,r,"delete",i,o);return}if(n.type==="call_expression"){let r=n.childForFieldName("function")??n.namedChild(0);if(!r||!ip(r))return;Kt(e,t,r,"mutation-call",i,o)}}}function Zu(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?oo(s):null;if(!a||!(o==="write"?zu:Ju).has(a))return;let u=n.childForFieldName("arguments")?.namedChild(0);if(!u)return;let m=u.text;for(let g of i){if(!m.includes(g.path))continue;let p=Ve(e,t,n.startPosition.row);r.push({variable:g.variable,alias:g.path,file:t,line:n.startPosition.row,target:`${a}(${m})`,kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?oe(p.symbol):void 0})}}function oo(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function ep(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=lS(a);if(c!==null&&Qu(c)===o)for(let l of i){if(!l.regex.test(c))continue;let u=Ve(e,t,n.startPosition.row),m=n.childForFieldName("function")??n.namedChild(0),g=(m&&oo(m))??"call";r.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${g}(${dS(c)})`,kind:"statement",enclosingSymbol:u?.symbol,enclosingShort:u?oe(u.symbol):void 0})}}}function lS(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function dS(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function tp(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?oo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let u=l.text.trim();for(let m of i){if(!np(m,a,u,o))continue;let g=Ve(e,t,n.startPosition.row);r.push({variable:m.variable,alias:m.table,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"orm-call",enclosingSymbol:g?.symbol,enclosingShort:g?oe(g.symbol):void 0})}}function np(e,t,n,i){return n!==e.table?!1:i==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function uS(e,t,n,i,o){if(!(!pS(n)||mS(n)))for(let r of i){if(n.text!==r.alias)continue;let s=Ve(e,t,n.startPosition.row);o.push({variable:r.variable,alias:r.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?oe(s.symbol):void 0})}}function pS(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function mS(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&no(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&no(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&ip(n)&&no(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function no(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function ip(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Ku.has(t.text))}function Kt(e,t,n,i,o,r){for(let s of o){if(!wS(s.alias,n.text))continue;let a=Ve(e,t,n.startPosition.row);r.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:i,enclosingSymbol:a?.symbol,enclosingShort:a?oe(a.symbol):void 0})}}function gS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),u=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let g=Math.max(0,n);g<=m;g+=1){let p=l[g]??"";for(let h of o){if(Bv(p,h.alias))continue;let f=Ct(h.alias);if(!new RegExp(`(?:\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${f}\\b\\s*\\.\\s*(?:${[...Ku].join("|")})\\s*\\(|\\b${f}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(p))continue;let v=Ve(e,t,g);u.push({variable:h.variable,alias:h.alias,file:t,line:g,target:p.trim(),kind:"source-scan",enclosingSymbol:v?.symbol,enclosingShort:v?oe(v.symbol):void 0})}op(e,t,g,p,r,zu,u),rp(e,t,g,p,s,"write",u),sp(e,t,g,p,a,"write",u)}return so(u)}function hS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),u=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let g=Math.max(0,n);g<=m;g+=1){let p=l[g]??"";for(let h of o){let f=Ct(h.alias);if(!new RegExp(`\\b${f}\\b`).test(p)||new RegExp(`\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(p))continue;let b=Ve(e,t,g);u.push({variable:h.variable,alias:h.alias,file:t,line:g,target:p.trim(),kind:"source-scan",enclosingSymbol:b?.symbol,enclosingShort:b?oe(b.symbol):void 0})}op(e,t,g,p,r,Ju,u),rp(e,t,g,p,s,"read",u),sp(e,t,g,p,a,"read",u)}return ao(u)}function op(e,t,n,i,o,r,s){if(o.length!==0)for(let a of r){let c=i.indexOf(`${a}(`);if(c===-1)continue;let l=i.slice(c+a.length);for(let u of o){if(!l.includes(u.path))continue;let m=Ve(e,t,n);s.push({variable:u.variable,alias:u.path,file:t,line:n,target:i.trim(),kind:"resource",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function rp(e,t,n,i,o,r,s){if(o.length!==0&&Qu(i)===r)for(let a of o){if(!a.regex.test(i))continue;let c=Ve(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:i.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?oe(c.symbol):void 0})}}function sp(e,t,n,i,o,r,s){if(o.length!==0)for(let a of i.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let u of o){if(!np(u,c,l,r))continue;let m=Ve(e,t,n);s.push({variable:u.variable,alias:u.table,file:t,line:n,target:i.trim(),kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function fS(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(o=>o.relative_path).filter(o=>n.some(r=>o.includes(r)))}function zn(e,t,n,i){let o=dn(e,t),r=o.match??(t.includes("#")?dn(e,t.replace("#","/")).match:null);return o.match&&o.total>1&&!bS(t)&&n.push(z("ambiguous-referent","warning","compiler-symbol",{modelElement:i,codeRef:t,file:o.match.relativePath,startLine:o.match.startLine,endLine:o.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${oe(o.match.symbol)}.`,why:[`${o.total} indexed definitions share this lookup shape.`,yS(o.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:r}}function bS(e){return/[/#:]/.test(e)}function yS(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function vS(e,t,n,i,o,r=!1){let s=ro(e,i);if(s===null||kS.has(s)||r)return;let a=co.has(s);o.push(z("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${kt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${kt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function SS(e,t,n,i,o){let r=ro(e,i);r===null||ap.has(r)||co.has(r)&&o.push(z("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${kt(r)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function $S(e,t,n,i,o){let r=ro(e,n);r===null||ap.has(r)||o||co.has(r)&&i.push(z("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${oe(n.symbol)} with SCIP kind ${kt(r)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function ro(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ve(e,t,n){return ln(e,t).filter(o=>o.startLine<=n&&o.endLine>=n).sort((o,r)=>o.endLine-o.startLine-(r.endLine-r.startLine))[0]??null}function wS(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Ct(e)}([^A-Za-z0-9_$]|$)`).test(t)}function xS(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function so(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function ao(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function RS(e){let t=new Set;return e.filter(n=>{let i=`${n.variable}:${n.alias}`;return t.has(i)?!1:(t.add(i),!0)})}function io(e){return e.filter(t=>t.match).length}function Hn(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function zt(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function CS(e){let t=Object.entries(e.actions).flatMap(([r,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:r,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:r,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([r,s])=>{let a=s.waive;return a?[{kind:"referent",variable:r,reason:a.reason,legacy:!1}]:[]}),i=e.init?.waive,o=i?[{kind:"referent",variable:"Init",reason:i.reason,legacy:!1}]:[];return[...t,...n,...o]}var co=new Set(hr()),ap=new Set(gr()),kS=new Set(fr());function z(e,t,n,i){let o=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${Ov("sha1").update(o).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{basename as ES,join as TS}from"path";var lo=/^[A-Za-z_][A-Za-z0-9_]*$/;function cp(e,t,n={}){let i=[],o=ln(e,t,{includeClassMemberFallbacks:!0});if(o.length===0)throw new Error(`no indexed definitions found for ${t}; run 'codebaseiq reindex' or check the path`);let s=at(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=x=>x.symbol.trimEnd().endsWith("()."),c=o.filter(x=>!a(x)&&!x.isTypeLike&&x.parentTypeName===null&&lo.test(x.leaf)),l=c.map(x=>({variable:x.leaf,alias:x.leaf})),u=l.length>0?ut(e,t,0,Number.POSITIVE_INFINITY,l):[],m=new Set(u.map(x=>x.variable)),g=c.filter(x=>m.has(x.leaf)?!0:AS(s,x)),p=null,h;if(g.length>0)h=o.filter(x=>a(x)&&x.parentTypeName===null);else{if(p=LS(e,t,o,a),!p){let x=o.some(M=>!a(M)&&!M.isTypeLike&&M.parentTypeName!==null&&lo.test(M.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(x?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}g=p.fields,h=p.methods,i.push(`state scoped to class ${p.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let f=g.map(x=>jS(x,s,t,i,p?.className)),b=f.map(x=>({variable:x.name,alias:x.leaf})),v=[],S=new Set;for(let x of h){let M=ut(e,t,x.startLine,x.endLine,b);if(M.length===0)continue;let J=Kn(e,t,x.startLine,x.endLine,b),O=OS(lp(x.leaf),S);v.push({name:O,leaf:x.leaf,codeRef:PS(t,x,p?.className),startLine:x.startLine,writes:[...new Set(M.map(Q=>Q.variable))].sort(),reads:[...new Set(J.map(Q=>Q.variable))].sort()})}v.length===0&&i.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let L=n.moduleName??MS(t),W=n.specDir??TS("specs",L),H=qS(L,f,v,t),j=FS(),_=BS(L,W,t,f,v);return{moduleName:L,file:t,variables:f,actions:v,warnings:i,spec:H,cfg:j,map:_}}function LS(e,t,n,i){let o=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!lo.test(s.leaf))continue;let a=o.get(s.parentTypeName);a?a.push(s):o.set(s.parentTypeName,[s])}let r=null;for(let[s,a]of o){let c=n.filter(g=>i(g)&&g.parentTypeName===s),l=a.map(g=>({variable:g.leaf,alias:g.leaf})),u=new Set;for(let g of c)for(let p of ut(e,t,g.startLine,g.endLine,l))u.add(p.variable);let m=a.filter(g=>u.has(g.leaf));m.length!==0&&(!r||m.length>r.fields.length)&&(r={className:s,fields:m,methods:c})}return r}function PS(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function AS(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function jS(e,t,n,i,o){let r=IS(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=NS(e.leaf,r);return a||i.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||i.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:o?`${n}/${o}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function IS(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function NS(e,t){let i=t.match(new RegExp(`\\b${WS(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,r=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=DS(i);l?(s=`{${l.map(u=>`"${u}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(i)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(i)||/^(Array|ReadonlyArray)</.test(i))&&(a="sequence",s=null)}let c=null;if(r){let l=r.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(r)?c=r.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(r)?c=r.match(/^-?\d+/)[0]:/^\[\s*\]/.test(r)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function DS(e){let t=e.split("|").map(i=>i.trim());if(t.length<2)return null;let n=[];for(let i of t){let o=i.match(/^['"]([^'"]*)['"]$/);if(!o)return null;n.push(o[1])}return n}function lp(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function OS(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function MS(e){let n=ES(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return lp(n||"Model")}function qS(e,t,n,i){let o=t.map(s=>s.name),r=[];r.push(`---- MODULE ${e} ----`),r.push(`\\* Scaffolded by 'codebaseiq tla scaffold ${i}'.`),r.push("\\* Draft evidence tier: state from the static write scan, domains from"),r.push("\\* declared types, actions from top-level callables that write state."),r.push("\\* Review every TODO before trusting a green model-check run."),r.push("EXTENDS Naturals, Sequences, TLC"),r.push(""),r.push(`VARIABLES ${o.join(", ")}`),r.push(""),r.push(`vars == <<${o.join(", ")}>>`),r.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';r.push(`${s.name}Domain == ${a}`)}r.push(""),r.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;r.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}r.push("");for(let s of n){let a=o.filter(c=>!s.writes.includes(c));r.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),r.push(`${s.name} ==`),r.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let u=t.find(m=>m.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;r.push(` /\\ ${c}' \\in ${u} \\* TODO: tighten to the concrete transition`)}a.length>0&&r.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),r.push("")}if(r.push("Next =="),n.length===0)r.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())r.push(` \\/ ${a.name}`);r.push(""),r.push("Spec == Init /\\ [][Next]_vars"),r.push(""),r.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?r.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):r.push(` /\\ ${s.name} \\in ${s.name}Domain`);return r.push("===="),r.push(""),r.join(`
|
|
272
|
-
`)}function
|
|
273
|
-
`)}function
|
|
274
|
-
`}function
|
|
266
|
+
${s.connectedSymbols.length} connected symbol(s).`)}),Fy=X(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Hs(e,i,{direction:y(n,"forward")?"forward":"backward",maxDepth:E(n,"depth",3),maxEdges:E(n,"maxEdges",200)});if(y(n,"json")){P("dependence-slice",t,n,o);return}console.log(`${o.direction} dependence slice of ${i}
|
|
267
|
+
`),o.edges.length===0?T.empty("No proved dependence path found. Missing output is not evidence of absence; inspect coverage."):T.list(o.edges,r=>` depth ${r.traversalDepth} ${r.supporting?"[support] ":""}${Ki(r)}`),console.log(`
|
|
268
|
+
Coverage: ${o.coverage.status}; ${o.coverage.basis}; ${o.coverage.criterionKind}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),By=X(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Cr(e,{className:i});if(y(n,"json")){P("methods",t,n,o,{coverage:Wy(o)}),o.kind!=="matched"&&(process.exitCode=1);return}if(o.kind==="matched"){T.list(o.methods,r=>` ${fe(r.startLine,r.endLine)} ${r.name}`);return}T.empty(_y(o)),process.exitCode=1});function Wy(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 _y(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}:${I(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 yu=[...Pa,Qe({id:"files",command:"files <pattern>",description:"Find current project files matching a path pattern",agent:k("Which current project files match this path pattern?","matching file paths",["pattern"],"complete"),docs:R("Navigation",["codebaseiq files auth"]),query:({db:e,args:t})=>br(e,N(t,0)),format:e=>e.relativePath}),dt({id:"inspect",command:"inspect",description:"Batch related searches, symbols, and source locations into one deduplicated source packet",options:[d("--search <text>","Find this literal text; repeat for related anchors",q,[]),d("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",q,[]),d("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",q,[]),d("-s, --scope <path>","Limit literal searches to indexed paths matching this text"),d("-C, --context <n>","Fallback lines around a match with no syntax unit",Te,6),d("-n, --limit <n>","Set matching lines materialized per search (default 12)",ne),d("--max-units <n>","Set the ranked packet unit ceiling (default 48)",ne),d("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",ne),d("--view <view>","Render exact source, or raw/normalized behavior chosen by token cost with complete statement accounting (source or behavior; default source)"),d("--allow-large-source",`Explicitly allow an exact-source packet above the ${2e4}-character safety ceiling`),d("--allow-large-behavior",`Explicitly allow a behavioral construct above the ${2e4}-character focus ceiling`),d("--unit-lines <n>","Deprecated compatibility option; inspect now returns complete syntax units",ne),d("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",ne),d("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",q,[]),d("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",q,[]),d("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...Ie("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",ce,di(["behavior","construct","exact-source"],["A source packet does not choose which implementation details are relevant to the user task.","A reference mention does not establish executable reachability."],void 0,{manualInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit."})),contrasts:[{command:"code",distinction:"inspect batches bounded behavior or source gaps; code materializes complete exact source."},{command:"evidence",distinction:"inspect reads implementation units; evidence projects typed relationships without source."}]},docs:R("Navigation",["codebaseiq inspect --search sessionStreamEvents --search work_session_stream_events --search 'agent:work_session' --view behavior","codebaseiq inspect --symbol appendEvent --symbol publishEvent --include definition,references,callers,callees","codebaseiq inspect --at src/api.ts:42 --at src/web.tsx:90"]),query:({db:e,opts:t,budget:n})=>{ri(e.config.projectRoot,"inspect",t.session!==!1);let i=y(t,"full"),o=Rr(e,{searches:A(t,"search"),symbols:A(t,"symbol"),locations:A(t,"at"),scope:$(t,"scope"),context:E(t,"context",6),searchLimit:sy(t),maxUnits:K(t,"maxUnits"),maxCharacters:K(t,"maxCharacters"),view:ay(t),full:i,unitLines:K(t,"unitLines"),totalLines:K(t,"totalLines"),evidence:{parts:_i(A(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:my(A(t,"evidenceBudget"))});return $y(o,t),Sy(o,t),o},coverage:(e,{budget:t})=>{let n=e.searches.reduce((o,r)=>o+r.omittedMatches,0),i=e.units?.length??e.slices.length;return t.analysisBudget||n>0||(e.omittedUnits??0)>0?{complete:!1,totalKnown:!1,returned:i}:{complete:!0,totalKnown:!0,returned:i,total:i,omitted:0}},agentResult:e=>({searches:e.searches,evidence:e.evidence.map(t=>({query:t.query,kind:t.kind})),locations:e.locations,returnedUnits:e.units?.length??e.slices.length,candidateUnits:e.candidateUnits??e.candidateSlices,omittedUnits:e.omittedUnits??e.omittedSlices,view:e.view,omissionGroups:e.omissionGroups,causalFrontier:e.causalFrontier,packetCoverage:e.packetCoverage,stoppingSummary:e.stoppingSummary}),sections:wy}),jn({id:"search",command:"search <exact-text>",description:"Count current project text matches and preview a bounded, recoverable identity and source manifest",options:[d("-s, --scope <path>","Limit the search to current project paths matching this text"),d("-C, --context <n>","Source lines before and after each representative match",Te,2),d("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",ne,6),d("--full","Materialize source for every match after deliberately narrowing broad selectors"),d("--regexp","Treat the search text as a bounded regular expression"),d("-i, --ignore-case","Ignore case")],agent:{...Ie("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,ce,gt(["text","symbol","construct","runtime-key"],["Structural source ranking orders exact matches but does not establish task relevance.","A literal co-occurrence does not establish a graph relationship."],{ranking:"identity-only",manualInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned."})),contrasts:[{command:"outline",distinction:"search locates exact text across files; outline enumerates compiler-owned constructs in one known file."}]},docs:R("Navigation",["codebaseiq search 'eventName'","codebaseiq search -- '--config'","codebaseiq search 'send.*event' --regexp --scope src"]),query:({db:e,args:t,opts:n})=>yr(e,N(t,0),{scope:$(n,"scope"),context:E(n,"context",2),limit:D(n,"limit",6),regexp:y(n,"regexp"),ignoreCase:y(n,"ignoreCase"),ranking:"structural"}),emptyMessage:e=>e.matchingLines===0?`${Gi(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=Hi(e).length;return Gi(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:Fn(e).length,totalMatches:e.matchingLines,omittedMatches:mu(e,Fn(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:Fn(e).map(t=>`${t.relativePath}:${I(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:gy}),jn({id:"anchors",command:"anchors <question>",hidden:!0,description:"Deprecated compatibility view for query-vocabulary candidate groups; use exact locators plus evidence",options:[d("-s, --scope <path>","Limit candidate ownership and text evidence to indexed paths matching this text"),d("-n, --limit <n>","Connected anchor sets to return; omitted candidates remain counted",ne,4),d("--full","Analyze every candidate anchor group with semantic enrichment")],agent:Ie("Which small graph-connected code regions contain repository vocabulary from this question?","ranked candidate owners, two-hop compiler call evidence, exact map commands, and an omission ledger",["pattern"],"bounded",void 0,ce,gt(["text","symbol","construct"],["Connected candidate groups are compatibility navigation hints, not inferred task relevance.","Candidate grouping does not establish implementation behavior."],{ranking:"identity-only",compatibility:"deprecated"})),docs:R("Compatibility"),query:({db:e,args:t,opts:n})=>{let i=vr(e,N(t,0),{scope:$(n,"scope"),limit:D(n,"limit",4),full:y(n,"full"),semantic:y(n,"full")});return or(e.config.projectRoot,i.groups.map(o=>o.systemMapCommand),n.session!==!1),i},emptyMessage:e=>e.candidateRootCount===0?`No compiler-owned repository construct matched the normalized terms: ${e.normalizedTerms.join(", ")}.`:void 0,coverage:e=>e.omittedRootCount===0&&e.omittedGroupCount===0?{complete:!0,totalKnown:!0,returned:e.candidateRootCount,total:e.candidateRootCount,omitted:0}:{complete:!1,totalKnown:!0,returned:e.analyzedRootCount,total:e.candidateRootCount,omitted:e.omittedRootCount},agentResult:e=>({normalizedTerms:e.normalizedTerms,matchedTerms:e.matchedTerms,unmatchedTerms:e.unmatchedTerms,candidateRoots:e.candidateRootCount,analyzedRoots:e.analyzedRootCount,omittedRoots:e.omittedRootCount,omittedAnchorSets:e.omittedGroupCount,anchorSets:e.groups.map(t=>({roots:t.roots.map(n=>({symbol:n.symbol,file:n.file,line:I(n.line),matchedTerms:n.matchedTerms})),keyAnchors:t.keyAnchors.map(n=>({file:n.file,line:I(n.line)})),relations:t.relations,systemMapCommand:t.systemMapCommand})),recoveryCommand:e.recoveryCommand}),sections:hy}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:C(),agent:{...k("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:R("Navigation"),renderShape:"list",handler:By},dt({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[d("--full","Run unbounded semantic analysis on large indexes"),li()],budget:"semantic",agent:{operation:ce,answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",semantic:lt("Resolve one symbol definition and its indexed reference sites.","Definition source and signatures plus referencing files and line numbers.",["Flat reference sites do not establish runtime calls, data flow, or task relevance."]),contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:R("Navigation",["codebaseiq trace parseSymbol"]),query:({db:e,args:t,budget:n})=>wr(e,N(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ue(t,N(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>de(t,N(n,0)),toJson:(e,{db:t,args:n})=>({...Nt(t,N(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:cy}),dt({id:"evidence",command:"evidence",description:"Traverse selected typed relationships around exact referents; recover source separately when needed",options:[d("--symbol <symbol>","Add an exact compiler symbol; repeat to batch",q,[]),d("--at <file:line>","Add the construct owning an exact source location; repeat to batch",q,[]),d("--search <literal>","Add an exact source or runtime literal; repeat to batch",q,[]),d("--view <view>","Select causal, structure, or complete graph evidence"),d("--edge <family>","Select execution, runtime, dataflow, state, temporal, contract, identity, ownership, dependencies, or all; repeat or comma-separate",q,[]),d("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),d("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",q,[]),d("--connecting","Return deterministic shortest paths connecting the resolved roots"),d("--inventory-only","Count relationships by family, subtype, and direction without rendering edges"),d("--fold <id>","Materialize an exact recoverable fold from the same projection; repeat to batch",q,[]),d("--depth <n>","Required maximum graph traversal depth",Te),d("--max-edges <n>","Required maximum typed relationships to render",ne),{...d("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",q,[]),hidden:!0},d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ce,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:It({rootKinds:["text","symbol","construct","runtime-key","state-resource"],edgeFamilies:Ke,directions:["incoming","outgoing","both"],operations:["adjacency","reachability","connecting","slice"],compression:["none","linear","scc","topology"],nonClaims:["The projection does not infer which relationships are relevant to the user task.","Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims."],manualInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage."}),contrasts:[{command:"refs",distinction:"refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships."},{command:"call-graph",distinction:"call-graph specializes in static calls; evidence can combine execution with other selected families."},{command:"value-flow",distinction:"value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families."},{command:"dependence-slice",distinction:"dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."}]},docs:R("Navigation",["codebaseiq evidence --symbol 'exact-symbol' --edge execution --edge dataflow --direction both --depth 2 --max-edges 32","codebaseiq evidence --symbol 'first' --symbol 'second' --edge runtime --direction both --depth 3 --max-edges 32 --connecting","codebaseiq 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=A(t,"symbol"),i=A(t,"at"),o=A(t,"search"),r=dy($(t,"view")),s=ly(A(t,"edge")),a=uy($(t,"direction")),c=py(A(t,"subtype")),l=y(t,"connecting"),u=y(t,"inventoryOnly"),m=A(t,"fold"),g=K(t,"depth"),p=K(t,"maxEdges");if(s===void 0)throw new Error("Graph evidence requires at least one explicit --edge <family>; repeat --edge to select several relationship families.");if(a===void 0)throw new Error("Graph evidence requires explicit --direction incoming, outgoing, or both.");if(g===void 0)throw new Error("Graph evidence requires an explicit finite --depth <n>.");if(!u&&p===void 0)throw new Error("Materialized graph evidence requires an explicit finite --max-edges <n>.");let h=_i(A(t,"include")),f=[...n,...i],b=h===void 0?null:{parts:h,selectors:f.length,command:["codebaseiq inspect",...n.map(v=>`--symbol ${xe(v)}`),...i.map(v=>`--at ${xe(v)}`),"--view source",`--include ${xe(h.join(","))}`].join(" ")};return{kind:"graph-packet",graph:Tr(e,{symbols:n,locations:i,searches:o},{view:r,families:s,direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:m,maxDepth:g,maxEdges:p??1}),source:[],sourceRecovery:b}},before:e=>{e.graph.targets.some(t=>t.status!=="matched")&&(process.exitCode=1)},coverage:e=>{let t=e.graph.edges.length,n=e.graph.targets.every(r=>r.status==="matched"),i=e.sourceRecovery!==null;return e.graph.coverage.status==="accounted"&&n&&!i?{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}:e.graph.coverage.status==="incomplete"||!n||i?{complete:!1,totalKnown:!1,returned:t}:{complete:!1,totalKnown:!0,returned:t,total:t+e.graph.coverage.omittedEdges,omitted:e.graph.coverage.omittedEdges}},agentResult:e=>({view:e.graph.view,families:e.graph.families,selection:e.graph.selection,targets:e.graph.targets,inventory:e.graph.inventory,relationshipCount:e.graph.edges.length,coverage:e.graph.coverage,sourceSelectors:e.source.length,sourceRecovery:e.sourceRecovery}),sections:Py}),dt({id:"evidence-source",command:"evidence-source <symbol>",description:"Deprecated compatibility path for positional source evidence; use inspect or code",hidden:!0,options:[d("--include <part>","Source parts to include",q,[]),d("-C, --context <n>","Source lines before and after each reference",Te,2),d("--related-source-lines <n>","Maximum source lines for each caller or callee",ne,80),d("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:ce,answers:["Which legacy definition, reference, caller, callee, dependency, and consumer source surrounds this symbol?"],returns:["deprecated qualified source-evidence packet"],inputs:["symbol"],coverage:"bounded",semantic:di(["construct","exact-source"],["This compatibility read does not establish graph reachability beyond its rendered evidence."],"deprecated")},docs:R("Compatibility"),query:({db:e,args:t,opts:n,budget:i})=>(ri(e.config.projectRoot,"evidence",n.session!==!1),xr(e,N(t,0),{parts:_i(A(n,"include")),referenceContext:E(n,"context",2),relatedSourceLines:E(n,"relatedSourceLines",80),semantic:i.semantic})),emptyMessage:e=>hu(e),before:e=>{e.kind!=="matched"&&(process.exitCode=1)},coverage:(e,{budget:t})=>{if(e.kind!=="matched")return{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0};let n=(e.definition?1:0)+e.referenceWindows.reduce((i,o)=>i+o.references.length,0)+e.callers.length+e.callees.length+e.dependencies.length+e.consumers.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>e.kind==="matched"?{symbol:e.symbol,file:e.file,parts:e.parts,referenceSites:e.referenceWindows.reduce((t,n)=>t+n.references.length,0),sourceWindows:e.referenceWindows.length,callers:e.callers.length,callees:e.callees.length,dependencies:e.dependencies.length,consumers:e.consumers.length}:e,sections:Ui}),Qe({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:k("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Sr(e,N(t,0)),format:e=>e.relativePath}),Qe({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:k("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>$r(e,N(t,0)),format:e=>e.relativePath}),jn({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[li()],agent:{operation:ce,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:lt("Summarize files, documented symbols, and one-hop file reference dependencies for a module selector.","Matched files, documented indexed symbols, dependencies, and reverse dependencies.",["A one-hop module summary does not establish runtime execution or complete transitive behavior."]),contrasts:[{command:"surface",distinction:"system lists documented indexed symbols; surface lists callable symbols that external consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:R("Navigation",["codebaseiq system queries"]),query:({db:e,args:t})=>Lr(e,N(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=>` ${fe(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),Qe({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:k("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Pr(e,N(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:k("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Navigation"),handler:Iy},Qe({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:k("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Nr(e,N(t,0)),format:e=>` ${e.fromFile}`}),Qe({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:k("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Or(e,N(t,0)),format:e=>` ${fe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>ue(e,N(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>$e(t,N(n,0),e,"members")}),Qe({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:k("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[d("-s, --scope <path>","Limit to files matching path"),d("-n, --limit <n>","Number of results",x,100),d("--full","Run unbounded analysis on large indexes")],docs:R("Navigation"),query:({db:e,args:t,opts:n})=>Hr(e,N(t,0),{scope:$(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${V(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${N(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
269
|
+
${e.length} symbol(s)`)}),Xl({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:k("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[d("-s, --scope <path>","Limit to files matching path")],docs:R("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Kr(e,{scope:$(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Qe({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:k("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Jr(e,N(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>ue(e,N(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>$e(t,N(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",hidden:!0,description:"Deprecated compatibility alias for a reference/call neighborhood; use value-flow",agent:k("What definitions, references, incoming calls, and outgoing calls surround this symbol?","legacy reference sites and call-neighborhood rows; no value-flow claim",["symbol"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:Ny},{id:"reference-neighborhood",command:"reference-neighborhood <symbol>",description:"Show definition/reference sites and incoming/outgoing static calls without value-flow claims",agent:k("What exact references and static calls surround this symbol?","definition sites, reference sites, incoming calls, and outgoing calls",["symbol"],"bounded"),options:C([d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:Dy},{id:"value-flow",command:"value-flow <symbol>",description:"Show only proved argument/parameter and bounded static-value transfers around a symbol",agent:k("Which values are proved to flow into or through this symbol?","typed value-transfer edges with evidence strength and explicit unsupported relations",["symbol"],"bounded"),options:C([d("--depth <n>","Maximum graph depth",x,2),d("--max-edges <n>","Maximum typed value-transfer edges",x,48)]),renderShape:"custom",docs:R("Navigation"),handler:Oy},{id:"slice",command:"slice <symbol>",hidden:!0,description:"Deprecated compatibility alias for reference/call reachability; use dependence-slice",agent:k("Which calls or reference owners are reachable from this symbol under the legacy traversal?","legacy connected symbols; no program-dependence claim",["symbol"],"bounded"),options:C([d("--forward","Forward slice (what does this affect). Default is backward."),d("--depth <n>","Max transitive depth for backward slice",x,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:My},{id:"reference-reachability",command:"reference-reachability <symbol>",description:"Traverse legacy callee or reference-owner reachability without calling it a program slice",agent:k("Which call/reference nodes are reachable from this symbol?","connected symbols with relationship and traversal depth",["symbol"],"bounded"),options:C([d("--forward","Traverse reference owners. Default traverses callees."),d("--depth <n>","Maximum callee depth",x,3),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:qy},{id:"dependence-slice",command:"dependence-slice <symbol-or-location>",description:"Directional slice over proved data/control dependencies with explicit supporting call edges",agent:k("What proved program dependencies can affect this criterion, or be affected by it?","directional dependence edges, supporting connectors, and coverage limits",[["symbol","path"]],"bounded"),options:C([d("--forward","Compute a forward slice. Default is backward."),d("--depth <n>","Maximum dependence traversal depth",x,3),d("--max-edges <n>","Maximum topology edges considered",x,200)]),renderShape:"custom",docs:R("Navigation"),handler:Fy}];var Vy=te("context",({db:e,args:t,opts:n,budget:i})=>{let o=D(n,"limit",20),r=ge(e.config.projectRoot).gitContext?.headCommit,s=Is(e,N(t,0),{semantic:i.semantic,impactDepth:E(n,"impactDepth",3),sliceDepth:E(n,"sliceDepth",3),scope:$(n,"scope"),...r?{gitHead:r}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(y(n,"json")){P("context",t,n,{...Nt(e,N(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:vu(s),agentResult:Su(s)});return}return T.empty(ue(e,N(t,0)))}if(y(n,"json")){let c=s.primaryCallable?.symbol??N(t,0);P("context",t,n,s.matched.symbol?{...Nt(e,c),...s}:s,{analysisBudget:i.analysisBudget,coverage:vu(s),agentResult:Su(s)});return}s.matched.symbol&&de(e,s.primaryCallable?.symbol??N(t,0));let a=y(n,"detail")?Uy(s,o):Gy(s,N(t,0),o,E(n,"impactDepth",3),E(n,"sliceDepth",3));T.sectionedReport(a)}),$u=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:Sa([d("--impact-depth <n>","Maximum affected traversal depth",x,3),d("--slice-depth <n>","Maximum backward slice depth",x,3),d("-s, --scope <path>","Limit downstream impact to files matching path"),d("-n, --limit <n>","Rows per section",x,20),d("--detail","Render every planning component instead of the compact decision packet"),d("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",claims:qe(["index-generation","live-workspace"],[Q("compiler-graph","trace","compiler-graph"),Q("semantic-flow","dataflow","semantic-analysis"),Q("change-history","history","change-history"),Q("planning-notes","warnings[]","heuristic")]),agent:{operation:ce,answers:["How is this target connected to the rest of the repository?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions","reuse candidates with evidence class and action tier","possible shared owners found from a bounded scan of affected consumers"],inputs:[["symbol","file","module"]],coverage:"bounded",semantic:lt("Assemble bounded compiler, semantic, history, and heuristic context around one explicit target.","A multi-section repository context report with each evidence family kept distinct.",["This composite report does not infer task relevance or prove that every returned candidate affects the requested change."]),contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; context includes flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:R("Exploration",["codebaseiq context parseSymbol"]),handler:Vy}];function Gy(e,t,n,i,o){return[{title:"TARGET",rows:xu(e)},{title:"CURRENT FLOW",rows:Hy(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:Ky(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:wu(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:zy(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:Jy(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Ru(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:Qy(e,t,i,o)}]}function Uy(e,t){return[{title:"TARGET",rows:xu(e)},{title:"DEFINITIONS",rows:Cu(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:Zy(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:ku(e,t),skipIfEmpty:!0},{title:"DATAFLOW",rows:Eu(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:wu(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:Ru(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:ev(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:tv(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:nv(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:iv(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:Tu(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Lu(e),skipIfEmpty:!0}]}function Hy(e,t){return Pe(Re([...Cu(e,Math.min(t,12)),...ku(e,t),...Eu(e,t)],t))}function Ky(e,t){let n=e.trace.referencedBy.map(o=>` direct ${o.relativePath}:${I(o.line)} ${o.enclosingShort}`),i=e.affected.map(o=>` depth ${o.depth} ${o.file} ${o.shortName}`);return Pe(Re(Xy([...n,...i]),t))}function zy(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}`,...Tu(e),...Lu(e)];return Pe(Re(n,t))}function Jy(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)??[],...bt(e).candidates.map(({candidate:i})=>i.fileB)];return Pe(Re([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function Qy(e,t,n,i){let o=bt(e).coverage,r=[` Direct compiler references observed: ${e.trace.referencedBy.length}.`,` Downstream and slice evidence is bounded at impact depth ${n} and slice depth ${i}.`,...e.affectedCoverage?[` Possible-impact coverage: ${e.affectedCoverage.status}; semantic evidence ${e.affectedCoverage.semanticEvidence}.`]:[],` Affected-consumer reuse scan: ${o.analyzedConsumers}/${o.totalConsumers} analyzed; ${o.omittedConsumers} omitted.`];return e.sourcePacket&&(r.push(` Source packet: ${e.sourcePacket.slices.length}/${e.sourcePacket.candidateSlices} slice(s); ${e.sourcePacket.omittedSlices} omitted; at most ${e.sourcePacket.maxSlices} slices, ${e.sourcePacket.maxLinesPerSlice} lines per slice, and ${e.sourcePacket.maxTotalLines} lines total.`),e.sourcePacket.targetLineLimit!==void 0&&e.sourcePacket.consumerContextLines!==void 0&&e.sourcePacket.reuseLineLimit!==void 0&&r.push(` Source roles: target up to ${e.sourcePacket.targetLineLimit} lines; consumer windows center on each use with ${e.sourcePacket.consumerContextLines} context lines; reuse candidates use up to ${e.sourcePacket.reuseLineLimit} lines.`)),e.warnings.length>0&&r.push(...e.warnings.map(s=>` Warning: ${s}`)),r.push(` Use codebaseiq refs ${t} --full only when a complete direct-consumer set can change the plan.`,` Use codebaseiq context ${t} --detail only when this packet leaves a named planning uncertainty.`),r}function Xy(e){return[...new Set(e)]}function vu(e){return{complete:!1,totalKnown:!1,returned:Yy(e)}}function Yy(e){let t=bt(e);return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length+(e.reuseCandidates?.length??0)+t.coverage.analyzedConsumers+t.candidates.length+(e.sourcePacket?.slices.length??0)}function Su(e){let t=bt(e);return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,reuseCandidates:e.reuseCandidates?.length??0,affectedConsumersAnalyzed:t.coverage.analyzedConsumers,consumerReuseCandidates:t.candidates.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length,sourceSlices:e.sourcePacket?.slices.length??0},warnings:e.warnings,affectedCoverage:e.affectedCoverage,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 wu(e,t){let n=(e.reuseCandidates??[]).flatMap(c=>[` target ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; ${c.evidenceClassReasons.join("; ")}`]),i=bt(e),o=i.candidates.flatMap(({candidate:c,consumers:l})=>[` consumer ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; observed from ${l.map(u=>u.shortName).join(", ")}; ${c.evidenceClassReasons.join("; ")}`]),r=i.coverage,s=r.totalConsumers>0?[` Affected-consumer scan: ${r.analyzedConsumers}/${r.totalConsumers} compiler-resolved consumer(s) analyzed; ${r.omittedConsumers} omitted; first ${r.perConsumerSearchLimit} similarity result(s) checked and up to ${r.perConsumerCandidateLimit} usable option(s) kept per consumer.`]:[],a=[...n,...s,...o];return Pe(Re(a,t))}function xu(e){let t=[`Target: ${e.target}`,`Matched: symbol=${zi(e.matched.symbol)} file=${zi(e.matched.file)} module=${zi(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)} ${V(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
|
|
270
|
+
`).map((i,o)=>{let r=n.startLine+o;return` ${n.focusLines?.includes(r)?">":" "}${String(I(r)).padStart(4)} ${i}`})),n.omittedLines>0&&t.push(` ... ${n.omittedLines} more line(s) in this callable`);return e.sourcePacket.omittedSlices>0&&t.push(` ... ${e.sourcePacket.omittedSlices} more candidate slice(s)`),t}function Cu(e,t){let n=[];for(let i of e.trace.definitions){let o=i.signature?` -- ${i.signature}`:"";n.push(` ${V(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&n.push(...i.source.split(`
|
|
271
|
+
`).map((r,s)=>` ${String(I(i.startLine+s)).padStart(4)} ${r}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${fe(i.startLine,i.endLine)} ${i.shortName}`)),Re(n,t).rows}function Zy(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${I(i.line)} in ${i.enclosingShort}`);return Pe(Re(n,t))}function ku(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(o=>` caller ${o.file} ${o.shortName}`),i=e.callGraph.callees.map(o=>` callee ${o.file} ${o.shortName}`);return Pe(Re([...n,...i],t))}function Eu(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(r=>` producer ${r.file} ${r.shortName}`),i=e.dataflow.consumers.map(r=>` consumer ${r.file} ${r.shortName}`),o=e.dataflow.usageSites.map(r=>` usage ${r.file}:${I(r.line)} in ${r.enclosingShort}`);return Pe(Re([...n,...i,...o],t))}function ev(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 Pe(Re(n,t))}function tv(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${fe(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return Pe(Re(n,t))}function nv(e,t){let n=[],i=-1;for(let o of e.affected)o.depth!==i&&(n.push(` -- Depth ${o.depth} --`),i=o.depth),n.push(` ${o.file} ${o.shortName}`);return Pe(Re(n,t))}function iv(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),e.changeSurface.fileRisk&&e.changeSurface.fileRisk.reasons.length>0&&n.push(` File risk factors (${e.changeSurface.fileRisk.coverage} metadata): ${e.changeSurface.fileRisk.reasons.map(i=>`${i.kind}: ${i.detail}`).join("; ")}`),n.push(...e.changeSurface.symbols.map(i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"",r=i.riskReasons??[],s=r.length===0?"":` [why: ${r.map(a=>`${a.kind}: ${a.detail}`).join("; ")}]`;return` ${fe(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}${s}`}))),e.complexity&&(n.push(` Complexity: ${V(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount??"unavailable"}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut??"unavailable"}`)),Pe(Re(n,t))}function Tu(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 Lu(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."),bt(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 bt(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function Re(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Pe(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function zi(e){return e?"yes":"no"}import{existsSync as Jt}from"fs";import{existsSync as wv,mkdtempSync as xv,rmSync as Rv}from"fs";import{tmpdir as Cv}from"os";import{dirname as Xi,join as kv}from"path";import{performance as Mu}from"perf_hooks";import{spawnSync as Ev}from"child_process";import{createHash as ju,randomUUID as ov}from"crypto";import{closeSync as Bn,createReadStream as rv,existsSync as sv,fsyncSync as av,mkdirSync as cv,openSync as Qi,renameSync as lv,unlinkSync as dv,writeSync as uv}from"fs";import{homedir as pv}from"os";import{dirname as Iu,join as Ji}from"path";var mv=3e5,gv=256*1024*1024;function Nu(e,t=process.env){let n=t.CODEBASEIQ_CACHE_DIR??(t.XDG_CACHE_HOME?Ji(t.XDG_CACHE_HOME,"codebaseiq"):Ji(pv(),".cache","codebaseiq"));return Ji(n,e)}var Z=class extends Error{constructor(n,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function Du(e){let{cachePath:t,url:n,expectedSha256:i}=e,o=e.timeoutMs??mv,r=e.maxBytes??gv,s=e.lockWaitMs??o;hv(o,r,s);let a=fv(n,o,e.signal);try{let c=await Pu(t,i,r,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};cv(Iu(t),{recursive:!0});let l=await ko(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new Z("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let u=await Pu(t,i,r,a.controller.signal);return u?{status:"cached",path:t,sha256:u}:await bv(e,a.controller,r)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?yt(a.controller.signal,n):c instanceof Z?c:new Z("stream",`failed to download ${n}: ${Ou(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function hv(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function fv(e,t,n){let i=new AbortController,o=()=>{i.abort(new Z("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",o,{once:!0}),n?.aborted&&o();let r=setTimeout(()=>{i.abort(new Z("timeout",`download of ${e} timed out after ${t}ms`))},t);return r.unref(),{controller:i,timeout:r,detachExternalAbort:()=>n?.removeEventListener("abort",o)}}async function Pu(e,t,n,i){if(!sv(e))return null;let o=ju("sha256"),r=0;try{for await(let a of rv(e,{signal:i})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(r+=c.length,r>n)return null;o.update(c)}}catch{if(i.aborted)throw yt(i,e);return null}let s=o.digest("hex");return s===t?s:null}async function bv(e,t,n){let i=e.fetchImpl??fetch,o;try{o=await Au(i(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?yt(t.signal,e.url):new Z("stream",`failed to download ${e.url}: ${Ou(l)}`,{cause:l})}if(!o.ok){let l=new Z("http",`failed to download ${e.url}: HTTP ${o.status}`);throw t.abort(l),l}let r=yv(o,n,e.url);if(!o.body)throw new Z("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${ov()}`,a,c=!1;try{a=Qi(s,"wx",384),c=!0;let l=o.body.getReader(),u=ju("sha256"),m=0;for(;;){let{done:p,value:h}=await Au(l.read(),t.signal);if(p)break;if(!(h instanceof Uint8Array))throw new Z("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(m+=h.byteLength,m>n||r!==void 0&&m>r){let b=new Z("length",`downloaded ${e.url} exceeded its ${r??n} byte limit`);throw t.abort(b),b}let f=Buffer.from(h.buffer,h.byteOffset,h.byteLength);u.update(f),vo(a,f,{writeFile:e.writeImpl??uv},"verified binary staging")}if(r!==void 0&&m!==r)throw new Z("length",`downloaded ${e.url} length mismatch: declared ${r} bytes, received ${m}`);let g=u.digest("hex");if(g!==e.expectedSha256)throw new Z("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${g}`);Bn(a),a=void 0;try{vv(s,e.cachePath,e.renameImpl??lv,e.syncImpl??av)}catch(p){throw new Z("install",`failed to install verified binary at ${e.cachePath}`,{cause:p})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:g}}catch(l){throw t.signal.aborted?yt(t.signal,e.url):l instanceof Z?l:new Z("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{Bn(a)}catch{}if(c)try{dv(s)}catch{}}}function yv(e,t,n){let i=e.headers?.get("content-length");if(i==null)return;if(!/^\d+$/.test(i))throw new Z("length",`downloaded ${n} has an invalid Content-Length header`);let o=Number(i);if(!Number.isSafeInteger(o)||o<0)throw new Z("length",`downloaded ${n} has an invalid Content-Length header`);if(o>t)throw new Z("length",`downloaded ${n} declares ${o} bytes, above the ${t} byte limit`);return o}function vv(e,t,n,i){Sv(e,i),Eo(()=>n(e,t)),$v(Iu(t),i)}function Sv(e,t){let n=Qi(e,process.platform==="win32"?"r+":"r");try{t(n)}finally{Bn(n)}}function $v(e,t){let n;try{n=Qi(e,"r")}catch(i){if(Yn(i,process.platform))return;throw i}try{t(n)}catch(i){if(!Yn(i,process.platform))throw i}finally{Bn(n)}}function Au(e,t){return t.aborted?Promise.reject(yt(t,"operation")):new Promise((n,i)=>{let o=()=>{t.removeEventListener("abort",o),i(yt(t,"operation"))};t.addEventListener("abort",o,{once:!0}),e.then(r=>{t.removeEventListener("abort",o),n(r)},r=>{t.removeEventListener("abort",o),i(r)})})}function yt(e,t){return e.reason instanceof Error?e.reason:new Z("aborted",`verified binary operation for ${t} was aborted`)}function Ou(e){return e instanceof Error?e.message:String(e)}var Tv=12e4,Bu="v1.8.0",Lv=`https://github.com/tlaplus/tlaplus/releases/download/${Bu}/tla2tools.jar`,Pv="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function _n(e){let t=e.spawn??Ev,n=Av(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let i=e.timeoutMs??Tv,o=Mu.now(),r;try{r=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:i,killSignal:"SIGKILL",windowsHide:!0,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Rv(l,{recursive:!0,force:!0})}let s=Math.round(Mu.now()-o),a=r.error?.name==="ETIMEDOUT"||r.signal==="SIGTERM"&&s>=i,c=a?"timed-out":r.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:r.status,signal:r.signal,timedOut:a,diagnostics:jv(c,r.stdout??"",r.stderr??""),stdout:r.stdout??"",stderr:r.stderr??""}}function Av(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&He(qu(e),t)){let r=qu(e);return He(r,t)?{checker:"apalache",command:[r,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Xi(e.specPath)}:Wn("apalache",`Apalache binary is not available: ${r}`)}let i=Yi(e),o=He("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return Wn(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'codebaseiq tla fetch-tools' or set TLA_TOOLS_JAR");if(!o)return Wn(n==="sany"?"sany":"tlc","java is not available on PATH");let r=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(r==="sany")return{checker:r,command:["java","-cp",i,"tla2sany.SANY",e.specPath],cwd:Xi(e.specPath)};let s=e.metaDir??xv(kv(Cv(),"scip-tla-tlc-"));return{checker:r,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Xi(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Wn("none",`unknown checker mode: ${n}`)}function qu(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Yi(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Wu(t)].filter(i=>typeof i=="string"&&i.length>0).find(i=>wv(i))??null}function Wu(e=process.env){return Nu("tla2tools.jar",e)}async function _u(e={}){let t=e.cachePath??Wu(e.env),n=e.expectedSha256??Pv,i=e.version??Bu,o=e.url??Lv;return{...await Du({cachePath:t,url:o,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:i,url:o}}function jv(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let i=[...Fu(n),...Fu(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(o=>({severity:"error",message:o}))}function Fu(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Wn(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Iv}from"crypto";var Gu=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Uu=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Hu=new Set(["readFileSync","existsSync","statSync"]),Nv=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Dv=/^\s*SELECT\b/i;function Ku(e){return Nv.test(e)?"write":Dv.test(e)?"read":null}var Ov=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Mv(e,t){let n=e.match(Ov);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${Ct(t)}\\b`).test(i)}function zu(e,t,n,i=[],o=[]){let r=[],s=Bv(e,t,r),a=s.aliases,c=Wv(t),l=_v(t),u=Vv(t),m=Hv(e,t,r),g=zv(e,t,r);n&&Jv(t,n,o,r);let p=new Map((n?.actions??[]).map(S=>[S.name,S])),h=new Set(m.flatMap(S=>S.referents.map(L=>L.match?.symbol).filter(Boolean))),f=new Set((g?.referents??[]).map(S=>S.match?.symbol).filter(Boolean)),b=Qv(e,t,m,a,c,l,u,h,f,r,p),v=Zv(e,m,a,c,l,u,r,p);return tS(e,m,r),nS(t,i,r),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:eo(m.flatMap(S=>S.referents))+eo(s.referents)+eo(g?.referents??[]),staticWrites:b,staticReads:v,waivers:wS(t),checkedInvariants:[...o],traceStepsChecked:i.length,findings:r,findingGroups:qv(r)}}function qv(e){let t=new Map;for(let n of e){let i=`${n.category}:${n.modelElement??"-"}`,o=t.get(i);o||(o={groupKey:i,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(i,o)),o.count+=1,o.findingIds.push(n.id),o.severity=Fv(o.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||Vn(i.severity)-Vn(n.severity)||n.groupKey.localeCompare(i.groupKey))}function Fv(e,t){return Vn(t)>Vn(e)?t:e}function Vn(e){return e==="error"?2:e==="warning"?1:0}function Bv(e,t,n){let i=[],o=[];for(let[r,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let u=Hn(e,l,n,r);o.push(u);let m=u.match;if(!m){c||n.push(J("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:l,message:`TLA+ variable ${r} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${r}.code to a live symbol, or remove the variable from the model mapping.`}));continue}fS(e,r,l,m,n,c),s.aliases.length===0&&a.add(lr(m.symbol))}for(let l of a)i.push({variable:r,alias:l})}return{aliases:$S(i),referents:o}}function Wv(e){let t=[];for(let[n,i]of Object.entries(e.variables))i.resource&&t.push({variable:n,path:i.resource.path});return t}function _v(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.statements??[])t.push({variable:n,pattern:o.pattern,regex:tn(o.pattern,`variables.${n}.statements pattern`)});return t}function Vv(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.ormCalls??[]){let{write:r,read:s}=Di(o);t.push({variable:n,table:o.table,writeMethods:new Set(r),readMethods:new Set(s)})}return t}function Gv(e,t,n,i,o,r){return Ju(e,t,(s,a,c)=>ut(e,s,a,c,n,i,o,r))}function Uv(e,t,n,i,o,r){return Ju(e,t,(s,a,c)=>Un(e,s,a,c,n,i,o,r))}function Ju(e,t,n){let i=Tt(e,t,{semantic:!1});if(!i)return[];let o=[],r=new Set;for(let s of i.callees){if(r.has(s.symbol))continue;r.add(s.symbol);let a=cn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))o.push({...c,via:s.shortName})}return o}function Hv(e,t,n){return Object.entries(t.actions).map(([i,o])=>{let r=o.code.map(s=>{let a=Oi(s),c="error"in a?s:a.ref,u=Hn(e,c,n,i).match;return u?(bS(e,i,s,u,n),"error"in a||!a.window?{ref:s,match:u}:Kv(a.window,u)?(n.push(J("invalid-line-window","error","compiler-symbol",{modelElement:i,codeRef:s,file:u.relativePath,startLine:u.startLine,endLine:u.endLine,message:`TLA+ action ${i} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${oe(u.symbol)}'s actual span L${u.startLine+1}-L${u.endLine+1} in ${u.relativePath}.`,why:[`${s} resolves to ${oe(u.symbol)} at ${u.relativePath}:${u.startLine+1}-${u.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${i}.code to fall within L${u.startLine+1}-L${u.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:u,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(J("missing-referent","error","compiler-symbol",{modelElement:i,codeRef:s,message:`TLA+ action ${i} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${i}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:i,mapping:o,referents:r}})}function Kv(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function zv(e,t,n){let i=t.init;if(!i)return;let o=!!i.waive,r=i.codeRefs.map(s=>{let a=Hn(e,s,n,"Init"),c=a.match;return c?yS(e,s,c,n,o):o||n.push(J("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:i,referents:r}}function Jv(e,t,n,i){let o=new Set(t.variables),r=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))o.has(a)||i.push(J("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))r.has(a)||i.push(J("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(Vu({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:i,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),Vu({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:i,file:t.path}))}for(let a of e.invariants)s.has(a)||i.push(J("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function Vu(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),i=e.isWaived??(()=>!1);for(let o of t)n.has(o)||i(o)||e.findings.push(J(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${o} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${o} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let o of n)t.has(o)||i(o)||e.findings.push(J(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${o}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${o}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Qv(e,t,n,i,o,r,s,a,c,l,u){let m=[];for(let p of n){let h=[];for(let f of p.referents){if(!f.match)continue;let b=f.window??{startLine:f.match.startLine,endLine:f.match.endLine},v=ut(e,f.match.relativePath,b.startLine,b.endLine,i,o,r,s);h.push(...v),m.push(...v);let S=new Set(p.mapping.writes),L=Gv(e,f.match.symbol,i,o,r,s).filter(B=>S.has(B.variable));h.push(...L),m.push(...L)}Yv(p,h,l,u.get(p.name))}let g=t.unmappedWriteScope==="actions"?[]:mS(e,t);for(let p of g)for(let h of ut(e,p,0,Number.POSITIVE_INFINITY,i,o,r,s))m.push(h),Xv(h)&&(h.enclosingSymbol&&(a.has(h.enclosingSymbol)||c.has(h.enclosingSymbol))||l.push(J("unmapped-write","error","static-action",{modelElement:h.variable,codeRef:h.enclosingSymbol??`${h.file}:${h.line+1}`,file:h.file,startLine:h.line,endLine:h.line,message:`Modeled variable ${h.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${h.target} at ${h.file}:${h.line+1}.`,h.enclosingShort?`The write is inside ${h.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${h.variable} from the modeled slice if it is intentionally out of scope.`})));return io(m)}function Xv(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function Yv(e,t,n,i){let o=new Set(e.mapping.writes),r=new Set(t.map(a=>a.variable)),s=new Set(i?.writes??[]);for(let a of t)i&&!s.has(a.variable)&&!Kt(e,"write",a.variable)&&n.push(J("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Gn(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${i.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!o.has(a.variable)&&!Kt(e,"write",a.variable)&&n.push(J("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Gn(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of o)!r.has(a)&&!Kt(e,"write",a)&&n.push(J("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function Zv(e,t,n,i,o,r,s,a){let c=[];for(let l of t){let u=[];for(let m of l.referents){if(!m.match)continue;let g=m.window??{startLine:m.match.startLine,endLine:m.match.endLine},p=Un(e,m.match.relativePath,g.startLine,g.endLine,n,i,o,r);u.push(...p),c.push(...p);let h=new Set(l.mapping.reads),f=Uv(e,m.match.symbol,n,i,o,r).filter(b=>h.has(b.variable));u.push(...f),c.push(...f)}eS(l,u,s,a.get(l.name))}return oo(c)}function eS(e,t,n,i){let o=new Set(e.mapping.reads),r=new Set(t.map(a=>a.variable)),s=new Set(i?.reads??[]);for(let a of t)i&&!s.has(a.variable)&&n.push(J("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Gn(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${i.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!o.has(a.variable)&&!Kt(e,"read",a.variable)&&n.push(J("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Gn(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of o)!r.has(a)&&!Kt(e,"read",a)&&n.push(J("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function tS(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let o=i.mapping.calls.map(s=>Hn(e,s,n,i.name));for(let s of o)s.match||n.push(J("missing-referent","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,message:`actions.${i.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${i.name}.calls to a live symbol or remove the stale call expectation.`}));let r=new Set(o.map(s=>s.match?.symbol).filter(Boolean));for(let s of i.referents){if(!s.match)continue;let a=Tt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of r)c.has(l)||n.push(J("missing-call","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${i.name} no longer calls ${oe(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${i.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function nS(e,t,n){for(let[i,o]of t.entries()){let r=e.actions[o.action];if(!r){n.push(J("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} uses action ${o.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${o.action} to the mapping, or fix the trace action name.`}));continue}let s=SS(o),a=new Set(r.writes);for(let c of s)a.has(c)||n.push(J("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} changed ${c}, but action ${o.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${o.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function ut(e,t,n,i,o,r=[],s=[],a=[]){let c=iS(e,t,n,i,o,r,s,a);return c||uS(e,t,n,i,o,r,s,a)}function Un(e,t,n,i,o,r=[],s=[],a=[]){let c=oS(e,t,n,i,o,r,s,a);return c||pS(e,t,n,i,o,r,s,a)}function iS(e,t,n,i,o,r=[],s=[],a=[]){let c=si(e,t);if(!c)return null;let l=[],u=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){rS(e,t,m,o,l),Qu(e,t,m,r,"write",l),Xu(e,t,m,s,"write",l),Yu(e,t,m,a,"write",l);for(let g of m.children)u(g)}};return u(c.rootNode),io(l)}function oS(e,t,n,i,o,r=[],s=[],a=[]){let c=si(e,t);if(!c)return null;let l=[],u=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){cS(e,t,m,o,l),Qu(e,t,m,r,"read",l),Xu(e,t,m,s,"read",l),Yu(e,t,m,a,"read",l);for(let g of m.children)u(g)}};return u(c.rootNode),oo(l)}function rS(e,t,n,i,o){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let r=n.childForFieldName("left")??n.namedChild(0);r&&Ht(e,t,r,"assignment",i,o);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let r=n.childForFieldName("key")??n.namedChild(0);r&&Ht(e,t,r,"object-field",i,o);return}if(n.type==="update_expression"){let r=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);r&&Ht(e,t,r,"update",i,o);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let r=n.namedChild(0);r&&Ht(e,t,r,"delete",i,o);return}if(n.type==="call_expression"){let r=n.childForFieldName("function")??n.namedChild(0);if(!r||!ep(r))return;Ht(e,t,r,"mutation-call",i,o)}}}function Qu(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?to(s):null;if(!a||!(o==="write"?Uu:Hu).has(a))return;let u=n.childForFieldName("arguments")?.namedChild(0);if(!u)return;let m=u.text;for(let g of i){if(!m.includes(g.path))continue;let p=Ve(e,t,n.startPosition.row);r.push({variable:g.variable,alias:g.path,file:t,line:n.startPosition.row,target:`${a}(${m})`,kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?oe(p.symbol):void 0})}}function to(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function Xu(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=sS(a);if(c!==null&&Ku(c)===o)for(let l of i){if(!l.regex.test(c))continue;let u=Ve(e,t,n.startPosition.row),m=n.childForFieldName("function")??n.namedChild(0),g=(m&&to(m))??"call";r.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${g}(${aS(c)})`,kind:"statement",enclosingSymbol:u?.symbol,enclosingShort:u?oe(u.symbol):void 0})}}}function sS(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function aS(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Yu(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?to(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let u=l.text.trim();for(let m of i){if(!Zu(m,a,u,o))continue;let g=Ve(e,t,n.startPosition.row);r.push({variable:m.variable,alias:m.table,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"orm-call",enclosingSymbol:g?.symbol,enclosingShort:g?oe(g.symbol):void 0})}}function Zu(e,t,n,i){return n!==e.table?!1:i==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function cS(e,t,n,i,o){if(!(!lS(n)||dS(n)))for(let r of i){if(n.text!==r.alias)continue;let s=Ve(e,t,n.startPosition.row);o.push({variable:r.variable,alias:r.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?oe(s.symbol):void 0})}}function lS(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function dS(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&Zi(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&Zi(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&ep(n)&&Zi(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function Zi(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function ep(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Gu.has(t.text))}function Ht(e,t,n,i,o,r){for(let s of o){if(!vS(s.alias,n.text))continue;let a=Ve(e,t,n.startPosition.row);r.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:i,enclosingSymbol:a?.symbol,enclosingShort:a?oe(a.symbol):void 0})}}function uS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),u=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let g=Math.max(0,n);g<=m;g+=1){let p=l[g]??"";for(let h of o){if(Mv(p,h.alias))continue;let f=Ct(h.alias);if(!new RegExp(`(?:\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${f}\\b\\s*\\.\\s*(?:${[...Gu].join("|")})\\s*\\(|\\b${f}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(p))continue;let v=Ve(e,t,g);u.push({variable:h.variable,alias:h.alias,file:t,line:g,target:p.trim(),kind:"source-scan",enclosingSymbol:v?.symbol,enclosingShort:v?oe(v.symbol):void 0})}tp(e,t,g,p,r,Uu,u),np(e,t,g,p,s,"write",u),ip(e,t,g,p,a,"write",u)}return io(u)}function pS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),u=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let g=Math.max(0,n);g<=m;g+=1){let p=l[g]??"";for(let h of o){let f=Ct(h.alias);if(!new RegExp(`\\b${f}\\b`).test(p)||new RegExp(`\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(p))continue;let b=Ve(e,t,g);u.push({variable:h.variable,alias:h.alias,file:t,line:g,target:p.trim(),kind:"source-scan",enclosingSymbol:b?.symbol,enclosingShort:b?oe(b.symbol):void 0})}tp(e,t,g,p,r,Hu,u),np(e,t,g,p,s,"read",u),ip(e,t,g,p,a,"read",u)}return oo(u)}function tp(e,t,n,i,o,r,s){if(o.length!==0)for(let a of r){let c=i.indexOf(`${a}(`);if(c===-1)continue;let l=i.slice(c+a.length);for(let u of o){if(!l.includes(u.path))continue;let m=Ve(e,t,n);s.push({variable:u.variable,alias:u.path,file:t,line:n,target:i.trim(),kind:"resource",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function np(e,t,n,i,o,r,s){if(o.length!==0&&Ku(i)===r)for(let a of o){if(!a.regex.test(i))continue;let c=Ve(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:i.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?oe(c.symbol):void 0})}}function ip(e,t,n,i,o,r,s){if(o.length!==0)for(let a of i.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let u of o){if(!Zu(u,c,l,r))continue;let m=Ve(e,t,n);s.push({variable:u.variable,alias:u.table,file:t,line:n,target:i.trim(),kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function mS(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(o=>o.relative_path).filter(o=>n.some(r=>o.includes(r)))}function Hn(e,t,n,i){let o=cn(e,t),r=o.match??(t.includes("#")?cn(e,t.replace("#","/")).match:null);return o.match&&o.total>1&&!gS(t)&&n.push(J("ambiguous-referent","warning","compiler-symbol",{modelElement:i,codeRef:t,file:o.match.relativePath,startLine:o.match.startLine,endLine:o.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${oe(o.match.symbol)}.`,why:[`${o.total} indexed definitions share this lookup shape.`,hS(o.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:r}}function gS(e){return/[/#:]/.test(e)}function hS(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function fS(e,t,n,i,o,r=!1){let s=no(e,i);if(s===null||xS.has(s)||r)return;let a=ro.has(s);o.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${kt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${kt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function bS(e,t,n,i,o){let r=no(e,i);r===null||op.has(r)||ro.has(r)&&o.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${kt(r)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function yS(e,t,n,i,o){let r=no(e,n);r===null||op.has(r)||o||ro.has(r)&&i.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${oe(n.symbol)} with SCIP kind ${kt(r)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function no(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ve(e,t,n){return an(e,t).filter(o=>o.startLine<=n&&o.endLine>=n).sort((o,r)=>o.endLine-o.startLine-(r.endLine-r.startLine))[0]??null}function vS(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Ct(e)}([^A-Za-z0-9_$]|$)`).test(t)}function SS(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function io(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function oo(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function $S(e){let t=new Set;return e.filter(n=>{let i=`${n.variable}:${n.alias}`;return t.has(i)?!1:(t.add(i),!0)})}function eo(e){return e.filter(t=>t.match).length}function Gn(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Kt(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function wS(e){let t=Object.entries(e.actions).flatMap(([r,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:r,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:r,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([r,s])=>{let a=s.waive;return a?[{kind:"referent",variable:r,reason:a.reason,legacy:!1}]:[]}),i=e.init?.waive,o=i?[{kind:"referent",variable:"Init",reason:i.reason,legacy:!1}]:[];return[...t,...n,...o]}var ro=new Set(pr()),op=new Set(ur()),xS=new Set(mr());function J(e,t,n,i){let o=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${Iv("sha1").update(o).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{basename as RS,join as CS}from"path";var so=/^[A-Za-z_][A-Za-z0-9_]*$/;function rp(e,t,n={}){let i=[],o=an(e,t,{includeClassMemberFallbacks:!0});if(o.length===0)throw new Error(`no indexed definitions found for ${t}; run 'codebaseiq reindex' or check the path`);let s=at(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=w=>w.symbol.trimEnd().endsWith("()."),c=o.filter(w=>!a(w)&&!w.isTypeLike&&w.parentTypeName===null&&so.test(w.leaf)),l=c.map(w=>({variable:w.leaf,alias:w.leaf})),u=l.length>0?ut(e,t,0,Number.POSITIVE_INFINITY,l):[],m=new Set(u.map(w=>w.variable)),g=c.filter(w=>m.has(w.leaf)?!0:TS(s,w)),p=null,h;if(g.length>0)h=o.filter(w=>a(w)&&w.parentTypeName===null);else{if(p=kS(e,t,o,a),!p){let w=o.some(_=>!a(_)&&!_.isTypeLike&&_.parentTypeName!==null&&so.test(_.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(w?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}g=p.fields,h=p.methods,i.push(`state scoped to class ${p.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let f=g.map(w=>LS(w,s,t,i,p?.className)),b=f.map(w=>({variable:w.name,alias:w.leaf})),v=[],S=new Set;for(let w of h){let _=ut(e,t,w.startLine,w.endLine,b);if(_.length===0)continue;let U=Un(e,t,w.startLine,w.endLine,b),O=IS(sp(w.leaf),S);v.push({name:O,leaf:w.leaf,codeRef:ES(t,w,p?.className),startLine:w.startLine,writes:[...new Set(_.map(ee=>ee.variable))].sort(),reads:[...new Set(U.map(ee=>ee.variable))].sort()})}v.length===0&&i.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let L=n.moduleName??NS(t),B=n.specDir??CS("specs",L),H=DS(L,f,v,t),j=OS(),W=MS(L,B,t,f,v);return{moduleName:L,file:t,variables:f,actions:v,warnings:i,spec:H,cfg:j,map:W}}function kS(e,t,n,i){let o=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!so.test(s.leaf))continue;let a=o.get(s.parentTypeName);a?a.push(s):o.set(s.parentTypeName,[s])}let r=null;for(let[s,a]of o){let c=n.filter(g=>i(g)&&g.parentTypeName===s),l=a.map(g=>({variable:g.leaf,alias:g.leaf})),u=new Set;for(let g of c)for(let p of ut(e,t,g.startLine,g.endLine,l))u.add(p.variable);let m=a.filter(g=>u.has(g.leaf));m.length!==0&&(!r||m.length>r.fields.length)&&(r={className:s,fields:m,methods:c})}return r}function ES(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function TS(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function LS(e,t,n,i,o){let r=PS(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=AS(e.leaf,r);return a||i.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||i.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:o?`${n}/${o}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function PS(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function AS(e,t){let i=t.match(new RegExp(`\\b${qS(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,r=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=jS(i);l?(s=`{${l.map(u=>`"${u}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(i)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(i)||/^(Array|ReadonlyArray)</.test(i))&&(a="sequence",s=null)}let c=null;if(r){let l=r.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(r)?c=r.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(r)?c=r.match(/^-?\d+/)[0]:/^\[\s*\]/.test(r)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function jS(e){let t=e.split("|").map(i=>i.trim());if(t.length<2)return null;let n=[];for(let i of t){let o=i.match(/^['"]([^'"]*)['"]$/);if(!o)return null;n.push(o[1])}return n}function sp(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function IS(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function NS(e){let n=RS(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return sp(n||"Model")}function DS(e,t,n,i){let o=t.map(s=>s.name),r=[];r.push(`---- MODULE ${e} ----`),r.push(`\\* Scaffolded by 'codebaseiq tla scaffold ${i}'.`),r.push("\\* Draft evidence tier: state from the static write scan, domains from"),r.push("\\* declared types, actions from top-level callables that write state."),r.push("\\* Review every TODO before trusting a green model-check run."),r.push("EXTENDS Naturals, Sequences, TLC"),r.push(""),r.push(`VARIABLES ${o.join(", ")}`),r.push(""),r.push(`vars == <<${o.join(", ")}>>`),r.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';r.push(`${s.name}Domain == ${a}`)}r.push(""),r.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;r.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}r.push("");for(let s of n){let a=o.filter(c=>!s.writes.includes(c));r.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),r.push(`${s.name} ==`),r.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let u=t.find(m=>m.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;r.push(` /\\ ${c}' \\in ${u} \\* TODO: tighten to the concrete transition`)}a.length>0&&r.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),r.push("")}if(r.push("Next =="),n.length===0)r.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())r.push(` \\/ ${a.name}`);r.push(""),r.push("Spec == Init /\\ [][Next]_vars"),r.push(""),r.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?r.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):r.push(` /\\ ${s.name} \\in ${s.name}Domain`);return r.push("===="),r.push(""),r.join(`
|
|
272
|
+
`)}function OS(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
|
|
273
|
+
`)}function MS(e,t,n,i,o){let r={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"codebaseiq tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(o.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(r,null,2)}
|
|
274
|
+
`}function qS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ap(e,t){let n=Object.keys(t.variables),i=Object.entries(t.actions).map(([o,r])=>{let s=r.code[0]??"",a=s?dr(e,s):null;return{action:o,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:r.writes}});return{recorderSource:FS(n),wiring:i,variables:n}}function FS(e){return`/**
|
|
275
275
|
* Generated by 'codebaseiq tla instrument'. Dependency-free trace recorder.
|
|
276
276
|
*
|
|
277
277
|
* Usage inside a mapped action (record the model-visible slice around the
|
|
@@ -322,16 +322,16 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
|
|
|
322
322
|
if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
|
|
323
323
|
writeFileSync(tracePath, payload);
|
|
324
324
|
}
|
|
325
|
-
`}import{copyFileSync as
|
|
325
|
+
`}import{copyFileSync as BS,mkdtempSync as WS,readdirSync as _S,rmSync as VS,writeFileSync as cp}from"fs";import{tmpdir as GS}from"os";import{basename as US,dirname as HS,join as zt}from"path";function Kn(e,t){let n=new Map;for(let i of t)n.set(i.action,(n.get(i.action)??0)+1);return e.map(i=>({action:i,stepsObserved:n.get(i)??0}))}function KS(e,t,n,i="Next"){if(n.length===0)return{error:"trace has no steps"};let o=[],r=n[0];if(!r.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...r.before},c=f=>{let b={};for(let[v,S]of Object.entries(f)){if(!t.includes(v))continue;let L=JS(S);L!==void 0&&(b[v]=L)}return b};s.push(c(a));for(let f of n){if(f.before)for(let[b,v]of Object.entries(f.before))b in a||(a[b]=v);Object.assign(a,f.after??{}),s.push(c(a))}let l=t.filter(f=>s.every(b=>f in b)),u=t.filter(f=>!l.includes(f));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};u.length>0&&o.push(`variables not pinned by the trace (missing or non-scalar values): ${u.join(", ")} \u2014 divergence in these variables is NOT checked.`);let m=`${e}Trace`,g=s.map(f=>` [${l.map(b=>`${b} |-> ${dp(f[b])}`).join(", ")}]`).join(`,
|
|
326
326
|
`),p=[`---- MODULE ${m} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${i}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",g,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(f=>` /\\ ${f} = TraceStates[1].${f}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${i}`,...l.map(f=>` /\\ ${f}' = TraceStates[traceIdx + 1].${f}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
|
|
327
327
|
`),h=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
|
|
328
|
-
`);return{moduleName:m,moduleText:p,cfgText:h,variables:l,skippedVariables:u,states:s.length,warnings:o}}function
|
|
329
|
-
`));let{contract:a,mapDir:c}=s.loaded,l=
|
|
330
|
-
`));let{contract:c}=a.loaded,l=A(n,"trace"),m=
|
|
331
|
-
`));let{contract:l,mapPath:u,mapDir:m}=c.loaded,g=$(n,"config")??l.config,p=
|
|
332
|
-
Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${o}`);for(let r of
|
|
328
|
+
`);return{moduleName:m,moduleText:p,cfgText:h,variables:l,skippedVariables:u,states:s.length,warnings:o}}function lp(e){let t=e.mappedActions??[],n=KS(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Kn(t,[])};let i=WS(zt(GS(),"scip-tla-trace-"));try{let o=HS(e.specPath);for(let u of _S(o))u.endsWith(".tla")&&BS(zt(o,u),zt(i,u));let r=zt(i,`${n.moduleName}.tla`),s=zt(i,`${n.moduleName}.cfg`);cp(r,n.moduleText),cp(s,n.cfgText);let a=_n({...e.toolOptions,specPath:r,configPath:s,checker:"tlc"});if(a.status==="skipped")return{status:"unavailable",states:n.states,detail:a.diagnostics[0]?.message??"model checker unavailable",checker:a,generation:n,actionCoverage:Kn(t,[])};if(a.status==="passed")return{status:"accepted",states:n.states,detail:`TLC accepted all ${n.states} pinned states under ${e.baseModuleName}!${e.nextOperator??"Next"}.`,checker:a,generation:n,actionCoverage:Kn(t,e.steps)};let c=zS(a.stdout,e.steps),l=c?e.steps.slice(0,c.divergedStep.index):[];return{status:"diverged",states:n.states,...c??{},detail:c?`trace diverges entering state ${c.divergedAtState+1} (step ${c.divergedStep.index}: ${c.divergedStep.action}) \u2014 the model's ${e.nextOperator??"Next"} relation does not accept the recorded transition.`:"TLC rejected the trace but the divergent step could not be parsed from its output; see checker stdout.",checker:a,generation:n,actionCoverage:Kn(t,l)}}finally{VS(i,{recursive:!0,force:!0})}}function zS(e,t){let n=null;for(let r of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(r[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let i=n-1,o=t[i];return{divergedAtState:n,divergedStep:{index:i,action:o?.action??"unknown"}}}function JS(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isInteger(e))return e;if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n=="string"||typeof n=="boolean")t.push(n);else if(typeof n=="number"&&Number.isInteger(n))t.push(n);else return;return t}}function dp(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>dp(t)).join(", ")}>>`}function up(e){return US(e).replace(/\.tla$/i,"")}import{mkdirSync as mp,writeFileSync as gp}from"fs";import{dirname as QS,join as vt}from"path";var XS=async(...e)=>{let{args:t,opts:n}=Sn(e),i=N(t,0);if(i==="fetch-tools"){let r=await _u();if(y(n,"json")){P("tla",t,n,r);return}console.log(`tla2tools.jar ${r.status}: ${r.path}`),console.log(`Version: ${r.version}`),console.log(`SHA-256: ${r.sha256}`);return}if(i==="scaffold"){let r=G(t,1);if(!r)throw new Error("tla scaffold requires a target source file");Ee(s=>YS(s,t,n,r));return}if(i==="instrument"){let r=G(t,1);Ee(s=>ZS(s,t,n,r));return}if(i==="trace-check"){let r=G(t,1);if(!r)throw new Error("tla trace-check requires a spec path");Ee(s=>e$(s,t,n,r));return}if(i!=="verify")throw new Error(`unknown tla operation: ${i}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let o=G(t,1);if(!o)throw new Error("tla verify requires a spec path");Ee(r=>i$(r,t,n,o))};function YS(e,t,n,i){let o=e.config.projectRoot,r=rp(e,i,{moduleName:$(n,"moduleName"),specDir:$(n,"out")}),s=$(n,"out")??vt("specs",r.moduleName),a=we(o,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=y(n,"force"),l=[{path:vt(a,`${r.moduleName}.tla`),body:r.spec},{path:vt(a,`${r.moduleName}.cfg`),body:r.cfg},{path:vt(a,`${r.moduleName}.scip-tla.json`),body:r.map}];for(let u of l)if(!c&&Jt(u.path))throw new Error(`refusing to overwrite ${u.path} (pass --force to replace scaffold output)`);mp(a,{recursive:!0});for(let u of l)gp(u.path,u.body);if(y(n,"json")){P("tla",t,n,{operation:"scaffold",moduleName:r.moduleName,target:i,written:l.map(u=>u.path),variables:r.variables,actions:r.actions,warnings:r.warnings});return}console.log(`Scaffolded ${r.moduleName} from ${i} (draft \u2014 review every TODO):`);for(let u of l)console.log(` wrote ${u.path}`);console.log(`Variables (${r.variables.length}): ${r.variables.map(u=>`${u.name}${u.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${r.actions.length}): ${r.actions.map(u=>`${u.name}(writes: ${u.writes.join(",")||"-"})`).join("; ")}`);for(let u of r.warnings)console.log(`WARNING: ${u}`);console.log(`Next: fill the TODO guards/domains, then run 'codebaseiq tla verify ${vt(s,`${r.moduleName}.tla`)}'.`)}function ZS(e,t,n,i){let o=e.config.projectRoot,r=$(n,"map")??(i?On(i):void 0);if(!r)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Dn(o,r);if(!s.loaded)throw new Error(s.errors.join(`
|
|
329
|
+
`));let{contract:a,mapDir:c}=s.loaded,l=ap(e,a),u=$(n,"out")??vt(c,"scip-tla-recorder.ts"),m=we(o,u);if(!m)throw new Error(`instrument output escapes the project root: ${u}`);if(!y(n,"force")&&Jt(m))throw new Error(`refusing to overwrite ${m} (pass --force to replace the recorder)`);if(mp(QS(m),{recursive:!0}),gp(m,l.recorderSource),y(n,"json")){P("tla",t,n,{operation:"instrument",recorder:m,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${m}`),console.log("Wire tlaRecord(...) into each mapped action (1 line per action), then run your tests with"),console.log("SCIP_TLA_TRACE=<trace.json> set, and check the result with 'codebaseiq tla trace-check'."),console.log("Wiring sites:");for(let g of l.wiring){let p=g.file?`${g.file}:${g.line}`:`UNRESOLVED (${g.codeRef})`;console.log(` - ${g.action} -> ${p} writes: ${g.writes.join(", ")||"-"}`)}}function e$(e,t,n,i){let o=e.config.projectRoot,r=we(o,i);if(!r||!Jt(r))throw new Error(`TLA+ spec not found: ${i}`);let s=$(n,"map")??On(i),a=Dn(o,s);if(!a.loaded)throw new Error(a.errors.join(`
|
|
330
|
+
`));let{contract:c}=a.loaded,l=A(n,"trace"),m=qi(o,[...c.traces,...l]).flatMap(h=>Mi(o,h).steps);if(m.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let g=lp({specPath:r,baseModuleName:up(r),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:m,nextOperator:$(n,"next"),toolOptions:{projectRoot:o,tlaToolsJar:$(n,"tlaTools"),timeoutMs:K(n,"timeoutMs")}}),p=g.status==="accepted"||g.status==="unavailable"&&y(n,"allowUnknown")?0:1;if(y(n,"json")){P("tla",t,n,{operation:"trace-check",...g,exitCode:p}),process.exitCode=p;return}if(console.log(`TLA+ trace-check: ${r}`),console.log(`Trace: ${m.length} step(s) -> ${g.states} pinned state(s)`),g.generation){console.log(`Pinned variables: ${g.generation.variables.join(", ")}`);for(let h of g.generation.warnings)console.log(`WARNING: ${h}`)}console.log(`${g.status.toUpperCase()}: ${g.detail}`),y(n,"coverage")&&t$(g.actionCoverage),process.exitCode=p}function t$(e){if(e.length===0)return;let t=e.filter(i=>i.stepsObserved>0),n=e.filter(i=>i.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let i of t)console.log(` - ${i.action}: ${i.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(i=>i.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function n$(e,t,n,i){let o=$(i,"map");if(o)return{mapArg:o};let r=On(t),s=we(e,r);if(s&&Jt(s))return{mapArg:r};let a=hd(e,n);if(a.status==="ambiguous")throw new Error(`multiple *.scip-tla.json files declare module "${a.moduleName}": ${a.candidates.join(", ")} \u2014 pass --map to disambiguate`);return a.status==="found"?{mapArg:a.mapPath,mappingDiscoveredBy:"module-field"}:{mapArg:r}}function i$(e,t,n,i){let o=e.config.projectRoot,r=we(o,i);if(!r||!Jt(r))throw new Error(`TLA+ spec not found: ${i}`);let{mapArg:s,mappingDiscoveredBy:a}=n$(o,i,r,n),c=Dn(o,s);if(!c.loaded)throw new Error(c.errors.join(`
|
|
331
|
+
`));let{contract:l,mapPath:u,mapDir:m}=c.loaded,g=$(n,"config")??l.config,p=dd(o,m,g),h=r$($(n,"checker")??"auto"),f=$(n,"tlaTools"),b=o$(o,i,r,f)??ud(o,i),v=md(p),S=A(n,"trace"),B=qi(o,[...l.traces,...S]).map(O=>({tracePath:O,...Mi(o,O)})),H=B.flatMap(O=>O.steps),j=new Set(S),W=B.filter(O=>j.has(O.tracePath)).flatMap(O=>O.errors),w=zu(e,l,b,H,v);for(let O of[...c.errors,...W])w.findings.push({id:`TLA-CONTRACT-${w.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:O,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun codebaseiq tla verify."});let _=_n({projectRoot:o,specPath:r,configPath:p??void 0,checker:h,tlaToolsJar:f,apalacheBin:$(n,"apalache"),length:E(n,"length",10),timeoutMs:K(n,"timeoutMs")});_.status==="skipped"&&h!=="none"&&w.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:_.diagnostics.map(O=>O.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'codebaseiq tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let U={operation:"verify",specPath:r,mapPath:u,...a?{mappingDiscoveredBy:a}:{},...p?{configPath:p}:{},checker:_,conformance:w,exitCode:s$(_,w,y(n,"allowUnknown"))};if(y(n,"json")){P("tla",t,n,U),process.exitCode=U.exitCode;return}a$(U,y(n,"full")),process.exitCode=U.exitCode}function o$(e,t,n,i){let o=Yi({projectRoot:e,specPath:n,tlaToolsJar:i,checker:"sany"});if(!o)return null;let r=ed({specPath:n,jarPath:o});return r?pd(e,t,r):null}var hp=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",agent:le("Does this TLA+ model and code mapping agree, or can the requested model artifact be generated?","checker status, conformance findings, trace coverage, or generated artifact paths",["action","path"],"bounded","repository",z("repository-observation",[{when:{kind:"argument",index:0,equals:"scaffold"},role:"mutation"},{when:{kind:"argument",index:0,equals:"instrument"},role:"mutation"},{when:{kind:"argument",index:0,equals:"fetch-tools"},role:"composite"}])),options:C([d("--map <file>","codebaseiq TLA mapping JSON file"),d("--config <file>","TLA+ checker config file"),d("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),d("--tla-tools <jar>","Path to tla2tools.jar"),d("--apalache <binary>","Path to apalache-mc binary"),d("--length <n>","Bounded checker length for Apalache",x,10),d("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",ne),d("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",q,[]),d("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),d("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),d("--allow-unknown","Exit zero when only unknown findings remain"),d("--out <path>","Output directory (scaffold) or file (instrument)"),d("--module-name <name>","Module name for scaffolded specs"),d("--force","Overwrite existing scaffold/instrument output"),d("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:R("Formal Models",["codebaseiq tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","codebaseiq tla scaffold src/queue/store.ts","codebaseiq tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","codebaseiq tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","codebaseiq tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","codebaseiq tla verify specs/Queue.tla --timeout-ms 300000","codebaseiq tla verify specs/Queue.tla --full","codebaseiq tla fetch-tools"]),handler:XS}];function r$(e){if(!ld(e))throw new Error(`unknown checker mode: ${e}`);return e}function s$(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(i=>i.severity==="error")||!n&&t.findings.some(i=>i.evidence==="unknown")?1:0}var pp=3;function a$(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let r of e.checker.diagnostics)console.log(` [${r.severity}] ${r.message}`);let n=e.conformance.findings.filter(r=>r.severity==="error"),i=e.conformance.findings.filter(r=>r.evidence==="unknown"),o=l$(e);console.log(`
|
|
332
|
+
Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${o}`);for(let r of d$(e))console.log(`WARNING: ${r}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let r of e.conformance.waivers){let s=r.legacy?" legacy":"",a=r.action?`${r.action} ${r.kind}`:`variable ${r.kind}`;console.log(` - ${a} ${r.variable}:${s} ${r.reason}`)}}if(e.conformance.findings.length===0){console.log(e.conformance.waivers.length===0?`PASS: model, mapping, and checked code evidence agree (model parsed by: ${e.conformance.modelParse}).`:`PASS: model checker and unwaived conformance checks passed (model parsed by: ${e.conformance.modelParse}); see waived facts above.`);return}if(console.log(`Findings: ${n.length} error(s), ${i.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let r of e.conformance.findings)fp(r);return}c$(e.conformance)}function c$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
|
|
333
333
|
Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
|
|
334
|
-
[${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let o of n.findingIds.slice(0,
|
|
335
|
-
[${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var
|
|
336
|
-
--focus, --scope, or --file points that viewer at the target and returns at once, so an agent can show a person a symbol.`,options:[d("--focus <selector>","Open the focus view of one symbol"),d("--scope <dir>","Open the map at one folder"),d("--file <path>","Open one file"),d("--port <n>","Listen on this port instead of a free one",Te),d("--no-open","Print the address without opening a browser")],renderShape:"custom",docs:R("Graph",["codebaseiq view","codebaseiq view --focus handleRequest","codebaseiq view --scope src/runtime"]),handler:b$};var IE=[ca,wa,{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:le("Did indexed source changes preserve the repository architecture policy?","architecture policy decision and enforced finding identities",[],"complete","diff",K("repository-observation")),description:"Internal architecture-only Stop hook",renderShape:"custom",handler:Sl},{id:"reindex",command:"reindex",agent:le("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository",K("composite")),description:"Index the codebase and convert to SQLite",options:C([d("-l, --language <lang>","Index only this language (can be repeated)",F,[]),d("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),d("--force","Rebuild even if source inputs are unchanged"),d("--allow-partial","Write an incomplete index when one or more detected languages fail"),d("--trust-project-tools","Permit reviewed indexers from this repository for this run"),d("--install-missing","Install missing global tools at reviewed immutable versions for this run"),d("--indexer-concurrency <n>","Number of language indexers to run at once",ne)]),renderShape:"custom",docs:R("Indexing",["codebaseiq reindex"]),handler:$l},{id:"augment-sources",command:"augment-sources",agent:le("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository",K("composite")),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:R("Indexing"),handler:wl},{id:"augment-vue",command:"augment-vue",agent:le("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository",K("composite")),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[d("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:R("Indexing"),handler:xl},...wp,{id:"__query-lane-ping",command:"__query-lane-ping",description:"Internal query lane transport probe",hidden:!0,renderShape:"custom",handler:Hl},{id:jt,command:jt,description:"Internal diff-impact batch worker",hidden:!0,options:[d("--json","Emit the private worker envelope without transport pagination"),d("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Rl},{id:"diff-impact",command:"diff-impact",agent:k("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:C([d("--base <ref>","Git ref to diff against (default: HEAD)")]),claims:qe(["index-generation","live-workspace"],[X("changed-files","changedFiles[]","repository-source"),X("changed-symbols","changedSymbols[]","compiler-graph"),X("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:R("Impact"),handler:Cl},{id:At,command:At,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[d("--json","Emit the private worker envelope without transport pagination"),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:kl},{id:"health",command:"health",agent:le("Where has this repository accumulated drift, duplication, complexity, or cleanup pressure?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository",K("repository-observation",[{when:{kind:"option",name:"writeBaseline",equals:!0},role:"composite"}])),description:"Composite repository health report with React, Vue, and general cleanup findings",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded candidate analyses on large indexes"),d("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),d("--write-baseline","Snapshot current finding identities to the baseline file")]),claims:qe(["index-generation","live-workspace","process"],[Ca("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),X("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:R("Health",["codebaseiq health --json","codebaseiq health --baseline"]),handler:El},{id:"install-skills",command:"install-skills",agent:le("Which codebaseiq skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",K("mutation")),description:`Install skills (${Ln.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:R("Maintenance"),handler:Tl},{id:"check-deps",command:"check-deps",agent:k("Which codebaseiq and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository",K("environment-observation")),description:"Check whether codebaseiq and the detected language indexers are runnable",renderShape:"custom",docs:R("Maintenance"),handler:Ll},{id:"capabilities",command:"capabilities",agent:k("Which repository-mapping and analysis capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository",K("environment-observation")),description:"Report which mapping and analysis capabilities are available in this project",options:C([d("--matrix","Add exhaustive provider and language support details")]),renderShape:"custom",docs:R("Maintenance"),handler:Pl},{id:"init",command:"init",agent:le("Can a starter codebaseiq configuration be created for this project?","configuration path and creation outcome",[],"complete","repository",K("mutation")),description:"Create a .codebaseiq.json configuration file for this project",renderShape:"custom",docs:R("Maintenance"),handler:Al},{id:"config-validate",command:"config-validate",agent:k("Is this project configuration valid and internally consistent?","validation diagnostics with configuration paths",[],"complete","repository"),description:"Validate .codebaseiq.json, structured suppressions, architecture, and coupling groups",options:C(),claims:Ra("repository-source",["live-workspace"]),renderShape:"custom",docs:R("Maintenance",["codebaseiq config-validate"]),handler:jl},{id:"suppress",command:"suppress <id>",agent:le("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete",void 0,K("mutation")),description:"Record an accepted finding under .codebaseiq/suppressions with a required reason",options:C([d("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),d("--reason-code <code>","Required adjudication code"),d("--evidence <kind:referent>","Required counterevidence; repeat for more evidence",F,[]),d("--check <check>","Optional detector name to narrow the suppression"),d("--file <path>","Optional file path to narrow the suppression"),d("--expires-at <iso>","Optional ISO date after which the suppression expires"),d("--replace <revision>","Replace a prior decision with this exact SHA-256 revision")]),renderShape:"custom",docs:R("Maintenance"),handler:Il},{id:"doctor",command:"doctor",agent:k("Why is codebaseiq unhealthy or unavailable in this project?","configuration, freshness, dependency, and capability diagnostics",[],"complete","repository",K("environment-observation")),description:"Diagnose configuration, index freshness, dependencies, and project capabilities",options:C(),renderShape:"custom",docs:R("Maintenance"),handler:Nl},{id:"setup",command:"setup",agent:le("Can codebaseiq be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository",K("composite")),description:"Install skills, write agent guidance, refresh the index, and report repository health",options:C([d("--guided","Require and open the interactive terminal checklist"),d("--yes","Accept recommended setup defaults without prompting"),d("--no-skills","Skip user-level agent skill installation"),d("--no-parsers","Skip Tree-sitter AST parser installation and repair"),d("--install-missing","Install missing global tools at reviewed immutable versions"),d("--no-health","Skip the optional full health report and dossier"),d("--dossier-dir <path>","Directory for generated setup health dossier files"),d("--builder-mode <mode>","Symbol builder provider mode: agent, embeddings, or auto"),d("--embeddings-endpoint <name=url>","Add an OpenAI-compatible embeddings endpoint (repeatable; needs --embeddings-model)",F,[]),d("--embeddings-model <model>","Model the --embeddings-endpoint servers should be asked for"),d("--agent-command <name>","Configure a built-in agent probe command: claude or codex"),d("--builder-scope <scope>","Where builder settings go: local (.codebaseiq.local.json, default) or project (.codebaseiq.json)"),d("--sentinel","Enable the trailing sentinel for agent sessions (also enables automatic indexing)"),d("--no-sentinel","Disable the trailing sentinel for agent sessions"),d("--sentinel-live [families]","Deliver sentinel findings to the agent, not only record them (implies --sentinel); name families (reuse-match,unwired) to promote only those")]),renderShape:"custom",docs:R("Maintenance",["codebaseiq setup","codebaseiq setup --install-missing","codebaseiq setup --json"]),handler:Ml},{id:"setup-agent",command:"setup-agent",agent:le("Can concise project guidance for codebaseiq be written?","written, unchanged, and skipped agent instruction files",[],"complete","repository",K("mutation")),description:"Write concise codebaseiq mapping and cleanup guidance to AGENTS.md and CLAUDE.md",renderShape:"custom",docs:R("Maintenance",["codebaseiq setup-agent"]),handler:Ol},{id:"uninstall",command:"uninstall",agent:le("Which codebaseiq-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository",K("mutation",[{when:{kind:"option",name:"dryRun",equals:!0},role:"repository-preview"}])),description:"Remove selected codebaseiq-owned skills or project guidance",options:C([d("--global","Remove codebaseiq-owned skill symlinks from user-level agent skill roots"),d("--project","Remove managed AGENTS.md and CLAUDE.md blocks"),d("--dry-run","List what would be removed without changing files"),d("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:R("Maintenance",["codebaseiq uninstall --dry-run","codebaseiq uninstall --project"]),handler:ql},{id:"watch",command:"watch",agent:le("What is the watcher doing, or can its background service be started or stopped?","watcher state, generation, activity, and errors",[],"complete","repository",K("composite",[{when:{kind:"option",name:"status",equals:!0},role:"environment-observation"}])),description:"Watch in the foreground or manage the project refresh service",options:C([d("--daemon","Make sure that the background service is running"),d("--status","Show the watcher state"),d("--stop","Stop the watcher for this project"),d("--debounce <ms>","Milliseconds after the last change",Te),d("--cooldown <ms>","Minimum milliseconds between indexes",Te),d("--git-poll <ms>","Milliseconds between Git state checks",Te),d("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",Te)]),renderShape:"custom",docs:R("Maintenance"),handler:Fl},{id:"status",command:"status",agent:k("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, and watcher state",[],"complete","repository",K("environment-observation")),description:"Show index status for this project",options:C([{...d("--capabilities","Compatibility: include a concise capability-readiness summary"),hidden:!0}]),renderShape:"custom",docs:R("Maintenance"),handler:_l},xp];export{IE as commandDescriptors};
|
|
337
|
-
//# sourceMappingURL=command-descriptors-
|
|
334
|
+
[${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let o of n.findingIds.slice(0,pp)){let r=t.get(o);r&&fp(r)}let i=n.count-pp;i>0&&console.log(` ... and ${i} more in this group (use --full to show all)`)}}function l$(e){let t=`${e.checker.checker} ${e.checker.status==="passed"?"PASS":e.checker.status.toUpperCase()}`,n=e.conformance.waivers.filter(s=>s.kind==="write").length,i=e.conformance.waivers.filter(s=>s.kind==="read").length,o=e.conformance.waivers.filter(s=>s.kind==="referent").length,r=e.conformance.findings.filter(s=>s.category==="missing-call").length;return[`checker: ${t}`,`model parsed by: ${e.conformance.modelParse}`,`writes: ${e.conformance.staticWrites.length} verified, ${n} waived`,`reads: ${e.conformance.staticReads.length} verified, ${i} waived`,`calls: ${r===0?"checked":`${r} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...o>0?[`referents: ${o} waived`]:[]].join(" | ")}function d$(e){let t=[],n=e.conformance.waivers.filter(o=>o.kind==="write").length,i=e.conformance.waivers.filter(o=>o.kind==="read").length;return n>0&&e.conformance.staticWrites.length===0&&t.push("NOTHING PROVEN ABOUT WRITES: every write fact found in this run was waived or unobserved."),i>0&&e.conformance.staticReads.length===0&&t.push("NOTHING PROVEN ABOUT READS: every read fact found in this run was waived or unobserved."),t}function fp(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${V(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
|
|
335
|
+
[${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var bp=["stats","files","session","inspect","search","anchors","methods","refs","trace","evidence","evidence-source","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","bottlenecks","isolated","by-kind","kind-counts","dependency-depth","deep-chains","hierarchy","entrypoints","entry-map","system-map","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","co-change","recent-duplicates","doc-drift","unused-params","incomplete-migration","tla","context","reuse","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","reference-neighborhood","dataflow","value-flow","dependence-slice","reference-reachability","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],u$=[Kd,yu,tu,qn,ou,$u,Ql,hp,nu],yp=u$.flat(),p$=new Map(yp.map(e=>[e.id,e]));for(let e of yp)if(!bp.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var vp=bp.map(e=>m$(e));function m$(e){let t=p$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}async function g$(e){let t=re(e),n=$(t,"focus"),i=$(t,"scope"),o=$(t,"file"),r=K(t,"port"),{runCodeViewer:s}=await import("./code-viewer-KIXEYQNJ.js");await s({...n!==void 0?{focus:n}:{},...i!==void 0?{scope:i}:{},...o!==void 0?{file:o}:{},...r!==void 0?{port:r}:{},open:t.open!==!1})}var Sp={id:"view",command:"view",agent:le("Can a person see this folder, file, or symbol on a browsable map of the repository?","the local viewer address, with a deep link when a target is named",[],"complete","repository",z("composite")),description:"Open a local browser map of folders, files, and one symbol at a time",helpAfter:`Serves 127.0.0.1 only and runs until interrupted. With a viewer already running for this project,
|
|
336
|
+
--focus, --scope, or --file points that viewer at the target and returns at once, so an agent can show a person a symbol.`,options:[d("--focus <selector>","Open the focus view of one symbol"),d("--scope <dir>","Open the map at one folder"),d("--file <path>","Open one file"),d("--port <n>","Listen on this port instead of a free one",Te),d("--no-open","Print the address without opening a browser")],renderShape:"custom",docs:R("Graph",["codebaseiq view","codebaseiq view --focus handleRequest","codebaseiq view --scope src/runtime"]),handler:g$};var TE=[ra,va,{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:le("Did indexed source changes preserve the repository architecture policy?","architecture policy decision and enforced finding identities",[],"complete","diff",z("repository-observation")),description:"Internal architecture-only Stop hook",renderShape:"custom",handler:bl},{id:"reindex",command:"reindex",agent:le("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository",z("composite")),description:"Index the codebase and convert to SQLite",options:C([d("-l, --language <lang>","Index only this language (can be repeated)",q,[]),d("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),d("--force","Rebuild even if source inputs are unchanged"),d("--allow-partial","Write an incomplete index when one or more detected languages fail"),d("--trust-project-tools","Permit reviewed indexers from this repository for this run"),d("--install-missing","Install missing global tools at reviewed immutable versions for this run"),d("--indexer-concurrency <n>","Number of language indexers to run at once",ne)]),renderShape:"custom",docs:R("Indexing",["codebaseiq reindex"]),handler:yl},{id:"augment-sources",command:"augment-sources",agent:le("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository",z("composite")),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:R("Indexing"),handler:vl},{id:"augment-vue",command:"augment-vue",agent:le("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository",z("composite")),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[d("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:R("Indexing"),handler:Sl},...vp,{id:"__query-lane-ping",command:"__query-lane-ping",description:"Internal query lane transport probe",hidden:!0,renderShape:"custom",handler:Vl},{id:jt,command:jt,description:"Internal diff-impact batch worker",hidden:!0,options:[d("--json","Emit the private worker envelope without transport pagination"),d("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:$l},{id:"diff-impact",command:"diff-impact",agent:k("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:C([d("--base <ref>","Git ref to diff against (default: HEAD)")]),claims:qe(["index-generation","live-workspace"],[Q("changed-files","changedFiles[]","repository-source"),Q("changed-symbols","changedSymbols[]","compiler-graph"),Q("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:R("Impact"),handler:wl},{id:At,command:At,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[d("--json","Emit the private worker envelope without transport pagination"),d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:xl},{id:"health",command:"health",agent:le("Where has this repository accumulated drift, duplication, complexity, or cleanup pressure?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository",z("repository-observation",[{when:{kind:"option",name:"writeBaseline",equals:!0},role:"composite"}])),description:"Composite repository health report with React, Vue, and general cleanup findings",options:C([d("-s, --scope <path>","Limit to files matching path"),d("--full","Run unbounded candidate analyses on large indexes"),d("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),d("--write-baseline","Snapshot current finding identities to the baseline file")]),claims:qe(["index-generation","live-workspace","process"],[wa("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),Q("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:R("Health",["codebaseiq health --json","codebaseiq health --baseline"]),handler:Rl},{id:"install-skills",command:"install-skills",agent:le("Which codebaseiq skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",z("mutation")),description:`Install skills (${En.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:R("Maintenance"),handler:Cl},{id:"check-deps",command:"check-deps",agent:k("Which codebaseiq and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository",z("environment-observation")),description:"Check whether codebaseiq and the detected language indexers are runnable",renderShape:"custom",docs:R("Maintenance"),handler:kl},{id:"capabilities",command:"capabilities",agent:k("Which repository-mapping and analysis capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository",z("environment-observation")),description:"Report which mapping and analysis capabilities are available in this project",options:C([d("--matrix","Add exhaustive provider and language support details")]),renderShape:"custom",docs:R("Maintenance"),handler:El},{id:"init",command:"init",agent:le("Can a starter codebaseiq configuration be created for this project?","configuration path and creation outcome",[],"complete","repository",z("mutation")),description:"Create a .codebaseiq.json configuration file for this project",renderShape:"custom",docs:R("Maintenance"),handler:Tl},{id:"config-validate",command:"config-validate",agent:k("Is this project configuration valid and internally consistent?","validation diagnostics with configuration paths",[],"complete","repository"),description:"Validate .codebaseiq.json, structured suppressions, architecture, and coupling groups",options:C(),claims:$a("repository-source",["live-workspace"]),renderShape:"custom",docs:R("Maintenance",["codebaseiq config-validate"]),handler:Ll},{id:"suppress",command:"suppress <id>",agent:le("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete",void 0,z("mutation")),description:"Record an accepted finding under .codebaseiq/suppressions with a required reason",options:C([d("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),d("--reason-code <code>","Required adjudication code"),d("--evidence <kind:referent>","Required counterevidence; repeat for more evidence",q,[]),d("--check <check>","Optional detector name to narrow the suppression"),d("--file <path>","Optional file path to narrow the suppression"),d("--expires-at <iso>","Optional ISO date after which the suppression expires"),d("--replace <revision>","Replace a prior decision with this exact SHA-256 revision")]),renderShape:"custom",docs:R("Maintenance"),handler:Pl},{id:"doctor",command:"doctor",agent:k("Why is codebaseiq unhealthy or unavailable in this project?","configuration, freshness, dependency, and capability diagnostics",[],"complete","repository",z("environment-observation")),description:"Diagnose configuration, index freshness, dependencies, and project capabilities",options:C(),renderShape:"custom",docs:R("Maintenance"),handler:Al},{id:"setup",command:"setup",agent:le("Can codebaseiq be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository",z("composite")),description:"Install skills, write agent guidance, refresh the index, and report repository health",options:C([d("--guided","Require and open the interactive terminal checklist"),d("--yes","Accept recommended setup defaults without prompting"),d("--no-skills","Skip user-level agent skill installation"),d("--no-parsers","Skip Tree-sitter AST parser installation and repair"),d("--install-missing","Install missing global tools at reviewed immutable versions"),d("--no-health","Skip the optional full health report and dossier"),d("--dossier-dir <path>","Directory for generated setup health dossier files"),d("--builder-mode <mode>","Symbol builder provider mode: agent, embeddings, or auto"),d("--embeddings-endpoint <name=url>","Add an OpenAI-compatible embeddings endpoint (repeatable; needs --embeddings-model)",q,[]),d("--embeddings-model <model>","Model the --embeddings-endpoint servers should be asked for"),d("--agent-command <name>","Configure a built-in agent probe command: claude or codex"),d("--builder-scope <scope>","Where builder settings go: local (.codebaseiq.local.json, default) or project (.codebaseiq.json)"),d("--sentinel","Enable the trailing sentinel for agent sessions (also enables automatic indexing)"),d("--no-sentinel","Disable the trailing sentinel for agent sessions"),d("--sentinel-live [families]","Deliver sentinel findings to the agent, not only record them (implies --sentinel); name families (reuse-match,unwired) to promote only those")]),renderShape:"custom",docs:R("Maintenance",["codebaseiq setup","codebaseiq setup --install-missing","codebaseiq setup --json"]),handler:Nl},{id:"setup-agent",command:"setup-agent",agent:le("Can concise project guidance for codebaseiq be written?","written, unchanged, and skipped agent instruction files",[],"complete","repository",z("mutation")),description:"Write concise codebaseiq mapping and cleanup guidance to AGENTS.md and CLAUDE.md",renderShape:"custom",docs:R("Maintenance",["codebaseiq setup-agent"]),handler:Il},{id:"uninstall",command:"uninstall",agent:le("Which codebaseiq-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository",z("mutation",[{when:{kind:"option",name:"dryRun",equals:!0},role:"repository-preview"}])),description:"Remove selected codebaseiq-owned skills or project guidance",options:C([d("--global","Remove codebaseiq-owned skill symlinks from user-level agent skill roots"),d("--project","Remove managed AGENTS.md and CLAUDE.md blocks"),d("--dry-run","List what would be removed without changing files"),d("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:R("Maintenance",["codebaseiq uninstall --dry-run","codebaseiq uninstall --project"]),handler:Dl},{id:"watch",command:"watch",agent:le("What is the watcher doing, or can its background service be started or stopped?","watcher state, generation, activity, and errors",[],"complete","repository",z("composite",[{when:{kind:"option",name:"status",equals:!0},role:"environment-observation"}])),description:"Watch in the foreground or manage the project refresh service",options:C([d("--daemon","Make sure that the background service is running"),d("--status","Show the watcher state"),d("--stop","Stop the watcher for this project"),d("--debounce <ms>","Milliseconds after the last change",Te),d("--cooldown <ms>","Minimum milliseconds between indexes",Te),d("--git-poll <ms>","Milliseconds between Git state checks",Te),d("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",Te)]),renderShape:"custom",docs:R("Maintenance"),handler:Ol},{id:"status",command:"status",agent:k("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, and watcher state",[],"complete","repository",z("environment-observation")),description:"Show index status for this project",options:C([{...d("--capabilities","Compatibility: include a concise capability-readiness summary"),hidden:!0}]),renderShape:"custom",docs:R("Maintenance"),handler:Fl},Sp];export{TE as commandDescriptors};
|
|
337
|
+
//# sourceMappingURL=command-descriptors-YCLATF5I.js.map
|