ctxtop 4.1.0 → 4.1.1
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/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +21 -18
- package/CHECKSUMS.sha256 +51 -44
- package/LICENSE +27 -27
- package/README.md +90 -56
- package/SECURITY.md +7 -1
- package/assets/hero-demo.svg +1 -1
- package/bin/ctxtop.mjs +267 -54
- package/config/modelCatalog.json +847 -273
- package/hooks/handlers/hookIpcClient.mjs +8 -4
- package/hooks/handlers/post-model-switch.mjs +39 -2
- package/hooks/handlers/post-tool-use-core.mjs +394 -0
- package/hooks/handlers/post-tool-use.mjs +54 -321
- package/hooks/handlers/pre-model-switch.mjs +115 -5
- package/hooks/handlers/pre-tool-use-core.mjs +680 -0
- package/hooks/handlers/pre-tool-use.mjs +61 -571
- package/hooks/handlers/stop-gate.mjs +20 -8
- package/hooks/handlers/user-prompt-submit.mjs +111 -2
- package/hooks/post_tool_use.mjs +17 -4
- package/hooks/pre_tool_use.mjs +84 -54
- package/hooks.json +56 -56
- package/package.json +4 -3
- package/packages/antigravity/package.json +10 -3
- package/packages/antigravity/src/adapter.mjs +109 -0
- package/packages/antigravity/src/index.mjs +7 -1
- package/packages/claude-code/package.json +10 -3
- package/packages/claude-code/src/adapter.mjs +194 -0
- package/packages/claude-code/src/index.mjs +8 -2
- package/packages/claude-code/src/register.js +726 -0
- package/packages/core/package.json +6 -2
- package/packages/core/src/catalog/detectorCatalog.mjs +558 -0
- package/packages/core/src/catalog/index.mjs +1 -0
- package/packages/core/src/catalog/safeguardGuide.mjs +412 -0
- package/packages/core/src/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/core/src/coach/effortShiftDetector.mjs +316 -0
- package/packages/core/src/coach/microSkills.mjs +1 -0
- package/packages/core/src/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/core/src/coach/repoCalibration.mjs +254 -0
- package/packages/core/src/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/core/src/coach/savedQuotaLedger.mjs +527 -0
- package/packages/core/src/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/core/src/coach/stateBatonHydrator.mjs +810 -0
- package/packages/core/src/coach/ttlWatchdog.mjs +464 -0
- package/packages/core/src/config/anthropicModelCatalog.json +607 -0
- package/packages/core/src/config/catalogLoader.mjs +1271 -0
- package/packages/core/src/config/horizonConfig.mjs +1055 -0
- package/packages/core/src/control/callTree.mjs +338 -0
- package/packages/core/src/control/coachLatches.mjs +126 -0
- package/packages/core/src/control/controlStateMachine.mjs +205 -0
- package/packages/core/src/control/index.mjs +49 -0
- package/packages/core/src/control/swarmWorktree.mjs +109 -0
- package/packages/core/src/control/toolSuspension.mjs +197 -0
- package/packages/core/src/diagnostics/drift_guard.mjs +382 -0
- package/packages/core/src/diagnostics/index.mjs +9 -0
- package/packages/core/src/diagnostics/micro_skills.mjs +471 -0
- package/packages/core/src/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/core/src/economics/billingBlocks.mjs +251 -0
- package/packages/core/src/economics/cacheGravity.mjs +371 -0
- package/packages/core/src/economics/cliffBreaker.mjs +256 -0
- package/packages/core/src/economics/driftLatency.mjs +433 -0
- package/packages/core/src/economics/dualTtl.mjs +198 -0
- package/packages/core/src/economics/index.mjs +47 -0
- package/packages/core/src/economics/retentionRadar.mjs +348 -0
- package/packages/core/src/economics/shadowAutoModel.mjs +228 -0
- package/packages/core/src/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/core/src/guards/bucketBGamma.mjs +442 -0
- package/packages/core/src/guards/bucketBHeuristics.mjs +37 -0
- package/packages/core/src/guards/circuitBreakers.mjs +1202 -0
- package/packages/core/src/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/core/src/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/core/src/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/core/src/guards/docIndexCore.mjs +446 -0
- package/packages/core/src/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/core/src/guards/slopsquatGate.mjs +551 -0
- package/packages/core/src/index.js +27 -0
- package/packages/core/src/index.mjs +25 -1
- package/packages/core/src/telemetry/otelExporter.mjs +187 -0
- package/packages/core/src/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/core/src/telemetry/sprintMetrics.mjs +327 -0
- package/packages/core/src/telemetry/swarmTopology.mjs +152 -0
- package/packages/core/src/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/core/src/ui/brailleSparkline.mjs +142 -0
- package/packages/core/src/ui/costRadarSvg.mjs +276 -0
- package/packages/core/src/ui/horizonGrid.mjs +475 -0
- package/packages/core/src/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/core/src/ui/modViews.mjs +1558 -0
- package/packages/core/src/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/core/src/ustf/index.mjs +7 -0
- package/packages/core/src/ustf/normalizer.mjs +512 -0
- package/packages/core/src/ustf/schema.mjs +186 -0
- package/packages/core/src/utils/runtime.mjs +962 -0
- package/packages/engine-node/package.json +6 -2
- package/packages/engine-node/src/db/index.mjs +58 -0
- package/packages/engine-node/src/db/jsonl_fallback.mjs +184 -0
- package/packages/engine-node/src/db/probe.mjs +342 -0
- package/packages/engine-node/src/db/sqlite_wrapper.mjs +122 -0
- package/packages/engine-node/src/index.mjs +11 -1
- package/packages/engine-node/src/ipc/client.mjs +447 -0
- package/packages/engine-node/src/ipc/fast_client.mjs +191 -0
- package/packages/engine-node/src/ipc/index.mjs +24 -0
- package/packages/engine-node/src/ipc/protocol.mjs +177 -0
- package/packages/engine-node/src/ipc/server.mjs +445 -0
- package/packages/engine-node/src/multi_host_mcp.mjs +168 -0
- package/packages/engine-node/src/offloader/index.mjs +6 -0
- package/packages/engine-node/src/offloader/tool_offloader.mjs +241 -0
- package/packages/engine-node/src/rsl/index.mjs +3 -0
- package/packages/engine-node/src/sensors/blindspots.mjs +376 -0
- package/packages/engine-node/src/sensors/git_merge_tree.mjs +223 -0
- package/packages/engine-node/src/sensors/index.mjs +7 -0
- package/packages/engine-node/src/vendor/config/default_flightcheck.json +133 -0
- package/packages/engine-node/src/vendor/config/modelCatalog.json +1359 -0
- package/packages/engine-node/src/vendor/config/platformQuirks.json +19 -0
- package/packages/engine-node/src/vendor/core/atomic_io.mjs +124 -0
- package/packages/engine-node/src/vendor/core/constants.mjs +2150 -0
- package/packages/engine-node/src/vendor/core/doc_indexer.mjs +338 -0
- package/packages/engine-node/src/vendor/core/rsl_clash_auditor.mjs +423 -0
- package/packages/engine-node/src/vendor/core/rsl_distiller.mjs +394 -0
- package/packages/engine-node/src/vendor/core/rsl_ledger.mjs +1029 -0
- package/packages/engine-node/src/vendor/core/rsl_triage.mjs +1051 -0
- package/packages/engine-node/src/vendor/core/shield_manager.mjs +1417 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/index.mjs +49 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/index.mjs +47 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/packages/engine-node/src/vendor/core-isomorphic/index.js +27 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
- package/packages/engine-node/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
- package/packages/mcp/package.json +7 -3
- package/packages/mcp/src/server.mjs +115 -14
- package/packages/mcp/src/vendor/config/default_flightcheck.json +133 -0
- package/packages/mcp/src/vendor/config/modelCatalog.json +1359 -0
- package/packages/mcp/src/vendor/config/platformQuirks.json +19 -0
- package/packages/mcp/src/vendor/core/atomic_io.mjs +124 -0
- package/packages/mcp/src/vendor/core/coach/saved_quota_ledger.mjs +615 -0
- package/packages/mcp/src/vendor/core/constants.mjs +2150 -0
- package/packages/mcp/src/vendor/core/doc_indexer.mjs +338 -0
- package/packages/mcp/src/vendor/core/fts5_output_compressor.mjs +596 -0
- package/packages/mcp/src/vendor/core/hook_diagnostics.mjs +158 -0
- package/packages/mcp/src/vendor/core/paths.mjs +311 -0
- package/packages/mcp/src/vendor/core/session_auditor.mjs +1109 -0
- package/packages/mcp/src/vendor/core/sqlite_client.mjs +289 -0
- package/packages/mcp/src/vendor/core/telemetry/scope_lock_registry.mjs +578 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/index.mjs +49 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/index.mjs +47 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/packages/mcp/src/vendor/core-isomorphic/index.js +27 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
- package/packages/mcp/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
- package/packages/mcp/src/vendor/engine-node/db/probe.mjs +342 -0
- package/packages/mcp/src/vendor/pro/pro_license.mjs +547 -0
- package/packages/pro/package.json +23 -16
- package/packages/pro/src/index.mjs +9 -3
- package/packages/pro/src/pro_license.mjs +547 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -241
- package/packages/pro/workers/polar_webhook_worker.mjs +219 -215
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +482 -44
- package/src/cli/doctor.mjs +11 -2
- package/src/cli/horizon_hud.mjs +31 -15
- package/src/cli/init.mjs +46 -13
- package/src/config/modelCatalog.json +886 -231
- package/src/core/classifier.mjs +25 -11
- package/src/core/coach/circuit_breakers.mjs +84 -6
- package/src/core/coach/task_quota_router.mjs +8 -0
- package/src/core/code_fold_lite.mjs +169 -0
- package/src/core/config.mjs +44 -0
- package/src/core/constants.mjs +175 -12
- package/src/core/detectors_det01_to_16.mjs +44 -3
- package/src/core/fts5_output_compressor.mjs +272 -35
- package/src/core/horizon_config.mjs +42 -0
- package/src/core/parser.mjs +86 -11
- package/src/core/pro_license.mjs +174 -12
- package/src/core/pruner.mjs +7 -146
- package/src/core/quota.mjs +14 -2
- package/src/core/rsl_distiller.mjs +31 -9
- package/src/core/rsl_ledger.mjs +66 -6
- package/src/core/rsl_triage.mjs +159 -17
- package/src/core/session_auditor.mjs +476 -25
- package/src/core/shadow_auto_ledger.mjs +205 -0
- package/src/core/sqlite_client.mjs +10 -4
- package/src/core/subagents.mjs +18 -2
- package/src/core/task_quota_router.mjs +61 -4
- package/src/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/src/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +54 -20
- package/src/core-isomorphic/config/anthropicModelCatalog.json +1 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +6 -3
- package/src/core-isomorphic/config/horizonConfig.mjs +1 -1
- package/src/core-isomorphic/economics/cacheGravity.mjs +3 -1
- package/src/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +1 -1
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +77 -1
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +395 -130
- package/src/core-isomorphic/ui/modViews.mjs +62 -8
- package/src/diagnostics/claudeHookCapabilities.mjs +32 -2
- package/src/diagnostics/doctorEngine.mjs +28 -2
- package/src/engine-node/ipc/fast_client.mjs +191 -0
- package/src/engine-node/ipc/index.mjs +2 -0
- package/src/engine-node/multi_host_mcp.mjs +168 -0
- package/src/hooks/antigravity_rsl_hook.mjs +24 -2
- package/src/hooks/claude_rsl_hook.mjs +22 -2
- package/src/hooks/daemon_hook_bridge.mjs +256 -0
- package/src/hooks/fast_hook_ipc.mjs +295 -0
- package/src/hooks/post_invocation.mjs +37 -597
- package/src/hooks/post_invocation_core.mjs +623 -0
- package/src/hooks/pre_invocation.mjs +103 -1668
- package/src/hooks/pre_invocation_core.mjs +1830 -0
- package/src/utils/sessionCalibration.mjs +52 -5
- package/src/webview/advanced_view.html +34 -18
- package/src/webview/horizon_panel.html +3233 -675
- package/src/webview/simple_view.html +1 -1
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/rsl_triage.mjs
|
|
3
|
+
* Dual-Platform Stage 1 Zero-Token Contrastive Triage & Anti-Reward-Hacking Gate.
|
|
4
|
+
*
|
|
5
|
+
* Supports both Google Antigravity (`SessionStart`, `PostToolUse`, `Stop`, `transcriptPath`,
|
|
6
|
+
* `artifactDirectoryPath`) and Claude Code (`session_id`, `cwd`, `transcript_path`, `PostToolUse`,
|
|
7
|
+
* `Stop`, `SessionEnd`) with <30ms synchronous latency and 0 LLM tokens.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import { atomicWriteFileSync } from './atomic_io.mjs';
|
|
14
|
+
import { RSL_CONSTANTS } from './constants.mjs';
|
|
15
|
+
|
|
16
|
+
const TEST_FILE_EXT_RE = /\.(?:[cm]?[jt]sx?|py|go|rs)$/i;
|
|
17
|
+
const EXCLUDED_DIR_SEGMENTS = new Set([
|
|
18
|
+
'node_modules',
|
|
19
|
+
'.git',
|
|
20
|
+
'.agents',
|
|
21
|
+
'.claude',
|
|
22
|
+
'evaluation_bundles',
|
|
23
|
+
'dist',
|
|
24
|
+
'build',
|
|
25
|
+
'out',
|
|
26
|
+
'.next',
|
|
27
|
+
'coverage'
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const GIT_MINING_RE = /\bgit\s+(?:fsck|cat-file|reflog|verify-pack)\b/i;
|
|
31
|
+
const TEST_CMD_RE = /(?:npm\s+(?:run\s+)?test|node\s+--test|pytest|vitest|jest|cargo\s+test|go\s+test|unittest|mocha|playwright)/i;
|
|
32
|
+
const USER_AUTHORIZED_TEST_REMOVAL_RE = /\b(?:delete|remove|drop|prune|disable|skip)\s+(?:the\s+|these\s+|old\s+|obsolete\s+)?tests?\b/i;
|
|
33
|
+
const USER_CORRECTION_RE = /\b(?:do\s+not|don'?t|never|instead\s+of|stop\s+using|wrong|should\s+be|always\s+use|avoid|rejected)\b/i;
|
|
34
|
+
const CONVERSATIONAL_NON_DIRECTIVE_RE = /\b(?:i\s+(?:don'?t|do\s+not)\s+(?:see|know|have|think|understand|want\s+to\s+wait)|don'?t\s+worry)\b/i;
|
|
35
|
+
const SLASH_COMMAND_ONLY_RE = /^\/(?:plan|browser|compact|handoff|horizon|grill-me|boost|teamwork|learn|evolve|schedule)\b/i;
|
|
36
|
+
const STRONG_DIRECTIVE_CORRECTION_RE = /\b(?:never\s+(?:use|run|modify|edit|read|write|commit|push|skip)|do\s+not\s+(?:use|run|modify|edit|read|write|touch)|instead\s+of|always\s+use|stop\s+using|must\s+(?:never|not|always))\b/i;
|
|
37
|
+
|
|
38
|
+
export const RSL_ANTIGRAVITY_POST_TOOL_MATCHER =
|
|
39
|
+
'run_command|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content';
|
|
40
|
+
export const RSL_CLAUDE_POST_TOOL_MATCHER =
|
|
41
|
+
'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit';
|
|
42
|
+
|
|
43
|
+
const RSL_MUTATING_OR_EXEC_TOOL_RE =
|
|
44
|
+
/^(?:run_command|execute_bash|bash|powershell|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content|edit|multiedit|multi_edit|write|notebookedit)$/i;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Returns true only for shell/command or file-mutating tools needed for RSL contrastive recovery.
|
|
48
|
+
* @param {string} [toolName='']
|
|
49
|
+
* @returns {boolean}
|
|
50
|
+
*/
|
|
51
|
+
export function isMutatingOrExecRslTool(toolName = '') {
|
|
52
|
+
const cleaned = String(toolName || '')
|
|
53
|
+
.trim()
|
|
54
|
+
.replace(/^default_api:/i, '');
|
|
55
|
+
if (!cleaned) return false;
|
|
56
|
+
return RSL_MUTATING_OR_EXEC_TOOL_RE.test(cleaned);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Checks whether the final recorded step in `.agents/telemetry/<sessionId>.rsl_steps.jsonl`
|
|
61
|
+
* matches this event's stepIdx, toolName, failed status, targetFile, and command.
|
|
62
|
+
*
|
|
63
|
+
* @param {object} [rawPayload={}]
|
|
64
|
+
* @param {object} [options={}]
|
|
65
|
+
* @returns {boolean}
|
|
66
|
+
*/
|
|
67
|
+
export function isDuplicateRslStepEvent(rawPayload = {}, options = {}) {
|
|
68
|
+
try {
|
|
69
|
+
const normalized = normalizeRslToolEvent(rawPayload, options);
|
|
70
|
+
if (normalized.stepIdx === null || normalized.stepIdx < 0) return false;
|
|
71
|
+
const stepsPath = path.join(
|
|
72
|
+
normalized.workspaceRoot,
|
|
73
|
+
'.agents',
|
|
74
|
+
'telemetry',
|
|
75
|
+
`${normalized.sessionId}.rsl_steps.jsonl`
|
|
76
|
+
);
|
|
77
|
+
if (!fs.existsSync(stepsPath)) return false;
|
|
78
|
+
const tail = readFileBoundedReadOnly(stepsPath, 4096);
|
|
79
|
+
const lines = tail.split(/\r?\n/).filter((l) => l.trim().length > 0);
|
|
80
|
+
if (lines.length === 0) return false;
|
|
81
|
+
const last = JSON.parse(lines[lines.length - 1]);
|
|
82
|
+
return Boolean(
|
|
83
|
+
last &&
|
|
84
|
+
last.stepIdx === normalized.stepIdx &&
|
|
85
|
+
last.toolName === normalized.toolName &&
|
|
86
|
+
last.failed === normalized.failed &&
|
|
87
|
+
last.targetFile === normalized.targetFile &&
|
|
88
|
+
last.command === normalized.command
|
|
89
|
+
);
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Strips injected prompt wrappers (`<CONTEXT_SUMMARY>`, `<ADDITIONAL_METADATA>`, etc.)
|
|
97
|
+
* and extracts only raw `<USER_REQUEST>` body text before directive classification.
|
|
98
|
+
* @param {string} raw
|
|
99
|
+
* @returns {string}
|
|
100
|
+
*/
|
|
101
|
+
export function extractCleanUserRequestText(raw = '') {
|
|
102
|
+
let text = String(raw || '');
|
|
103
|
+
const userReqMatches = [];
|
|
104
|
+
text.replace(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi, (_, inner) => {
|
|
105
|
+
const cleanInner = String(inner || '').trim();
|
|
106
|
+
if (cleanInner) userReqMatches.push(cleanInner);
|
|
107
|
+
return '';
|
|
108
|
+
});
|
|
109
|
+
if (userReqMatches.length > 0) {
|
|
110
|
+
return userReqMatches.join('\n').trim();
|
|
111
|
+
}
|
|
112
|
+
text = text
|
|
113
|
+
.replace(/<(?:CONTEXT_SUMMARY|ADDITIONAL_METADATA|USER_SETTINGS_CHANGE|SYSTEM_MESSAGE|PLAN|system_context_prefix|user_rules|system-reminder)>[\s\S]*?<\/(?:CONTEXT_SUMMARY|ADDITIONAL_METADATA|USER_SETTINGS_CHANGE|SYSTEM_MESSAGE|PLAN|system_context_prefix|user_rules|system-reminder)>/gi, ' ')
|
|
114
|
+
.replace(/<\/?(?:USER_REQUEST|ARTIFACT|TASK)\b[^>]*>/gi, ' ')
|
|
115
|
+
.replace(/\s+/g, ' ')
|
|
116
|
+
.trim();
|
|
117
|
+
return text;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Filters out casual UI status observations or bare slash commands while preserving real coding directives.
|
|
122
|
+
* @param {string} cleanText
|
|
123
|
+
* @returns {boolean}
|
|
124
|
+
*/
|
|
125
|
+
export function isExplicitDirectiveCorrection(cleanText = '') {
|
|
126
|
+
const txt = String(cleanText || '').trim();
|
|
127
|
+
if (!txt || txt.length < 10) return false;
|
|
128
|
+
if (!USER_CORRECTION_RE.test(txt)) return false;
|
|
129
|
+
if (CONVERSATIONAL_NON_DIRECTIVE_RE.test(txt) && !STRONG_DIRECTIVE_CORRECTION_RE.test(txt)) {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
if (SLASH_COMMAND_ONLY_RE.test(txt) && !STRONG_DIRECTIVE_CORRECTION_RE.test(txt)) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Returns true if a file path points outside the active workspace or inside ephemeral brain/temp storage.
|
|
140
|
+
* @param {string} targetPath
|
|
141
|
+
* @param {string} [workspaceRoot='']
|
|
142
|
+
* @returns {boolean}
|
|
143
|
+
*/
|
|
144
|
+
export function isExternalOrEphemeralPath(targetPath = '', workspaceRoot = '') {
|
|
145
|
+
const raw = String(targetPath || '').trim();
|
|
146
|
+
if (!raw) return false;
|
|
147
|
+
const norm = raw.replace(/\\/g, '/');
|
|
148
|
+
if (
|
|
149
|
+
raw.startsWith('~') ||
|
|
150
|
+
raw.startsWith('..') ||
|
|
151
|
+
/(?:^|\/)\.(?:gemini|claude\/cache|attention-horizon|agents\/telemetry)\//i.test(norm) ||
|
|
152
|
+
/\/antigravity[^/]*\/brain\//i.test(norm)
|
|
153
|
+
) {
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
if (workspaceRoot && (path.isAbsolute(raw) || /^[a-zA-Z]:[\\/]/.test(raw))) {
|
|
157
|
+
const resolvedRoot = path.resolve(workspaceRoot);
|
|
158
|
+
const resolvedTarget = path.resolve(raw);
|
|
159
|
+
const rel = path.relative(resolvedRoot, resolvedTarget);
|
|
160
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
if (/\/AppData\/Local\/Temp\//i.test(norm) || /^\/(?:tmp|var\/folders)\//i.test(norm)) {
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Sanitizes a conversation/session identifier for telemetry filenames.
|
|
173
|
+
* @param {string} [sessionId='default']
|
|
174
|
+
* @returns {string}
|
|
175
|
+
*/
|
|
176
|
+
export function sanitizeRslSessionId(sessionId = 'default') {
|
|
177
|
+
const safe = String(sessionId || 'default')
|
|
178
|
+
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
|
179
|
+
.slice(0, 80);
|
|
180
|
+
return safe || 'default';
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Resolves the workspace root from Antigravity, Claude Code, or CLI options.
|
|
185
|
+
* @param {object} [payload={}]
|
|
186
|
+
* @param {object} [options={}]
|
|
187
|
+
* @returns {string}
|
|
188
|
+
*/
|
|
189
|
+
export function resolveWorkspaceRoot(payload = {}, options = {}) {
|
|
190
|
+
const candidate =
|
|
191
|
+
options.workspaceRoot ||
|
|
192
|
+
options.cwd ||
|
|
193
|
+
(Array.isArray(payload?.workspacePaths) && payload.workspacePaths[0]) ||
|
|
194
|
+
payload?.workspaceRoot ||
|
|
195
|
+
payload?.cwd ||
|
|
196
|
+
process.cwd();
|
|
197
|
+
return path.resolve(String(candidate || process.cwd()));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Strictly excludes `packages/airlock/` and non-source directories from all workspace scans.
|
|
202
|
+
* @param {string} relPath
|
|
203
|
+
* @returns {boolean}
|
|
204
|
+
*/
|
|
205
|
+
export function isExcludedFromRslScan(relPath = '') {
|
|
206
|
+
const posix = String(relPath || '')
|
|
207
|
+
.replace(/\\/g, '/')
|
|
208
|
+
.replace(/^\.\/+/, '')
|
|
209
|
+
.replace(/^\/+/, '');
|
|
210
|
+
if (!posix) return false;
|
|
211
|
+
if (
|
|
212
|
+
posix === 'packages/airlock' ||
|
|
213
|
+
posix.startsWith('packages/airlock/') ||
|
|
214
|
+
posix === '.github/workflows/airlock-schema-canary.yml' ||
|
|
215
|
+
posix.startsWith('docs/HIGHBEAM_AIRLOCK_')
|
|
216
|
+
) {
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
const parts = posix.split('/');
|
|
220
|
+
return parts.some((part) => EXCLUDED_DIR_SEGMENTS.has(part));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function isWorkspaceTestFile(relPosix) {
|
|
224
|
+
if (!TEST_FILE_EXT_RE.test(relPosix)) return false;
|
|
225
|
+
return (
|
|
226
|
+
/\.(?:test|spec)\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
|
|
227
|
+
/(?:^|\/)(?:test|tests|__tests__)\/.+\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
|
|
228
|
+
/_test\.(?:py|go)$/i.test(relPosix)
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Computes SHA-256 + assertion/skip metrics for a single test file (opened strictly read-only `'r'`).
|
|
234
|
+
* @param {string} filePath
|
|
235
|
+
* @returns {{ sha256: string, lfSha256: string, assertionCount: number, skipCount: number, bytes: number } | null}
|
|
236
|
+
*/
|
|
237
|
+
export function computeTestFileMetrics(filePath) {
|
|
238
|
+
let fd;
|
|
239
|
+
try {
|
|
240
|
+
const stat = fs.statSync(filePath);
|
|
241
|
+
if (!stat.isFile() || stat.size > 512 * 1024) return null;
|
|
242
|
+
fd = fs.openSync(filePath, 'r');
|
|
243
|
+
const buf = Buffer.allocUnsafe(stat.size);
|
|
244
|
+
let offset = 0;
|
|
245
|
+
while (offset < stat.size) {
|
|
246
|
+
const n = fs.readSync(fd, buf, offset, stat.size - offset, offset);
|
|
247
|
+
if (n === 0) break;
|
|
248
|
+
offset += n;
|
|
249
|
+
}
|
|
250
|
+
const rawBuf = offset === stat.size ? buf : buf.subarray(0, offset);
|
|
251
|
+
const raw = rawBuf.toString('utf8');
|
|
252
|
+
const normalized = raw.replace(/\r\n/g, '\n');
|
|
253
|
+
const sha256 = crypto.createHash('sha256').update(rawBuf).digest('hex');
|
|
254
|
+
const lfSha256 = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex');
|
|
255
|
+
const assertionCount =
|
|
256
|
+
(normalized.match(/\b(?:assert(?:\.[a-zA-Z0-9_]+)?\s*\(|expect\s*\(|should\.|assert_eq!\s*\()/g) || []).length +
|
|
257
|
+
(normalized.match(/^\s*assert\s+\S+/gm) || []).length;
|
|
258
|
+
const skipCount =
|
|
259
|
+
(normalized.match(/(?:\.(?:skip|todo)\s*\(|\b(?:xit|xdescribe|xtest)\s*\(|(?:@?pytest\.mark\.skip(?:if)?|unittest\.skip)\b|#\[\s*ignore\b)/g) || []).length;
|
|
260
|
+
return { sha256, lfSha256, assertionCount, skipCount, bytes: rawBuf.byteLength };
|
|
261
|
+
} catch {
|
|
262
|
+
return null;
|
|
263
|
+
} finally {
|
|
264
|
+
if (fd !== undefined) {
|
|
265
|
+
try {
|
|
266
|
+
fs.closeSync(fd);
|
|
267
|
+
} catch {
|
|
268
|
+
// Ignore close error
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Snapshots SHA-256 hashes, assertion counts, and skip counts of workspace test files
|
|
276
|
+
* into `.agents/telemetry/<sessionId>.test_hashes.json` (excluding `packages/airlock/`).
|
|
277
|
+
*
|
|
278
|
+
* @param {string} workspaceRoot
|
|
279
|
+
* @param {string} [sessionId='default']
|
|
280
|
+
* @param {object} [options={}]
|
|
281
|
+
*/
|
|
282
|
+
export function snapshotTestSuiteBaseline(workspaceRoot, sessionId = 'default', options = {}) {
|
|
283
|
+
const baseRoot = path.resolve(workspaceRoot || process.cwd());
|
|
284
|
+
const safeSessionId = sanitizeRslSessionId(sessionId);
|
|
285
|
+
const maxFiles = Math.max(1, Number(options.maxFiles || 400));
|
|
286
|
+
const deadlineMs = Date.now() + Number(options.budgetMs || 22);
|
|
287
|
+
const files = {};
|
|
288
|
+
let scannedCount = 0;
|
|
289
|
+
|
|
290
|
+
const walk = (dir, depth) => {
|
|
291
|
+
if (depth > 6 || scannedCount >= maxFiles || Date.now() > deadlineMs) return;
|
|
292
|
+
let entries;
|
|
293
|
+
try {
|
|
294
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
295
|
+
} catch {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
if (scannedCount >= maxFiles || Date.now() > deadlineMs) break;
|
|
300
|
+
const fullPath = path.join(dir, entry.name);
|
|
301
|
+
const relPosix = path.relative(baseRoot, fullPath).replace(/\\/g, '/');
|
|
302
|
+
if (isExcludedFromRslScan(relPosix)) continue;
|
|
303
|
+
if (entry.isDirectory()) {
|
|
304
|
+
walk(fullPath, depth + 1);
|
|
305
|
+
} else if (entry.isFile() && isWorkspaceTestFile(relPosix)) {
|
|
306
|
+
const metrics = computeTestFileMetrics(fullPath);
|
|
307
|
+
if (metrics) {
|
|
308
|
+
files[relPosix] = metrics;
|
|
309
|
+
scannedCount += 1;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
walk(baseRoot, 0);
|
|
316
|
+
const snapshotPath = path.join(baseRoot, '.agents', 'telemetry', `${safeSessionId}.test_hashes.json`);
|
|
317
|
+
const payload = {
|
|
318
|
+
schemaVersion: '2026.11.1',
|
|
319
|
+
sessionId: safeSessionId,
|
|
320
|
+
recordedAt: new Date().toISOString(),
|
|
321
|
+
fileCount: scannedCount,
|
|
322
|
+
files
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
try {
|
|
326
|
+
fs.mkdirSync(path.dirname(snapshotPath), { recursive: true });
|
|
327
|
+
atomicWriteFileSync(snapshotPath, `${JSON.stringify(payload, null, 2)}\n`);
|
|
328
|
+
} catch {
|
|
329
|
+
// Non-fatal on read-only workspaces
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return { snapshotPath, fileCount: scannedCount, files };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function extractTargetFileFromArgs(args, workspaceRoot) {
|
|
336
|
+
if (!args || typeof args !== 'object') return '';
|
|
337
|
+
const raw =
|
|
338
|
+
args.file_path ||
|
|
339
|
+
args.filePath ||
|
|
340
|
+
args.TargetFile ||
|
|
341
|
+
args.AbsolutePath ||
|
|
342
|
+
args.Path ||
|
|
343
|
+
args.path ||
|
|
344
|
+
args.notebook_path ||
|
|
345
|
+
args.targetFile ||
|
|
346
|
+
'';
|
|
347
|
+
if (!raw || typeof raw !== 'string') return '';
|
|
348
|
+
const trimmed = raw.trim();
|
|
349
|
+
if (!trimmed) return '';
|
|
350
|
+
if (path.isAbsolute(trimmed) && workspaceRoot) {
|
|
351
|
+
const rel = path.relative(workspaceRoot, trimmed).replace(/\\/g, '/');
|
|
352
|
+
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
|
|
353
|
+
return rel;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return trimmed.replace(/\\/g, '/');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function extractCommandFromArgs(args) {
|
|
360
|
+
if (!args || typeof args !== 'object') return '';
|
|
361
|
+
const raw = args.CommandLine || args.command || args.cmd || args.script || '';
|
|
362
|
+
return typeof raw === 'string' ? raw.trim() : '';
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function inspectClaudeToolResponseFailure(resp) {
|
|
366
|
+
if (!resp) return { failed: false, errorText: '' };
|
|
367
|
+
if (typeof resp === 'string') {
|
|
368
|
+
const trimmed = resp.trim();
|
|
369
|
+
const isErr = /\b(?:Error|ERR!|FAIL|Exception|Command failed|exit status [1-9]|exit code [1-9])\b/i.test(trimmed);
|
|
370
|
+
return { failed: isErr, errorText: isErr ? trimmed.slice(0, 500) : '' };
|
|
371
|
+
}
|
|
372
|
+
if (typeof resp !== 'object') return { failed: false, errorText: '' };
|
|
373
|
+
|
|
374
|
+
const exitVal = resp.exitCode ?? resp.exit_code ?? resp.returncode;
|
|
375
|
+
const hasNonZeroExit = exitVal !== undefined && exitVal !== null && Number.isFinite(Number(exitVal)) && Number(exitVal) !== 0;
|
|
376
|
+
const stderr = typeof resp.stderr === 'string' ? resp.stderr.trim() : '';
|
|
377
|
+
const errStr = typeof resp.error === 'string' ? resp.error.trim() : (resp.error?.message ? String(resp.error.message) : '');
|
|
378
|
+
const stdoutStr = typeof resp.stdout === 'string' ? resp.stdout.trim() : '';
|
|
379
|
+
const hasStderrErr = Boolean(stderr) && (hasNonZeroExit || /\b(?:Error|ERR!|FAIL|Exception|SyntaxError|TypeError|ENOENT|exit code [1-9])\b/i.test(stderr));
|
|
380
|
+
const failed = Boolean(
|
|
381
|
+
resp.is_error === true ||
|
|
382
|
+
resp.isError === true ||
|
|
383
|
+
resp.succeeded === false ||
|
|
384
|
+
resp.status === 'error' ||
|
|
385
|
+
resp.status === 'failed' ||
|
|
386
|
+
Boolean(errStr) ||
|
|
387
|
+
hasNonZeroExit ||
|
|
388
|
+
hasStderrErr
|
|
389
|
+
);
|
|
390
|
+
|
|
391
|
+
if (!failed) return { failed: false, errorText: '' };
|
|
392
|
+
const detail = [errStr, stderr, hasNonZeroExit ? `exit ${exitVal}` : '', !errStr && !stderr ? stdoutStr : '']
|
|
393
|
+
.filter(Boolean)
|
|
394
|
+
.join(' | ')
|
|
395
|
+
.slice(0, 500);
|
|
396
|
+
return { failed: true, errorText: detail || 'Tool execution failed' };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Normalizes a `PostToolUse` payload from either Google Antigravity or Claude Code.
|
|
401
|
+
*
|
|
402
|
+
* @param {object} [rawPayload={}]
|
|
403
|
+
* @param {object} [options={}]
|
|
404
|
+
* @returns {object}
|
|
405
|
+
*/
|
|
406
|
+
export function normalizeRslToolEvent(rawPayload = {}, options = {}) {
|
|
407
|
+
const workspaceRoot = resolveWorkspaceRoot(rawPayload, options);
|
|
408
|
+
const isClaudeShape = Boolean(
|
|
409
|
+
options.platform === 'claude' ||
|
|
410
|
+
rawPayload.tool_name ||
|
|
411
|
+
rawPayload.session_id ||
|
|
412
|
+
rawPayload.transcript_path
|
|
413
|
+
);
|
|
414
|
+
const platform = options.platform || (isClaudeShape ? 'claude' : 'antigravity');
|
|
415
|
+
const sessionId = sanitizeRslSessionId(
|
|
416
|
+
rawPayload.conversationId || rawPayload.session_id || rawPayload.sessionId || options.sessionId || 'default'
|
|
417
|
+
);
|
|
418
|
+
const toolName = String(
|
|
419
|
+
rawPayload.toolCall?.name || rawPayload.tool_name || rawPayload.toolName || ''
|
|
420
|
+
).trim();
|
|
421
|
+
const args = rawPayload.toolCall?.args || rawPayload.tool_input || rawPayload.toolInput || {};
|
|
422
|
+
const targetFile = extractTargetFileFromArgs(args, workspaceRoot);
|
|
423
|
+
const command = extractCommandFromArgs(args);
|
|
424
|
+
const stepIdx = Number.isFinite(Number(rawPayload.stepIdx ?? rawPayload.step_index))
|
|
425
|
+
? Number(rawPayload.stepIdx ?? rawPayload.step_index)
|
|
426
|
+
: null;
|
|
427
|
+
|
|
428
|
+
let failed = false;
|
|
429
|
+
let errorText = '';
|
|
430
|
+
|
|
431
|
+
if (typeof rawPayload.error === 'string' && rawPayload.error.trim().length > 0) {
|
|
432
|
+
failed = true;
|
|
433
|
+
errorText = rawPayload.error.trim().slice(0, 500);
|
|
434
|
+
} else if (rawPayload.is_error === true || rawPayload.isError === true || rawPayload.succeeded === false) {
|
|
435
|
+
failed = true;
|
|
436
|
+
errorText = String(rawPayload.tool_error || rawPayload.error || 'Tool execution failed').slice(0, 500);
|
|
437
|
+
} else if (
|
|
438
|
+
(rawPayload.exit_code !== undefined && Number(rawPayload.exit_code) !== 0) ||
|
|
439
|
+
(rawPayload.exitCode !== undefined && Number(rawPayload.exitCode) !== 0)
|
|
440
|
+
) {
|
|
441
|
+
failed = true;
|
|
442
|
+
errorText = `exit ${rawPayload.exit_code ?? rawPayload.exitCode}`;
|
|
443
|
+
} else {
|
|
444
|
+
const respCheck = inspectClaudeToolResponseFailure(rawPayload.tool_response ?? rawPayload.toolResponse);
|
|
445
|
+
failed = respCheck.failed;
|
|
446
|
+
errorText = respCheck.errorText;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const isTestRun = TEST_CMD_RE.test(command);
|
|
450
|
+
const isTestPass = isTestRun && !failed;
|
|
451
|
+
const isGitMining = GIT_MINING_RE.test(command);
|
|
452
|
+
|
|
453
|
+
return {
|
|
454
|
+
ts: Date.now(),
|
|
455
|
+
platform,
|
|
456
|
+
sessionId,
|
|
457
|
+
workspaceRoot,
|
|
458
|
+
stepIdx,
|
|
459
|
+
toolName,
|
|
460
|
+
targetFile,
|
|
461
|
+
command: command.slice(0, 300),
|
|
462
|
+
failed,
|
|
463
|
+
errorText,
|
|
464
|
+
isTestRun,
|
|
465
|
+
isTestPass,
|
|
466
|
+
isGitMining
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Records a normalized `PostToolUse` step outcome to `.agents/telemetry/<sessionId>.rsl_steps.jsonl`.
|
|
472
|
+
* Executes in <5ms synchronously.
|
|
473
|
+
*
|
|
474
|
+
* @param {object} [rawPayload={}]
|
|
475
|
+
* @param {object} [options={}]
|
|
476
|
+
*/
|
|
477
|
+
export function recordStepOutcome(rawPayload = {}, options = {}) {
|
|
478
|
+
const normalized = normalizeRslToolEvent(rawPayload, options);
|
|
479
|
+
const stepsPath = path.join(
|
|
480
|
+
normalized.workspaceRoot,
|
|
481
|
+
'.agents',
|
|
482
|
+
'telemetry',
|
|
483
|
+
`${normalized.sessionId}.rsl_steps.jsonl`
|
|
484
|
+
);
|
|
485
|
+
try {
|
|
486
|
+
fs.mkdirSync(path.dirname(stepsPath), { recursive: true });
|
|
487
|
+
fs.appendFileSync(stepsPath, `${JSON.stringify(normalized)}\n`, 'utf8');
|
|
488
|
+
} catch {
|
|
489
|
+
// Never throw from post-tool hook telemetry
|
|
490
|
+
}
|
|
491
|
+
return { ...normalized, stepsPath };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function readFileBoundedReadOnly(filePath, maxBytes = 512 * 1024) {
|
|
495
|
+
let fd;
|
|
496
|
+
try {
|
|
497
|
+
const stat = fs.statSync(filePath);
|
|
498
|
+
if (!stat.isFile()) return '';
|
|
499
|
+
const bytesToRead = Math.min(stat.size, maxBytes);
|
|
500
|
+
const startOffset = Math.max(0, stat.size - bytesToRead);
|
|
501
|
+
fd = fs.openSync(filePath, 'r');
|
|
502
|
+
const buf = Buffer.allocUnsafe(bytesToRead);
|
|
503
|
+
let offset = 0;
|
|
504
|
+
while (offset < bytesToRead) {
|
|
505
|
+
const n = fs.readSync(fd, buf, offset, bytesToRead - offset, startOffset + offset);
|
|
506
|
+
if (n === 0) break;
|
|
507
|
+
offset += n;
|
|
508
|
+
}
|
|
509
|
+
let text = buf.subarray(0, offset).toString('utf8');
|
|
510
|
+
if (startOffset > 0) {
|
|
511
|
+
const nl = text.indexOf('\n');
|
|
512
|
+
if (nl !== -1) text = text.slice(nl + 1);
|
|
513
|
+
}
|
|
514
|
+
return text;
|
|
515
|
+
} catch {
|
|
516
|
+
return '';
|
|
517
|
+
} finally {
|
|
518
|
+
if (fd !== undefined) {
|
|
519
|
+
try {
|
|
520
|
+
fs.closeSync(fd);
|
|
521
|
+
} catch {
|
|
522
|
+
// Ignore
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function readRecordedSteps(workspaceRoot, sessionId) {
|
|
529
|
+
const safeId = sanitizeRslSessionId(sessionId);
|
|
530
|
+
const stepsPath = path.join(workspaceRoot, '.agents', 'telemetry', `${safeId}.rsl_steps.jsonl`);
|
|
531
|
+
if (!fs.existsSync(stepsPath)) return [];
|
|
532
|
+
const raw = readFileBoundedReadOnly(stepsPath, 512 * 1024);
|
|
533
|
+
const steps = [];
|
|
534
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
535
|
+
if (!line.trim()) continue;
|
|
536
|
+
try {
|
|
537
|
+
const parsed = JSON.parse(line);
|
|
538
|
+
if (parsed && typeof parsed === 'object') steps.push(parsed);
|
|
539
|
+
} catch {
|
|
540
|
+
// Skip malformed line
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return steps;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function extractTextFromClaudeContent(content) {
|
|
547
|
+
if (typeof content === 'string') return content;
|
|
548
|
+
if (!Array.isArray(content)) return '';
|
|
549
|
+
return content
|
|
550
|
+
.map((block) => {
|
|
551
|
+
if (typeof block === 'string') return block;
|
|
552
|
+
if (block?.type === 'text') return String(block.text || '');
|
|
553
|
+
return '';
|
|
554
|
+
})
|
|
555
|
+
.filter(Boolean)
|
|
556
|
+
.join('\n');
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function parseTranscriptForRsl(transcriptPath, workspaceRoot, sessionId, platform) {
|
|
560
|
+
if (!transcriptPath || !fs.existsSync(transcriptPath)) {
|
|
561
|
+
return { steps: [], userCorrections: [], prompts: [] };
|
|
562
|
+
}
|
|
563
|
+
const raw = readFileBoundedReadOnly(transcriptPath, 512 * 1024);
|
|
564
|
+
if (!raw) return { steps: [], userCorrections: [], prompts: [] };
|
|
565
|
+
|
|
566
|
+
const steps = [];
|
|
567
|
+
const userCorrections = [];
|
|
568
|
+
const prompts = [];
|
|
569
|
+
const toolUseById = new Map();
|
|
570
|
+
let syntheticIdx = 0;
|
|
571
|
+
|
|
572
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
573
|
+
if (!line.trim()) continue;
|
|
574
|
+
let obj;
|
|
575
|
+
try {
|
|
576
|
+
obj = JSON.parse(line);
|
|
577
|
+
} catch {
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (!obj || typeof obj !== 'object') continue;
|
|
581
|
+
|
|
582
|
+
// 1. Antigravity transcript entries
|
|
583
|
+
if (obj.type === 'USER_INPUT' && typeof obj.content === 'string') {
|
|
584
|
+
const cleanTxt = extractCleanUserRequestText(obj.content);
|
|
585
|
+
if (cleanTxt) {
|
|
586
|
+
prompts.push(cleanTxt);
|
|
587
|
+
if (isExplicitDirectiveCorrection(cleanTxt)) {
|
|
588
|
+
userCorrections.push({
|
|
589
|
+
stepIdx: obj.step_index ?? syntheticIdx,
|
|
590
|
+
text: cleanTxt.slice(0, 400)
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
if (Array.isArray(obj.tool_calls)) {
|
|
597
|
+
for (const tc of obj.tool_calls) {
|
|
598
|
+
const idx = obj.step_index ?? syntheticIdx++;
|
|
599
|
+
const ev = normalizeRslToolEvent(
|
|
600
|
+
{
|
|
601
|
+
conversationId: sessionId,
|
|
602
|
+
workspacePaths: [workspaceRoot],
|
|
603
|
+
toolCall: { name: tc.name, args: tc.args || tc.arguments || {} },
|
|
604
|
+
stepIdx: idx,
|
|
605
|
+
error: tc.error || obj.error || ''
|
|
606
|
+
},
|
|
607
|
+
{ platform }
|
|
608
|
+
);
|
|
609
|
+
steps.push(ev);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// 2. Claude Code JSONL transcript entries
|
|
614
|
+
if (obj.type === 'user' || obj.role === 'user') {
|
|
615
|
+
const msgContent = obj.message?.content ?? obj.content;
|
|
616
|
+
const cleanText = extractCleanUserRequestText(extractTextFromClaudeContent(msgContent));
|
|
617
|
+
if (cleanText) {
|
|
618
|
+
prompts.push(cleanText);
|
|
619
|
+
if (isExplicitDirectiveCorrection(cleanText)) {
|
|
620
|
+
userCorrections.push({
|
|
621
|
+
stepIdx: syntheticIdx,
|
|
622
|
+
text: cleanText.slice(0, 400)
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (Array.isArray(msgContent)) {
|
|
627
|
+
for (const block of msgContent) {
|
|
628
|
+
if (block?.type === 'tool_result') {
|
|
629
|
+
const linked = toolUseById.get(block.tool_use_id) || {};
|
|
630
|
+
const resultText = extractTextFromClaudeContent(block.content) || String(block.content || '');
|
|
631
|
+
const inferredErr =
|
|
632
|
+
Boolean(block.is_error) ||
|
|
633
|
+
(block.is_error === undefined && /^(?:Error:|Exit code [1-9]|Command failed)/im.test(resultText));
|
|
634
|
+
const ev = normalizeRslToolEvent(
|
|
635
|
+
{
|
|
636
|
+
session_id: sessionId,
|
|
637
|
+
cwd: workspaceRoot,
|
|
638
|
+
tool_name: linked.name || block.tool_name || 'Bash',
|
|
639
|
+
tool_input: linked.input || {},
|
|
640
|
+
stepIdx: syntheticIdx++,
|
|
641
|
+
tool_response: {
|
|
642
|
+
is_error: inferredErr,
|
|
643
|
+
error: inferredErr ? resultText : '',
|
|
644
|
+
stderr: inferredErr ? resultText : '',
|
|
645
|
+
stdout: inferredErr ? '' : resultText
|
|
646
|
+
}
|
|
647
|
+
},
|
|
648
|
+
{ platform: 'claude' }
|
|
649
|
+
);
|
|
650
|
+
steps.push(ev);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if (obj.type === 'assistant' || obj.role === 'assistant') {
|
|
657
|
+
const msgContent = obj.message?.content ?? obj.content;
|
|
658
|
+
if (Array.isArray(msgContent)) {
|
|
659
|
+
for (const block of msgContent) {
|
|
660
|
+
if (block?.type === 'tool_use') {
|
|
661
|
+
toolUseById.set(block.id || `u_${syntheticIdx}`, {
|
|
662
|
+
name: block.name,
|
|
663
|
+
input: block.input || {}
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// 3. Direct tool step records inside custom transcripts
|
|
671
|
+
if ((obj.tool_name || obj.toolCall) && obj.type !== 'assistant' && obj.type !== 'user') {
|
|
672
|
+
const ev = normalizeRslToolEvent(
|
|
673
|
+
{
|
|
674
|
+
...obj,
|
|
675
|
+
cwd: obj.cwd || workspaceRoot,
|
|
676
|
+
session_id: obj.session_id || sessionId
|
|
677
|
+
},
|
|
678
|
+
{ platform }
|
|
679
|
+
);
|
|
680
|
+
if (ev.stepIdx === null) ev.stepIdx = syntheticIdx++;
|
|
681
|
+
steps.push(ev);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
return { steps, userCorrections, prompts };
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function scanArtifactDirectoryForSupervision(artifactDirectoryPath) {
|
|
689
|
+
if (!artifactDirectoryPath || !fs.existsSync(artifactDirectoryPath)) {
|
|
690
|
+
return [];
|
|
691
|
+
}
|
|
692
|
+
const comments = [];
|
|
693
|
+
let entries = [];
|
|
694
|
+
try {
|
|
695
|
+
entries = fs.readdirSync(artifactDirectoryPath, { withFileTypes: true });
|
|
696
|
+
} catch {
|
|
697
|
+
return [];
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
for (const entry of entries.slice(0, 30)) {
|
|
701
|
+
if (!entry.isFile() || !/\.(?:md|json|txt)$/i.test(entry.name)) continue;
|
|
702
|
+
const full = path.join(artifactDirectoryPath, entry.name);
|
|
703
|
+
const content = readFileBoundedReadOnly(full, 128 * 1024);
|
|
704
|
+
if (!content) continue;
|
|
705
|
+
|
|
706
|
+
const lines = content.split(/\r?\n/);
|
|
707
|
+
for (let i = 0; i < lines.length; i++) {
|
|
708
|
+
const line = lines[i];
|
|
709
|
+
if (/✗\s*rejected|\[\s*rejected\s*\]|"status"\s*:\s*"rejected"/i.test(line)) {
|
|
710
|
+
const ctx = lines.slice(Math.max(0, i - 1), Math.min(lines.length, i + 3)).join(' ').trim();
|
|
711
|
+
comments.push({
|
|
712
|
+
file: entry.name,
|
|
713
|
+
kind: 'rejected',
|
|
714
|
+
lineNumber: i + 1,
|
|
715
|
+
text: ctx.slice(0, 400)
|
|
716
|
+
});
|
|
717
|
+
} else if (line.includes('💬')) {
|
|
718
|
+
comments.push({
|
|
719
|
+
file: entry.name,
|
|
720
|
+
kind: 'inline_comment',
|
|
721
|
+
lineNumber: i + 1,
|
|
722
|
+
text: line.replace(/\s+/g, ' ').trim().slice(0, 400)
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return comments.slice(0, 10);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Runs EvilGenie & Coding-or-Cheating verification against the SessionStart test baseline.
|
|
732
|
+
*
|
|
733
|
+
* @param {string} workspaceRoot
|
|
734
|
+
* @param {string} sessionId
|
|
735
|
+
* @param {Array<object>} steps
|
|
736
|
+
* @param {string} [promptText='']
|
|
737
|
+
*/
|
|
738
|
+
export function evaluateTestIntegrityGate(workspaceRoot, sessionId, steps = [], promptText = '') {
|
|
739
|
+
const safeId = sanitizeRslSessionId(sessionId);
|
|
740
|
+
const baselinePath = path.join(workspaceRoot, '.agents', 'telemetry', `${safeId}.test_hashes.json`);
|
|
741
|
+
const taintDetails = [];
|
|
742
|
+
const userAuthorizedRemoval = USER_AUTHORIZED_TEST_REMOVAL_RE.test(String(promptText || ''));
|
|
743
|
+
|
|
744
|
+
for (const st of steps) {
|
|
745
|
+
if (st?.isGitMining || GIT_MINING_RE.test(String(st?.command || ''))) {
|
|
746
|
+
taintDetails.push(`git_object_mining: ${String(st?.command || '').slice(0, 120)}`);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
if (fs.existsSync(baselinePath)) {
|
|
751
|
+
try {
|
|
752
|
+
const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
|
|
753
|
+
const files = baseline?.files || {};
|
|
754
|
+
for (const [relPosix, prev] of Object.entries(files)) {
|
|
755
|
+
if (isExcludedFromRslScan(relPosix)) continue;
|
|
756
|
+
const abs = path.join(workspaceRoot, relPosix);
|
|
757
|
+
if (!fs.existsSync(abs)) {
|
|
758
|
+
if (!userAuthorizedRemoval) {
|
|
759
|
+
taintDetails.push(`test_file_deleted: ${relPosix}`);
|
|
760
|
+
}
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
const curr = computeTestFileMetrics(abs);
|
|
764
|
+
if (!curr) continue;
|
|
765
|
+
if (curr.skipCount > Number(prev.skipCount || 0)) {
|
|
766
|
+
taintDetails.push(`test_skip_added: ${relPosix} (${prev.skipCount} -> ${curr.skipCount})`);
|
|
767
|
+
}
|
|
768
|
+
if (curr.assertionCount < Number(prev.assertionCount || 0) && !userAuthorizedRemoval) {
|
|
769
|
+
taintDetails.push(
|
|
770
|
+
`test_assertions_removed: ${relPosix} (${prev.assertionCount} -> ${curr.assertionCount})`
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
} catch {
|
|
775
|
+
// Corrupt baseline should fail open for integrity gate
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
return {
|
|
780
|
+
tainted: taintDetails.length > 0,
|
|
781
|
+
status: taintDetails.length > 0 ? 'TAINTED_REWARD_HACK' : 'CLEAN',
|
|
782
|
+
taintDetails
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function normalizeTerminationReason(rawStopPayload = {}) {
|
|
787
|
+
const raw = String(
|
|
788
|
+
rawStopPayload.terminationReason ?? rawStopPayload.termination_reason ?? ''
|
|
789
|
+
).trim();
|
|
790
|
+
const upper = raw.toUpperCase();
|
|
791
|
+
if (!raw || upper === 'NO_TOOL_CALL' || upper === 'MODEL_STOP' || upper === 'END_TURN') {
|
|
792
|
+
return { raw: raw || 'NO_TOOL_CALL', cleanStop: true, canceled: false };
|
|
793
|
+
}
|
|
794
|
+
if (upper === 'USER_CANCELED' || upper === 'CANCELLED' || upper === 'CANCELED') {
|
|
795
|
+
return { raw, cleanStop: false, canceled: true };
|
|
796
|
+
}
|
|
797
|
+
if (
|
|
798
|
+
upper === 'TERMINAL_STEP_TYPE' ||
|
|
799
|
+
upper === 'INJECTED_RESPONSE' ||
|
|
800
|
+
upper === 'MAX_INVOCATIONS' ||
|
|
801
|
+
upper === 'MAX_STEPS_EXCEEDED'
|
|
802
|
+
) {
|
|
803
|
+
return { raw, cleanStop: upper === 'TERMINAL_STEP_TYPE' || upper === 'INJECTED_RESPONSE', canceled: false };
|
|
804
|
+
}
|
|
805
|
+
return { raw, cleanStop: upper !== 'ERROR', canceled: false };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function stepsMatchTarget(a, b) {
|
|
809
|
+
if (!a || !b) return false;
|
|
810
|
+
if (a.targetFile && b.targetFile && a.targetFile === b.targetFile) return true;
|
|
811
|
+
if (a.toolName && b.toolName && a.toolName === b.toolName) return true;
|
|
812
|
+
return false;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function extractContrastivePairsAndThrash(steps = [], cleanStop = true, workspaceRoot = '') {
|
|
816
|
+
const pairs = [];
|
|
817
|
+
const thrashLoops = [];
|
|
818
|
+
const windowSize = RSL_CONSTANTS.CONTRASTIVE_WINDOW_STEPS;
|
|
819
|
+
|
|
820
|
+
let consecutiveFails = 0;
|
|
821
|
+
let thrashStartIdx = null;
|
|
822
|
+
let thrashTarget = '';
|
|
823
|
+
|
|
824
|
+
for (let i = 0; i < steps.length; i++) {
|
|
825
|
+
const st = steps[i];
|
|
826
|
+
if (st.failed) {
|
|
827
|
+
if (consecutiveFails === 0 || (thrashTarget && (st.targetFile || st.toolName) === thrashTarget)) {
|
|
828
|
+
if (consecutiveFails === 0) {
|
|
829
|
+
thrashStartIdx = st.stepIdx ?? i;
|
|
830
|
+
thrashTarget = st.targetFile || st.toolName;
|
|
831
|
+
}
|
|
832
|
+
consecutiveFails += 1;
|
|
833
|
+
} else {
|
|
834
|
+
consecutiveFails = 1;
|
|
835
|
+
thrashStartIdx = st.stepIdx ?? i;
|
|
836
|
+
thrashTarget = st.targetFile || st.toolName;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// Search 1..windowSize steps ahead for recovery on same tool/file
|
|
840
|
+
const recoverySteps = [];
|
|
841
|
+
let recoveredIdx = -1;
|
|
842
|
+
let validatedByTest = false;
|
|
843
|
+
|
|
844
|
+
for (let j = i + 1; j < steps.length && j <= i + windowSize; j++) {
|
|
845
|
+
const cand = steps[j];
|
|
846
|
+
if (cand.failed) break;
|
|
847
|
+
if (cand.isTestPass) validatedByTest = true;
|
|
848
|
+
if (stepsMatchTarget(st, cand) || cand.isTestPass || recoveredIdx === -1) {
|
|
849
|
+
recoverySteps.push({
|
|
850
|
+
stepIdx: cand.stepIdx ?? j,
|
|
851
|
+
toolName: cand.toolName,
|
|
852
|
+
targetFile: cand.targetFile,
|
|
853
|
+
command: cand.command,
|
|
854
|
+
isTestPass: Boolean(cand.isTestPass)
|
|
855
|
+
});
|
|
856
|
+
if (stepsMatchTarget(st, cand) && recoveredIdx === -1) {
|
|
857
|
+
recoveredIdx = j;
|
|
858
|
+
}
|
|
859
|
+
if (cand.isTestPass && recoveredIdx !== -1) {
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
if (recoveredIdx !== -1) {
|
|
863
|
+
const next = steps[j + 1];
|
|
864
|
+
if (!next || next.failed || (!stepsMatchTarget(st, next) && !next.isTestPass)) {
|
|
865
|
+
break;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (recoveredIdx !== -1 && (validatedByTest || cleanStop)) {
|
|
872
|
+
const pairTarget = st.targetFile || steps[recoveredIdx].targetFile || '';
|
|
873
|
+
if (isExternalOrEphemeralPath(pairTarget, workspaceRoot)) {
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
pairs.push({
|
|
877
|
+
failureStepIdx: st.stepIdx ?? i,
|
|
878
|
+
recoveryStepIdx: steps[recoveredIdx].stepIdx ?? recoveredIdx,
|
|
879
|
+
toolName: st.toolName,
|
|
880
|
+
targetFile: pairTarget,
|
|
881
|
+
command: st.command,
|
|
882
|
+
errorText: st.errorText,
|
|
883
|
+
recoveryAction: steps[recoveredIdx].command || steps[recoveredIdx].targetFile || steps[recoveredIdx].toolName,
|
|
884
|
+
recoverySteps,
|
|
885
|
+
validatedByTest
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
} else {
|
|
889
|
+
if (consecutiveFails >= 3) {
|
|
890
|
+
thrashLoops.push({
|
|
891
|
+
startStepIdx: thrashStartIdx,
|
|
892
|
+
resolvedStepIdx: st.stepIdx ?? i,
|
|
893
|
+
failureCount: consecutiveFails,
|
|
894
|
+
target: thrashTarget,
|
|
895
|
+
resolvedTool: st.toolName
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
consecutiveFails = 0;
|
|
899
|
+
thrashStartIdx = null;
|
|
900
|
+
thrashTarget = '';
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
return { pairs, thrashLoops };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Builds a bounded contrastive post-mortem digest (~2k tokens) from step telemetry,
|
|
909
|
+
* read-only transcripts, and Antigravity artifacts. Fast-exits in <10ms if 0 triggers occurred.
|
|
910
|
+
*
|
|
911
|
+
* @param {object} [rawStopPayload={}]
|
|
912
|
+
* @param {object} [options={}]
|
|
913
|
+
*/
|
|
914
|
+
export function buildContrastiveDigest(rawStopPayload = {}, options = {}) {
|
|
915
|
+
const workspaceRoot = resolveWorkspaceRoot(rawStopPayload, options);
|
|
916
|
+
const platform =
|
|
917
|
+
options.platform ||
|
|
918
|
+
(rawStopPayload.session_id || rawStopPayload.transcript_path ? 'claude' : 'antigravity');
|
|
919
|
+
const sessionId = sanitizeRslSessionId(
|
|
920
|
+
rawStopPayload.conversationId || rawStopPayload.session_id || rawStopPayload.sessionId || options.sessionId || 'default'
|
|
921
|
+
);
|
|
922
|
+
const term = normalizeTerminationReason(rawStopPayload);
|
|
923
|
+
const transcriptPath = rawStopPayload.transcriptPath || rawStopPayload.transcript_path || options.transcriptPath || '';
|
|
924
|
+
const artifactDirectoryPath = rawStopPayload.artifactDirectoryPath || options.artifactDirectoryPath || '';
|
|
925
|
+
|
|
926
|
+
const recordedSteps = readRecordedSteps(workspaceRoot, sessionId);
|
|
927
|
+
const transcriptData = parseTranscriptForRsl(transcriptPath, workspaceRoot, sessionId, platform);
|
|
928
|
+
const steps = recordedSteps.length > 0 ? recordedSteps : transcriptData.steps;
|
|
929
|
+
|
|
930
|
+
const combinedPromptText = [
|
|
931
|
+
String(rawStopPayload.lastUserInput || ''),
|
|
932
|
+
...transcriptData.prompts
|
|
933
|
+
]
|
|
934
|
+
.filter(Boolean)
|
|
935
|
+
.join('\n');
|
|
936
|
+
|
|
937
|
+
const integrity = evaluateTestIntegrityGate(workspaceRoot, sessionId, steps, combinedPromptText);
|
|
938
|
+
|
|
939
|
+
const touchedFiles = Array.from(
|
|
940
|
+
new Set(steps.map((s) => s.targetFile).filter(Boolean))
|
|
941
|
+
);
|
|
942
|
+
const executedTools = Array.from(
|
|
943
|
+
new Set(steps.map((s) => s.toolName).filter(Boolean))
|
|
944
|
+
);
|
|
945
|
+
const unresolvedErrors = steps
|
|
946
|
+
.filter((s) => s.failed)
|
|
947
|
+
.map((s) => ({
|
|
948
|
+
stepIdx: s.stepIdx,
|
|
949
|
+
toolName: s.toolName,
|
|
950
|
+
targetFile: s.targetFile,
|
|
951
|
+
errorText: s.errorText
|
|
952
|
+
}));
|
|
953
|
+
|
|
954
|
+
if (integrity.tainted) {
|
|
955
|
+
return {
|
|
956
|
+
schemaVersion: '2026.11.1',
|
|
957
|
+
sessionId,
|
|
958
|
+
platform,
|
|
959
|
+
workspaceRoot,
|
|
960
|
+
terminationReason: term.raw,
|
|
961
|
+
triggered: false,
|
|
962
|
+
tainted: true,
|
|
963
|
+
status: 'TAINTED_REWARD_HACK',
|
|
964
|
+
taintDetails: integrity.taintDetails,
|
|
965
|
+
contrastivePairs: [],
|
|
966
|
+
artifactComments: [],
|
|
967
|
+
userCorrections: [],
|
|
968
|
+
thrashLoops: [],
|
|
969
|
+
touchedFiles,
|
|
970
|
+
executedTools,
|
|
971
|
+
unresolvedErrors
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
const { pairs, thrashLoops } = extractContrastivePairsAndThrash(steps, term.cleanStop, workspaceRoot);
|
|
976
|
+
const filteredPairs = pairs.filter((p) => !isExternalOrEphemeralPath(p.targetFile, workspaceRoot));
|
|
977
|
+
const filteredThrash = thrashLoops.filter((l) => !isExternalOrEphemeralPath(l.target, workspaceRoot));
|
|
978
|
+
const artifactComments = scanArtifactDirectoryForSupervision(artifactDirectoryPath);
|
|
979
|
+
const userCorrections = transcriptData.userCorrections.slice(0, 8);
|
|
980
|
+
|
|
981
|
+
const hasTriggers =
|
|
982
|
+
!term.canceled &&
|
|
983
|
+
(filteredPairs.length > 0 || artifactComments.length > 0 || userCorrections.length > 0 || filteredThrash.length > 0);
|
|
984
|
+
|
|
985
|
+
if (!hasTriggers) {
|
|
986
|
+
return {
|
|
987
|
+
schemaVersion: '2026.11.1',
|
|
988
|
+
sessionId,
|
|
989
|
+
platform,
|
|
990
|
+
workspaceRoot,
|
|
991
|
+
terminationReason: term.raw,
|
|
992
|
+
triggered: false,
|
|
993
|
+
tainted: false,
|
|
994
|
+
status: 'CLEAN_NO_TRIGGERS',
|
|
995
|
+
taintDetails: [],
|
|
996
|
+
contrastivePairs: [],
|
|
997
|
+
artifactComments: [],
|
|
998
|
+
userCorrections: [],
|
|
999
|
+
thrashLoops: [],
|
|
1000
|
+
touchedFiles,
|
|
1001
|
+
executedTools,
|
|
1002
|
+
unresolvedErrors
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
let digest = {
|
|
1007
|
+
schemaVersion: '2026.11.1',
|
|
1008
|
+
sessionId,
|
|
1009
|
+
platform,
|
|
1010
|
+
workspaceRoot,
|
|
1011
|
+
recordedAt: new Date().toISOString(),
|
|
1012
|
+
terminationReason: term.raw,
|
|
1013
|
+
triggered: true,
|
|
1014
|
+
tainted: false,
|
|
1015
|
+
status: 'READY',
|
|
1016
|
+
taintDetails: [],
|
|
1017
|
+
contrastivePairs: filteredPairs.slice(0, 6),
|
|
1018
|
+
artifactComments: artifactComments.slice(0, 6),
|
|
1019
|
+
userCorrections: userCorrections.slice(0, 6),
|
|
1020
|
+
thrashLoops: filteredThrash.slice(0, 4),
|
|
1021
|
+
touchedFiles: touchedFiles.slice(0, 20),
|
|
1022
|
+
executedTools: executedTools.slice(0, 15),
|
|
1023
|
+
unresolvedErrors: unresolvedErrors.slice(0, 10)
|
|
1024
|
+
};
|
|
1025
|
+
|
|
1026
|
+
// Enforce ~2k token budget ceiling on persisted contrastive digest
|
|
1027
|
+
let serialized = JSON.stringify(digest, null, 2);
|
|
1028
|
+
if (serialized.length > RSL_CONSTANTS.MAX_DIGEST_CHARS) {
|
|
1029
|
+
digest = {
|
|
1030
|
+
...digest,
|
|
1031
|
+
contrastivePairs: digest.contrastivePairs.slice(0, 3),
|
|
1032
|
+
artifactComments: digest.artifactComments.slice(0, 3),
|
|
1033
|
+
userCorrections: digest.userCorrections.slice(0, 3)
|
|
1034
|
+
};
|
|
1035
|
+
serialized = JSON.stringify(digest, null, 2);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
const queueDir = path.join(workspaceRoot, '.agents', 'telemetry', 'rsl_queue');
|
|
1039
|
+
const digestPath = path.join(queueDir, `${sessionId}.digest.json`);
|
|
1040
|
+
try {
|
|
1041
|
+
fs.mkdirSync(queueDir, { recursive: true });
|
|
1042
|
+
atomicWriteFileSync(digestPath, `${serialized}\n`);
|
|
1043
|
+
} catch {
|
|
1044
|
+
// Non-fatal
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
return {
|
|
1048
|
+
...digest,
|
|
1049
|
+
digestPath
|
|
1050
|
+
};
|
|
1051
|
+
}
|