chompyy 0.5.0 → 0.7.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 (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6955 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,2036 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { randomBytes } from 'crypto';
3
+ import { existsSync } from 'fs';
4
+ import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'fs/promises';
5
+ import { join } from 'path';
6
+ import { getCodeburnCacheDir, RETIRED_PROVIDER_NAMES } from './cache-dir.js';
7
+ import { sweepSupersededCacheFiles } from './cache-sweep.js';
8
+ import { coverageFor, coversLocalDay, loadCursorImport } from './cursor-import.js';
9
+ import { projectOriginKey } from './git-origin.js';
10
+ // Bumped to 27: claude-haiku-4.5 copilot store rows now price correctly (alias added) — #1093.
11
+ // Previously the raw id 'claude-haiku-4.5' (tier-first, dot) from session-store.db had no
12
+ // pricing alias, so days finalized with this model were stuck at $0. No self-heal via prefix
13
+ // fallback exists for this id, so a version bump is required to force re-derivation.
14
+ // Bumped to 26: copilot input/cache tokens for sessions covered by the CLI's
15
+ // session-store.db move from one shutdown-rollup lump (stamped at session end)
16
+ // to per-request DB rows with real timestamps, supplementary accounting calls
17
+ // (rollups, residuals, paired rows) stop counting as api/model calls, and
18
+ // reasoning tokens leave the copilot cost recompute (they are inside the
19
+ // output the per-turn calls already bill). Per-day attribution, call counts and
20
+ // costs all move, so days finalized under an earlier version would disagree
21
+ // with the live parse.
22
+ //
23
+ // Why 26 and not 21 (the number this change first claimed): 20 is #1040 (codex
24
+ // model attribution), 18 was burned by an earlier public head of THIS change
25
+ // under different accounting, and 21-25 landed on main while this branch was in
26
+ // validation — 25 in particular was spent by #1056 (`codex-auto-review`
27
+ // pricing) after this PR had already minted it, which is why the number moves
28
+ // again here. 26 is the first free number on main's ladder — and it is load
29
+ // bearing beyond the collision: the branch's own validators already hold
30
+ // daily-cache.v21.json files whose copilot slices were carried stale by the
31
+ // bug PENDING_REDERIVE_PROVIDER_VERSIONS fixes below, and only a number those files
32
+ // cannot claim gets them re-derived. isMigratableCache/adoptOlderDailyCaches
33
+ // carry a same-or-newer version forward as FINALIZED without re-deriving it,
34
+ // so a number can never mean two accountings. (feat/core-extraction also sits
35
+ // at 26 and reconciles at its final merge by keeping the max.)
36
+ //
37
+ // Bumped to 25: `codex-auto-review` now prices as the recommended GPT-5.5
38
+ // row (#1047). Days already finalized under v24 keep that id at $0
39
+ // forever unless MIN_SUPPORTED_VERSION moves: the daily cache has no
40
+ // per-provider invalidation. The Codex parse version and CODEX_CACHE_VERSION
41
+ // move with this so the lower caches reprice first; this pass then re-derives
42
+ // ALL days from the warm session cache (seconds, not a full re-parse).
43
+ // adoptOlderDailyCaches keeps the superseded file as the baseline. v21 is
44
+ // #946, v22 was this PR's earlier claim, v23 is #1075, v24 is #1090.
45
+ //
46
+ // Bumped to 20: the Codex fast-path read a nested
47
+ // `base_instructions.provenance.model` out of `session_meta` as if it were
48
+ // `payload.model` (#1040), so every call a rollout attributed from session
49
+ // metadata - the ones before its first `turn_context`, and every one after a
50
+ // mid-file `session_meta` - was credited to the wrong model. The codex parse
51
+ // version and CODEX_CACHE_VERSION move with it, but the daily cache has no
52
+ // per-provider invalidation, so days already finalized keep the wrong model
53
+ // rows forever unless MIN_SUPPORTED_VERSION moves too. This pass re-derives
54
+ // ALL days for EVERY provider off the warm session cache, so it costs seconds
55
+ // rather than a full re-parse, and it is lossless: adoptOlderDailyCaches keeps
56
+ // the superseded v19 file as the baseline, and the partial-survival guard from
57
+ // #1033 holds any day whose sources have only partly aged out. On a real
58
+ // 110-day cache the 19 -> 20 pass moved ZERO days down and lost none: 100 days
59
+ // came back byte-identical and 9 grok days rose by $19.80 in total, clearing
60
+ // rollups the grok parse change had left stale, while every codex model row
61
+ // stayed identical (that corpus predates the `provenance` field, so the fix it
62
+ // carries has nothing to correct there).
63
+ //
64
+ // Bumped to 19: Grok authoritative usage now keeps one session-level rollup
65
+ // from top-level totals, clamps reasoning to reported output, and labels mixed
66
+ // authoritative/heuristic coverage. Every day finalized under the previous
67
+ // accounting carries the old Grok totals, and the daily cache has no
68
+ // per-provider invalidation, so raising MIN_SUPPORTED_VERSION is the only
69
+ // lever: it forces a one-time re-derivation of ALL days, for every provider,
70
+ // not just Grok. That pass reads the warm session cache (CACHE_VERSION is
71
+ // unchanged and only PROVIDER_PARSE_VERSIONS.grok moved), so it costs seconds
72
+ // rather than a full re-parse, and adoptOlderDailyCaches keeps the superseded
73
+ // file as the baseline for days no source can still re-derive. Days whose
74
+ // sources only PARTLY survive are held by the partial-survival guard in
75
+ // mergeDayEntries, which is what makes a global re-derive safe to force: on a
76
+ // real 108-day cache the 17 -> 19 pass moves Grok cost and tokens and nothing
77
+ // else - the day-by-day call counts come back identical.
78
+ //
79
+ // The shipped predecessor is v17; v18 was an unreleased draft of this change
80
+ // and only exists in pre-release checkouts. 19 clears both.
81
+ //
82
+ // Bumped to 17: copilot CLI sessions were misclassified as VS Code transcripts
83
+ // (#944), so days finalized at v16 or earlier carry output-only copilot costs —
84
+ // the session.shutdown rollup's input/cache tokens were dropped. Raising
85
+ // MIN_SUPPORTED_VERSION forces the one-time re-derivation under the
86
+ // provenance-based classification; sourceless days carry forward as-is.
87
+ //
88
+ // v16: Codex discovery is structural instead of originator-gated
89
+ // (#873/#626), so rollouts written by third-party frontends driving
90
+ // `codex app-server` ("t3code_desktop", "JetBrains.IntelliJ IDEA", ...) now
91
+ // contribute usage that v15 rollups never contained. Those files were rejected
92
+ // before they were ever parsed, so nothing downstream can notice on its own:
93
+ // `usage-aggregator` serves every day before today from this cache, and
94
+ // retention is ten years, so an upgrading user with a warm cache would keep the
95
+ // pre-fix history forever while today's numbers silently disagreed with it.
96
+ // Raising MIN_SUPPORTED_VERSION forces the one-time re-derivation.
97
+ //
98
+ // v15: per-project daily rollups. Days and provider slices now carry
99
+ // a `projects` breakdown (cost/calls/savings/sessions per project) so project
100
+ // history outlives the session files, like models and categories already do.
101
+ // This bump is the first to ride the v14 carry-forward: the old cache is
102
+ // adopted losslessly and only days whose sources survive are re-derived (now
103
+ // with projects); days already sourceless keep their totals and simply have
104
+ // no project split.
105
+ //
106
+ // v14: NEVER-LOSE history. Session files are ephemeral (Claude Code
107
+ // deletes transcripts after ~30 days), so a day that can no longer be re-derived
108
+ // from sources exists ONLY in this cache. Every earlier version treated the
109
+ // cache as disposable — schema bumps, savings-config changes, timezone changes
110
+ // and incomplete-hydration retries all dropped the days and re-derived from
111
+ // whatever sources survived, silently truncating history to the source-retention
112
+ // window (five bumps between 2026-06-22 and 2026-07-16 erased everything before
113
+ // 2026-04-24 on a machine with usage since March). From v14 on, invalidation
114
+ // re-derives what it can and CARRIES FORWARD every (day, provider) slice it
115
+ // cannot, and loading a missing/unsupported cache file adopts days from every
116
+ // older daily-cache file in the cache dir instead of starting empty. Bumping
117
+ // the version now only forces re-derivation of days whose sources still exist;
118
+ // it must never again lose the rest. DailyEntry.providers slices carry a full
119
+ // per-provider breakdown (tokens, models, categories) so those carry-forwards
120
+ // stay exact across rebuilds.
121
+ //
122
+ // v13: day bucketing is now TURN-anchored (a turn's whole cost/calls
123
+ // land on the day of its user-message timestamp) to match the live headline/
124
+ // report rollup. v12 bucketed each call by its own timestamp, so a midnight-
125
+ // straddling turn split across two days and history.daily / the provider
126
+ // breakdown never reconciled to current.cost. Raising MIN_SUPPORTED_VERSION
127
+ // forces the one-time re-hydration that rebuilds history under turn bucketing.
128
+ //
129
+ // v12: CodeWhale support adds historical usage that earlier rollups
130
+ // did not contain. Both the CodeWhale branch and the kiro credit-pricing
131
+ // change (below) claimed v11 independently, so v12 is the first version that
132
+ // contains both; raising MIN_SUPPORTED_VERSION forces the one-time
133
+ // re-hydration for days finalized at either v11.
134
+ //
135
+ // v11: kiro cost accounting changed (metered credits pass through
136
+ // the session cache instead of being re-priced from estimated tokens), so
137
+ // days finalized at v10 carry token-estimated kiro costs that were off by up
138
+ // to 16× per model. Raising MIN_SUPPORTED_VERSION forces the one-time full
139
+ // re-hydration that backfills history under credit-based pricing.
140
+ //
141
+ // v10: cursor accounting changed (real composer context tokens on
142
+ // conversation-anchored records, Cursor-published composer pricing), so days
143
+ // finalized at v9 carry the old double-counted agentKv estimates and
144
+ // sonnet-proxy composer costs.
145
+ //
146
+ // v9: providers added since the v8 rollup (Grok, Hermes, ZCode) parse usage
147
+ // that older binaries skipped. v8 added local-model savings to the daily
148
+ // rollup; the `savingsConfigHash` field is invalidated separately when the
149
+ // user changes their `localModelSavings` mapping.
150
+ // v23: codex pricing fix (#1075) - reasoning tokens were billed on top of
151
+ // output (they are a subset of it) and cache_write_input_tokens was ignored, so
152
+ // days finalized at v20 carry codex costs overstated by ~3.5% and codex output
153
+ // tokens overstated by ~34.6%. Raising MIN_SUPPORTED_VERSION forces the
154
+ // one-time re-derivation.
155
+ // It takes 23, not 21: v21 is claimed by the #946 landing branch and v22 by
156
+ // PR #1056, so those numbers are spoken for and reusing one would let two
157
+ // incompatible schemas share a filename. (feat/core-extraction sits at 26 and
158
+ // reconciles at its final merge by keeping the max.)
159
+ //
160
+ // v24: gpt-5.6-codex / gpt-5.6-codex-max pricing (#1077) - added as explicit
161
+ // litellm-snapshot.json rows. getModelCosts already resolved both ids to the
162
+ // correct rate via the `gpt-5.6` prefix fallback before this landed, so a day
163
+ // finalized on any binary that had a `gpt-5.6` snapshot row already carries
164
+ // the right cost; this bump only matters for a day finalized before THAT (a
165
+ // window where neither existed). The daily cache has no per-provider
166
+ // invalidation, so there is no way to tell those days apart from here -
167
+ // raising MIN_SUPPORTED_VERSION forces the one-time re-derivation for
168
+ // everyone, which is a lossless no-op for days already correct.
169
+ // v25: #1047 activity-id pricing. v24 on main already shipped #1090.
170
+ // v26: #946 copilot session-store accounting (see the top of this ladder).
171
+ // v27: #1093 claude-haiku-4.5 alias (see top).
172
+ // v28: #1115 report/optimize output tokens go through billableOutputTokens.
173
+ // Exclusive providers (Grok and the rest) were under-counted by reasoningTokens
174
+ // in finalized daily rows; inclusive {claude,codex,copilot} were correct there
175
+ // but optimize added reasoning again. Re-derive so report matches the live parse.
176
+ // v29: #1118 OrcaRouter route pricing (fusion aliases + peel; auto stays unpriced).
177
+ // v28 on main already shipped #1115.
178
+ // v31: Hermes cost provenance. Subscription-included sessions stay $0,
179
+ // explicit estimates retain their status, and surviving Hermes sources replace
180
+ // v29 slices produced by the old API-equivalent fallback.
181
+ // 31: #1234 Hermes cost contract; 30 is claimed by #1132.
182
+ // v32: DSH session formats v1-v3 and inclusive reasoning accounting. Re-derive
183
+ // finalized DSH days so migrated generations and retry attempts replace the
184
+ // v0-only totals, and reasoning detail is not added on top of full output.
185
+ // v33: #1450 billing routes. `day.models` is keyed by modelRowKey (display
186
+ // name + route label) instead of the raw provider id, so a route the provider
187
+ // recorded in its own column (Hermes `billing_provider`) survives into the
188
+ // finalized day; the raw id alone cannot carry it. A v32 day holds raw ids,
189
+ // which re-derive to the same rows for direct calls and to "(Bedrock)" rows
190
+ // for Bedrock-shaped ids, but its Hermes column routes are unrecoverable
191
+ // without a re-parse, so hermes joins PENDING_REDERIVE_PROVIDER_VERSIONS.
192
+ // v34: Warp cost accounting changed the same way kiro's did at v11 - Warp's
193
+ // own billing record (provider cost / charged usage / metered credits) now
194
+ // passes through the session cache instead of being re-priced from the token
195
+ // floor, which understated or overstated every Warp day. Days finalized at v33
196
+ // carry the floor figure; the bump re-derives those whose Warp conversations
197
+ // still exist (Warp's sqlite is durable, so effectively all of them) and
198
+ // carries the rest forward untouched. Call counts are unchanged, so no
199
+ // PENDING_REDERIVE entry is needed and the partial-survival guard is unaffected.
200
+ // v35: a non-Anthropic model with no published cache-write rate now bills
201
+ // cache-write tokens at its input rate instead of a fabricated 1.25x. Days
202
+ // finalized at v34 overstate those tokens; the bump re-derives surviving days.
203
+ // v36: Cursor Agent counts every assistant message of an agentic loop, not
204
+ // just the first after each user message, and bills tool_use inputs and the
205
+ // full user text. Days finalized at v35 hold a fraction of those calls; the
206
+ // provider parse version alone re-parses sessions but never reopens a
207
+ // finalized day, so the bump re-derives surviving days. Call counts only
208
+ // rise, so no PENDING_REDERIVE entry is needed.
209
+ // v37: #1547 OpenCode/KiloCode. A turn CodeBurn cannot price keeps the cost
210
+ // OpenCode recorded instead of $0, and Vertex turns land on a "(Vertex)" row.
211
+ // Days finalized at v36 hold $0 and the unrouted row; the bump re-derives
212
+ // surviving days. Call counts are unchanged.
213
+ // v38: #1529 Copilot OTel conversations land on their VS Code workspace
214
+ // instead of `copilot-chat`. Only the per-project split moves; cost, tokens and
215
+ // calls are unchanged. Settled days keep the old split unless they re-derive,
216
+ // and the session cache still holds their calls, so the bump re-derives them.
217
+ // Calls whose spans were already pruned from agent-traces.db keep the old
218
+ // label: the copilot re-parse only replaces calls the DB still holds.
219
+ // v39: #986 Cursor Agent reads CLI sessions that exist only in
220
+ // ~/.cursor/chats/*/*/store.db. Days finalized at v38 miss those calls; the
221
+ // bump re-derives surviving days. Call counts only rise.
222
+ // v40: Codex fork usage after the copied-history burst was clipped by the old
223
+ // 5s window. Re-derive Codex slices from the updated session cache so settled
224
+ // days recover those calls and tokens.
225
+ // v41: OMP side calls (`model_usage` entries: find, judge, cache warming) now
226
+ // count. Days finalized at v40 miss them; the bump re-derives surviving days.
227
+ // Call counts and cost only rise.
228
+ // v42: #1076 long-context tiers. A Codex call past a model's published
229
+ // long-context threshold prices at the tier rate, so settled days re-derive.
230
+ // v43: Codex response-level token_usage_record repairs compacted/interrupted
231
+ // responses and suppresses stale token_count twins. Counts can rise or fall,
232
+ // so re-derive surviving days and allow the Codex slice to shrink once.
233
+ // v44: Claude queued_command human prompts split and reclassify turns. Calls
234
+ // and tokens are unchanged, but settled category totals need re-derivation.
235
+ // v45: #1581 ZCode user prompt text now reaches classification. Calls and
236
+ // cost are unchanged, but settled zcode category totals need re-derivation.
237
+ // v46: Devin usage comes from sessions.db instead of the transcript exports,
238
+ // which held a few sessions and dated steps without metadata.created_at on the
239
+ // session's last activity. Days finalized at v45 miss most Devin calls, and a
240
+ // day can also lose calls that now land on their real date, so devin joins
241
+ // PENDING_REDERIVE_PROVIDER_VERSIONS.
242
+ // v47: Copilot chat-session journals read request-level promptTokens, repairing
243
+ // missing input usage and input-only calls. Re-derive settled days from the
244
+ // corrected session cache; calls and cost only rise.
245
+ // v48: #1620 Antigravity manage_task/search_web/read_url_content/invoke_subagent
246
+ // reclassify turns. Calls and cost are unchanged, but settled antigravity
247
+ // category totals need re-derivation.
248
+ // v49: Crush's recorded cumulative session cost now passes through the session
249
+ // cache instead of being re-priced from its non-cumulative token counters. Days
250
+ // finalized before v49 hold the re-priced figure with unchanged call counts, so the
251
+ // read path's equal-call rule keeps them; the bump re-derives surviving days.
252
+ // Call counts are unchanged, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is
253
+ // needed.
254
+ // v50: Hermes uses its native Windows LOCALAPPDATA root; finalized days can
255
+ // miss sessions there and must be re-derived after the default path is fixed.
256
+ // v51: honor redirected Copilot and Cursor editor data roots. Backfill settled
257
+ // days that previously missed usage stored under APPDATA or XDG_CONFIG_HOME.
258
+ // v52: DSH session format v4 (dsh 0.2.0-rc.2) is read; days finalized while
259
+ // those sessions were skipped re-derive. Calls only rise, so no
260
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
261
+ // v53: #1616 Codex priority-tier pricing. Turns run under Codex's Fast speed
262
+ // setting bill at the published priority rates (2x on most gpt-5/6 rows, 2.5x
263
+ // on gpt-5.5; per-row, derived from LiteLLM's priority keys), so settled days
264
+ // under-price them; the bump re-derives surviving days off the warm session
265
+ // cache. MIN_SUPPORTED_VERSION stays at 28 (#1478's convention: a version bump
266
+ // alone re-derives warm caches, so raising the floor buys nothing).
267
+ // v54: `codex-auto-review` prices as gpt-5.4 before 30 Jul 2026 and GPT-5.6
268
+ // Luna from then on (OpenAI's auto-review move), not gpt-5.5, so settled days
269
+ // over-price it. Only cost falls; call counts are unchanged, so no
270
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
271
+ // v55: Codex service_tier "flex" bills at the published Flex rates instead of
272
+ // standard, and `gpt-reserve` / `gpt-5.3-spark` price as GPT-5.6 Luna / GPT-5.3
273
+ // Codex Spark instead of $0. Only cost moves; call counts are unchanged, so no
274
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
275
+ // v56: Copilot assistant.message events with no outputTokens (CLI 1.0.8x, the
276
+ // VS Code agent host) count as calls, and their shutdown rollup (or, under
277
+ // session-store rows, its residual) carries the output it previously dropped.
278
+ // Settled days re-derive. Calls only rise, except a store row and its message
279
+ // straddling midnight, which moves one call to the next day; copilot's
280
+ // PENDING_REDERIVE contract moves to 56 so that day may shrink once.
281
+ // v57: Copilot session-store rows carry their own output where no per-turn call
282
+ // does, so a session that never wrote session.shutdown (ACP hosts such as
283
+ // JetBrains AI Chat) counts its output, and grok-4.6 prices at xAI's $2/M input
284
+ // instead of Azure's $1.25/M. Output and cost only rise; call counts are
285
+ // unchanged, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
286
+ // v58: Cursor Agent transcript turns are dated by their prompt's <timestamp>
287
+ // tag instead of the session's last write. Settled days re-derive; a session
288
+ // that crossed midnight moves calls to an earlier day, so cursor-agent joins
289
+ // PENDING_REDERIVE_PROVIDER_VERSIONS at 58.
290
+ // v59: Antigravity reads cache-read tokens from gen_metadata and the RPC usage,
291
+ // and the standalone app's placeholder-only model (MODEL_PLACEHOLDER_M16, stored
292
+ // as "gemini-pro-default") prices as gemini-3.1-pro-high instead of $0, with
293
+ // the above-200k tier. Cache read and cost only rise. Standalone rows without
294
+ // created_at move from the file-mtime day to their first step's day, so a
295
+ // session that crossed midnight moves calls to an earlier day, and antigravity
296
+ // joins PENDING_REDERIVE_PROVIDER_VERSIONS at 59.
297
+ // v60: Mistral Vibe 2.26 Unified Harness sessions (`unified/<id>/`) are read;
298
+ // days finalized while they were skipped re-derive. Calls only rise, so no
299
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
300
+ // v61: #1579 Claude Desktop usage-ledger records (Claude-3p Cowork and Code)
301
+ // are read and de-duplicated against matching transcript calls. Calls only
302
+ // rise, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
303
+ // v62: Devin's SWE-2 prices at Cognition's list rate and swe-1-7-lightning as
304
+ // swe-1.7-lightning instead of $0. Only cost rises; call counts are unchanged,
305
+ // so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
306
+ // v63: Cline CLI input tokens include cache reads and writes, which were then
307
+ // billed again at the cache rates. Only input tokens and estimated cost fall;
308
+ // call counts are unchanged, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is
309
+ // needed.
310
+ // v64: Kimi Code's `kimi-for-coding` prices by the model it served on the call's
311
+ // date (K2.5, K2.6, K2.7 Code) instead of retired K2 Thinking, and
312
+ // `kimi-for-coding-highspeed` prices at K2.7 Code HighSpeed instead of $0.
313
+ // From 11 Sep 2026 the alias served K2.8 Preview, which has no published rate;
314
+ // those calls price as K2.7 Code and are marked estimated.
315
+ // Calls are unchanged, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
316
+ // v65: Grok Build reads per-request usage from logs/unified.jsonl and uses it
317
+ // in place of a session dir's one-call rollup for every session the log holds;
318
+ // days finalized without it re-derive. A logged session's single rollup call,
319
+ // dated at its last activity, becomes one call per request dated at that
320
+ // request, so a session that crossed midnight moves calls to an earlier day and
321
+ // grok joins PENDING_REDERIVE_PROVIDER_VERSIONS at 65.
322
+ // v66: Codex fork replay bursts drop only records found in the parent rollout;
323
+ // burst records the parent kept only inside a running total now count. Calls
324
+ // only rise, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
325
+ // v67: a day's project split is keyed per (label, path) instead of per label,
326
+ // which kept only the first path a label showed that day and handed the whole
327
+ // label (e.g. every home-folder Claude session) to whichever project owned it.
328
+ // Day and provider totals are unchanged, only the split inside them moves, so
329
+ // no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
330
+ // v68: Kimi Code sessions whose state.json carries `cwd` but no `workDir` land
331
+ // on that folder. Only the per-project split moves; cost, tokens and calls are
332
+ // unchanged, so the bump re-derives surviving days.
333
+ // v69: Claude calls go to the project of their own cwd, so a session that
334
+ // moved folders splits across projects per call. Settled days re-derive their
335
+ // project rows; provider call counts and cost are unchanged, so no
336
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed. Days whose transcripts
337
+ // are gone keep their old single-project attribution.
338
+ // v70: a day's project entry records the `origin` remote of its checkout, so
339
+ // clones and worktrees of one repository still group once the folder is
340
+ // deleted. Totals and the split are unchanged; surviving days re-derive to
341
+ // pick it up, carried days stay as they were.
342
+ // v71: a Cursor usage import that landed while the running binary had no
343
+ // daily-cache file of its own skipped its invalidation, so adoption carried the
344
+ // local Cursor estimates back and the guard kept them over the imported events,
345
+ // which are fewer calls. cursor joins PENDING_REDERIVE_PROVIDER_VERSIONS at 71.
346
+ // v72: on days a Cursor import fully covers, the parse produces no local
347
+ // cursor-agent (or Grok Bot, when the import holds its rows) slice, so the
348
+ // merge carried the old one on top of the imported rows. Adoption and the
349
+ // complete re-derive now drop those slices; the bump repairs carried days.
350
+ // v73: cursor-agent skips agent transcripts of Cursor IDE chats, which the
351
+ // cursor provider already counts from the IDE database. Those calls leave
352
+ // cursor-agent, so it joins PENDING_REDERIVE_PROVIDER_VERSIONS at 73.
353
+ // v74: Antigravity sessions whose gen_metadata lacks usage.model are parsed
354
+ // instead of dropped, Gemini 3.8 Flash placeholders get their own ids and
355
+ // Gemini 3 Flash -a/-d rows are priced. Calls and cost only rise, so no
356
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
357
+ // v75: Copilot chat-session requests count every agent round and bill from
358
+ // copilotCredits, and a chat session that also ran on the agent host is left
359
+ // to it. That twin drops calls, so copilot joins
360
+ // PENDING_REDERIVE_PROVIDER_VERSIONS at 75.
361
+ // v76: Codex reads the Zstandard-compressed rollouts (`rollout-*.jsonl.zst`)
362
+ // Codex moves cold sessions into, which were skipped, so days settled after
363
+ // that move miss their Codex usage. Calls and cost only rise, so no
364
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
365
+ // v77: Warp conversations that carry only total_billed_cost_in_cents are
366
+ // priced from it instead of the credits estimate. Calls are unchanged, so no
367
+ // PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed. 77 is the generation
368
+ // both 0.9.27 upgrade paths converge on; no-zstd Nodes can no longer run since
369
+ // the 22.15 floor.
370
+ // v78: subagent messages from Claude Code before 2.1.307 never got a final
371
+ // usage row, and their output is now estimated from content. Days settled on
372
+ // the placeholder counts re-derive so they carry it. Calls are unchanged and
373
+ // output and cost only rise, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is
374
+ // needed. The re-derive also moves the Claude activity split (exploration,
375
+ // coding and delegation turns and their cost share, edit turns, one-shot
376
+ // counts) of days whose transcripts survive onto the streamed-tool-blocks
377
+ // parse (October 2026), which left settled days on the old split.
378
+ // v79: the November provider fixes reach settled days. Calls leave a day for
379
+ // codex (rate-limit pings are no longer calls), copilot (a chat that both the
380
+ // trace database and a transcript record counts once), cursor (old
381
+ // conversations' streams are no longer billed at the database mtime, cut
382
+ // streams move to their own bubble time), goose (UTC timestamps can move a
383
+ // session across midnight) and quickdesk (an estimate stops counting once its
384
+ // metrics land), so those providers join PENDING_REDERIVE_PROVIDER_VERSIONS at
385
+ // 79. Qwen and Hermes tokens, Droid model ids, Cline-family recorded costs,
386
+ // Antigravity output, Warp exchange shares and version-boundary pricing change
387
+ // with calls unchanged or rising, which the bump alone re-derives.
388
+ // v80: settled days pick up Kimi Code managed workspaces (wm_*). Discovery only
389
+ // adds calls, so no PENDING_REDERIVE_PROVIDER_VERSIONS entry is needed.
390
+ // v81: reprice settled Antigravity days for users who already configured rates or discounts.
391
+ export const DAILY_CACHE_VERSION = 81;
392
+ const MIN_SUPPORTED_VERSION = 28;
393
+ /// Providers whose per-day CALL COUNT means something different at
394
+ /// DAILY_CACHE_VERSION 26 than it did before it. Copilot's supplementary
395
+ /// accounting calls (rollups, residuals, store rows paired with a per-turn
396
+ /// call) stopped counting as api calls here, so a settled day's re-derivation
397
+ /// legitimately reports FEWER calls than the cache holds — which is exactly
398
+ /// the shape `isPartialSurvival` reads as "the sources aged out" (see the
399
+ /// TRADE-OFF note there, which called this case out in advance). Left
400
+ /// unhandled the guard pins every store-era copilot slice to its pre-store
401
+ /// value: measured on a real 17 -> 21 upgrade, `overview` served 2,980,804
402
+ /// tokens for a day whose fresh derivation is 74,811,412, while
403
+ /// `export`/`models`/`audit` (which never read this cache) served the
404
+ /// corrected figures off the same machine.
405
+ ///
406
+ /// The exemption is one-shot and provider-scoped, not a relaxation of the
407
+ /// guard: `pendingRederive` is set only when a cache is migrated FROM a
408
+ /// version below this one, it is spent by the first complete re-derivation,
409
+ /// and it only ever fires where that re-derivation actually produced a slice
410
+ /// for the (day, provider). A day whose copilot sources are gone yields no
411
+ /// fresh slice at all, so it still carries forward whole — the #1033 bar is
412
+ /// untouched, in both directions, and every other provider keeps the guard.
413
+ const PENDING_REDERIVE_PROVIDER_VERSIONS = {
414
+ // 56: a store row now pairs with its tokenless per-turn twin, which can
415
+ // move one call across midnight. 75: chat sessions that also ran on the
416
+ // agent host are no longer counted from the journal. 79: the transcript of
417
+ // a chat the trace database also holds is no longer an extra call.
418
+ copilot: 79,
419
+ // Codex response records replace stale/zero token_count twins and can
420
+ // legitimately reduce counts as well as recover missing usage. 79: a
421
+ // turn-start rate-limit ping is no longer an estimated call. A day whose
422
+ // only Codex calls were pings has no fresh slice and stays carried: a day
423
+ // slice records no estimated share to tell it from pruned history.
424
+ codex: 79,
425
+ // 31: a v30 file may have been written by #1132's accounting, which never
426
+ // carried the Hermes cost contract. 33: day.models is keyed by route, and a
427
+ // v32 Hermes day cannot know which of its rows went through
428
+ // `billing_provider = bedrock` / `openrouter` (#1450).
429
+ hermes: 33,
430
+ // DSH v0-only parsing and exclusive-reasoning display were both stale in
431
+ // finalized days written before the multi-generation reader.
432
+ dsh: 32,
433
+ // 46: transcript-era Devin days put every step lacking metadata.created_at
434
+ // on the session's last-activity day; sessions.db dates each request.
435
+ devin: 46,
436
+ // 58: transcript turns moved from the session's last write to prompt time.
437
+ // 73: transcripts of Cursor IDE chats are left to the cursor provider.
438
+ 'cursor-agent': 73,
439
+ // 59: standalone rows without created_at moved from the file mtime to the
440
+ // first step's time.
441
+ antigravity: 59,
442
+ // 65: logged sessions moved from one rollup at last activity to per-request
443
+ // calls at request time.
444
+ grok: 65,
445
+ // 71: imported Cursor events replace the local estimates with fewer calls.
446
+ // 79: streams of conversations older than the window are dropped, and cut
447
+ // streams move from the database mtime to their newest bubble.
448
+ cursor: 79,
449
+ // 79: zoneless timestamps read as UTC, not local time.
450
+ goose: 79,
451
+ // 79: a sessions.db estimate stops counting once the session's metrics land.
452
+ quickdesk: 79,
453
+ };
454
+ function providersPendingRederiveFrom(fromVersion) {
455
+ return Object.entries(PENDING_REDERIVE_PROVIDER_VERSIONS)
456
+ .filter(([, contractVersion]) => fromVersion < contractVersion)
457
+ .map(([provider]) => provider);
458
+ }
459
+ // Version-suffixed so different binaries each own a distinct file and never
460
+ // clobber an incompatible schema. Bumping the version mints a fresh filename;
461
+ // adoptOlderDailyCaches then unions days out of every previous file (including
462
+ // the pre-versioning `daily-cache.json`, which old binaries still own and we
463
+ // never write or delete).
464
+ const DAILY_CACHE_FILENAME = `daily-cache.v${DAILY_CACHE_VERSION}.json`;
465
+ /// One project label can span several real paths (every Claude session started
466
+ /// from the home folder shares `-Users-<name>`), so since v67 a day's project
467
+ /// split is keyed per (label, path). Days written earlier key by label alone
468
+ /// and keep one path for the whole label; they stay readable through
469
+ /// projectDayIdentity.
470
+ const PROJECT_KEY_SEP = '\u0000';
471
+ export function projectDayKey(project, path) {
472
+ return path ? `${project}${PROJECT_KEY_SEP}${path}` : project;
473
+ }
474
+ export function projectDayIdentity(key, stats) {
475
+ const sep = key.indexOf(PROJECT_KEY_SEP);
476
+ return { project: sep === -1 ? key : key.slice(0, sep), projectPath: stats.path ?? '', ...(stats.originKey ? { originKey: stats.originKey } : {}) };
477
+ }
478
+ /** IANA name of the current local timezone (respects the TZ env var). Days are
479
+ * bucketed by local midnight, so this tags the cache for TZ-change invalidation. */
480
+ export function currentTzKey() {
481
+ try {
482
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || '';
483
+ }
484
+ catch {
485
+ return '';
486
+ }
487
+ }
488
+ function getCachePath() {
489
+ return join(getCodeburnCacheDir(), DAILY_CACHE_FILENAME);
490
+ }
491
+ /** Absolute path of the active (version-suffixed) daily cache file. */
492
+ export function dailyCachePath() {
493
+ return getCachePath();
494
+ }
495
+ export function emptyCache(savingsConfigHash = '') {
496
+ return { version: DAILY_CACHE_VERSION, savingsConfigHash, tzKey: currentTzKey(), lastComputedDate: null, days: [], complete: false };
497
+ }
498
+ function isMigratableCache(parsed) {
499
+ if (!parsed || typeof parsed !== 'object')
500
+ return false;
501
+ const c = parsed;
502
+ if (typeof c.version !== 'number')
503
+ return false;
504
+ if (!Array.isArray(c.days))
505
+ return false;
506
+ return c.version >= MIN_SUPPORTED_VERSION && c.version <= DAILY_CACHE_VERSION;
507
+ }
508
+ function num(v) {
509
+ return typeof v === 'number' && Number.isFinite(v) ? v : 0;
510
+ }
511
+ function isRecord(value) {
512
+ return !!value && typeof value === 'object' && !Array.isArray(value);
513
+ }
514
+ function sanitizeModels(raw) {
515
+ if (!isRecord(raw))
516
+ return {};
517
+ const out = {};
518
+ for (const [name, m] of Object.entries(raw)) {
519
+ if (!isRecord(m))
520
+ continue;
521
+ setOwn(out, name, {
522
+ calls: num(m.calls),
523
+ cost: num(m.cost),
524
+ savingsUSD: num(m.savingsUSD),
525
+ inputTokens: num(m.inputTokens),
526
+ outputTokens: num(m.outputTokens),
527
+ cacheReadTokens: num(m.cacheReadTokens),
528
+ cacheWriteTokens: num(m.cacheWriteTokens),
529
+ });
530
+ }
531
+ return out;
532
+ }
533
+ function sanitizeCategories(raw) {
534
+ if (!isRecord(raw))
535
+ return {};
536
+ const out = {};
537
+ for (const [name, c] of Object.entries(raw)) {
538
+ if (name in Object.prototype || !isRecord(c))
539
+ continue;
540
+ setOwn(out, name, {
541
+ turns: num(c.turns),
542
+ cost: num(c.cost),
543
+ savingsUSD: num(c.savingsUSD),
544
+ editTurns: num(c.editTurns),
545
+ oneShotTurns: num(c.oneShotTurns),
546
+ });
547
+ }
548
+ return out;
549
+ }
550
+ const OPTIONAL_SLICE_NUMERICS = ['sessions', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'editTurns', 'oneShotTurns'];
551
+ /// Same junk-tolerance as sanitizeProjects, one level up: a foreign cache can
552
+ /// hold anything under a provider slice, and structuredClone in the merge
553
+ /// would faithfully preserve that junk into the next cache generation. Numeric
554
+ /// fields and nested maps are sanitized before the slice enters the cache.
555
+ function sanitizeProviders(raw) {
556
+ if (!isRecord(raw))
557
+ return {};
558
+ const out = {};
559
+ for (const [name, s] of Object.entries(raw)) {
560
+ if (name in Object.prototype || !isRecord(s))
561
+ continue;
562
+ const slice = s;
563
+ const clean = { calls: num(slice.calls), cost: num(slice.cost), savingsUSD: num(slice.savingsUSD) };
564
+ for (const key of OPTIONAL_SLICE_NUMERICS) {
565
+ if (slice[key] !== undefined)
566
+ clean[key] = num(slice[key]);
567
+ }
568
+ if (isRecord(slice.models))
569
+ clean.models = sanitizeModels(slice.models);
570
+ if (isRecord(slice.categories))
571
+ clean.categories = sanitizeCategories(slice.categories);
572
+ const projects = sanitizeProjects(slice.projects).projects;
573
+ if (projects)
574
+ clean.projects = projects;
575
+ setOwn(out, name, clean);
576
+ }
577
+ return out;
578
+ }
579
+ /// Foreign or hand-edited caches can hold anything under `projects`; keep only
580
+ /// a plain record of finite numeric stats (arrays and null entries dropped) so
581
+ /// later carry merges can't crash on junk.
582
+ function sanitizeProjects(raw) {
583
+ if (!isRecord(raw))
584
+ return {};
585
+ const out = {};
586
+ for (const [name, p] of Object.entries(raw)) {
587
+ // A project key is a directory basename, so it can legitimately be a
588
+ // prototype-member name ("constructor", "valueOf", ...). `setOwn` writes it
589
+ // as an own property via defineProperty, so keeping it is pollution-safe —
590
+ // and dropping it would silently subtract that project's cost from a
591
+ // --project/--exclude total (the day's split would no longer sum to its own
592
+ // cost, which the filtered headline relies on).
593
+ if (!isRecord(p))
594
+ continue;
595
+ setOwn(out, name, {
596
+ cost: num(p.cost),
597
+ calls: num(p.calls),
598
+ savingsUSD: num(p.savingsUSD),
599
+ sessions: num(p.sessions),
600
+ ...(typeof p.path === 'string' && p.path.length > 0 ? { path: p.path } : {}),
601
+ ...(typeof p.originKey === 'string' && p.originKey.length > 0 ? { originKey: p.originKey } : {}),
602
+ });
603
+ }
604
+ return Object.keys(out).length > 0 ? { projects: out } : {};
605
+ }
606
+ const DATE_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
607
+ /// The row that owns a provider slice's calls and cost no model row explains.
608
+ /// Pre-v14 slices carry only calls/cost/savings, so their money exists in the
609
+ /// day total with nothing to attribute it to and every model table silently
610
+ /// totals less than the headline it sits under.
611
+ export const CARRIED_MODEL_NAME = 'Unknown (carried)';
612
+ const REMAINDER_KEYS = ['calls', 'cost', 'savingsUSD', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'];
613
+ const TOKEN_KEYS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'];
614
+ /// Money is compared at the cent every surface reports it in. Summing a day's
615
+ /// model rows in a different order than its total was accumulated leaves a
616
+ /// 1e-13 residue on most days; without this, every one of them would grow a
617
+ /// carried row holding a fraction of a cent and no calls.
618
+ const CENT = 0.005;
619
+ /// Credit whatever `totals` holds that its own model rows cannot explain to
620
+ /// CARRIED_MODEL_NAME. Idempotent: the row it writes is part of the next sum,
621
+ /// so a second pass sees a zero remainder. Only ever adds: money with no calls
622
+ /// against it (a slice that recorded cost but never a request) still gets a row.
623
+ function creditCarriedRemainder(totals, models) {
624
+ const rows = Object.values(models);
625
+ const rest = emptyModelStats();
626
+ for (const key of REMAINDER_KEYS) {
627
+ rest[key] = Math.max(0, num(totals[key]) - rows.reduce((sum, m) => sum + m[key], 0));
628
+ }
629
+ // Token remainders (whole tokens) are part of REMAINDER_KEYS too: a day whose
630
+ // cost and calls reconcile but whose token totals fall short must still credit
631
+ // the missing tokens to the carried row, or the model rows sum to fewer tokens
632
+ // than the day headline.
633
+ const tokenRemainder = rest.inputTokens + rest.outputTokens + rest.cacheReadTokens + rest.cacheWriteTokens;
634
+ if (rest.calls <= 0 && rest.cost < CENT && rest.savingsUSD < CENT && tokenRemainder < 1)
635
+ return;
636
+ const acc = Object.hasOwn(models, CARRIED_MODEL_NAME) ? models[CARRIED_MODEL_NAME] : emptyModelStats();
637
+ for (const key of REMAINDER_KEYS)
638
+ acc[key] += rest[key];
639
+ setOwn(models, CARRIED_MODEL_NAME, acc);
640
+ }
641
+ /// A token-only slice used to read as a placeholder, so every merge over it
642
+ /// added its tokens to the day again while the slice itself stayed whole. A day
643
+ /// whose slices all carry token figures never holds more than their sum; one
644
+ /// holding a pre-v14 slice without them keeps its own totals.
645
+ function healTokenTotals(day) {
646
+ const slices = Object.values(day.providers);
647
+ if (slices.length === 0 || slices.some(s => TOKEN_KEYS.every(k => s[k] === undefined)))
648
+ return;
649
+ // A day whose calls or cost also disagree with its slices has a different
650
+ // problem, and capping its tokens alone would hide it.
651
+ if (slices.reduce((sum, s) => sum + s.calls, 0) !== day.calls || Math.abs(slices.reduce((sum, s) => sum + s.cost, 0) - day.cost) >= CENT)
652
+ return;
653
+ const sums = TOKEN_KEYS.map(k => slices.reduce((sum, s) => sum + (s[k] ?? 0), 0));
654
+ if (TOKEN_KEYS.every((k, i) => day[k] <= sums[i]))
655
+ return;
656
+ TOKEN_KEYS.forEach((k, i) => { day[k] = Math.min(day[k], sums[i]); });
657
+ const rows = {};
658
+ for (const s of slices) {
659
+ for (const [name, m] of Object.entries(s.models ?? {})) {
660
+ const acc = Object.hasOwn(rows, name) ? rows[name] : emptyModelStats();
661
+ for (const k of TOKEN_KEYS)
662
+ acc[k] += m[k];
663
+ setOwn(rows, name, acc);
664
+ }
665
+ }
666
+ for (const [name, r] of Object.entries(rows)) {
667
+ if (Object.hasOwn(day.models, name))
668
+ for (const k of TOKEN_KEYS)
669
+ day.models[name][k] = Math.min(day.models[name][k], r[k]);
670
+ }
671
+ }
672
+ function migrateDays(days) {
673
+ return days
674
+ .filter(d => d && typeof d === 'object' && typeof d.date === 'string' && DATE_KEY_RE.test(d.date))
675
+ .map((d) => ({
676
+ date: d.date,
677
+ cost: num(d.cost),
678
+ savingsUSD: num(d.savingsUSD),
679
+ calls: num(d.calls),
680
+ sessions: num(d.sessions),
681
+ inputTokens: num(d.inputTokens),
682
+ outputTokens: num(d.outputTokens),
683
+ cacheReadTokens: num(d.cacheReadTokens),
684
+ cacheWriteTokens: num(d.cacheWriteTokens),
685
+ editTurns: num(d.editTurns),
686
+ oneShotTurns: num(d.oneShotTurns),
687
+ models: sanitizeModels(d.models),
688
+ categories: sanitizeCategories(d.categories),
689
+ providers: sanitizeProviders(d.providers),
690
+ ...(sanitizeProjects(d.projects)),
691
+ ...(d.carried === true ? { carried: true } : {}),
692
+ }))
693
+ .filter(day => {
694
+ let retired = false;
695
+ for (const provider of RETIRED_PROVIDER_NAMES) {
696
+ if (!Object.hasOwn(day.providers, provider))
697
+ continue;
698
+ subtractSliceFromDay(day, provider, day.providers[provider]);
699
+ retired = true;
700
+ }
701
+ return !retired || hasPositiveDayContent(day);
702
+ })
703
+ // Day and slices are summed independently: a day can hold the full model
704
+ // split while one of its slices was written before slices carried one (or
705
+ // the reverse), and a provider-scoped view reads the slice's map alone.
706
+ .map(day => {
707
+ healTokenTotals(day);
708
+ for (const slice of Object.values(day.providers))
709
+ creditCarriedRemainder(slice, slice.models ??= {});
710
+ creditCarriedRemainder(day, day.models);
711
+ return day;
712
+ });
713
+ }
714
+ /// The providers a cache at `fromVersion` still owes a re-derivation, carrying
715
+ /// an unspent entitlement out of the parsed file so a same-version reload does
716
+ /// not drop it.
717
+ function pendingRederiveFor(fromVersion, parsed) {
718
+ const raw = parsed?.pendingRederive;
719
+ const pending = new Set(Array.isArray(raw) ? raw.filter((p) => typeof p === 'string') : []);
720
+ if (fromVersion < DAILY_CACHE_VERSION) {
721
+ for (const provider of providersPendingRederiveFrom(fromVersion))
722
+ pending.add(provider);
723
+ }
724
+ return pending.size > 0 ? [...pending] : undefined;
725
+ }
726
+ function migratedFrom(parsed) {
727
+ const pendingRederive = pendingRederiveFor(parsed.version, parsed);
728
+ return {
729
+ ...(pendingRederive ? { pendingRederive } : {}),
730
+ version: DAILY_CACHE_VERSION,
731
+ savingsConfigHash: parsed.savingsConfigHash ?? '',
732
+ tzKey: parsed.tzKey,
733
+ lastComputedDate: typeof parsed.lastComputedDate === 'string' && DATE_KEY_RE.test(parsed.lastComputedDate)
734
+ ? parsed.lastComputedDate
735
+ : null,
736
+ days: migrateDays(parsed.days),
737
+ // Only a cache explicitly marked complete stays trusted; one written before
738
+ // the marker existed reads false and is re-backfilled once.
739
+ complete: parsed.complete === true,
740
+ // Absent on a pre-fix cache: the watermark is distrusted once (healing
741
+ // pull-back), then re-stamped by the finalize that follows.
742
+ watermarkTrusted: parsed.watermarkTrusted === true,
743
+ };
744
+ }
745
+ export async function loadDailyCache() {
746
+ const path = getCachePath();
747
+ if (existsSync(path)) {
748
+ try {
749
+ const parsed = JSON.parse(await readFile(path, 'utf-8'));
750
+ if (isMigratableCache(parsed)) {
751
+ const migrated = migratedFrom(parsed);
752
+ if (parsed.version < DAILY_CACHE_VERSION)
753
+ await saveDailyCache(migrated).catch(() => { });
754
+ return migrated;
755
+ }
756
+ }
757
+ catch {
758
+ // fall through to adoption — a corrupt current file must not cost history
759
+ // that older cache files still hold.
760
+ }
761
+ return adoptOlderDailyCaches();
762
+ }
763
+ return adoptOlderDailyCaches();
764
+ }
765
+ function isAdoptableCache(parsed) {
766
+ if (!parsed || typeof parsed !== 'object')
767
+ return false;
768
+ const c = parsed;
769
+ return typeof c.version === 'number' && Array.isArray(c.days);
770
+ }
771
+ /// Versioned file absent (or unreadable): adopt days from EVERY other
772
+ /// daily-cache file in the cache dir — the legacy unversioned file, older
773
+ /// versioned files, and manual .bak copies. Files are read, never written or
774
+ /// deleted (old binaries still own theirs). A candidate at exactly our version
775
+ /// (the legacy file written by a same-version binary) is fully trusted and
776
+ /// becomes the base; every other candidate contributes per-(day, provider)
777
+ /// slices it alone still has, marked `carried`. This is what makes a schema
778
+ /// bump lossless: the new version starts from the union of everything every
779
+ /// previous version ever recorded, then re-derives what sources still support.
780
+ async function adoptOlderDailyCaches() {
781
+ const dir = getCodeburnCacheDir();
782
+ let names = [];
783
+ try {
784
+ names = await readdir(dir);
785
+ }
786
+ catch {
787
+ return emptyCache();
788
+ }
789
+ let candidates = [];
790
+ for (const name of names) {
791
+ if (!name.startsWith('daily-cache') || !name.includes('.json'))
792
+ continue;
793
+ if (name === DAILY_CACHE_FILENAME)
794
+ continue;
795
+ // .tmp files are included deliberately: a crash between the atomic write
796
+ // completing and the rename landing leaves the NEWEST state only in the
797
+ // .tmp. A truncated half-write fails JSON.parse below and is skipped.
798
+ const path = join(dir, name);
799
+ try {
800
+ const parsed = JSON.parse(await readFile(path, 'utf-8'));
801
+ if (!isAdoptableCache(parsed))
802
+ continue;
803
+ candidates.push({ parsed, mtimeMs: (await stat(path)).mtimeMs });
804
+ }
805
+ catch {
806
+ continue;
807
+ }
808
+ }
809
+ if (candidates.length === 0)
810
+ return emptyCache();
811
+ // Priority: files finalized by a complete parse first (an interrupted
812
+ // backfill can hold under-read days), then newer schema, then most recently
813
+ // written. Higher priority wins per (day, provider); lower priority only
814
+ // fills what is missing. Not "more calls wins": older generations hold both
815
+ // days a later re-derive truncated and calls a later dedup removed, and a
816
+ // call count cannot tell the two apart.
817
+ candidates.sort((a, b) => Number(b.parsed.complete === true) - Number(a.parsed.complete === true) || (b.parsed.version - a.parsed.version) || (b.mtimeMs - a.mtimeMs));
818
+ // A date is a local-midnight bucket, so two files written under different
819
+ // timezones hold different hours under the same date and any per-slice union
820
+ // of them counts the hours between the two midnights twice. Adopt one
821
+ // timezone only, the top file's, and tag the result with it so hydration
822
+ // re-buckets it if the machine's differs. Preferring the machine's dropped
823
+ // the richest file whenever an older one matched. Files from before tzKey
824
+ // existed cannot be told apart and stay in.
825
+ const adoptTz = candidates.find(c => c.parsed.tzKey !== undefined)?.parsed.tzKey ?? currentTzKey();
826
+ candidates = candidates.filter(c => c.parsed.tzKey === undefined || c.parsed.tzKey === adoptTz);
827
+ let base;
828
+ let rest = candidates;
829
+ if (candidates[0].parsed.version === DAILY_CACHE_VERSION && isMigratableCache(candidates[0].parsed)) {
830
+ base = migratedFrom(candidates[0].parsed);
831
+ rest = candidates.slice(1);
832
+ }
833
+ else {
834
+ base = emptyCache(candidates[0].parsed.savingsConfigHash);
835
+ }
836
+ let days = base.days;
837
+ for (const { parsed } of rest) {
838
+ days = mergeDayEntries(days, await withoutImportReplacedSlices(migrateDays(parsed.days)), true);
839
+ }
840
+ // loadDailyCache has standalone readers, so the adopted result must already
841
+ // satisfy the cache's own invariants: no today/future entries (they would be
842
+ // served frozen instead of recomputed live) and nothing past retention.
843
+ const now = new Date();
844
+ const todayStr = toDateString(now);
845
+ const yesterdayStr = toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
846
+ days = stampOrigins(applyRetention(days.filter(d => d.date < todayStr), yesterdayStr));
847
+ // A trusted base can carry lastComputedDate >= today (clock skew wrote a
848
+ // frozen today entry that the purge above just removed). Left as-is it would
849
+ // make hydration skip the gap parse forever and the purged day would never
850
+ // be recomputed. Clamp back to the retained data.
851
+ let lastComputedDate = base.lastComputedDate;
852
+ if (lastComputedDate && lastComputedDate > yesterdayStr) {
853
+ lastComputedDate = days.length > 0 ? days[days.length - 1].date : null;
854
+ }
855
+ const adopted = {
856
+ ...base,
857
+ tzKey: adoptTz,
858
+ lastComputedDate,
859
+ days,
860
+ // Anything adopted out of an OLDER file was derived under an older
861
+ // accounting, so the providers whose call counts changed meaning get their
862
+ // one guarded-shrink-exempt re-derivation (see
863
+ // PENDING_REDERIVE_PROVIDER_VERSIONS).
864
+ pendingRederive: (() => {
865
+ const pending = new Set(base.pendingRederive ?? []);
866
+ for (const candidate of rest) {
867
+ for (const provider of pendingRederiveFor(candidate.parsed.version, candidate.parsed) ?? []) {
868
+ pending.add(provider);
869
+ }
870
+ }
871
+ return pending.size > 0 ? [...pending] : undefined;
872
+ })(),
873
+ // An untrusted base means nothing here was derived under the current
874
+ // accounting: leave complete unset so the next hydration re-derives every
875
+ // day whose sources survive (the merge keeps the rest).
876
+ complete: rest.length === candidates.length ? false : base.complete,
877
+ watermarkTrusted: rest.length === candidates.length ? false : base.watermarkTrusted,
878
+ };
879
+ await saveDailyCache(adopted).catch(() => { });
880
+ return adopted;
881
+ }
882
+ /// Adopted days written before v70 learn the repository of each checkout that
883
+ /// still exists, so the record outlives the folder. Days whose folder is gone
884
+ /// keep their path alone.
885
+ function stampOrigins(days) {
886
+ for (const day of days) {
887
+ for (const holder of [day, ...Object.values(day.providers)]) {
888
+ for (const p of Object.values(holder.projects ?? {})) {
889
+ if (p.originKey || !p.path)
890
+ continue;
891
+ const originKey = projectOriginKey(p.path);
892
+ if (originKey)
893
+ p.originKey = originKey;
894
+ }
895
+ }
896
+ }
897
+ return days;
898
+ }
899
+ export async function saveDailyCache(cache) {
900
+ const dir = getCodeburnCacheDir();
901
+ if (!existsSync(dir))
902
+ await mkdir(dir, { recursive: true });
903
+ const finalPath = getCachePath();
904
+ const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`;
905
+ const payload = JSON.stringify(cache);
906
+ const handle = await open(tempPath, 'w', 0o600);
907
+ try {
908
+ await handle.writeFile(payload, { encoding: 'utf-8' });
909
+ await handle.sync();
910
+ }
911
+ finally {
912
+ await handle.close();
913
+ }
914
+ try {
915
+ await rename(tempPath, finalPath);
916
+ }
917
+ catch (err) {
918
+ try {
919
+ await unlink(tempPath);
920
+ }
921
+ catch { /* ignore */ }
922
+ throw err;
923
+ }
924
+ // Off the hot path and at most once a day: the save is already done.
925
+ await sweepSupersededCacheFiles();
926
+ }
927
+ export function addNewDays(cache, incoming, newestDate) {
928
+ const byDate = new Map(cache.days.map(d => [d.date, d]));
929
+ for (const day of incoming) {
930
+ byDate.set(day.date, day);
931
+ }
932
+ const merged = Array.from(byDate.values()).sort((a, b) => a.date.localeCompare(b.date));
933
+ const nextLast = cache.lastComputedDate && cache.lastComputedDate > newestDate
934
+ ? cache.lastComputedDate
935
+ : newestDate;
936
+ return {
937
+ version: DAILY_CACHE_VERSION,
938
+ savingsConfigHash: cache.savingsConfigHash,
939
+ tzKey: cache.tzKey,
940
+ lastComputedDate: nextLast,
941
+ days: applyRetention(merged, newestDate),
942
+ complete: cache.complete,
943
+ watermarkTrusted: cache.watermarkTrusted,
944
+ };
945
+ }
946
+ /// Prune entries older than the retention window so the cache file does not
947
+ /// grow unbounded over years of daily use. Anchor the cutoff on newestDate so
948
+ /// a stale or stuck clock can't accidentally evict everything. Skip the prune
949
+ /// entirely if newestDate is malformed — an invalid Date would produce a NaN
950
+ /// cutoff and `d.date >= "Invalid Date"` would silently drop every entry.
951
+ function applyRetention(days, newestDate) {
952
+ const cutoffDate = new Date(`${newestDate}T00:00:00Z`);
953
+ if (isNaN(cutoffDate.getTime()))
954
+ return days;
955
+ cutoffDate.setUTCDate(cutoffDate.getUTCDate() - DAILY_CACHE_RETENTION_DAYS);
956
+ const cutoff = toDateString(cutoffDate);
957
+ return days.filter(d => d.date >= cutoff);
958
+ }
959
+ /// Tokens count: a slice with usage but no call or cost (a Hermes session
960
+ /// total) is already in the day's totals, so merging over it as a placeholder
961
+ /// counts it twice.
962
+ function hasSliceData(slice) {
963
+ return slice.cost > 0 || slice.calls > 0 || (slice.savingsUSD ?? 0) > 0 || TOKEN_KEYS.some(k => (slice[k] ?? 0) > 0);
964
+ }
965
+ /// A day from a pre-v5-era cache: day-level totals exist but the providers map
966
+ /// is empty, so nothing can be attributed per provider. Such a day merges
967
+ /// all-or-nothing — filling slices into it would double-count whatever share
968
+ /// of its totals the incoming provider already contributed.
969
+ function isOpaqueDay(day) {
970
+ return (day.cost > 0 || day.calls > 0) && Object.keys(day.providers).length === 0;
971
+ }
972
+ function emptyModelStats() {
973
+ return { calls: 0, cost: 0, savingsUSD: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
974
+ }
975
+ /// Fold one provider's day slice into a day: the providers map, the day-level
976
+ /// totals, and (when the slice carries them — v14+ slices do) the model and
977
+ /// category breakdowns. Skinny slices from pre-v14 caches restore only
978
+ /// cost/calls/savings; the day's other totals simply don't grow. A zero-data
979
+ /// placeholder already present for the provider (a session that started this
980
+ /// day but whose turns all landed on another) only contributes its session
981
+ /// count, deduplicated by max — the same real session may be counted on both
982
+ /// sides.
983
+ /// `residual` marks a slice that came out of the tz subtraction (issue #770):
984
+ /// the subtraction already removed the placeholder's sessions (the ones the
985
+ /// fresh parse explained), so the residual sessions are all distinct from the
986
+ /// placeholder's and must ADD to it, not max-dedup against it. Max would clamp
987
+ /// max(placeholder, residual) and permanently drop the source-gone sessions the
988
+ /// residual still carries.
989
+ function addSliceIntoDay(day, provider, slice, residual = false) {
990
+ // Reads keyed by names from foreign caches use hasOwn throughout: a plain
991
+ // lookup of "__proto__" returns the prototype object, and accumulating into
992
+ // it pollutes every object in the process.
993
+ const placeholder = Object.hasOwn(day.providers, provider) ? day.providers[provider] : undefined;
994
+ const placeholderSessions = placeholder?.sessions ?? 0;
995
+ // A residual over a fresh slice that carries data is content no surviving
996
+ // source explains, so it adds to that slice instead of replacing it.
997
+ const summed = residual && placeholder !== undefined && hasSliceData(placeholder);
998
+ const merged = summed ? addSliceInto(structuredClone(placeholder), slice) : structuredClone(slice);
999
+ if (residual && !summed) {
1000
+ // The subtraction removed the placeholder's sessions from this residual, so
1001
+ // every remaining session is distinct from the placeholder's - add, don't
1002
+ // max (max would clamp 1 + 1 to 1 and lose the source-gone session).
1003
+ merged.sessions = placeholderSessions + (merged.sessions ?? 0);
1004
+ }
1005
+ else if (placeholderSessions > (merged.sessions ?? 0)) {
1006
+ merged.sessions = placeholderSessions;
1007
+ }
1008
+ setOwn(day.providers, provider, merged);
1009
+ day.cost += slice.cost;
1010
+ day.calls += slice.calls;
1011
+ day.savingsUSD += slice.savingsUSD ?? 0;
1012
+ day.sessions += residual ? (slice.sessions ?? 0) : Math.max(0, (slice.sessions ?? 0) - placeholderSessions);
1013
+ day.inputTokens += slice.inputTokens ?? 0;
1014
+ day.outputTokens += slice.outputTokens ?? 0;
1015
+ day.cacheReadTokens += slice.cacheReadTokens ?? 0;
1016
+ day.cacheWriteTokens += slice.cacheWriteTokens ?? 0;
1017
+ day.editTurns += slice.editTurns ?? 0;
1018
+ day.oneShotTurns += slice.oneShotTurns ?? 0;
1019
+ for (const [name, m] of Object.entries(slice.models ?? {})) {
1020
+ const acc = Object.hasOwn(day.models, name) ? day.models[name] : emptyModelStats();
1021
+ acc.calls += m.calls;
1022
+ acc.cost += m.cost;
1023
+ acc.savingsUSD += m.savingsUSD ?? 0;
1024
+ acc.inputTokens += m.inputTokens;
1025
+ acc.outputTokens += m.outputTokens;
1026
+ acc.cacheReadTokens += m.cacheReadTokens;
1027
+ acc.cacheWriteTokens += m.cacheWriteTokens;
1028
+ setOwn(day.models, name, acc);
1029
+ }
1030
+ for (const [cat, c] of Object.entries(slice.categories ?? {})) {
1031
+ const acc = Object.hasOwn(day.categories, cat) ? day.categories[cat] : { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 };
1032
+ acc.turns += c.turns;
1033
+ acc.cost += c.cost;
1034
+ acc.savingsUSD += c.savingsUSD ?? 0;
1035
+ acc.editTurns += c.editTurns;
1036
+ acc.oneShotTurns += c.oneShotTurns;
1037
+ setOwn(day.categories, cat, acc);
1038
+ }
1039
+ const placeholderProjects = placeholder?.projects ?? {};
1040
+ for (const [name, p] of Object.entries(slice.projects ?? {})) {
1041
+ if (!p || typeof p !== 'object' || Array.isArray(p))
1042
+ continue;
1043
+ const dayProjects = (day.projects ??= {});
1044
+ const acc = Object.hasOwn(dayProjects, name) ? dayProjects[name] : { cost: 0, calls: 0, savingsUSD: 0, sessions: 0 };
1045
+ acc.cost += num(p.cost);
1046
+ acc.calls += num(p.calls);
1047
+ acc.savingsUSD += num(p.savingsUSD);
1048
+ if (!acc.path && typeof p.path === 'string')
1049
+ acc.path = p.path;
1050
+ if (!acc.originKey && typeof p.originKey === 'string')
1051
+ acc.originKey = p.originKey;
1052
+ // Same session dedup as the slice-level sessions above: a placeholder's
1053
+ // project sessions were already counted into the day when the fresh day
1054
+ // was built, so only the excess is added.
1055
+ const placeholderProjectSessions = Object.hasOwn(placeholderProjects, name) ? num(placeholderProjects[name]?.sessions) : 0;
1056
+ acc.sessions += residual ? num(p.sessions) : Math.max(0, num(p.sessions) - placeholderProjectSessions);
1057
+ setOwn(dayProjects, name, acc);
1058
+ }
1059
+ if (summed)
1060
+ return;
1061
+ // Placeholder-only projects (session counted fresh, calls landed elsewhere)
1062
+ // survive on the merged slice rather than being dropped by the clone above.
1063
+ const mergedProjects = merged.projects;
1064
+ if (mergedProjects) {
1065
+ for (const [name, p] of Object.entries(placeholderProjects)) {
1066
+ if (!p || typeof p !== 'object')
1067
+ continue;
1068
+ if (Object.hasOwn(mergedProjects, name)) {
1069
+ if (residual) {
1070
+ mergedProjects[name].sessions = num(mergedProjects[name].sessions) + num(p.sessions);
1071
+ }
1072
+ else if (num(p.sessions) > num(mergedProjects[name].sessions)) {
1073
+ mergedProjects[name].sessions = num(p.sessions);
1074
+ }
1075
+ }
1076
+ else {
1077
+ setOwn(mergedProjects, name, { cost: 0, calls: 0, savingsUSD: 0, sessions: num(p.sessions) });
1078
+ }
1079
+ }
1080
+ }
1081
+ else if (placeholder?.projects) {
1082
+ merged.projects = structuredClone(placeholder.projects);
1083
+ }
1084
+ }
1085
+ function addSliceInto(target, add) {
1086
+ for (const key of ['calls', 'cost', 'savingsUSD', 'sessions', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'editTurns', 'oneShotTurns']) {
1087
+ target[key] = (target[key] ?? 0) + (add[key] ?? 0);
1088
+ }
1089
+ for (const [name, m] of Object.entries(add.models ?? {})) {
1090
+ const models = (target.models ??= {});
1091
+ const acc = Object.hasOwn(models, name) ? models[name] : emptyModelStats();
1092
+ for (const key of REMAINDER_KEYS)
1093
+ acc[key] += m[key] ?? 0;
1094
+ setOwn(models, name, acc);
1095
+ }
1096
+ for (const [cat, c] of Object.entries(add.categories ?? {})) {
1097
+ const categories = (target.categories ??= {});
1098
+ const acc = Object.hasOwn(categories, cat) ? categories[cat] : { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 };
1099
+ for (const key of ['turns', 'cost', 'savingsUSD', 'editTurns', 'oneShotTurns'])
1100
+ acc[key] += c[key] ?? 0;
1101
+ setOwn(categories, cat, acc);
1102
+ }
1103
+ for (const [name, p] of Object.entries(add.projects ?? {})) {
1104
+ const projects = (target.projects ??= {});
1105
+ const acc = Object.hasOwn(projects, name) ? projects[name] : { cost: 0, calls: 0, savingsUSD: 0, sessions: 0 };
1106
+ for (const key of ['cost', 'calls', 'savingsUSD', 'sessions'])
1107
+ acc[key] += num(p[key]);
1108
+ if (!acc.path && p.path)
1109
+ acc.path = p.path;
1110
+ if (!acc.originKey && p.originKey)
1111
+ acc.originKey = p.originKey;
1112
+ setOwn(projects, name, acc);
1113
+ }
1114
+ return target;
1115
+ }
1116
+ /// Assign via defineProperty so filesystem-derived keys like "__proto__" become
1117
+ /// ordinary own properties instead of mutating the prototype link.
1118
+ function setOwn(target, key, value) {
1119
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
1120
+ }
1121
+ // --- tz-aware carry subtraction (issue #770) ---------------------------------
1122
+ //
1123
+ // After a timezone change the full re-derive re-aggregates the same session
1124
+ // parse under the CURRENT tz and merges it over the cached (old-tz) days.
1125
+ // mergeDayEntries carries a baseline slice only when the fresh day has no data
1126
+ // slice for that (date, provider), so a turn that re-bucketed across local
1127
+ // midnight leaves its old day sliceless, gets carried there, AND counts again on
1128
+ // its new day. The fix subtracts from each carried baseline slice the content
1129
+ // the fresh parse still attributes to that (date, provider) under the OLD
1130
+ // bucketing (`freshUnderOldTz`): exactly the re-bucketed turns, nothing else.
1131
+ // A sources-gone slice has no such content and survives untouched; a slice fully
1132
+ // explained away is dropped.
1133
+ /// Reduce `base` by `sub` at the slice level, clamping every field at 0 and
1134
+ /// dropping nested entries that reduce to nothing. Returns null when no positive
1135
+ /// data remains; the merge then drops the slice instead of carrying an empty
1136
+ /// one. `sub` is always a subset of `base` in practice (same parse, old bucketing
1137
+ /// vs cached baseline), so the clamp only guards rounding and cache/baseline skew.
1138
+ function subtractSlice(base, sub) {
1139
+ const calls = Math.max(0, base.calls - (sub.calls ?? 0));
1140
+ const cost = Math.max(0, base.cost - (sub.cost ?? 0));
1141
+ const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0));
1142
+ const sessions = Math.max(0, (base.sessions ?? 0) - (sub.sessions ?? 0));
1143
+ const inputTokens = Math.max(0, (base.inputTokens ?? 0) - (sub.inputTokens ?? 0));
1144
+ const outputTokens = Math.max(0, (base.outputTokens ?? 0) - (sub.outputTokens ?? 0));
1145
+ const cacheReadTokens = Math.max(0, (base.cacheReadTokens ?? 0) - (sub.cacheReadTokens ?? 0));
1146
+ const cacheWriteTokens = Math.max(0, (base.cacheWriteTokens ?? 0) - (sub.cacheWriteTokens ?? 0));
1147
+ const editTurns = Math.max(0, (base.editTurns ?? 0) - (sub.editTurns ?? 0));
1148
+ const oneShotTurns = Math.max(0, (base.oneShotTurns ?? 0) - (sub.oneShotTurns ?? 0));
1149
+ const totals = { calls, cost, savingsUSD, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, editTurns, oneShotTurns };
1150
+ const models = capToTotals(subtractModels(base.models, sub.models), totals, REMAINDER_KEYS);
1151
+ const categories = capToTotals(subtractCategories(base.categories, sub.categories), totals, ['cost', 'savingsUSD', 'editTurns', 'oneShotTurns']);
1152
+ const projects = capToTotals(subtractProjects(base.projects, sub.projects), totals, ['cost', 'calls', 'savingsUSD']);
1153
+ const out = {
1154
+ calls, cost, savingsUSD,
1155
+ ...(sessions > 0 ? { sessions } : {}),
1156
+ ...(inputTokens > 0 ? { inputTokens } : {}),
1157
+ ...(outputTokens > 0 ? { outputTokens } : {}),
1158
+ ...(cacheReadTokens > 0 ? { cacheReadTokens } : {}),
1159
+ ...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),
1160
+ ...(editTurns > 0 ? { editTurns } : {}),
1161
+ ...(oneShotTurns > 0 ? { oneShotTurns } : {}),
1162
+ ...(models ? { models } : {}),
1163
+ ...(categories ? { categories } : {}),
1164
+ ...(projects ? { projects } : {}),
1165
+ };
1166
+ // Tokens alone do not keep a remainder: it can be drift between two scans or
1167
+ // usage whose source is gone, and nothing here tells which.
1168
+ return calls > 0 || cost > 0 || savingsUSD > 0 || sessions > 0 ? out : null;
1169
+ }
1170
+ /// Entries are subtracted key by key, so content the fresh parse files under a
1171
+ /// key the base lacks (a pre-v67 label-only project, a project now split per
1172
+ /// worktree, a renamed model) leaves the base's entry whole and the breakdown
1173
+ /// outgrows the residual. Scale each field back to the residual's own total,
1174
+ /// keeping whole counts whole; the old keys are the only identity that content has.
1175
+ function capToTotals(entries, totals, keys) {
1176
+ if (!entries)
1177
+ return undefined;
1178
+ // Untouched entries are still the base's own objects.
1179
+ const rows = Object.entries(entries).map(([name, r]) => {
1180
+ const copy = { ...r };
1181
+ setOwn(entries, name, copy);
1182
+ return copy;
1183
+ });
1184
+ for (const key of keys) {
1185
+ const total = totals[key] ?? 0;
1186
+ const sum = rows.reduce((s, r) => s + num(r[key]), 0);
1187
+ if (sum <= total)
1188
+ continue;
1189
+ for (const r of rows)
1190
+ r[key] = num(r[key]) * total / sum;
1191
+ if (key === 'cost' || key === 'savingsUSD')
1192
+ continue;
1193
+ let left = total;
1194
+ for (const r of rows)
1195
+ left -= (r[key] = Math.floor(r[key]));
1196
+ rows.reduce((a, b) => (b[key] > a[key] ? b : a))[key] += left;
1197
+ }
1198
+ for (const [name, r] of Object.entries(entries)) {
1199
+ if (Object.values(r).every(v => typeof v !== 'number' || v === 0))
1200
+ delete entries[name];
1201
+ }
1202
+ return Object.keys(entries).length > 0 ? entries : undefined;
1203
+ }
1204
+ function subtractModelStats(base, sub) {
1205
+ const calls = Math.max(0, base.calls - (sub.calls ?? 0));
1206
+ const cost = Math.max(0, base.cost - (sub.cost ?? 0));
1207
+ const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0));
1208
+ const inputTokens = Math.max(0, base.inputTokens - (sub.inputTokens ?? 0));
1209
+ const outputTokens = Math.max(0, base.outputTokens - (sub.outputTokens ?? 0));
1210
+ const cacheReadTokens = Math.max(0, base.cacheReadTokens - (sub.cacheReadTokens ?? 0));
1211
+ const cacheWriteTokens = Math.max(0, base.cacheWriteTokens - (sub.cacheWriteTokens ?? 0));
1212
+ if (calls === 0 && cost === 0 && savingsUSD === 0 && inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0)
1213
+ return null;
1214
+ return { calls, cost, savingsUSD, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens };
1215
+ }
1216
+ function subtractModels(base, sub) {
1217
+ if (!base)
1218
+ return undefined;
1219
+ const out = {};
1220
+ for (const [name, stats] of Object.entries(base)) {
1221
+ const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined;
1222
+ const reduced = s ? subtractModelStats(stats, s) : stats;
1223
+ if (reduced)
1224
+ setOwn(out, name, reduced);
1225
+ }
1226
+ return Object.keys(out).length > 0 ? out : undefined;
1227
+ }
1228
+ function subtractCategoryStats(base, sub) {
1229
+ const turns = Math.max(0, base.turns - (sub.turns ?? 0));
1230
+ const cost = Math.max(0, base.cost - (sub.cost ?? 0));
1231
+ const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0));
1232
+ const editTurns = Math.max(0, base.editTurns - (sub.editTurns ?? 0));
1233
+ const oneShotTurns = Math.max(0, base.oneShotTurns - (sub.oneShotTurns ?? 0));
1234
+ if (turns === 0 && cost === 0 && savingsUSD === 0 && editTurns === 0 && oneShotTurns === 0)
1235
+ return null;
1236
+ return { turns, cost, savingsUSD, editTurns, oneShotTurns };
1237
+ }
1238
+ function subtractCategories(base, sub) {
1239
+ if (!base)
1240
+ return undefined;
1241
+ const out = {};
1242
+ for (const [name, stats] of Object.entries(base)) {
1243
+ const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined;
1244
+ const reduced = s ? subtractCategoryStats(stats, s) : stats;
1245
+ if (reduced)
1246
+ setOwn(out, name, reduced);
1247
+ }
1248
+ return Object.keys(out).length > 0 ? out : undefined;
1249
+ }
1250
+ function subtractProjectStats(base, sub) {
1251
+ const cost = Math.max(0, base.cost - (sub.cost ?? 0));
1252
+ const calls = Math.max(0, base.calls - (sub.calls ?? 0));
1253
+ const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0));
1254
+ const sessions = Math.max(0, (base.sessions ?? 0) - (sub.sessions ?? 0));
1255
+ if (cost === 0 && calls === 0 && savingsUSD === 0 && sessions === 0)
1256
+ return null;
1257
+ return { cost, calls, savingsUSD, sessions, ...(base.path ? { path: base.path } : {}), ...(base.originKey ? { originKey: base.originKey } : {}) };
1258
+ }
1259
+ function subtractProjects(base, sub) {
1260
+ if (!base)
1261
+ return undefined;
1262
+ const out = {};
1263
+ for (const [name, stats] of Object.entries(base)) {
1264
+ const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined;
1265
+ const reduced = s ? subtractProjectStats(stats, s) : stats;
1266
+ if (reduced)
1267
+ setOwn(out, name, reduced);
1268
+ }
1269
+ return Object.keys(out).length > 0 ? out : undefined;
1270
+ }
1271
+ /// How much a nested stat entry actually lost: `base` before minus `reduced`
1272
+ /// after, or null when nothing was lost. The raw `sub` is only a lower bound -
1273
+ /// with tz skew it can exceed the slice, and subtracting it would eat OTHER
1274
+ /// providers' share of the day-level breakdown.
1275
+ function modelStatsDelta(base, reduced) {
1276
+ const calls = base.calls - reduced.calls;
1277
+ const cost = base.cost - reduced.cost;
1278
+ const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0);
1279
+ const inputTokens = base.inputTokens - reduced.inputTokens;
1280
+ const outputTokens = base.outputTokens - reduced.outputTokens;
1281
+ const cacheReadTokens = base.cacheReadTokens - reduced.cacheReadTokens;
1282
+ const cacheWriteTokens = base.cacheWriteTokens - reduced.cacheWriteTokens;
1283
+ if (calls === 0 && cost === 0 && savingsUSD === 0 && inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0)
1284
+ return null;
1285
+ return { calls, cost, savingsUSD, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens };
1286
+ }
1287
+ function categoryStatsDelta(base, reduced) {
1288
+ const turns = base.turns - reduced.turns;
1289
+ const cost = base.cost - reduced.cost;
1290
+ const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0);
1291
+ const editTurns = base.editTurns - reduced.editTurns;
1292
+ const oneShotTurns = base.oneShotTurns - reduced.oneShotTurns;
1293
+ if (turns === 0 && cost === 0 && savingsUSD === 0 && editTurns === 0 && oneShotTurns === 0)
1294
+ return null;
1295
+ return { turns, cost, savingsUSD, editTurns, oneShotTurns };
1296
+ }
1297
+ function projectStatsDelta(base, reduced) {
1298
+ const cost = base.cost - reduced.cost;
1299
+ const calls = base.calls - reduced.calls;
1300
+ const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0);
1301
+ const sessions = (base.sessions ?? 0) - (reduced.sessions ?? 0);
1302
+ if (cost === 0 && calls === 0 && savingsUSD === 0 && sessions === 0)
1303
+ return null;
1304
+ return { cost, calls, savingsUSD, sessions };
1305
+ }
1306
+ /// Remove `sub`'s contribution from a carried baseline day (the baseline-only
1307
+ /// date branch of the merge, where the whole day clones over). Reduces the
1308
+ /// provider's slice, the day-level totals, and the day-level models/categories/
1309
+ /// projects maps that `addSliceIntoDay` would have grown them by.
1310
+ ///
1311
+ /// Every day-level subtraction uses the EFFECTIVE removal - what the provider
1312
+ /// slice actually lost (current before minus reduced after) - not the raw `sub`.
1313
+ /// With tz skew (`freshUnderOldTz` content larger than the baseline slice), the
1314
+ /// raw sub exceeds the slice and subtracting it would over-remove the day's
1315
+ /// totals and its nested maps, eating unrelated providers' carried history and
1316
+ /// breaking the invariant that a day's totals sum to its slices. A provider
1317
+ /// slice that was absent has an effective removal of zero: nothing is subtracted
1318
+ /// from the day.
1319
+ function subtractSliceFromDay(day, provider, sub) {
1320
+ const current = Object.hasOwn(day.providers, provider) ? day.providers[provider] : undefined;
1321
+ if (!current)
1322
+ return;
1323
+ const reduced = subtractSlice(current, sub);
1324
+ if (reduced)
1325
+ setOwn(day.providers, provider, reduced);
1326
+ else
1327
+ delete day.providers[provider];
1328
+ day.cost = Math.max(0, day.cost - (current.cost - (reduced?.cost ?? 0)));
1329
+ day.calls = Math.max(0, day.calls - (current.calls - (reduced?.calls ?? 0)));
1330
+ day.savingsUSD = Math.max(0, (day.savingsUSD ?? 0) - ((current.savingsUSD ?? 0) - (reduced?.savingsUSD ?? 0)));
1331
+ day.sessions = Math.max(0, day.sessions - ((current.sessions ?? 0) - (reduced?.sessions ?? 0)));
1332
+ day.inputTokens = Math.max(0, day.inputTokens - ((current.inputTokens ?? 0) - (reduced?.inputTokens ?? 0)));
1333
+ day.outputTokens = Math.max(0, day.outputTokens - ((current.outputTokens ?? 0) - (reduced?.outputTokens ?? 0)));
1334
+ day.cacheReadTokens = Math.max(0, day.cacheReadTokens - ((current.cacheReadTokens ?? 0) - (reduced?.cacheReadTokens ?? 0)));
1335
+ day.cacheWriteTokens = Math.max(0, day.cacheWriteTokens - ((current.cacheWriteTokens ?? 0) - (reduced?.cacheWriteTokens ?? 0)));
1336
+ day.editTurns = Math.max(0, day.editTurns - ((current.editTurns ?? 0) - (reduced?.editTurns ?? 0)));
1337
+ day.oneShotTurns = Math.max(0, day.oneShotTurns - ((current.oneShotTurns ?? 0) - (reduced?.oneShotTurns ?? 0)));
1338
+ for (const [name, m] of Object.entries(current.models ?? {})) {
1339
+ const rm = reduced?.models && Object.hasOwn(reduced.models, name) ? reduced.models[name] : undefined;
1340
+ const removed = rm ? modelStatsDelta(m, rm) : m;
1341
+ if (!removed)
1342
+ continue;
1343
+ const acc = Object.hasOwn(day.models, name) ? day.models[name] : undefined;
1344
+ if (!acc)
1345
+ continue;
1346
+ const reducedM = subtractModelStats(acc, removed);
1347
+ if (reducedM)
1348
+ setOwn(day.models, name, reducedM);
1349
+ else
1350
+ delete day.models[name];
1351
+ }
1352
+ for (const [cat, c] of Object.entries(current.categories ?? {})) {
1353
+ const rc = reduced?.categories && Object.hasOwn(reduced.categories, cat) ? reduced.categories[cat] : undefined;
1354
+ const removed = rc ? categoryStatsDelta(c, rc) : c;
1355
+ if (!removed)
1356
+ continue;
1357
+ const acc = Object.hasOwn(day.categories, cat) ? day.categories[cat] : undefined;
1358
+ if (!acc)
1359
+ continue;
1360
+ const reducedC = subtractCategoryStats(acc, removed);
1361
+ if (reducedC)
1362
+ setOwn(day.categories, cat, reducedC);
1363
+ else
1364
+ delete day.categories[cat];
1365
+ }
1366
+ if (!day.projects)
1367
+ return;
1368
+ for (const [name, p] of Object.entries(current.projects ?? {})) {
1369
+ const rp = reduced?.projects && Object.hasOwn(reduced.projects, name) ? reduced.projects[name] : undefined;
1370
+ const removed = rp ? projectStatsDelta(p, rp) : p;
1371
+ if (!removed)
1372
+ continue;
1373
+ const acc = Object.hasOwn(day.projects, name) ? day.projects[name] : undefined;
1374
+ if (!acc)
1375
+ continue;
1376
+ const reducedP = subtractProjectStats(acc, removed);
1377
+ if (reducedP)
1378
+ setOwn(day.projects, name, reducedP);
1379
+ else
1380
+ delete day.projects[name];
1381
+ }
1382
+ }
1383
+ /// A Cursor usage import stands in for the replaced providers on the days it
1384
+ /// covers, and the parse drops their local calls there. A cached slice of one
1385
+ /// of them on such a day is an old local estimate no parse produces again, so
1386
+ /// merging it would stack it on the imported rows. Days before the backfill
1387
+ /// window stay: the re-derive cannot rebuild their imported rows.
1388
+ async function withoutImportReplacedSlices(days) {
1389
+ const coverage = await loadCursorImport().then(s => s && coverageFor(s), () => null);
1390
+ if (!coverage)
1391
+ return days;
1392
+ const now = new Date();
1393
+ const backfillStart = toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - BACKFILL_DAYS));
1394
+ return days.flatMap(day => {
1395
+ const replaced = Object.keys(day.providers).filter(p => coverage.providers.has(p));
1396
+ if (replaced.length === 0 || day.date < backfillStart || !coversLocalDay(coverage, day.date))
1397
+ return [day];
1398
+ const copy = structuredClone(day);
1399
+ for (const provider of replaced)
1400
+ subtractSliceFromDay(copy, provider, copy.providers[provider]);
1401
+ return hasPositiveDayContent(copy) ? [copy] : [];
1402
+ });
1403
+ }
1404
+ /// Did the tz subtraction leave any positive data on a carried baseline day?
1405
+ /// Mirrors the merge's own carry criterion (`hasSliceData` or sessions) at the
1406
+ /// day level, extended to the day's other scalar and nested content.
1407
+ function hasPositiveDayContent(day) {
1408
+ if (day.cost > 0 || day.calls > 0 || (day.savingsUSD ?? 0) > 0 || day.sessions > 0)
1409
+ return true;
1410
+ if (day.inputTokens > 0 || day.outputTokens > 0 || day.cacheReadTokens > 0 || day.cacheWriteTokens > 0)
1411
+ return true;
1412
+ if (day.editTurns > 0 || day.oneShotTurns > 0)
1413
+ return true;
1414
+ if (Object.keys(day.providers).length > 0)
1415
+ return true;
1416
+ if (Object.keys(day.models).length > 0 || Object.keys(day.categories).length > 0)
1417
+ return true;
1418
+ if (day.projects && Object.keys(day.projects).length > 0)
1419
+ return true;
1420
+ return false;
1421
+ }
1422
+ /// PARTIAL SURVIVAL (the v14 never-lose contract, extended past all-or-nothing).
1423
+ /// v14 protected a (date, provider) slice only when the fresh derivation found
1424
+ /// NOTHING there. But transcripts age out per FILE, not per day: Claude Code
1425
+ /// deletes them after ~30 days, and turn-anchored bucketing means a handful of
1426
+ /// turns from surviving later files still land on a mostly-aged-out day. The
1427
+ /// fresh slice is then non-empty but truncated, and replacing the baseline with
1428
+ /// it silently deletes the rest (measured on a real cache upgrading 17 -> 19:
1429
+ /// 2026-07-16 fell from $1,685.17 / 12,530 calls to $385.44 / 560 calls).
1430
+ ///
1431
+ /// So a fresh slice replaces a settled baseline slice only when it carries at
1432
+ /// least as many CALLS — the same or more evidence. Fewer calls means the
1433
+ /// source set demonstrably lost data, and the baseline is kept whole.
1434
+ ///
1435
+ /// Why calls and not sessions: session counts shrink routinely on days whose
1436
+ /// sources are entirely intact (a session's turns re-attribute to a neighbouring
1437
+ /// day), measured at 1-5 sessions on recent days whose call counts were
1438
+ /// identical across the re-derivation. A sessions test would freeze stale slices
1439
+ /// on healthy days. Why not cost/tokens: those are re-priced accounting on the
1440
+ /// same evidence — exactly what a legitimate re-derivation changes (#1015 Grok
1441
+ /// keeps its per-day calls and raises cost, and is unaffected by this guard).
1442
+ ///
1443
+ /// Why no source-set test instead: a day entry records no source files, counts
1444
+ /// or fingerprints, and the session cache is keyed by file rather than by day,
1445
+ /// so "were this day's sources all present?" cannot be answered from the cache.
1446
+ /// The calls comparison is the available proxy.
1447
+ ///
1448
+ /// TRADE-OFF: a future fix that legitimately REDUCES calls on a settled day
1449
+ /// (deduplication) is blocked, and that day keeps the older, higher value until
1450
+ /// its slice is re-derived under an equal-or-greater call count. That is the
1451
+ /// "estimate high, never lose" direction v14 already chose over silent loss.
1452
+ ///
1453
+ /// Recent days stay authoritative: within the settle window their session files
1454
+ /// are still on disk, so a shrink there is a real change (the user deleted a
1455
+ /// transcript), not aged-out sources. Seven days is far inside the ~30-day
1456
+ /// retention floor of the shortest-lived source we know of, so any shrink older
1457
+ /// than that is source loss with overwhelming likelihood.
1458
+ const SETTLE_DAYS = 7;
1459
+ function settleCutoffDate(now) {
1460
+ return toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - SETTLE_DAYS));
1461
+ }
1462
+ function isPartialSurvival(date, baseline, fresh, settleCutoff) {
1463
+ return date < settleCutoff && fresh.calls < baseline.calls;
1464
+ }
1465
+ /// The read path's rule: keep whichever derivation explains MORE calls, on
1466
+ /// every date, with ties going to the baseline. Unlike the write path this is
1467
+ /// not deciding what to freeze, so it has no reason to prefer a thinner slice
1468
+ /// on a recent day — but it is also not the place a re-pricing lands, so an
1469
+ /// equal-call slice leaves the durable value alone.
1470
+ function baselineExplainsMore(baseline, fresh) {
1471
+ return fresh.calls <= baseline.calls;
1472
+ }
1473
+ /// Index `freshUnderOldTz` (the same parse re-aggregated under the cache's OLD
1474
+ /// tzKey) by date then provider, so the merge can subtract exactly what the
1475
+ /// fresh parse still explains under the old bucketing.
1476
+ function buildTzSubtraction(days) {
1477
+ const byDate = new Map();
1478
+ for (const day of days) {
1479
+ if (Object.keys(day.providers).length === 0)
1480
+ continue;
1481
+ const byProvider = new Map();
1482
+ for (const [provider, slice] of Object.entries(day.providers)) {
1483
+ byProvider.set(provider, slice);
1484
+ }
1485
+ byDate.set(day.date, byProvider);
1486
+ }
1487
+ return byDate;
1488
+ }
1489
+ /// Merge two day lists per (date, provider): `primary` wins wherever both have
1490
+ /// data; `secondary` only fills dates primary lacks entirely and provider
1491
+ /// slices primary lacks on shared dates. Nothing in secondary can overwrite or
1492
+ /// double into primary. With markSecondaryCarried, every day that received a
1493
+ /// secondary contribution is flagged `carried`.
1494
+ ///
1495
+ /// Days that cannot be attributed per provider merge all-or-nothing:
1496
+ /// - an OPAQUE primary day (pre-v5-era: totals but empty providers map) is
1497
+ /// never slice-filled — its totals may already contain the incoming
1498
+ /// provider's share, so adding would double-count;
1499
+ /// - an opaque secondary day on a date primary already has contributes
1500
+ /// nothing — its day-level totals cannot be attributed without slices.
1501
+ /// A primary slice blocks a secondary one only when it carries DATA; a
1502
+ /// zero-data placeholder (sessions only) is merged into, not treated as a
1503
+ /// re-derivation of the provider's day — UNLESS that data is a strict shrink of
1504
+ /// the baseline on a settled day, see `isPartialSurvival`.
1505
+ /// `subtract`, present ONLY on the tz-change re-derive, maps (date, provider)
1506
+ /// to the content the fresh parse still attributes there under the OLD
1507
+ /// bucketing. Every baseline slice the merge would otherwise carry has that
1508
+ /// content subtracted first (clamped at 0, dropped when nothing positive
1509
+ /// remains), so turns that re-bucketed across local midnight are not counted on
1510
+ /// both their old and new days. What remains is by construction content NO
1511
+ /// surviving source explains, so it is added even when the fresh slice for that
1512
+ /// (date, provider) already carries data — the tz path's form of the
1513
+ /// partial-survival rule, exact instead of heuristic. Absent (undefined) on
1514
+ /// every other path, which keeps those merges byte-identical to the pre-fix
1515
+ /// behavior apart from that rule.
1516
+ export function mergeDayEntries(primary, secondary, markSecondaryCarried, subtract,
1517
+ /// Set ONLY by the complete-parse re-derive, where `primary` is a fresh
1518
+ /// derivation from live sources and `secondary` is the cache baseline: a
1519
+ /// primary slice with fewer calls there means sources aged out, so the
1520
+ /// baseline wins on settled days (`isPartialSurvival`). The adoption union
1521
+ /// leaves it off - both sides are cache generations there and the newer
1522
+ /// schema deliberately wins per (date, provider).
1523
+ ///
1524
+ /// `'prefer-richer'` is the read-path union's rule (`unionDaysForPeriod`):
1525
+ /// on EVERY date, keep the slice explaining more calls, ties to the baseline.
1526
+ /// That path is choosing what to REPORT, not what to freeze, so a thinner
1527
+ /// derivation is never the better answer there — while the write path still
1528
+ /// lets a recent day shrink, on the grounds that a still-settling day is
1529
+ /// defined by its fresh parse.
1530
+ guardPartialSurvival = false,
1531
+ /// Providers whose baseline slices were recorded under an accounting where a
1532
+ /// call meant something else, so a shrink is not evidence of source loss for
1533
+ /// this one re-derivation (see PENDING_REDERIVE_PROVIDER_VERSIONS). Only consulted
1534
+ /// where the fresh parse actually produced a slice for the (date, provider);
1535
+ /// a slice it could not produce at all is carried by the branch above,
1536
+ /// exactly as before.
1537
+ pendingRederive,
1538
+ /// Days before this date count as settled for the guard even inside the
1539
+ /// settle window: the gap path passes its first unsealed day, so a day it
1540
+ /// re-derives after sealing it before can grow or re-price but never shrink.
1541
+ sealedBefore) {
1542
+ const byDate = new Map();
1543
+ const windowCutoff = settleCutoffDate(new Date());
1544
+ const settleCutoff = sealedBefore && sealedBefore > windowCutoff ? sealedBefore : windowCutoff;
1545
+ for (const day of primary)
1546
+ byDate.set(day.date, structuredClone(day));
1547
+ for (const day of secondary) {
1548
+ const existing = byDate.get(day.date);
1549
+ if (!existing) {
1550
+ const copy = structuredClone(day);
1551
+ if (subtract) {
1552
+ const subForDate = subtract.get(day.date);
1553
+ if (subForDate) {
1554
+ for (const [provider, slice] of Object.entries(copy.providers)) {
1555
+ const subSlice = subForDate.get(provider);
1556
+ if (!subSlice)
1557
+ continue;
1558
+ subtractSliceFromDay(copy, provider, subSlice);
1559
+ }
1560
+ if (!hasPositiveDayContent(copy))
1561
+ continue;
1562
+ }
1563
+ }
1564
+ if (markSecondaryCarried)
1565
+ copy.carried = true;
1566
+ byDate.set(day.date, copy);
1567
+ continue;
1568
+ }
1569
+ if (isOpaqueDay(existing))
1570
+ continue;
1571
+ for (const [provider, slice] of Object.entries(day.providers)) {
1572
+ // Sessions-only slices (a session whose calls all landed on another
1573
+ // day) still carry a real session count — worth preserving.
1574
+ if (!hasSliceData(slice) && !(slice.sessions ?? 0))
1575
+ continue;
1576
+ const existingSlice = Object.hasOwn(existing.providers, provider) ? existing.providers[provider] : undefined;
1577
+ let toAdd = slice;
1578
+ let residual = false;
1579
+ if (subtract) {
1580
+ const subSlice = subtract.get(day.date)?.get(provider);
1581
+ if (subSlice) {
1582
+ const reduced = subtractSlice(slice, subSlice);
1583
+ if (!reduced)
1584
+ continue;
1585
+ toAdd = reduced;
1586
+ // The subtraction already removed the sessions the fresh parse
1587
+ // explained, so the residual's sessions are distinct from the fresh
1588
+ // placeholder's: merging over it must ADD, not max-dedup (fix round
1589
+ // 1 - max would drop the source-gone sessions the residual carries).
1590
+ residual = true;
1591
+ }
1592
+ }
1593
+ if (existingSlice && hasSliceData(existingSlice) && !residual) {
1594
+ const keepBaseline = guardPartialSurvival === 'prefer-richer'
1595
+ ? baselineExplainsMore(slice, existingSlice)
1596
+ : isPartialSurvival(day.date, slice, existingSlice, settleCutoff);
1597
+ if (!guardPartialSurvival || pendingRederive?.has(provider) || !keepBaseline)
1598
+ continue;
1599
+ // The baseline holds more evidence than the sources can still produce:
1600
+ // swap the fresh slice back out for it (inverse of addSliceIntoDay, so
1601
+ // the day's totals and nested maps stay reconciled with its slices).
1602
+ subtractSliceFromDay(existing, provider, existingSlice);
1603
+ }
1604
+ addSliceIntoDay(existing, provider, toAdd, residual);
1605
+ // The result day is seeded from `primary`, which has no provenance, so a
1606
+ // secondary day already marked carried would silently lose the mark on
1607
+ // every date both sides hold. Re-assert it only where this slice brought
1608
+ // calls the primary could not produce — that is what "preserved from
1609
+ // expired session logs" claims. An equal-call slice claims nothing.
1610
+ if (markSecondaryCarried || (day.carried && slice.calls > (existingSlice?.calls ?? 0)))
1611
+ existing.carried = true;
1612
+ }
1613
+ }
1614
+ return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));
1615
+ }
1616
+ /// Forget the given providers' slices on the local days `start`..`end` and pull
1617
+ /// the watermark back before them, so the next hydration re-derives those days
1618
+ /// from sources. For a provider whose data changed on settled days by the
1619
+ /// user's own hand (a usage import added or removed), which the partial-
1620
+ /// survival guard would otherwise read as sources aging out and keep the old
1621
+ /// slices over.
1622
+ export async function invalidateProviderDays(providers, start, end) {
1623
+ await withDailyCacheLock(async () => {
1624
+ const c = await loadDailyCache();
1625
+ for (const day of c.days) {
1626
+ if (day.date < start || day.date > end)
1627
+ continue;
1628
+ for (const provider of providers) {
1629
+ if (Object.hasOwn(day.providers, provider))
1630
+ subtractSliceFromDay(day, provider, day.providers[provider]);
1631
+ }
1632
+ }
1633
+ const before = toDateString(new Date(Number(start.slice(0, 4)), Number(start.slice(5, 7)) - 1, Number(start.slice(8, 10)) - 1));
1634
+ const lastComputedDate = c.lastComputedDate !== null && c.lastComputedDate > before ? before : c.lastComputedDate;
1635
+ await saveDailyCache({ ...c, days: c.days.filter(hasPositiveDayContent), lastComputedDate });
1636
+ });
1637
+ }
1638
+ export function getDaysInRange(cache, start, end) {
1639
+ return cache.days.filter(d => d.date >= start && d.date <= end);
1640
+ }
1641
+ function phantomAmountBucket(cost) {
1642
+ if (cost < 1)
1643
+ return '<$1';
1644
+ if (cost < 10)
1645
+ return '$1-10';
1646
+ if (cost < 100)
1647
+ return '$10-100';
1648
+ if (cost < 1000)
1649
+ return '$100-1000';
1650
+ return '>$1000';
1651
+ }
1652
+ /// DETECTION-ONLY tripwire for the "phantom spend" anomaly: a rare, non-repro
1653
+ /// over-count that attributed cost/calls to days with ZERO underlying source
1654
+ /// records. Pure observer — never changes a day, a total, or any output; it only
1655
+ /// warns (at most once per run). A non-carried day is expected to be backed by a
1656
+ /// fresh source record for its date; a carried/preserved day legitimately has
1657
+ /// spend with no live records (its session files expired), so it is never
1658
+ /// suspect. `datesWithSourceRecords` is the set of dates the fresh parse
1659
+ /// actually produced records for (a date is in it iff it had >=1 record).
1660
+ export function detectPhantomSpend(days, datesWithSourceRecords, warn = message => console.warn(message)) {
1661
+ for (const day of days) {
1662
+ if (day.carried === true)
1663
+ continue;
1664
+ if (day.cost <= 0 && day.calls <= 0)
1665
+ continue;
1666
+ if (datesWithSourceRecords.has(day.date))
1667
+ continue;
1668
+ warn(`codeburn: phantom-spend guard tripped — ${day.date} has spend without source records (${phantomAmountBucket(day.cost)}); totals unchanged, please report`);
1669
+ return;
1670
+ }
1671
+ }
1672
+ let lockChain = Promise.resolve();
1673
+ export function withDailyCacheLock(fn) {
1674
+ const next = lockChain.then(() => fn());
1675
+ lockChain = next.catch(() => undefined);
1676
+ return next;
1677
+ }
1678
+ export const MS_PER_DAY = 24 * 60 * 60 * 1000;
1679
+ export const BACKFILL_DAYS = 365;
1680
+ // Ten years. This cache is the ONLY durable record of carried days (their
1681
+ // session files are long deleted), and the uncapped `lifetime` period reads
1682
+ // from it via buildDurablePeriod, so pruning at the old 2-year mark would
1683
+ // have replayed the lost-history bug in slow motion at that horizon.
1684
+ // Measured envelope keeps this honest: ~2.3 MB / ~11 ms JSON parse per 730
1685
+ // days of fully dense data, so even a decade of daily use stays ~11 MB and
1686
+ // well under 100 ms on the polling path.
1687
+ export const DAILY_CACHE_RETENTION_DAYS = 3650;
1688
+ export function toDateString(date) {
1689
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
1690
+ }
1691
+ /// A day whose ONLY content is turn-anchored residue (one straddling turn's
1692
+ /// category/edit counts, no calls) is not a derived day — it is a day the parse
1693
+ /// under-read. Re-derive it instead of serving it.
1694
+ export function isTurnResidueOnly(day) {
1695
+ if (day.cost > 0 || day.calls > 0 || day.sessions > 0)
1696
+ return false;
1697
+ if (day.inputTokens + day.outputTokens + day.cacheReadTokens + day.cacheWriteTokens > 0)
1698
+ return false;
1699
+ return Object.values(day.categories).some(c => c.turns > 0);
1700
+ }
1701
+ /// Keep only the days a RANGED parse actually covered (issue #1130): a turn
1702
+ /// anchored before the range start survives range slicing whole, so the
1703
+ /// aggregator can emit a residue day outside the parsed range — and out-of-range
1704
+ /// residue days must not reach durable history even with the merge guards.
1705
+ /// Date keys are zero-padded YYYY-MM-DD, so a string compare is exact.
1706
+ export function daysInRange(days, range, dateKeyFn = toDateString) {
1707
+ const first = dateKeyFn(range.start);
1708
+ const last = dateKeyFn(range.end);
1709
+ return days.filter(d => d.date >= first && d.date <= last);
1710
+ }
1711
+ export async function ensureCacheHydrated(parseSessions, aggregateDays,
1712
+ /// Hash of the active `localModelSavings` config. When this changes
1713
+ /// (user re-mapped a baseline) the cached `savingsUSD` totals are no
1714
+ /// longer accurate, so we treat the cache as stale and force a full
1715
+ /// re-hydration. Pass `''` for "no savings config" to disable.
1716
+ savingsConfigHash = '',
1717
+ /// Whether the session parse that fed this backfill left the session cache
1718
+ /// fully hydrated. A partial (interrupted) session cache yields empty/partial
1719
+ /// older days; finalizing them would freeze that gap into the daily history.
1720
+ /// So the backfill is only marked `complete` when this returns true. Defaults
1721
+ /// to a trusting `true` for callers that don't (or can't) supply it.
1722
+ sessionComplete = () => true,
1723
+ /// Re-aggregate the SAME parsed projects under an explicit timezone instead of
1724
+ /// the machine's local one. Used only on a tz-change re-derive: the result is
1725
+ /// compared against the fresh local-tz days to subtract the turns that
1726
+ /// re-bucketed across local midnight from the carried baseline (issue #770).
1727
+ /// Absent, the tz-change path carries forward exactly as it did before.
1728
+ aggregateDaysInTz) {
1729
+ const now = new Date();
1730
+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1731
+ const yesterdayEnd = new Date(todayStart.getTime() - 1);
1732
+ const yesterdayStr = toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
1733
+ return withDailyCacheLock(async () => {
1734
+ let c = await loadDailyCache();
1735
+ // Drop any cached entry dated today or later BEFORE anything else can
1736
+ // carry it forward. The cache only ever stores complete past days (up to
1737
+ // yesterday), so a >= today entry can only come from the clock moving
1738
+ // backward or a stale older cache; left in place it would be served frozen
1739
+ // instead of recomputed live. Yesterday and earlier stay cached.
1740
+ const todayStr = toDateString(now);
1741
+ if (c.days.some(d => d.date >= todayStr)) {
1742
+ const freshDays = c.days.filter(d => d.date < todayStr);
1743
+ const latestFresh = freshDays.length > 0 ? freshDays[freshDays.length - 1].date : null;
1744
+ c = { ...c, days: freshDays, lastComputedDate: latestFresh };
1745
+ }
1746
+ // A cache can claim `complete` while its watermark points PAST its newest
1747
+ // populated day — what a run finalizing off a degraded (read-only) parse
1748
+ // leaves behind: it advanced lastComputedDate over days the parse never
1749
+ // covered. Since gapStart is lastComputedDate + 1, that hole is invisible
1750
+ // to the gap logic forever. Trust the DATA over the marker: pull the
1751
+ // watermark back to the newest day actually present so the ordinary gap
1752
+ // parse re-derives the tail. Nothing is dropped — the cached days all stay.
1753
+ //
1754
+ // Only UNSTAMPED caches are distrusted here. A degraded parse can no longer
1755
+ // set `complete` (that is this fix), so the corrupt state can only be
1756
+ // written by pre-fix code: an unstamped cache. A stamped one whose watermark
1757
+ // outruns its newest day is a legitimately idle tail (recent days had no
1758
+ // activity), and re-deriving that empty tail on every launch is the
1759
+ // regression this guard avoids. A cache with NO days is exempt: it has no
1760
+ // newest day to trust, and a machine with no history at all must still be
1761
+ // able to finalize (below) rather than re-backfill on every launch.
1762
+ const newestCachedDate = c.days.reduce((max, d) => (max === null || d.date > max ? d.date : max), null);
1763
+ if (c.watermarkTrusted !== true && newestCachedDate !== null && c.lastComputedDate !== null && c.lastComputedDate > newestCachedDate) {
1764
+ c = { ...c, lastComputedDate: newestCachedDate };
1765
+ }
1766
+ // Never seal a residue-only day (issue #1127): a day whose only content is
1767
+ // turn-anchored residue was under-read by the parse that produced it, so
1768
+ // trust the DATA over the marker again — pull the watermark back to just
1769
+ // before the oldest such day and let the ordinary gap parse re-derive it.
1770
+ // This is what heals every already-broken cache on the next launch, with
1771
+ // no version bump.
1772
+ //
1773
+ // Caveat: a day that GENUINELY held only one straddling turn and no other
1774
+ // activity re-derives to the same residue shape and would be re-parsed on
1775
+ // every launch. Bound that cost: skip the pull-back when the residue day
1776
+ // is the oldest day in the cache, and only pull back inside the settle
1777
+ // window — outside it the source files are gone and re-deriving cannot
1778
+ // recover the day anyway.
1779
+ const oldestCachedDate = c.days.reduce((min, d) => (min === null || d.date < min ? d.date : min), null);
1780
+ const residueSettleCutoff = settleCutoffDate(now);
1781
+ const oldestResidueDate = c.days.reduce((min, d) => (d.date >= residueSettleCutoff && d.date !== oldestCachedDate && isTurnResidueOnly(d) && (min === null || d.date < min) ? d.date : min), null);
1782
+ if (oldestResidueDate !== null && c.lastComputedDate !== null && c.lastComputedDate >= oldestResidueDate) {
1783
+ const pulledBack = new Date(parseInt(oldestResidueDate.slice(0, 4)), parseInt(oldestResidueDate.slice(5, 7)) - 1, parseInt(oldestResidueDate.slice(8, 10)) - 1);
1784
+ c = { ...c, lastComputedDate: toDateString(pulledBack) };
1785
+ }
1786
+ // Three reasons to re-derive the whole retention window:
1787
+ // 1. Savings config changed — cached `savingsUSD` totals are stale.
1788
+ // 2. The cache was never finalized against a COMPLETE session parse (an old
1789
+ // pre-marker cache, an adoption from older cache files, or one frozen
1790
+ // from a partial/interrupted hydration).
1791
+ // 3. The local timezone changed — days are bucketed by local midnight, so a
1792
+ // TZ change mis-buckets every cached day. Only invalidate when a tzKey is
1793
+ // present and differs (a cache written before this field, or a test
1794
+ // fixture, has none → left alone rather than force a spurious rebuild).
1795
+ //
1796
+ // Re-derive, NOT discard. Session files are ephemeral; a cached day whose
1797
+ // sources are gone exists nowhere else, so the old days stay as a baseline
1798
+ // and the fresh parse overrides per (day, provider) wherever it actually
1799
+ // produced data. What it could not re-derive is carried forward (marked
1800
+ // `carried`) with its old accounting — every wipe here before v14 turned
1801
+ // into permanently lost history.
1802
+ const tzKey = currentTzKey();
1803
+ const tzChanged = c.tzKey !== undefined && c.tzKey !== tzKey;
1804
+ if (c.savingsConfigHash !== savingsConfigHash || c.complete !== true || tzChanged) {
1805
+ const baseline = c.days;
1806
+ const priorWatermark = c.lastComputedDate;
1807
+ const backfillStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - BACKFILL_DAYS);
1808
+ let freshDays = [];
1809
+ let projects = [];
1810
+ if (backfillStart.getTime() <= yesterdayEnd.getTime()) {
1811
+ // Hoisted so a tz-change re-derive can aggregate the SAME parse twice
1812
+ // (once under the current tz as freshDays, once under the cache's old
1813
+ // tzKey as freshUnderOldTz) without a second session parse.
1814
+ //
1815
+ // The parse stops at yesterdayEnd. Keeping it a HISTORY parse is what
1816
+ // makes the parser slice a midnight-straddling turn at the yesterday
1817
+ // boundary: day-N's turn-level category/counts then carry only the
1818
+ // pre-midnight half and today's live parse carries the rest, so the two
1819
+ // sides reconcile (issue #852). Widening THIS parse through now would
1820
+ // leave the full turn on day N while today's half was excluded from the
1821
+ // cache, breaking that reconciliation - so the subtraction below gets
1822
+ // its own through-now parse instead.
1823
+ projects = await parseSessions({ start: backfillStart, end: yesterdayEnd });
1824
+ freshDays = daysInRange(aggregateDays(projects), { start: backfillStart, end: yesterdayEnd });
1825
+ }
1826
+ const parseWasComplete = sessionComplete();
1827
+ // A PARTIAL parse must not overwrite finalized baseline days with
1828
+ // undercounts (if their sources die before the next complete parse, the
1829
+ // undercount would be what survives). Partial fresh data only fills days
1830
+ // and slices the baseline lacks; the next complete parse gets to win.
1831
+ //
1832
+ // On a complete-parse TZ re-derive (savings config untouched), subtract
1833
+ // from each carried baseline slice the content the fresh parse still
1834
+ // attributes to that (date, provider) under the OLD bucketing: the turns
1835
+ // that re-bucketed across local midnight. That is the issue #770
1836
+ // double-count. Re-pricing drift (a savings-hash change) must never be
1837
+ // subtracted, so with a hash change in the same re-derive every baseline
1838
+ // slice a surviving source touches under the old bucketing is dropped
1839
+ // whole and the fresh parse wins there: a tz change must never inflate,
1840
+ // even if that loses the source-gone part of a partly surviving slice.
1841
+ let tzSubtraction;
1842
+ let carriedBaseline = baseline;
1843
+ if (parseWasComplete && tzChanged && aggregateDaysInTz && c.tzKey !== undefined) {
1844
+ // The subtraction re-parses THROUGH NOW (fix round 1): a call bucketed
1845
+ // to OLD-tz yesterday that re-buckets to NEW-tz TODAY sits past the
1846
+ // history parse's yesterdayEnd, so `freshUnderOldTz` built from `projects`
1847
+ // would never see it - the baseline slice would be carried un-subtracted
1848
+ // while today's live parse counts it again. This second parse exists
1849
+ // ONLY for the subtraction; it never feeds freshDays, so the merged
1850
+ // days written to the cache stay exactly the history days and today is
1851
+ // still owned by the caller's live parse.
1852
+ const wideProjects = await parseSessions({ start: backfillStart, end: now });
1853
+ const freshUnderOldTz = buildTzSubtraction(aggregateDaysInTz(wideProjects, c.tzKey));
1854
+ if (c.savingsConfigHash === savingsConfigHash) {
1855
+ tzSubtraction = freshUnderOldTz;
1856
+ }
1857
+ else {
1858
+ carriedBaseline = structuredClone(baseline);
1859
+ for (const day of carriedBaseline) {
1860
+ for (const [provider, slice] of Object.entries(day.providers)) {
1861
+ const explained = freshUnderOldTz.get(day.date)?.get(provider);
1862
+ if (explained && hasSliceData(explained))
1863
+ subtractSliceFromDay(day, provider, slice);
1864
+ }
1865
+ }
1866
+ carriedBaseline = carriedBaseline.filter(hasPositiveDayContent);
1867
+ }
1868
+ }
1869
+ const pendingRederive = c.pendingRederive?.length ? new Set(c.pendingRederive) : undefined;
1870
+ const freshProviders = new Map(freshDays.map(d => [d.date, d.providers]));
1871
+ // v73 moved Cursor IDE chat transcripts from cursor-agent to cursor. A day
1872
+ // the fresh parse explains with a cursor slice and no cursor-agent slice
1873
+ // is that move, not pruned history, so the old cursor-agent slice goes.
1874
+ if (parseWasComplete && pendingRederive?.has('cursor-agent')) {
1875
+ carriedBaseline = carriedBaseline.flatMap(day => {
1876
+ const fresh = freshProviders.get(day.date);
1877
+ if (!day.providers['cursor-agent'] || !fresh || fresh['cursor-agent'] || !fresh['cursor'] || !hasSliceData(fresh['cursor']))
1878
+ return [day];
1879
+ const copy = structuredClone(day);
1880
+ subtractSliceFromDay(copy, 'cursor-agent', copy.providers['cursor-agent']);
1881
+ return hasPositiveDayContent(copy) ? [copy] : [];
1882
+ });
1883
+ }
1884
+ // A pending provider's new accounting can empty a settled day outright (a
1885
+ // Codex day of rate-limit pings, a Goose session moved across midnight,
1886
+ // a Quick Desktop estimate its metrics replaced), and the merge would
1887
+ // carry that slice as pruned history. Sources are pruned oldest first,
1888
+ // so a day on or after the provider's earliest fresh day still has its
1889
+ // sources: its missing slice goes on this one re-derive. Days before it
1890
+ // stay carried. TRADE-OFF: a user who deleted one mid-history source
1891
+ // file loses that day's carried slice once.
1892
+ if (parseWasComplete && pendingRederive) {
1893
+ const earliestFresh = new Map();
1894
+ for (const d of freshDays) {
1895
+ for (const [provider, slice] of Object.entries(d.providers)) {
1896
+ const seen = earliestFresh.get(provider);
1897
+ if (pendingRederive.has(provider) && hasSliceData(slice) && (seen === undefined || d.date < seen))
1898
+ earliestFresh.set(provider, d.date);
1899
+ }
1900
+ }
1901
+ carriedBaseline = carriedBaseline.flatMap(day => {
1902
+ const fresh = freshProviders.get(day.date);
1903
+ const emptied = Object.keys(day.providers).filter(provider => {
1904
+ const earliest = earliestFresh.get(provider);
1905
+ return earliest !== undefined && day.date >= earliest && !fresh?.[provider];
1906
+ });
1907
+ if (emptied.length === 0)
1908
+ return [day];
1909
+ const copy = structuredClone(day);
1910
+ for (const provider of emptied)
1911
+ subtractSliceFromDay(copy, provider, copy.providers[provider]);
1912
+ return hasPositiveDayContent(copy) ? [copy] : [];
1913
+ });
1914
+ }
1915
+ // Without the subtraction an old-zone slice is never a partial survivor
1916
+ // of the fresh one, so the guard would swap a shifted day back in.
1917
+ const merged = parseWasComplete
1918
+ ? mergeDayEntries(freshDays, await withoutImportReplacedSlices(carriedBaseline), true, tzSubtraction, !tzChanged || tzSubtraction !== undefined, pendingRederive)
1919
+ : mergeDayEntries(baseline, freshDays, false);
1920
+ // Only the complete re-derive re-parses the whole window, so freshDays is
1921
+ // the authoritative record set and every non-carried merged day should be
1922
+ // one of them; the partial path only fills gaps and cannot vouch for
1923
+ // record presence, so it is not checked. Observer only — wrapped so it can
1924
+ // never affect hydration.
1925
+ if (parseWasComplete) {
1926
+ try {
1927
+ detectPhantomSpend(merged, new Set(freshDays.map(d => d.date)));
1928
+ }
1929
+ catch { /* detection must never break hydration */ }
1930
+ }
1931
+ c = {
1932
+ version: DAILY_CACHE_VERSION,
1933
+ savingsConfigHash,
1934
+ tzKey,
1935
+ // Spent: this re-derivation was the one the migration owed those
1936
+ // providers. A PARTIAL parse never got to use it (its fresh data only
1937
+ // filled gaps), so the entitlement is kept for the next complete run.
1938
+ ...(parseWasComplete || !c.pendingRederive ? {} : { pendingRederive: c.pendingRederive }),
1939
+ // The watermark records how far history has actually been derived, so
1940
+ // only a COMPLETE parse may advance it. A partial one produced no data
1941
+ // for whatever it could not read; moving the watermark to yesterday
1942
+ // anyway would place those days behind the next run's gapStart and
1943
+ // freeze the hole in (retention still anchors on yesterdayStr — the
1944
+ // real calendar edge — so holding the watermark can't evict anything).
1945
+ lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark,
1946
+ days: applyRetention(merged, yesterdayStr),
1947
+ complete: parseWasComplete,
1948
+ // Stamp the watermark as trusted only when a COMPLETE parse produced it,
1949
+ // so a later idle tail under this watermark is not distrusted above.
1950
+ watermarkTrusted: parseWasComplete,
1951
+ };
1952
+ await saveDailyCache(c);
1953
+ return c;
1954
+ }
1955
+ if (c.tzKey === undefined) {
1956
+ // First write under the tzKey scheme: tag the cache so a later TZ change is
1957
+ // detectable, without discarding the (still-valid, same-TZ) cached days.
1958
+ c = { ...c, tzKey };
1959
+ }
1960
+ const gapStart = c.lastComputedDate
1961
+ ? new Date(parseInt(c.lastComputedDate.slice(0, 4)), parseInt(c.lastComputedDate.slice(5, 7)) - 1, parseInt(c.lastComputedDate.slice(8, 10)) + 1)
1962
+ : new Date(now.getFullYear(), now.getMonth(), now.getDate() - BACKFILL_DAYS);
1963
+ if (gapStart.getTime() <= yesterdayEnd.getTime()) {
1964
+ // Sealing a new day also re-derives the still-settling ones before it. A
1965
+ // day sealed once is otherwise frozen, while every surface that parses
1966
+ // that date live (report --day, a week period) prefers the live parse
1967
+ // whenever it finds more calls: a call that landed after the seal, or a
1968
+ // price change since, then made history.daily disagree with report for
1969
+ // the same date. The merge below lets the fresh parse win there when it
1970
+ // explains at least as many calls; a sealed day never shrinks, since a
1971
+ // transcript cleaned up or a partial provider sync looks the same.
1972
+ const settleStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - SETTLE_DAYS);
1973
+ const gapRange = { start: settleStart < gapStart ? settleStart : gapStart, end: yesterdayEnd };
1974
+ // A re-derived window starts on a day sealed together with the day before
1975
+ // it, which already holds any turn crossing that midnight. Parse from that
1976
+ // day so the turn stays whole there instead of being cut and its later
1977
+ // part counted again on the window start.
1978
+ const parseStart = settleStart < gapStart
1979
+ ? new Date(now.getFullYear(), now.getMonth(), now.getDate() - SETTLE_DAYS - 1)
1980
+ : gapStart;
1981
+ const gapProjects = await parseSessions({ start: parseStart, end: yesterdayEnd });
1982
+ const gapDays = daysInRange(aggregateDays(gapProjects), gapRange);
1983
+ const parseWasComplete = sessionComplete();
1984
+ const priorWatermark = c.lastComputedDate;
1985
+ // Gate the merge on parse completeness (issue #1127): replacing cached
1986
+ // days wholesale with the gap parse's days let a PARTIAL parse overwrite
1987
+ // a populated baseline day with its under-read version — and if the
1988
+ // day's sources die before the next complete parse, the undercount is
1989
+ // what survives. A complete parse still wins per (date, provider)
1990
+ // exactly as the re-derive path does (partial-survival guarded); a
1991
+ // partial one only fills days and slices the baseline lacks, so the gap
1992
+ // merge is strictly additive and no cached data can shrink.
1993
+ const merged = parseWasComplete
1994
+ ? mergeDayEntries(gapDays, c.days, false, undefined, true, undefined, toDateString(gapStart))
1995
+ : mergeDayEntries(c.days, gapDays, false);
1996
+ // Finalize as complete ONLY when the session parse that produced these days
1997
+ // was itself complete. If it was partial, leave `complete: false` so the
1998
+ // next launch (once the session cache is whole) re-backfills instead of
1999
+ // freezing the partial history — and hold the watermark where it was, for
2000
+ // the same reason as the re-derive path above: a partial parse cannot
2001
+ // vouch for the days it never read, and gapStart is the only thing that
2002
+ // will ever bring them back.
2003
+ c = { ...c, days: applyRetention(merged, yesterdayStr), lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete };
2004
+ await saveDailyCache(c);
2005
+ }
2006
+ else if (c.complete !== true && sessionComplete()) {
2007
+ // No gap to fill (already current through yesterday) but not yet marked —
2008
+ // e.g. a brand-new machine whose only data is today. Finalize so future
2009
+ // launches don't re-backfill the whole window every time.
2010
+ c = { ...c, complete: true, watermarkTrusted: true };
2011
+ await saveDailyCache(c);
2012
+ }
2013
+ return c;
2014
+ });
2015
+ }
2016
+ /// The projects the day cache still knows about over a range, whose sources may
2017
+ /// be long expired. A --project/--exclude pattern is only reported as naming
2018
+ /// nothing once it has missed here too: the cache is what the totals are built
2019
+ /// from, so a path it carries is a path the report bills, whatever the live
2020
+ /// parse can still see. Read all-provider on purpose, like the day split itself,
2021
+ /// so a provider-scoped command does not call a path wrong because the spend
2022
+ /// sits under another tool.
2023
+ export function cachedProjectIdentities(cache, startStr, endStr) {
2024
+ const identities = [];
2025
+ for (const day of cache.days) {
2026
+ if (day.date < startStr || day.date > endStr || !day.projects)
2027
+ continue;
2028
+ for (const [key, stats] of Object.entries(day.projects)) {
2029
+ identities.push(projectDayIdentity(key, stats));
2030
+ }
2031
+ }
2032
+ return identities;
2033
+ }
2034
+ export async function cachedProjectIdentitiesForRange(range) {
2035
+ return cachedProjectIdentities(await loadDailyCache(), toDateString(range.start), toDateString(range.end));
2036
+ }