codebaseiq 0.1.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 +481 -0
- package/LICENSE +202 -0
- package/README.md +349 -0
- package/dist/augment-vue-worker.js +2 -0
- package/dist/call-graph-evidence-gNsxjCW8.d.ts +16 -0
- package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
- package/dist/chunk-2Q2LW5JW.js +14 -0
- package/dist/chunk-2X7V4HS4.js +88 -0
- package/dist/chunk-34WBMAYK.js +2 -0
- package/dist/chunk-35NLDRZC.js +2 -0
- package/dist/chunk-362QOSFD.js +3 -0
- package/dist/chunk-3IER7Q6H.js +12 -0
- package/dist/chunk-3JSXXYTZ.js +345 -0
- package/dist/chunk-3LCDIREB.js +4 -0
- package/dist/chunk-476NR5B7.js +2 -0
- package/dist/chunk-4FC325IF.js +30 -0
- package/dist/chunk-4WKDMDEW.js +9 -0
- package/dist/chunk-4XTAUQFD.js +2 -0
- package/dist/chunk-5PUWMSDU.js +26 -0
- package/dist/chunk-5VKBFZZU.js +3 -0
- package/dist/chunk-6BQ3DSPK.js +2 -0
- package/dist/chunk-6CS3UQTN.js +3 -0
- package/dist/chunk-6MUIJMVL.js +6 -0
- package/dist/chunk-6NW7MU72.js +40 -0
- package/dist/chunk-6OAHRI2D.js +6 -0
- package/dist/chunk-6YTSKJJ3.js +2 -0
- package/dist/chunk-7FND7D7N.js +2 -0
- package/dist/chunk-7MGU3HPH.js +2 -0
- package/dist/chunk-7NVGT435.js +2 -0
- package/dist/chunk-7XAN6GKB.js +2 -0
- package/dist/chunk-AAQQPKCU.js +2 -0
- package/dist/chunk-ADTBPVUZ.js +21 -0
- package/dist/chunk-AKB7V7TV.js +2 -0
- package/dist/chunk-ANFVSJWQ.js +11 -0
- package/dist/chunk-B2OB55RR.js +3 -0
- package/dist/chunk-B3UYV66Z.js +4 -0
- package/dist/chunk-B75HZHUP.js +2 -0
- package/dist/chunk-BFFZDZQV.js +2 -0
- package/dist/chunk-BGBBVSH4.js +2 -0
- package/dist/chunk-BH5F2Q4O.js +2 -0
- package/dist/chunk-BJ6SQAEN.js +2 -0
- package/dist/chunk-BMYOV5GP.js +77 -0
- package/dist/chunk-BVAJLC5A.js +7 -0
- package/dist/chunk-C6SBF2WH.js +4 -0
- package/dist/chunk-C74PPYLA.js +3 -0
- package/dist/chunk-C7QOQX32.js +8 -0
- package/dist/chunk-CAUCPUOF.js +7 -0
- package/dist/chunk-CO5R3UNA.js +2 -0
- package/dist/chunk-CQP3THUZ.js +7 -0
- package/dist/chunk-CVYSU6BX.js +16 -0
- package/dist/chunk-CWONGW6P.js +3 -0
- package/dist/chunk-DDZ7VHWV.js +20 -0
- package/dist/chunk-DGXRDLV5.js +2 -0
- package/dist/chunk-DO6WQD2T.js +3 -0
- package/dist/chunk-DQMDCD24.js +2 -0
- package/dist/chunk-DR2LURYU.js +3 -0
- package/dist/chunk-DRENNWRG.js +2 -0
- package/dist/chunk-ECQBG7PW.js +564 -0
- package/dist/chunk-EF2R3WNQ.js +2 -0
- package/dist/chunk-ELNRLMC5.js +29 -0
- package/dist/chunk-EMNIHCRB.js +18 -0
- package/dist/chunk-ENCCHKM6.js +5 -0
- package/dist/chunk-EZNMUY67.js +5 -0
- package/dist/chunk-FAJQ7LWY.js +3 -0
- package/dist/chunk-FDGD5AB5.js +2 -0
- package/dist/chunk-FETNQCFO.js +117 -0
- package/dist/chunk-FM5BPL4V.js +60 -0
- package/dist/chunk-FQKZWM4L.js +49 -0
- package/dist/chunk-FW53T7EB.js +2 -0
- package/dist/chunk-G6XFR4ZL.js +4 -0
- package/dist/chunk-GCHRX4YW.js +4 -0
- package/dist/chunk-GTIYTDRE.js +562 -0
- package/dist/chunk-GTXSJDCO.js +2 -0
- package/dist/chunk-GW6Z3WGY.js +2 -0
- package/dist/chunk-H3LGFZVK.js +2 -0
- package/dist/chunk-HKQUXIFO.js +2 -0
- package/dist/chunk-HOA5YGOH.js +3 -0
- package/dist/chunk-HPJRBHVT.js +3 -0
- package/dist/chunk-HRWGYWRJ.js +49 -0
- package/dist/chunk-I2T2LLK2.js +4 -0
- package/dist/chunk-ICFDQHAM.js +3 -0
- package/dist/chunk-ID63777H.js +4 -0
- package/dist/chunk-IJ4HMYBE.js +3 -0
- package/dist/chunk-ILMHV3KM.js +2 -0
- package/dist/chunk-IOP6FWIM.js +2 -0
- package/dist/chunk-IRQOAM5G.js +2 -0
- package/dist/chunk-J77SU6VA.js +38 -0
- package/dist/chunk-JE3WZ6II.js +2 -0
- package/dist/chunk-JEJLSICM.js +4 -0
- package/dist/chunk-JOIRNPPY.js +2 -0
- package/dist/chunk-JSOYNVWH.js +3 -0
- package/dist/chunk-KMITESMT.js +2 -0
- package/dist/chunk-KUW32IRO.js +2 -0
- package/dist/chunk-KWVHSKHK.js +31 -0
- package/dist/chunk-L4NRUAGJ.js +18 -0
- package/dist/chunk-L57ZKWVG.js +6 -0
- package/dist/chunk-LTA3BRZX.js +2 -0
- package/dist/chunk-LU3BMVH2.js +10 -0
- package/dist/chunk-LZYFLFEH.js +2 -0
- package/dist/chunk-MOVBWNIP.js +16 -0
- package/dist/chunk-MVB3DAEY.js +3 -0
- package/dist/chunk-N3IQCBCF.js +29 -0
- package/dist/chunk-NAUD7LCA.js +2 -0
- package/dist/chunk-NCZUNH3E.js +109 -0
- package/dist/chunk-NE6IU5ZD.js +5 -0
- package/dist/chunk-NEDP5RFQ.js +60 -0
- package/dist/chunk-NMTSZXCL.js +2 -0
- package/dist/chunk-NNJ2KZZG.js +4 -0
- package/dist/chunk-NNO6A2PO.js +2 -0
- package/dist/chunk-NNOKTMZT.js +20 -0
- package/dist/chunk-O6QTXQPJ.js +13 -0
- package/dist/chunk-OANDYLJQ.js +2 -0
- package/dist/chunk-OFBE4NGP.js +2 -0
- package/dist/chunk-OGTFJ3XD.js +2 -0
- package/dist/chunk-OL6KJP3N.js +16 -0
- package/dist/chunk-OLF4MA5W.js +8 -0
- package/dist/chunk-OTOKVOJ3.js +2 -0
- package/dist/chunk-OVTS4DKB.js +2 -0
- package/dist/chunk-OZYRSMSH.js +3 -0
- package/dist/chunk-P5XHIJHI.js +2 -0
- package/dist/chunk-PBI2LFKH.js +2 -0
- package/dist/chunk-PIOMTC27.js +2 -0
- package/dist/chunk-PTAWHLVJ.js +6 -0
- package/dist/chunk-PX4RYAAK.js +2 -0
- package/dist/chunk-PYAB5SM6.js +7 -0
- package/dist/chunk-Q5ELPRKQ.js +2 -0
- package/dist/chunk-Q65CQ4XL.js +2 -0
- package/dist/chunk-Q72QSKXC.js +308 -0
- package/dist/chunk-QCN62RTF.js +3 -0
- package/dist/chunk-QDCCHMVZ.js +2 -0
- package/dist/chunk-QHRNXP3C.js +3 -0
- package/dist/chunk-QKPLA6IC.js +2 -0
- package/dist/chunk-QOKYJ33H.js +2 -0
- package/dist/chunk-QW7EP6WI.js +21 -0
- package/dist/chunk-R2NOK63J.js +4 -0
- package/dist/chunk-RBAS5ZHI.js +2 -0
- package/dist/chunk-RDBI2RXU.js +9 -0
- package/dist/chunk-RKEJ6VTF.js +73 -0
- package/dist/chunk-RR7SX44N.js +35 -0
- package/dist/chunk-RU65DDUP.js +215 -0
- package/dist/chunk-SELM5MER.js +2 -0
- package/dist/chunk-SGX43S2L.js +2 -0
- package/dist/chunk-SMRBZ6EC.js +2 -0
- package/dist/chunk-SNNWPCN7.js +4 -0
- package/dist/chunk-ST7V3SKN.js +2 -0
- package/dist/chunk-SWHMHUKF.js +2 -0
- package/dist/chunk-SYDJMPES.js +2 -0
- package/dist/chunk-SZD2KF7Q.js +2 -0
- package/dist/chunk-T3DGWPXM.js +3 -0
- package/dist/chunk-TFZB6XTM.js +239 -0
- package/dist/chunk-TIIC3ZE7.js +2 -0
- package/dist/chunk-TRRC4ZJ7.js +2 -0
- package/dist/chunk-TXXOEMZJ.js +2 -0
- package/dist/chunk-UBGWN7I4.js +2 -0
- package/dist/chunk-UCD3H3UZ.js +5 -0
- package/dist/chunk-UDS562V4.js +5 -0
- package/dist/chunk-UNBY47BC.js +3 -0
- package/dist/chunk-UP3BUZR5.js +74 -0
- package/dist/chunk-UXM43C7T.js +3 -0
- package/dist/chunk-UZGZB3VB.js +3 -0
- package/dist/chunk-VE5AVNMP.js +2 -0
- package/dist/chunk-VEXUL62T.js +2 -0
- package/dist/chunk-VFY6Y2H6.js +61 -0
- package/dist/chunk-VUIYB2V3.js +2 -0
- package/dist/chunk-VXYS3FZD.js +23 -0
- package/dist/chunk-WE5RZHZ7.js +5 -0
- package/dist/chunk-WMPRTGH2.js +2 -0
- package/dist/chunk-WOQBZPIF.js +2 -0
- package/dist/chunk-XLQ3GLWZ.js +2 -0
- package/dist/chunk-XME3HPXZ.js +2 -0
- package/dist/chunk-XMQ23E27.js +2 -0
- package/dist/chunk-XWUOUWYI.js +2 -0
- package/dist/chunk-XZEE23VG.js +5 -0
- package/dist/chunk-Y6KHROC3.js +7 -0
- package/dist/chunk-YESXMKX3.js +3 -0
- package/dist/chunk-YMGZZEW4.js +2 -0
- package/dist/chunk-YSNONTJ2.js +2 -0
- package/dist/chunk-YUKYB54I.js +1 -0
- package/dist/chunk-YVCIMIOC.js +12 -0
- package/dist/chunk-Z54RD7VL.js +3 -0
- package/dist/chunk-ZKX2FRS6.js +15 -0
- package/dist/chunk-ZMI2JSX2.js +2 -0
- package/dist/chunk-ZV3JV5G5.js +8 -0
- package/dist/chunk-ZZ3MWF33.js +4 -0
- package/dist/chunk-ZZXSWSN6.js +2 -0
- package/dist/cli-context-3SNLDYBM.js +3 -0
- package/dist/cli-context-T3B7W6GG.js +2 -0
- package/dist/cli-program-YNOXO72B.js +7 -0
- package/dist/cli.js +3 -0
- package/dist/code-DlqpBDd0.d.ts +121 -0
- package/dist/command-descriptors-6AOUKWW7.js +346 -0
- package/dist/command-descriptors-ZFKJSRUP.js +344 -0
- package/dist/command-panels-SZONPMLJ.js +3 -0
- package/dist/config-types-BNoC96J3.d.ts +560 -0
- package/dist/db-D7sauVFH.d.ts +95 -0
- package/dist/direct-navigation-DP4LVMRX.js +3 -0
- package/dist/direct-navigation-FLUS3BT6.js +2 -0
- package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
- package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
- package/dist/file-kind-BKCVMNUf.d.ts +10 -0
- package/dist/frontend-behavior-evidence-EfM4_9bc.d.ts +4 -0
- package/dist/git-history-ChNHbfZQ.d.ts +13 -0
- package/dist/graph-evidence-BIFqyisO.d.ts +131 -0
- package/dist/health-DJaZXg8I.d.ts +340 -0
- package/dist/index.d.ts +183 -0
- package/dist/index.js +2 -0
- package/dist/invocation-command-descriptors-QT2JMY5J.js +3 -0
- package/dist/invocation-command-descriptors-YN4QJEAX.js +2 -0
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
- package/dist/output-continuation-command-2V2SL4TD.js +2 -0
- package/dist/output-continuation-command-65J5IP3O.js +3 -0
- package/dist/postinstall.js +3 -0
- package/dist/project-reindex-5JOKXAXT.js +2 -0
- package/dist/project-reindex-UQBIKO4M.js +3 -0
- package/dist/queries/affected.d.ts +40 -0
- package/dist/queries/affected.js +2 -0
- package/dist/queries/anchors.d.ts +123 -0
- package/dist/queries/anchors.js +2 -0
- package/dist/queries/architecture.d.ts +166 -0
- package/dist/queries/architecture.js +2 -0
- package/dist/queries/bottlenecks.d.ts +68 -0
- package/dist/queries/bottlenecks.js +2 -0
- package/dist/queries/by-kind.d.ts +27 -0
- package/dist/queries/by-kind.js +2 -0
- package/dist/queries/call-graph.d.ts +52 -0
- package/dist/queries/call-graph.js +2 -0
- package/dist/queries/change-surface.d.ts +55 -0
- package/dist/queries/change-surface.js +2 -0
- package/dist/queries/cleanup-plan.d.ts +66 -0
- package/dist/queries/cleanup-plan.js +2 -0
- package/dist/queries/co-change.d.ts +90 -0
- package/dist/queries/co-change.js +2 -0
- package/dist/queries/code.d.ts +6 -0
- package/dist/queries/code.js +2 -0
- package/dist/queries/complexity-hotspots.d.ts +61 -0
- package/dist/queries/complexity-hotspots.js +2 -0
- package/dist/queries/complexity.d.ts +74 -0
- package/dist/queries/complexity.js +2 -0
- package/dist/queries/context.d.ts +146 -0
- package/dist/queries/context.js +2 -0
- package/dist/queries/convergence.d.ts +33 -0
- package/dist/queries/convergence.js +2 -0
- package/dist/queries/coupling.d.ts +32 -0
- package/dist/queries/coupling.js +2 -0
- package/dist/queries/cycles.d.ts +66 -0
- package/dist/queries/cycles.js +2 -0
- package/dist/queries/dataflow.d.ts +77 -0
- package/dist/queries/dataflow.js +2 -0
- package/dist/queries/dead.d.ts +58 -0
- package/dist/queries/dead.js +2 -0
- package/dist/queries/decorative-checkers.d.ts +34 -0
- package/dist/queries/decorative-checkers.js +2 -0
- package/dist/queries/deep-chains.d.ts +5 -0
- package/dist/queries/deep-chains.js +2 -0
- package/dist/queries/dependence-slice.d.ts +46 -0
- package/dist/queries/dependence-slice.js +2 -0
- package/dist/queries/dependency-depth.d.ts +49 -0
- package/dist/queries/dependency-depth.js +2 -0
- package/dist/queries/deps.d.ts +15 -0
- package/dist/queries/deps.js +2 -0
- package/dist/queries/diff-impact.d.ts +165 -0
- package/dist/queries/diff-impact.js +2 -0
- package/dist/queries/doc-drift.d.ts +115 -0
- package/dist/queries/doc-drift.js +2 -0
- package/dist/queries/drift.d.ts +79 -0
- package/dist/queries/drift.js +2 -0
- package/dist/queries/duplicate-bodies.d.ts +55 -0
- package/dist/queries/duplicate-bodies.js +2 -0
- package/dist/queries/entry-map.d.ts +121 -0
- package/dist/queries/entry-map.js +2 -0
- package/dist/queries/evidence.d.ts +70 -0
- package/dist/queries/evidence.js +2 -0
- package/dist/queries/extract-candidates.d.ts +52 -0
- package/dist/queries/extract-candidates.js +2 -0
- package/dist/queries/fan.d.ts +53 -0
- package/dist/queries/fan.js +2 -0
- package/dist/queries/files.d.ts +20 -0
- package/dist/queries/files.js +2 -0
- package/dist/queries/health.d.ts +8 -0
- package/dist/queries/health.js +2 -0
- package/dist/queries/hierarchy.d.ts +21 -0
- package/dist/queries/hierarchy.js +2 -0
- package/dist/queries/hotspots.d.ts +42 -0
- package/dist/queries/hotspots.js +2 -0
- package/dist/queries/imports.d.ts +34 -0
- package/dist/queries/imports.js +2 -0
- package/dist/queries/incomplete-migration.d.ts +90 -0
- package/dist/queries/incomplete-migration.js +2 -0
- package/dist/queries/index.d.ts +180 -0
- package/dist/queries/index.js +2 -0
- package/dist/queries/isolated.d.ts +24 -0
- package/dist/queries/isolated.js +2 -0
- package/dist/queries/locality-candidates.d.ts +51 -0
- package/dist/queries/locality-candidates.js +2 -0
- package/dist/queries/members.d.ts +21 -0
- package/dist/queries/members.js +2 -0
- package/dist/queries/methods.d.ts +43 -0
- package/dist/queries/methods.js +2 -0
- package/dist/queries/not-implemented.d.ts +33 -0
- package/dist/queries/not-implemented.js +2 -0
- package/dist/queries/outline.d.ts +22 -0
- package/dist/queries/outline.js +2 -0
- package/dist/queries/passthrough-candidates.d.ts +41 -0
- package/dist/queries/passthrough-candidates.js +2 -0
- package/dist/queries/plan-context.d.ts +33 -0
- package/dist/queries/plan-context.js +2 -0
- package/dist/queries/react-component-duplicates.d.ts +39 -0
- package/dist/queries/react-component-duplicates.js +2 -0
- package/dist/queries/react-hook-candidates.d.ts +44 -0
- package/dist/queries/react-hook-candidates.js +2 -0
- package/dist/queries/react-large-component-pressure.d.ts +34 -0
- package/dist/queries/react-large-component-pressure.js +2 -0
- package/dist/queries/recent-duplicates.d.ts +79 -0
- package/dist/queries/recent-duplicates.js +2 -0
- package/dist/queries/redundant-reexports.d.ts +37 -0
- package/dist/queries/redundant-reexports.js +2 -0
- package/dist/queries/reference-neighborhood.d.ts +4 -0
- package/dist/queries/reference-neighborhood.js +2 -0
- package/dist/queries/reference-reachability.d.ts +48 -0
- package/dist/queries/reference-reachability.js +2 -0
- package/dist/queries/refs.d.ts +13 -0
- package/dist/queries/refs.js +2 -0
- package/dist/queries/self-audit.d.ts +65 -0
- package/dist/queries/self-audit.js +2 -0
- package/dist/queries/similar-chains.d.ts +48 -0
- package/dist/queries/similar-chains.js +2 -0
- package/dist/queries/similar-files.d.ts +35 -0
- package/dist/queries/similar-files.js +2 -0
- package/dist/queries/similar-signatures.d.ts +46 -0
- package/dist/queries/similar-signatures.js +2 -0
- package/dist/queries/similar.d.ts +187 -0
- package/dist/queries/similar.js +2 -0
- package/dist/queries/slice.d.ts +4 -0
- package/dist/queries/slice.js +2 -0
- package/dist/queries/source-inspection.d.ts +209 -0
- package/dist/queries/source-inspection.js +2 -0
- package/dist/queries/source-search.d.ts +85 -0
- package/dist/queries/source-search.js +2 -0
- package/dist/queries/stale-abstractions.d.ts +72 -0
- package/dist/queries/stale-abstractions.js +2 -0
- package/dist/queries/stats.d.ts +15 -0
- package/dist/queries/stats.js +2 -0
- package/dist/queries/surface.d.ts +22 -0
- package/dist/queries/surface.js +2 -0
- package/dist/queries/symbols.d.ts +14 -0
- package/dist/queries/symbols.js +2 -0
- package/dist/queries/system-map.d.ts +449 -0
- package/dist/queries/system-map.js +2 -0
- package/dist/queries/system.d.ts +21 -0
- package/dist/queries/system.js +2 -0
- package/dist/queries/test-quality.d.ts +56 -0
- package/dist/queries/test-quality.js +2 -0
- package/dist/queries/trace.d.ts +68 -0
- package/dist/queries/trace.js +2 -0
- package/dist/queries/twin-ab.d.ts +66 -0
- package/dist/queries/twin-ab.js +2 -0
- package/dist/queries/twin-drift.d.ts +119 -0
- package/dist/queries/twin-drift.js +2 -0
- package/dist/queries/unused-imports.d.ts +4 -0
- package/dist/queries/unused-imports.js +2 -0
- package/dist/queries/unused-params.d.ts +38 -0
- package/dist/queries/unused-params.js +2 -0
- package/dist/queries/value-flow.d.ts +42 -0
- package/dist/queries/value-flow.js +2 -0
- package/dist/queries/vue-component-duplicates.d.ts +43 -0
- package/dist/queries/vue-component-duplicates.js +2 -0
- package/dist/queries/vue-composable-candidates.d.ts +44 -0
- package/dist/queries/vue-composable-candidates.js +2 -0
- package/dist/queries/vue-large-view-pressure.d.ts +41 -0
- package/dist/queries/vue-large-view-pressure.js +2 -0
- package/dist/queries/wrapper-candidates.d.ts +34 -0
- package/dist/queries/wrapper-candidates.js +2 -0
- package/dist/reindex-worker.js +3 -0
- package/dist/reindex.d.ts +254 -0
- package/dist/reindex.js +298 -0
- package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
- package/dist/runtime.d.ts +555 -0
- package/dist/runtime.js +4 -0
- package/dist/rust-semantic-session-server.js +2 -0
- package/dist/rust-semantic-session-worker.js +2 -0
- package/dist/rust-semantic-worker.js +2 -0
- package/dist/scip-cli-B7N3haxa.d.ts +67 -0
- package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
- package/dist/symbol-types-BIQwfoAx.d.ts +74 -0
- package/dist/typescript-mailbox-worker.js +2 -0
- package/dist/watch-server.js +8 -0
- package/docs/AGENT_GUIDE.md +148 -0
- package/docs/AI_FAILURE_MODES.md +43 -0
- package/docs/API.md +40 -0
- package/docs/API_EVOLUTION.md +77 -0
- package/docs/CLI_JSON_OUTPUT.md +389 -0
- package/docs/COMMAND_REFERENCE.md +294 -0
- package/docs/CONFIGURATION_WRITE_SAFETY.md +131 -0
- package/docs/DETECTOR_GUIDE.md +46 -0
- package/docs/DURABILITY.md +159 -0
- package/docs/INDEX_GENERATIONS.md +167 -0
- package/docs/LOCK_PROTOCOL.md +133 -0
- package/docs/MAILBOX_LIFECYCLE.md +224 -0
- package/docs/REGEX_POLICY.md +36 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +104 -0
- package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
- package/docs/SECURITY_MODEL.md +125 -0
- package/docs/TELEMETRY_RETENTION.md +84 -0
- package/docs/TIME_SEMANTICS.md +77 -0
- package/docs/WATCH_REFRESH_REQUESTS.md +123 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +424 -0
- package/docs/accuracy-audit-checklist.md +304 -0
- package/docs/accuracy-hardening-goal.md +500 -0
- package/docs/analyzer-inventory.md +78 -0
- package/docs/analyzer-validation-protocol.md +84 -0
- package/docs/architecture-coherence-vision.md +254 -0
- package/docs/assets/codebaseiq-logo-dark.svg +21 -0
- package/docs/assets/codebaseiq-logo.svg +24 -0
- package/docs/locality-analyzer-design.md +193 -0
- package/docs/schemas/cli-json-envelope.schema.json +237 -0
- package/docs/schemas/cli-output-page.schema.json +104 -0
- package/docs/schemas/npm-release-state.schema.json +146 -0
- package/docs/schemas/observation-receipt.schema.json +164 -0
- package/docs/schemas/project-config.schema.json +318 -0
- package/docs/schemas/suppression-record.schema.json +79 -0
- package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
- package/package.json +482 -0
- package/scripts/build-codebaseiq-windows.mjs +197 -0
- package/scripts/codebaseiq-windows-provenance.mjs +364 -0
- package/scripts/evidence-product-contract.mjs +197 -0
- package/scripts/verify-codebaseiq-windows.mjs +29 -0
- package/skills/codebaseiq/SKILL.md +75 -0
- package/skills/codebaseiq/agents/openai.yaml +4 -0
- package/skills/codebaseiq-explore/SKILL.md +34 -0
- package/skills/codebaseiq-explore/agents/openai.yaml +4 -0
- package/skills/concrete-plan/SKILL.md +79 -0
- package/skills/concrete-plan/agents/openai.yaml +4 -0
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{b as _e,c as Pe,e as Mt,f as Dt,g as $t,l as Ae,o as Ne}from"./chunk-YVCIMIOC.js";import{a as Te}from"./chunk-NEDP5RFQ.js";import{c as Se,e as $,f as Oe,k as Ie,l as Ee}from"./chunk-ZKX2FRS6.js";import"./chunk-OANDYLJQ.js";import"./chunk-3LCDIREB.js";import{$ as ke,A as be,B as ve,G as Re,I as Ce,Q as xe,T as we,Y as z,ca as P,da as L,i as ye,n as l,p as g,q as x,r as h,t as _}from"./chunk-NNJ2KZZG.js";import{existsSync as fn}from"fs";import{randomUUID as mn}from"crypto";import{isAbsolute as ji,join as et,relative as Vi,resolve as Mi}from"path";var S=1,I=2,Lt="./node_modules/codebaseiq/docs/schemas/project-config.schema.json";function X(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(c){return{kind:"malformed",reason:`invalid JSON: ${c instanceof Error?c.message:String(c)}`}}if(!l(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let i=n===void 0?S:n;if(i!==S&&i!==I)return{kind:"unsupported",schemaVersion:i,direction:i<S?"older":"future"};let r=t.$schema;if(r!==void 0&&(typeof r!="string"||r.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let s=F(t),o=i!==I||typeof t.$schema!="string";return i===S?{kind:"legacy",sourceVersion:S,config:s,needsMigration:o}:{kind:"supported",sourceVersion:I,config:s,needsMigration:o}}function F(e){let t=e,{$schema:n,schemaVersion:i,...r}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Lt,schemaVersion:I,...r}}function je(e){return`${JSON.stringify(F(e),null,2)}
|
|
2
|
+
`}import{createHash as Ft}from"crypto";var m=1,C=2,W=1,N=1,A="sha256",te=1;function Le(e,t,n){if(!h(e)||!qe(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:W,canonicalizationVersion:N,hashAlgorithm:A,projection:{name:e,version:t},digest:Ft(A).update(Wt(e,t,n)).digest("hex")}}function Wt(e,t,n){return`{"canonicalizationVersion":${N},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ne(e){if(!l(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===m)return Yt(e)?{kind:"legacy",schemaVersion:m,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===C)return Ht(e)?{kind:"supported",schemaVersion:C,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<m?"older":"future"}}function G(e){let t=ne(e);return t.kind==="legacy"||t.kind==="supported"}function ie(e,t){return{collaborationDomain:O(y(e,n=>n.facts.collaborationDomain),y(t,n=>n.facts.collaborationDomain)),repositoryLineage:O(y(e,n=>n.facts.repositoryLineage),y(t,n=>n.facts.repositoryLineage)),workspaceInstance:O(y(e,n=>n.facts.workspaceInstance),y(t,n=>n.facts.workspaceInstance)),wholeContent:O(y(e,n=>n.facts.wholeContent),y(t,n=>n.facts.wholeContent)),relevantInputs:Gt(e,t),indexInput:O(y(e,n=>n.facts.index?.inputs),y(t,n=>n.facts.index?.inputs)),indexGeneration:Bt(e,t),observationStability:Ut(e,t)}}function B(e,t,n=ie(e,t)){let i=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],r=[];for(let[o,c]of i)c.state!=="established"&&r.push(`${o}:${c.state}`);for(let[o,c]of[["left",e],["right",t]]){let a=qt(c);a!=="not-applicable"&&a!=="established"&&r.push(`${o}IndexAlignment:${a}`)}let s=i.some(([,o])=>o.state==="disproven")||r.some(o=>o.endsWith(":disproven"));return{policyVersion:te,authority:r.length===0?"completion":s?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:r}}function Fe(e){return e.schemaVersion===m?e.index?.generationIdentity:e.facts.index?.generation.digest}function We(e){return e.schemaVersion===m?void 0:e.facts.workspaceInstance?.digest}function Ge(e){if(e.schemaVersion===m)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function Gt(e,t){let n=Ve(e),i=Ve(t);return[...new Set([...n.keys(),...i.keys()])].sort().map(s=>{let o=n.get(s),c=i.get(s),a=o?.subject??c?.subject??s,d=o?.identity.projection.name??c?.identity.projection.name??s;return{subject:a,projection:d,judgment:O(o?.identity,c?.identity)}})}function Ve(e){return e.schemaVersion!==C?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function Bt(e,t){return e.schemaVersion===m&&t.schemaVersion===m?Jt(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===m||t.schemaVersion===m?v("unknown",["legacy-fact-not-comparable"],De(e),De(t)):O(e.facts.index?.generation,t.facts.index?.generation)}function Jt(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],i=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?Be(n,i):v(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,i)}function O(e,t){let n=e?[{kind:"identity",identity:e}]:[],i=t?[{kind:"identity",identity:t}]:[];return!e||!t?Be(n,i):re(e,t)?v(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,i):v("unknown",["identity-projections-not-comparable"],n,i)}function Ut(e,t){if(e.schemaVersion===m||t.schemaVersion===m)return v("unknown",["legacy-fact-not-comparable"],[],[]);let n=$e(e),i=$e(t),r=Me(e),s=Me(t);return r==="invalidated"||s==="invalidated"?v("disproven",[...r==="invalidated"?["left-observation-invalidated"]:[],...s==="invalidated"?["right-observation-invalidated"]:[]],n,i):r!=="fixed"||s!=="fixed"?v("unknown",[...r==="no-repository-source"?["left-observation-has-no-repository-source"]:r!=="fixed"?["left-observation-not-fixed"]:[],...s==="no-repository-source"?["right-observation-has-no-repository-source"]:s!=="fixed"?["right-observation-not-fixed"]:[]],n,i):v("established",["all-observed-sources-fixed"],n,i)}function Me(e){let t=e.observedSources.filter(i=>i.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(i=>[i.source,i.kind]));return t.some(i=>n.get(i.kind)==="invalidated")?"invalidated":t.every(i=>{let r=n.get(i.kind);return r==="immutable"||r==="fixed-snapshot"})?"fixed":"unknown"}function qt(e){if(e.schemaVersion!==C)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(i=>i.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(i=>re(i.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function y(e,t){return e.schemaVersion===C?t(e):void 0}function De(e){return e.schemaVersion===m&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===C&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function $e(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function Be(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return v("unknown",[n],e,t)}function v(e,t,n,i){return{state:e,reasons:t,facts:{left:n,right:i}}}function re(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Yt(e){if(!l(e))return!1;let t=e.index,n=e.worktree;return Ue(e.observedAt)&&h(e.projectIdentity)&&tn(e.authorityKind)&&(t===void 0||l(t)&&h(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||l(n)&&h(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||h(n.headCommit))&&(n.treeOid===void 0||h(n.treeOid)))&&en(e.authorityKind,t,n)}function Ht(e){if(!l(e))return!1;let t=e.facts,n=e.observedSources,i=e.stabilityProofs;if(!Ue(e.observedAt)||!l(t)||!Array.isArray(n)||n.length===0||!n.every(Qt)||!ee(n,a=>a.kind)||!Array.isArray(i)||!i.every(zt)||!ee(i,a=>a.source)||i.some(a=>!n.some(d=>d.kind===a.source))||!i.every(a=>Zt(a,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(a=>t[a]!==void 0&&!R(t[a])))return!1;let s=t.relevantInputs;if(s!==void 0&&(!Array.isArray(s)||!s.every(Kt)||!ee(s,a=>`${a.subject}\0${a.identity.projection.name}`)))return!1;let o=t.index;if(o!==void 0&&(!l(o)||!R(o.generation)||o.inputs!==void 0&&!R(o.inputs)||o.source!=="immutable"&&o.source!=="legacy"))return!1;let c=e.diagnostics;return(c===void 0||l(c)&&(c.clean===void 0||typeof c.clean=="boolean")&&(c.headCommit===void 0||h(c.headCommit))&&(c.treeOid===void 0||h(c.treeOid)))&&Xt(t,n)}function R(e){return!l(e)||!l(e.projection)?!1:e.schemaVersion===W&&e.canonicalizationVersion===N&&e.hashAlgorithm===A&&h(e.projection.name)&&qe(e.projection.version)&&typeof e.digest=="string"&&/^[a-f0-9]{64}$/u.test(e.digest)}function Kt(e){return l(e)&&h(e.subject)&&R(e.identity)}function Qt(e){return l(e)&&Je(e.kind)&&(e.identity===void 0||R(e.identity))}function zt(e){return l(e)&&Je(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function Xt(e,t){let n=e.index,i=t.find(a=>a.kind==="index-generation");if(i){if(!l(n)||!R(n.generation)||i.identity&&!Z(i.identity,n.generation))return!1}else if(n!==void 0)return!1;let r=e.workspaceInstance,s=t.find(a=>a.kind==="live-workspace");if(s?.identity&&(!R(r)||!Z(s.identity,r)))return!1;let o=e.wholeContent,c=t.find(a=>a.kind==="repository-snapshot");return!(c?.identity&&(!R(o)||!Z(c.identity,o)))}function Zt(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&l(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Z(e,t){return re(e,t)&&e.digest===t.digest}function en(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function tn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function Je(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function Ue(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function qe(e){return Number.isSafeInteger(e)&&e>0}function ee(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ye}from"crypto";import{closeSync as nn,fstatSync as He,openSync as rn,rmSync as on}from"fs";import{dirname as sn}from"path";var an=2e3,cn=10,dn=3,U=class extends Error{constructor(n,i,r){super(`Concurrent edit detected for ${n}; expected revision ${Qe(i)}, but found ${Qe(r)}. The latest file was left untouched.`);this.path=n;this.original=i;this.latest=r;this.name="FileRevisionConflictError"}path;original;latest};function ze(e,t,n={}){let i=ln(e,n.lockTimeoutMs??an,n.monotonicNow??$);try{let r=Math.max(0,Math.floor(n.maxRetries??dn));for(let s=0;;s+=1){let o=J(e),c=t(o,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:o,current:o};n.onBeforeCommit?.({attempt:s,snapshot:o,mutation:c});let a=J(e);if(!pn(o.revision,a.revision)){if(s<r)continue;throw new U(e,o.revision,a.revision)}try{un(e,c,o.revision)}catch(d){if(d.code==="EEXIST"){let p=J(e);if(s<r)continue;throw new U(e,o.revision,p.revision)}throw d}return{changed:!0,attempts:s+1,previous:o,current:J(e)}}}finally{i.release()}}function J(e){for(let t=0;t<4;t+=1){let n;try{n=rn(e,"r");let i=Ke(He(n)),r=Ce(n,{maxBytes:ve,inputKind:"revisioned text file"}),s=Ke(He(n));if(!Xe(i,s))continue;return{path:e,text:r,revision:{exists:!0,hash:Ye("sha256").update(r).digest("hex"),identity:s}}}catch(i){if(i.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ye("sha256").update("").digest("hex")}};throw i}finally{n!==void 0&&nn(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function ln(e,t,n){let i=`${e}.codebaseiq-write.lock`,r=n()+Math.max(0,t);for(;;){let s=Oe(i,{kind:"revisioned-file-mutation",detail:{target:e}});if(s.kind==="acquired")return s.lock;if(n()>=r)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,cn)}}function un(e,t,n){if(t.kind==="delete"){if(!n.exists)return;on(e),xe(sn(e));return}let i=t.mode??n.identity?.mode;n.exists?Ie(e,t.text,{durability:"durable",mode:i}):Ee(e,t.text,{durability:"durable",mode:i})}function pn(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&Xe(e.identity,t.identity))}function Ke(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function Xe(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Qe(e){return e.exists?e.hash.slice(0,12):"<absent>"}var j=".codebaseiq.json",tt=2e3,nt=5e3,oe=nt,se=3*6e4,hn=60*6e4,ae={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},gn={enabled:!1,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,ignore:[],resourceBudget:ae};var Wi=new Set(_);function q(e){let t=et(e,j);if(!fn(t))return{};let n;try{n=Re(t,{maxBytes:be,inputKind:"codebaseiq project config"})}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(`unable to read ${j} at ${t}: ${r}`,{cause:i})}return rt(X(n),t,"read").config}function it(e){return{...gn,...e.watch,idleTimeoutMs:e.watch?.idleTimeoutMs??(e.daemon?.enabled===!0?hn:se),cooldownMs:Math.max(nt,e.watch?.cooldownMs??oe),resourceBudget:{...ae,...e.watch?.resourceBudget}}}function yn(e,t){return bn(e,t).configPath}function bn(e,t){let n=et(e,j),i=mn(),r={collaborationDomainId:i,languages:t,watch:{enabled:!0,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,resourceBudget:{...ae}}},s=ze(n,o=>{if(!o.revision.exists)return{kind:"write",text:Ze(r)};let c=vn(o,r);return c.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:Ze({...c.config,collaborationDomainId:i})}});return{configPath:n,changed:s.changed}}function vn(e,t){if(!e.revision.exists)return{config:F(t),needsMigration:!0};let n=rt(X(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Ze(e){return je(e)}function rt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let r=n==="read"?`invalid ${j} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${r} The file was left untouched.`)}let i=n==="read"?`invalid ${j} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${i} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this codebaseiq reads legacy v${S} and current v${I}). Upgrade codebaseiq before retrying; the file was left untouched.`)}import{statSync as ot}from"fs";import{basename as Rn,isAbsolute as Cn,join as V,relative as Sn}from"path";import{fileURLToPath as On}from"url";import{watch as xn}from"chokidar";import In from"ignore";var pt=5e3,de=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;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=it(t.config),this.outputDb=t.outputDb??V(we(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??(()=>{});let n=t.onError??(i=>console.error(i.message));this.onError=i=>{this.observationEpoch+=1,n(i)},this.clock=t.clock??Tn,ft.set(this,Mn(t.stopTimeoutMs??pt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??gt(),this.subscriptionFactory=t.subscriptionFactory??_n,this.budgetInspector=t.budgetInspector??Ne,mt.set(this,{gitReader:t.gitReader??ke,languages:yt(t.languages??t.config.languages),stagedIndexEntries:null,gitSignalPaths:null,lastGitSignal:null}),this.gitignoreFilter=Te(t.projectRoot),this.extraIgnore=In(),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,Y(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();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Y(this).closures],r=wn(this),s=this.clock.now()+r;return this.stopPromise=this.finishStop(t,i,n,s,r).catch(o=>{throw this.stopInProgress=!1,o}),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=ct(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,r)=>this.isIgnoredWatchPath(i,r?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,r)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(r)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!Vn(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(r=>r!==t),kn(Y(this),t,r=>this.onError(r));try{this.startSourceWatcher(!0)}catch(r){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let r=n?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}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")||Rn(n).startsWith(Ae)||(n===".codebaseiq.json"&&dt(this,this.projectRoot),lt(this,n)&&this.scheduleReindex({kind:"watch-source",detail:n}))}relativeWatchPath(t){let n=Cn(t)?t:V(this.projectRoot,t);return Sn(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=ct(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 o=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:o,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,o-this.wallNow())));return}let n=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&n<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-n;this.dirty=!0;let c=this.wallNow()+o;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())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let s=this.reindexRunner.start(this.reindexRequest(i));this.activeOperation=s,s.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=!1;try{c=this.onReindexComplete(o,i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(c){let d=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(d),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=o instanceof Error?o:new Error(String(o));this.onReindexError(c,i),this.onError(c),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===s&&(this.activeOperation=null)})}async finishStop(t,n,i,r,s){let o=[],c=t.map(async f=>{try{await f.close()}catch(D){o.push(`watch subscription close failed: ${String(D)}`)}});c.push(...n),i&&c.push((async()=>{try{let f=await i.cancel();f.state==="degraded"&&o.push(f.reason)}catch(f){o.push(`reindex cancellation failed: ${f instanceof Error?f.message:String(f)}`)}})());let a=c.length,d=c.map(f=>f.finally(()=>{a-=1})),p=await En(d,r,this.clock),u=Y(this);return o.push(...u.errors),u.errors=[],p?this.stopInProgress=!1:(o.push(`watch shutdown exceeded the ${s}ms deadline with ${a} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),o.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:o.join("; ")}),{state:"degraded",reasons:o}):(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=b(this);t.gitSignalPaths=this.resolveGitSignalPaths(),t.lastGitSignal=this.gitActivitySignal(),t.stagedIndexEntries=ut(this.projectRoot,t.gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.()}resolveGitSignalPaths(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-dir"],t),i=P(this.projectRoot,["rev-parse","--git-common-dir"],t);if(!n)return null;let r=L(this.projectRoot,n),s=i?L(this.projectRoot,i):r,o=this.lastGitState?.indexPath;return[V(r,"HEAD"),V(s,"packed-refs"),V(s,"refs","heads"),...o?[o]:[]]}gitActivitySignal(){let t=b(this).gitSignalPaths;if(!t)return null;let n="";for(let i of t)try{let r=ot(i);n+=`${i}:${r.mtimeMs}:${r.size};`}catch{n+=`${i}:absent;`}return n}pollGitState(){let t=this.gitActivitySignal();if(t!==null){if(t===b(this).lastGitSignal)return;b(this).lastGitSignal=t}let n=this.lastGitState,i=this.readGitState();if(!n||!i||this.stopped){this.lastGitState=i;return}this.lastGitState=i;let r=n.head!==i.head,s=n.indexPath!==i.indexPath||n.indexMtimeMs!==i.indexMtimeMs||n.indexSize!==i.indexSize;if(!r&&!s)return;let o=b(this),c=o.stagedIndexEntries,a=ut(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let d=Dn(this.projectRoot,o.gitReader,n,i,c,a,r,s),p=null;d!==null&&(d.includes(".codebaseiq.json")&&dt(this,this.projectRoot),p=d.filter(u=>lt(this,u)),p.length===0)||(r&&s?this.scheduleReindex({kind:"watch-git-state",detail:ce("HEAD and index changed",p)}):r?this.scheduleReindex({kind:"watch-git-head",detail:ce("HEAD changed",p)}):s&&this.scheduleReindex({kind:"watch-git-index",detail:ce(i.indexPath??"index changed",p)}))}readGitState(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=L(this.projectRoot,n),r={head:P(this.projectRoot,["rev-parse","--verify","HEAD"],t),indexPath:i};try{let s=ot(i);r.indexMtimeMs=s.mtimeMs,r.indexSize=s.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function En(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),r=Math.max(0,t-n.now()),s=null,o=new Promise(a=>{s=n.setTimeout(()=>a(!1),r)}),c=await Promise.race([i,o]);return c&&s&&n.clearTimeout(s),c}var st=new WeakMap,ft=new WeakMap,mt=new WeakMap;function Y(e){let t=st.get(e);if(t)return t;let n={closures:new Set,errors:[]};return st.set(e,n),n}function wn(e){return ft.get(e)??pt}function b(e){let t=mt.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function kn(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(r=>{let s=`watch subscription close failed during polling fallback: ${String(r)}`;e.errors.push(s),n(new Error(s))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function ht(e,t=Se){let{projectRoot:n,config:i,languages:r,pnpmWorkspaces:s,typescriptProjectMode:o,typescriptProjects:c,clojureConfigPath:a,indexerConcurrency:d,trigger:p}=e,u=q(n),f=Object.keys(u).length>0?u:i,D=z(n,f),Q=f.indexer?.typescript,Vt=f.indexer?.clojure,ge=t(process.pid);if(!ge)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:On(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:D.indexPath,SCIP_REINDEX_OUTPUT_DB:D.dbPath,SCIP_REINDEX_LANGUAGES:(f.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(f.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:Q?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:Q?.projectMode??o,projects:Q?.projects??c??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:Vt?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:p.kind,SCIP_REINDEX_TRIGGER_DETAIL:p.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(ge)}}}var Tn={now:$,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_n=(e,t)=>xn(e,t),Pn=15*6e4,An=1e3,Nn=64*1024;function jn(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function at(e,t){let n=e instanceof Error?e.message:String(e),i=t.stderrTail.trim()||t.stdoutTail.trim();return i?`${n}
|
|
3
|
+
${i}`:n}function gt(e={}){let t=e.timeoutMs??Pn,n=e.terminationGraceMs??An,i=e.maxOutputBytes??Nn,r=e.resolveLaunch??ht;return{start(s){let o=r(s),c=new AbortController,a=jn(),d=!1,p=Pe({command:process.execPath,args:[...process.execArgv,o.workerPath],label:"watch reindex worker",env:o.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:c.signal,detached:!0}).then(u=>{if(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(at(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),a));return u.durationMs}).catch(u=>{throw u instanceof _e&&(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(at(u,a),{cause:u})}).finally(()=>{d=!0});return{completion:p,async cancel(){d||c.abort();try{await p}catch{}return{state:"exited",diagnostics:a}},diagnostics:()=>a}}}}function ct(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 Vn(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Mn(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function yt(e){return e&&e.length>0?[...e]:_}function dt(e,t){try{b(e).languages=yt(q(t).languages)}catch{b(e).languages=_}}function lt(e,t){return ye(t,b(e).languages)!=="other"}function Dn(e,t,n,i,r,s,o,c){let a=new Set;if(o){if(!n.head||!i.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(d.kind!=="success")return null;for(let p of $n(d.output))a.add(p)}if(c){if(r===null||s===null)return null;for(let d of Fn(r,s))a.add(d)}return[...a].sort()}function ut(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Ln(n.output):null}function $n(e){return e.split("\0").filter(t=>t.length>0)}function Ln(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let r=t[i],s=t[i+1];if(!r.startsWith(":")||!s)return null;n.set(s,r)}return n}function Fn(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function ce(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 le,mkdirSync as Wn,symlinkSync as Gn,readlinkSync as bt,unlinkSync as vt,readdirSync as Bn}from"fs";import{join as E,dirname as pe,resolve as w,relative as Jn,isAbsolute as Un}from"path";import{homedir as ue,platform as qn}from"os";import{fileURLToPath as Yn}from"url";var Hn=qn()==="win32",Rt=["codebaseiq","codebaseiq-explore","concrete-plan"];function Kn(e={}){let t=e.quiet?()=>{}:console.log,n=Yn(import.meta.url),i=w(pe(n),"..","skills"),r=[E(ue(),".claude","skills"),E(ue(),".codex","skills"),E(ue(),".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let o of r){let c=pe(o);if(!le(c))continue;Wn(o,{recursive:!0});let a=Xn(o);Qn(o,i,a,s,t);for(let d of Rt){let p=E(i,d),u=E(o,d);if(!le(p)){s.skipped.push(`${a}/${d}`);continue}if(le(u)){try{let f=bt(u);if(w(f)===w(p)){s.alreadyLinked.push(`${a}/${d}`),t(` ok: ${d} \u2192 ${a} (already linked)`);continue}}catch{s.skipped.push(`${a}/${d}`),t(` skip: ${d} \u2192 ${a} (exists, not a symlink)`);continue}vt(u)}Gn(p,u,Hn?"junction":"dir"),s.installed.push(`${a}/${d}`),t(` done: ${d} \u2192 ${a}`)}}return s}function Qn(e,t,n,i,r){let s=new Set(Rt);for(let o of Bn(e)){if(s.has(o))continue;let c=E(e,o),a;try{a=w(pe(c),bt(c))}catch{continue}zn(a,t)&&(vt(c),i.pruned.push(`${n}/${o}`),r(` prune: ${o} \u2192 ${n} (removed stale codebaseiq skill link)`))}}function zn(e,t){let n=Jn(w(t),w(e));return n===""||!n.startsWith("..")&&!Un(n)}function Xn(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var Ct=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function Zn(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function ei(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let r=t.options[n.when.name];if(r!==void 0&&r!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function ti(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function H(e){return Ct.includes(e)}function ni(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var fe=1,me=1,K=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],St=["complete","partial","unknown"],Ot=["validated","failed","not-evaluated","not-applicable"],xt=["observe","advise","require-adjudication","block","not-established"],It={policyId:"codebaseiq:unresolved-repository-policy",policyVersion:me,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function ii(e){return{schemaVersion:fe,origin:e.contract.origin,coverage:Et(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:B(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??It,...e.contract.families?{families:e.contract.families}:{}}}function Et(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function ri(e,t){let n=[];return M(n,"origin",t.origins,e.origin),M(n,"coverage",t.coverage,e.coverage.state),M(n,"producer-validation",t.producerValidation,e.producerValidation.status),M(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),M(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(i=>i.satisfied),predicates:n}}function M(e,t,n,i){n&&e.push({predicate:t,satisfied:n.includes(i),required:n,actual:i})}function he(e){return!l(e)||e.schemaVersion!==fe||!k(e.origin,K)||!oi(e.coverage)||!si(e.producerValidation)||!ai(e.stateAuthority)||!ci(e.repositoryPolicy)?!1:e.families===void 0||di(e.families)}function oi(e){return!l(e)||!k(e.state,St)||!x(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!x(e.total)||e.omitted!==void 0&&!x(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&x(e.total)&&x(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function si(e){if(!l(e)||!k(e.status,Ot))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?l(t)&&g(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&g(t.corpus):t===void 0}function ai(e){return l(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(g)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function ci(e){return l(e)&&g(e.policyId)&&e.policyVersion===me&&k(e.permission,xt)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function di(e){return Array.isArray(e)&&e.every(t=>l(t)&&g(t.id)&&g(t.selector)&&li(t.origin))}function li(e){return l(e)?e.kind==="fixed"?k(e.origin,K)&&e.origin!=="mixed":e.kind!=="result-field"||!g(e.field)||!l(e.values)?!1:Object.values(e.values).every(t=>k(t,K)&&t!=="mixed"):!1}function k(e,t){return typeof e=="string"&&t.includes(e)}var Tt="codebaseiq-result",_t=0,T=1,ui=1,Pt=1,At=1;function Nt(e){if(!l(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let o=wt(e);return o?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${o}`}:{kind:"legacy",schemaVersion:_t,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==Tt)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${gi(e.kind)}.`};let i=e.schemaVersion;if(!Number.isSafeInteger(i)||Number(i)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(i!==T)return{kind:"unsupported",schemaVersion:Number(i),direction:Number(i)<T?"older":"future",...kt(e.producer)?{producer:e.producer}:{}};let r=wt(e);if(r)return{kind:"malformed",reason:`CLI JSON envelope v1: ${r}`};if(!kt(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify codebaseiq and its non-empty version."};if(!mi(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};let s=jt(e.command);return s.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!hi(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!H(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:l(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:T,envelope:e}:{kind:"unsupported-result",schemaVersion:T,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:s}}function pi(e){let t=Nt(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported codebaseiq CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${T}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for codebaseiq command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed codebaseiq CLI JSON envelope: ${t.reason}`)}function jt(e){return fi[e]??[ui]}var fi={hotspots:[1,2],bottlenecks:[1,2],"complexity-hotspots":[1,2]};function wt(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?l(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function kt(e){return l(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function mi(e){return Number.isSafeInteger(e)&&Number(e)>0}function hi(e){if(!l(e)||e.schemaVersion!==Pt||e.operationRole!==void 0&&!H(e.operationRole)||!G(e.receipt))return!1;let t=e.analysisManifest;return l(t)&&t.schemaVersion===At&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||he(t.claimQualification))}function gi(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{xt as CLAIM_ACTION_PERMISSIONS,me as CLAIM_ACTION_POLICY_VERSION,St as CLAIM_COVERAGE_STATES,K as CLAIM_ORIGINS,fe as CLAIM_QUALIFICATION_SCHEMA_VERSION,At as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Pt as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,Tt as CLI_JSON_ENVELOPE_KIND,Ct as COMMAND_OPERATION_ROLES,T as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,It as DEFAULT_REPOSITORY_POLICY_ACTION,_t as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,m as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,N as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,A as OBSERVATION_IDENTITY_HASH_ALGORITHM,W as OBSERVATION_IDENTITY_SCHEMA_VERSION,C as OBSERVATION_RECEIPT_SCHEMA_VERSION,te as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,Ot as PRODUCER_VALIDATION_STATUSES,de as Watcher,Zn as commandOperation,ti as commandOperationRoles,ie as compareObservationReceipts,Le as createObservationIdentity,gt as createReindexRunner,Nt as decodeCliJsonEnvelope,ne as decodeObservationReceipt,Et as deriveClaimCoverage,ii as deriveClaimQualification,B as deriveObservationStateAuthority,ri as evaluateClaimQualification,Dt as getScipVersion,yn as initProjectConfig,Kn as installSkills,he as isClaimQualificationV1,H as isCommandOperationRole,G as isObservationReceipt,Mt as isScipInstalled,q as loadProjectConfig,Fe as observationReceiptGenerationIdentity,Ge as observationReceiptStabilityLabel,We as observationReceiptWorkspaceIdentity,ni as operationObservesRepository,$t as printScipInstallInstructions,pi as requireCompatibleCliJsonEnvelope,ei as resolveCommandOperationRole,z as resolveIndexStoragePaths,ht as resolveReindexWorkerLaunch,jt as supportedCliResultSchemaVersions};
|
|
4
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as V}from"./chunk-AAQQPKCU.js";import{e as E,f as A,g as U,h as O,n as C}from"./chunk-NNO6A2PO.js";import"./chunk-P5XHIJHI.js";import"./chunk-KUW32IRO.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import"./chunk-DRENNWRG.js";import{A as N,B as P,C as g,D as k,F as B,j as D,l as h,r as x,s as T,v as _,w as q}from"./chunk-RDBI2RXU.js";import"./chunk-R2NOK63J.js";import{c as L,d as b}from"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";import"./chunk-2Q2LW5JW.js";import n from"process";import{randomUUID as H}from"crypto";import{rmSync as J}from"fs";import{resolve as f}from"path";import{pathToFileURL as W}from"url";var X=10*6e4,F=10,G=250,z=1e3;function Y(e,t,s={}){let M=_(e),d=s.now??(s.nowMs===void 0?Date.now:()=>s.nowMs),S=d(),y=A(e),w=N(M,{ownerId:s.ownerId??re,nowMs:S,limits:s.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let o=null,c,m="handler-error";try{let a=P(i,s.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=U(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);o=r.value,c={id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs};let l=$(o.request,s.monotonicNowMs??b());s.beforeRequest?.(l);let R=t.handle(l),I=d();if(o.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");g(M,i,{ok:!0,protocolVersion:E,id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs,...R},{nowMs:I,limits:s.limits})}catch(a){let u=d(),r=c??(o?{id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);k(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:s.limits})}p+=1}return p}function $(e,t){let s=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:s}}}async function K(e,t){let s=_(e);q(s);let M=f(e,"server.lock"),d=ee(M);if(!d)return;let S=new O(()=>C({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,o=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<z)return;p=I;let v={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:B(s)};l==="durable"?T(f(e,"server.json"),v):x(f(e,"server.json"),v)};try{u(!0);let r=te();for(;!y&&b()-w<r;){let l=Y(e,S,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(o=0,w=b(),i=void 0,u(!0,"visibility")):(o+=1,u()),await se(Q(l,o))}}finally{S.shutdown(),J(f(e,"server.json"),{force:!0}),d.release()}}function Q(e,t=1){if(e>0)return F;let s=Math.max(0,Math.min(5,t-1));return Math.min(G,F*2**s)}var Z=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function ee(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:Z});return t.kind==="acquired"?t.lock:null}function te(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:X}function se(e){return new Promise(t=>setTimeout(t,e))}var oe=n.argv[1]?W(f(n.argv[1])).href:null;if(oe===import.meta.url){V();let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await K(e,t)}var re=`rust-semantic-${n.pid}-${H()}`,j=L(n.pid),ne={pid:n.pid,...j?{processIdentity:j}:{}},ie={isProcessAlive:D,readProcessIdentity:L};export{ee as acquireDurableRustSessionServerLock,Q as durableSessionLoopDelayMs,Y as processDurableRustSessionRequests};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-session-server.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as te,b as ie,c as C,d as N,e as G,f as E,g as B,i as H,j as U,k as K,l as W,m as le,p as ce,q as ue,r as de,s as fe,t as S,v as me,w as pe,x as D}from"./chunk-OLF4MA5W.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import{a as j,j as d,k as M}from"./chunk-R2NOK63J.js";import"./chunk-EF2R3WNQ.js";import{ba as q,ca as ee}from"./chunk-WE5RZHZ7.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,S(e.client,r,c)),o,s.deadlineMs):S(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>D(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>D(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,S(e.client,l,f)),u,o.deadlineMs):S(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>D(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>D(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-session-worker.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m,t as n,u as o,v as p,w as q,x as r}from"./chunk-OLF4MA5W.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,r as sleep,n as waitForOpenedDocuments};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-worker.js.map
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { S as SupportedLanguage } from './config-types-BNoC96J3.js';
|
|
2
|
+
|
|
3
|
+
type WatcherStatus = {
|
|
4
|
+
state: 'idle';
|
|
5
|
+
} | {
|
|
6
|
+
state: 'waiting';
|
|
7
|
+
changedFiles: number;
|
|
8
|
+
reindexAt: number;
|
|
9
|
+
} | {
|
|
10
|
+
state: 'indexing';
|
|
11
|
+
startedAt: number;
|
|
12
|
+
} | {
|
|
13
|
+
state: 'cooldown';
|
|
14
|
+
until: number;
|
|
15
|
+
dirty: boolean;
|
|
16
|
+
} | {
|
|
17
|
+
state: 'budget-paused';
|
|
18
|
+
until: number;
|
|
19
|
+
dirty: boolean;
|
|
20
|
+
reason: string;
|
|
21
|
+
rebuilt: number;
|
|
22
|
+
estimatedWriteBytes: number;
|
|
23
|
+
} | {
|
|
24
|
+
state: 'draining';
|
|
25
|
+
startedAt: number;
|
|
26
|
+
reason: string;
|
|
27
|
+
};
|
|
28
|
+
type RefreshTriggerKind = 'manual-cli' | 'setup' | 'watch-source' | 'watch-startup' | 'watch-demand' | 'watch-git-head' | 'watch-git-index' | 'watch-git-state' | 'unknown';
|
|
29
|
+
interface RefreshTrigger {
|
|
30
|
+
kind: RefreshTriggerKind;
|
|
31
|
+
detail?: string;
|
|
32
|
+
}
|
|
33
|
+
type RefreshResultKind = 'rebuilt' | 'reused' | 'failed';
|
|
34
|
+
interface LastRefreshMetadata {
|
|
35
|
+
trigger: RefreshTrigger;
|
|
36
|
+
result: RefreshResultKind;
|
|
37
|
+
startedAt: string;
|
|
38
|
+
completedAt: string;
|
|
39
|
+
durationMs: number;
|
|
40
|
+
indexedLanguages?: SupportedLanguage[];
|
|
41
|
+
skipped?: {
|
|
42
|
+
language: SupportedLanguage;
|
|
43
|
+
reason: string;
|
|
44
|
+
}[];
|
|
45
|
+
error?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Check if the `scip` CLI binary is available on PATH or packaged with codebaseiq.
|
|
50
|
+
*/
|
|
51
|
+
declare function isScipInstalled(): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Get the scip CLI version if installed.
|
|
54
|
+
*/
|
|
55
|
+
declare function getScipVersion(): string | null;
|
|
56
|
+
/**
|
|
57
|
+
* Print instructions for installing the scip CLI binary.
|
|
58
|
+
*/
|
|
59
|
+
declare function printScipInstallInstructions(): void;
|
|
60
|
+
/**
|
|
61
|
+
* Attempt to auto-install the `scip` CLI binary.
|
|
62
|
+
* Uses an immutable Go module identity, then prints versioned manual instructions.
|
|
63
|
+
* Returns true if installation succeeded.
|
|
64
|
+
*/
|
|
65
|
+
declare function tryInstallScipCli(onStatus: (msg: string) => void): boolean;
|
|
66
|
+
|
|
67
|
+
export { type LastRefreshMetadata as L, type RefreshTrigger as R, type WatcherStatus as W, getScipVersion as g, isScipInstalled as i, printScipInstallInstructions as p, tryInstallScipCli as t };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
interface SourceSnippet {
|
|
2
|
+
relativePath: string;
|
|
3
|
+
startLine: number;
|
|
4
|
+
endLine: number;
|
|
5
|
+
focusLine: number;
|
|
6
|
+
source: string;
|
|
7
|
+
}
|
|
8
|
+
interface SourceUnitSnippet extends SourceSnippet {
|
|
9
|
+
unitType: string | null;
|
|
10
|
+
unitStartLine: number;
|
|
11
|
+
unitEndLine: number;
|
|
12
|
+
omittedLines: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type { SourceSnippet as S, SourceUnitSnippet as a };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A symbol's location in the SCIP index. The minimum data needed to
|
|
3
|
+
* identify a definition: which document it lives in, which lines it
|
|
4
|
+
* spans, and the global symbol id. Used as a lightweight handle when
|
|
5
|
+
* the caller doesn't need the symbol's textual name or path.
|
|
6
|
+
*/
|
|
7
|
+
interface SymbolLocation {
|
|
8
|
+
documentId: number;
|
|
9
|
+
startLine: number;
|
|
10
|
+
startChar?: number;
|
|
11
|
+
endLine: number;
|
|
12
|
+
endChar?: number;
|
|
13
|
+
symbolId: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A SymbolLocation plus the human-readable bits: the SCIP symbol string
|
|
17
|
+
* and the document's relative path. Returned by lookup helpers like
|
|
18
|
+
* `findFirstSymbolMatch` so callers don't have to round-trip through the
|
|
19
|
+
* documents table to get a path or symbol name.
|
|
20
|
+
*/
|
|
21
|
+
interface SymbolMatch extends SymbolLocation {
|
|
22
|
+
symbol: string;
|
|
23
|
+
relativePath: string;
|
|
24
|
+
}
|
|
25
|
+
interface SymbolResolutionCandidate {
|
|
26
|
+
symbol: string;
|
|
27
|
+
shortName: string;
|
|
28
|
+
relativePath: string;
|
|
29
|
+
startLine: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A full definition record: SymbolMatch plus per-symbol metadata
|
|
33
|
+
* (leaf name, parent type, kind, documentation, enclosing symbol).
|
|
34
|
+
* Used by the catalog APIs (`getDefinitionsForFile`, `getAllDefinitions`,
|
|
35
|
+
* `getScopedDefinitions`) so consumers don't have to re-derive any of
|
|
36
|
+
* these per-record.
|
|
37
|
+
*/
|
|
38
|
+
interface IndexedDefinition extends SymbolMatch {
|
|
39
|
+
leaf: string;
|
|
40
|
+
parentTypeName: string | null;
|
|
41
|
+
isFunctionLike: boolean;
|
|
42
|
+
isTypeLike: boolean;
|
|
43
|
+
kind: number | null;
|
|
44
|
+
documentation: string | null;
|
|
45
|
+
enclosingSymbol: string | null;
|
|
46
|
+
}
|
|
47
|
+
/** Parsed components of a SCIP symbol string */
|
|
48
|
+
interface ScipSymbol {
|
|
49
|
+
/** The indexer scheme (e.g. "scip-typescript", "scip-java", "rust-analyzer") */
|
|
50
|
+
scheme: string;
|
|
51
|
+
/** Package manager (e.g. "npm", "maven", "cargo") */
|
|
52
|
+
manager: string;
|
|
53
|
+
/** Package name (e.g. "@vega/api", "com.example/mylib") */
|
|
54
|
+
packageName: string;
|
|
55
|
+
/** Package version */
|
|
56
|
+
version: string;
|
|
57
|
+
/** Descriptor chain — the path to the symbol within the file */
|
|
58
|
+
descriptors: ScipDescriptor[];
|
|
59
|
+
/** The raw, unparsed symbol string */
|
|
60
|
+
raw: string;
|
|
61
|
+
}
|
|
62
|
+
interface ScipDescriptor {
|
|
63
|
+
name: string;
|
|
64
|
+
suffix: DescriptorSuffix;
|
|
65
|
+
}
|
|
66
|
+
type DescriptorSuffix = 'namespace' | 'type' | 'term' | 'method' | 'type-param' | 'parameter' | 'meta' | 'macro';
|
|
67
|
+
/** A local symbol (file-scoped, no cross-file identity) */
|
|
68
|
+
interface ScipLocalSymbol {
|
|
69
|
+
kind: 'local';
|
|
70
|
+
id: string;
|
|
71
|
+
raw: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type { IndexedDefinition as I, SymbolMatch as S, ScipSymbol as a, ScipLocalSymbol as b, SymbolResolutionCandidate as c };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as c,c as u}from"./chunk-6BQ3DSPK.js";import"./chunk-FAJQ7LWY.js";import{M as l}from"./chunk-Z54RD7VL.js";import{f as d}from"./chunk-FDGD5AB5.js";import"./chunk-RU65DDUP.js";import"./chunk-QW7EP6WI.js";import"./chunk-3IER7Q6H.js";import"./chunk-FM5BPL4V.js";import"./chunk-DRENNWRG.js";import"./chunk-RDBI2RXU.js";import{g as a,h as s}from"./chunk-R2NOK63J.js";import"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";import{parentPort as p,workerData as S}from"worker_threads";var i=k(S);if(!p)throw new Error("TypeScript mailbox worker requires a parent port.");if(i.kind==="index"){let t=new c({projectRoot:i.projectRoot,currentGeneration:()=>d(i.dbPath)});p.on("message",e=>{let r=m(e);y(r,()=>t.handle(r.payload.baseGeneration,r.payload.request),()=>t.status())})}else{let t=new u({openDb:()=>l(i.projectRoot)});p.on("message",e=>{let r=m(e),o=a();s(r.payload.profileEnvironment??{});try{y(r,()=>t.handle(r.payload.generation,r.payload.request),()=>t.status())}finally{s(o)}})}function y(t,e,r){let o;try{if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired before processing.");let n=e();if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired while the worker was processing it.");o={kind:"response",requestId:t.requestId,ok:!0,result:n,status:r()}}catch(n){o={kind:"response",requestId:t.requestId,ok:!1,error:n instanceof Error?n.message:String(n),status:r()}}p.postMessage(o)}function k(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker data is missing.");let e=t;if(e.kind==="index"&&typeof e.projectRoot=="string"&&typeof e.dbPath=="string")return{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath};if(e.kind==="semantic"&&typeof e.projectRoot=="string")return{kind:"semantic",projectRoot:e.projectRoot};throw new Error("TypeScript mailbox worker data is invalid.")}function m(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker request is missing.");let e=t;if(e.kind!=="request"||typeof e.requestId!="string"||!Number.isSafeInteger(e.deadlineAtMs)||typeof e.payload!="object"||e.payload===null)throw new Error("TypeScript mailbox worker request is invalid.");return e}
|
|
2
|
+
//# sourceMappingURL=typescript-mailbox-worker.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{A as Vt,B as Bt,C as Re,D as Ut,E as Gt,H as Pe,a as Rt,b as Pt,c as It,d as Mt,e as we,f as Tt,g as Ce,h as At,i as kt,j as Ot,k as ne,l as Lt,m as qt,p as Dt,q as _t,r as Wt,s as jt,t as Nt,u as j,w as x,x as $t,y as Ee,z as Ft}from"./chunk-HOA5YGOH.js";import{c as Yt,d as Xt,e as Jt,f as Kt,g as Zt,h as er}from"./chunk-LTA3BRZX.js";import{tb as Qt,vb as Ht,xb as zt}from"./chunk-GTIYTDRE.js";import{c as tr}from"./chunk-Q5ELPRKQ.js";import{a as be,b as ee}from"./chunk-ZZ3MWF33.js";import{f as ot,g as J}from"./chunk-PYAB5SM6.js";import{U as ut,X as Z}from"./chunk-NCZUNH3E.js";import"./chunk-YUKYB54I.js";import{a as lt}from"./chunk-AAQQPKCU.js";import"./chunk-NNO6A2PO.js";import"./chunk-P5XHIJHI.js";import"./chunk-KUW32IRO.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import{b as mt,d as Et}from"./chunk-6BQ3DSPK.js";import"./chunk-FAJQ7LWY.js";import{E as bt,F as A,H as re,J as xt,K as B,M as wt,O as xe,P as Ct,h as pt,j as ht,o as V,p as ft,q as yt,r as gt,s as te,t as vt,u as W,v as St}from"./chunk-Z54RD7VL.js";import{c as K,d as ct,e as dt}from"./chunk-FDGD5AB5.js";import{c as nt}from"./chunk-RU65DDUP.js";import{d as Ye}from"./chunk-QW7EP6WI.js";import"./chunk-3IER7Q6H.js";import"./chunk-FM5BPL4V.js";import"./chunk-DRENNWRG.js";import{A as it,B as st,C as ge,D as ve,E as Se,F as at,j as rt}from"./chunk-RDBI2RXU.js";import{a as Xe,b as Je,c as Ke,d as Ze,e as et}from"./chunk-R2NOK63J.js";import{c as q,d as D}from"./chunk-EF2R3WNQ.js";import{G as b,N as tt,S as _,X as ye,b as Ge,h as X,m as Qe,n as He,o as ze}from"./chunk-WE5RZHZ7.js";import"./chunk-2Q2LW5JW.js";import v from"process";import{rmSync as Mr}from"fs";import{resolve as kn}from"path";import{pathToFileURL as On}from"url";var oe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(t,r={}){this.root=t,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=Ce(t)}initializeAfterOwnershipAcquired(){let t=Tt(this.root),r=At(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:r}}observeLegacyRequest(t,r){Pt(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${t}`,now:()=>new Date(t)}),this.refreshStatus()}poll(t,r){if(this.active||t.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let o=It(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),o.requests.length===0)return!1;this.active=o;try{return r(Ar(o)),!0}catch(n){throw we(this.root,o),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(Mt(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(we(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ce(this.root)}};function Ar(e){if(e.requests.length===1)return e.requests[0].detail;let r=[...new Set(e.requests.map(o=>o.detail))].slice(0,3).join("; ");return`${e.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{createHash as hn}from"crypto";import{readdirSync as fn,statSync as yn}from"fs";import{join as Oe}from"path";import{performance as Le}from"perf_hooks";var Ie;function Me(e){Ie=e}function rr(){return Ie||{argv:process.argv.slice(2),execPath:process.execPath,...process.argv[1]!==void 0?{scriptPath:process.argv[1]}:{},cwd:process.cwd()}}import{Command as an,Help as cn}from"commander";import{Option as Or}from"commander";function Te(e){return e.evidence?e.evidence:kr.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var kr=new Set(["health","context","co-change"]);function nr(e){if(e.claims){if(e.claims.origin==="mixed"&&!e.claims.families?.length)throw new Error(`Mixed command ${e.id} must declare at least one claim family.`);return e.claims}let t=Te(e);if(t==="mixed")throw new Error(`Mixed command ${e.id} must declare claim families.`);let r=e.agent?Xt(e.agent.operation):[];return r.length>0&&r.every(n=>n==="repository-observation"||n==="repository-preview")?{origin:t==="heuristic"?"heuristic":"compiler-graph",observedSources:["index-generation"],producerValidation:{status:"not-evaluated"}}:{origin:"unknown",observedSources:["process"],producerValidation:{status:"not-evaluated"}}}function or(e,t){return Kt(new Map(t.map(r=>[r.id,Te(r)]))),er(new Map(t.map(r=>[r.id,nr(r)]))),Zt(new Map(t.flatMap(r=>r.agent?[[r.id,{...r.agent,resultUnits:qr(r)}]]:[]))),t.map(r=>{let o=r.hidden?e.command(r.command,{hidden:!0}):e.command(r.command);o.description(r.description),r.helpAfter&&o.addHelpText("after",`
|
|
2
|
+
${r.helpAfter.trim()}
|
|
3
|
+
`);for(let n of r.arguments??[])o.argument(n.name);for(let n of r.options??[])if(n.hidden){let i=new Or(n.flags,n.description).hideHelp();n.parser&&i.argParser(n.parser),Object.hasOwn(n,"defaultValue")&&i.default(n.defaultValue),o.addOption(i)}else n.parser&&Object.hasOwn(n,"defaultValue")?o.option(n.flags,n.description,n.parser,n.defaultValue):n.parser?o.option(n.flags,n.description,n.parser):Object.hasOwn(n,"defaultValue")?o.option(n.flags,n.description,n.defaultValue):o.option(n.flags,n.description);return o.action(async(...n)=>{try{let i=o.optsWithGlobals();Lr(i);let s=rr(),d=()=>r.id===Qt?r.handler(...n):Ht({command:r.id,producerVersion:b,invocationPrefix:s.scriptPath?[s.execPath,s.scriptPath]:["codebaseiq"],argv:[...s.argv],cwd:s.cwd,json:i.json===!0,sourceSession:i.session!==!1,reemitSource:i.reemit===!0,...typeof i.outputPageSize=="number"?{pageSize:i.outputPageSize}:{},...typeof i.outputCursor=="string"?{cursor:i.outputCursor}:{}},()=>r.handler(...n)),h=r.agent?Yt(r.agent.operation,{args:n.slice(0,-1),options:i}):void 0;await(h?Jt(h,d):d())}catch(i){Dr(i)}finally{A(void 0),yt()}}),{descriptor:r,command:o}})}function Lr(e){if(e.resultOnly===!0&&e.json!==!0)throw new Error("--result-only requires --json.");if(e.compact===!0&&e.json!==!0)throw new Error("--compact requires --json.")}function qr(e){let t=e.agent?.resultUnits;if(t?.kind==="field"&&t.field.trim()==="")throw new Error(`Command ${e.id} declares an empty result-unit field.`);return t||(e.renderShape==="list"||e.renderShape==="table"||e.renderShape==="grouped-by-file"?{kind:"rows"}:{kind:"report"})}function Dr(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${ee(t)}`),process.exitCode=1}var _r=new Set(Pe),ir=new Map(Pe.map((e,t)=>[e,t])),Wr=new Set(["Navigation","Graph","Impact","Exploration"]),jr=new Set(["Cleanup","Health"]),Nr=new Set(["Indexing","Core","Maintenance"]);function $r(e){if(e.hidden||e.agent?.semantic?.compatibility==="deprecated")return"compatibility";if(_r.has(e.id))return"primary-exploration";let t=e.docs?.category;if(t&&Wr.has(t))return"specialized-analysis";if(t&&jr.has(t))return"quality-cleanup";if(t&&Nr.has(t))return"maintenance";if(t==="Formal Models")return"formal-modeling";throw new Error(`Visible command ${e.id} has no cockpit panel (docs category: ${t??"missing"}).`)}function Fr(e,t={}){return[{id:"primary-exploration",title:"Primary exploration",purpose:"Locate exact referents, project chosen relationships, and read only named implementation gaps."},{id:"specialized-analysis",title:"Specialized analysis",purpose:"Run a named graph, impact, or structural analysis when that exact analysis answers the task."},{id:"quality-cleanup",title:"Quality and cleanup",purpose:"Evaluate repository quality, cleanup candidates, and configured architecture findings."},{id:"maintenance",title:"Maintenance",purpose:"Build, inspect, configure, and maintain the project index and local integrations."},{id:"formal-modeling",title:"Formal modeling",purpose:"Create, verify, and check explicit state-machine models and traces."},{id:"compatibility",title:"Compatibility and deprecated controls",purpose:"Preserved invocation surfaces for existing consumers; do not choose these for new workflows."}].map(n=>({...n,commands:e.filter(i=>$r(i)===n.id).sort((i,s)=>n.id==="primary-exploration"?(ir.get(i.id)??Number.MAX_SAFE_INTEGER)-(ir.get(s.id)??Number.MAX_SAFE_INTEGER):0)})).filter(n=>n.commands.length>0&&(t.includeCompatibility||n.id!=="compatibility"))}function sr(e,t,r={}){let o=[`Usage: ${e.name()} [options] [command]`,"",e.description(),"","Options:"],n=e.options.map(s=>s.flags),i=Math.max(...n.map(s=>s.length),0);for(let s of e.options)o.push(` ${s.flags.padEnd(i)} ${s.description}`);o.push(` ${"-h, --help".padEnd(i)} Display this grouped command help`);for(let s of Fr(t,r)){o.push("",`${s.title}:`,` ${s.purpose}`);let d=Math.max(...s.commands.map(h=>h.command.length),0);for(let h of s.commands)o.push(` ${h.command.padEnd(d)} ${h.description}`)}return r.includeCompatibility||o.push("","Run `codebaseiq --help-all` to include compatibility and deprecated controls."),o.push("Run `codebaseiq <command> --help` for one control's options and examples.",""),o.join(`
|
|
4
|
+
`)}import{existsSync as Vr,mkdirSync as Br,writeFileSync as Ur}from"fs";import{homedir as Gr}from"os";import{join as ie}from"path";var Qr=1440*60*1e3,cr="update-check.json",Hr="https://registry.npmjs.org/codebaseiq/latest";async function Ae(e={}){let t=e.env??process.env;if(t.CODEBASEIQ_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let r=e.cacheDir??Xr(t),o=e.now??Date.now(),n=e.currentVersion??b,i=Jr(r),s=i&&o-i.checkedAt<Qr?i.latestVersion:await Kr(r,e.fetchLatestVersion??en,o);if(!s||!Yr(s,n))return;(e.writeNotice??(h=>console.error(h)))(zr(n,s))}function zr(e,t){return[`codebaseiq update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g codebaseiq@latest",""].join(`
|
|
5
|
+
`)}function Yr(e,t){let r=ar(e),o=ar(t);if(!r||!o)return e!==t;for(let n=0;n<r.length;n++){let i=r[n]-o[n];if(i>0)return!0;if(i<0)return!1}return!1}function Xr(e){let t=e.XDG_CACHE_HOME||ie(Gr(),".cache");return ie(t,"codebaseiq")}function Jr(e){let t=ie(e,cr);if(!Vr(t))return null;try{let r=JSON.parse(X(t,"update notice cache"));return typeof r.checkedAt=="number"&&(typeof r.latestVersion=="string"||r.latestVersion===null)?{checkedAt:r.checkedAt,latestVersion:r.latestVersion}:null}catch{return null}}async function Kr(e,t,r){let o;try{o=await t()}catch{o=null}return Zr(e,{checkedAt:r,latestVersion:o}),o}function Zr(e,t){try{Br(e,{recursive:!0}),Ur(ie(e,cr),`${JSON.stringify(t,null,2)}
|
|
6
|
+
`)}catch{}}async function en(){let e=await fetch(Hr,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function ar(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}var tn=5e3,rn=100,nn={prepare:xt,freshness:V,ensureService:ne,inspectService:qt,requestRefresh:_t,async reindex(e,t,r,o){let{reindexConfiguredProject:n}=await import("./project-reindex-5JOKXAXT.js");return n(e,t,r,o)},wait(e){return new Promise(t=>setTimeout(t,e))},now:Date.now};async function dr(e,t=nn,r={}){if(e.dbPathSource==="env")return{source:"explicit-index",service:{kind:"skipped",reason:"environment"}};let o=on(e,t),n=t.prepare(e.projectRoot,e.config,e.paths,{gitContext:e.gitContext,...o?{watcherGeneration:o}:{}}),i=t.freshness(e.projectRoot,e.config,e.paths),s=t.ensureService({commandName:e.commandName,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:b,config:e.config,gitContext:e.gitContext});if(i.state==="fresh")return{source:n.kind==="local-fresh"?"existing":"shared-generation",service:s};if((s.kind==="started"||s.kind==="reused")&&(t.requestRefresh(Z(e.paths.cacheDir).activityPath,`evidence command ${e.commandName} requires a fresh generation`),i=await sn(e,i,t,r,s),i.state==="fresh"))return{source:"watcher",service:s};try{await t.reindex(e.projectRoot,e.config,e.paths,{allowPartial:!1,skipAutoInstall:!0,trigger:{kind:"watch-demand",detail:`codebaseiq ${e.commandName}`},onStatus:()=>{}})}catch(d){throw new Error(`Could not prepare fresh evidence for codebaseiq ${e.commandName}: ${d instanceof Error?d.message:String(d)}`,{cause:d})}if(i=t.freshness(e.projectRoot,e.config,e.paths),i.state!=="fresh")throw new Error(`Could not prepare fresh evidence for codebaseiq ${e.commandName}: index remained ${i.state} (${i.reason})`);return{source:"synchronous-reindex",service:s}}function on(e,t){if(e.config.watch?.enabled===!0)try{return kt(t.inspectService({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:b,gitContext:e.gitContext}))}catch{return}}async function sn(e,t,r,o,n){if(n.state.watcher.state==="budget-paused")return t;let i=Math.max(0,o.waitMs??tn),s=Math.max(1,o.pollMs??rn),d=r.now()+i,h=t;for(;r.now()<d;)if(await r.wait(Math.min(s,Math.max(1,d-r.now()))),gt(),h=r.freshness(e.projectRoot,e.config,e.paths),h.state==="fresh")return h;return h}async function lr(e={}){let t=new an;e.resident&&t.exitOverride(),e.terminalOutput&&t.configureOutput({writeOut:n=>process.stdout.write(be(n)),writeErr:n=>process.stderr.write(be(n))}),t.name("codebaseiq").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(b).option("--output-page-size <characters>","Return bounded output pages with an exact continuation command",zt).option("--output-cursor <cursor>","Continue a bounded output page").option("--no-session","Disable the explicit exploration evidence ledger").option("--reemit","Recovery only: render source and graph evidence again instead of citing session receipts").option("--help-all","Display every command, including compatibility and deprecated controls");let r=await tr(e.invocationCommand);or(t,r);let o=new cn;return t.configureHelp({formatHelp:(n,i)=>n===t?sr(t,r):o.formatHelp(n,i)}),t.hook("preAction",async(n,i)=>{let s=i.name();if(e.resident){await e.resident.preAction(s);return}let d=B(s),h=Ot(s);if(!d&&!h){ur(),await Ae({commandName:s});return}let u=bt(),c=_(u);ft(c);let l=re(u,c);A(l),ur(),await Ae({commandName:s});let{config:p,paths:a}=l;if(d){let f=await dr({commandName:s,projectRoot:u,config:p,paths:a,dbPathSource:l.dbPathSource,gitContext:c});process.env.CODEBASEIQ_DEBUG&&console.error(`evidence-freshness: ${f.source}`),f.service.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${f.service.message}`),(f.service.kind==="failed"||f.service.kind==="skipped")&&j(u,b);return}if(!h){j(u,b);return}let g=ne({commandName:s,projectRoot:u,cacheDir:a.cacheDir,cliVersion:b,config:p,gitContext:c});g.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${g.message}`),(g.kind==="failed"||g.kind==="skipped")&&j(u,b)}),t.hook("postAction",()=>A(void 0)),{program:t,descriptors:r}}function ur(){if(Ke(),!Xe()||Ze())return;let e=null;try{e=Ct(t=>nt(t))}catch{}et({command:Je()??`codebaseiq ${process.argv.slice(2).join(" ")}`,toolVersion:b,projectFingerprint:e})}import{execFileSync as mr}from"child_process";import{lstatSync as dn}from"fs";import{join as un}from"path";var ke=3e4,pr={encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:ke,killSignal:"SIGKILL"};function hr(e){return{generation:e.generation,epoch:e.epoch,changeSequence:e.changeSequence,headCommit:e.headCommit,treeOid:e.treeOid,fingerprintByPath:new Map(e.snapshot.files.map(t=>[t.path,t.hash])),languages:[...e.snapshot.languages],markerFiles:[...e.config.indexer?.typescript?.projects??[],...e.config.indexer?.clojure?.configPath?[e.config.indexer.clojure.configPath]:[]]}}function fr(e,t,r){if(r.epoch!==t.epoch)return{continuous:!1,reason:"the watcher observation epoch advanced since this generation was published"};if(r.changeSequence!==t.changeSequence)return{continuous:!1,reason:"the watcher observed a change after this generation was published"};let o,n;try{o=ln(e),n=mn(e)}catch(i){return{continuous:!1,reason:`git state could not be read: ${i instanceof Error?i.message:String(i)}`}}if(o.headCommit!==t.headCommit||o.treeOid!==t.treeOid)return{continuous:!1,reason:"the git HEAD tree moved since this generation was published"};for(let i of n){if(He(i,t.languages,t.markerFiles)==="other")continue;let s=t.fingerprintByPath.get(i),d=pn(un(e,i));if(d===null)return{continuous:!1,reason:`indexed input ${i} is no longer readable as a plain file`};if(s!==d)return{continuous:!1,reason:s===void 0?`indexed input ${i} appeared after this generation was published`:`indexed input ${i} changed after this generation was published`}}return{continuous:!0}}function ln(e){let t=mr("git",["-C",e,"rev-parse","HEAD","HEAD^{tree}"],{...pr,timeout:ke}).split(`
|
|
7
|
+
`).map(n=>n.trim()).filter(Boolean),[r,o]=t;if(!/^[0-9a-f]{40,64}$/.test(r??"")||!/^[0-9a-f]{40,64}$/.test(o??""))throw new Error("git did not report a resolved HEAD tree");return{headCommit:r,treeOid:o}}function mn(e){return mr("git",["-C",e,"status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--","."],{...pr,timeout:ke}).split("\0").filter(t=>t.length>=4&&t[2]===" ").map(t=>t.slice(3))}function pn(e){try{return dn(e).isFile()?Qe(e,{maxBytes:Ge,inputKind:"project-file"}):null}catch{return null}}var R=class extends Error{constructor(r,o){super(o);this.code=r}code};function Sr(e){let t=!1,r,o=()=>{let u=r;if(r=void 0,!!u)try{u.db.close()}catch{}},n=()=>{let u=e.indexGeneration();if(!u)throw new R("stale-index","The resident index is not idle-fresh; run the command in-process.");return u},i=u=>{let c=e.observation();if(!c||c.published.generation!==u)throw new R("stale-index","No provable observation is bound to the published generation; run the command in-process.");let l=fr(e.projectRoot,c.published,{epoch:c.epoch,changeSequence:c.changeSequence});if(!l.continuous)throw new R("stale-index",`${l.reason}; run the command in-process.`)},s=()=>{let u=n(),c=Sn(e.projectRoot);if(r&&(r.generation!==u||r.stamp!==c||W(e.dbPath)!==u)&&o(),!r){let l=wt(e.projectRoot);if(W(e.dbPath)!==u){try{l.close()}catch{}throw new R("stale-index","The published generation moved while opening the resident database.")}r={generation:u,stamp:c,db:l}}return r.db},d=u=>{if(!B(u))throw new R("ineligible-command",`Command ${u} always executes in-process.`);n();let c=re(e.projectRoot,_(e.projectRoot));if(c.dbPathSource!=="configured")throw new R("stale-index","The resident host does not serve fallback index locations.");A(c)};return{execute:async u=>{if(t)return U("busy","The resident host is executing another request; run the command in-process.");let c=u.argv[0];if(!c||c.startsWith("-")||!B(c))return U("ineligible-command","Only evidence commands are served by the resident host.");let l;try{l=n(),i(l)}catch(y){return yr(y)}t=!0;let p=Le.now(),a=new qe(u.tty),g=vn(u.envAllowlist),f=process.exitCode;process.exitCode=0,Me({argv:u.argv,execPath:u.clientInvocation?.execPath??process.execPath,...u.clientInvocation?.scriptPath!==void 0?{scriptPath:u.clientInvocation.scriptPath}:{},cwd:u.cwd}),xe(s);try{let{program:y}=await lr({invocationCommand:c,resident:{preAction:d}});a.install();try{await y.parseAsync([...u.argv],{from:"user"})}finally{a.restore()}let S=typeof process.exitCode=="number"?process.exitCode:0;return{ok:!0,kind:"executed",protocolVersion:x,serverPid:process.pid,exitCode:S,stdout:a.stdout(),stderr:a.stderr(),generation:l,durationMs:Le.now()-p}}catch(y){return y instanceof R?yr(y):gn(y)?{ok:!0,kind:"executed",protocolVersion:x,serverPid:process.pid,exitCode:y.exitCode,stdout:a.stdout(),stderr:a.stderr(),generation:l,durationMs:Le.now()-p}:U("execution-error",`Resident execution failed: ${y instanceof Error?y.message:String(y)}`)}finally{xe(void 0),Me(void 0),A(void 0),process.exitCode=f,g(),t=!1}},releaseDatabase:o}}function U(e,t){return{ok:!1,protocolVersion:x,code:e,message:t}}function yr(e){return e instanceof R?U(e.code,e.message):U("execution-error",e instanceof Error?e.message:String(e))}function gn(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&(e.code.startsWith("commander.")||e.code==="commander")&&typeof e.exitCode=="number"}function vn(e){let t=new Map;for(let r of Vt){t.set(r,process.env[r]);let o=e?.[r];o===void 0?delete process.env[r]:process.env[r]=o}return()=>{for(let[r,o]of t)o===void 0?delete process.env[r]:process.env[r]=o}}var qe=class{constructor(t){this.tty=t}tty;stdoutChunks=[];stderrChunks=[];restorers=[];install(){this.restorers=[gr(process.stdout,this.stdoutChunks),gr(process.stderr,this.stderrChunks),se(process.stdout,"isTTY",this.tty?.isTTY??!1),se(process.stderr,"isTTY",this.tty?.isTTY??!1),se(process.stdout,"columns",this.tty?.columns),se(process.stderr,"columns",this.tty?.columns)]}restore(){for(let t of this.restorers.reverse())t();this.restorers=[]}stdout(){return this.stdoutChunks.join("")}stderr(){return this.stderrChunks.join("")}};function gr(e,t){let r=e.write,o=(n,i,s)=>{t.push(typeof n=="string"?n:Buffer.isBuffer(n)?n.toString(typeof i=="string"?i:"utf8"):String(n));let d=typeof s=="function"?s:typeof i=="function"?i:void 0;return typeof d=="function"&&d(),!0};return e.write=o,()=>{e.write=r}}function se(e,t,r){let o=Object.hasOwn(e,t),n=o?Object.getOwnPropertyDescriptor(e,t):void 0;return r===void 0?o&&Reflect.deleteProperty(e,t):Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}}function Sn(e){let t=hn("sha256");for(let o of[".codebaseiq.json",".codebaseiq-baseline.json"])t.update(o),t.update(vr(Oe(e,o)));let r=Oe(e,".codebaseiq","suppressions");t.update(r);try{for(let o of fn(r).sort())t.update(o),t.update(vr(Oe(r,o)))}catch{t.update("absent")}return t.digest("hex")}function vr(e){try{let t=yn(e);return`${t.size}:${t.mtimeMs}`}catch{return"absent"}}import{chmodSync as bn,mkdirSync as xn,rmSync as br}from"fs";import{createServer as wn}from"net";import{dirname as Cn}from"path";var xr=1e4,En=5e3,Rn=6e5;function wr(e){let t=ye(e.projectRoot),r=0,o,n,i=new Set,s=wn(c=>{i.add(c),c.setTimeout(xr,()=>c.destroy()),c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c));let l=Ut($t,p=>{r+=1,o=new Date().toISOString(),e.onActivity?.(),d(p,c).then(a=>u(c,a)).catch(a=>{n=a instanceof Error?a.message:String(a),c.destroy()})},p=>{n=p.message,u(c,{ok:!1,protocolVersion:x,code:"invalid-request",message:p.message})});c.on("data",p=>{try{l.push(p)}catch(a){n=a instanceof Error?a.message:String(a),c.destroy()}})}),d=async(c,l)=>{let p=Gt(c);return p?ye(p.projectRoot)!==t?{ok:!1,protocolVersion:x,code:"wrong-project",message:"This query lane serves a different project root."}:h(p,l):{ok:!1,protocolVersion:x,code:"invalid-request",message:"The query lane received a request it could not validate."}},h=async(c,l)=>{if(c.kind==="ping"){let a=e.indexGeneration();return{ok:!0,kind:"pong",protocolVersion:x,serverPid:process.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{},cliVersion:e.cliVersion,projectRoot:t,...a?{indexGeneration:a}:{}}}if(!e.execute)return{ok:!1,protocolVersion:x,code:"unsupported",message:"Resident execution is not enabled on this service; run the command in-process."};let p=Math.max(c.deadlineMs??Ft,xr);l.setTimeout(Math.min(p+En,Rn));try{l.write(Re({ok:!0,kind:"accepted",protocolVersion:x,serverPid:process.pid},Ee))}catch(a){return n=a instanceof Error?a.message:String(a),l.destroy(),{ok:!1,protocolVersion:x,code:"execution-error",message:"The query lane could not acknowledge the request."}}try{return await e.execute(c)}catch(a){return n=a instanceof Error?a.message:String(a),{ok:!1,protocolVersion:x,code:"execution-error",message:`Resident execution failed: ${n}`}}},u=(c,l)=>{try{c.end(Re(l,Ee))}catch(p){n=p instanceof Error?p.message:String(p),c.destroy()}};return process.platform!=="win32"&&(xn(Cn(e.socketPath),{recursive:!0,mode:448}),br(e.socketPath,{force:!0})),new Promise((c,l)=>{s.once("error",l),s.listen(e.socketPath,()=>{if(s.removeListener("error",l),s.on("error",p=>{n=p.message}),process.platform!=="win32")try{bn(e.socketPath,384)}catch{}c({status:()=>({protocolVersion:x,socketPath:e.socketPath,requests:r,...o!==void 0?{lastRequestAt:o}:{},...n!==void 0?{lastError:n}:{}}),close:()=>new Promise(p=>{for(let a of i)a.destroy();s.close(()=>{process.platform!=="win32"&&br(e.socketPath,{force:!0}),p()})})})})})}import{randomUUID as In}from"crypto";import{Worker as Mn}from"worker_threads";var ae=class{constructor(t){this.options=t;this.now=t.now??Date.now,this.setTimer=t.setTimer??setTimeout,this.clearTimer=t.clearTimer??clearTimeout}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}start(t){if(!this.canAccept())return!1;if(t.deadlineAtMs<this.now()){try{this.options.onReject(t,`${this.options.name} request expired before processing.`)}catch(i){this.closed=!0,this.options.onFatal(De(i))}return!0}let r=this.ensureWorker(),o=Math.max(1,Math.min(2147483647,t.deadlineAtMs-this.now())),n=this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},o);this.active={request:t,timer:n};try{r.postMessage({kind:"request",...t})}catch(i){this.failActiveAfterTermination(Cr(i))}return!0}async close(t=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.active){await this.failActiveAfterTermination(t);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let t=this.options.createWorker(),r=++this.workerGeneration;return t.on("message",o=>this.handleMessage(r,o)),t.on("error",o=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${o.message}`)}),t.on("exit",o=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${o}.`))}),this.worker=t,t}handleMessage(t,r){if(t!==this.workerGeneration||this.closed||!this.active)return;let o=Pn(r);if(!o){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(o.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active;try{this.options.onStatus(o.status),o.ok?this.options.onComplete(n.request,o.result,o.status):this.options.onReject(n.request,o.error,o.status)}catch(i){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(De(i));return}this.releaseActive(n)}async failActiveAfterTermination(t){if(this.activeFailure){await this.activeFailure;return}let r=this.active;if(!r){await this.terminateWorker();return}this.clearTimer(r.timer);let o=(async()=>{if(await this.terminateWorker()){try{this.options.onReject(r.request,t)}catch(i){this.closed=!0,this.options.onFatal(De(i));return}this.releaseActive(r)}})();this.activeFailure=o;try{await o}finally{this.activeFailure===o&&(this.activeFailure=null)}}releaseActive(t){this.active===t&&(this.active=null,this.clearTimer(t.timer))}async terminateWorker(){if(this.terminating)return this.terminating;let t=this.worker;if(!t)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await t.terminate(),!0}catch(o){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Cr(o)}`,{cause:o})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Pn(e){if(!e||typeof e!="object")return null;let t=e;if(t.kind!=="response"||typeof t.requestId!="string"||!("status"in t))return null;if(t.ok===!0){if(!("result"in t)||"error"in t)return null}else if(t.ok===!1){if("result"in t||typeof t.error!="string")return null}else return null;return t}function De(e){return e instanceof Error?e:new Error(String(e))}function Cr(e){return e instanceof Error?e.message:String(e)}function Er(e){let t=()=>({protocolVersion:K,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Pr({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:dt,createWorker:()=>Ir(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath}),complete(r,o,n,i){ge(e.paths,r,{ok:!0,protocolVersion:K,id:o.id,baseGeneration:o.baseGeneration,response:n},{nowMs:i,limits:e.limits})},reject(r,o,n,i){ve(e.paths,r,{ok:!1,protocolVersion:K,id:o,error:n},n,{nowMs:i,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Rr(e){let t=()=>({protocolVersion:te,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Pr({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:St,createWorker:()=>Ir(e,{kind:"semantic",projectRoot:e.projectRoot}),complete(r,o,n,i){ge(e.paths,r,{ok:!0,protocolVersion:te,id:o.id,generation:o.generation,response:n},{nowMs:i,limits:e.limits})},reject(r,o,n,i){ve(e.paths,r,{ok:!1,protocolVersion:te,id:o,error:n},n,{nowMs:i,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Pr(e){let t=e.now??Date.now,r=q(process.pid),o={pid:process.pid,...r?{processIdentity:r}:{}},n=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${In()}`,i={...e.limits,maxBatch:1},s=null,d=e.initialStatus(),h=!1,u=a=>{h=!0,e.onFatal(a)},c=new ae({name:e.name,createWorker:e.createWorker,now:t,onComplete(a,g,f){let y=l(a.requestId);d=f,e.complete(y.claim,y.envelope,g,t()),p(y)},onReject(a,g,f){let y=l(a.requestId);f!==void 0&&(d=f),e.reject(y.claim,y.envelope.id,g,t()),p(y)},onStatus(a){d=a},onFatal:u});return{poll(){if(h||!c.canAccept())return 0;let a=it(e.paths,{ownerId:n,nowMs:t(),limits:i,owner:o,liveness:{isProcessAlive:rt,readProcessIdentity:q}})[0];if(!a)return 0;let g=a.requestId;try{let f=e.parseEnvelope(st(a,i));if(g=f.id,f.id!==a.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(f.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(s={claim:a,envelope:f},e.onBusy?.(f.deadlineAtMs),!c.start({requestId:f.id,deadlineAtMs:f.deadlineAtMs,payload:f}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(f){let y=An(f);try{e.reject(a,g,y,t()),s?.claim===a&&p(s)}catch(S){u(Tn(S))}}return 1},status(){return{...d,mailbox:at(e.paths)}},async close(a){await c.close(a)}};function l(a){let g=s;if(!g||g.envelope.id!==a)throw new Error(`${e.name} parent lost the active mailbox claim.`);return g}function p(a){s===a&&(s=null,e.onBusy?.(void 0))}}function Ir(e,t){if(e.createWorker)return e.createWorker(t);let r=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new Mn(r,{workerData:t})}function Tn(e){return e instanceof Error?e:new Error(String(e))}function An(e){return e instanceof Error?e.message:String(e)}var Ln=1e3,qn=250,Dn=6e4,_n=10,Wn=50,jn=250;function Nn(e,t=1){if(e>0)return _n;let r=Math.max(0,Math.min(3,t-1));return Math.min(jn,Wn*2**r)}async function $n(e,t){let r=t.processIndexRequests(),o=t.processSemanticRequests(),n=r+o,i=n>0?0:e+1;if(t.afterMailboxPoll({indexRequests:r,semanticRequests:o,processedRequests:n}),t.shouldStop())return{indexRequests:r,semanticRequests:o,processedRequests:n,consecutiveIdlePolls:i,stopped:!0};let s=Nn(n,i);return await t.wait(s),{indexRequests:r,semanticRequests:o,processedRequests:n,consecutiveIdlePolls:i,stopped:!1,delayMs:s}}function Fn(e){return e==="fresh"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}async function Vn(e,t,r={}){let o=Lt(e,t),n=o.projectRoot;v.env.CODEBASEIQ_PROJECT_ROOT=n;let i=pt(n);i.watch={...i.watch,...r};let s=ht(i);if(!s.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let d=tt(n,i),h=Z(d.cacheDir),u=q(v.pid),c=jt(h.lockPath,n,{readProcessIdentity:m=>m===v.pid?u:q(m)});if(!c.acquired)return;let l=new oe(h.refreshRequestsPath,{retryDelayMs:Math.max(1e3,s.cooldownMs)});l.initializeAfterOwnershipAcquired();let p=Date.now(),a=D(),g=p,f=a,y={state:"idle"},S,G,P,Q,ce=J(d.dbPath),de=!1,_e=!1,We=0,je=Number.NEGATIVE_INFINITY,Ne=Number.NEGATIVE_INFINITY,$e=Number.NEGATIVE_INFINITY,Fe=Number.NEGATIVE_INFINITY,ue,le,Ve=0,me=vt(d.cacheDir),pe=ct(d.cacheDir);Et(me),mt(pe);let H,N,O,Be=m=>{if(O=void 0,!!m)try{let C=_(n);if(!C?.headCommit||!C.treeOid)return;let w=Ye(X(d.metaPath,"reindex metadata"));if(w.kind!=="legacy"&&w.kind!=="supported")return;let I=ze(w.metadata.fingerprint);if(!I)return;O=hr({generation:m,...L.observation(),headCommit:C.headCommit,treeOid:C.treeOid,snapshot:I,config:i})}catch{}},E=(m=!1,C=m?"durable":"visibility")=>{if(!_e)return;let w=Date.now(),I=D();!m&&I-je<Ln||(je=I,Dt(h.statePath,{version:1,protocolVersion:ut,pid:v.pid,...u?{processIdentity:u}:{},projectRoot:n,...o.worktreeId?{worktreeId:o.worktreeId}:{},cliVersion:t,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(w).toISOString(),lastActivityAt:new Date(g).toISOString(),...s.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(g+s.idleTimeoutMs).toISOString()},watcher:y,...y.state==="idle"&&S?{indexGeneration:S}:{},...G?{lastRefresh:G}:{},...P?{lastError:P}:{},reindexActivity:ce,refreshRequests:l.status(),typescriptSemantic:{...he.status(),...ue===void 0?{}:{busyUntil:new Date(ue).toISOString()}},typescriptIndex:{...fe.status(),...le===void 0?{}:{busyUntil:new Date(le).toISOString()}},...H?{queryLane:H.status()}:{}},{durability:C}))},M=()=>{g=Date.now(),f=D()},Ue=m=>{M(),Q??=m,P={at:new Date().toISOString(),message:m.message},E(!0,"visibility")},he=Rr({paths:me,projectRoot:n,onBusy(m){ue=m===void 0?void 0:m+5e3,E(!0,"visibility")},onFatal:Ue}),fe=Er({paths:pe,projectRoot:n,dbPath:d.dbPath,onBusy(m){le=m===void 0?void 0:m+5e3,E(!0,"visibility")},onFatal:Ue}),L=new Rt({projectRoot:n,config:{...i,watch:s},outputDb:d.dbPath,languages:i.languages,onStatus(m){y=m,m.state!=="idle"&&(S=void 0,O=void 0,N?.releaseDatabase(),M()),E(!0)},onReindexComplete(){M();let m=V(n,i,d);return G=m.lastRefresh,S=m.state==="fresh"?W(d.dbPath)??void 0:void 0,Be(S),ce=J(d.dbPath),l.completeActive(),P=void 0,E(!0),m.state==="fresh"},onReindexError(){l.failActive()},onRefreshSuppressed(m){let C=ot(d.dbPath,m);C.state==="failed"&&(P={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${C.reason}`},E(!0,"visibility")),ce=J(d.dbPath)},onError(m){M(),S=void 0,O=void 0,P={at:new Date().toISOString(),message:m.message},E(!0)}}),z=()=>{de=!0};v.once("SIGINT",z),v.once("SIGTERM",z);let $=!1,Y,F;try{try{N=v.env.CODEBASEIQ_DAEMON==="1"||i.daemon?.enabled===!0?Sr({projectRoot:n,dbPath:d.dbPath,indexGeneration:()=>S,observation:()=>O?{published:O,...L.observation()}:void 0}):void 0,H=await wr({socketPath:Bt(d.cacheDir),projectRoot:n,cliVersion:t,...u?{processIdentity:u}:{},indexGeneration:()=>S,onActivity:M,...N?{execute:I=>N.execute(I)}:{}})}catch(w){P={at:new Date().toISOString(),message:`Query lane did not start: ${w instanceof Error?w.message:String(w)}`}}L.start();let m=V(n,i,d);G=m.lastRefresh,S=m.state==="fresh"?W(d.dbPath)??void 0:void 0,Be(S);let C=Fn(m.state);for(C&&L.requestRefresh(C,{immediate:!0}),M(),_e=!0,E(!0);!de;){let w=await $n(Ve,{processIndexRequests:()=>fe.poll(),processSemanticRequests:()=>he.poll(),afterMailboxPoll:({processedRequests:I})=>{let k=D();if(k-Fe>=Dn&&(Fe=k,Se(pe),Se(me)),k-$e>=6e4&&($e=k,j(n,t)),k-Ne>=qn){Ne=k;let T=Wt(h.activityPath);T&&T.atMs>g&&(g=T.atMs,f=k),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>We&&(We=T.refreshRequestedAtMs,l.observeLegacyRequest(T.refreshRequestedAtMs,T.refreshDetail??"stale index observed by a legacy command")),l.poll(y,Tr=>{M(),L.requestRefresh({kind:"watch-demand",detail:Tr},{immediate:!0})})}I>0&&(M(),E(!0,"visibility")),E()},shouldStop:()=>de||Q!==void 0||Nt({watcher:y,lastActivityAtMs:f,nowMs:D(),idleTimeoutMs:s.idleTimeoutMs}),wait:Bn});if(Ve=w.consecutiveIdlePolls,w.stopped)break}}catch(m){$=!0,Y=m}finally{v.off("SIGINT",z),v.off("SIGTERM",z),await H?.close(),N?.releaseDatabase(),await Promise.all([he.close("TypeScript semantic service stopped before completing the request."),fe.close("TypeScript index service stopped before completing the request.")]);let m=await L.stop();m.state==="stopped"?(Mr(h.statePath,{force:!0}),Mr(h.activityPath,{force:!0}),c.release()):(P={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${m.reasons.join("; ")}`},E(!0),F=new Error(P.message))}if(!$&&Q&&($=!0,Y=Q),$&&F)throw new AggregateError([Y,F],"Watch service execution and shutdown both failed.");if($)throw Y;if(F)throw F}function Bn(e){return new Promise(t=>setTimeout(t,e))}function Un(e,t={report:r=>console.error(r),exit:r=>v.exit(r)}){return t.report(`watch-service: ${ee(e instanceof Error?e.message:String(e))}`),t.exit(1)}var Gn=v.argv[1]?On(kn(v.argv[1])).href:null;if(Gn===import.meta.url){lt();let e=v.argv[2],t=v.argv[3],r=Qn(v.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),v.exitCode=1;else try{await Vn(e,t,r)}catch(o){Un(o)}}function Qn(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}export{$n as runWatchServiceLoopIteration,Vn as runWatchServiceServer,Fn as startupRefreshTrigger,Un as terminateWatchServiceProcess,Nn as watchServiceLoopDelayMs};
|
|
8
|
+
//# sourceMappingURL=watch-server.js.map
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# Agent guide
|
|
2
|
+
|
|
3
|
+
codebaseiq supplies repository evidence. The agent owns the goal, plan, code,
|
|
4
|
+
tests, and final decision.
|
|
5
|
+
|
|
6
|
+
## Before a nonlocal edit
|
|
7
|
+
|
|
8
|
+
Use one evidence ladder: locate exact text; orient it by compiler identity and
|
|
9
|
+
construct ownership; navigate typed compiler and runtime relationships; account
|
|
10
|
+
for every omitted direction; read connected behavior for the selected path;
|
|
11
|
+
then retrieve exact current source only where full implementation detail can
|
|
12
|
+
change the decision.
|
|
13
|
+
|
|
14
|
+
For a cross-layer or end-to-end question, first reduce the question to the few
|
|
15
|
+
material claims the answer must establish. Locate exact referents with `search`,
|
|
16
|
+
`outline`, or `entrypoints`, then choose the relationship families and directions
|
|
17
|
+
capable of establishing each claim. Use `--symbol` only for a printed compiler
|
|
18
|
+
identity and `--at` for an exact construct location. Batch independent roots:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
codebaseiq evidence \
|
|
22
|
+
--symbol <symbol> \
|
|
23
|
+
--edge execution \
|
|
24
|
+
--edge runtime \
|
|
25
|
+
--direction both \
|
|
26
|
+
--depth 2 \
|
|
27
|
+
--max-edges 32
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Read the returned facts, evidence strength, provider support, coverage, folds,
|
|
31
|
+
and recovery paths together. Query completion accounts for the requested bounded
|
|
32
|
+
projection; it does not mean the user's task is complete. If a material claim
|
|
33
|
+
still requires implementation behavior, resolve its exact constructs with one
|
|
34
|
+
batched `inspect --view behavior` call. Use `code` only when exact syntax can
|
|
35
|
+
change the decision. Do not enumerate unrelated helpers, examples, tests, or
|
|
36
|
+
frontiers. Query count measures efficiency but never makes a recoverable material
|
|
37
|
+
claim optional.
|
|
38
|
+
|
|
39
|
+
Before sending the answer, audit the draft itself against the material claims.
|
|
40
|
+
Evidence seen but left implicit in the draft is not recovered. Copy returned
|
|
41
|
+
file and line identities exactly instead of reconstructing citation paths.
|
|
42
|
+
|
|
43
|
+
A broad literal is counted exactly and returned with recoverable structural
|
|
44
|
+
scopes. Narrow only when a named material claim requires one of those scopes.
|
|
45
|
+
Exact edges are facts within their reported coverage. Derived or candidate edges
|
|
46
|
+
and unsupported dynamic frontiers require the displayed source, another exact
|
|
47
|
+
referent, or an explicit limitation—not an absence claim.
|
|
48
|
+
|
|
49
|
+
When one known target is already the center of the change, run the aggregate
|
|
50
|
+
context query:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
codebaseiq context <target>
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Treat its source packet as already read. Write a normal concise plan. Add a
|
|
57
|
+
focused query only when a named uncertainty can change that plan.
|
|
58
|
+
|
|
59
|
+
For tracked nonbinary repository content, use `search`, `inspect`, and `code`
|
|
60
|
+
instead of native search or source reads. Native tools are for applying edits,
|
|
61
|
+
running checks, binary content, or a specific unsupported gap that codebaseiq
|
|
62
|
+
has explicitly reported.
|
|
63
|
+
|
|
64
|
+
## After a coherent edit
|
|
65
|
+
|
|
66
|
+
Run the repository's native checks. Then map downstream consumers when the
|
|
67
|
+
change can propagate:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
codebaseiq diff-impact
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
For declared structural rules, run:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
codebaseiq architecture
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
For cleanup, drift, React, or Vue work, run the relevant health or focused
|
|
80
|
+
detector command. Confirm heuristic candidates in source before editing them.
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
codebaseiq health --full
|
|
84
|
+
codebaseiq react-hook-candidates --full
|
|
85
|
+
codebaseiq vue-composable-candidates --full
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
There is no codebaseiq acceptance ceremony. Native tests establish behavior;
|
|
89
|
+
codebaseiq adds relationship and cleanup evidence.
|
|
90
|
+
|
|
91
|
+
## Efficient use
|
|
92
|
+
|
|
93
|
+
- Use `search` for an unknown literal anchor in indexed source.
|
|
94
|
+
- Use `system-map` before source drilldown when several layers or subsystems may
|
|
95
|
+
participate. Treat its connected behavior as source already read. Follow an
|
|
96
|
+
unresolved frontier only when it can answer a named material uncertainty.
|
|
97
|
+
- Use a behavior-view `inspect` packet for several related locations. Escalate
|
|
98
|
+
to `code` only for known exact definitions or ranges whose complete source
|
|
99
|
+
can change the decision. An exact
|
|
100
|
+
file path returns exported definitions (or top-level definitions when no
|
|
101
|
+
explicit export surface exists) plus same-file definitions they reference
|
|
102
|
+
and a complete ledger of omitted local definitions. Use
|
|
103
|
+
`--members all` only when the whole file matters. If the command refuses an
|
|
104
|
+
oversized packet, it emitted no partial source; narrow to the exact units
|
|
105
|
+
still needed before deciding whether every split remains necessary.
|
|
106
|
+
- After the map, put known text, symbol, and file-line gaps into one
|
|
107
|
+
`codebaseiq inspect --symbol <symbol> --at <file:line> --view behavior`
|
|
108
|
+
packet. Read its exact selector cardinality, per-channel evidence coverage,
|
|
109
|
+
omission ledger, and query completion. Stop when no named fact remains
|
|
110
|
+
unanswered. Otherwise drill into several relevant omission groups together;
|
|
111
|
+
omit the behavior view only for exact units whose full implementation can
|
|
112
|
+
change the decision, and use `--full` only when all omitted evidence can change it.
|
|
113
|
+
`--full` and `--limit` are mutually exclusive; never combine them.
|
|
114
|
+
- Treat returned, line-numbered source as citation-ready and already read.
|
|
115
|
+
Native tools are for applying edits, running checks, binary content, or a
|
|
116
|
+
specific unsupported gap that codebaseiq has explicitly reported.
|
|
117
|
+
- Do not repeat an unchanged query after context compaction.
|
|
118
|
+
- Do not claim that a caller, route, branch, poller, or consumer is absent from
|
|
119
|
+
a bounded result. Use `--full` only when complete coverage can change a
|
|
120
|
+
decision.
|
|
121
|
+
- Do not claim what every callsite passes unless the `trace` or `evidence`
|
|
122
|
+
claim-support section marks callsite-argument claims eligible. A complete
|
|
123
|
+
call expression contains the callee and every argument through the closing
|
|
124
|
+
delimiter; a bounded context window does not.
|
|
125
|
+
- Search always reports exact match cardinality. Small results list every
|
|
126
|
+
matching path-line identity and owner; broad results stop lower-ranked
|
|
127
|
+
identities before output transport and return a representative manifest plus
|
|
128
|
+
ranked scope commands. There is no transport cursor to drain. Narrow to a
|
|
129
|
+
distinctive literal or one relevant scope; use `search --full` only after
|
|
130
|
+
deliberately narrowing when every remaining source window matters.
|
|
131
|
+
- With an explicit `CODEBASEIQ_SESSION`, a complete source unit, a
|
|
132
|
+
byte-identical exact subset of a prior exact source read, or a graph unit/edge
|
|
133
|
+
may be replaced by a visible receipt from the same index generation. Preview
|
|
134
|
+
coverage never suppresses an exact unit; changed bytes, changed graph
|
|
135
|
+
content, a new generation, or `--reemit` force full evidence.
|
|
136
|
+
- Follow an emitted `Continue exactly:` command until transport is complete.
|
|
137
|
+
Coverage expansion commands are optional drilldowns, not transport pages.
|
|
138
|
+
- Use human output for model reading and `--json --result-only` for programs.
|
|
139
|
+
- Never rerun a successful human command as JSON. Before each drilldown, name
|
|
140
|
+
the still-unanswered fact and stop when none remains; every additional
|
|
141
|
+
reasoning step pays again for the accumulated context.
|
|
142
|
+
- Commit relevant suppression files, but do not create work-state records.
|
|
143
|
+
|
|
144
|
+
## Setup failures
|
|
145
|
+
|
|
146
|
+
Use `codebaseiq doctor` when a query reports that the tool or index is not
|
|
147
|
+
usable. Use `codebaseiq status --capabilities` to see which evidence providers
|
|
148
|
+
are available.
|