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.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,527 @@
1
+ /**
2
+ * @file src/coach/savedQuotaLedger.mjs
3
+ * Append-only `.jsonl` Saved-Quota Receipt Ledger (`horizon_ledger.jsonl`).
4
+ *
5
+ * Strict Invariant:
6
+ * - Initialized strictly at `0` tokens and `$0.00` USD (never uses the legacy `142,400` fallback bug).
7
+ * - Zero `node:sqlite` dependency; works across all Node >= 20 environments.
8
+ */
9
+
10
+ import {
11
+ path,
12
+ getCwd,
13
+ getHomeDir,
14
+ readTextSafe,
15
+ appendJsonlSafe,
16
+ recordRuntimeDiagnostic
17
+ } from '../utils/runtime.mjs';
18
+ import { calculateTurnCostUSD } from '../config/catalogLoader.mjs';
19
+
20
+ /**
21
+ * Resolves the ledger file path (`options.ledgerPath`, or `.claude/cache/horizon_ledger.jsonl`
22
+ * when `options.cwd` is provided, or `~/.claude/plugins/store/horizon_ledger.jsonl`).
23
+ *
24
+ * @param {object} [options={}]
25
+ * @returns {string}
26
+ */
27
+ export function getLedgerFilePath(options = {}) {
28
+ if (typeof options.ledgerPath === 'string' && options.ledgerPath.trim()) {
29
+ return options.ledgerPath.trim();
30
+ }
31
+ if (options.cwd) {
32
+ return path.join(options.cwd, '.claude', 'cache', 'horizon_ledger.jsonl');
33
+ }
34
+ const home = getHomeDir(options);
35
+ if (home) {
36
+ return path.join(home, '.claude', 'plugins', 'store', 'horizon_ledger.jsonl');
37
+ }
38
+ const fallbackCwd = getCwd(options);
39
+ return path.join(fallbackCwd, '.claude', 'cache', 'horizon_ledger.jsonl');
40
+ }
41
+
42
+ /**
43
+ * Reads all valid JSONL entries from the ledger file.
44
+ * Returns an empty array if the file does not exist (strictly 0 fallback).
45
+ *
46
+ * @param {object} [options={}]
47
+ * @returns {Array<object>}
48
+ */
49
+ export function readLedgerEntries(options = {}) {
50
+ const filePath = getLedgerFilePath(options);
51
+ const raw = readTextSafe(filePath, null, options);
52
+ if (!raw) {
53
+ return [];
54
+ }
55
+ try {
56
+ const lines = raw.split(/\r?\n/).filter((line) => line.trim().length > 0);
57
+ const entries = [];
58
+ for (const line of lines) {
59
+ try {
60
+ const parsed = JSON.parse(line);
61
+ if (parsed && typeof parsed === 'object') {
62
+ entries.push(parsed);
63
+ }
64
+ } catch (err) {
65
+ recordRuntimeDiagnostic('savedQuotaLedger', 'readLedgerEntries.parseLine', err, options);
66
+ }
67
+ }
68
+ return entries;
69
+ } catch (err) {
70
+ recordRuntimeDiagnostic('savedQuotaLedger', 'readLedgerEntries', err, options);
71
+ return [];
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Appends a verified savings receipt entry to `horizon_ledger.jsonl`.
77
+ *
78
+ * @param {object} receipt
79
+ * @param {string} [receipt.sessionId='default']
80
+ * @param {string} [receipt.category='CACHE_READ_DISCOUNT']
81
+ * @param {number} [receipt.savedTokens=0]
82
+ * @param {number} [receipt.savedUSD=0]
83
+ * @param {string} [receipt.modelId='claude-sonnet-5-5']
84
+ * @param {string} [receipt.detail='']
85
+ * @param {object} [options={}]
86
+ * @returns {{ ok: boolean, entry: object, filePath: string }}
87
+ */
88
+ const recordedTurnSavingsKeys = new Set();
89
+ const recordedInterventionKeys = new Set();
90
+
91
+ export const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
92
+
93
+ /**
94
+ * Canonical 5-category Claude Code savings taxonomy for Simple View (Rank 4) and Advanced View (Section 1).
95
+ */
96
+ export const SAVINGS_BUCKETS = Object.freeze({
97
+ cacheReadDiscount: Object.freeze({
98
+ id: 'cacheReadDiscount',
99
+ label: 'Prompt Cache Read Discounts (0.10x)',
100
+ shortLabel: 'Cache Read Discounts',
101
+ rawCategories: Object.freeze(['CACHE_READ_DISCOUNT', 'CACHE_HIT_PRESERVED'])
102
+ }),
103
+ prefixBustAvoided: Object.freeze({
104
+ id: 'prefixBustAvoided',
105
+ label: 'Warm-Prefix & Cross-Model Busts Avoided (C*)',
106
+ shortLabel: 'Prefix Busts Avoided',
107
+ rawCategories: Object.freeze([
108
+ 'COLD_PREFILL_AVOIDED',
109
+ 'MODEL_SWITCH_DEFERRED',
110
+ 'PREFIX_MUTATION_DEFERRED',
111
+ 'POST_COMPACT_MUTATION_RELEASE',
112
+ 'COMPACT_STATE_BATON',
113
+ 'DET_08_MODEL_SWITCH_HOLD',
114
+ 'DET_09_PREFIX_FENCE'
115
+ ])
116
+ }),
117
+ toolOutputCompressed: Object.freeze({
118
+ id: 'toolOutputCompressed',
119
+ label: 'Lossless PostToolUse Sanitizer & >4k Offloads',
120
+ shortLabel: 'Tool Output Sanitized',
121
+ rawCategories: Object.freeze([
122
+ 'LOSSLESS_POST_SANITIZER',
123
+ 'ARTIFACT_OFFLOAD_4K',
124
+ 'TOOL_OUTPUT_COMPRESSED'
125
+ ])
126
+ }),
127
+ loopAndReadGuarded: Object.freeze({
128
+ id: 'loopAndReadGuarded',
129
+ label: 'Loop, Bounded-Read & Quota Interventions',
130
+ shortLabel: 'Loop & Read Guards',
131
+ rawCategories: Object.freeze([
132
+ 'LOOP_TURN_PREVENTED',
133
+ 'BOUNDED_READ_ENFORCED',
134
+ 'TTL_EXPIRY_HOLD',
135
+ 'SCOPE_QUOTA_BRAKE',
136
+ 'DET_06_LOOP_BREAKER',
137
+ 'DET_10_TTL_HOLD',
138
+ 'DET_11_BOUNDED_READ',
139
+ 'DET_20_SCOPE_BRAKE',
140
+ 'PROMPT_HYGIENE_STEERED',
141
+ 'PROMPT_HYGIENE_BLOCKED',
142
+ 'SIGHTSEEING_TOOL_PREVENTED'
143
+ ])
144
+ }),
145
+ subagentIsolated: Object.freeze({
146
+ id: 'subagentIsolated',
147
+ label: 'Task / Agent Subagent Context Isolation',
148
+ shortLabel: 'Subagent Isolation',
149
+ rawCategories: Object.freeze(['SUBAGENT_ISOLATED', 'TASK_SUBAGENT_ISOLATED'])
150
+ })
151
+ });
152
+
153
+ /**
154
+ * Maps a raw ledger category string into one of the 5 canonical Claude Code savings buckets.
155
+ *
156
+ * @param {string} [rawCategory='']
157
+ * @returns {'cacheReadDiscount'|'prefixBustAvoided'|'toolOutputCompressed'|'loopAndReadGuarded'|'subagentIsolated'}
158
+ */
159
+ export function normalizeSavingsBucketId(rawCategory = '') {
160
+ const upper = String(rawCategory || '').trim().toUpperCase();
161
+ for (const [bucketId, spec] of Object.entries(SAVINGS_BUCKETS)) {
162
+ if (spec.rawCategories.includes(upper) || bucketId.toUpperCase() === upper) {
163
+ return bucketId;
164
+ }
165
+ }
166
+ if (upper.includes('CACHE')) return 'cacheReadDiscount';
167
+ if (upper.includes('PREFIX') || upper.includes('MODEL') || upper.includes('DET_08') || upper.includes('DET_09')) {
168
+ return 'prefixBustAvoided';
169
+ }
170
+ if (upper.includes('SANITIZ') || upper.includes('OFFLOAD') || upper.includes('COMPRESS')) {
171
+ return 'toolOutputCompressed';
172
+ }
173
+ if (upper.includes('SUBAGENT') || upper.includes('TASK')) {
174
+ return 'subagentIsolated';
175
+ }
176
+ return 'loopAndReadGuarded';
177
+ }
178
+
179
+ export function recordSavingsReceipt(receipt = {}, options = {}) {
180
+ const filePath = getLedgerFilePath(options);
181
+ const entry = {
182
+ timestamp: receipt.timestamp || options.nowMs || Date.now(),
183
+ sessionId: String(receipt.sessionId || 'default'),
184
+ category: String(receipt.category || 'CACHE_READ_DISCOUNT'),
185
+ modelId: String(receipt.modelId || 'claude-sonnet-5-5'),
186
+ savedTokens: Math.max(0, Math.round(Number(receipt.savedTokens || 0))),
187
+ savedUSD: Math.max(0, Number(Number(receipt.savedUSD || 0).toFixed(6))),
188
+ detail: String(receipt.detail || ''),
189
+ ...(receipt.turnId ? { turnId: String(receipt.turnId) } : {})
190
+ };
191
+
192
+ const ok = appendJsonlSafe(filePath, entry, options);
193
+ return { ok, entry, filePath };
194
+ }
195
+
196
+ /**
197
+ * Records a deduplicated intervention savings receipt (e.g. `DET-08` model switch hold,
198
+ * `DET-09` warm-prefix file mutation fence, `DET-06`/`10`/`11`/`20` guard, or `SUBAGENT_ISOLATED`).
199
+ *
200
+ * @param {object} [params={}]
201
+ * @param {string} [params.sessionId='default']
202
+ * @param {string} [params.category='COLD_PREFILL_AVOIDED']
203
+ * @param {string} [params.modelId='claude-sonnet-5-5']
204
+ * @param {number} [params.savedTokens=0]
205
+ * @param {number} [params.savedUSD=0]
206
+ * @param {string} [params.detail='']
207
+ * @param {string} [params.dedupeId]
208
+ * @param {object} [options={}]
209
+ */
210
+ export function recordInterventionSavings(params = {}, options = {}) {
211
+ const sessionId = String(params.sessionId || options.sessionId || 'default');
212
+ const category = String(params.category || 'COLD_PREFILL_AVOIDED');
213
+ const modelId = String(params.modelId || 'claude-sonnet-5-5');
214
+ const savedTokens = Math.max(0, Math.round(Number(params.savedTokens || 0)));
215
+ let savedUSD = Math.max(0, Number(params.savedUSD || 0));
216
+
217
+ if (savedTokens <= 0 && savedUSD <= 0) {
218
+ return { recorded: false, deduplicated: false, receipt: null };
219
+ }
220
+
221
+ if (savedUSD <= 0 && savedTokens > 0) {
222
+ const turnCost = calculateTurnCostUSD(
223
+ {
224
+ model: modelId,
225
+ inputTokens: savedTokens
226
+ },
227
+ options
228
+ );
229
+ savedUSD = Math.max(0, Number(turnCost.costsUSD.totalActualSpendUSD || 0));
230
+ }
231
+
232
+ const dedupeToken = params.dedupeId || params.turnId || '';
233
+ const dedupeKey = dedupeToken
234
+ ? `${getLedgerFilePath(options)}::${sessionId}::${category}::${dedupeToken}`
235
+ : null;
236
+ if (dedupeKey) {
237
+ if (recordedInterventionKeys.has(dedupeKey)) {
238
+ return { recorded: false, deduplicated: true, receipt: null };
239
+ }
240
+ recordedInterventionKeys.add(dedupeKey);
241
+ }
242
+
243
+ const res = recordSavingsReceipt(
244
+ {
245
+ sessionId,
246
+ turnId: dedupeToken || undefined,
247
+ category,
248
+ modelId,
249
+ savedTokens,
250
+ savedUSD,
251
+ detail: String(params.detail || '')
252
+ },
253
+ options
254
+ );
255
+
256
+ return {
257
+ recorded: res.ok,
258
+ deduplicated: false,
259
+ receipt: res.entry
260
+ };
261
+ }
262
+
263
+ /**
264
+ * Computes exact cache read USD & token savings for a turn via `calculateTurnCostUSD`
265
+ * (honoring the Haiku 5.5 `$0.10/$0.50` base and `100,000` total-prompt `5x` cliff)
266
+ * and records a verified receipt if `netCacheSavingsUSD > 0`.
267
+ * Deduplicates by `turnId` per session when provided (`ISS-027`).
268
+ *
269
+ * @param {object} [usage={}]
270
+ * @param {object} [options={}]
271
+ */
272
+ export function recordTurnCacheSavings(usage = {}, options = {}) {
273
+ const sessionId = String(usage.sessionId || options.sessionId || 'default');
274
+ const turnId =
275
+ usage.turnId ||
276
+ usage.turn_id ||
277
+ usage.messageId ||
278
+ usage.message_id ||
279
+ usage.message?.id ||
280
+ options.turnId ||
281
+ null;
282
+
283
+ const dedupeKey = turnId ? `${getLedgerFilePath(options)}::${sessionId}::${turnId}` : null;
284
+ if (dedupeKey) {
285
+ if (recordedTurnSavingsKeys.has(dedupeKey)) {
286
+ const turnCost = calculateTurnCostUSD(usage, options);
287
+ return {
288
+ recorded: false,
289
+ deduplicated: true,
290
+ turnCost,
291
+ receipt: null
292
+ };
293
+ }
294
+ const existing = readLedgerEntries(options);
295
+ if (existing.some((e) => e.sessionId === sessionId && e.turnId === String(turnId))) {
296
+ recordedTurnSavingsKeys.add(dedupeKey);
297
+ const turnCost = calculateTurnCostUSD(usage, options);
298
+ return {
299
+ recorded: false,
300
+ deduplicated: true,
301
+ turnCost,
302
+ receipt: null
303
+ };
304
+ }
305
+ }
306
+
307
+ const turnCost = calculateTurnCostUSD(usage, options);
308
+ const savedUSD = Math.max(0, Number(turnCost.costsUSD.netCacheSavingsUSD || 0));
309
+ const savedTokens = Math.max(0, Number(turnCost.tokens.cacheRead || 0));
310
+
311
+ if (savedUSD <= 0 && savedTokens <= 0) {
312
+ return {
313
+ recorded: false,
314
+ turnCost,
315
+ receipt: null
316
+ };
317
+ }
318
+
319
+ const receipt = recordSavingsReceipt(
320
+ {
321
+ sessionId,
322
+ turnId,
323
+ category: 'CACHE_READ_DISCOUNT',
324
+ modelId: turnCost.modelId,
325
+ savedTokens,
326
+ savedUSD,
327
+ detail: `Warm cache read (${savedTokens.toLocaleString()} tok, total prompt ${turnCost.tokens.totalPrompt.toLocaleString()} tok)`
328
+ },
329
+ options
330
+ );
331
+
332
+ if (dedupeKey) {
333
+ recordedTurnSavingsKeys.add(dedupeKey);
334
+ }
335
+
336
+ return {
337
+ recorded: receipt.ok,
338
+ turnCost,
339
+ receipt: receipt.entry
340
+ };
341
+ }
342
+
343
+ /**
344
+ * Computes the deterministic Saved-Quota Receipt summary across all recorded entries
345
+ * (or filtered by `options.sessionId`). Always starts strictly at `0`.
346
+ *
347
+ * @param {object} [options={}]
348
+ * @returns {{
349
+ * totalSavedTokens: number,
350
+ * totalSavedUSD: number,
351
+ * entryCount: number,
352
+ * byCategory: Record<string, { savedTokens: number, savedUSD: number, count: number }>,
353
+ * entries: Array<object>
354
+ * }}
355
+ */
356
+ export function getSavedQuotaReceiptSummary(options = {}) {
357
+ const nowMs = Number(options.nowMs || Date.now());
358
+ const cutoff30d = nowMs - THIRTY_DAYS_MS;
359
+ const allEntries = readLedgerEntries(options);
360
+ const filtered = options.sessionId
361
+ ? allEntries.filter((e) => e.sessionId === options.sessionId)
362
+ : allEntries;
363
+
364
+ const targetSessionId =
365
+ options.sessionId ||
366
+ options.activeSessionId ||
367
+ (allEntries.length > 0 ? allEntries[allEntries.length - 1].sessionId : 'default');
368
+
369
+ let totalSavedTokens = 0;
370
+ let totalSavedUSD = 0;
371
+ const byCategory = {};
372
+
373
+ const categories = {};
374
+ for (const [bucketId, spec] of Object.entries(SAVINGS_BUCKETS)) {
375
+ categories[bucketId] = {
376
+ id: bucketId,
377
+ label: spec.label,
378
+ shortLabel: spec.shortLabel,
379
+ savedTokens: 0,
380
+ savedUSD: 0,
381
+ sessionSavedTokens: 0,
382
+ sessionSavedUSD: 0,
383
+ count: 0
384
+ };
385
+ }
386
+
387
+ for (const entry of filtered) {
388
+ const tokens = Math.max(0, Number(entry.savedTokens || 0));
389
+ const usd = Math.max(0, Number(entry.savedUSD || 0));
390
+ totalSavedTokens += tokens;
391
+ totalSavedUSD += usd;
392
+
393
+ const cat = entry.category || 'OTHER';
394
+ if (!byCategory[cat]) {
395
+ byCategory[cat] = { savedTokens: 0, savedUSD: 0, count: 0 };
396
+ }
397
+ byCategory[cat].savedTokens += tokens;
398
+ byCategory[cat].savedUSD = Number((byCategory[cat].savedUSD + usd).toFixed(6));
399
+ byCategory[cat].count += 1;
400
+
401
+ const bucketId = normalizeSavingsBucketId(cat);
402
+ const bucket = categories[bucketId];
403
+ if (bucket) {
404
+ bucket.savedTokens += tokens;
405
+ bucket.savedUSD = Number((bucket.savedUSD + usd).toFixed(6));
406
+ bucket.count += 1;
407
+ }
408
+ }
409
+
410
+ let sessionSavedTokens = 0;
411
+ let sessionSavedUSD = 0;
412
+ let sessionEntryCount = 0;
413
+ let workspace30dSavedTokens = 0;
414
+ let workspace30dSavedUSD = 0;
415
+ let workspace30dEntryCount = 0;
416
+
417
+ for (const entry of allEntries) {
418
+ const tokens = Math.max(0, Number(entry.savedTokens || 0));
419
+ const usd = Math.max(0, Number(entry.savedUSD || 0));
420
+ const ts = Number(entry.timestamp || nowMs);
421
+ const bucketId = normalizeSavingsBucketId(entry.category || 'OTHER');
422
+
423
+ if (!options.sessionId || entry.sessionId === targetSessionId) {
424
+ if (entry.sessionId === targetSessionId || !options.activeSessionId) {
425
+ sessionSavedTokens += tokens;
426
+ sessionSavedUSD += usd;
427
+ sessionEntryCount += 1;
428
+ if (categories[bucketId]) {
429
+ categories[bucketId].sessionSavedTokens += tokens;
430
+ categories[bucketId].sessionSavedUSD = Number(
431
+ (categories[bucketId].sessionSavedUSD + usd).toFixed(6)
432
+ );
433
+ }
434
+ }
435
+ }
436
+
437
+ if (ts >= cutoff30d) {
438
+ workspace30dSavedTokens += tokens;
439
+ workspace30dSavedUSD += usd;
440
+ workspace30dEntryCount += 1;
441
+ }
442
+ }
443
+
444
+ workspace30dSavedTokens = Math.max(workspace30dSavedTokens, sessionSavedTokens, totalSavedTokens);
445
+ workspace30dSavedUSD = Math.max(workspace30dSavedUSD, sessionSavedUSD, totalSavedUSD);
446
+
447
+ const categoryList = Object.values(categories);
448
+ let topDriver = {
449
+ id: 'cacheReadDiscount',
450
+ label: SAVINGS_BUCKETS.cacheReadDiscount.label,
451
+ shortLabel: SAVINGS_BUCKETS.cacheReadDiscount.shortLabel,
452
+ savedTokens: 0,
453
+ savedUSD: 0
454
+ };
455
+ for (const bucket of categoryList) {
456
+ if (
457
+ bucket.savedTokens > topDriver.savedTokens ||
458
+ (bucket.savedTokens === topDriver.savedTokens && bucket.savedUSD > topDriver.savedUSD)
459
+ ) {
460
+ topDriver = {
461
+ id: bucket.id,
462
+ label: bucket.label,
463
+ shortLabel: bucket.shortLabel,
464
+ savedTokens: bucket.savedTokens,
465
+ savedUSD: bucket.savedUSD
466
+ };
467
+ }
468
+ }
469
+
470
+ const measuredPromptHygiene = {
471
+ steeredPrompts: Number(byCategory.PROMPT_HYGIENE_STEERED?.count || 0),
472
+ blockedPrompts: Number(byCategory.PROMPT_HYGIENE_BLOCKED?.count || 0),
473
+ sightseeingToolsPrevented: Number(byCategory.SIGHTSEEING_TOOL_PREVENTED?.count || 0),
474
+ modeledEstimateTokensSaved:
475
+ Number(byCategory.PROMPT_HYGIENE_STEERED?.savedTokens || 0) +
476
+ Number(byCategory.PROMPT_HYGIENE_BLOCKED?.savedTokens || 0) +
477
+ Number(byCategory.SIGHTSEEING_TOOL_PREVENTED?.savedTokens || 0),
478
+ provenanceTag: '[modeled-estimate]'
479
+ };
480
+
481
+ return {
482
+ totalSavedTokens: Math.round(totalSavedTokens),
483
+ totalSavedUSD: Number(totalSavedUSD.toFixed(6)),
484
+ entryCount: filtered.length,
485
+ sessionSavedTokens: Math.round(sessionSavedTokens),
486
+ sessionSavedUSD: Number(sessionSavedUSD.toFixed(6)),
487
+ sessionEntryCount,
488
+ workspace30dSavedTokens: Math.round(workspace30dSavedTokens),
489
+ workspace30dSavedUSD: Number(workspace30dSavedUSD.toFixed(6)),
490
+ workspace30dEntryCount,
491
+ measuredPromptHygiene,
492
+ byCategory,
493
+ categories,
494
+ categoryList,
495
+ topDriver,
496
+ entries: filtered
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Stateful SavedQuotaReceiptLedger class wrapper.
502
+ */
503
+ export class SavedQuotaReceiptLedger {
504
+ constructor(options = {}) {
505
+ this.options = options;
506
+ }
507
+
508
+ record(receipt = {}) {
509
+ return recordSavingsReceipt(receipt, this.options);
510
+ }
511
+
512
+ getSummary(filterOptions = {}) {
513
+ return getSavedQuotaReceiptSummary({ ...this.options, ...filterOptions });
514
+ }
515
+ }
516
+
517
+ export default {
518
+ SAVINGS_BUCKETS,
519
+ normalizeSavingsBucketId,
520
+ getLedgerFilePath,
521
+ readLedgerEntries,
522
+ recordSavingsReceipt,
523
+ recordTurnCacheSavings,
524
+ recordInterventionSavings,
525
+ getSavedQuotaReceiptSummary,
526
+ SavedQuotaReceiptLedger
527
+ };