ctxtop 4.0.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 +81 -57
- package/LICENSE +27 -27
- package/README.md +385 -330
- package/SECURITY.md +7 -1
- package/assets/hero-demo.svg +1 -1
- package/bin/ah-statusline.mjs +30 -0
- package/bin/ctxtop.mjs +587 -49
- package/config/default_flightcheck.json +19 -0
- package/config/modelCatalog.json +952 -213
- package/hooks/handlers/compact-lifecycle.mjs +323 -8
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +56 -0
- package/hooks/handlers/hookIpcClient.mjs +8 -4
- package/hooks/handlers/post-model-switch.mjs +148 -0
- package/hooks/handlers/post-tool-use-core.mjs +394 -0
- package/hooks/handlers/post-tool-use.mjs +54 -220
- package/hooks/handlers/pre-model-switch.mjs +933 -24
- package/hooks/handlers/pre-tool-use-core.mjs +680 -0
- package/hooks/handlers/pre-tool-use.mjs +61 -304
- package/hooks/handlers/stop-gate.mjs +310 -12
- package/hooks/handlers/user-prompt-submit.mjs +334 -1
- package/hooks/hooks.json +50 -0
- package/hooks/post_tool_use.mjs +24 -3
- package/hooks/pre_tool_use.mjs +84 -54
- package/hooks/register.js +48 -9
- package/hooks/session_start.mjs +11 -1
- package/hooks/stop.mjs +11 -1
- package/hooks.json +56 -56
- package/package.json +12 -4
- 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 +514 -40
- package/skills/handoff/SKILL.md +8 -0
- package/src/adapters/antigravity/index.mjs +31 -1
- package/src/adapters/claude-code/index.mjs +40 -1
- package/src/cli/doctor.mjs +11 -2
- package/src/cli/horizon_hud.mjs +283 -65
- package/src/cli/init.mjs +46 -13
- package/src/config/modelCatalog.json +952 -213
- package/src/core/bucket_b_runtime.mjs +1200 -0
- 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 +365 -15
- package/src/core/detectors_det01_to_16.mjs +98 -8
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/fts5_output_compressor.mjs +272 -35
- package/src/core/horizon_config.mjs +42 -0
- package/src/core/layer5_hygiene.mjs +118 -0
- package/src/core/parser.mjs +88 -12
- package/src/core/paths.mjs +3 -2
- 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_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +394 -0
- package/src/core/rsl_ledger.mjs +1029 -0
- package/src/core/rsl_triage.mjs +1051 -0
- package/src/core/session_auditor.mjs +1109 -0
- package/src/core/shadow_auto_ledger.mjs +205 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sqlite_client.mjs +10 -4
- package/src/core/subagents.mjs +18 -2
- package/src/core/task_quota_router.mjs +62 -5
- package/src/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
- package/src/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
- package/src/core-isomorphic/config/anthropicModelCatalog.json +405 -1
- package/src/core-isomorphic/config/catalogLoader.mjs +549 -46
- package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +21 -1
- package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
- package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
- package/src/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +1 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +113 -13
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +684 -363
- package/src/core-isomorphic/ui/modViews.mjs +95 -15
- package/src/diagnostics/claudeHookCapabilities.mjs +426 -0
- package/src/diagnostics/doctorEngine.mjs +122 -4
- package/src/engine-node/db/probe.mjs +234 -2
- package/src/engine-node/index.mjs +3 -0
- 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/engine-node/sensors/blindspots.mjs +13 -6
- package/src/hooks/antigravity_rsl_hook.mjs +272 -0
- package/src/hooks/claude_rsl_hook.mjs +308 -0
- 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 -405
- package/src/hooks/post_invocation_core.mjs +623 -0
- package/src/hooks/pre_invocation.mjs +103 -958
- package/src/hooks/pre_invocation_core.mjs +1830 -0
- package/src/hooks/session_start.mjs +39 -1
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/sessionCalibration.mjs +704 -0
- package/src/webview/advanced_view.html +34 -18
- package/src/webview/horizon_panel.html +4191 -625
- package/src/webview/simple_view.html +1 -1
|
@@ -0,0 +1,1558 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/ui/modViews.mjs
|
|
3
|
+
* Multi-Surface UI Renderers for Claude Code Highbeam:
|
|
4
|
+
* 1. `AbovePrompt` Band: 1-line 40-Cell Horizon Bar + active Coach Pill (`OFF | COACH | AUTO_PILOT`)
|
|
5
|
+
* 2. Docked `Pane` (`/horizon`): Strict 5-Box Simple View vertical hierarchy (zero promotional text)
|
|
6
|
+
* 3. `Spinner` Suffix: Compact live status (`· Cache 95% (4m12s) · Saved $1.84`)
|
|
7
|
+
* 4. Terminal `statusLine`: Responsive ANSI single-line bar adapting to 80 / 110 / 144 columns
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
computeHorizonGrid,
|
|
12
|
+
extractHorizonTokens,
|
|
13
|
+
isNoColorEnabled
|
|
14
|
+
} from './horizonGrid.mjs';
|
|
15
|
+
import { resolveEffectiveRates } from '../config/catalogLoader.mjs';
|
|
16
|
+
import {
|
|
17
|
+
computeBreakEvenCachedTokens,
|
|
18
|
+
resolveNaturalDownshiftPeer
|
|
19
|
+
} from '../coach/cacheGravityRouter.mjs';
|
|
20
|
+
import { formatRemainingTtl } from '../coach/ttlWatchdog.mjs';
|
|
21
|
+
import { SAVINGS_BUCKETS, getSavedQuotaReceiptSummary } from '../coach/savedQuotaLedger.mjs';
|
|
22
|
+
import {
|
|
23
|
+
formatRetentionCompact,
|
|
24
|
+
formatRetentionLabel,
|
|
25
|
+
formatDriftCompact,
|
|
26
|
+
formatDriftLabel
|
|
27
|
+
} from '../telemetry/sprintMetrics.mjs';
|
|
28
|
+
import { computeSwarmSummary, formatSwarmCompact } from '../telemetry/swarmTopology.mjs';
|
|
29
|
+
|
|
30
|
+
const ANSI_ESCAPE_REGEX = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Formats seconds into `MM:SS` digital clock notation (e.g. `04:12`, `00:38`).
|
|
34
|
+
* @param {number} seconds
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function formatTtlClock(seconds = 0) {
|
|
38
|
+
const s = Math.max(0, Math.floor(Number(seconds || 0)));
|
|
39
|
+
const mins = Math.floor(s / 60);
|
|
40
|
+
const rem = s % 60;
|
|
41
|
+
return `${String(mins).padStart(2, '0')}:${String(rem).padStart(2, '0')}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Strips ANSI escape sequences to measure exact visible terminal column width.
|
|
46
|
+
* @param {string} text
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
export function stripAnsi(text = '') {
|
|
50
|
+
return String(text || '').replace(ANSI_ESCAPE_REGEX, '');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Truncates an ANSI-styled string to at most `maxCols` visible columns while stepping over
|
|
55
|
+
* `\x1b\[[0-9;]*m` (and CSI) sequences without counting them toward visible width (`ISS-050`).
|
|
56
|
+
* Appends `\x1b[0m` when truncation cuts off while color styling is active.
|
|
57
|
+
*
|
|
58
|
+
* @param {string} ansiStr
|
|
59
|
+
* @param {number} [maxCols=80]
|
|
60
|
+
* @returns {string}
|
|
61
|
+
*/
|
|
62
|
+
export function truncateAnsiVisible(ansiStr = '', maxCols = 80) {
|
|
63
|
+
const str = String(ansiStr || '');
|
|
64
|
+
const limit = Math.max(0, Math.floor(Number(maxCols ?? 80)));
|
|
65
|
+
if (limit === 0) return '';
|
|
66
|
+
if (stripAnsi(str).length <= limit) return str;
|
|
67
|
+
|
|
68
|
+
const csiHeadRegex = /^\x1b\[[0-?]*[ -/]*[@-~]/;
|
|
69
|
+
let out = '';
|
|
70
|
+
let visible = 0;
|
|
71
|
+
let idx = 0;
|
|
72
|
+
let colorActive = false;
|
|
73
|
+
|
|
74
|
+
while (idx < str.length && visible < limit) {
|
|
75
|
+
if (str.charCodeAt(idx) === 0x1b) {
|
|
76
|
+
const match = csiHeadRegex.exec(str.slice(idx));
|
|
77
|
+
if (match) {
|
|
78
|
+
const seq = match[0];
|
|
79
|
+
out += seq;
|
|
80
|
+
if (seq === '\x1b[0m' || seq === '\x1b[m') {
|
|
81
|
+
colorActive = false;
|
|
82
|
+
} else if (seq.endsWith('m')) {
|
|
83
|
+
colorActive = true;
|
|
84
|
+
}
|
|
85
|
+
idx += seq.length;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const cp = str.codePointAt(idx);
|
|
90
|
+
const step = cp > 0xffff ? 2 : 1;
|
|
91
|
+
out += str.slice(idx, idx + step);
|
|
92
|
+
visible += 1;
|
|
93
|
+
idx += step;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (colorActive && !out.endsWith('\x1b[0m')) {
|
|
97
|
+
out += '\x1b[0m';
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Clamps a plain-text line to at most `maxCols` visible columns.
|
|
104
|
+
* @param {string} text
|
|
105
|
+
* @param {number} maxCols
|
|
106
|
+
* @returns {string}
|
|
107
|
+
*/
|
|
108
|
+
function clampPlainLine(text = '', maxCols = 80) {
|
|
109
|
+
const str = String(text || '');
|
|
110
|
+
if (str.length <= maxCols) return str;
|
|
111
|
+
if (maxCols <= 1) return str.slice(0, maxCols);
|
|
112
|
+
return `${str.slice(0, maxCols - 1)}…`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Formats a scale tick label (`0k`, `50k`, `100k`, `200k`, `500k`, `1M`).
|
|
117
|
+
* @param {number} tokens
|
|
118
|
+
* @returns {string}
|
|
119
|
+
*/
|
|
120
|
+
function formatScaleTickLabel(tokens = 0) {
|
|
121
|
+
const n = Math.max(0, Math.round(Number(tokens || 0)));
|
|
122
|
+
if (n === 0) return '0k';
|
|
123
|
+
if (n >= 1_000_000) {
|
|
124
|
+
const m = n / 1_000_000;
|
|
125
|
+
return Number.isInteger(m) ? `${m}M` : `${Number(m.toFixed(2))}M`;
|
|
126
|
+
}
|
|
127
|
+
if (n >= 1_000) {
|
|
128
|
+
const k = n / 1_000;
|
|
129
|
+
return Number.isInteger(k) ? `${k}k` : `${Number(k.toFixed(1))}k`;
|
|
130
|
+
}
|
|
131
|
+
return String(n);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Builds a Tufte scale-tick ruler row (`0k ··· midpoint ··· ceiling`) aligned to `barSpan` columns (`ISS-050`).
|
|
136
|
+
* @param {number} ceilingTokens
|
|
137
|
+
* @param {number} [barSpan=42]
|
|
138
|
+
* @returns {string}
|
|
139
|
+
*/
|
|
140
|
+
export function buildScaleTickRuler(ceilingTokens = 200000, barSpan = 42) {
|
|
141
|
+
const left = '0k';
|
|
142
|
+
const mid = formatScaleTickLabel(Math.round(ceilingTokens / 2));
|
|
143
|
+
const right = formatScaleTickLabel(ceilingTokens);
|
|
144
|
+
const minPlain = `${left} · ${mid} · ${right}`;
|
|
145
|
+
if (barSpan <= minPlain.length) {
|
|
146
|
+
return minPlain;
|
|
147
|
+
}
|
|
148
|
+
const totalDots = Math.max(2, barSpan - left.length - mid.length - right.length - 4);
|
|
149
|
+
const leftDots = Math.max(1, Math.floor(totalDots / 2));
|
|
150
|
+
const rightDots = Math.max(1, totalDots - leftDots);
|
|
151
|
+
return `${left} ${'·'.repeat(leftDots)} ${mid} ${'·'.repeat(rightDots)} ${right}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Formats token counts compactly (e.g. `0`, `950`, `45.0k`, `90.0k`, `210.0k`, `1.0M`).
|
|
156
|
+
* @param {number} tokens
|
|
157
|
+
* @returns {string}
|
|
158
|
+
*/
|
|
159
|
+
export function formatTokensCompact(tokens = 0) {
|
|
160
|
+
const n = Math.max(0, Number(tokens || 0));
|
|
161
|
+
if (n >= 1000000) {
|
|
162
|
+
return `${(n / 1000000).toFixed(2).replace(/\.00$/, '')}M`;
|
|
163
|
+
}
|
|
164
|
+
if (n >= 1000) {
|
|
165
|
+
const k = n / 1000;
|
|
166
|
+
return `${k >= 100 ? Math.round(k) : Number(k.toFixed(1))}k`;
|
|
167
|
+
}
|
|
168
|
+
return String(Math.round(n));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Formats seconds into compact `XmYs` (e.g. `4m12s`, `38s`, `0s`).
|
|
173
|
+
* @param {number} seconds
|
|
174
|
+
* @returns {string}
|
|
175
|
+
*/
|
|
176
|
+
export function formatDurationCompact(seconds = 0) {
|
|
177
|
+
const s = Math.max(0, Math.floor(Number(seconds || 0)));
|
|
178
|
+
const mins = Math.floor(s / 60);
|
|
179
|
+
const rem = s % 60;
|
|
180
|
+
if (mins > 0) {
|
|
181
|
+
return `${mins}m${String(rem).padStart(2, '0')}s`;
|
|
182
|
+
}
|
|
183
|
+
return `${rem}s`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Formats USD amount (`$0.00`, `$1.84`).
|
|
188
|
+
* @param {number} usd
|
|
189
|
+
* @returns {string}
|
|
190
|
+
*/
|
|
191
|
+
export function formatUsd(usd = 0) {
|
|
192
|
+
const val = Math.max(0, Number(usd || 0));
|
|
193
|
+
return `$${val.toFixed(2)}`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Computes live cache hit percentage, remaining TTL seconds, and total saved USD/tokens
|
|
198
|
+
* from telemetry state, optional TTL tick, and optional ledger summary.
|
|
199
|
+
*
|
|
200
|
+
* @param {object} [state={}]
|
|
201
|
+
* @param {object} [options={}]
|
|
202
|
+
*/
|
|
203
|
+
export function deriveSurfaceMetrics(state = {}, options = {}) {
|
|
204
|
+
const nowMs = options.nowMs || Date.now();
|
|
205
|
+
const cw = state.contextWindow || {};
|
|
206
|
+
const pc = state.promptCache || {};
|
|
207
|
+
const roi = state.cacheRoi || {};
|
|
208
|
+
const cumulative = state.cumulative || {};
|
|
209
|
+
const extracted = extractHorizonTokens(state);
|
|
210
|
+
|
|
211
|
+
const totalInputTokens = Math.max(
|
|
212
|
+
0,
|
|
213
|
+
Number(
|
|
214
|
+
cw.totalInputTokens ??
|
|
215
|
+
state.totalInputTokens ??
|
|
216
|
+
state.totalTokens ??
|
|
217
|
+
extracted.totalInputTokens ??
|
|
218
|
+
0
|
|
219
|
+
)
|
|
220
|
+
);
|
|
221
|
+
const warmPrefixTokens = Math.max(
|
|
222
|
+
0,
|
|
223
|
+
Number(
|
|
224
|
+
cw.warmPrefixTokens ??
|
|
225
|
+
cw.cachedTokens ??
|
|
226
|
+
state.cachedTokens ??
|
|
227
|
+
state.cacheReadTokens ??
|
|
228
|
+
extracted.cachedHistoryTokens ??
|
|
229
|
+
0
|
|
230
|
+
)
|
|
231
|
+
);
|
|
232
|
+
const cacheWriteTokens = Math.max(
|
|
233
|
+
0,
|
|
234
|
+
Number(
|
|
235
|
+
cw.cacheWriteTokens ??
|
|
236
|
+
cw.lastWriteTokens ??
|
|
237
|
+
state.cacheWriteTokens ??
|
|
238
|
+
state.lastWriteTokens ??
|
|
239
|
+
0
|
|
240
|
+
)
|
|
241
|
+
);
|
|
242
|
+
const hasExplicitCacheRead =
|
|
243
|
+
cw.cacheReadTokens !== undefined || state.cacheReadTokens !== undefined;
|
|
244
|
+
const cacheReadTokens = hasExplicitCacheRead
|
|
245
|
+
? Math.max(0, Number(cw.cacheReadTokens ?? state.cacheReadTokens ?? 0))
|
|
246
|
+
: Math.max(0, warmPrefixTokens - cacheWriteTokens);
|
|
247
|
+
|
|
248
|
+
const cachedTokens = warmPrefixTokens;
|
|
249
|
+
|
|
250
|
+
// ISS-006: Check typeof roi.cacheHitRatio === 'number' (including 0, NEVER > 0!) when ROI was evaluated,
|
|
251
|
+
// and fall back to cacheReadTokens / totalInputTokens so Turn-1 cold writes render Cache 0%
|
|
252
|
+
const hasEvaluatedRoi =
|
|
253
|
+
typeof roi.cacheHitRatio === 'number' &&
|
|
254
|
+
(state.lastSource !== 'init' || roi.cacheHitRatio > 0 || Number(roi.actualCacheSpendUSD || 0) > 0);
|
|
255
|
+
const hitRatio = hasEvaluatedRoi
|
|
256
|
+
? roi.cacheHitRatio
|
|
257
|
+
: totalInputTokens > 0
|
|
258
|
+
? cacheReadTokens / totalInputTokens
|
|
259
|
+
: 0;
|
|
260
|
+
const cacheHitPct = Math.max(0, Math.min(100, Math.round(hitRatio * 100)));
|
|
261
|
+
|
|
262
|
+
let parsedExpiresAtMs = null;
|
|
263
|
+
if (typeof pc.expiresAt === 'number' && Number.isFinite(pc.expiresAt)) {
|
|
264
|
+
parsedExpiresAtMs = pc.expiresAt < 1e11 ? pc.expiresAt * 1000 : pc.expiresAt;
|
|
265
|
+
} else if (typeof pc.expiresAt === 'string' && pc.expiresAt.trim()) {
|
|
266
|
+
const parsed = Date.parse(pc.expiresAt);
|
|
267
|
+
if (!Number.isNaN(parsed)) parsedExpiresAtMs = parsed;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const explicitTtlOpt =
|
|
271
|
+
options.ttlRemainingSeconds ??
|
|
272
|
+
options.ttlRemainingSec ??
|
|
273
|
+
state.ttlRemainingSeconds ??
|
|
274
|
+
state.ttlRemainingSec ??
|
|
275
|
+
pc.ttlRemainingSec;
|
|
276
|
+
|
|
277
|
+
const hasExplicitTtlField =
|
|
278
|
+
typeof explicitTtlOpt === 'number' ||
|
|
279
|
+
(options.ttlTick && typeof options.ttlTick.remainingSeconds === 'number') ||
|
|
280
|
+
parsedExpiresAtMs !== null ||
|
|
281
|
+
typeof pc.ttlSeconds === 'number' ||
|
|
282
|
+
typeof state.ttlSeconds === 'number';
|
|
283
|
+
|
|
284
|
+
const hasExplicitWarm = typeof pc.warm === 'boolean' || typeof state.cacheWarm === 'boolean';
|
|
285
|
+
const explicitWarmVal = typeof pc.warm === 'boolean' ? pc.warm : Boolean(state.cacheWarm);
|
|
286
|
+
|
|
287
|
+
let remainingSeconds = 0;
|
|
288
|
+
if (typeof explicitTtlOpt === 'number') {
|
|
289
|
+
remainingSeconds = Math.max(0, Math.floor(explicitTtlOpt));
|
|
290
|
+
} else if (options.ttlTick && typeof options.ttlTick.remainingSeconds === 'number') {
|
|
291
|
+
remainingSeconds = Math.max(0, Math.floor(options.ttlTick.remainingSeconds));
|
|
292
|
+
} else if (parsedExpiresAtMs !== null) {
|
|
293
|
+
remainingSeconds = Math.max(0, Math.floor((parsedExpiresAtMs - nowMs) / 1000));
|
|
294
|
+
} else if (typeof pc.ttlSeconds === 'number') {
|
|
295
|
+
remainingSeconds = Math.max(0, Math.floor(pc.ttlSeconds));
|
|
296
|
+
} else if (typeof state.ttlSeconds === 'number') {
|
|
297
|
+
remainingSeconds = Math.max(0, Math.floor(state.ttlSeconds));
|
|
298
|
+
} else if (!hasExplicitTtlField && hasExplicitWarm && explicitWarmVal) {
|
|
299
|
+
remainingSeconds = pc.ttlTier === '1h' ? 3600 : 300;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ISS-027: Never allow cacheWarm = true when remainingSeconds <= 0!
|
|
303
|
+
const cacheWarm = hasExplicitWarm
|
|
304
|
+
? Boolean(explicitWarmVal && remainingSeconds > 0)
|
|
305
|
+
: Boolean(warmPrefixTokens > 0 && remainingSeconds > 0);
|
|
306
|
+
if (!cacheWarm) {
|
|
307
|
+
remainingSeconds = 0;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const amberAlert = Boolean(
|
|
311
|
+
cacheWarm &&
|
|
312
|
+
(options.ttlTick?.amberAlertActive ||
|
|
313
|
+
(remainingSeconds > 0 && remainingSeconds <= 45 && cachedTokens >= 25000))
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
const ledgerSummary =
|
|
317
|
+
options.ledgerSummary ||
|
|
318
|
+
(options.includeDiskLedger !== false
|
|
319
|
+
? getSavedQuotaReceiptSummary({
|
|
320
|
+
...options,
|
|
321
|
+
activeSessionId: state.sessionId || options.sessionId || 'default'
|
|
322
|
+
})
|
|
323
|
+
: null);
|
|
324
|
+
|
|
325
|
+
const ledgerTokens = Math.max(0, Number(ledgerSummary?.totalSavedTokens || 0));
|
|
326
|
+
const ledgerUSD = Math.max(0, Number(ledgerSummary?.totalSavedUSD || 0));
|
|
327
|
+
const sessionNetSavingsUSD = Math.max(
|
|
328
|
+
0,
|
|
329
|
+
Number(cumulative.netCacheSavingsUSD ?? roi.netCacheSavingsUSD ?? 0)
|
|
330
|
+
);
|
|
331
|
+
const liveSessionCacheReadTokens = Math.max(
|
|
332
|
+
0,
|
|
333
|
+
Math.round(Number(cumulative.cacheReadTokens ?? state.savedTokensTotal ?? 0))
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
// Subagent isolated tokens from Task/Agent workers in state.subagents
|
|
337
|
+
let liveSubagentIsolatedTokens = 0;
|
|
338
|
+
if (state.subagents && typeof state.subagents === 'object') {
|
|
339
|
+
for (const worker of Object.values(state.subagents)) {
|
|
340
|
+
liveSubagentIsolatedTokens += Math.max(0, Math.round(Number(worker?.totalTokens || 0)));
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const activeRatesForSub = resolveEffectiveRates(
|
|
344
|
+
state.rawModelId || state.modelId || state.model || 'claude-sonnet-5-5',
|
|
345
|
+
totalInputTokens,
|
|
346
|
+
options
|
|
347
|
+
);
|
|
348
|
+
const liveSubagentIsolatedUSD =
|
|
349
|
+
activeRatesForSub && !activeRatesForSub.unknownModel && Number.isFinite(activeRatesForSub.inputPer1M)
|
|
350
|
+
? Number(((liveSubagentIsolatedTokens / 1_000_000) * activeRatesForSub.inputPer1M).toFixed(6))
|
|
351
|
+
: 0;
|
|
352
|
+
|
|
353
|
+
// Use explicit options.savedUSD / options.savedTokens if passed, else max of ledger + session
|
|
354
|
+
const savedUSD =
|
|
355
|
+
typeof options.savedUSD === 'number'
|
|
356
|
+
? Math.max(0, options.savedUSD)
|
|
357
|
+
: Number(Math.max(ledgerUSD, sessionNetSavingsUSD).toFixed(2));
|
|
358
|
+
const savedTokens =
|
|
359
|
+
typeof options.savedTokens === 'number'
|
|
360
|
+
? Math.max(0, Math.round(options.savedTokens))
|
|
361
|
+
: Math.max(ledgerTokens, liveSessionCacheReadTokens);
|
|
362
|
+
|
|
363
|
+
const rawSessionTokens = Math.max(
|
|
364
|
+
Number(ledgerSummary?.sessionSavedTokens || 0),
|
|
365
|
+
liveSessionCacheReadTokens + liveSubagentIsolatedTokens,
|
|
366
|
+
typeof options.savedTokens === 'number' ? Math.max(0, Math.round(options.savedTokens)) : 0
|
|
367
|
+
);
|
|
368
|
+
const rawSessionUSD = Math.max(
|
|
369
|
+
Number(ledgerSummary?.sessionSavedUSD || 0),
|
|
370
|
+
sessionNetSavingsUSD + liveSubagentIsolatedUSD,
|
|
371
|
+
typeof options.savedUSD === 'number' ? Math.max(0, options.savedUSD) : 0
|
|
372
|
+
);
|
|
373
|
+
const sessionSavedTokens = Math.max(0, Math.round(options.sessionSavedTokens ?? rawSessionTokens));
|
|
374
|
+
const sessionSavedUSD = Number(
|
|
375
|
+
Math.max(0, Number(options.sessionSavedUSD ?? rawSessionUSD)).toFixed(2)
|
|
376
|
+
);
|
|
377
|
+
const workspace30dSavedTokens = Math.max(
|
|
378
|
+
sessionSavedTokens,
|
|
379
|
+
savedTokens,
|
|
380
|
+
Math.round(Number(options.workspace30dSavedTokens ?? ledgerSummary?.workspace30dSavedTokens ?? 0))
|
|
381
|
+
);
|
|
382
|
+
const workspace30dSavedUSD = Number(
|
|
383
|
+
Math.max(
|
|
384
|
+
sessionSavedUSD,
|
|
385
|
+
savedUSD,
|
|
386
|
+
Number(options.workspace30dSavedUSD ?? ledgerSummary?.workspace30dSavedUSD ?? 0)
|
|
387
|
+
).toFixed(2)
|
|
388
|
+
);
|
|
389
|
+
|
|
390
|
+
// Build 5-category savings breakdown combining ledger + live session telemetry
|
|
391
|
+
const baseCats = ledgerSummary?.categories || {};
|
|
392
|
+
const savingsCategories = {
|
|
393
|
+
cacheReadDiscount: {
|
|
394
|
+
id: 'cacheReadDiscount',
|
|
395
|
+
label: SAVINGS_BUCKETS.cacheReadDiscount.label,
|
|
396
|
+
shortLabel: SAVINGS_BUCKETS.cacheReadDiscount.shortLabel,
|
|
397
|
+
savedTokens: Math.max(
|
|
398
|
+
Number(baseCats.cacheReadDiscount?.savedTokens || 0),
|
|
399
|
+
liveSessionCacheReadTokens
|
|
400
|
+
),
|
|
401
|
+
savedUSD: Number(
|
|
402
|
+
Math.max(
|
|
403
|
+
Number(baseCats.cacheReadDiscount?.savedUSD || 0),
|
|
404
|
+
sessionNetSavingsUSD
|
|
405
|
+
).toFixed(4)
|
|
406
|
+
),
|
|
407
|
+
count: Math.max(
|
|
408
|
+
Number(baseCats.cacheReadDiscount?.count || 0),
|
|
409
|
+
liveSessionCacheReadTokens > 0 ? Math.max(1, Number(state.turnsCompleted || 1)) : 0
|
|
410
|
+
)
|
|
411
|
+
},
|
|
412
|
+
prefixBustAvoided: {
|
|
413
|
+
id: 'prefixBustAvoided',
|
|
414
|
+
label: SAVINGS_BUCKETS.prefixBustAvoided.label,
|
|
415
|
+
shortLabel: SAVINGS_BUCKETS.prefixBustAvoided.shortLabel,
|
|
416
|
+
savedTokens: Math.max(0, Number(baseCats.prefixBustAvoided?.savedTokens || 0)),
|
|
417
|
+
savedUSD: Number(Math.max(0, Number(baseCats.prefixBustAvoided?.savedUSD || 0)).toFixed(4)),
|
|
418
|
+
count: Math.max(0, Number(baseCats.prefixBustAvoided?.count || 0))
|
|
419
|
+
},
|
|
420
|
+
toolOutputCompressed: {
|
|
421
|
+
id: 'toolOutputCompressed',
|
|
422
|
+
label: SAVINGS_BUCKETS.toolOutputCompressed.label,
|
|
423
|
+
shortLabel: SAVINGS_BUCKETS.toolOutputCompressed.shortLabel,
|
|
424
|
+
savedTokens: Math.max(0, Number(baseCats.toolOutputCompressed?.savedTokens || 0)),
|
|
425
|
+
savedUSD: Number(Math.max(0, Number(baseCats.toolOutputCompressed?.savedUSD || 0)).toFixed(4)),
|
|
426
|
+
count: Math.max(0, Number(baseCats.toolOutputCompressed?.count || 0))
|
|
427
|
+
},
|
|
428
|
+
loopAndReadGuarded: {
|
|
429
|
+
id: 'loopAndReadGuarded',
|
|
430
|
+
label: SAVINGS_BUCKETS.loopAndReadGuarded.label,
|
|
431
|
+
shortLabel: SAVINGS_BUCKETS.loopAndReadGuarded.shortLabel,
|
|
432
|
+
savedTokens: Math.max(0, Number(baseCats.loopAndReadGuarded?.savedTokens || 0)),
|
|
433
|
+
savedUSD: Number(Math.max(0, Number(baseCats.loopAndReadGuarded?.savedUSD || 0)).toFixed(4)),
|
|
434
|
+
count: Math.max(0, Number(baseCats.loopAndReadGuarded?.count || 0))
|
|
435
|
+
},
|
|
436
|
+
subagentIsolated: {
|
|
437
|
+
id: 'subagentIsolated',
|
|
438
|
+
label: SAVINGS_BUCKETS.subagentIsolated.label,
|
|
439
|
+
shortLabel: SAVINGS_BUCKETS.subagentIsolated.shortLabel,
|
|
440
|
+
savedTokens: Math.max(
|
|
441
|
+
Number(baseCats.subagentIsolated?.savedTokens || 0),
|
|
442
|
+
liveSubagentIsolatedTokens
|
|
443
|
+
),
|
|
444
|
+
savedUSD: Number(
|
|
445
|
+
Math.max(
|
|
446
|
+
Number(baseCats.subagentIsolated?.savedUSD || 0),
|
|
447
|
+
liveSubagentIsolatedUSD
|
|
448
|
+
).toFixed(4)
|
|
449
|
+
),
|
|
450
|
+
count: Math.max(
|
|
451
|
+
Number(baseCats.subagentIsolated?.count || 0),
|
|
452
|
+
liveSubagentIsolatedTokens > 0 ? Object.keys(state.subagents || {}).length : 0
|
|
453
|
+
)
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
let topSavingsDriver = savingsCategories.cacheReadDiscount;
|
|
458
|
+
for (const bucket of Object.values(savingsCategories)) {
|
|
459
|
+
if (
|
|
460
|
+
bucket.savedTokens > topSavingsDriver.savedTokens ||
|
|
461
|
+
(bucket.savedTokens === topSavingsDriver.savedTokens &&
|
|
462
|
+
bucket.savedUSD > topSavingsDriver.savedUSD)
|
|
463
|
+
) {
|
|
464
|
+
topSavingsDriver = bucket;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const flightMode = String(
|
|
469
|
+
options.flightMode || state.flightMode || 'COACH'
|
|
470
|
+
).toUpperCase();
|
|
471
|
+
|
|
472
|
+
const ttlTier = pc.ttlTier === '1h' ? '1h' : '5m';
|
|
473
|
+
let breakEvenReadsPerWrite = 0.263;
|
|
474
|
+
if (typeof roi.breakEvenReadsPerWrite === 'number' && roi.breakEvenReadsPerWrite > 0 && state.lastSource !== 'init') {
|
|
475
|
+
breakEvenReadsPerWrite = roi.breakEvenReadsPerWrite;
|
|
476
|
+
} else {
|
|
477
|
+
const activeRates = resolveEffectiveRates(
|
|
478
|
+
state.rawModelId || state.modelId || state.model || 'claude-sonnet-5-5',
|
|
479
|
+
totalInputTokens,
|
|
480
|
+
options
|
|
481
|
+
);
|
|
482
|
+
if (activeRates && !activeRates.unknownModel && activeRates.multipliers) {
|
|
483
|
+
const mWrite =
|
|
484
|
+
ttlTier === '1h' ? activeRates.multipliers.write1h : activeRates.multipliers.write5m;
|
|
485
|
+
const mRead = activeRates.multipliers.read;
|
|
486
|
+
breakEvenReadsPerWrite = Number(((mWrite - 1) / (1 - mRead)).toFixed(3));
|
|
487
|
+
} else {
|
|
488
|
+
breakEvenReadsPerWrite = null;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const sessionFiveMinRoiTarget = Number(roi.sessionFiveMinRoiTarget || 1.39);
|
|
492
|
+
|
|
493
|
+
const hasEvaluatedRwRatio =
|
|
494
|
+
typeof roi.readsPerWriteRatio === 'number' &&
|
|
495
|
+
(state.lastSource !== 'init' || roi.readsPerWriteRatio > 0 || Number(roi.actualCacheSpendUSD || 0) > 0);
|
|
496
|
+
const derivedRwRatio = hasEvaluatedRwRatio
|
|
497
|
+
? roi.readsPerWriteRatio
|
|
498
|
+
: cacheWriteTokens > 0
|
|
499
|
+
? cacheReadTokens / cacheWriteTokens
|
|
500
|
+
: cacheReadTokens > 0
|
|
501
|
+
? Infinity
|
|
502
|
+
: 0;
|
|
503
|
+
const readsPerWriteRatio = Math.max(0, Number(derivedRwRatio || 0));
|
|
504
|
+
const negativeCacheRoi =
|
|
505
|
+
typeof roi.negativeCacheRoi === 'boolean' && state.lastSource !== 'init'
|
|
506
|
+
? roi.negativeCacheRoi
|
|
507
|
+
: cacheWriteTokens > 0 && readsPerWriteRatio < breakEvenReadsPerWrite;
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
totalInputTokens,
|
|
511
|
+
cachedTokens,
|
|
512
|
+
cacheReadTokens,
|
|
513
|
+
cacheWriteTokens,
|
|
514
|
+
warmPrefixTokens,
|
|
515
|
+
cacheHitPct,
|
|
516
|
+
cacheWarm,
|
|
517
|
+
remainingSeconds,
|
|
518
|
+
ttlCompact: cacheWarm ? formatDurationCompact(remainingSeconds) : 'COLD',
|
|
519
|
+
ttlClock: cacheWarm ? formatTtlClock(remainingSeconds) : '00:00',
|
|
520
|
+
ttlTier,
|
|
521
|
+
amberAlert,
|
|
522
|
+
savedUSD,
|
|
523
|
+
savedTokens,
|
|
524
|
+
sessionSavedTokens,
|
|
525
|
+
sessionSavedUSD,
|
|
526
|
+
workspace30dSavedTokens,
|
|
527
|
+
workspace30dSavedUSD,
|
|
528
|
+
savingsCategories,
|
|
529
|
+
topSavingsDriver,
|
|
530
|
+
flightMode: ['OFF', 'COACH', 'AUTO_PILOT'].includes(flightMode) ? flightMode : 'COACH',
|
|
531
|
+
negativeCacheRoi,
|
|
532
|
+
readsPerWriteRatio,
|
|
533
|
+
breakEvenReadsPerWrite,
|
|
534
|
+
sessionFiveMinRoiTarget
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Checks whether a path is a lockfile, log, build artifact, or scratch file eligible
|
|
540
|
+
* for a `.claudeignore` recommendation (never active source code files).
|
|
541
|
+
*
|
|
542
|
+
* @param {string} [filePath='']
|
|
543
|
+
* @returns {boolean}
|
|
544
|
+
*/
|
|
545
|
+
export function isIgnorableClaudePath(filePath = '') {
|
|
546
|
+
const s = String(filePath || '').trim();
|
|
547
|
+
if (!s) return false;
|
|
548
|
+
return /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|go\.sum|\.(?:log|tmp|bak|min\.js|min\.css|map|bundle\.js)$|(?:^|[\\/])(?:dist|build|coverage|\.next|out|node_modules|\.claude[\\/]cache)[\\/])/i.test(
|
|
549
|
+
s
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Derives plain-English Claude Code status verdict and prioritized action cards
|
|
555
|
+
* for Simple View (Rank 1 & Rank 3) and Advanced View.
|
|
556
|
+
*
|
|
557
|
+
* @param {object} [state={}]
|
|
558
|
+
* @param {object} grid
|
|
559
|
+
* @param {object} metrics
|
|
560
|
+
* @param {object} [options={}]
|
|
561
|
+
*/
|
|
562
|
+
export function deriveClaudeCodeVerdictAndActions(state = {}, grid, metrics, options = {}) {
|
|
563
|
+
const actions = [];
|
|
564
|
+
let verdict = {
|
|
565
|
+
severity: 'healthy',
|
|
566
|
+
badge: 'HEALTHY',
|
|
567
|
+
headline: metrics.cacheWarm
|
|
568
|
+
? `Healthy — Prompt Cache Warm (${metrics.ttlCompact})`
|
|
569
|
+
: 'Ready — Cold Prompt Prefix',
|
|
570
|
+
detail: metrics.cacheWarm
|
|
571
|
+
? `${metrics.cacheHitPct}% of prompt reading at 0.10x cached rates (${metrics.ttlTier} TTL)`
|
|
572
|
+
: 'Next turn establishes the 5m warm prompt cache prefix'
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
const reclaimEstimate = Math.max(
|
|
576
|
+
grid.tokens.D,
|
|
577
|
+
Math.round(grid.totalInputTokens * 0.35)
|
|
578
|
+
);
|
|
579
|
+
|
|
580
|
+
if (options.breakerVerdict?.triggered) {
|
|
581
|
+
const breakerId =
|
|
582
|
+
options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
|
|
583
|
+
const reasonText =
|
|
584
|
+
options.breakerVerdict.reason || 'Circuit breaker triggered on active tool or model call';
|
|
585
|
+
verdict = {
|
|
586
|
+
severity: 'critical',
|
|
587
|
+
badge: 'CRITICAL',
|
|
588
|
+
headline: `${breakerId} Active — Guard Intervention`,
|
|
589
|
+
detail: reasonText
|
|
590
|
+
};
|
|
591
|
+
actions.push({
|
|
592
|
+
id: breakerId.toLowerCase(),
|
|
593
|
+
severity: 'critical',
|
|
594
|
+
title: `Resolve ${breakerId} guard before continuing`,
|
|
595
|
+
instruction: reasonText,
|
|
596
|
+
commandHint: `npx ah-claude config set ${breakerId} warn`,
|
|
597
|
+
reclaimTokens: 0
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
if (state.thinkingDrift?.loop?.triggered) {
|
|
602
|
+
const ratio = state.thinkingDrift.lastDriftRatio ?? 'high';
|
|
603
|
+
if (verdict.severity !== 'critical') {
|
|
604
|
+
verdict = {
|
|
605
|
+
severity: 'critical',
|
|
606
|
+
badge: 'CRITICAL',
|
|
607
|
+
headline: `Critical — Scratchpad Loop Detected (${ratio}x)`,
|
|
608
|
+
detail:
|
|
609
|
+
state.thinkingDrift.loop.message ||
|
|
610
|
+
`DET-21: Thinking tokens exceeded ${ratio}x output tokens with zero file edits`
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
actions.push({
|
|
614
|
+
id: 'det-21-loop',
|
|
615
|
+
severity: 'critical',
|
|
616
|
+
title: `Break ${ratio}x thinking loop`,
|
|
617
|
+
instruction:
|
|
618
|
+
'Add a concrete target file path and test constraint to your next prompt, or lower /effort.',
|
|
619
|
+
commandHint: '/effort medium',
|
|
620
|
+
reclaimTokens: Math.max(0, Number(state.contextWindow?.lastThinkingTokens || 4000))
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
if (state.cliffTriggered) {
|
|
625
|
+
if (verdict.severity !== 'critical') {
|
|
626
|
+
verdict = {
|
|
627
|
+
severity: 'critical',
|
|
628
|
+
badge: 'CRITICAL',
|
|
629
|
+
headline: 'Critical — Haiku 5.5 100k 5x Pricing Cliff Exceeded',
|
|
630
|
+
detail: 'Total prompt exceeded 100,000 tokens ($0.10 -> $0.50/1M input step-up)'
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
actions.push({
|
|
634
|
+
id: 'det-12-cliff',
|
|
635
|
+
severity: 'critical',
|
|
636
|
+
title: 'Exit Haiku 100k 5x pricing cliff now',
|
|
637
|
+
instruction: `Type /compact in the chat box and press Enter to drop below 100k tokens (reclaims ~${formatTokensCompact(reclaimEstimate)}).`,
|
|
638
|
+
commandHint: 'Type /compact in the chat box and press Enter',
|
|
639
|
+
reclaimTokens: reclaimEstimate
|
|
640
|
+
});
|
|
641
|
+
} else if (state.preCliffWarningTriggered) {
|
|
642
|
+
if (verdict.severity === 'healthy') {
|
|
643
|
+
verdict = {
|
|
644
|
+
severity: 'warn',
|
|
645
|
+
badge: 'ACTION NEEDED',
|
|
646
|
+
headline: 'Approaching Haiku 100k 5x Pricing Cliff (>= 90k)',
|
|
647
|
+
detail: 'Compact before 100,000 tokens to avoid the 5x Haiku rate step-up'
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
actions.push({
|
|
651
|
+
id: 'det-12-precliff',
|
|
652
|
+
severity: 'warn',
|
|
653
|
+
title: 'Compact before crossing 100k Haiku cliff',
|
|
654
|
+
instruction: `Type /compact in the chat box and press Enter to reclaim ~${formatTokensCompact(reclaimEstimate)} before 100k.`,
|
|
655
|
+
commandHint: 'Type /compact in the chat box and press Enter',
|
|
656
|
+
reclaimTokens: reclaimEstimate
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
if (metrics.amberAlert) {
|
|
661
|
+
if (verdict.severity === 'healthy') {
|
|
662
|
+
verdict = {
|
|
663
|
+
severity: 'warn',
|
|
664
|
+
badge: 'CACHE EXPIRING',
|
|
665
|
+
headline: `5m Prompt Cache Expiring in ${metrics.ttlCompact}`,
|
|
666
|
+
detail: `${formatTokensCompact(metrics.cachedTokens)} warm prefix will go cold in ${metrics.ttlClock}`
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
actions.push({
|
|
670
|
+
id: 'det-10-ttl',
|
|
671
|
+
severity: 'warn',
|
|
672
|
+
title: `Send next prompt within ${metrics.ttlCompact} or hold prefix edits`,
|
|
673
|
+
instruction:
|
|
674
|
+
'Keep coding to refresh the 5m TTL at 0.10x read cost, and hold CLAUDE.md or .mcp.json edits until PostCompact.',
|
|
675
|
+
commandHint: '/handoff',
|
|
676
|
+
reclaimTokens: metrics.cachedTokens
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
if (grid.tokens.D >= 25000 || grid.utilizationPct >= 75) {
|
|
681
|
+
if (verdict.severity === 'healthy') {
|
|
682
|
+
verdict = {
|
|
683
|
+
severity: 'warn',
|
|
684
|
+
badge: 'ACTION NEEDED',
|
|
685
|
+
headline:
|
|
686
|
+
metrics.cacheWarm && metrics.remainingSeconds > 60
|
|
687
|
+
? `Stale Tool Debt High (${formatTokensCompact(grid.tokens.D)}) — Compact After Cache Window`
|
|
688
|
+
: `Context ${grid.utilizationPct}% Full — Compact Recommended`,
|
|
689
|
+
detail: `${formatTokensCompact(grid.tokens.D)} in middle-window distractors [D]`
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
if (metrics.cacheWarm && metrics.remainingSeconds > 60) {
|
|
693
|
+
actions.push({
|
|
694
|
+
id: 'compact-cache-gated',
|
|
695
|
+
severity: 'warn',
|
|
696
|
+
title: `Wait ${metrics.ttlCompact} for warm cache, then compact (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
|
|
697
|
+
instruction: `Finish your current step while ${formatTokensCompact(metrics.cachedTokens)} is warm (${metrics.ttlCompact} left), then: Type /compact in the chat box and press Enter`,
|
|
698
|
+
commandHint: 'Type /compact in the chat box and press Enter',
|
|
699
|
+
reclaimTokens: reclaimEstimate
|
|
700
|
+
});
|
|
701
|
+
} else {
|
|
702
|
+
actions.push({
|
|
703
|
+
id: 'compact-now',
|
|
704
|
+
severity: 'warn',
|
|
705
|
+
title: `Compact context now (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
|
|
706
|
+
instruction: 'Type /compact in the chat box and press Enter',
|
|
707
|
+
commandHint: 'Type /compact in the chat box and press Enter',
|
|
708
|
+
reclaimTokens: reclaimEstimate
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
if (metrics.negativeCacheRoi) {
|
|
714
|
+
if (verdict.severity === 'healthy') {
|
|
715
|
+
verdict = {
|
|
716
|
+
severity: 'warn',
|
|
717
|
+
badge: 'CACHE ROI WARN',
|
|
718
|
+
headline: 'Cache Write Surcharge Exceeds Read Discount',
|
|
719
|
+
detail: `Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite} break-even`
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
actions.push({
|
|
723
|
+
id: 'negative-roi',
|
|
724
|
+
severity: 'warn',
|
|
725
|
+
title: 'Hold CLAUDE.md, .claude/rules/, and .mcp.json mutations',
|
|
726
|
+
instruction: `Keep prefix static for at least 2 turns so 0.10x cache reads amortize the 1.25x write surcharge.`,
|
|
727
|
+
commandHint: 'Hold prefix edits until /compact',
|
|
728
|
+
reclaimTokens: metrics.cacheWriteTokens
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
const rslData = options.rsl || state.rsl || null;
|
|
733
|
+
if (rslData && Number(rslData.clashCount || 0) > 0) {
|
|
734
|
+
if (verdict.severity === 'healthy') {
|
|
735
|
+
verdict = {
|
|
736
|
+
severity: 'warn',
|
|
737
|
+
badge: 'RULE CLASH',
|
|
738
|
+
headline: `${rslData.clashCount} Conflicting Learned Rule${rslData.clashCount === 1 ? '' : 's'}`,
|
|
739
|
+
detail: 'Quarantined RSL heuristic conflict needs review before applying automatically'
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
actions.push({
|
|
743
|
+
id: 'rsl-clash',
|
|
744
|
+
severity: 'warn',
|
|
745
|
+
title: `Resolve ${rslData.clashCount} RSL rule clash${rslData.clashCount === 1 ? '' : 'es'}`,
|
|
746
|
+
instruction: 'Run `npx ah rsl status` to inspect and resolve conflicting workspace heuristics.',
|
|
747
|
+
commandHint: 'npx ah rsl status',
|
|
748
|
+
reclaimTokens: 0
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const shardedSpec = options.shardedSpec || state.shardedSpec || null;
|
|
753
|
+
if (shardedSpec && shardedSpec.sharded) {
|
|
754
|
+
actions.push({
|
|
755
|
+
id: 'sharded-spec',
|
|
756
|
+
severity: 'warn',
|
|
757
|
+
title: `Consolidate ${Number(shardedSpec.count || 2)} sharded specification files`,
|
|
758
|
+
instruction: 'Run `npx ah handoff --consolidate` so split constraints stay anchored in Turn 0.',
|
|
759
|
+
commandHint: 'npx ah handoff --consolidate',
|
|
760
|
+
reclaimTokens: 0
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const shieldData = options.shield || state.shield || null;
|
|
765
|
+
if (shieldData && (shieldData.quarantined || shieldData.alert)) {
|
|
766
|
+
actions.push({
|
|
767
|
+
id: 'shield-firewall',
|
|
768
|
+
severity: 'warn',
|
|
769
|
+
title: 'Prefix-cache Shield held a mutation',
|
|
770
|
+
instruction: 'Inspect queued prefix updates with `npx ah doctor` before modifying rules mid-chat.',
|
|
771
|
+
commandHint: 'npx ah doctor',
|
|
772
|
+
reclaimTokens: 0
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
if (actions.length === 0) {
|
|
777
|
+
actions.push({
|
|
778
|
+
id: 'keep-coding',
|
|
779
|
+
severity: 'healthy',
|
|
780
|
+
title: metrics.cacheWarm
|
|
781
|
+
? `Keep coding — warm prefix active (${metrics.ttlCompact} remaining)`
|
|
782
|
+
: 'Keep coding — context headroom is clean',
|
|
783
|
+
instruction: metrics.cacheWarm
|
|
784
|
+
? `Hold model switches and CLAUDE.md edits while ${formatTokensCompact(metrics.cachedTokens)} is reading at 0.10x.`
|
|
785
|
+
: 'No compaction or intervention needed right now.',
|
|
786
|
+
commandHint: '',
|
|
787
|
+
reclaimTokens: 0
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
const priorityAction = actions[0];
|
|
792
|
+
const secondaryActions = actions.slice(1);
|
|
793
|
+
|
|
794
|
+
return {
|
|
795
|
+
verdict,
|
|
796
|
+
priorityAction,
|
|
797
|
+
secondaryActions,
|
|
798
|
+
overflowActionCount: secondaryActions.length
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* 1. Renders the `AbovePrompt` 1-line Band with the 40-Cell Horizon Bar and active Coach Pill.
|
|
804
|
+
*
|
|
805
|
+
* @param {object} [state={}]
|
|
806
|
+
* @param {object} [options={}]
|
|
807
|
+
* @returns {{
|
|
808
|
+
* line: string,
|
|
809
|
+
* plainLine: string,
|
|
810
|
+
* grid: object,
|
|
811
|
+
* metrics: object,
|
|
812
|
+
* coachPill: string
|
|
813
|
+
* }}
|
|
814
|
+
*/
|
|
815
|
+
export function renderAbovePromptBand(state = {}, options = {}) {
|
|
816
|
+
const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
|
|
817
|
+
const useAnsi = Boolean(options.ansi) && !isNoColorEnabled(options);
|
|
818
|
+
const grid = computeHorizonGrid(state, options);
|
|
819
|
+
const metrics = deriveSurfaceMetrics(state, options);
|
|
820
|
+
|
|
821
|
+
let coachAction = 'HOLD WARM PREFIX';
|
|
822
|
+
if (options.breakerVerdict?.triggered) {
|
|
823
|
+
const breakerId =
|
|
824
|
+
options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
|
|
825
|
+
coachAction = `${breakerId} ACTIVE`;
|
|
826
|
+
} else if (state.thinkingDrift?.loop?.triggered) {
|
|
827
|
+
coachAction = `THINK LOOP ${state.thinkingDrift.lastDriftRatio ?? ''}x`;
|
|
828
|
+
} else if (state.cliffTriggered) {
|
|
829
|
+
coachAction = 'HAIKU 100K CLIFF (5X)';
|
|
830
|
+
} else if (state.preCliffWarningTriggered) {
|
|
831
|
+
coachAction = 'HAIKU 90K PRE-CLIFF';
|
|
832
|
+
} else if (metrics.amberAlert) {
|
|
833
|
+
coachAction = `TTL EXPIRING ${metrics.ttlCompact}`;
|
|
834
|
+
} else if (!metrics.cacheWarm) {
|
|
835
|
+
coachAction = 'COLD PREFIX';
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
const coachPill = `[${metrics.flightMode} · ${coachAction}]`;
|
|
839
|
+
const tokenBadge = `${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id}`;
|
|
840
|
+
const ttlBadge = metrics.cacheWarm ? `TTL ${metrics.ttlCompact}` : 'TTL COLD';
|
|
841
|
+
|
|
842
|
+
const suffixWithPct = ` ${tokenBadge} (${grid.utilizationPct}%) · ${ttlBadge} · ${coachPill}`;
|
|
843
|
+
const suffixCompact = ` ${tokenBadge} · ${ttlBadge} · ${coachPill}`;
|
|
844
|
+
|
|
845
|
+
let plainCandidate = `AH ${grid.bracketedBar}${suffixWithPct}`;
|
|
846
|
+
let ansiCandidate = `AH ${grid.ansiCodeBar}${suffixWithPct}`;
|
|
847
|
+
|
|
848
|
+
if (plainCandidate.length > maxCols) {
|
|
849
|
+
const availWithPct = maxCols - 3 - suffixWithPct.length - 2;
|
|
850
|
+
const availCompact = maxCols - 3 - suffixCompact.length - 2;
|
|
851
|
+
if (availWithPct >= 12) {
|
|
852
|
+
const dynCells = Math.min(40, availWithPct);
|
|
853
|
+
const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
|
|
854
|
+
plainCandidate = `AH ${barGrid.bracketedBar}${suffixWithPct}`;
|
|
855
|
+
ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixWithPct}`;
|
|
856
|
+
} else if (availCompact >= 8) {
|
|
857
|
+
const dynCells = Math.min(40, availCompact);
|
|
858
|
+
const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
|
|
859
|
+
plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
|
|
860
|
+
ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
|
|
861
|
+
} else {
|
|
862
|
+
const barGrid = computeHorizonGrid(state, { ...options, cellCount: 8 });
|
|
863
|
+
plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
|
|
864
|
+
ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
if (plainCandidate.length > maxCols) {
|
|
869
|
+
plainCandidate = plainCandidate.slice(0, maxCols);
|
|
870
|
+
ansiCandidate = truncateAnsiVisible(ansiCandidate, maxCols);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const plainLine = plainCandidate;
|
|
874
|
+
const line = useAnsi ? ansiCandidate : plainLine;
|
|
875
|
+
|
|
876
|
+
return {
|
|
877
|
+
line,
|
|
878
|
+
plainLine,
|
|
879
|
+
grid,
|
|
880
|
+
metrics,
|
|
881
|
+
coachPill
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/**
|
|
886
|
+
* 2. Renders the `Spinner` suffix appended during active turns (`· Cache 95% (4m12s) · Saved $1.84`).
|
|
887
|
+
*
|
|
888
|
+
* @param {object} [state={}]
|
|
889
|
+
* @param {object} [options={}]
|
|
890
|
+
* @returns {{
|
|
891
|
+
* suffix: string,
|
|
892
|
+
* cacheHitPct: number,
|
|
893
|
+
* ttlText: string,
|
|
894
|
+
* savedUSDText: string
|
|
895
|
+
* }}
|
|
896
|
+
*/
|
|
897
|
+
export function renderSpinnerSuffix(state = {}, options = {}) {
|
|
898
|
+
const metrics = deriveSurfaceMetrics(state, options);
|
|
899
|
+
const ttlText = metrics.cacheWarm ? metrics.ttlCompact : 'cold';
|
|
900
|
+
const savedUSDText = formatUsd(metrics.savedUSD);
|
|
901
|
+
let suffix = `· Cache ${metrics.cacheHitPct}% (${ttlText}) · Saved ${savedUSDText}`;
|
|
902
|
+
if (state.prefixRetention?.measured) suffix += ` · ${formatRetentionCompact(state.prefixRetention)}`;
|
|
903
|
+
if (state.thinkingDrift?.loop?.triggered) suffix += ` · ${formatDriftCompact(state.thinkingDrift)}`;
|
|
904
|
+
|
|
905
|
+
return {
|
|
906
|
+
suffix,
|
|
907
|
+
cacheHitPct: metrics.cacheHitPct,
|
|
908
|
+
ttlText,
|
|
909
|
+
savedUSDText
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Builds the ranked list of Top Context Offenders for Box 4 of the Simple View Pane.
|
|
915
|
+
*
|
|
916
|
+
* @param {object} state
|
|
917
|
+
* @param {object} grid
|
|
918
|
+
* @param {object} [options={}]
|
|
919
|
+
* @returns {Array<{ name: string, tokens: number, category: string, pct: number }>}
|
|
920
|
+
*/
|
|
921
|
+
function buildTopContextOffenders(state = {}, grid, options = {}) {
|
|
922
|
+
if (Array.isArray(options.offenders) && options.offenders.length > 0) {
|
|
923
|
+
return options.offenders.slice(0, 4).map((item) => {
|
|
924
|
+
const name = String(item.name || 'Context Item');
|
|
925
|
+
return {
|
|
926
|
+
name,
|
|
927
|
+
tokens: Math.max(0, Number(item.tokens || 0)),
|
|
928
|
+
category: String(item.category || 'C'),
|
|
929
|
+
ignorable: isIgnorableClaudePath(name),
|
|
930
|
+
pct:
|
|
931
|
+
grid.totalInputTokens > 0
|
|
932
|
+
? Number(((Number(item.tokens || 0) / grid.totalInputTokens) * 100).toFixed(1))
|
|
933
|
+
: 0
|
|
934
|
+
};
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
const entries = [
|
|
939
|
+
{
|
|
940
|
+
name: 'Middle-Window Distractor / Stale Tool Output',
|
|
941
|
+
tokens: grid.tokens.D,
|
|
942
|
+
category: '[D]',
|
|
943
|
+
ignorable: false
|
|
944
|
+
},
|
|
945
|
+
{
|
|
946
|
+
name: 'System Prompt & MCP Tool Schemas',
|
|
947
|
+
tokens: grid.tokens.S,
|
|
948
|
+
category: '[S]',
|
|
949
|
+
ignorable: false
|
|
950
|
+
},
|
|
951
|
+
{
|
|
952
|
+
name: 'Fresh 1.25x Cache Write Delta',
|
|
953
|
+
tokens: grid.tokens.W,
|
|
954
|
+
category: '[W]',
|
|
955
|
+
ignorable: false
|
|
956
|
+
},
|
|
957
|
+
{
|
|
958
|
+
name: 'Warm Cached Conversation Prefix',
|
|
959
|
+
tokens: grid.tokens.C,
|
|
960
|
+
category: '[C]',
|
|
961
|
+
ignorable: false
|
|
962
|
+
}
|
|
963
|
+
].filter((e) => e.tokens > 0);
|
|
964
|
+
|
|
965
|
+
entries.sort((a, b) => b.tokens - a.tokens);
|
|
966
|
+
|
|
967
|
+
if (entries.length === 0) {
|
|
968
|
+
return [
|
|
969
|
+
{
|
|
970
|
+
name: 'No active context offenders recorded',
|
|
971
|
+
tokens: 0,
|
|
972
|
+
category: '[.]',
|
|
973
|
+
ignorable: false,
|
|
974
|
+
pct: 0
|
|
975
|
+
}
|
|
976
|
+
];
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
return entries.slice(0, 4).map((e) => ({
|
|
980
|
+
...e,
|
|
981
|
+
pct:
|
|
982
|
+
grid.totalInputTokens > 0
|
|
983
|
+
? Number(((e.tokens / grid.totalInputTokens) * 100).toFixed(1))
|
|
984
|
+
: 0
|
|
985
|
+
}));
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* 3. Renders the Docked `Pane` (`id: 'attention-horizon'`) with both the 4-Rank Glanceable Simple View
|
|
990
|
+
* (`ranks` / `simpleText`) and the 5-Box vertical hierarchy (`boxes`, zero promotional banner text):
|
|
991
|
+
* - Rank 1: Status Verdict & Flight Header (`Healthy` / `Action Needed` / `Critical`)
|
|
992
|
+
* - Rank 2: 40-Cell Horizon Bar, 3-Stat Row & 5m/1h Prompt Cache Shield
|
|
993
|
+
* - Rank 3: Single Priority Next Action (+ overflow count for `/horizon advanced`)
|
|
994
|
+
* - Rank 4: Elevated "Tokens & USD Saved" Card (`This Session` + `30d Workspace` + Top Driver)
|
|
995
|
+
*
|
|
996
|
+
* @param {object} [state={}]
|
|
997
|
+
* @param {object} [options={}]
|
|
998
|
+
*/
|
|
999
|
+
export function renderSimpleViewPane(state = {}, options = {}) {
|
|
1000
|
+
const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
|
|
1001
|
+
const grid = computeHorizonGrid(state, options);
|
|
1002
|
+
const paneCellCount = maxCols >= 49 ? 40 : Math.max(8, maxCols - 9);
|
|
1003
|
+
const paneGrid =
|
|
1004
|
+
paneCellCount === 40 ? grid : computeHorizonGrid(state, { ...options, cellCount: paneCellCount });
|
|
1005
|
+
const scaleRuler = buildScaleTickRuler(
|
|
1006
|
+
grid.zoomTier.ceilingTokens,
|
|
1007
|
+
paneGrid.bracketedBar.length
|
|
1008
|
+
);
|
|
1009
|
+
const metrics = deriveSurfaceMetrics(state, options);
|
|
1010
|
+
const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
|
|
1011
|
+
const breakEven = computeBreakEvenCachedTokens(
|
|
1012
|
+
{
|
|
1013
|
+
currentModel: grid.modelId,
|
|
1014
|
+
targetModel: peerModel,
|
|
1015
|
+
expectedOutputTokens: 1500,
|
|
1016
|
+
cacheTtlTier: metrics.ttlTier
|
|
1017
|
+
},
|
|
1018
|
+
options
|
|
1019
|
+
);
|
|
1020
|
+
const { verdict, priorityAction, secondaryActions, overflowActionCount } =
|
|
1021
|
+
deriveClaudeCodeVerdictAndActions(state, grid, metrics, options);
|
|
1022
|
+
|
|
1023
|
+
const headroomTokens = Math.max(0, grid.zoomTier.ceilingTokens - grid.totalInputTokens);
|
|
1024
|
+
|
|
1025
|
+
// 4-Rank Glanceable Simple View (`ranks`)
|
|
1026
|
+
const rank1Lines = [
|
|
1027
|
+
`[Rank 1] ${verdict.badge}: ${verdict.headline}`,
|
|
1028
|
+
`Model: ${state.modelLabel || grid.modelId} · Mode: ${metrics.flightMode} · ${verdict.detail}`
|
|
1029
|
+
];
|
|
1030
|
+
const rank2Lines = [
|
|
1031
|
+
`[Rank 2] Context Capacity & Prompt Cache Shield (${grid.zoomTier.label})`,
|
|
1032
|
+
`Grid : ${paneGrid.bracketedBar}`,
|
|
1033
|
+
`Scale: ${scaleRuler}`,
|
|
1034
|
+
`Stats: Used ${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id} (${grid.utilizationPct}%) | Stale Debt [D] ${formatTokensCompact(grid.tokens.D)} | Free ${formatTokensCompact(headroomTokens)}`,
|
|
1035
|
+
`Cache: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier}) · TTL ${metrics.ttlClock} (${metrics.ttlCompact}) · Hit ${metrics.cacheHitPct}%`
|
|
1036
|
+
];
|
|
1037
|
+
const overflowNote =
|
|
1038
|
+
overflowActionCount > 0 ? ` (+${overflowActionCount} more in /horizon advanced)` : '';
|
|
1039
|
+
const rank3Lines = [
|
|
1040
|
+
`[Rank 3] Next Action${overflowNote}`,
|
|
1041
|
+
`Action: ${priorityAction.title}`,
|
|
1042
|
+
`Guide : ${priorityAction.instruction}`
|
|
1043
|
+
];
|
|
1044
|
+
const rank4Lines = [
|
|
1045
|
+
`[Rank 4] Verified Tokens & USD Saved`,
|
|
1046
|
+
`Saved : +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) this session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
|
|
1047
|
+
`Driver: ${metrics.topSavingsDriver.shortLabel} (+${formatTokensCompact(metrics.topSavingsDriver.savedTokens)})`
|
|
1048
|
+
];
|
|
1049
|
+
|
|
1050
|
+
const rawRanks = [
|
|
1051
|
+
{
|
|
1052
|
+
rankNumber: 1,
|
|
1053
|
+
id: 'status-verdict-header',
|
|
1054
|
+
title: 'Status Verdict & Flight Header',
|
|
1055
|
+
lines: rank1Lines
|
|
1056
|
+
},
|
|
1057
|
+
{
|
|
1058
|
+
rankNumber: 2,
|
|
1059
|
+
id: 'capacity-cache-shield',
|
|
1060
|
+
title: 'Context Capacity & Prompt Cache Shield',
|
|
1061
|
+
lines: rank2Lines
|
|
1062
|
+
},
|
|
1063
|
+
{
|
|
1064
|
+
rankNumber: 3,
|
|
1065
|
+
id: 'priority-next-action',
|
|
1066
|
+
title: 'Priority Next Action',
|
|
1067
|
+
lines: rank3Lines
|
|
1068
|
+
},
|
|
1069
|
+
{
|
|
1070
|
+
rankNumber: 4,
|
|
1071
|
+
id: 'tokens-usd-saved',
|
|
1072
|
+
title: 'Verified Tokens & USD Saved',
|
|
1073
|
+
lines: rank4Lines
|
|
1074
|
+
}
|
|
1075
|
+
];
|
|
1076
|
+
|
|
1077
|
+
const ranks = rawRanks.map((r) => {
|
|
1078
|
+
const clampedLines = r.lines.map((l) => clampPlainLine(l, maxCols));
|
|
1079
|
+
return {
|
|
1080
|
+
...r,
|
|
1081
|
+
lines: clampedLines,
|
|
1082
|
+
text: clampedLines.join('\n')
|
|
1083
|
+
};
|
|
1084
|
+
});
|
|
1085
|
+
|
|
1086
|
+
// Box 1: Capacity & Horizon Bar + Tufte Scale-Tick Ruler
|
|
1087
|
+
const box1Lines = [
|
|
1088
|
+
`[Box 1] Capacity & Horizon Bar · ${grid.zoomTier.label}`,
|
|
1089
|
+
`Model: ${state.modelLabel || grid.modelId} | Tokens: ${formatTokensCompact(grid.totalInputTokens)} / ${grid.zoomTier.id} (${grid.utilizationPct}%)`,
|
|
1090
|
+
`Grid : ${paneGrid.bracketedBar}`,
|
|
1091
|
+
`Scale: ${scaleRuler}`,
|
|
1092
|
+
`Cells: [S] ${grid.cellCounts.S} (${formatTokensCompact(grid.tokens.S)}) | [C] ${grid.cellCounts.C} (${formatTokensCompact(grid.tokens.C)}) | [D] ${grid.cellCounts.D} (${formatTokensCompact(grid.tokens.D)}) | [W] ${grid.cellCounts.W} (${formatTokensCompact(grid.tokens.W)})`
|
|
1093
|
+
];
|
|
1094
|
+
|
|
1095
|
+
// Box 2: Cache Hold & 5m TTL Countdown
|
|
1096
|
+
const roiLabel = metrics.negativeCacheRoi
|
|
1097
|
+
? `NEGATIVE ROI (Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite})`
|
|
1098
|
+
: `POSITIVE ROI (Hit ${metrics.cacheHitPct}% | R/W ${metrics.readsPerWriteRatio.toFixed(2)} >= ${metrics.breakEvenReadsPerWrite})`;
|
|
1099
|
+
const ttlAlertText = metrics.amberAlert ? ' [AMBER TTL ALERT <= 45s]' : '';
|
|
1100
|
+
const box2Lines = [
|
|
1101
|
+
`[Box 2] Cache Hold & 5m TTL Countdown`,
|
|
1102
|
+
`State: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier} tier) | Countdown: ${metrics.ttlClock} (${metrics.ttlCompact})${ttlAlertText}`,
|
|
1103
|
+
`Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tokens`,
|
|
1104
|
+
`Cache ROI: ${roiLabel}`,
|
|
1105
|
+
`Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
|
|
1106
|
+
`Thinking Drift: ${formatDriftLabel(state.thinkingDrift)}`
|
|
1107
|
+
];
|
|
1108
|
+
|
|
1109
|
+
// Sprint 2.1: Swarm & Worktrees block (progressive disclosure: only when subagents seen)
|
|
1110
|
+
const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
|
|
1111
|
+
if (swarmSummary.active) {
|
|
1112
|
+
box2Lines.push(`Swarm & Worktrees: ${swarmSummary.label}`);
|
|
1113
|
+
for (const w of swarmSummary.workers.slice(0, 4)) {
|
|
1114
|
+
const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
|
|
1115
|
+
box2Lines.push(` · ${w.agentId} ${w.state}${w.state === 'waiting' ? ' ($0)' : ''} · ${formatTokensCompact(w.totalTokens)} · ${w.turns}t${loc}`);
|
|
1116
|
+
}
|
|
1117
|
+
if (swarmSummary.workers.length > 4) box2Lines.push(` · +${swarmSummary.workers.length - 4} more`);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// Box 3: Active Coach / Circuit Breaker Slot
|
|
1121
|
+
const activeBreakerId =
|
|
1122
|
+
options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || 'BREAKER';
|
|
1123
|
+
const activeBreaker = options.breakerVerdict?.triggered
|
|
1124
|
+
? options.breakerVerdict.reason
|
|
1125
|
+
? `${activeBreakerId} ACTIVE — ${options.breakerVerdict.reason}`
|
|
1126
|
+
: `${activeBreakerId} ACTIVE`
|
|
1127
|
+
: state.thinkingDrift?.loop?.triggered
|
|
1128
|
+
? state.thinkingDrift.loop.message
|
|
1129
|
+
: state.cliffTriggered
|
|
1130
|
+
? 'DET-12: Haiku 5.5 100k 5x pricing cliff exceeded'
|
|
1131
|
+
: state.preCliffWarningTriggered
|
|
1132
|
+
? 'DET-12: Haiku 5.5 90k pre-cliff compaction recommended'
|
|
1133
|
+
: metrics.amberAlert
|
|
1134
|
+
? 'DET-10: 5m KV-cache TTL <= 45s; hold mutations or flush State Baton'
|
|
1135
|
+
: 'All DET-01..32 circuit breakers nominal';
|
|
1136
|
+
const singleBox3Status = `Flight Mode: ${metrics.flightMode} | Status: ${activeBreaker}`;
|
|
1137
|
+
const box3Lines =
|
|
1138
|
+
singleBox3Status.length <= maxCols
|
|
1139
|
+
? [
|
|
1140
|
+
`[Box 3] Active Coach / Circuit Breaker Slot`,
|
|
1141
|
+
singleBox3Status,
|
|
1142
|
+
`Action: ${priorityAction.title}`
|
|
1143
|
+
]
|
|
1144
|
+
: [
|
|
1145
|
+
`[Box 3] Active Coach / Circuit Breaker Slot`,
|
|
1146
|
+
`Flight Mode: ${metrics.flightMode}`,
|
|
1147
|
+
`Status: ${activeBreaker}`,
|
|
1148
|
+
`Action: ${priorityAction.title}`
|
|
1149
|
+
];
|
|
1150
|
+
|
|
1151
|
+
// Box 4: Top Context Offenders
|
|
1152
|
+
const offenders = buildTopContextOffenders(state, grid, options);
|
|
1153
|
+
const offenderLines = offenders.map((o, idx) => {
|
|
1154
|
+
const prefix = ` ${idx + 1}. ${o.category} `;
|
|
1155
|
+
const suffix = `: ${formatTokensCompact(o.tokens)} (${o.pct}%)`;
|
|
1156
|
+
const maxNameLen = Math.max(6, maxCols - prefix.length - suffix.length);
|
|
1157
|
+
const safeName =
|
|
1158
|
+
o.name.length > maxNameLen ? `${o.name.slice(0, maxNameLen - 1)}…` : o.name;
|
|
1159
|
+
return `${prefix}${safeName}${suffix}`;
|
|
1160
|
+
});
|
|
1161
|
+
const box4Lines = [`[Box 4] Top Context Offenders`, ...offenderLines];
|
|
1162
|
+
|
|
1163
|
+
// Box 5: Deterministic Saved-Quota Receipt in USD & Tokens
|
|
1164
|
+
const box5Lines = [
|
|
1165
|
+
`[Box 5] Deterministic Saved-Quota Receipt`,
|
|
1166
|
+
`Verified Savings: ${formatUsd(metrics.savedUSD)} USD | ${metrics.savedTokens.toLocaleString('en-US')} tokens preserved`,
|
|
1167
|
+
`Session: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) | 30d: +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)})`
|
|
1168
|
+
];
|
|
1169
|
+
|
|
1170
|
+
const rawBoxes = [
|
|
1171
|
+
{
|
|
1172
|
+
boxNumber: 1,
|
|
1173
|
+
id: 'capacity-horizon-bar',
|
|
1174
|
+
title: 'Capacity & Horizon Bar',
|
|
1175
|
+
lines: box1Lines
|
|
1176
|
+
},
|
|
1177
|
+
{
|
|
1178
|
+
boxNumber: 2,
|
|
1179
|
+
id: 'cache-hold-ttl-countdown',
|
|
1180
|
+
title: 'Cache Hold & 5m TTL Countdown',
|
|
1181
|
+
lines: box2Lines
|
|
1182
|
+
},
|
|
1183
|
+
{
|
|
1184
|
+
boxNumber: 3,
|
|
1185
|
+
id: 'active-coach-circuit-breaker',
|
|
1186
|
+
title: 'Active Coach / Circuit Breaker Slot',
|
|
1187
|
+
lines: box3Lines
|
|
1188
|
+
},
|
|
1189
|
+
{
|
|
1190
|
+
boxNumber: 4,
|
|
1191
|
+
id: 'top-context-offenders',
|
|
1192
|
+
title: 'Top Context Offenders',
|
|
1193
|
+
lines: box4Lines
|
|
1194
|
+
},
|
|
1195
|
+
{
|
|
1196
|
+
boxNumber: 5,
|
|
1197
|
+
id: 'saved-quota-receipt',
|
|
1198
|
+
title: 'Deterministic Saved-Quota Receipt',
|
|
1199
|
+
lines: box5Lines
|
|
1200
|
+
}
|
|
1201
|
+
];
|
|
1202
|
+
|
|
1203
|
+
const boxes = rawBoxes.map((b) => {
|
|
1204
|
+
const clampedLines = b.lines.map((l) => clampPlainLine(l, maxCols));
|
|
1205
|
+
return {
|
|
1206
|
+
...b,
|
|
1207
|
+
lines: clampedLines,
|
|
1208
|
+
text: clampedLines.join('\n')
|
|
1209
|
+
};
|
|
1210
|
+
});
|
|
1211
|
+
|
|
1212
|
+
const divider = '─'.repeat(Math.min(76, maxCols));
|
|
1213
|
+
const simpleText = ranks.map((r) => r.text).join(`\n${divider}\n`);
|
|
1214
|
+
const boxText = boxes.map((b) => b.text).join(`\n${divider}\n`);
|
|
1215
|
+
const useRankMode = options.viewMode === 'SIMPLE_4_RANK' || options.layout === '4-rank';
|
|
1216
|
+
|
|
1217
|
+
return {
|
|
1218
|
+
paneId: 'attention-horizon',
|
|
1219
|
+
title: 'Highbeam',
|
|
1220
|
+
viewMode: useRankMode ? 'SIMPLE_4_RANK' : 'SIMPLE_5_BOX',
|
|
1221
|
+
ranks,
|
|
1222
|
+
simpleText,
|
|
1223
|
+
boxes,
|
|
1224
|
+
text: useRankMode ? simpleText : boxText,
|
|
1225
|
+
verdict,
|
|
1226
|
+
priorityAction,
|
|
1227
|
+
secondaryActions,
|
|
1228
|
+
overflowActionCount,
|
|
1229
|
+
grid,
|
|
1230
|
+
metrics
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/**
|
|
1235
|
+
* Renders the pure 4-Rank Glanceable Simple View HUD (`viewMode: 'SIMPLE_4_RANK'`).
|
|
1236
|
+
*
|
|
1237
|
+
* @param {object} [state={}]
|
|
1238
|
+
* @param {object} [options={}]
|
|
1239
|
+
*/
|
|
1240
|
+
export function renderSimpleHudPane(state = {}, options = {}) {
|
|
1241
|
+
return renderSimpleViewPane(state, { ...options, viewMode: 'SIMPLE_4_RANK' });
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/**
|
|
1245
|
+
* Renders the 5-Section Advanced View Workbench for Claude Code (`/horizon advanced` / `npx ah-claude receipt --advanced`):
|
|
1246
|
+
* Section 1: Verified 5-Category Savings & Anthropic Cache ROI (`C*` & `0.263`/`1.053` R/W)
|
|
1247
|
+
* Section 2: 40-Cell `[S]/[C]/[D]/[W]` Context Anatomy & Top Context Offenders
|
|
1248
|
+
* Section 3: Circuit Breakers (`DET-01..21`), Thinking Drift & Prefix Retention
|
|
1249
|
+
* Section 4: Subagent Swarm (`Task`/`Agent`), Worktrees & `DET-20` Scope Locks
|
|
1250
|
+
* Section 5: `PreCompact` State Baton (`HANDOFF_LATEST.md`) & Session Forensics
|
|
1251
|
+
*
|
|
1252
|
+
* @param {object} [state={}]
|
|
1253
|
+
* @param {object} [options={}]
|
|
1254
|
+
*/
|
|
1255
|
+
export function renderAdvancedViewPane(state = {}, options = {}) {
|
|
1256
|
+
const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
|
|
1257
|
+
const simple = renderSimpleViewPane(state, options);
|
|
1258
|
+
const { grid, metrics } = simple;
|
|
1259
|
+
const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
|
|
1260
|
+
const breakEven = computeBreakEvenCachedTokens(
|
|
1261
|
+
{
|
|
1262
|
+
currentModel: grid.modelId,
|
|
1263
|
+
targetModel: peerModel,
|
|
1264
|
+
expectedOutputTokens: 1500,
|
|
1265
|
+
cacheTtlTier: metrics.ttlTier
|
|
1266
|
+
},
|
|
1267
|
+
options
|
|
1268
|
+
);
|
|
1269
|
+
const offenders = buildTopContextOffenders(state, grid, options);
|
|
1270
|
+
const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
|
|
1271
|
+
|
|
1272
|
+
// Section 1: 5-Category Savings Breakdown & Anthropic Cache ROI
|
|
1273
|
+
const catOrder = [
|
|
1274
|
+
metrics.savingsCategories.cacheReadDiscount,
|
|
1275
|
+
metrics.savingsCategories.prefixBustAvoided,
|
|
1276
|
+
metrics.savingsCategories.toolOutputCompressed,
|
|
1277
|
+
metrics.savingsCategories.loopAndReadGuarded,
|
|
1278
|
+
metrics.savingsCategories.subagentIsolated
|
|
1279
|
+
];
|
|
1280
|
+
const sec1Lines = [
|
|
1281
|
+
`[Section 1] Verified 5-Category Savings & Anthropic Cache ROI`,
|
|
1282
|
+
`Headline: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
|
|
1283
|
+
...catOrder.map(
|
|
1284
|
+
(c, idx) =>
|
|
1285
|
+
` ${idx + 1}. ${c.shortLabel}: +${formatTokensCompact(c.savedTokens)} (${formatUsd(c.savedUSD)}) [${c.count}x]`
|
|
1286
|
+
),
|
|
1287
|
+
`Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tok (${grid.modelId} -> ${peerModel})`,
|
|
1288
|
+
`Reads/Write Ratio: ${metrics.readsPerWriteRatio.toFixed(2)} (target >= ${metrics.breakEvenReadsPerWrite} for ${metrics.ttlTier} TTL)`
|
|
1289
|
+
];
|
|
1290
|
+
|
|
1291
|
+
// Section 2: 40-Cell [S]/[C]/[D]/[W] Anatomy & Top Context Offenders
|
|
1292
|
+
const sec2Lines = [
|
|
1293
|
+
`[Section 2] 40-Cell Context Anatomy & Top Context Offenders`,
|
|
1294
|
+
`[S] System & MCP Schemas : ${grid.cellCounts.S} cells (${formatTokensCompact(grid.tokens.S)})`,
|
|
1295
|
+
`[C] Warm Cached Prefix : ${grid.cellCounts.C} cells (${formatTokensCompact(grid.tokens.C)})`,
|
|
1296
|
+
`[D] Stale Tool Debt : ${grid.cellCounts.D} cells (${formatTokensCompact(grid.tokens.D)})`,
|
|
1297
|
+
`[W] Fresh 1.25x Write : ${grid.cellCounts.W} cells (${formatTokensCompact(grid.tokens.W)})`,
|
|
1298
|
+
...offenders.map(
|
|
1299
|
+
(o, idx) =>
|
|
1300
|
+
` Offender ${idx + 1}: ${o.category} ${o.name} — ${formatTokensCompact(o.tokens)} (${o.pct}%)${o.ignorable ? ' [.claudeignore candidate]' : ''}`
|
|
1301
|
+
)
|
|
1302
|
+
];
|
|
1303
|
+
|
|
1304
|
+
// Section 3: Circuit Breakers (DET-01..32), Thinking Drift & Prefix Retention
|
|
1305
|
+
const activeBreakerId =
|
|
1306
|
+
options.breakerVerdict?.detectorId ||
|
|
1307
|
+
options.breakerVerdict?.ruleId ||
|
|
1308
|
+
state.coachState?.detectors?.tripped?.detectorId ||
|
|
1309
|
+
state.circuitBreakerTripped?.detectorId ||
|
|
1310
|
+
null;
|
|
1311
|
+
const activeBreakerReason =
|
|
1312
|
+
options.breakerVerdict?.reason ||
|
|
1313
|
+
state.coachState?.detectors?.tripped?.reason ||
|
|
1314
|
+
state.circuitBreakerTripped?.reason ||
|
|
1315
|
+
'active';
|
|
1316
|
+
const sec3Lines = [
|
|
1317
|
+
`[Section 3] Circuit Breakers (DET-01..32), Thinking Drift & Retention`,
|
|
1318
|
+
`Flight Mode: ${metrics.flightMode} | Active Trigger: ${activeBreakerId ? `${activeBreakerId} (${activeBreakerReason})` : 'None (32 guards nominal)'}`,
|
|
1319
|
+
`Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
|
|
1320
|
+
`Thinking Drift (DET-30): ${formatDriftLabel(state.thinkingDrift)}`,
|
|
1321
|
+
`Haiku 100k 5x Cliff (DET-12): ${state.cliffTriggered ? 'EXCEEDED (5x step-up)' : state.preCliffWarningTriggered ? 'PRE-CLIFF WARNING (>= 90k)' : 'Nominal'}`
|
|
1322
|
+
];
|
|
1323
|
+
|
|
1324
|
+
// Section 4: Subagent Swarm (Task/Agent), Worktrees & DET-20 Scope Locks
|
|
1325
|
+
const sec4Lines = [
|
|
1326
|
+
`[Section 4] Subagent Swarm (Task/Agent), Worktrees & Scope Locks`,
|
|
1327
|
+
`Topology: ${swarmSummary.active ? swarmSummary.label : 'Solo main agent (0 active Task/Agent subagents)'}`
|
|
1328
|
+
];
|
|
1329
|
+
if (swarmSummary.active) {
|
|
1330
|
+
for (const w of swarmSummary.workers.slice(0, 6)) {
|
|
1331
|
+
const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
|
|
1332
|
+
sec4Lines.push(
|
|
1333
|
+
` · ${w.agentId} [${w.state}${w.state === 'waiting' ? ' $0' : ''}] ${formatTokensCompact(w.totalTokens)} (${w.turns}t)${loc}`
|
|
1334
|
+
);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// Section 5: PreCompact State Baton & Session Forensics
|
|
1339
|
+
const sec5Lines = [
|
|
1340
|
+
`[Section 5] PreCompact State Baton & Claude Code Forensics`,
|
|
1341
|
+
`Session ID: ${state.sessionId || 'default'} | Completed Turns: ${Number(state.turnsCompleted ?? state.window?.turnCount ?? state.sessionTimeline?.totalTurns ?? 0)}`,
|
|
1342
|
+
`Zoom Tier : ${grid.zoomTier.label} (${grid.zoomTier.tokensPerCell.toLocaleString('en-US')} tok/cell)`,
|
|
1343
|
+
`State Baton: Auto-flushed on PreCompact to .claude/cache/HANDOFF_LATEST.md`,
|
|
1344
|
+
`CLI Tools : npx ctxtop statusline | npx ctxtop radar | npx ctxtop inspect | npx ctxtop doctor`
|
|
1345
|
+
];
|
|
1346
|
+
|
|
1347
|
+
const rawSections = [
|
|
1348
|
+
{
|
|
1349
|
+
sectionNumber: 1,
|
|
1350
|
+
id: 'savings-and-cache-roi',
|
|
1351
|
+
title: 'Verified 5-Category Savings & Anthropic Cache ROI',
|
|
1352
|
+
lines: sec1Lines
|
|
1353
|
+
},
|
|
1354
|
+
{
|
|
1355
|
+
sectionNumber: 2,
|
|
1356
|
+
id: 'context-anatomy-offenders',
|
|
1357
|
+
title: '40-Cell Context Anatomy & Top Context Offenders',
|
|
1358
|
+
lines: sec2Lines
|
|
1359
|
+
},
|
|
1360
|
+
{
|
|
1361
|
+
sectionNumber: 3,
|
|
1362
|
+
id: 'circuit-breakers-drift',
|
|
1363
|
+
title: 'Circuit Breakers (DET-01..32), Thinking Drift & Retention',
|
|
1364
|
+
lines: sec3Lines
|
|
1365
|
+
},
|
|
1366
|
+
{
|
|
1367
|
+
sectionNumber: 4,
|
|
1368
|
+
id: 'subagent-swarm-worktrees',
|
|
1369
|
+
title: 'Subagent Swarm (Task/Agent), Worktrees & Scope Locks',
|
|
1370
|
+
lines: sec4Lines
|
|
1371
|
+
},
|
|
1372
|
+
{
|
|
1373
|
+
sectionNumber: 5,
|
|
1374
|
+
id: 'state-baton-forensics',
|
|
1375
|
+
title: 'PreCompact State Baton & Claude Code Forensics',
|
|
1376
|
+
lines: sec5Lines
|
|
1377
|
+
}
|
|
1378
|
+
];
|
|
1379
|
+
|
|
1380
|
+
const sections = rawSections.map((s) => {
|
|
1381
|
+
const clampedLines = s.lines.map((l) => clampPlainLine(l, maxCols));
|
|
1382
|
+
return {
|
|
1383
|
+
...s,
|
|
1384
|
+
lines: clampedLines,
|
|
1385
|
+
text: clampedLines.join('\n')
|
|
1386
|
+
};
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1389
|
+
const divider = '─'.repeat(Math.min(76, maxCols));
|
|
1390
|
+
const text = sections.map((s) => s.text).join(`\n${divider}\n`);
|
|
1391
|
+
|
|
1392
|
+
return {
|
|
1393
|
+
paneId: 'attention-horizon',
|
|
1394
|
+
title: 'Highbeam (Advanced View)',
|
|
1395
|
+
viewMode: 'ADVANCED_5_SECTION',
|
|
1396
|
+
sections,
|
|
1397
|
+
boxes: simple.boxes,
|
|
1398
|
+
ranks: simple.ranks,
|
|
1399
|
+
text,
|
|
1400
|
+
verdict: simple.verdict,
|
|
1401
|
+
priorityAction: simple.priorityAction,
|
|
1402
|
+
grid,
|
|
1403
|
+
metrics
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/**
|
|
1408
|
+
* Pure zero-Node formatter for the Claude Code `statusLine` RSL budget segment.
|
|
1409
|
+
*
|
|
1410
|
+
* @param {object} rsl
|
|
1411
|
+
* @returns {string}
|
|
1412
|
+
*/
|
|
1413
|
+
export function formatRslStatusSegment(rsl) {
|
|
1414
|
+
if (!rsl || typeof rsl !== 'object') return '';
|
|
1415
|
+
const rules = Math.max(0, Number(rsl.activeRules ?? 0));
|
|
1416
|
+
const tokens = Math.max(0, Number(rsl.ruleBudgetTokens ?? 0));
|
|
1417
|
+
const clashes = Math.max(0, Number(rsl.clashCount ?? 0));
|
|
1418
|
+
const budgetStr =
|
|
1419
|
+
tokens >= 1000 ? `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k` : String(tokens);
|
|
1420
|
+
const base = `RSL: ${rules} rules | Budget: ${budgetStr}/20k`;
|
|
1421
|
+
return clashes > 0 ? `${base} | ${clashes} clash!` : base;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/**
|
|
1425
|
+
* 4. Renders a single-line terminal `statusLine` adapting cleanly to terminal column width
|
|
1426
|
+
* (`80`, `110`, `144`, or arbitrary column count).
|
|
1427
|
+
*
|
|
1428
|
+
* Guaranteed invariant: `stripAnsi(result.line).length <= columns`.
|
|
1429
|
+
*
|
|
1430
|
+
* @param {object} [state={}]
|
|
1431
|
+
* @param {object} [options={}]
|
|
1432
|
+
* @param {number} [options.columns=110]
|
|
1433
|
+
* @param {boolean} [options.ansi=true]
|
|
1434
|
+
* @returns {{
|
|
1435
|
+
* line: string,
|
|
1436
|
+
* plainLine: string,
|
|
1437
|
+
* visibleLength: number,
|
|
1438
|
+
* columns: number,
|
|
1439
|
+
* layoutTier: 'compact-80'|'standard-110'|'wide-144',
|
|
1440
|
+
* grid: object,
|
|
1441
|
+
* metrics: object
|
|
1442
|
+
* }}
|
|
1443
|
+
*/
|
|
1444
|
+
export function renderStatusLine(state = {}, options = {}) {
|
|
1445
|
+
const columns = Math.max(
|
|
1446
|
+
40,
|
|
1447
|
+
Number(options.columns || options.maxCols || globalThis.process?.stdout?.columns || 110)
|
|
1448
|
+
);
|
|
1449
|
+
const useAnsi = options.ansi !== false && !isNoColorEnabled(options);
|
|
1450
|
+
const metrics = deriveSurfaceMetrics(state, options);
|
|
1451
|
+
|
|
1452
|
+
let layoutTier = 'standard-110';
|
|
1453
|
+
let candidateBarWidths = [24, 20, 16, 12];
|
|
1454
|
+
if (columns < 96) {
|
|
1455
|
+
layoutTier = 'compact-80';
|
|
1456
|
+
candidateBarWidths = [20, 16, 14, 12];
|
|
1457
|
+
} else if (columns >= 132) {
|
|
1458
|
+
layoutTier = 'wide-144';
|
|
1459
|
+
candidateBarWidths = [40, 24, 20, 16, 12];
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
const breakerId =
|
|
1463
|
+
options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || '';
|
|
1464
|
+
const shortMode =
|
|
1465
|
+
metrics.flightMode === 'AUTO_PILOT' ? 'AUTO' : metrics.flightMode;
|
|
1466
|
+
const fullCoachPill =
|
|
1467
|
+
options.breakerVerdict?.triggered && breakerId
|
|
1468
|
+
? `[${shortMode}·${breakerId}]`
|
|
1469
|
+
: layoutTier === 'wide-144'
|
|
1470
|
+
? `[${metrics.flightMode}]`
|
|
1471
|
+
: metrics.flightMode;
|
|
1472
|
+
const compactCoachPill =
|
|
1473
|
+
options.breakerVerdict?.triggered && breakerId ? breakerId : shortMode;
|
|
1474
|
+
|
|
1475
|
+
const pillVariants =
|
|
1476
|
+
fullCoachPill === compactCoachPill ? [fullCoachPill] : [fullCoachPill, compactCoachPill];
|
|
1477
|
+
|
|
1478
|
+
let chosenGrid = null;
|
|
1479
|
+
let plainCandidate = '';
|
|
1480
|
+
let ansiCandidate = '';
|
|
1481
|
+
let matchedFit = false;
|
|
1482
|
+
|
|
1483
|
+
for (const pill of pillVariants) {
|
|
1484
|
+
for (const barWidth of candidateBarWidths) {
|
|
1485
|
+
const g = computeHorizonGrid(state, { ...options, cellCount: barWidth });
|
|
1486
|
+
const tokStr = `${formatTokensCompact(g.totalInputTokens)}/${g.zoomTier.id}`;
|
|
1487
|
+
const ttlStr = metrics.cacheWarm ? metrics.ttlCompact : 'COLD';
|
|
1488
|
+
const savedStr = formatUsd(metrics.savedUSD);
|
|
1489
|
+
const loopStr = state.thinkingDrift?.loop?.triggered ? ` ${formatDriftCompact(state.thinkingDrift)}` : '';
|
|
1490
|
+
const retStr = state.prefixRetention?.measured ? ` · ${formatRetentionCompact(state.prefixRetention)}` : '';
|
|
1491
|
+
const swarmTok = layoutTier === 'wide-144' ? formatSwarmCompact(computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() })) : '';
|
|
1492
|
+
const swarmStr = swarmTok ? ` · ${swarmTok}` : '';
|
|
1493
|
+
const rslData = options.rsl || state.rsl || null;
|
|
1494
|
+
const rslTok = layoutTier !== 'compact-80' && rslData ? formatRslStatusSegment(rslData) : '';
|
|
1495
|
+
const rslStr = rslTok ? ` · ${rslTok}` : '';
|
|
1496
|
+
|
|
1497
|
+
const prefix = options.legacyPrefix ? 'AH' : 'HB';
|
|
1498
|
+
let p = '';
|
|
1499
|
+
let a = '';
|
|
1500
|
+
if (layoutTier === 'compact-80') {
|
|
1501
|
+
p = `${prefix} ${g.bracketedBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
|
|
1502
|
+
a = `${prefix} ${g.ansiCodeBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
|
|
1503
|
+
} else {
|
|
1504
|
+
const shortModel = g.modelId.replace(/^claude-/, '');
|
|
1505
|
+
p = `${prefix} ${g.bracketedBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
|
|
1506
|
+
a = `${prefix} ${g.ansiCodeBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
chosenGrid = g;
|
|
1510
|
+
plainCandidate = p;
|
|
1511
|
+
ansiCandidate = a;
|
|
1512
|
+
|
|
1513
|
+
if (p.length <= columns) {
|
|
1514
|
+
matchedFit = true;
|
|
1515
|
+
break;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
if (matchedFit) break;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
// Enforce strict column ceiling via ANSI-preserving truncation (never stripping ANSI colors!)
|
|
1522
|
+
if (plainCandidate.length > columns) {
|
|
1523
|
+
plainCandidate = plainCandidate.slice(0, columns);
|
|
1524
|
+
ansiCandidate = truncateAnsiVisible(ansiCandidate, columns);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
const finalLine = useAnsi ? ansiCandidate : plainCandidate;
|
|
1528
|
+
const visibleLength = stripAnsi(finalLine).length;
|
|
1529
|
+
|
|
1530
|
+
return {
|
|
1531
|
+
line: finalLine,
|
|
1532
|
+
plainLine: stripAnsi(finalLine),
|
|
1533
|
+
visibleLength,
|
|
1534
|
+
columns,
|
|
1535
|
+
layoutTier,
|
|
1536
|
+
grid: chosenGrid,
|
|
1537
|
+
metrics
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
export default {
|
|
1542
|
+
stripAnsi,
|
|
1543
|
+
truncateAnsiVisible,
|
|
1544
|
+
buildScaleTickRuler,
|
|
1545
|
+
formatTokensCompact,
|
|
1546
|
+
formatDurationCompact,
|
|
1547
|
+
formatUsd,
|
|
1548
|
+
isIgnorableClaudePath,
|
|
1549
|
+
deriveClaudeCodeVerdictAndActions,
|
|
1550
|
+
deriveSurfaceMetrics,
|
|
1551
|
+
renderAbovePromptBand,
|
|
1552
|
+
renderSpinnerSuffix,
|
|
1553
|
+
renderSimpleViewPane,
|
|
1554
|
+
renderSimpleHudPane,
|
|
1555
|
+
renderAdvancedViewPane,
|
|
1556
|
+
formatRslStatusSegment,
|
|
1557
|
+
renderStatusLine
|
|
1558
|
+
};
|