ctxtop 0.0.0-stage → 4.0.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 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- 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 +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -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 +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -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 +2002 -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 +42 -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 +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -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 +620 -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/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 +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -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 +966 -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 +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -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/sanitizer.mjs +121 -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/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 +720 -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/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -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 +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -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/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -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 +1132 -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 +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -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/doctorEngine.mjs +203 -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 +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -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 +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -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/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/economics/cliffBreaker.mjs
|
|
3
|
+
* Feature 20: Haiku 100k 5x Cliff Breaker (DET-12).
|
|
4
|
+
*
|
|
5
|
+
* Implements:
|
|
6
|
+
* - Total prompt token envelope monitoring for Haiku models
|
|
7
|
+
* - Exemption of all non-Haiku models (Sonnet, Opus, Gemini, etc.)
|
|
8
|
+
* - 4-Tier trigger matrix:
|
|
9
|
+
* < 90k: allow (nominal)
|
|
10
|
+
* 90k - 98k: advisory (advise_compact)
|
|
11
|
+
* 98k - 100k: warn / deny (hard circuit breaker trip)
|
|
12
|
+
* >= 100k: halt / deny (emergency halt for 5x cost cliff)
|
|
13
|
+
*
|
|
14
|
+
* Adheres strictly to Claude Mod Laws 1–5: pure ESM, zero `node:*` imports, zero Node globals.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { computeTotalPromptTokens } from '../config/catalogLoader.mjs';
|
|
18
|
+
|
|
19
|
+
export const HAIKU_CLIFF_DETECTOR_ID = 'DET-12';
|
|
20
|
+
|
|
21
|
+
export const HAIKU_CLIFF_THRESHOLDS = Object.freeze({
|
|
22
|
+
ADVISORY_TOKENS: 90000,
|
|
23
|
+
BREAKER_TOKENS: 98000,
|
|
24
|
+
CLIFF_TOKENS: 100000,
|
|
25
|
+
PRICE_MULTIPLIER: 5.0
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Checks whether a given model string corresponds to an Anthropic Claude Haiku model.
|
|
30
|
+
* @param {string} [modelId='']
|
|
31
|
+
* @returns {boolean}
|
|
32
|
+
*/
|
|
33
|
+
export function isHaikuModel(modelId = '') {
|
|
34
|
+
return String(modelId || '').toLowerCase().includes('haiku');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Evaluates prompt token volume against the Haiku 100k 5x price cliff.
|
|
39
|
+
*
|
|
40
|
+
* @param {string} [modelId='']
|
|
41
|
+
* @param {number} [promptTokens=0]
|
|
42
|
+
* @returns {{
|
|
43
|
+
* triggered: boolean,
|
|
44
|
+
* threshold: number,
|
|
45
|
+
* action: 'allow' | 'advisory' | 'warn' | 'halt',
|
|
46
|
+
* reason: string
|
|
47
|
+
* }}
|
|
48
|
+
*/
|
|
49
|
+
export function checkHaiku100kCliffBreaker(modelId = '', promptTokens = 0) {
|
|
50
|
+
const isHaiku = isHaikuModel(modelId);
|
|
51
|
+
const threshold = HAIKU_CLIFF_THRESHOLDS.BREAKER_TOKENS;
|
|
52
|
+
const tokens = Math.max(0, Number(promptTokens) || 0);
|
|
53
|
+
|
|
54
|
+
if (!isHaiku) {
|
|
55
|
+
return {
|
|
56
|
+
triggered: false,
|
|
57
|
+
threshold,
|
|
58
|
+
action: 'allow',
|
|
59
|
+
reason: 'Non-Haiku model; 100k cliff check exempt'
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (tokens >= HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS) {
|
|
64
|
+
return {
|
|
65
|
+
triggered: true,
|
|
66
|
+
threshold,
|
|
67
|
+
action: 'halt',
|
|
68
|
+
reason: `Prompt tokens (${tokens.toLocaleString()}) exceeded 100k 5x cost cliff`
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (tokens >= threshold) {
|
|
73
|
+
return {
|
|
74
|
+
triggered: true,
|
|
75
|
+
threshold,
|
|
76
|
+
action: 'warn',
|
|
77
|
+
reason: `Prompt tokens (${tokens.toLocaleString()}) reached Haiku cliff breaker threshold (${threshold})`
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (tokens >= HAIKU_CLIFF_THRESHOLDS.ADVISORY_TOKENS) {
|
|
82
|
+
return {
|
|
83
|
+
triggered: false,
|
|
84
|
+
threshold,
|
|
85
|
+
action: 'advisory',
|
|
86
|
+
reason: `Prompt tokens (${tokens.toLocaleString()}) approaching 90k advisory boundary`
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
triggered: false,
|
|
92
|
+
threshold,
|
|
93
|
+
action: 'allow',
|
|
94
|
+
reason: `Prompt tokens (${tokens.toLocaleString()}) within safe boundary`
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Evaluates DET-12 Haiku Pre-Cliff Breaker conforming to canonical detector schema.
|
|
100
|
+
*
|
|
101
|
+
* @param {object} [params={}]
|
|
102
|
+
* @param {string} [params.modelId='']
|
|
103
|
+
* @param {number} [params.totalInputTokens]
|
|
104
|
+
* @param {number} [params.promptTokens]
|
|
105
|
+
* @returns {{
|
|
106
|
+
* detectorId: 'DET-12',
|
|
107
|
+
* triggered: boolean,
|
|
108
|
+
* decision: 'allow' | 'advise_compact' | 'deny',
|
|
109
|
+
* advisory: boolean,
|
|
110
|
+
* modelId: string,
|
|
111
|
+
* totalInputTokens: number,
|
|
112
|
+
* cliffThresholdTokens: 100000,
|
|
113
|
+
* reason: string
|
|
114
|
+
* }}
|
|
115
|
+
*/
|
|
116
|
+
export function evaluateDet12HaikuPreCliffBreaker(params = {}) {
|
|
117
|
+
const safeParams = (params && typeof params === 'object') ? params : {};
|
|
118
|
+
const modelId = String(safeParams.modelId || '');
|
|
119
|
+
|
|
120
|
+
// Extract candidate token volume, prioritizing totalInputTokens, then promptTokens, then computeTotalPromptTokens
|
|
121
|
+
let candidate = safeParams.totalInputTokens;
|
|
122
|
+
if (candidate === undefined || candidate === null || Number.isNaN(Number(candidate))) {
|
|
123
|
+
candidate = safeParams.promptTokens;
|
|
124
|
+
}
|
|
125
|
+
if (candidate === undefined || candidate === null || Number.isNaN(Number(candidate))) {
|
|
126
|
+
candidate = computeTotalPromptTokens(safeParams);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const totalTokens = Math.max(0, Number(candidate) || 0);
|
|
130
|
+
|
|
131
|
+
const isHaiku = isHaikuModel(modelId);
|
|
132
|
+
if (!isHaiku || totalTokens < HAIKU_CLIFF_THRESHOLDS.ADVISORY_TOKENS) {
|
|
133
|
+
return {
|
|
134
|
+
detectorId: HAIKU_CLIFF_DETECTOR_ID,
|
|
135
|
+
triggered: false,
|
|
136
|
+
decision: 'allow',
|
|
137
|
+
advisory: false,
|
|
138
|
+
modelId,
|
|
139
|
+
totalInputTokens: totalTokens,
|
|
140
|
+
cliffThresholdTokens: HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
141
|
+
reason: isHaiku
|
|
142
|
+
? `Haiku prompt size (${totalTokens.toLocaleString()}) is within safe volume (<90k).`
|
|
143
|
+
: `Non-Haiku model (${modelId || 'unspecified'}); exempt from DET-12 100k cliff breaker.`
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const isHardDeny = totalTokens >= HAIKU_CLIFF_THRESHOLDS.BREAKER_TOKENS;
|
|
148
|
+
return {
|
|
149
|
+
detectorId: HAIKU_CLIFF_DETECTOR_ID,
|
|
150
|
+
triggered: true,
|
|
151
|
+
decision: isHardDeny ? 'deny' : 'advise_compact',
|
|
152
|
+
advisory: !isHardDeny,
|
|
153
|
+
modelId,
|
|
154
|
+
totalInputTokens: totalTokens,
|
|
155
|
+
cliffThresholdTokens: HAIKU_CLIFF_THRESHOLDS.CLIFF_TOKENS,
|
|
156
|
+
reason: isHardDeny
|
|
157
|
+
? `[DET-12 Haiku Cliff Breaker] Prompt volume (${totalTokens.toLocaleString()} tokens) reached or exceeded 98k buffer. Tripping circuit breaker before 100k 5x price jump.`
|
|
158
|
+
: `[DET-12 Haiku 90k Pre-Cliff Breaker] Prompt volume (${totalTokens.toLocaleString()} tokens) approaching 100k 5x cost cliff. Compact now to avoid 5x billing penalty.`
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Convenience wrapper returning unified breaker decision.
|
|
164
|
+
* @param {string} modelId
|
|
165
|
+
* @param {number} promptTokens
|
|
166
|
+
* @returns {object}
|
|
167
|
+
*/
|
|
168
|
+
export function evaluateHaikuCliffBreaker(modelId, promptTokens) {
|
|
169
|
+
return checkHaiku100kCliffBreaker(modelId, promptTokens);
|
|
170
|
+
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/economics/driftLatency.mjs
|
|
3
|
+
* Feature 17: Time-To-First-Token (TTFT) & Thinking vs. Generation Drift Detection.
|
|
4
|
+
*
|
|
5
|
+
* Implements:
|
|
6
|
+
* - TTFT latency tracking in milliseconds (null / "—" on <= 0 or clock skew)
|
|
7
|
+
* - Latency spike detection (> 5x baseline)
|
|
8
|
+
* - Thinking vs. generation token drift ratio (reported tokens only, non-estimated)
|
|
9
|
+
* - Scratchpad loop detection: canonical DET-30 (preserving DET-21 alias)
|
|
10
|
+
*
|
|
11
|
+
* Adheres strictly to Claude Mod Laws 1–5: pure ESM, zero `node:*` imports, zero Node globals.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const THINKING_DRIFT_DETECTOR_ID = 'DET-30';
|
|
15
|
+
export const LEGACY_THINKING_DRIFT_ALIAS = 'DET-21';
|
|
16
|
+
|
|
17
|
+
export const DRIFT_THRESHOLDS = Object.freeze({
|
|
18
|
+
MIN_THINKING_TOKENS: 4000,
|
|
19
|
+
LOOP_RATIO: 12.0,
|
|
20
|
+
ELEVATED_RATIO: 4.0,
|
|
21
|
+
CUMULATIVE_THINKING_TOKENS: 10000,
|
|
22
|
+
CONSECUTIVE_TURNS_CRITICAL: 2,
|
|
23
|
+
ROLLING_WINDOW: 3,
|
|
24
|
+
SPIKE_MULTIPLIER: 5.0
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const DRIFT_STATES = Object.freeze({
|
|
28
|
+
NOMINAL: 'nominal',
|
|
29
|
+
ELEVATED: 'elevated',
|
|
30
|
+
LOOP_SUSPECT: 'loop_suspect'
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Creates an empty initial thinking drift accumulator.
|
|
35
|
+
* @returns {object}
|
|
36
|
+
*/
|
|
37
|
+
export function createInitialThinkingDrift() {
|
|
38
|
+
return {
|
|
39
|
+
measured: false,
|
|
40
|
+
turns: [],
|
|
41
|
+
lastTtftMs: null,
|
|
42
|
+
avgTtftMs: null,
|
|
43
|
+
lastDriftRatio: null,
|
|
44
|
+
rollingDriftRatio: null,
|
|
45
|
+
cumulativeThinkingTokens: 0,
|
|
46
|
+
cumulativeOutputTokens: 0,
|
|
47
|
+
consecutiveLoopTurns: 0,
|
|
48
|
+
loop: {
|
|
49
|
+
triggered: false,
|
|
50
|
+
severity: 'nominal',
|
|
51
|
+
gaDetectorId: THINKING_DRIFT_DETECTOR_ID,
|
|
52
|
+
aliasDetectorId: LEGACY_THINKING_DRIFT_ALIAS,
|
|
53
|
+
consecutiveLoopTurns: 0,
|
|
54
|
+
cumulativeThinkingTokens: 0,
|
|
55
|
+
message: ''
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Formats millisecond TTFT into a human-readable high data-ink string.
|
|
62
|
+
* Clamps <= 0 or invalid numbers to '—' (never fabricated 0ms).
|
|
63
|
+
*
|
|
64
|
+
* @param {number|null|undefined} ms
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function formatTtft(ms) {
|
|
68
|
+
if (ms == null || typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) {
|
|
69
|
+
return '—';
|
|
70
|
+
}
|
|
71
|
+
const rounded = Math.round(ms);
|
|
72
|
+
if (rounded < 1000) {
|
|
73
|
+
return `${rounded}ms`;
|
|
74
|
+
}
|
|
75
|
+
if (rounded < 60000) {
|
|
76
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
77
|
+
}
|
|
78
|
+
const mins = Math.floor(rounded / 60000);
|
|
79
|
+
const remSec = Math.round((rounded % 60000) / 1000);
|
|
80
|
+
return `${mins}m${remSec}s`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Classifies a turn's thinking drift into 'nominal' | 'elevated' | 'loop_suspect'.
|
|
85
|
+
*
|
|
86
|
+
* @param {object} turn
|
|
87
|
+
* @param {number} [turn.thinkingTokens=0]
|
|
88
|
+
* @param {number} [turn.visibleOutputTokens=0]
|
|
89
|
+
* @param {number} [turn.outputTokens=0]
|
|
90
|
+
* @param {number} [turn.mutatingCalls=0]
|
|
91
|
+
* @returns {'nominal' | 'elevated' | 'loop_suspect'}
|
|
92
|
+
*/
|
|
93
|
+
export function classifyTurnDrift(turn = {}) {
|
|
94
|
+
const thinking = Math.max(0, Number(turn.thinkingTokens ?? 0));
|
|
95
|
+
const output = Math.max(0, Number(turn.visibleOutputTokens ?? turn.outputTokens ?? 0));
|
|
96
|
+
const mutating = Math.max(0, Number(turn.mutatingCalls ?? 0));
|
|
97
|
+
|
|
98
|
+
const ratio = thinking / Math.max(1, output);
|
|
99
|
+
|
|
100
|
+
if (thinking >= DRIFT_THRESHOLDS.MIN_THINKING_TOKENS &&
|
|
101
|
+
ratio >= DRIFT_THRESHOLDS.LOOP_RATIO &&
|
|
102
|
+
mutating === 0) {
|
|
103
|
+
return DRIFT_STATES.LOOP_SUSPECT;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (thinking > 0 && ratio >= DRIFT_THRESHOLDS.ELEVATED_RATIO) {
|
|
107
|
+
return DRIFT_STATES.ELEVATED;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return DRIFT_STATES.NOMINAL;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Evaluates a sequence of turn records for DET-30 (alias DET-21) scratchpad loop conditions.
|
|
115
|
+
*
|
|
116
|
+
* @param {Array<object>} [turnRecords=[]]
|
|
117
|
+
* @returns {{
|
|
118
|
+
* triggered: boolean,
|
|
119
|
+
* severity: 'nominal' | 'warn' | 'critical',
|
|
120
|
+
* gaDetectorId: 'DET-30',
|
|
121
|
+
* aliasDetectorId: 'DET-21',
|
|
122
|
+
* consecutiveLoopTurns: number,
|
|
123
|
+
* cumulativeThinkingTokens: number,
|
|
124
|
+
* message: string
|
|
125
|
+
* }}
|
|
126
|
+
*/
|
|
127
|
+
export function evaluateThinkingDriftLoop(turnRecords = []) {
|
|
128
|
+
if (!Array.isArray(turnRecords) || turnRecords.length === 0) {
|
|
129
|
+
return {
|
|
130
|
+
triggered: false,
|
|
131
|
+
severity: 'nominal',
|
|
132
|
+
gaDetectorId: THINKING_DRIFT_DETECTOR_ID,
|
|
133
|
+
aliasDetectorId: LEGACY_THINKING_DRIFT_ALIAS,
|
|
134
|
+
consecutiveLoopTurns: 0,
|
|
135
|
+
cumulativeThinkingTokens: 0,
|
|
136
|
+
message: ''
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let consecutiveLoop = 0;
|
|
141
|
+
let nonMutatingThinking = 0;
|
|
142
|
+
let lastSuspectRatio = 0;
|
|
143
|
+
|
|
144
|
+
for (let i = 0; i < turnRecords.length; i++) {
|
|
145
|
+
const turn = turnRecords[i];
|
|
146
|
+
const mutating = Math.max(0, Number(turn.mutatingCalls ?? 0));
|
|
147
|
+
const thinking = Math.max(0, Number(turn.thinkingTokens ?? 0));
|
|
148
|
+
const output = Math.max(0, Number(turn.visibleOutputTokens ?? turn.outputTokens ?? 0));
|
|
149
|
+
const state = classifyTurnDrift(turn);
|
|
150
|
+
|
|
151
|
+
if (mutating > 0) {
|
|
152
|
+
consecutiveLoop = 0;
|
|
153
|
+
nonMutatingThinking = 0;
|
|
154
|
+
} else {
|
|
155
|
+
nonMutatingThinking += thinking;
|
|
156
|
+
if (state === DRIFT_STATES.LOOP_SUSPECT) {
|
|
157
|
+
consecutiveLoop += 1;
|
|
158
|
+
lastSuspectRatio = Math.round(thinking / Math.max(1, output));
|
|
159
|
+
} else {
|
|
160
|
+
consecutiveLoop = 0;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const isCritical =
|
|
166
|
+
consecutiveLoop >= DRIFT_THRESHOLDS.CONSECUTIVE_TURNS_CRITICAL ||
|
|
167
|
+
(consecutiveLoop >= 1 && nonMutatingThinking >= DRIFT_THRESHOLDS.CUMULATIVE_THINKING_TOKENS);
|
|
168
|
+
|
|
169
|
+
const isWarn = consecutiveLoop === 1 && !isCritical;
|
|
170
|
+
const triggered = isCritical || isWarn;
|
|
171
|
+
const severity = isCritical ? 'critical' : isWarn ? 'warn' : 'nominal';
|
|
172
|
+
|
|
173
|
+
const message = triggered
|
|
174
|
+
? `🚨 DET-30 (DET-21) Scratchpad Loop: ${lastSuspectRatio}x reasoning-to-output over ${consecutiveLoop} turn(s) with 0 edits. Inject a concrete constraint (target file + acceptance test) or step effort down.`
|
|
175
|
+
: '';
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
triggered,
|
|
179
|
+
severity,
|
|
180
|
+
gaDetectorId: THINKING_DRIFT_DETECTOR_ID,
|
|
181
|
+
aliasDetectorId: LEGACY_THINKING_DRIFT_ALIAS,
|
|
182
|
+
consecutiveLoopTurns: consecutiveLoop,
|
|
183
|
+
cumulativeThinkingTokens: nonMutatingThinking,
|
|
184
|
+
message
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Applies a turn event to the thinking drift accumulator.
|
|
190
|
+
*
|
|
191
|
+
* @param {object} drift Current drift state
|
|
192
|
+
* @param {object} ev Event data
|
|
193
|
+
* @param {string} [ev.eventType]
|
|
194
|
+
* @param {number} [ev.turnStartedAtMs]
|
|
195
|
+
* @param {number} [ev.nowMs]
|
|
196
|
+
* @param {number} [ev.ttftMs]
|
|
197
|
+
* @param {number} [ev.thinkingTokens=0]
|
|
198
|
+
* @param {number} [ev.outputTokens=0]
|
|
199
|
+
* @param {number} [ev.mutatingCalls=0]
|
|
200
|
+
* @param {boolean} [ev.thinkingEstimated=false]
|
|
201
|
+
* @returns {object} Updated drift state
|
|
202
|
+
*/
|
|
203
|
+
export function applyThinkingDriftEvent(drift, ev = {}) {
|
|
204
|
+
const current = drift ? { ...drift, turns: [...drift.turns] } : createInitialThinkingDrift();
|
|
205
|
+
|
|
206
|
+
// TTFT calculation: measured from turnStartedAtMs to nowMs
|
|
207
|
+
let ttft = null;
|
|
208
|
+
if (typeof ev.ttftMs === 'number' && ev.ttftMs > 0) {
|
|
209
|
+
ttft = Math.round(ev.ttftMs);
|
|
210
|
+
} else if (
|
|
211
|
+
typeof ev.turnStartedAtMs === 'number' &&
|
|
212
|
+
typeof ev.nowMs === 'number' &&
|
|
213
|
+
ev.nowMs > ev.turnStartedAtMs
|
|
214
|
+
) {
|
|
215
|
+
ttft = Math.round(ev.nowMs - ev.turnStartedAtMs);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const thinking = Math.max(0, Number(ev.thinkingTokens ?? 0));
|
|
219
|
+
const output = Math.max(0, Number(ev.outputTokens ?? ev.visibleOutputTokens ?? 0));
|
|
220
|
+
const mutating = Math.max(0, Number(ev.mutatingCalls ?? 0));
|
|
221
|
+
const isEstimated = Boolean(ev.thinkingEstimated);
|
|
222
|
+
|
|
223
|
+
// Compute drift ratio only if thinking tokens are reported and non-estimated
|
|
224
|
+
let ratio = null;
|
|
225
|
+
if (!isEstimated && (thinking > 0 || output > 0)) {
|
|
226
|
+
ratio = parseFloat((thinking / Math.max(1, output)).toFixed(1));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const turnRecord = {
|
|
230
|
+
turnIndex: current.turns.length,
|
|
231
|
+
ttftMs: ttft,
|
|
232
|
+
thinkingTokens: thinking,
|
|
233
|
+
outputTokens: output,
|
|
234
|
+
visibleOutputTokens: output,
|
|
235
|
+
mutatingCalls: mutating,
|
|
236
|
+
driftRatio: ratio,
|
|
237
|
+
driftState: classifyTurnDrift({ thinkingTokens: thinking, visibleOutputTokens: output, mutatingCalls: mutating }),
|
|
238
|
+
thinkingEstimated: isEstimated,
|
|
239
|
+
timestamp: typeof ev.nowMs === 'number' ? ev.nowMs : Date.now()
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
current.turns.push(turnRecord);
|
|
243
|
+
current.measured = current.turns.length > 0;
|
|
244
|
+
|
|
245
|
+
if (ttft !== null) {
|
|
246
|
+
current.lastTtftMs = ttft;
|
|
247
|
+
const measuredTtfts = current.turns
|
|
248
|
+
.map(t => t.ttftMs)
|
|
249
|
+
.filter(t => typeof t === 'number' && t > 0);
|
|
250
|
+
if (measuredTtfts.length > 0) {
|
|
251
|
+
const sum = measuredTtfts.reduce((acc, v) => acc + v, 0);
|
|
252
|
+
current.avgTtftMs = Math.round(sum / measuredTtfts.length);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (ratio !== null) {
|
|
257
|
+
current.lastDriftRatio = ratio;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (!isEstimated) {
|
|
261
|
+
current.cumulativeThinkingTokens += thinking;
|
|
262
|
+
current.cumulativeOutputTokens += output;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Rolling drift across trailing window
|
|
266
|
+
const trailing = current.turns.slice(-DRIFT_THRESHOLDS.ROLLING_WINDOW);
|
|
267
|
+
const trailingThinking = trailing.reduce((acc, t) => acc + (t.thinkingEstimated ? 0 : t.thinkingTokens), 0);
|
|
268
|
+
const trailingOutput = trailing.reduce((acc, t) => acc + (t.thinkingEstimated ? 0 : t.outputTokens), 0);
|
|
269
|
+
if (trailingThinking > 0 || trailingOutput > 0) {
|
|
270
|
+
current.rollingDriftRatio = parseFloat((trailingThinking / Math.max(1, trailingOutput)).toFixed(1));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Evaluate loop detector
|
|
274
|
+
current.loop = evaluateThinkingDriftLoop(current.turns);
|
|
275
|
+
current.consecutiveLoopTurns = current.loop.consecutiveLoopTurns;
|
|
276
|
+
|
|
277
|
+
return current;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Checks whether a TTFT observation constitutes a sudden spike against baseline.
|
|
282
|
+
*
|
|
283
|
+
* @param {number} ttftMs
|
|
284
|
+
* @param {number} baselineAvgMs
|
|
285
|
+
* @returns {boolean}
|
|
286
|
+
*/
|
|
287
|
+
export function isTtftSpike(ttftMs, baselineAvgMs) {
|
|
288
|
+
if (typeof ttftMs !== 'number' || typeof baselineAvgMs !== 'number' || baselineAvgMs <= 0) {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
return ttftMs > baselineAvgMs * DRIFT_THRESHOLDS.SPIKE_MULTIPLIER;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Returns a compact 1-line summary of thinking drift for CLI statuslines.
|
|
296
|
+
* @param {object} drift
|
|
297
|
+
* @returns {string}
|
|
298
|
+
*/
|
|
299
|
+
export function formatDriftCompact(drift) {
|
|
300
|
+
if (!drift?.measured) return 'TTFT: — | Drift: —';
|
|
301
|
+
const ttftStr = formatTtft(drift.lastTtftMs);
|
|
302
|
+
const ratioStr = drift.lastDriftRatio != null ? `${drift.lastDriftRatio}x` : '—';
|
|
303
|
+
if (drift.loop?.triggered) {
|
|
304
|
+
return `TTFT: ${ttftStr} | 🚨 DET-30 Loop (${ratioStr})`;
|
|
305
|
+
}
|
|
306
|
+
return `TTFT: ${ttftStr} | Drift: ${ratioStr}`;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Formats an informative drift label for reports.
|
|
311
|
+
* @param {object} drift
|
|
312
|
+
* @returns {string}
|
|
313
|
+
*/
|
|
314
|
+
export function formatDriftLabel(drift) {
|
|
315
|
+
if (!drift?.measured) return 'Thinking drift unmeasured';
|
|
316
|
+
const ttftStr = drift.avgTtftMs != null ? formatTtft(drift.avgTtftMs) : '—';
|
|
317
|
+
const rollingStr = drift.rollingDriftRatio != null ? `${drift.rollingDriftRatio}x` : '—';
|
|
318
|
+
return `Avg TTFT ${ttftStr} · Rolling Drift ${rollingStr}`;
|
|
319
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/economics/dualTtl.mjs
|
|
3
|
+
* Feature 21: 1s Live Dual-TTL Countdown & Pause Distribution Analyzer.
|
|
4
|
+
*
|
|
5
|
+
* Implements:
|
|
6
|
+
* - 5-Minute (300s) Ephemeral Prompt Cache TTL Countdown
|
|
7
|
+
* - 1-Hour (3,600s) Rolling Billing Block TTL Countdown
|
|
8
|
+
* - Sub-second accuracy clamped cleanly at "00:00" without negative rollover
|
|
9
|
+
* - Inter-turn pause distribution analyzer (recommends 1h tier upgrade when >= 3.1% pauses are 5m-60m)
|
|
10
|
+
* - Amber warning at <= 45s, Keep-alive at <= 15s, T-10s StateBaton pre-snapshot
|
|
11
|
+
*
|
|
12
|
+
* Adheres strictly to Claude Mod Laws 1–5: pure ESM, zero `node:*` imports, zero Node globals.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const DUAL_TTL_CONSTANTS = Object.freeze({
|
|
16
|
+
CACHE_TTL_MS: 300000, // 5 minutes
|
|
17
|
+
BILLING_TTL_MS: 3600000, // 1 hour
|
|
18
|
+
CACHE_TTL_SEC: 300,
|
|
19
|
+
BILLING_TTL_SEC: 3600,
|
|
20
|
+
AMBER_ALERT_SEC: 45,
|
|
21
|
+
KEEP_ALIVE_SEC: 15,
|
|
22
|
+
SNAPSHOT_SEC: 10,
|
|
23
|
+
ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD: 0.031 // 3.1%
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Formats seconds into digital countdown clock notation "MM:SS".
|
|
28
|
+
* Clamps negative or non-finite values to "00:00".
|
|
29
|
+
*
|
|
30
|
+
* @param {number} sec
|
|
31
|
+
* @returns {string}
|
|
32
|
+
*/
|
|
33
|
+
export function formatMmSs(sec) {
|
|
34
|
+
const s = Math.max(0, Math.floor(Number(sec || 0)));
|
|
35
|
+
const m = Math.floor(s / 60);
|
|
36
|
+
const remS = s % 60;
|
|
37
|
+
return `${String(m).padStart(2, '0')}:${String(remS).padStart(2, '0')}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Formats remaining seconds into compact human-readable display e.g. "4m12s" or "42s".
|
|
42
|
+
* @param {number} remainingSeconds
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export function formatRemainingTtl(remainingSeconds = 0) {
|
|
46
|
+
const sec = Math.max(0, Math.floor(Number(remainingSeconds || 0)));
|
|
47
|
+
if (sec <= 0) return '0s';
|
|
48
|
+
const mins = Math.floor(sec / 60);
|
|
49
|
+
const remSec = sec % 60;
|
|
50
|
+
if (mins === 0) return `${remSec}s`;
|
|
51
|
+
return `${mins}m${String(remSec).padStart(2, '0')}s`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Calculates live Dual-TTL countdown for 5-minute cache TTL and 1-hour billing TTL.
|
|
56
|
+
*
|
|
57
|
+
* @param {number} lastTurnTimestamp Epoch ms when last turn/cache event finished
|
|
58
|
+
* @param {number} [now=Date.now()] Current epoch ms
|
|
59
|
+
* @param {number} [cacheTtlMs=300000] Ephemeral cache window (default 300,000ms = 5m)
|
|
60
|
+
* @param {number} [billingTtlMs=3600000] Billing block TTL (default 3,600,000ms = 1h)
|
|
61
|
+
* @param {object} [options={}] Optional configuration (e.g. { rolling: boolean })
|
|
62
|
+
* @returns {{
|
|
63
|
+
* cacheTtlSec: number,
|
|
64
|
+
* billingTtlSec: number,
|
|
65
|
+
* formattedCacheTtl: string,
|
|
66
|
+
* formattedBillingTtl: string,
|
|
67
|
+
* isCacheExpired: boolean,
|
|
68
|
+
* isBillingExpired: boolean
|
|
69
|
+
* }}
|
|
70
|
+
*/
|
|
71
|
+
export function calculateDualTtlCountdown(
|
|
72
|
+
lastTurnTimestamp,
|
|
73
|
+
now = Date.now(),
|
|
74
|
+
cacheTtlMs = DUAL_TTL_CONSTANTS.CACHE_TTL_MS,
|
|
75
|
+
billingTtlMs = DUAL_TTL_CONSTANTS.BILLING_TTL_MS,
|
|
76
|
+
options = {}
|
|
77
|
+
) {
|
|
78
|
+
const elapsedMs = Math.max(0, now - lastTurnTimestamp);
|
|
79
|
+
const cacheRemainingMs = Math.max(0, cacheTtlMs - elapsedMs);
|
|
80
|
+
|
|
81
|
+
const isRolling = Boolean(options.rolling);
|
|
82
|
+
const billingRemainingMs = isRolling
|
|
83
|
+
? (elapsedMs >= billingTtlMs && elapsedMs % billingTtlMs === 0
|
|
84
|
+
? 0
|
|
85
|
+
: Math.max(0, billingTtlMs - (elapsedMs % billingTtlMs)))
|
|
86
|
+
: Math.max(0, billingTtlMs - elapsedMs);
|
|
87
|
+
|
|
88
|
+
const cacheTtlSec = Math.floor(cacheRemainingMs / 1000);
|
|
89
|
+
const billingTtlSec = Math.floor(billingRemainingMs / 1000);
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
cacheTtlSec,
|
|
93
|
+
billingTtlSec,
|
|
94
|
+
formattedCacheTtl: formatMmSs(cacheTtlSec),
|
|
95
|
+
formattedBillingTtl: formatMmSs(billingTtlSec),
|
|
96
|
+
isCacheExpired: cacheRemainingMs === 0,
|
|
97
|
+
isBillingExpired: elapsedMs >= billingTtlMs
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Evaluates inter-turn pause durations (in seconds) and advises upgrading the session
|
|
103
|
+
* prompt cache tier to 1h when >= 3.1% of pauses fall between 5m and 60m.
|
|
104
|
+
*
|
|
105
|
+
* @param {Array<number>} pauseDurationsSeconds
|
|
106
|
+
* @param {number} [thresholdRatio=0.031]
|
|
107
|
+
* @returns {{
|
|
108
|
+
* totalIntervals: number,
|
|
109
|
+
* fiveToSixtyMinCount: number,
|
|
110
|
+
* fiveToSixtyMinRatio: number,
|
|
111
|
+
* fiveToSixtyMinPct: number,
|
|
112
|
+
* thresholdRatio: number,
|
|
113
|
+
* recommend1hTierUpgrade: boolean,
|
|
114
|
+
* advisoryMessage: string | null
|
|
115
|
+
* }}
|
|
116
|
+
*/
|
|
117
|
+
export function evaluatePauseDistribution(
|
|
118
|
+
pauseDurationsSeconds = [],
|
|
119
|
+
thresholdRatio = DUAL_TTL_CONSTANTS.ONE_HOUR_UPGRADE_PAUSE_RATIO_THRESHOLD
|
|
120
|
+
) {
|
|
121
|
+
const validPauses = Array.isArray(pauseDurationsSeconds)
|
|
122
|
+
? pauseDurationsSeconds.map(v => Number(v)).filter(v => Number.isFinite(v) && v >= 0)
|
|
123
|
+
: [];
|
|
124
|
+
|
|
125
|
+
const totalIntervals = validPauses.length;
|
|
126
|
+
if (totalIntervals === 0) {
|
|
127
|
+
return {
|
|
128
|
+
totalIntervals: 0,
|
|
129
|
+
fiveToSixtyMinCount: 0,
|
|
130
|
+
fiveToSixtyMinRatio: 0,
|
|
131
|
+
fiveToSixtyMinPct: 0,
|
|
132
|
+
thresholdRatio,
|
|
133
|
+
recommend1hTierUpgrade: false,
|
|
134
|
+
advisoryMessage: null
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const fiveToSixtyMinCount = validPauses.filter(
|
|
139
|
+
sec => sec > DUAL_TTL_CONSTANTS.CACHE_TTL_SEC && sec <= DUAL_TTL_CONSTANTS.BILLING_TTL_SEC
|
|
140
|
+
).length;
|
|
141
|
+
|
|
142
|
+
const fiveToSixtyMinRatio = Number((fiveToSixtyMinCount / totalIntervals).toFixed(4));
|
|
143
|
+
const fiveToSixtyMinPct = Number((fiveToSixtyMinRatio * 100).toFixed(2));
|
|
144
|
+
const recommend1hTierUpgrade = fiveToSixtyMinRatio >= thresholdRatio;
|
|
145
|
+
|
|
146
|
+
const advisoryMessage = recommend1hTierUpgrade
|
|
147
|
+
? `Inter-turn pause telemetry: ${fiveToSixtyMinPct}% of turns (${fiveToSixtyMinCount}/${totalIntervals}) ` +
|
|
148
|
+
`followed a 5-to-60 minute pause (>= ${(thresholdRatio * 100).toFixed(1)}% break-even threshold). ` +
|
|
149
|
+
`Upgrade session prompt cache tier from 5m (1.25x) to 1h (2.0x) to prevent recurring cold prefix rewrites.`
|
|
150
|
+
: null;
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
totalIntervals,
|
|
154
|
+
fiveToSixtyMinCount,
|
|
155
|
+
fiveToSixtyMinRatio,
|
|
156
|
+
fiveToSixtyMinPct,
|
|
157
|
+
thresholdRatio,
|
|
158
|
+
recommend1hTierUpgrade,
|
|
159
|
+
advisoryMessage
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Stateful Dual-TTL countdown tracker.
|
|
165
|
+
*/
|
|
166
|
+
export class DualTtlTracker {
|
|
167
|
+
constructor(options = {}) {
|
|
168
|
+
this.cacheTtlMs = options.cacheTtlMs || DUAL_TTL_CONSTANTS.CACHE_TTL_MS;
|
|
169
|
+
this.billingTtlMs = options.billingTtlMs || DUAL_TTL_CONSTANTS.BILLING_TTL_MS;
|
|
170
|
+
this.rolling = Boolean(options.rolling);
|
|
171
|
+
this.lastTurnTimestamp = Date.now();
|
|
172
|
+
this.pauseDurationsSeconds = [];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
recordTurn(now = Date.now()) {
|
|
176
|
+
if (this.lastTurnTimestamp > 0) {
|
|
177
|
+
const pauseSec = Math.max(0, Math.floor((now - this.lastTurnTimestamp) / 1000));
|
|
178
|
+
this.pauseDurationsSeconds.push(pauseSec);
|
|
179
|
+
}
|
|
180
|
+
this.lastTurnTimestamp = now;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
getCountdown(now = Date.now()) {
|
|
184
|
+
return calculateDualTtlCountdown(
|
|
185
|
+
this.lastTurnTimestamp,
|
|
186
|
+
now,
|
|
187
|
+
this.cacheTtlMs,
|
|
188
|
+
this.billingTtlMs,
|
|
189
|
+
{ rolling: this.rolling }
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
getPauseAnalysis() {
|
|
194
|
+
return evaluatePauseDistribution(this.pauseDurationsSeconds);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export { TtlWatchdog } from '../coach/ttlWatchdog.mjs';
|