ctxtop 0.0.0-stage → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -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 +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/coach/ttlWatchdog.mjs
|
|
3
|
+
* 5-Minute Anthropic KV-Cache TTL Cliff Watchdog, Zero-Token `StateBaton` T-10s Pre-Snapshotter,
|
|
4
|
+
* and Inter-Turn Pause Distribution Analyzer (>= 3.1% 5m-to-60m pause ratio -> 1h tier recommendation).
|
|
5
|
+
*
|
|
6
|
+
* Strictly zero outbound network sockets: never sends synthetic un-credentialed HTTPS pings.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
normalizeModelId,
|
|
11
|
+
computeTotalPromptTokens,
|
|
12
|
+
resolveEffectiveRates
|
|
13
|
+
} from '../config/catalogLoader.mjs';
|
|
14
|
+
import { FLIGHT_MODES, normalizeFlightMode, isSilentOrOffMode } from './cacheGravityRouter.mjs';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_MIN_CACHED_TOKENS_FOR_WATCHDOG = 25000;
|
|
17
|
+
export const DEFAULT_AMBER_THRESHOLD_SECONDS = 45;
|
|
18
|
+
export const DEFAULT_KEEP_ALIVE_THRESHOLD_SECONDS = 15;
|
|
19
|
+
export const DEFAULT_SNAPSHOT_THRESHOLD_SECONDS = 10;
|
|
20
|
+
export const ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD = 0.031; // 3.1% (~1 in 30 turns)
|
|
21
|
+
export const FIVE_MINUTES_SECONDS = 300;
|
|
22
|
+
export const SIXTY_MINUTES_SECONDS = 3600;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Formats remaining seconds into compact `4m12s` or `42s` display format.
|
|
26
|
+
* @param {number} remainingSeconds
|
|
27
|
+
* @returns {string}
|
|
28
|
+
*/
|
|
29
|
+
export function formatRemainingTtl(remainingSeconds = 0) {
|
|
30
|
+
const sec = Math.max(0, Math.floor(Number(remainingSeconds || 0)));
|
|
31
|
+
if (sec <= 0) return '0s';
|
|
32
|
+
const mins = Math.floor(sec / 60);
|
|
33
|
+
const remSec = sec % 60;
|
|
34
|
+
if (mins === 0) return `${remSec}s`;
|
|
35
|
+
return `${mins}m${String(remSec).padStart(2, '0')}s`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Builds a lightweight zero-token `StateBaton` pre-snapshot at T-10s before cache expiry.
|
|
40
|
+
* @param {object} context
|
|
41
|
+
* @returns {object}
|
|
42
|
+
*/
|
|
43
|
+
export function buildPreExpiryStateBaton(context = {}) {
|
|
44
|
+
return {
|
|
45
|
+
schemaVersion: '2026.11.1',
|
|
46
|
+
trigger: 'TTL_T_MINUS_10S_PRE_SNAPSHOT',
|
|
47
|
+
createdAt: context.nowMs || Date.now(),
|
|
48
|
+
sessionId: context.sessionId || 'default',
|
|
49
|
+
modelId: normalizeModelId(context.modelId || 'claude-opus-5-5'),
|
|
50
|
+
cachedTokensAtSnapshot: Math.max(0, Number(context.cachedTokens || 0)),
|
|
51
|
+
remainingSeconds: Math.max(0, Number(context.remainingSeconds || 0)),
|
|
52
|
+
activeGoal: context.activeGoal || 'Preserve active implementation state across 5m KV-cache TTL boundary',
|
|
53
|
+
workingSetFiles: Array.isArray(context.workingSetFiles) ? [...context.workingSetFiles] : [],
|
|
54
|
+
verifiedInvariants: Array.isArray(context.verifiedInvariants) ? [...context.verifiedInvariants] : [],
|
|
55
|
+
deadEndsAndFailures: Array.isArray(context.deadEndsAndFailures) ? [...context.deadEndsAndFailures] : [],
|
|
56
|
+
queuedCacheMutations: Array.isArray(context.queuedCacheMutations) ? [...context.queuedCacheMutations] : []
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Evaluates inter-turn pause durations (in seconds) and advises upgrading the session
|
|
62
|
+
* cache tier to `1h` when `>= 3.1%` of pauses fall in the un-pinged 5-to-60 minute window.
|
|
63
|
+
*
|
|
64
|
+
* @param {Array<number>} pauseDurationsSeconds - Array of inter-turn pause durations in seconds
|
|
65
|
+
* @param {number} [thresholdRatio=0.031]
|
|
66
|
+
* @returns {{
|
|
67
|
+
* totalIntervals: number,
|
|
68
|
+
* fiveToSixtyMinCount: number,
|
|
69
|
+
* fiveToSixtyMinRatio: number,
|
|
70
|
+
* fiveToSixtyMinPct: number,
|
|
71
|
+
* thresholdRatio: number,
|
|
72
|
+
* recommend1hTierUpgrade: boolean,
|
|
73
|
+
* advisoryMessage: string | null
|
|
74
|
+
* }}
|
|
75
|
+
*/
|
|
76
|
+
export function evaluatePauseDistribution(
|
|
77
|
+
pauseDurationsSeconds = [],
|
|
78
|
+
thresholdRatio = ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD
|
|
79
|
+
) {
|
|
80
|
+
const validPauses = Array.isArray(pauseDurationsSeconds)
|
|
81
|
+
? pauseDurationsSeconds.map((v) => Number(v)).filter((v) => Number.isFinite(v) && v >= 0)
|
|
82
|
+
: [];
|
|
83
|
+
|
|
84
|
+
const totalIntervals = validPauses.length;
|
|
85
|
+
if (totalIntervals === 0) {
|
|
86
|
+
return {
|
|
87
|
+
totalIntervals: 0,
|
|
88
|
+
fiveToSixtyMinCount: 0,
|
|
89
|
+
fiveToSixtyMinRatio: 0,
|
|
90
|
+
fiveToSixtyMinPct: 0,
|
|
91
|
+
thresholdRatio,
|
|
92
|
+
recommend1hTierUpgrade: false,
|
|
93
|
+
advisoryMessage: null
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const fiveToSixtyMinCount = validPauses.filter(
|
|
98
|
+
(sec) => sec > FIVE_MINUTES_SECONDS && sec <= SIXTY_MINUTES_SECONDS
|
|
99
|
+
).length;
|
|
100
|
+
|
|
101
|
+
const fiveToSixtyMinRatio = Number((fiveToSixtyMinCount / totalIntervals).toFixed(4));
|
|
102
|
+
const fiveToSixtyMinPct = Number((fiveToSixtyMinRatio * 100).toFixed(2));
|
|
103
|
+
const recommend1hTierUpgrade = fiveToSixtyMinRatio >= thresholdRatio;
|
|
104
|
+
|
|
105
|
+
const advisoryMessage = recommend1hTierUpgrade
|
|
106
|
+
? `Inter-turn pause telemetry: ${fiveToSixtyMinPct}% of turns (${fiveToSixtyMinCount}/${totalIntervals}) ` +
|
|
107
|
+
`followed a 5-to-60 minute pause (>= ${(thresholdRatio * 100).toFixed(1)}% break-even threshold). ` +
|
|
108
|
+
`Upgrade session prompt cache tier from 5m (1.25x) to 1h (2.0x) to prevent recurring cold prefix rewrites.`
|
|
109
|
+
: null;
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
totalIntervals,
|
|
113
|
+
fiveToSixtyMinCount,
|
|
114
|
+
fiveToSixtyMinRatio,
|
|
115
|
+
fiveToSixtyMinPct,
|
|
116
|
+
thresholdRatio,
|
|
117
|
+
recommend1hTierUpgrade,
|
|
118
|
+
advisoryMessage
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 5-Minute TTL Cliff Watchdog.
|
|
124
|
+
* Tracks `prompt_cache.expires_at` on a 1-second tick, pulses amber countdown alerts at `<= 45s`,
|
|
125
|
+
* takes zero-token `StateBaton` pre-snapshots at `T-10s` in `AUTO_PILOT` mode, and tracks
|
|
126
|
+
* inter-turn pause distribution (`>= 3.1%` -> recommend `1h` cache tier).
|
|
127
|
+
*/
|
|
128
|
+
export class TtlWatchdog {
|
|
129
|
+
/**
|
|
130
|
+
* @param {object} [options={}]
|
|
131
|
+
*/
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
this.options = options;
|
|
134
|
+
this.mode = normalizeFlightMode(options.mode || FLIGHT_MODES.COACH);
|
|
135
|
+
this.minCachedTokens = Number(
|
|
136
|
+
options.minCachedTokens ?? DEFAULT_MIN_CACHED_TOKENS_FOR_WATCHDOG
|
|
137
|
+
);
|
|
138
|
+
this.amberThresholdSeconds = Number(
|
|
139
|
+
options.amberThresholdSeconds ?? DEFAULT_AMBER_THRESHOLD_SECONDS
|
|
140
|
+
);
|
|
141
|
+
this.keepAliveThresholdSeconds = Number(
|
|
142
|
+
options.keepAliveThresholdSeconds ?? DEFAULT_KEEP_ALIVE_THRESHOLD_SECONDS
|
|
143
|
+
);
|
|
144
|
+
this.snapshotThresholdSeconds = Number(
|
|
145
|
+
options.snapshotThresholdSeconds ?? DEFAULT_SNAPSHOT_THRESHOLD_SECONDS
|
|
146
|
+
);
|
|
147
|
+
this.pauseRatioThreshold = Number(
|
|
148
|
+
options.pauseRatioThreshold ?? ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
this.lastTurnTimestampMs = options.lastTurnTimestampMs ?? null;
|
|
152
|
+
this.pauseDurationsSeconds = Array.isArray(options.pauseDurationsSeconds)
|
|
153
|
+
? [...options.pauseDurationsSeconds]
|
|
154
|
+
: [];
|
|
155
|
+
this.lastFileChangedAtMs = options.lastFileChangedAtMs ?? null;
|
|
156
|
+
this.workingSetFiles = new Set(options.workingSetFiles || []);
|
|
157
|
+
this.lastSnapshotExpiryCycle = null;
|
|
158
|
+
this.lastKeepAliveExpiryCycle = null;
|
|
159
|
+
this.latestSnapshot = null;
|
|
160
|
+
this.onSnapshotCallback = typeof options.onSnapshot === 'function' ? options.onSnapshot : null;
|
|
161
|
+
this.onKeepAliveCallback =
|
|
162
|
+
typeof options.onKeepAlive === 'function' ? options.onKeepAlive : null;
|
|
163
|
+
this.enableLocalKeepAlive = Boolean(options.enableLocalKeepAlive);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Sets Flight Computer mode (`OFF | COACH | AUTO_PILOT`).
|
|
168
|
+
* @param {string} mode
|
|
169
|
+
*/
|
|
170
|
+
setMode(mode) {
|
|
171
|
+
this.mode = normalizeFlightMode(mode);
|
|
172
|
+
return this.mode;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Records a workspace `FileChanged` event so the watchdog knows active edits are in progress.
|
|
177
|
+
* @param {string} [filePath]
|
|
178
|
+
* @param {number} [nowMs=Date.now()]
|
|
179
|
+
*/
|
|
180
|
+
recordFileChanged(filePath = '', nowMs = Date.now()) {
|
|
181
|
+
this.lastFileChangedAtMs = nowMs;
|
|
182
|
+
if (filePath) {
|
|
183
|
+
this.workingSetFiles.add(String(filePath));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Clears the recent workspace edit flag (e.g. after commit, test pass, or compaction).
|
|
189
|
+
*/
|
|
190
|
+
clearRecentEdits() {
|
|
191
|
+
this.lastFileChangedAtMs = null;
|
|
192
|
+
this.workingSetFiles.clear();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Records a turn timestamp and updates inter-turn pause distribution telemetry.
|
|
197
|
+
* @param {number} [nowMs=Date.now()]
|
|
198
|
+
* @returns {object} Pause distribution summary
|
|
199
|
+
*/
|
|
200
|
+
recordTurnTimestamp(nowMs = Date.now()) {
|
|
201
|
+
if (this.lastTurnTimestampMs !== null && nowMs >= this.lastTurnTimestampMs) {
|
|
202
|
+
const pauseSec = (nowMs - this.lastTurnTimestampMs) / 1000;
|
|
203
|
+
this.pauseDurationsSeconds.push(Number(pauseSec.toFixed(2)));
|
|
204
|
+
}
|
|
205
|
+
this.lastTurnTimestampMs = nowMs;
|
|
206
|
+
return this.getPauseDistribution();
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Directly records an inter-turn pause duration in seconds.
|
|
211
|
+
* @param {number} pauseSeconds
|
|
212
|
+
* @returns {object} Pause distribution summary
|
|
213
|
+
*/
|
|
214
|
+
recordPauseDurationSeconds(pauseSeconds) {
|
|
215
|
+
const sec = Number(pauseSeconds);
|
|
216
|
+
if (Number.isFinite(sec) && sec >= 0) {
|
|
217
|
+
this.pauseDurationsSeconds.push(sec);
|
|
218
|
+
}
|
|
219
|
+
return this.getPauseDistribution();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Evaluates current inter-turn pause distribution against the 3.1% 1h-tier threshold.
|
|
224
|
+
*/
|
|
225
|
+
getPauseDistribution() {
|
|
226
|
+
return evaluatePauseDistribution(this.pauseDurationsSeconds, this.pauseRatioThreshold);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Evaluates a 1-second watchdog tick against the active prompt cache expiration deadline.
|
|
231
|
+
*
|
|
232
|
+
* @param {object} [tickState={}]
|
|
233
|
+
* @param {boolean} [tickState.cacheWarm=false]
|
|
234
|
+
* @param {number} [tickState.cachedTokens=0]
|
|
235
|
+
* @param {number|string|null} [tickState.expiresAt=null] - Epoch ms or ISO timestamp
|
|
236
|
+
* @param {number} [tickState.remainingSeconds] - Optional explicit remaining seconds
|
|
237
|
+
* @param {string} [tickState.modelId='claude-opus-5-5']
|
|
238
|
+
* @param {boolean} [tickState.hasRecentWorkspaceEdits] - Defaults to true if FileChanged recorded
|
|
239
|
+
* @param {string} [tickState.mode] - Optional mode override (`OFF | COACH | AUTO_PILOT`)
|
|
240
|
+
* @param {number} [tickState.nowMs=Date.now()]
|
|
241
|
+
*/
|
|
242
|
+
evaluateTick(tickState = {}) {
|
|
243
|
+
const nowMs = tickState.nowMs ?? Date.now();
|
|
244
|
+
const activeMode = tickState.mode ? normalizeFlightMode(tickState.mode) : this.mode;
|
|
245
|
+
const modelId = normalizeModelId(tickState.modelId || 'claude-opus-5-5');
|
|
246
|
+
const cachedTokens = Math.max(0, Number(tickState.cachedTokens ?? 0));
|
|
247
|
+
|
|
248
|
+
const force5mDrop =
|
|
249
|
+
Boolean(tickState.aiCreditOveragesActive) ||
|
|
250
|
+
Boolean(tickState.isSubagent) ||
|
|
251
|
+
String(tickState.billingMode || '').toLowerCase() === 'api';
|
|
252
|
+
const effectiveTtlSeconds =
|
|
253
|
+
tickState.planDefaultTtlSeconds != null
|
|
254
|
+
? (force5mDrop ? FIVE_MINUTES_SECONDS : Math.max(60, Number(tickState.planDefaultTtlSeconds)))
|
|
255
|
+
: ((tickState.cacheTtlTier || tickState.ttlTier || this.options?.cacheTtlTier) === '1h'
|
|
256
|
+
? (force5mDrop ? FIVE_MINUTES_SECONDS : SIXTY_MINUTES_SECONDS)
|
|
257
|
+
: FIVE_MINUTES_SECONDS);
|
|
258
|
+
const ttlDroppedTo5m =
|
|
259
|
+
(tickState.planDefaultTtlSeconds != null && Number(tickState.planDefaultTtlSeconds) > FIVE_MINUTES_SECONDS && effectiveTtlSeconds === FIVE_MINUTES_SECONDS) ||
|
|
260
|
+
(((tickState.cacheTtlTier || tickState.ttlTier || this.options?.cacheTtlTier) === '1h') && force5mDrop);
|
|
261
|
+
|
|
262
|
+
let expiresAtMs = null;
|
|
263
|
+
if (typeof tickState.expiresAt === 'number' && Number.isFinite(tickState.expiresAt)) {
|
|
264
|
+
expiresAtMs = tickState.expiresAt < 1e11 ? tickState.expiresAt * 1000 : tickState.expiresAt;
|
|
265
|
+
} else if (typeof tickState.expiresAt === 'string' && tickState.expiresAt.trim()) {
|
|
266
|
+
const parsed = Date.parse(tickState.expiresAt);
|
|
267
|
+
if (!Number.isNaN(parsed)) expiresAtMs = parsed;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
let remainingSeconds = 0;
|
|
271
|
+
if (typeof tickState.remainingSeconds === 'number' && Number.isFinite(tickState.remainingSeconds)) {
|
|
272
|
+
remainingSeconds = Math.max(0, Math.ceil(tickState.remainingSeconds));
|
|
273
|
+
if (expiresAtMs === null) {
|
|
274
|
+
expiresAtMs = nowMs + remainingSeconds * 1000;
|
|
275
|
+
}
|
|
276
|
+
} else if (expiresAtMs !== null) {
|
|
277
|
+
remainingSeconds = Math.max(0, Math.ceil((expiresAtMs - nowMs) / 1000));
|
|
278
|
+
} else if (typeof tickState.elapsedSeconds === 'number' && Number.isFinite(tickState.elapsedSeconds)) {
|
|
279
|
+
remainingSeconds = Math.max(0, Math.ceil(effectiveTtlSeconds - Math.max(0, tickState.elapsedSeconds)));
|
|
280
|
+
expiresAtMs = nowMs + remainingSeconds * 1000;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const cacheExpired =
|
|
284
|
+
typeof tickState.elapsedSeconds === 'number'
|
|
285
|
+
? tickState.elapsedSeconds > effectiveTtlSeconds
|
|
286
|
+
: remainingSeconds <= 0 && cachedTokens > 0 && tickState.cacheWarm === false;
|
|
287
|
+
|
|
288
|
+
const cacheWarm =
|
|
289
|
+
tickState.cacheWarm !== undefined
|
|
290
|
+
? Boolean(tickState.cacheWarm) && !cacheExpired
|
|
291
|
+
: cachedTokens > 0 && !cacheExpired;
|
|
292
|
+
|
|
293
|
+
const hasRecentWorkspaceEdits =
|
|
294
|
+
tickState.hasRecentWorkspaceEdits !== undefined
|
|
295
|
+
? Boolean(tickState.hasRecentWorkspaceEdits)
|
|
296
|
+
: this.lastFileChangedAtMs !== null;
|
|
297
|
+
|
|
298
|
+
const tier = effectiveTtlSeconds >= SIXTY_MINUTES_SECONDS ? '1h' : '5m';
|
|
299
|
+
const totalPromptTokens = Math.max(cachedTokens, computeTotalPromptTokens(tickState));
|
|
300
|
+
const rates = resolveEffectiveRates(
|
|
301
|
+
tickState.modelId || 'claude-opus-5-5',
|
|
302
|
+
totalPromptTokens,
|
|
303
|
+
this.options
|
|
304
|
+
);
|
|
305
|
+
const hasKnownPrices = Boolean(rates && !rates.unknownModel && rates.readPer1M !== null);
|
|
306
|
+
const writeRate = hasKnownPrices
|
|
307
|
+
? (tier === '1h' ? rates.write1hPer1M : rates.write5mPer1M)
|
|
308
|
+
: null;
|
|
309
|
+
// Cost of losing the warm cache and rewriting it at writeRate (1.25x 5m / 2.0x 1h) instead of reading at readPer1M
|
|
310
|
+
const expiryPenaltyUSD = hasKnownPrices
|
|
311
|
+
? Number(((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6))
|
|
312
|
+
: null;
|
|
313
|
+
|
|
314
|
+
const formattedRemaining = formatRemainingTtl(remainingSeconds);
|
|
315
|
+
const pauseDistribution = this.getPauseDistribution();
|
|
316
|
+
|
|
317
|
+
const suppressed = isSilentOrOffMode(activeMode);
|
|
318
|
+
const meetsWatchdogCriteria =
|
|
319
|
+
!suppressed &&
|
|
320
|
+
cacheWarm &&
|
|
321
|
+
cachedTokens >= this.minCachedTokens &&
|
|
322
|
+
remainingSeconds > 0 &&
|
|
323
|
+
remainingSeconds <= this.amberThresholdSeconds &&
|
|
324
|
+
hasRecentWorkspaceEdits;
|
|
325
|
+
|
|
326
|
+
if (!meetsWatchdogCriteria) {
|
|
327
|
+
let statusReason = 'IDLE';
|
|
328
|
+
if (suppressed) {
|
|
329
|
+
statusReason = 'MODE_SILENT';
|
|
330
|
+
} else if (!cacheWarm || remainingSeconds <= 0) {
|
|
331
|
+
statusReason = 'CACHE_COLD_OR_EXPIRED';
|
|
332
|
+
} else if (cachedTokens < this.minCachedTokens) {
|
|
333
|
+
statusReason = 'BELOW_MIN_CACHED_TOKENS';
|
|
334
|
+
} else if (!hasRecentWorkspaceEdits) {
|
|
335
|
+
statusReason = 'IDLE_NO_EDITS';
|
|
336
|
+
} else if (remainingSeconds > this.amberThresholdSeconds) {
|
|
337
|
+
statusReason = 'TTL_HEALTHY';
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
detectorId: 'DET-10',
|
|
342
|
+
mode: activeMode,
|
|
343
|
+
statusReason,
|
|
344
|
+
effectiveTtlSeconds,
|
|
345
|
+
ttlDroppedTo5m,
|
|
346
|
+
cacheExpired,
|
|
347
|
+
cacheWarm: cacheWarm && remainingSeconds > 0,
|
|
348
|
+
cachedTokens,
|
|
349
|
+
remainingSeconds,
|
|
350
|
+
formattedRemaining,
|
|
351
|
+
amberAlertActive: false,
|
|
352
|
+
alertLevel: (remainingSeconds === 0 && cacheWarm) || cacheExpired ? 'EXPIRED' : 'NONE',
|
|
353
|
+
expiryPenaltyUSD,
|
|
354
|
+
availableActions: [],
|
|
355
|
+
preSnapshotTriggered: false,
|
|
356
|
+
stateBatonSnapshot: null,
|
|
357
|
+
bannerText: null,
|
|
358
|
+
pauseDistribution
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Amber alert is active (remainingSeconds <= 45)
|
|
363
|
+
let alertLevel = 'AMBER';
|
|
364
|
+
let preSnapshotTriggered = false;
|
|
365
|
+
let keepAliveTriggered = false;
|
|
366
|
+
let stateBatonSnapshot = null;
|
|
367
|
+
const availableActions =
|
|
368
|
+
activeMode === FLIGHT_MODES.COACH
|
|
369
|
+
? ['KEEP_ALIVE_PROMPT', 'SNAPSHOT_STATE_BATON']
|
|
370
|
+
: ['AUTO_SNAPSHOT_STATE_BATON', 'LOCAL_CLI_KEEP_ALIVE'];
|
|
371
|
+
|
|
372
|
+
const cycleKey = expiresAtMs ? Math.round(expiresAtMs / 1000) : 'active_cycle';
|
|
373
|
+
|
|
374
|
+
if (
|
|
375
|
+
activeMode === FLIGHT_MODES.AUTO_PILOT &&
|
|
376
|
+
(this.enableLocalKeepAlive || tickState.optInLocalKeepAlive === true) &&
|
|
377
|
+
remainingSeconds <= this.keepAliveThresholdSeconds &&
|
|
378
|
+
this.lastKeepAliveExpiryCycle !== cycleKey
|
|
379
|
+
) {
|
|
380
|
+
this.lastKeepAliveExpiryCycle = cycleKey;
|
|
381
|
+
keepAliveTriggered = true;
|
|
382
|
+
if (this.onKeepAliveCallback) {
|
|
383
|
+
this.onKeepAliveCallback({
|
|
384
|
+
sessionId: tickState.sessionId || 'default',
|
|
385
|
+
modelId,
|
|
386
|
+
cachedTokens,
|
|
387
|
+
remainingSeconds,
|
|
388
|
+
expiryPenaltyUSD
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (
|
|
394
|
+
remainingSeconds <= this.snapshotThresholdSeconds &&
|
|
395
|
+
(activeMode === FLIGHT_MODES.AUTO_PILOT || tickState.optInAutoSnapshot === true)
|
|
396
|
+
) {
|
|
397
|
+
alertLevel = 'CRITICAL_SNAPSHOT';
|
|
398
|
+
if (this.lastSnapshotExpiryCycle !== cycleKey) {
|
|
399
|
+
this.lastSnapshotExpiryCycle = cycleKey;
|
|
400
|
+
preSnapshotTriggered = true;
|
|
401
|
+
stateBatonSnapshot = buildPreExpiryStateBaton({
|
|
402
|
+
nowMs,
|
|
403
|
+
sessionId: tickState.sessionId || 'default',
|
|
404
|
+
modelId,
|
|
405
|
+
cachedTokens,
|
|
406
|
+
remainingSeconds,
|
|
407
|
+
activeGoal: tickState.activeGoal,
|
|
408
|
+
workingSetFiles:
|
|
409
|
+
tickState.workingSetFiles || Array.from(this.workingSetFiles),
|
|
410
|
+
verifiedInvariants: tickState.verifiedInvariants,
|
|
411
|
+
deadEndsAndFailures: tickState.deadEndsAndFailures,
|
|
412
|
+
queuedCacheMutations: tickState.queuedCacheMutations
|
|
413
|
+
});
|
|
414
|
+
this.latestSnapshot = stateBatonSnapshot;
|
|
415
|
+
if (this.onSnapshotCallback) {
|
|
416
|
+
this.onSnapshotCallback(stateBatonSnapshot);
|
|
417
|
+
}
|
|
418
|
+
} else {
|
|
419
|
+
stateBatonSnapshot = this.latestSnapshot;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const penaltySuffix =
|
|
424
|
+
expiryPenaltyUSD !== null
|
|
425
|
+
? ` ($${expiryPenaltyUSD.toFixed(2)} rewrite)`
|
|
426
|
+
: ' (prices unknown)';
|
|
427
|
+
const bannerText = preSnapshotTriggered
|
|
428
|
+
? `amber TTL cliff (${formattedRemaining}): zero-token StateBaton pre-snapshot saved at T-${remainingSeconds}s (protects ${(cachedTokens / 1000).toFixed(1)}k cache${penaltySuffix}).`
|
|
429
|
+
: `amber TTL warning (${formattedRemaining}): ${(cachedTokens / 1000).toFixed(1)}k warm cache on ${rates.shortLabel} expires soon${expiryPenaltyUSD !== null ? ` (+$${expiryPenaltyUSD.toFixed(2)} rewrite penalty)` : '; prices unknown'}.`;
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
detectorId: 'DET-10',
|
|
433
|
+
mode: activeMode,
|
|
434
|
+
statusReason: preSnapshotTriggered ? 'PRE_SNAPSHOT_SAVED' : 'AMBER_WARNING',
|
|
435
|
+
effectiveTtlSeconds,
|
|
436
|
+
ttlDroppedTo5m,
|
|
437
|
+
cacheExpired,
|
|
438
|
+
cacheWarm: true,
|
|
439
|
+
cachedTokens,
|
|
440
|
+
remainingSeconds,
|
|
441
|
+
formattedRemaining,
|
|
442
|
+
amberAlertActive: true,
|
|
443
|
+
alertLevel,
|
|
444
|
+
expiryPenaltyUSD,
|
|
445
|
+
availableActions,
|
|
446
|
+
keepAliveTriggered,
|
|
447
|
+
preSnapshotTriggered,
|
|
448
|
+
stateBatonSnapshot,
|
|
449
|
+
bannerText,
|
|
450
|
+
pauseDistribution
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export default {
|
|
456
|
+
DEFAULT_MIN_CACHED_TOKENS_FOR_WATCHDOG,
|
|
457
|
+
DEFAULT_AMBER_THRESHOLD_SECONDS,
|
|
458
|
+
DEFAULT_SNAPSHOT_THRESHOLD_SECONDS,
|
|
459
|
+
ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD,
|
|
460
|
+
formatRemainingTtl,
|
|
461
|
+
buildPreExpiryStateBaton,
|
|
462
|
+
evaluatePauseDistribution,
|
|
463
|
+
TtlWatchdog
|
|
464
|
+
};
|