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,3040 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFile, stat, open, rename, unlink, readdir, mkdir, rm } from 'fs/promises';
3
+ import { existsSync, readFileSync, unlinkSync } from 'fs';
4
+ import { createHash, randomBytes } from 'crypto';
5
+ import { basename, dirname, join } from 'path';
6
+ import { StringDecoder } from 'string_decoder';
7
+ import { getCodeburnCacheDir, RETIRED_PROVIDER_NAMES } from './cache-dir.js';
8
+ import { acquireCacheRefreshLock, releaseOwnedRefreshLocksForExit } from './cache-refresh-lock.js';
9
+ import { parseBillingMode } from './models.js';
10
+ import { isGrokbotMirrorPath } from './providers/grokbot.js';
11
+ import { SPEEDS } from './types.js';
12
+ import { isWslUncPath } from './wsl.js';
13
+ // ── Constants ──────────────────────────────────────────────────────────
14
+ // v5: kiro joined the costUSD pass-through allowlist (credit-based pricing).
15
+ // Cached kiro entries from v4 carry costUSD: undefined and would keep being
16
+ // re-priced from estimated tokens forever, since historical session files
17
+ // never change. Bump forces a one-time re-parse so metered credit costs land.
18
+ // v6: per-turn `prRefs` capture for turn-level PR spend attribution. Existing
19
+ // cache turns carry no prRefs; bumping forces a one-time re-parse so surviving
20
+ // transcripts populate the field. (Daily-cache versioning is untouched.)
21
+ // v7: sidechain->parent linkage - per-turn `spawnToolUseIds`, per-file
22
+ // `parentSessionId` / `agentSpawnLinks` - so subagent spend folds into the parent
23
+ // turn's PR set. v6 never shipped, so users cross v5->v7 in a single combined bump.
24
+ // INVARIANT: a version bump must extend `PRIOR_CACHE_VERSIONS` (the adoption path
25
+ // below) to EVERY prior version that can still exist on disk, or expired-PR
26
+ // history from the immediately preceding build silently vanishes.
27
+ // v8: on-disk layout only - the single blob became a directory of per-provider
28
+ // shards plus a small envelope, so a launch that only touched one provider
29
+ // rewrites just that provider's file. The turn shape is unchanged, so a v7 file
30
+ // migrates losslessly (migrateSingleFileCache) rather than re-parsing.
31
+ // v9: on-disk layout only - a provider's shard split further by the UTC month of
32
+ // each cached file, so one appended session rewrites one month instead of the
33
+ // provider's whole (100MB-scale) history, and a ranged query loads only the
34
+ // months it can possibly report on. Turn shape unchanged, so v8 and v7 both
35
+ // migrate losslessly.
36
+ // v10: on-disk layout only - a provider's files are stored in pieces by the UTC
37
+ // day of each file's newest call, with a per-provider index of every cached
38
+ // file (piece, fingerprint, call span) and a per-piece file of dedup keys. A
39
+ // narrow query reads the index, the keys, and only the members it reports on;
40
+ // an append rewrites one day. Turn shape unchanged, so v9 migrates losslessly.
41
+ export const CACHE_VERSION = 10;
42
+ // The cache directory is version-suffixed for the same reason the file used to
43
+ // be: different binaries (an old launchd menubar, a newer desktop app) each own
44
+ // a distinct layout and can never clobber each other's incompatible schema.
45
+ const CACHE_DIR_NAME = `session-cache.v${CACHE_VERSION}`;
46
+ // The v9 month shards and the v8 provider shards, each read once by a lossless
47
+ // re-layout.
48
+ const MONTH_SHARD_DIR_NAME = 'session-cache.v9';
49
+ const PRIOR_SHARD_DIR_NAME = 'session-cache.v8';
50
+ // Written LAST on every save: it names every provider's index, which names its
51
+ // pieces, so the rename that publishes it is the single point at which a save
52
+ // becomes visible.
53
+ const ENVELOPE_FILE = 'envelope.json';
54
+ // The pre-versioning filename. Never written or deleted anymore — old binaries
55
+ // still own it. On first load we adopt-copy it once (see loadCache) when the
56
+ // versioned file is absent and the legacy file's version matches ours.
57
+ const LEGACY_CACHE_FILE = 'session-cache.json';
58
+ const TEMP_FILE_MAX_AGE_MS = 5 * 60 * 1000;
59
+ // A shard the published envelope does not name is either superseded garbage or
60
+ // a CONCURRENT writer's shard that its envelope has not published yet. The
61
+ // second case is why this guard is an order of magnitude above the temp-file
62
+ // one: sweeping a live save's shard out from under it would publish an envelope
63
+ // naming a file that no longer exists. No save takes an hour.
64
+ const UNREFERENCED_SHARD_MAX_AGE_MS = 60 * 60 * 1000;
65
+ // Env vars that change what a provider discovers or how its sessions parse.
66
+ // computeEnvFingerprint hashes exactly these to decide when a provider's cache
67
+ // section is stale; a var read by the provider but missing here means changing
68
+ // it serves the old section silently, reporting nothing from the new root.
69
+ // One read in src/providers/ is deliberately absent: CODEBURN_VERBOSE
70
+ // (sqlite-session-parser.ts:276) only changes logging verbosity, never parsed
71
+ // output.
72
+ //
73
+ // Copilot is deliberately NOT declared here. Declaring any CODEBURN_COPILOT_*
74
+ // var would change its fingerprint, and on a fingerprint change
75
+ // getOrCreateProviderSection (src/parser.ts:2650) keeps only the cached
76
+ // entries whose source path no longer exists — but copilot's OTel discovery
77
+ // returns one source per DB file ({ path: dbPath }, src/providers/copilot.ts:1935)
78
+ // and that DB keeps existing, so its cached entry would be dropped and
79
+ // re-parsed, destroying conversations Copilot has since pruned from the DB
80
+ // that only the cache still holds (see DURABLE_PROVIDER_NAMES below). Do not
81
+ // "complete" the map for copilot until the durable carry-forward learns to
82
+ // merge instead of drop.
83
+ //
84
+ // CODEBURN_COPILOT_SESSION_STORE_DB is covered by that ruling too, and needs
85
+ // no exception: repointing it cannot serve stale data. Copilot's
86
+ // rollup-vs-store reconciliation runs at SERVE time over the cached serve set
87
+ // (parseProviderSources), never against a discovery-time snapshot, so a
88
+ // repointed path is simply a new source parsed on sight while the old path's
89
+ // cached rows persist as durable orphans contributing exactly what they
90
+ // always did. There is no cross-file dependency for the fingerprint to catch,
91
+ // so declaring it would buy nothing and cost the durable-history loss above.
92
+ //
93
+ // CODEBURN_WSL (src/wsl.ts) is also deliberately absent, for claude and codex
94
+ // alike. It is a live read policy, not parsed content: active roots add paths;
95
+ // stopped roots retain historical WSL rows without touching their UNC share;
96
+ // and active-root deletions are reconciled explicitly by src/parser.ts.
97
+ // `off` disables discovery/UNC access while leaving that retained history
98
+ // readable. Hashing the policy here would instead discard the rows that make a
99
+ // shutdown/restart cycle lossless and force a full 9P re-parse after re-enable.
100
+ export const PROVIDER_ENV_VARS = {
101
+ amp: ['AMP_DATA_DIR'],
102
+ claude: ['CLAUDE_CONFIG_DIRS', 'CLAUDE_CONFIG_DIR', 'CODEBURN_DESKTOP_SESSIONS_DIR', 'APPDATA', 'LOCALAPPDATA'],
103
+ 'cline-cli': ['CLINE_SESSION_DATA_DIR', 'CLINE_DATA_DIR', 'CLINE_DIR'],
104
+ codebuff: ['CODEBUFF_DATA_DIR'],
105
+ codewhale: ['CODEWHALE_HOME'],
106
+ 'command-code': ['CODEBURN_COMMANDCODE_DIR'],
107
+ codex: ['CODEX_HOME'],
108
+ hermes: ['HERMES_HOME', 'LOCALAPPDATA'],
109
+ 'lingtai-tui': ['LINGTAI_HOME', 'LINGTAI_TUI_HOME', 'LINGTAI_TUI_GLOBAL_DIR'],
110
+ droid: ['FACTORY_DIR'],
111
+ dsh: ['DSH_HOME'],
112
+ cursor: ['CODEBURN_CURSOR_MAX_BUBBLES', 'APPDATA', 'XDG_CONFIG_HOME'],
113
+ // XDG_DATA_HOME is stale here (cursor-agent never reads it) but deliberately
114
+ // kept: removing it would force a re-parse to fix nothing.
115
+ 'cursor-agent': ['XDG_DATA_HOME'],
116
+ 'open-design': ['CODEBURN_OPEN_DESIGN_DIR', 'APPDATA'],
117
+ openclaude: ['CODEBURN_OPENCLAUDE_DIR'],
118
+ opencode: ['XDG_DATA_HOME', 'OPENCODE_DATA_DIR', 'OPENCODE_DB_PREFIX'],
119
+ goose: ['XDG_DATA_HOME', 'GOOSE_PATH_ROOT'],
120
+ grok: ['GROK_HOME'],
121
+ grokbot: ['CODEBURN_GROKBOT_DIR', 'APPDATA'],
122
+ crush: ['XDG_DATA_HOME', 'CRUSH_GLOBAL_DATA', 'LOCALAPPDATA'],
123
+ warp: ['WARP_DB_PATH', 'XDG_STATE_HOME', 'LOCALAPPDATA'],
124
+ antigravity: ['CODEBURN_CACHE_DIR'],
125
+ 'kilo-code': ['XDG_DATA_HOME'],
126
+ kimi: ['KIMI_SHARE_DIR', 'KIMI_MODEL_NAME'],
127
+ kiro: ['KIRO_HOME'],
128
+ 'mistral-vibe': ['VIBE_HOME'],
129
+ mux: ['MUX_ROOT', 'CODEBURN_MUX_DIR'],
130
+ qwen: ['QWEN_DATA_DIR'],
131
+ 'ibm-bob': ['XDG_CONFIG_HOME', 'APPDATA'],
132
+ quickdesk: ['QUICKWORK_HOME'],
133
+ kimicode: ['KIMI_CODE_HOME'],
134
+ zerostack: ['ZS_DATA_DIR', 'XDG_DATA_HOME'],
135
+ // The gateway credential is a deliberate user override and MUST move the
136
+ // fingerprint: a read-only refresh (the refresh-lock fallback) serves the
137
+ // cached report straight from the section (parser.ts:2875 seeds servedSources
138
+ // before the network re-fetch at parser.ts:2888, which only runs when
139
+ // !readOnly), so an undeclared credential would keep serving the previous
140
+ // account's usage after a swap — the exact #920 defect.
141
+ 'vercel-gateway': ['AI_GATEWAY_API_KEY', 'VERCEL_OIDC_TOKEN'],
142
+ };
143
+ // Names of providers whose cache entries are never evicted when source files
144
+ // disappear — they are preserved so month-to-date totals never drop.
145
+ export const DURABLE_PROVIDER_NAMES = new Set(['copilot']);
146
+ // Read in full by a ranged load, like the durable providers: their parse reads
147
+ // cached entries no report shows. hermes seeds its ledger cursors from every
148
+ // cached call, quickdesk has durable sources before its section is stamped
149
+ // durable, and antigravity, devin and gemini decide a re-parse from the cached
150
+ // entry itself (cachedFileNeedsProviderReparse in parser.ts).
151
+ const FULL_LOAD_PROVIDER_NAMES = new Set(['hermes', 'quickdesk', 'antigravity', 'devin', 'gemini']);
152
+ // Estimated-cost surfacing (#639): providers that set `costIsEstimated` carry a
153
+ // `-est-cost` suffix (or a new entry) so their already-cached sessions reparse
154
+ // once and the flag lands, instead of silently reading as measured. Copilot
155
+ // needs no suffix: the cli-shutdown-cost-v1 bump below already forces its one
156
+ // re-parse, which lands the flag too, and durable orphans now survive
157
+ // fingerprint changes (the carry-forward in getOrCreateProviderSection).
158
+ export const PROVIDER_PARSE_VERSIONS = {
159
+ // usage-ledger-v2: include positive ledger total remainders as output after
160
+ // subtracting input, output, and cache tokens joined through toMessageId.
161
+ amp: 'usage-ledger-v2',
162
+ // rich-session-capture-v1: parse-time capture of per-turn gitBranch, per-call
163
+ // LOC deltas / interruptions / userModified / toolErrors, and session-level
164
+ // title / prLinks / isSidechain. Forces one re-parse so cached sessions gain
165
+ // the new optional fields.
166
+ // session-lineage-capture-v1: SessionLineage (CB-1, slice 1) is now carried
167
+ // on the cached file. The child evidence is the transcript's
168
+ // provider-recorded `parentSessionId` (already captured); the root evidence
169
+ // is the parent-side `agentSpawnLinks` (already captured). A one-time
170
+ // re-parse is forced so cached sessions without the lineage field gain it.
171
+ // The field is purely additive; every cost / token / call total is
172
+ // byte-identical to a build that omits it (see parser-lineage-capture test).
173
+ // queued-human-prompts-v1: cached turns need to be regrouped around Claude's
174
+ // queued_command prompt attachments, including classification and PR links.
175
+ // per-call-cwd-v1: cached calls carry their cwd so a session that moved
176
+ // folders splits across projects per call.
177
+ // streamed-tool-blocks-v1: parallel tool_use blocks written on earlier lines
178
+ // of one streamed message are kept, so cached calls regain their tools.
179
+ // powershell-shell-tool-v1: the Windows PowerShell tool is a shell tool, so
180
+ // cached calls regain the commands compaction used to drop.
181
+ // thinking-tokens-v1: reasoningTokens is read from usage.output_tokens_details,
182
+ // so cached calls regain their thinking share of the output.
183
+ // sidechain-output-estimate-v1: subagent messages from Claude Code before
184
+ // 2.1.307 that never got a final usage row have their output estimated.
185
+ claude: 'advisor-usage-v1-skills-rich-capture-v1-cross-provider-pr-v1-session-lineage-capture-v1-queued-human-prompts-v1-per-call-cwd-v1-streamed-tool-blocks-v1-powershell-shell-tool-v1-thinking-tokens-v1-sidechain-output-estimate-v1-multiline-bash-v1',
186
+ // reported-cost-v1: a request's recorded `cost` is kept through the cache
187
+ // instead of being re-priced from tokens on every read.
188
+ cline: 'worktree-project-grouping-v1-reported-cost-v1',
189
+ // reported-cost-v1: the CLI reports its own per-message cost, so entries
190
+ // cached before cline-cli joined the reported-cost allowlist in parser.ts
191
+ // hold costUSD: undefined and get re-priced from tokens on every read.
192
+ // cache-inclusive-input-v1: cached calls hold inputTokens with cache reads
193
+ // and writes still inside it, so they must re-parse.
194
+ 'cline-cli': 'reported-cost-v1-est-reprice-v1-cache-inclusive-input-v1-multiline-bash-v1',
195
+ codewhale: 'aggregate-session-v1-est-cost-multiline-bash-v1',
196
+ 'command-code': 'cache-inclusive-input-v1-multiline-bash-v1',
197
+ // Bump when the Codex parser changes attribution so unchanged, already-cached
198
+ // session files re-parse (session-cache.json serves them without invoking the
199
+ // provider parser otherwise). Covers native mcp_tool_call_end (#513) and
200
+ // CLI-wrapped `mcp-cli call` (#478) MCP attribution.
201
+ // rich-session-capture-v1: per-call LOC deltas + editFailed from
202
+ // patch_apply_end. (The codex-results.json CODEX_CACHE_VERSION is bumped in
203
+ // lockstep so the pre-session-cache layer re-parses too.)
204
+ // session-meta-model-v1: parse large session_meta records structurally so a
205
+ // nested base_instructions provenance.model cannot overwrite turn_context.
206
+ // session-meta-fields-v1: the same depth-1 window for cwd/name/originator/
207
+ // session_id/forked_from_id/model_provider, not just model. (#1055)
208
+ // codex-pricing-v1 (#1075): reasoning tokens are no longer added on top of
209
+ // output, and cache_write_input_tokens moves out of the plain input bucket on
210
+ // models with an explicit cache-write rate. The bucket move does NOT self-heal
211
+ // on read (cached entries store the buckets, not the raw event), so cached
212
+ // sessions must re-parse.
213
+ // codex-tps-v1 (#1079): activeGeneratedTokens summed output + reasoning, the
214
+ // same double-count codex-pricing-v1 removed from cost. Cached entries store
215
+ // activeGeneratedTokens/activeDurationMs/toolWaitMs verbatim (cachedCallToApiCall
216
+ // passes them through without recomputing), so this does NOT self-heal either.
217
+ // codex-mcp-skills-v1 (#478): CLI-wrapped MCP calls and SKILL.md reads made
218
+ // through the `exec` custom tool or the item model's `CommandExecution` item
219
+ // were counted as Bash only. Cached sessions store tools/toolSequence/skills
220
+ // verbatim, so they must re-parse to gain the attribution.
221
+ // activity-price-v1: `codex-auto-review` now prices via the recommended
222
+ // review model. session-cache.json would otherwise keep the pre-alias $0.
223
+ // fork-replay-burst-v1: copied fork history ends at the first >1s timestamp
224
+ // gap, preserving genuine work that starts before the old 5s cutoff.
225
+ // codex-token-usage-record-v1: prefer response-level usage records on newer
226
+ // rollouts and retain the legacy-to-record handover state. Cached turns must
227
+ // reparse because session-cache otherwise bypasses the provider parser.
228
+ // Compose both suffixes so cached sessions receive both accounting fixes.
229
+ // codex-priority-tier-v1 (#1616): turns under Codex's Fast speed setting
230
+ // (service_tier "priority") now bill at the priority rates. Cached calls
231
+ // hold speed: 'standard' and are re-priced from that field on read, so the
232
+ // multiplier alone cannot reach them - they must re-parse to re-record it.
233
+ // codex-auto-review-date-v1: the cached cache-write split follows the
234
+ // auto-review model by date (gpt-5.4 before 30 Jul 2026, Luna after).
235
+ // codex-flex-reserve-v1: flex turns record speed 'flex' (cached calls hold
236
+ // 'standard'), and `gpt-reserve` now splits cache writes like GPT-5.6 Luna.
237
+ // codex-fork-mask-v1: a fork's replay burst drops only records the parent
238
+ // rollout holds, so cached forks that dropped the whole burst re-parse.
239
+ // native-tool-events-v1: capture built-in Responses tools and item-model
240
+ // WebSearch mirrors, preserving the first observed item identity across
241
+ // cached turns and append checkpoints.
242
+ // mcp-cli-command-v1: mcp-cli counts only in command position, so cached
243
+ // fake mcp__ tools from commit messages or echoes re-parse away.
244
+ // thread-id-key-v1: rollouts without payload.session_id key on payload.id,
245
+ // the UUID forks name, so cached double-counted fork replays re-parse.
246
+ // rate-limit-ping-v1: a null-info token_count before any output is not a
247
+ // call, and measured usage replaces a ping estimate of the same turn, so
248
+ // cached phantom estimates re-parse away.
249
+ // cumulative-restart-v1: a cumulative-only total below the previous one is a
250
+ // counter restart and an omitted field is unchanged, so cached negative or
251
+ // overcounted token deltas re-parse.
252
+ // Compose every suffix so cached sessions receive all accounting fixes.
253
+ codex: 'mcp-attribution-v5-est-cost-active-timing-mcp-wait-rich-capture-v1-cross-provider-pr-v1-session-meta-model-v1-session-meta-fields-v1-codex-pricing-v1-codex-tps-v1-codex-mcp-skills-v1-activity-price-v1-fork-replay-burst-v1-codex-token-usage-record-v1-codex-priority-tier-v1-codex-auto-review-date-v1-codex-flex-reserve-v1-codex-fork-mask-v1-native-tool-events-v1-mcp-cli-command-v1-thread-id-key-v1-rate-limit-ping-v1-cumulative-restart-v1',
254
+ // reported-cost-v1: cached Crush calls stored costUSD: undefined and must
255
+ // re-parse to keep the recorded session cost.
256
+ crush: 'reported-cost-v1',
257
+ // import-guess-est-v1: synced Auto rows with no dollar amount are estimated.
258
+ // full-lookback-v1: a cached parse could be cut at a narrow request's start.
259
+ // agentkv-first-seen-v1: streams of conversations older than the window were
260
+ // billed at the DB mtime, and agent-only sessions moved to each new write.
261
+ // own-bubble-prompt-v1: a reply could carry another turn's prompt.
262
+ // agentkv-json-valid-v1: one agentKv value that was not valid JSON emptied
263
+ // the whole agent stream.
264
+ // cap-resume-v1: agent-stream ids past the lookup cap were never billed on
265
+ // an unchanged DB.
266
+ cursor: 'composer-anchored-crediting-v1-est-cost-import-guess-est-v1-full-lookback-v1-bubble-id-dedupe-v1-agentkv-first-seen-v1-own-bubble-prompt-v1-agentkv-json-valid-v1-cap-resume-v1-multiline-bash-v1',
267
+ // full-turn-accounting: every assistant message counts as a turn
268
+ // (previously only the first after each user message survived), tool_use
269
+ // inputs join the output text, and input tokens use the full user text
270
+ // instead of the 500-char display truncation. Cached sessions hold a
271
+ // fraction of their turns, so they must re-parse. v2 bills the user text
272
+ // once per user message instead of once per assistant message.
273
+ // store-db-v1 (#986): sessions with no exported transcript are read from
274
+ // ~/.cursor/chats/*/*/store.db.
275
+ // prompt-time-v1: transcript turns take their prompt's <timestamp> tag, not
276
+ // the session's last write.
277
+ // ide-composer-skip-v1: transcripts of Cursor IDE chats are not read; the
278
+ // cursor provider counts those chats.
279
+ 'cursor-agent': 'workspaceless-transcript-v1-full-turn-accounting-v2-store-db-v1-est-cost-prompt-time-v1-ide-composer-skip-v1',
280
+ // source-provenance-v1 (#944): CLI sessions were misread as VS Code
281
+ // transcripts (both carry producer 'copilot-agent'), skipping the shutdown
282
+ // input/cache rollup; this bump re-parses them so the missing tokens land.
283
+ // #1051 did NOT bump this on its own. A fingerprint change drops every present
284
+ // Copilot source (parser.ts getOrCreateProviderSection) and would erase
285
+ // conversations already pruned from a still-present OTel DB. Old `:n`
286
+ // shutdown keys migrate via cachedFileNeedsProviderReparse + a durable
287
+ // strip of legacy shutdown calls on that JSONL file only.
288
+ // session-store-v2: input/cache for sessions covered by session-store.db
289
+ // moved from shutdown-rollup calls to per-request DB rows. This bump
290
+ // re-parses pre-store caches so the DB rows land; the rollup calls stay
291
+ // cached (the durable union merge never deletes) and the serve-time
292
+ // reconciliation in parseProviderSources decides per (session, model) what
293
+ // they still contribute. v2 (over the never-released v1): store dedup keys
294
+ // grew a content discriminator so a same-path DB reset cannot alias rows.
295
+ // v3: the `initiator='compaction'` row now carries its own output tokens (no
296
+ // assistant.message owns them). The dedup key deliberately did NOT change -
297
+ // it identifies the request, and moving it would leave the cached output-0
298
+ // copy beside the new row - so only this bump re-parses a v2 cache into the
299
+ // corrected shape.
300
+ // chatsession-otel-skills-v1: structured Skill calls are now extracted from
301
+ // VS Code chatSessions and OTel execute_tool spans. Cached calls lack those
302
+ // fields, so force one re-parse before serving period breakdowns.
303
+ // otel-trace-metadata-once-v1: trace-level tool/skill/bash metadata is now
304
+ // attributed to one chat span per trace instead of every span, so cached
305
+ // calls carry the old per-span duplication - force one re-parse.
306
+ // transcript-unknown-usage-v1: a transcript call with no token count is
307
+ // marked estimated; cached entries hold no flag and must re-parse once.
308
+ // otel-workspace-project-v1 (#1529): OTel conversations without a repository
309
+ // attribute take their VS Code workspace name instead of `copilot-chat`, and
310
+ // multi-root workspaces are named after their .code-workspace file. Dedup
311
+ // keys are unchanged, so the durable union replaces the cached calls in place.
312
+ // journal-request-input-v1: journals also record promptTokens directly on
313
+ // each request. Re-parse unchanged sources to repair cached input totals.
314
+ // tokenless-turns-v1: assistant.message events with no outputTokens field
315
+ // (CLI 1.0.8x, VS Code agent host) count as calls, and their leg's shutdown
316
+ // rollup carries output and totalNanoAiu.
317
+ // store-row-output-v1: every session-store row carries its own
318
+ // output_tokens; serve time zeroes it where a per-turn call owns the output.
319
+ // Keys are unchanged, so the re-parse replaces cached output-0 rows in place.
320
+ // jetbrains-opus-4-7-v1: JetBrains claude-opus-4.7 turns priced as the
321
+ // anthropic-auto fallback; cached entries must re-parse once.
322
+ // chatsession-agent-totals-v1: chat-session requests read every agent round
323
+ // (modelTotals, root completionTokens) and copilotCredits as nanoAiu.
324
+ // otel-cache-inclusive-input-v1: cached OTel calls hold inputTokens with
325
+ // cache reads and writes still inside it, so they must re-parse. Calls whose
326
+ // spans agent-traces.db already pruned keep the old input.
327
+ // legacy-estimated-reasoning-in-output-v1: estimated thinking tokens in
328
+ // legacy chat JSON now ride inside outputTokens, so the served price keeps
329
+ // them; cached calls must re-parse once.
330
+ // journal-auto-model-v1: chatSessions journal requests in Auto mode with no
331
+ // resolvedModel take the legacy path's inferred model and an estimated cost
332
+ // instead of model 'auto' at $0.
333
+ // jetbrains-guid-case-v1: JetBrains conversation GUIDs match in any case, so
334
+ // a store using uppercase or mixed-case ids re-attributes its turns.
335
+ copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1-otel-trace-metadata-once-v1-transcript-unknown-usage-v1-otel-workspace-project-v1-journal-request-input-v1-tokenless-turns-v1-store-row-output-v1-jetbrains-opus-4-7-v1-chatsession-agent-totals-v1-otel-cache-inclusive-input-v1-legacy-estimated-reasoning-in-output-v1-journal-auto-model-v1-jetbrains-guid-case-v1-multiline-bash-v1',
336
+ // authoritative-usage-v4: persist one Grok session call from top-level
337
+ // authoritative totals, use modelUsage only for priced attribution, clamp
338
+ // reasoning per record, and label mixed sessions estimated.
339
+ // unified-log-v1: per-request usage from logs/unified.jsonl replaces the
340
+ // session-dir rollup for every session the log holds.
341
+ grok: 'authoritative-usage-v4-unified-log-v1-multiline-bash-v1',
342
+ // Estimated from message text: Grok Bot's local mirror records no tokens.
343
+ // import-guess-est-v1: synced Grok Bot rows with no dollar amount are estimated.
344
+ grokbot: 'estimated-usage-v1-import-guess-est-v1',
345
+ // sqlite-utc-timestamp-v1: zoneless SQLite timestamps are UTC, so cached
346
+ // sessions stamped as local time re-parse.
347
+ goose: 'sqlite-utc-timestamp-v1-multiline-bash-v1',
348
+ // v0-v4 generations, embedded attempt streams, retry accounting, and the
349
+ // version-specific inherited-prefix rules all change cached DSH calls.
350
+ dsh: 'session-formats-v0-v4-attempts-v6-multiline-bash-v1',
351
+ // model-minor-version-v1: undated ids keep their minor version
352
+ // (claude-opus-4-6 no longer stored and priced as claude-opus-4).
353
+ droid: 'model-minor-version-v1',
354
+ // cost-provenance-v3: preserve Hermes included/estimated/actual status and
355
+ // rebuild the provider section alongside the v3 lifetime ledger. The parse
356
+ // bump is required with the ledger bump: seeding a new ledger from a section
357
+ // produced under v2 can turn historical accounting deltas into today's use.
358
+ // billing-route-v1: the session's `billing_provider` column now rides on
359
+ // each call as `route`. Cached calls hold none, so they must re-parse.
360
+ // billing-mode-v1: the resolved cost basis now rides on each call as
361
+ // `billing` (`included` -> subscription, `actual` -> metered). Cached calls
362
+ // hold none, so they must re-parse.
363
+ // helper-usage-v1: auxiliary-model rows in session_model_usage now become calls.
364
+ // ledger-v4: sessions re-parse so v4 can rebuild the cursors whose calculated
365
+ // cost added reasoning on top of output.
366
+ hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-cost-provenance-v3-billing-route-v1-billing-mode-v1-helper-usage-v1-ledger-v4',
367
+ // reported-cost-v1: OpenClaw's per-message `usage.cost.total` is now
368
+ // preserved through the cache via `costFromBilling`. This is OpenClaw's
369
+ // first parse version; adding it moves the provider's env fingerprint,
370
+ // which is what forces the one re-parse that lands the reported dollars.
371
+ // sqlite-store-v1: id-less dedup keys now carry an occurrence index
372
+ // (`h:<hash>:<n>`) instead of the bare payload hash; cached turns hold the
373
+ // old keys, so without this bump they would suppress the re-parsed calls.
374
+ openclaw: 'reported-cost-v1-sqlite-store-v1-multiline-bash-v1',
375
+ // sessions-db-v1: usage now comes from sessions.db message_nodes, one
376
+ // source per session keyed by request_id; transcripts are read only when the
377
+ // database is unusable. The legacy metadata.metrics path no longer carves
378
+ // cache reads out of an input count that never held them. Devin is not
379
+ // durable, so the bump rebuilds its section and old step_id keys go with it.
380
+ // swe-pricing-v1: cached Devin calls carry their parse-time cost, so SWE-2
381
+ // calls cached at $0 must re-parse to pick up its price.
382
+ devin: 'sessions-db-v1-swe-pricing-v1',
383
+ 'lingtai-tui': 'token-ledger-registry-activity-v3',
384
+ 'ibm-bob': 'worktree-project-grouping-v1-reported-cost-v1',
385
+ // project-path-v1: the parser now records the session's full working
386
+ // directory as projectPath (CLI meta.cwd, v2 workspacePaths[0], workspace
387
+ // sessions' workspaceDirectory), which sync attribution needs to resolve
388
+ // the git repo. Cached entries from before the bump lack projectPath and
389
+ // would serve attribution-blind sessions forever without a re-parse.
390
+ // working-directory-v1: project-path-v1 wired the session's directory to
391
+ // projectPath only, but sync attribution does not read that field. It calls
392
+ // buildRepoGroups in "trusted-session-cwd" mode, which resolves the repo from
393
+ // `session.workingDirectory` and drops any session whose own directory does
394
+ // not resolve — so every kiro session stayed attribution-blind despite
395
+ // carrying the path. All three parsers now emit workingDirectory from the
396
+ // same provider-recorded value; parser.ts stamps
397
+ // workingDirectoryProvenance: 'provider-field' on it, which is what the
398
+ // consumer requires (a marker-less value is treated as synthesized and fails
399
+ // closed). Entries cached under project-path-v1 hold projectPath but no
400
+ // workingDirectory, so a re-parse is required for the fix to take effect.
401
+ kiro: 'ide-parsing-v1-est-cost-project-path-v1-working-directory-v1-no-text-tools-v1',
402
+ // nested-agent-v1: OMP writes crewmate transcripts one directory below each
403
+ // parent session. reported-cost-v2 persists those measured costs through the
404
+ // cache, including the explicit zero on xai-oauth turns.
405
+ // cwd-project-path-v1 (#1260): retain absolute session header cwd on
406
+ // projectPath/workingDirectory instead of basename-only identity.
407
+ // project-group-by-abs-v1 (#1260): parseProviderSources groups by abs
408
+ // projectPath/workingDirectory so same-basename distinct roots stay apart.
409
+ // reported-cost-v1: Pi writes a per-message `usage.cost.total`, which is now
410
+ // preserved through the cache via `costFromBilling` instead of being
411
+ // re-priced from tokens on every read. (omp, the same parser, has carried
412
+ // reported costs since reported-cost-v2 below.) Cached calls hold
413
+ // costUSD: undefined, so they must re-parse once.
414
+ pi: 'cwd-project-path-v1-project-group-by-abs-v1-reported-cost-v1-multiline-bash-v1',
415
+ // project-group-by-abs-v1: shared Pi/OMP serve grouping uses abs identity.
416
+ // model-usage-v1: counts OMP side calls (`model_usage` entries: find, judge,
417
+ // cache warming), so cached sessions must re-parse to gain them.
418
+ omp: 'nested-agent-v1-reported-cost-v2-cwd-project-path-v1-project-group-by-abs-v1-model-usage-v1-multiline-bash-v1',
419
+ // archived-subtree-v1 (#1362): the subtree walk no longer filters
420
+ // `time_archived IS NULL`. An archived ROOT self-heals — it was evicted as an
421
+ // undiscovered non-durable source and comes back new — but a root whose CHILD
422
+ // was archived stays a present, unchanged source: every opencode entry
423
+ // fingerprints the same database file, so a warm cache keeps serving the
424
+ // parse that dropped the child's calls until the database is written again.
425
+ // billing-routes-v2: OpenCode's exact `providerID` values now ride on every
426
+ // parsed call as `route`: `openrouter` and `amazon-bedrock`. Cached calls hold
427
+ // neither, so they must re-parse. v2 also invalidates the OpenRouter-only
428
+ // fingerprint used by pre-merge builds of #1486.
429
+ // unknown-usage-v1: a message with output but no usage is marked estimated.
430
+ // v2-legacy-union-v1: a session present in both OpenCode 2.x `session_v2` and
431
+ // the frozen 1.x tables now reads its legacy turns too. Cached parses of an
432
+ // upgraded database hold only what the 2.x migration carried over, and v2
433
+ // turns now carry the bare model id 1.x used instead of `provider/model`.
434
+ // vertex-fallback-cost-v1 (#1547): the recorded `cost` of a turn CodeBurn
435
+ // cannot price rides on the cached call as `fallbackCostUSD`, the session-level
436
+ // rollup uses the bare model id, and `google-vertex`/`google-vertex-anthropic`
437
+ // ride as the `vertex` route. Cached calls hold none of these.
438
+ // cached-prompt-v1: promptTokenCount includes the cached tokens, which
439
+ // were billed again as fresh input.
440
+ // output-thoughts-v1: thoughts already inside candidates are not added again.
441
+ qwen: 'cached-prompt-v1-output-thoughts-v1-multiline-bash-v1',
442
+ opencode: 'session-model-v1-archived-subtree-v1-billing-routes-v2-v2-legacy-union-v1-unknown-usage-v1-vertex-fallback-cost-v1-multiline-bash-v1',
443
+ // snapshot-db-v1: sessions.db estimates are replaced on re-parse, so an
444
+ // estimate superseded by metrics no longer stays cached beside them.
445
+ quickdesk: 'emf-sqlite-v2-est-cost-snapshot-db-v1',
446
+ // session-lineage-capture-v1: SessionLineage (CB-1, slice 1) is now carried
447
+ // on the cached file for every kimicode wire. Child evidence is the
448
+ // provider-recorded `state.json` `agents[<id>].parentAgentId === 'main'`
449
+ // (any non-`main` agent); root evidence is a sibling non-`main` entry
450
+ // alongside the `main` agent. A one-time re-parse is forced so cached
451
+ // sessions without the lineage field gain it. The field is purely
452
+ // additive; every cost / token / call total is byte-identical to a build
453
+ // that omits it.
454
+ // cwd-project-v1: sessions whose state.json has `cwd` but no `workDir` land
455
+ // on that folder instead of a path decoded from the wd_ directory name.
456
+ // tool-sequence-v1: calls carry each tool call's path and shell command, so
457
+ // optimize sees commits/PRs and retries per file. Costs are unchanged.
458
+ kimicode: 'wire-usage-v1-est-cost-session-lineage-capture-v1-cwd-project-v1-tool-sequence-v1-multiline-bash-v1',
459
+ // subagent-session-id-v1: subagent wire logs take `<session>/<subagent>` as
460
+ // their session id, so cached subagents merged across sessions re-parse.
461
+ kimi: 'subagent-session-id-v1-multiline-bash-v1',
462
+ // archived-subtree-v1: KiloCode shares the SQLite parser and the same schema.
463
+ // billing-routes-v2: its warm cache must move with both shared route fields.
464
+ 'kilo-code': 'worktree-project-grouping-v1-session-model-v1-archived-subtree-v1-billing-routes-v2-v2-legacy-union-v1-unknown-usage-v1-vertex-fallback-cost-v1-reported-cost-v1-multiline-bash-v1',
465
+ // billing-cost-v1: Warp's own billing record (total_provider_cost_in_cents,
466
+ // total_charged_usage, credits_spent) now rides on each call as
467
+ // `costFromBilling` and is preserved by providerCallToCachedCall. Entries
468
+ // cached before this hold costUSD: undefined and are re-priced from the
469
+ // token floor on every read, so they must re-parse once for the real dollars
470
+ // to land.
471
+ // billed-cost-v1: total_billed_cost_in_cents prices conversations that carry
472
+ // no provider cost or charged usage.
473
+ // exchange-share-v1: cached exchanges keep their share of a conversation's
474
+ // cost and only new spend goes to new exchanges (parser.ts
475
+ // keepCachedWarpShares); unchanged databases re-parse once onto that rule.
476
+ warp: 'worktree-project-grouping-v1-est-cost-billing-cost-v1-billed-cost-v1-exchange-share-v1-multiline-bash-v1',
477
+ // cache-read-v1-est-cost: gen_metadata and RPC usage now carry cache-read
478
+ // tokens, fields 9/10 read as thinking/response (they were swapped), and
479
+ // placeholder-only models are priced and flagged costIsEstimated.
480
+ // model-fallback-v1: gen_metadata without usage.model falls back to
481
+ // chatModel.model instead of dropping the session, Gemini 3.8 Flash
482
+ // placeholders resolve, and Gemini 3 Flash -a/-d rows are priced.
483
+ // user-msg-v1: extracts user prompts from brain transcripts (<USER_REQUEST>)
484
+ // or SQLite steps table, attributing userMessage across calls and turns.
485
+ // cli-workspace-v1: Antigravity CLI (.db) conversations now attribute
486
+ // projectPath and project from trajectory_metadata_blob instead of collapsing
487
+ // into a generic antigravity-cli bucket.
488
+ // rpc-output-total-v1: RPC calls without a response/thinking split now keep
489
+ // outputTokens as their output instead of 0 (results cache v11 in lockstep).
490
+ antigravity: 'worktree-project-grouping-v7-cache-read-v1-est-cost-model-fallback-v1-user-msg-v1-cli-workspace-v1-rpc-output-total-v1-multiline-bash-v1',
491
+ // pr-attribution-v1: the parser now reads the `message`/`part` tables for
492
+ // per-turn user prompt text and the GitHub PR URLs it references. Cached
493
+ // ZCode sessions hold empty userMessage turns and no session prLinks, so
494
+ // they never appeared under attributed pull requests; one re-parse gains
495
+ // userMessage / per-turn prRefs / session prLinks. Cost totals are
496
+ // unchanged.
497
+ zcode: 'pr-attribution-v1',
498
+ codebuff: 'multiline-bash-v1',
499
+ forge: 'multiline-bash-v1',
500
+ gemini: 'multiline-bash-v1',
501
+ 'mistral-vibe': 'multiline-bash-v1',
502
+ mux: 'multiline-bash-v1',
503
+ openclaude: 'multiline-bash-v1',
504
+ };
505
+ function getLegacyCachePath() {
506
+ return join(getCodeburnCacheDir(), LEGACY_CACHE_FILE);
507
+ }
508
+ /** Absolute path of the active (version-suffixed) session cache directory. */
509
+ export function sessionCacheDir() {
510
+ return join(getCodeburnCacheDir(), CACHE_DIR_NAME);
511
+ }
512
+ // Needed by every range: a failure marker, a turn-less file, a spawn anchor.
513
+ const ROW_ALWAYS = 1;
514
+ const ROW_PR = 2;
515
+ const ROW_DURABLE = 4;
516
+ // A cached source that is durable on its own (CachedFile.durable). A file or
517
+ // index row written before that stamp existed falls back to the provider's
518
+ // per-source rule, so the first stale run after an upgrade keeps it too.
519
+ export function isDurableCachedSource(provider, path, stamped) {
520
+ return stamped || (provider === 'grokbot' && isGrokbotMirrorPath(path));
521
+ }
522
+ function emptyBase() {
523
+ return { index: undefined, pieces: {}, rows: new Map(), hash: '' };
524
+ }
525
+ // Files with no turns (failure markers, empty sessions) have no month to bucket
526
+ // by; they form one month group that every load reads.
527
+ const UNDATED_BUCKET = '0000-00';
528
+ // The piece of a file with no call.
529
+ const UNDATED_DAY = '0000-00-00';
530
+ // Sentinel inside a provider's dirty paths: every file of the provider is dirty.
531
+ const ALL_PATHS = '*';
532
+ function monthKey(timestamp) {
533
+ if (!timestamp)
534
+ return null;
535
+ const ms = Date.parse(timestamp);
536
+ if (Number.isNaN(ms))
537
+ return null;
538
+ const d = new Date(ms);
539
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
540
+ }
541
+ function dayKey(ms) {
542
+ return new Date(ms).toISOString().slice(0, 10);
543
+ }
544
+ /** The UTC month span a cached file covers: `bucket` is its OLDEST turn's month
545
+ * (the shard it lives in), `until` its NEWEST (how far forward the shard can
546
+ * contribute). Both scan every turn rather than reading turns[0]/turns[-1]:
547
+ * several providers emit turns out of chronological order (cursor composers by
548
+ * ROWID, goose/crush/copilot by a DESC ordering), and a `until < bucket` span
549
+ * is empty, which makes the shard unreachable at EVERY scope. */
550
+ export function cacheFileSpan(file) {
551
+ let bucket = null;
552
+ let until = null;
553
+ for (const turn of file.turns) {
554
+ const month = monthKey(turn.timestamp);
555
+ if (month === null)
556
+ continue;
557
+ if (bucket === null || month < bucket)
558
+ bucket = month;
559
+ if (until === null || month > until)
560
+ until = month;
561
+ }
562
+ return bucket === null ? { bucket: UNDATED_BUCKET, until: UNDATED_BUCKET } : { bucket, until: until };
563
+ }
564
+ /** The shard bucket a cached file belongs to. Derived from the file's own turns,
565
+ * so an APPEND never moves it: appending can only extend `until`. */
566
+ export function cacheBucketMonth(file) {
567
+ return cacheFileSpan(file).bucket;
568
+ }
569
+ function keysOf(file) {
570
+ return file.turns.map(turn => turn.calls.map(call => call.deduplicationKey));
571
+ }
572
+ function rowFor(path, file) {
573
+ let lo = Infinity;
574
+ let hi = -Infinity;
575
+ for (const turn of file.turns) {
576
+ for (const call of turn.calls) {
577
+ const ms = Date.parse(call.timestamp);
578
+ if (ms < lo)
579
+ lo = ms;
580
+ if (ms > hi)
581
+ hi = ms;
582
+ }
583
+ }
584
+ const span = cacheFileSpan(file);
585
+ const anchor = !!file.prLinks?.length && file.isSidechain !== true && file.turns.some(t => t.spawnToolUseIds?.length);
586
+ return {
587
+ day: hi === -Infinity ? UNDATED_DAY : dayKey(hi),
588
+ month: span.bucket,
589
+ until: span.until,
590
+ fingerprint: file.fingerprint,
591
+ lo,
592
+ hi,
593
+ flags: (file.failed || file.turns.length === 0 || anchor ? ROW_ALWAYS : 0) | (file.prLinks?.length ? ROW_PR : 0) | (file.durable ? ROW_DURABLE : 0),
594
+ offset: 0,
595
+ length: 0,
596
+ };
597
+ }
598
+ // Needed by a query over [startMs, endMs]: a call in the range, or something a
599
+ // report reads whatever the range: a spawn anchor (an in-range child folds into
600
+ // it), a failure marker or turn-less file, and a WSL path (its orphan handling
601
+ // depends on the root being online).
602
+ function fileNeeded(path, row, startMs, endMs) {
603
+ if ((row.flags & ROW_ALWAYS) !== 0 || isWslUncPath(path))
604
+ return true;
605
+ return row.hi === -Infinity || (row.hi >= startMs && row.lo <= endMs);
606
+ }
607
+ const cacheStates = new WeakMap();
608
+ function stateOf(cache) {
609
+ let state = cacheStates.get(cache);
610
+ if (!state) {
611
+ state = {
612
+ dirty: false,
613
+ dirtyPaths: new Map(),
614
+ base: new Map(),
615
+ visible: new Map(),
616
+ fingerprints: new Map(),
617
+ nonce: undefined,
618
+ scope: 'all',
619
+ dir: sessionCacheDir(),
620
+ stubs: new Map(),
621
+ hidden: new Map(),
622
+ seq: new WeakMap(),
623
+ covered: null,
624
+ };
625
+ cacheStates.set(cache, state);
626
+ }
627
+ return state;
628
+ }
629
+ function markPathDirty(state, provider, path) {
630
+ state.dirty = true;
631
+ let paths = state.dirtyPaths.get(provider);
632
+ if (!paths) {
633
+ paths = new Set();
634
+ state.dirtyPaths.set(provider, paths);
635
+ }
636
+ paths.add(path);
637
+ }
638
+ /** Record that `provider`'s section changed, so the next save rewrites the
639
+ * pieces involved. Pass `filePath` whenever the change is scoped to one cached
640
+ * file (a write, a delete or a re-parse); omitting it dirties every file. */
641
+ export function markCacheDirty(cache, provider, filePath) {
642
+ markPathDirty(stateOf(cache), provider, filePath ?? ALL_PATHS);
643
+ }
644
+ /** True when any provider section changed since the last save. */
645
+ export function isCacheDirty(cache) {
646
+ return stateOf(cache).dirty;
647
+ }
648
+ function stubsOf(state, cache, provider) {
649
+ const held = state.stubs.get(provider);
650
+ return held && held.section === cache.providers[provider] ? held.byPath : undefined;
651
+ }
652
+ function hiddenOf(state, cache, provider) {
653
+ const held = state.hidden.get(provider);
654
+ return held && held.section === cache.providers[provider] ? held.byPath : undefined;
655
+ }
656
+ /** The paths of `provider` a ranged load holds as stubs (see {@link CacheStub}). */
657
+ export function cacheStubs(cache, provider) {
658
+ return stubsOf(stateOf(cache), cache, provider);
659
+ }
660
+ /** The fingerprint a cached file outside the load's months was saved at. v9
661
+ * could not see such a file at all, so a narrow query re-parsed every older
662
+ * transcript it discovered; an unchanged one needs nothing from this range. */
663
+ export function cacheHiddenFingerprint(cache, provider, path) {
664
+ return hiddenOf(stateOf(cache), cache, provider)?.get(path)?.fingerprint;
665
+ }
666
+ /** The dedup keys of hidden files, per turn. A transcript parsed now can replay
667
+ * their message ids (a fork or resume of an old session), and the cached copy
668
+ * must win, as it does for every loaded month. */
669
+ export async function loadCacheHiddenKeys(cache, provider, paths) {
670
+ const state = stateOf(cache);
671
+ const hidden = hiddenOf(state, cache, provider);
672
+ const base = state.base.get(provider);
673
+ const out = [];
674
+ if (!hidden || !base)
675
+ return out;
676
+ const byPiece = new Map();
677
+ for (const path of paths) {
678
+ const row = hidden.get(path);
679
+ if (row)
680
+ pushTo(byPiece, row.day, [path, row]);
681
+ }
682
+ for (const [day, rows] of byPiece) {
683
+ const name = base.pieces[day];
684
+ if (name)
685
+ for (const list of (await readKeyLists(state.dir, name, rows)).values())
686
+ out.push(list);
687
+ }
688
+ return out;
689
+ }
690
+ // A key file is written without a sync, so one lost to a crash is rebuilt
691
+ // from its piece's members.
692
+ async function readKeyLists(dir, name, rows) {
693
+ const keys = await readKeys(dir, name);
694
+ const missing = rows.filter(([path]) => !isKeyList(keys?.[path]));
695
+ const files = missing.length > 0 ? await readMembersAt(join(dir, name), missing) : null;
696
+ const out = new Map();
697
+ for (const [path] of rows) {
698
+ const file = files?.get(path);
699
+ const list = file ? keysOf(file) : keys?.[path];
700
+ if (isKeyList(list))
701
+ out.set(path, list);
702
+ }
703
+ return out;
704
+ }
705
+ /** True when `provider` has any cached entry, full or stubbed. */
706
+ export function hasCachedEntries(cache, provider) {
707
+ const section = cache.providers[provider];
708
+ if (!section)
709
+ return false;
710
+ for (const _ in section.files)
711
+ return true;
712
+ return (stubsOf(stateOf(cache), cache, provider)?.size ?? 0) > 0;
713
+ }
714
+ /** Drop a stub whose source is gone, exactly as deleting its entry would. */
715
+ export function evictCacheStub(cache, provider, path) {
716
+ stubsOf(stateOf(cache), cache, provider)?.delete(path);
717
+ markCacheDirty(cache, provider, path);
718
+ }
719
+ function entriesInLoadOrder(state, section, stubs) {
720
+ if (!stubs)
721
+ return Object.entries(section.files);
722
+ const loaded = [];
723
+ const later = [];
724
+ for (const [path, file] of Object.entries(section.files)) {
725
+ const seq = state.seq.get(file);
726
+ if (seq === undefined)
727
+ later.push([path, file]);
728
+ else
729
+ loaded.push([path, file, seq]);
730
+ }
731
+ for (const [path, stub] of stubs)
732
+ loaded.push([path, stub, stub.seq]);
733
+ loaded.sort((a, b) => a[2] - b[2]);
734
+ return [...loaded.map(([path, entry]) => [path, entry]), ...later];
735
+ }
736
+ /** Every cached entry of `provider`, full or stubbed, in the order a full load
737
+ * would hold them in `files`: loaded entries in index order, then entries
738
+ * written since in the order they were written. */
739
+ export function cacheEntriesInLoadOrder(cache, provider) {
740
+ const section = cache.providers[provider];
741
+ if (!section)
742
+ return [];
743
+ const state = stateOf(cache);
744
+ return entriesInLoadOrder(state, section, stubsOf(state, cache, provider));
745
+ }
746
+ export function isCacheStub(entry) {
747
+ return 'keys' in entry;
748
+ }
749
+ /** Load stubbed members in full, in place, at their load position. A member
750
+ * that can no longer be read loses its stub, so the file re-parses like any
751
+ * uncached one and the save drops its line. */
752
+ export async function loadCacheStubs(cache, provider, paths) {
753
+ const state = stateOf(cache);
754
+ const stubs = stubsOf(state, cache, provider);
755
+ const section = cache.providers[provider];
756
+ const base = state.base.get(provider);
757
+ if (!stubs || !section || !base)
758
+ return;
759
+ const byPiece = new Map();
760
+ for (const path of paths) {
761
+ const row = stubs.has(path) ? base.rows.get(path) : undefined;
762
+ if (row)
763
+ pushTo(byPiece, row.day, [path, row]);
764
+ }
765
+ for (const [day, rows] of byPiece) {
766
+ const name = base.pieces[day];
767
+ const members = name ? await readMembersAt(join(state.dir, name), rows) : new Map();
768
+ for (const [path] of rows) {
769
+ const stub = stubs.get(path);
770
+ stubs.delete(path);
771
+ const file = members.get(path);
772
+ if (file) {
773
+ section.files[path] = file;
774
+ state.seq.set(file, stub.seq);
775
+ }
776
+ else {
777
+ markPathDirty(state, provider, path);
778
+ }
779
+ }
780
+ }
781
+ }
782
+ // Widen what a memoized ranged load holds in full to [startMs, endMs] (and
783
+ // whatever it already covered), loading the stubs that range can report on.
784
+ async function coverRange(cache, startMs, endMs) {
785
+ const state = stateOf(cache);
786
+ const covered = state.covered;
787
+ if (!covered || (startMs >= covered.startMs && endMs <= covered.endMs))
788
+ return;
789
+ const from = Math.min(startMs, covered.startMs);
790
+ const to = Math.max(endMs, covered.endMs);
791
+ for (const provider of Object.keys(cache.providers)) {
792
+ const stubs = stubsOf(state, cache, provider);
793
+ if (!stubs)
794
+ continue;
795
+ const wanted = [];
796
+ for (const [path, stub] of stubs)
797
+ if (stub.hi >= from && stub.lo <= to)
798
+ wanted.push(path);
799
+ await loadCacheStubs(cache, provider, wanted);
800
+ }
801
+ state.covered = { startMs: from, endMs: to };
802
+ }
803
+ /** True when a dirty bucket belongs to a provider whose cache entry is the ONLY
804
+ * surviving record of that spend (see {@link DURABLE_PROVIDER_NAMES}): the
805
+ * source can be pruned before the next publish, so such a window must never be
806
+ * held back by the resident process's coalescing. */
807
+ export function hasDirtyDurableProvider(cache) {
808
+ for (const provider of stateOf(cache).dirtyPaths.keys()) {
809
+ if (DURABLE_PROVIDER_NAMES.has(provider) || cache.providers[provider]?.durable)
810
+ return true;
811
+ }
812
+ return false;
813
+ }
814
+ function pushTo(map, key, value) {
815
+ const list = map.get(key);
816
+ if (list)
817
+ list.push(value);
818
+ else
819
+ map.set(key, [value]);
820
+ }
821
+ // ── Env Fingerprint ────────────────────────────────────────────────────
822
+ export function computeEnvFingerprint(provider) {
823
+ const vars = PROVIDER_ENV_VARS[provider] ?? [];
824
+ const parts = vars.map(v => `${v}=${process.env[v] ?? ''}`);
825
+ const parseVersion = PROVIDER_PARSE_VERSIONS[provider];
826
+ if (parseVersion)
827
+ parts.push(`parser=${parseVersion}`);
828
+ return createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 16);
829
+ }
830
+ // ── Load / Save ────────────────────────────────────────────────────────
831
+ export function emptyCache() {
832
+ return { version: CACHE_VERSION, providers: {}, complete: false };
833
+ }
834
+ /** A cache is warm only when a full scan finished against it. Empty-but-marked
835
+ * (a machine with no sessions) is complete; present-but-unmarked (an interrupted
836
+ * cold start, or a pre-marker cache) is NOT — it is still cold.
837
+ *
838
+ * The answer is composed from the sections the REQUEST needs, on both axes a
839
+ * scan can be scoped on:
840
+ * - provider: a `--provider X` request asks only about X's section; an
841
+ * unscoped one needs the whole-cache flag (only an unscoped scan can vouch
842
+ * for the providers that have no section at all) plus every section it holds.
843
+ * - date: a section stamped with a `completeFrom` floor skipped older sources,
844
+ * so it answers a query starting at or after that floor and no other.
845
+ *
846
+ * `sinceMs` is the requested range start; omitting it asks about ALL of
847
+ * history, which only a section with no floor can satisfy. A section with no
848
+ * `complete` of its own inherits the whole-cache flag, which is what keeps a
849
+ * cache written before per-provider stamps (and one an unscoped scan wrote)
850
+ * reading exactly as it did. */
851
+ export function isCacheComplete(cache, providerFilter, sinceMs) {
852
+ const sectionComplete = (provider) => {
853
+ const section = cache.providers[provider];
854
+ if ((section?.complete ?? cache.complete) !== true)
855
+ return false;
856
+ const from = section?.completeFrom;
857
+ return from === undefined || (sinceMs !== undefined && sinceMs >= from);
858
+ };
859
+ if (providerFilter && providerFilter !== 'all')
860
+ return sectionComplete(providerFilter);
861
+ return cache.complete === true && Object.keys(cache.providers).every(sectionComplete);
862
+ }
863
+ /** Record that this scan walked `provider` to the end, optionally only back to
864
+ * `completeFrom` (the range start that filtered older sources out). Coverage
865
+ * only ever grows — a section already complete for all of history stays that
866
+ * way — so the stored floor is the lowest of the two. Returns whether anything
867
+ * changed, which is what makes the caller save a cache that is otherwise
868
+ * clean. The section is created when absent: a scoped scan of a provider with
869
+ * no sessions has nothing to cache but still has completeness to record, and
870
+ * without it every such run would re-enter cold hydration forever. */
871
+ export function markProviderComplete(cache, provider, completeFrom) {
872
+ const section = cache.providers[provider]
873
+ ?? (cache.providers[provider] = { envFingerprint: computeEnvFingerprint(provider), files: {} });
874
+ const prior = section.complete === true ? section.completeFrom ?? 0 : undefined;
875
+ const widened = prior === undefined ? completeFrom : Math.min(prior, completeFrom ?? 0);
876
+ const floor = widened !== undefined && widened > 0 ? widened : undefined;
877
+ const changed = section.complete !== true || section.completeFrom !== floor;
878
+ section.complete = true;
879
+ if (floor === undefined)
880
+ delete section.completeFrom;
881
+ else
882
+ section.completeFrom = floor;
883
+ return changed;
884
+ }
885
+ /** Pre-parse probe of the same question `isCacheComplete` answers after a load:
886
+ * is the next parse going to be a cold hydration? Reads only the (tiny)
887
+ * envelope, so a caller can branch on coldness before paying for the shards.
888
+ * A cache still in a legacy layout has no envelope and reads as cold — the
889
+ * adoption in `loadCache` may still make it warm, which costs the caller
890
+ * nothing: a warm cache has an entry for every discovered file, so a
891
+ * cold-start optimisation keyed on missing entries simply finds no work.
892
+ * Deliberately the WHOLE-cache question, matching `isCacheComplete` with no
893
+ * provider filter: its callers (the serve first-paint floor, the background
894
+ * fill) answer for every provider at once, so a cache only one scoped run has
895
+ * vouched for is still cold to them. A `completeFrom` floor does not make it
896
+ * cold — the floored months are cached, and a wider request re-enters cold
897
+ * hydration through `isCacheComplete` on its own. */
898
+ export async function isColdCacheOnDisk() {
899
+ return (await readEnvelope(sessionCacheDir()))?.complete !== true;
900
+ }
901
+ function isNum(v) {
902
+ return typeof v === 'number' && Number.isFinite(v);
903
+ }
904
+ function isStringArray(v) {
905
+ return Array.isArray(v) && v.every(e => typeof e === 'string');
906
+ }
907
+ function isOptionalString(v) {
908
+ return v === undefined || typeof v === 'string';
909
+ }
910
+ function isOptionalNum(v) {
911
+ return v === undefined || isNum(v);
912
+ }
913
+ function isOptionalBool(v) {
914
+ return v === undefined || typeof v === 'boolean';
915
+ }
916
+ // A plain object whose every value is a string (or undefined). Used for the
917
+ // sidechain `agentSpawnLinks` map (agentId -> spawn tool_use id).
918
+ function isOptionalStringRecord(v) {
919
+ if (v === undefined)
920
+ return true;
921
+ if (!v || typeof v !== 'object' || Array.isArray(v))
922
+ return false;
923
+ return Object.values(v).every(e => typeof e === 'string');
924
+ }
925
+ // Validates the optional SessionLineage payload. Only `provider-recorded`
926
+ // is accepted; a stray role/evidence value (e.g. an inferred-link stub the
927
+ // brief forbids) must fail the shard validation rather than silently leak.
928
+ function isOptionalLineage(v) {
929
+ if (v === undefined)
930
+ return true;
931
+ if (!v || typeof v !== 'object' || Array.isArray(v))
932
+ return false;
933
+ const o = v;
934
+ if (isOptionalString(o['parentSessionId']) === false)
935
+ return false;
936
+ if (o['role'] !== 'root' && o['role'] !== 'child')
937
+ return false;
938
+ if (o['evidence'] !== 'provider-recorded')
939
+ return false;
940
+ return true;
941
+ }
942
+ function isToolCall(v) {
943
+ if (!v || typeof v !== 'object')
944
+ return false;
945
+ const o = v;
946
+ return typeof o['tool'] === 'string'
947
+ && isOptionalString(o['file'])
948
+ && isOptionalString(o['command']);
949
+ }
950
+ function isToolCallArray(v) {
951
+ return Array.isArray(v) && v.every(isToolCall);
952
+ }
953
+ function validateFingerprint(fp) {
954
+ if (!fp || typeof fp !== 'object')
955
+ return false;
956
+ const f = fp;
957
+ return isNum(f['dev']) && isNum(f['ino']) && isNum(f['mtimeMs']) && isNum(f['sizeBytes']);
958
+ }
959
+ function validateUsage(u) {
960
+ if (!u || typeof u !== 'object')
961
+ return false;
962
+ const o = u;
963
+ return isNum(o['inputTokens']) && isNum(o['outputTokens'])
964
+ && isNum(o['cacheCreationInputTokens']) && isNum(o['cacheReadInputTokens'])
965
+ && isNum(o['cachedInputTokens']) && isNum(o['reasoningTokens'])
966
+ && isNum(o['webSearchRequests']) && isNum(o['cacheCreationOneHourTokens']);
967
+ }
968
+ function validateCall(c) {
969
+ if (!c || typeof c !== 'object')
970
+ return false;
971
+ const o = c;
972
+ return typeof o['provider'] === 'string'
973
+ && typeof o['model'] === 'string'
974
+ && typeof o['deduplicationKey'] === 'string'
975
+ && typeof o['timestamp'] === 'string'
976
+ && SPEEDS.includes(o['speed'])
977
+ && isOptionalNum(o['costUSD'])
978
+ && isOptionalNum(o['fallbackCostUSD'])
979
+ && isOptionalBool(o['isEstimated'])
980
+ && isOptionalNum(o['activeDurationMs'])
981
+ && isOptionalNum(o['activeGeneratedTokens'])
982
+ && isOptionalNum(o['toolWaitMs'])
983
+ && isOptionalNum(o['nanoAiu'])
984
+ && isOptionalNum(o['requestMultiplier'])
985
+ && isOptionalString(o['compactedAt'])
986
+ && isOptionalString(o['initiator'])
987
+ && isStringArray(o['tools'])
988
+ && isStringArray(o['bashCommands'])
989
+ && isStringArray(o['skills'])
990
+ && (o['subagentTypes'] === undefined || isStringArray(o['subagentTypes']))
991
+ && isOptionalString(o['project'])
992
+ && isOptionalString(o['projectPath'])
993
+ && (o['workingDirectoryProvenance'] === undefined || o['workingDirectoryProvenance'] === 'provider-field')
994
+ && isOptionalString(o['workingDirectory'])
995
+ && isOptionalString(o['cwd'])
996
+ && (o['toolSequence'] === undefined || (Array.isArray(o['toolSequence']) && o['toolSequence'].every(s => isToolCallArray(s))))
997
+ && isOptionalNum(o['locAdded'])
998
+ && isOptionalNum(o['locRemoved'])
999
+ && isOptionalBool(o['interrupted'])
1000
+ && isOptionalBool(o['userModified'])
1001
+ && isOptionalNum(o['toolErrors'])
1002
+ && isOptionalNum(o['editFailed'])
1003
+ && isOptionalBool(o['supplementaryAccounting'])
1004
+ && isOptionalNum(o['requestCount'])
1005
+ && isOptionalString(o['route'])
1006
+ && isOptionalString(o['costRung'])
1007
+ && (o['billing'] === undefined || parseBillingMode(o['billing']) !== undefined)
1008
+ && validateUsage(o['usage']);
1009
+ }
1010
+ function validateTurn(t) {
1011
+ if (!t || typeof t !== 'object')
1012
+ return false;
1013
+ const o = t;
1014
+ return typeof o['timestamp'] === 'string'
1015
+ && typeof o['sessionId'] === 'string'
1016
+ && typeof o['userMessage'] === 'string'
1017
+ && isOptionalString(o['gitBranch'])
1018
+ && (o['prRefs'] === undefined || isStringArray(o['prRefs']))
1019
+ && (o['spawnToolUseIds'] === undefined || isStringArray(o['spawnToolUseIds']))
1020
+ && Array.isArray(o['calls'])
1021
+ && o['calls'].every(validateCall);
1022
+ }
1023
+ function validateCachedFile(f) {
1024
+ if (!f || typeof f !== 'object')
1025
+ return false;
1026
+ const o = f;
1027
+ return validateFingerprint(o['fingerprint'])
1028
+ && isOptionalNum(o['lastCompleteLineOffset'])
1029
+ && isOptionalString(o['canonicalCwd'])
1030
+ && isOptionalString(o['workingDirectory'])
1031
+ && isOptionalString(o['canonicalProjectName'])
1032
+ && isStringArray(o['mcpInventory'])
1033
+ && isOptionalString(o['title'])
1034
+ && (o['prLinks'] === undefined || isStringArray(o['prLinks']))
1035
+ && isOptionalBool(o['isSidechain'])
1036
+ && isOptionalString(o['agentType'])
1037
+ && isOptionalString(o['agentName'])
1038
+ && isOptionalString(o['agentStartedAt'])
1039
+ && isOptionalBool(o['failed'])
1040
+ && isOptionalString(o['failedAt'])
1041
+ && isOptionalNum(o['retryableFailures'])
1042
+ && isOptionalString(o['parentSessionId'])
1043
+ && isOptionalStringRecord(o['agentSpawnLinks'])
1044
+ && (o['ambiguousSpawnAgentIds'] === undefined || isStringArray(o['ambiguousSpawnAgentIds']))
1045
+ && isOptionalLineage(o['lineage'])
1046
+ && isOptionalString(o['retainedSince'])
1047
+ && isOptionalBool(o['durable'])
1048
+ && Array.isArray(o['turns'])
1049
+ && o['turns'].every(validateTurn);
1050
+ }
1051
+ // A shard's payload: the provider's `files` map, restricted to one month.
1052
+ function validateFiles(v) {
1053
+ if (!v || typeof v !== 'object' || Array.isArray(v))
1054
+ return false;
1055
+ return Object.values(v).every(validateCachedFile);
1056
+ }
1057
+ function validateProviderSection(s) {
1058
+ if (!s || typeof s !== 'object')
1059
+ return false;
1060
+ const o = s;
1061
+ if (typeof o['envFingerprint'] !== 'string')
1062
+ return false;
1063
+ if (!o['files'] || typeof o['files'] !== 'object' || Array.isArray(o['files']))
1064
+ return false;
1065
+ return Object.values(o['files']).every(validateCachedFile);
1066
+ }
1067
+ // Full validation of a single-file (pre-v8) cache blob at `version`.
1068
+ function validateCache(raw, version) {
1069
+ if (!raw || typeof raw !== 'object')
1070
+ return false;
1071
+ const o = raw;
1072
+ if (o['version'] !== version)
1073
+ return false;
1074
+ if (!o['providers'] || typeof o['providers'] !== 'object' || Array.isArray(o['providers']))
1075
+ return false;
1076
+ return Object.values(o['providers']).every(validateProviderSection);
1077
+ }
1078
+ // Every prior versioned cache file that can still exist on disk from a shipped or
1079
+ // dev build, NEWEST first. On a bump we adopt the newest one present: its
1080
+ // expired-source PR orphans (transcripts since deleted) hold attributable spend
1081
+ // that can never be re-parsed, and each newer version already carried the older
1082
+ // versions' orphans forward, so the newest is a superset. INVARIANT: a
1083
+ // CACHE_VERSION bump MUST extend this list to every prior version that can still
1084
+ // exist on disk, or that history silently vanishes. (v5 was missed on the 5->6
1085
+ // bump; v6 on the 6->7 bump; both are listed here.)
1086
+ const PRIOR_CACHE_VERSIONS = [7, 6, 5];
1087
+ function priorCacheFile(version) {
1088
+ return `session-cache.v${version}.json`;
1089
+ }
1090
+ // Lightweight top-level check: a specific prior-version cache envelope with a
1091
+ // providers object. Files are validated per-entry in adoptPriorCache so one
1092
+ // corrupt entry cannot drop every valid expired-transcript PR session.
1093
+ function isCacheEnvelope(raw, version) {
1094
+ if (!raw || typeof raw !== 'object')
1095
+ return false;
1096
+ const o = raw;
1097
+ return o['version'] === version
1098
+ && !!o['providers'] && typeof o['providers'] === 'object' && !Array.isArray(o['providers']);
1099
+ }
1100
+ // One-time migration on a version bump: carry forward exactly the prior-version
1101
+ // entries whose source no longer exists AND that carry prLinks (they can never
1102
+ // re-parse, but they hold attributable PR spend); present sources are dropped so
1103
+ // they re-parse fresh under the new version and gain the new fields. Each file is
1104
+ // validated individually, so a single corrupt entry is skipped rather than
1105
+ // discarding the whole cache. Each carried section takes the CURRENT
1106
+ // envFingerprint so the scan reuses it and appends the freshly-parsed present
1107
+ // sources. The daily cache (durable cost history) is not touched.
1108
+ async function adoptPriorCache(version) {
1109
+ try {
1110
+ const raw = await readFile(join(getCodeburnCacheDir(), priorCacheFile(version)), 'utf-8');
1111
+ const parsed = JSON.parse(raw);
1112
+ if (!isCacheEnvelope(parsed, version))
1113
+ return null;
1114
+ const migrated = { version: CACHE_VERSION, providers: {}, complete: false };
1115
+ for (const [provider, section] of Object.entries(parsed.providers)) {
1116
+ if (!section || typeof section !== 'object')
1117
+ continue;
1118
+ const rawFiles = section['files'];
1119
+ const files = {};
1120
+ if (rawFiles && typeof rawFiles === 'object' && !Array.isArray(rawFiles)) {
1121
+ for (const [path, file] of Object.entries(rawFiles)) {
1122
+ if (!validateCachedFile(file))
1123
+ continue;
1124
+ if (!existsSync(path) && file.prLinks?.length)
1125
+ files[path] = file;
1126
+ }
1127
+ }
1128
+ migrated.providers[provider] = {
1129
+ envFingerprint: computeEnvFingerprint(provider),
1130
+ files,
1131
+ ...(section['durable'] ? { durable: true } : {}),
1132
+ };
1133
+ }
1134
+ return migrated;
1135
+ }
1136
+ catch {
1137
+ return null;
1138
+ }
1139
+ }
1140
+ // Adopt EVERY prior versioned cache present on disk, migrating OLDEST first and
1141
+ // merging per source path so a newer version wins per entry. Returning the newest
1142
+ // alone would be wrong: a sparse or partial newer file (e.g. v6 holding only some
1143
+ // orphans) would mask older-only orphans that still hold attributable spend. Newer
1144
+ // entries overwrite older ones for the same path; entries unique to an older
1145
+ // version survive.
1146
+ async function adoptNewestPriorCache() {
1147
+ const oldestFirst = [...PRIOR_CACHE_VERSIONS].sort((a, b) => a - b);
1148
+ let merged = null;
1149
+ for (const version of oldestFirst) {
1150
+ const adopted = await adoptPriorCache(version);
1151
+ if (!adopted)
1152
+ continue;
1153
+ if (!merged) {
1154
+ merged = adopted;
1155
+ continue;
1156
+ }
1157
+ for (const [provider, section] of Object.entries(adopted.providers)) {
1158
+ const existing = merged.providers[provider];
1159
+ if (!existing) {
1160
+ merged.providers[provider] = section;
1161
+ continue;
1162
+ }
1163
+ // Newer version's entries overwrite older ones for the same source path.
1164
+ Object.assign(existing.files, section.files);
1165
+ if (section.durable)
1166
+ existing.durable = true;
1167
+ }
1168
+ }
1169
+ return merged;
1170
+ }
1171
+ // In-process memo of the parsed cache, keyed by the envelope nonce that last
1172
+ // produced it. On a 100MB+ corpus the JSON.parse of the shards is seconds of
1173
+ // work per load; a resident process (codeburn serve) pays it once and
1174
+ // revalidates by re-reading the (tiny) envelope per request. A save by ANOTHER
1175
+ // process mints a new nonce and forces a reload, so cross-process freshness is
1176
+ // preserved; saveCache updates the memo write-through so the object handed out
1177
+ // stays the canonical one after a refresh.
1178
+ let cacheMemo = null;
1179
+ export function clearLoadCacheMemo() {
1180
+ cacheMemo = null;
1181
+ clearShardMemo();
1182
+ }
1183
+ /// Is this in-memory cache still the one the published envelope describes? A
1184
+ /// holder that deferred its publish (see the coalescing window in parser.ts)
1185
+ /// asks before writing: if another process has published since, this object is
1186
+ /// a stale pre-image and saving it could drop that process's entries. Dropping
1187
+ /// the deferred write instead costs a re-parse, never a wrong number.
1188
+ export async function isCacheCurrent(cache) {
1189
+ if (!cacheMemo || cacheMemo.cache !== cache)
1190
+ return false;
1191
+ const live = await readEnvelope(cacheMemo.dir);
1192
+ return live?.nonce === cacheMemo.nonce;
1193
+ }
1194
+ export function monthScopeForRange(start, end) {
1195
+ return { fromMonth: monthKey(start.toISOString()), toMonth: monthKey(end.toISOString()), startMs: start.getTime(), endMs: end.getTime() };
1196
+ }
1197
+ function previousMonth(month) {
1198
+ const [y, m] = month.split('-').map(Number);
1199
+ return m === 1 ? `${y - 1}-12` : `${y}-${String(m - 1).padStart(2, '0')}`;
1200
+ }
1201
+ // A shard is in scope when its [bucket .. until] span overlaps the query. One
1202
+ // extra month of slack BELOW the range (and none above — every carry reads
1203
+ // backwards) covers the cross-range carries that read turns from before the
1204
+ // window: the pre-range PR set / git branch a session carries into its first
1205
+ // in-range turn (both resolved from the same file, so they only need the file
1206
+ // loaded at all), and the out-of-range subagent-spawn ANCHOR whose in-range
1207
+ // child folds into it. LIMITATION: an anchor whose last turn is two or more
1208
+ // months before its child's is not loaded, so that child attributes without the
1209
+ // parent's PR set. One month of slack is the deliberate ceiling; widening it
1210
+ // gives back the read savings the scope exists for.
1211
+ // The undated bucket has no span and is always loaded.
1212
+ function shardInScope(bucket, until, scope) {
1213
+ if (bucket === UNDATED_BUCKET)
1214
+ return true;
1215
+ return bucket <= scope.toMonth && until >= previousMonth(scope.fromMonth);
1216
+ }
1217
+ function isEnvelope(raw) {
1218
+ if (!raw || typeof raw !== 'object')
1219
+ return false;
1220
+ const o = raw;
1221
+ if (o['version'] !== CACHE_VERSION || typeof o['nonce'] !== 'string')
1222
+ return false;
1223
+ const providers = o['providers'];
1224
+ if (!providers || typeof providers !== 'object' || Array.isArray(providers))
1225
+ return false;
1226
+ return Object.values(providers).every(p => {
1227
+ if (!p || typeof p !== 'object')
1228
+ return false;
1229
+ const e = p;
1230
+ return typeof e['envFingerprint'] === 'string' && typeof e['index'] === 'string';
1231
+ });
1232
+ }
1233
+ async function readEnvelope(dir) {
1234
+ try {
1235
+ const parsed = JSON.parse(await readFile(join(dir, ENVELOPE_FILE), 'utf-8'));
1236
+ return isEnvelope(parsed) ? parsed : null;
1237
+ }
1238
+ catch {
1239
+ return null;
1240
+ }
1241
+ }
1242
+ function rowTuple(path, row) {
1243
+ const fp = row.fingerprint;
1244
+ return [path, row.day, row.month, row.until, fp.dev, fp.ino, fp.mtimeMs, fp.sizeBytes,
1245
+ row.lo === Infinity ? null : row.lo, row.hi === -Infinity ? null : row.hi, row.flags, row.offset, row.length];
1246
+ }
1247
+ function parseRow(t) {
1248
+ if (!Array.isArray(t) || t.length !== 13)
1249
+ return null;
1250
+ const [path, day, month, until, dev, ino, mtimeMs, sizeBytes, lo, hi, flags, offset, length] = t;
1251
+ if (typeof path !== 'string' || typeof day !== 'string' || typeof month !== 'string' || typeof until !== 'string')
1252
+ return null;
1253
+ if (![dev, ino, mtimeMs, sizeBytes, flags, offset, length].every(isNum))
1254
+ return null;
1255
+ if ((lo !== null && !isNum(lo)) || (hi !== null && !isNum(hi)))
1256
+ return null;
1257
+ return [path, {
1258
+ day, month, until,
1259
+ fingerprint: { dev: dev, ino: ino, mtimeMs: mtimeMs, sizeBytes: sizeBytes },
1260
+ lo: lo === null ? Infinity : lo,
1261
+ hi: hi === null ? -Infinity : hi,
1262
+ flags: flags, offset: offset, length: length,
1263
+ }];
1264
+ }
1265
+ function indexText(pieces, rows) {
1266
+ const tuples = [];
1267
+ for (const [path, row] of rows)
1268
+ tuples.push(rowTuple(path, row));
1269
+ return JSON.stringify({ version: CACHE_VERSION, pieces, rows: tuples });
1270
+ }
1271
+ function textHash(text) {
1272
+ return createHash('sha256').update(text).digest('hex');
1273
+ }
1274
+ // Null when missing or malformed: the provider's files then re-parse, as a lost
1275
+ // v9 shard's did.
1276
+ async function readIndex(dir, name) {
1277
+ if (!name)
1278
+ return null;
1279
+ try {
1280
+ const text = await readFile(join(dir, name), 'utf-8');
1281
+ const parsed = JSON.parse(text);
1282
+ if (parsed.version !== CACHE_VERSION || !parsed.pieces || typeof parsed.pieces !== 'object' || !Array.isArray(parsed.rows))
1283
+ return null;
1284
+ const pieces = parsed.pieces;
1285
+ if (!Object.values(pieces).every(v => typeof v === 'string'))
1286
+ return null;
1287
+ const rows = new Map();
1288
+ for (const t of parsed.rows) {
1289
+ const row = parseRow(t);
1290
+ if (!row)
1291
+ return null;
1292
+ rows.set(row[0], row[1]);
1293
+ }
1294
+ return { index: name, pieces: pieces, rows, hash: textHash(text) };
1295
+ }
1296
+ catch {
1297
+ return null;
1298
+ }
1299
+ }
1300
+ function isKeyList(v) {
1301
+ return Array.isArray(v) && v.every(isStringArray);
1302
+ }
1303
+ async function readKeys(dir, piece) {
1304
+ try {
1305
+ const parsed = JSON.parse(await readFile(join(dir, keysFileName(piece)), 'utf-8'));
1306
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
1307
+ }
1308
+ catch {
1309
+ return null;
1310
+ }
1311
+ }
1312
+ const SHARD_READ_CHUNK = 1 << 20;
1313
+ function splitMemberLine(line) {
1314
+ if (line.charCodeAt(0) !== 34)
1315
+ return null;
1316
+ let i = 1;
1317
+ for (; i < line.length; i++) {
1318
+ const c = line.charCodeAt(i);
1319
+ if (c === 92)
1320
+ i++;
1321
+ else if (c === 34)
1322
+ break;
1323
+ }
1324
+ if (line.charCodeAt(i + 1) !== 58)
1325
+ return null;
1326
+ const end = line.charCodeAt(line.length - 1) === 44 ? line.length - 1 : line.length;
1327
+ return [JSON.parse(line.slice(0, i + 1)), line.slice(i + 2, end)];
1328
+ }
1329
+ function shardLine(text, offset, length) {
1330
+ const split = splitMemberLine(text);
1331
+ if (!split)
1332
+ throw new Error('malformed shard line');
1333
+ return { key: split[0], value: split[1], offset, length };
1334
+ }
1335
+ // A piece's members one at a time, without holding the file. Throws on anything
1336
+ // malformed, as JSON.parse would.
1337
+ async function* shardLines(path) {
1338
+ const handle = await open(path, 'r');
1339
+ try {
1340
+ const head = Buffer.alloc(2);
1341
+ await handle.read(head, 0, 2, 0);
1342
+ if (head[0] !== 0x7b || head[1] !== 0x0a) {
1343
+ if (JSON.stringify(JSON.parse(await readFile(path, 'utf-8'))) === '{}')
1344
+ return;
1345
+ throw new Error('not a line-format shard');
1346
+ }
1347
+ // One reused buffer, and a line that spans reads is carried as decoded text:
1348
+ // per-line Buffers are off-heap memory only a GC returns, which shows up as
1349
+ // RSS when members run to megabytes. A newline is always a character
1350
+ // boundary, so the decoder never holds bytes across one.
1351
+ const chunk = Buffer.allocUnsafe(SHARD_READ_CHUNK);
1352
+ const decoder = new StringDecoder('utf-8');
1353
+ let pos = 2;
1354
+ let lineStart = 2;
1355
+ let pending = '';
1356
+ for (;;) {
1357
+ const { bytesRead } = await handle.read(chunk, 0, SHARD_READ_CHUNK, pos);
1358
+ if (bytesRead === 0)
1359
+ break;
1360
+ const view = chunk.subarray(0, bytesRead);
1361
+ let from = 0;
1362
+ for (let nl = view.indexOf(10); nl !== -1; nl = view.indexOf(10, from)) {
1363
+ const text = pending + decoder.write(view.subarray(from, nl));
1364
+ pending = '';
1365
+ if (text === '}')
1366
+ return;
1367
+ yield shardLine(text, lineStart, pos + nl - lineStart);
1368
+ from = nl + 1;
1369
+ lineStart = pos + from;
1370
+ }
1371
+ if (from < bytesRead)
1372
+ pending += decoder.write(view.subarray(from));
1373
+ pos += bytesRead;
1374
+ }
1375
+ if (pending + decoder.end() !== '}')
1376
+ throw new Error('truncated shard');
1377
+ }
1378
+ finally {
1379
+ await handle.close();
1380
+ }
1381
+ }
1382
+ // The members of any JSON object file as [key, value text], a chunk at a time:
1383
+ // the one-member-per-line form and a single-line object main wrote alike, so a
1384
+ // v9 shard is never one string (or one parse) during the re-layout.
1385
+ async function* objectMembers(path) {
1386
+ const handle = await open(path, 'r');
1387
+ try {
1388
+ const chunk = Buffer.allocUnsafe(SHARD_READ_CHUNK);
1389
+ const decoder = new StringDecoder('utf-8');
1390
+ let depth = 0;
1391
+ let inString = false;
1392
+ let escaped = false;
1393
+ let member = '';
1394
+ let pos = 0;
1395
+ const split = (text) => {
1396
+ const pair = splitMemberLine(text.trim());
1397
+ if (!pair)
1398
+ throw new Error('malformed shard member');
1399
+ return pair;
1400
+ };
1401
+ for (;;) {
1402
+ const { bytesRead } = await handle.read(chunk, 0, SHARD_READ_CHUNK, pos);
1403
+ if (bytesRead === 0)
1404
+ break;
1405
+ pos += bytesRead;
1406
+ const text = decoder.write(chunk.subarray(0, bytesRead));
1407
+ let start = 0;
1408
+ for (let i = 0; i < text.length; i++) {
1409
+ const c = text.charCodeAt(i);
1410
+ if (inString) {
1411
+ if (escaped)
1412
+ escaped = false;
1413
+ else if (c === 92)
1414
+ escaped = true;
1415
+ else if (c === 34)
1416
+ inString = false;
1417
+ }
1418
+ else if (c === 34) {
1419
+ inString = true;
1420
+ }
1421
+ else if (c === 123 || c === 91) {
1422
+ if (depth++ === 0)
1423
+ start = i + 1;
1424
+ }
1425
+ else if (c === 125 || c === 93) {
1426
+ if (--depth === 0) {
1427
+ const last = member + text.slice(start, i);
1428
+ if (last.trim())
1429
+ yield split(last);
1430
+ return;
1431
+ }
1432
+ }
1433
+ else if (c === 44 && depth === 1) {
1434
+ const done = member + text.slice(start, i);
1435
+ member = '';
1436
+ start = i + 1;
1437
+ yield split(done);
1438
+ }
1439
+ }
1440
+ if (depth > 0)
1441
+ member += text.slice(start);
1442
+ }
1443
+ throw new Error('truncated shard');
1444
+ }
1445
+ finally {
1446
+ await handle.close();
1447
+ }
1448
+ }
1449
+ function shardLineText(line) {
1450
+ return `${JSON.stringify(line.key)}:${line.value}`;
1451
+ }
1452
+ function memberText(path, value) {
1453
+ return `${JSON.stringify(path)}:${JSON.stringify(value)}`;
1454
+ }
1455
+ // The writer's side of the format above. `positions`, when given, receives each
1456
+ // member's byte span.
1457
+ async function* shardPayload(members, positions) {
1458
+ let pos = 0;
1459
+ let first = true;
1460
+ for await (const member of members) {
1461
+ const head = first ? '{\n' : ',\n';
1462
+ first = false;
1463
+ if (positions) {
1464
+ const length = Buffer.byteLength(member);
1465
+ positions.push([pos + 2, length]);
1466
+ pos += 2 + length;
1467
+ }
1468
+ yield head + member;
1469
+ }
1470
+ yield first ? '{}' : '\n}';
1471
+ }
1472
+ // A piece that is missing or malformed costs exactly the files it held: those
1473
+ // re-parse while every other piece keeps serving.
1474
+ async function loadShard(path) {
1475
+ try {
1476
+ const files = {};
1477
+ for await (const line of shardLines(path))
1478
+ files[line.key] = JSON.parse(line.value);
1479
+ return validateFiles(files) ? files : null;
1480
+ }
1481
+ catch {
1482
+ return null;
1483
+ }
1484
+ }
1485
+ // The members of `rows` from one piece. Neighbouring members are read together,
1486
+ // up to SHARD_READ_CHUNK a read, into one reused buffer: Buffers are off-heap
1487
+ // memory only a GC returns, which shows up as RSS when members run to megabytes.
1488
+ async function readMembersAt(path, rows, scratch = { buf: Buffer.allocUnsafe(0) }) {
1489
+ const out = new Map();
1490
+ try {
1491
+ const handle = await open(path, 'r');
1492
+ try {
1493
+ const sorted = [...rows].sort((a, b) => a[1].offset - b[1].offset);
1494
+ for (let i = 0; i < sorted.length;) {
1495
+ const from = sorted[i][1].offset;
1496
+ let j = i + 1;
1497
+ while (j < sorted.length && sorted[j][1].offset + sorted[j][1].length - from <= SHARD_READ_CHUNK)
1498
+ j++;
1499
+ const to = sorted[j - 1][1].offset + sorted[j - 1][1].length;
1500
+ if (scratch.buf.length < to - from)
1501
+ scratch.buf = Buffer.allocUnsafe(to - from);
1502
+ const buf = scratch.buf;
1503
+ const { bytesRead } = await handle.read(buf, 0, to - from, from);
1504
+ for (const [key, row] of sorted.slice(i, j)) {
1505
+ const start = row.offset - from;
1506
+ if (start + row.length > bytesRead)
1507
+ continue;
1508
+ const split = splitMemberLine(buf.toString('utf-8', start, start + row.length));
1509
+ if (!split || split[0] !== key)
1510
+ continue;
1511
+ try {
1512
+ const file = JSON.parse(split[1]);
1513
+ if (validateCachedFile(file))
1514
+ out.set(key, file);
1515
+ }
1516
+ catch { /* a malformed member re-parses */ }
1517
+ }
1518
+ i = j;
1519
+ }
1520
+ }
1521
+ finally {
1522
+ await handle.close();
1523
+ }
1524
+ }
1525
+ catch { /* unreadable: the caller treats every wanted member as gone */ }
1526
+ return out;
1527
+ }
1528
+ // Shards a resident process (codeburn serve) keeps parsed between requests,
1529
+ // keyed by shard FILE NAME. A name carries a fresh nonce on every write
1530
+ // (shardFileName), so a name that is still published names the same bytes and
1531
+ // the memo needs no revalidation: a rewritten month arrives under a new name
1532
+ // and the retired one ages out below. This is what makes a period switch stop
1533
+ // re-parsing the months it already read - the whole-cache memo above is keyed
1534
+ // by scope and misses the moment the range widens.
1535
+ // Counted in shard text. A shard the current query scope also holds costs this
1536
+ // memo nothing extra - the same objects are already in the whole-cache memo
1537
+ // above - so this budget only bounds the months NOTHING else is holding, which
1538
+ // is why it is the smaller of the two. Both budgets together have to stay well
1539
+ // under SERVE_MAX_RSS_BYTES: reaching that guard drops every memo, and the next
1540
+ // request pays a cold parse and a cold scan.
1541
+ const SHARD_MEMO_MAX_BYTES = 64 * 1024 * 1024;
1542
+ const SHARD_MEMO_MAX_AGE_MS = 10 * 60 * 1000;
1543
+ const shardMemo = new Map();
1544
+ let shardMemoBytes = 0;
1545
+ export function clearShardMemo() {
1546
+ shardMemo.clear();
1547
+ shardMemoBytes = 0;
1548
+ }
1549
+ export function shardMemoStats() {
1550
+ return { entries: shardMemo.size, bytes: shardMemoBytes };
1551
+ }
1552
+ /// Drop entries unused past the age bound, then least-recently-used entries
1553
+ /// until the byte budget holds. `now` is injected so the rule is testable.
1554
+ export function evictShardMemo(now, maxBytes = SHARD_MEMO_MAX_BYTES) {
1555
+ // Least-recently-used order is the map's own insertion order, because a hit
1556
+ // reinserts its entry at the back; walking from the front therefore evicts the
1557
+ // oldest first and stops as soon as the budget holds.
1558
+ for (const [name, entry] of shardMemo) {
1559
+ if (shardMemoBytes <= maxBytes && now - entry.usedAt <= SHARD_MEMO_MAX_AGE_MS)
1560
+ break;
1561
+ shardMemo.delete(name);
1562
+ shardMemoBytes -= entry.bytes;
1563
+ }
1564
+ }
1565
+ export async function loadShardMemoized(dir, name) {
1566
+ const key = `${dir}\0${name}`;
1567
+ const now = Date.now();
1568
+ const hit = shardMemo.get(key);
1569
+ if (hit) {
1570
+ hit.usedAt = now;
1571
+ shardMemo.delete(key);
1572
+ shardMemo.set(key, hit);
1573
+ return hit.files;
1574
+ }
1575
+ let raw;
1576
+ try {
1577
+ raw = await readFile(join(dir, name), 'utf-8');
1578
+ }
1579
+ catch (err) {
1580
+ // Past the string limit a shard can still be read a member at a time. It is
1581
+ // far over the memo budget, so it is not memoized.
1582
+ return err instanceof RangeError ? loadShard(join(dir, name)) : null;
1583
+ }
1584
+ let files;
1585
+ try {
1586
+ const parsed = JSON.parse(raw);
1587
+ if (!validateFiles(parsed))
1588
+ return null;
1589
+ files = parsed;
1590
+ }
1591
+ catch {
1592
+ return null;
1593
+ }
1594
+ const bytes = Buffer.byteLength(raw);
1595
+ shardMemo.set(key, { files, bytes, usedAt: now });
1596
+ shardMemoBytes += bytes;
1597
+ evictShardMemo(now);
1598
+ return files;
1599
+ }
1600
+ /**
1601
+ * Read the cache. With a `scope`, only the files whose v9 month group the range
1602
+ * can report on are part of the result; with `startMs`/`endMs` as well, those
1603
+ * the range itself cannot report on are held as {@link CacheStub}s built from
1604
+ * the index and the piece key files, and only the members a report reads are
1605
+ * read. Everything else stays on disk and is carried across the next save
1606
+ * untouched (see saveCache). Durable providers and any provider whose recorded
1607
+ * fingerprint no longer matches are always read in full: the first because its
1608
+ * cache is the only surviving record of pruned usage, the second because a
1609
+ * fingerprint change discards the whole section and must see every entry it is
1610
+ * discarding.
1611
+ *
1612
+ * `CODEBURN_CACHE_SCOPE=all` is the escape hatch: it drops the scope here, at
1613
+ * the one place every caller routes through, so a suspect scoped read can be
1614
+ * compared against a full one without a rebuild. It is a READ policy and
1615
+ * deliberately not part of any env fingerprint (PROVIDER_ENV_VARS) — setting or
1616
+ * unsetting it must never invalidate a cache, only change how much of it is read.
1617
+ */
1618
+ export async function loadCache(scope, dropStale = false) {
1619
+ if (process.env['CODEBURN_CACHE_SCOPE'] === 'all')
1620
+ scope = undefined;
1621
+ const dir = sessionCacheDir();
1622
+ let envelope = await readEnvelope(dir);
1623
+ if (!envelope) {
1624
+ // A process that loses the re-layout race reads the winner's publish.
1625
+ await migrateMonthShardCache(dir);
1626
+ envelope = await readEnvelope(dir);
1627
+ }
1628
+ if (!envelope)
1629
+ return afterMissingShardCache();
1630
+ const scopeKey = scope ? `${scope.fromMonth}..${scope.toMonth}` : 'all';
1631
+ if (cacheMemo && cacheMemo.dir === dir && cacheMemo.nonce === envelope.nonce
1632
+ && (cacheMemo.scope === 'all' || cacheMemo.scope === scopeKey)) {
1633
+ if (scope)
1634
+ await coverRange(cacheMemo.cache, scope.startMs ?? -Infinity, scope.endMs ?? Infinity);
1635
+ return cacheMemo.cache;
1636
+ }
1637
+ // Released before the new view is read, so the two are never held at once.
1638
+ cacheMemo = null;
1639
+ const cache = { version: CACHE_VERSION, providers: {}, complete: envelope.complete === true };
1640
+ const state = stateOf(cache);
1641
+ state.dir = dir;
1642
+ state.nonce = envelope.nonce;
1643
+ const ranged = scope?.startMs !== undefined && scope.endMs !== undefined
1644
+ ? { startMs: scope.startMs, endMs: scope.endMs }
1645
+ : null;
1646
+ const reads = [];
1647
+ for (const [provider, meta] of Object.entries(envelope.providers)) {
1648
+ if (RETIRED_PROVIDER_NAMES.has(provider)) {
1649
+ // Kept only in the base, so the next save leaves it out of the envelope
1650
+ // and deletes its index and pieces.
1651
+ state.base.set(provider, await readIndex(dir, meta.index) ?? { ...emptyBase(), index: meta.index });
1652
+ state.dirty = true;
1653
+ continue;
1654
+ }
1655
+ const section = {
1656
+ envFingerprint: meta.envFingerprint,
1657
+ files: {},
1658
+ ...(meta.durable ? { durable: true } : {}),
1659
+ ...(meta.complete === true ? { complete: true } : {}),
1660
+ ...(typeof meta.completeFrom === 'number' ? { completeFrom: meta.completeFrom } : {}),
1661
+ };
1662
+ // Recorded even when every file is skipped or unreadable: the section is
1663
+ // what tells the next save which provider the carried rows belong to, and
1664
+ // what stops the reconcile from re-parsing under a fingerprint the envelope
1665
+ // already agrees with.
1666
+ cache.providers[provider] = section;
1667
+ state.fingerprints.set(provider, meta.envFingerprint);
1668
+ // Durable providers are ALWAYS loaded in full, by name as well as by the
1669
+ // envelope flag: copilot's serve-time reconciliation pairs store rows and
1670
+ // retires residuals over the complete cached serve set, so a scoped load
1671
+ // of a copilot section persisted before the durable stamp landed would
1672
+ // make pairing range-dependent. The name check closes that window.
1673
+ const durable = meta.durable === true || DURABLE_PROVIDER_NAMES.has(provider);
1674
+ const stale = meta.envFingerprint !== computeEnvFingerprint(provider);
1675
+ const full = !scope || durable || stale;
1676
+ const stubbed = !full && ranged !== null && !FULL_LOAD_PROVIDER_NAMES.has(provider);
1677
+ if (stubbed)
1678
+ state.covered = ranged;
1679
+ reads.push(loadProvider(state, provider, section, meta.index, full ? null : scope, stubbed ? ranged : null, dropStale && stale && !durable));
1680
+ }
1681
+ await Promise.all(reads);
1682
+ state.scope = scopeKey;
1683
+ cacheMemo = { dir, nonce: envelope.nonce, scope: scopeKey, cache };
1684
+ return cache;
1685
+ }
1686
+ // The months of `rows` a query over `scope` reports on: a v9 shard's span was
1687
+ // its oldest file's month to its newest file's `until`.
1688
+ function visibleMonths(rows, scope) {
1689
+ const until = new Map();
1690
+ for (const row of rows.values()) {
1691
+ const seen = until.get(row.month);
1692
+ if (seen === undefined || row.until > seen)
1693
+ until.set(row.month, row.until);
1694
+ }
1695
+ const visible = new Set([UNDATED_BUCKET]);
1696
+ for (const [month, last] of until)
1697
+ if (shardInScope(month, last, scope))
1698
+ visible.add(month);
1699
+ return visible;
1700
+ }
1701
+ async function loadProvider(state, provider, section, indexName, scope, ranged, stale = false) {
1702
+ const index = await readIndex(state.dir, indexName);
1703
+ const base = index ?? emptyBase();
1704
+ state.base.set(provider, base);
1705
+ // Unreadable: its files re-parse, and the save publishes a fresh index.
1706
+ if (!index)
1707
+ markPathDirty(state, provider, ALL_PATHS);
1708
+ const visible = scope ? visibleMonths(base.rows, scope) : null;
1709
+ state.visible.set(provider, visible);
1710
+ const stubs = ranged ? new Map() : undefined;
1711
+ if (stubs)
1712
+ state.stubs.set(provider, { section, byPath: stubs });
1713
+ const hidden = new Map();
1714
+ state.hidden.set(provider, { section, byPath: hidden });
1715
+ const inFull = new Map();
1716
+ const asStubs = new Map();
1717
+ for (const [path, row] of base.rows) {
1718
+ // The parser replaces a stale section on first use, keeping only entries
1719
+ // whose source is gone or that are durable (getOrCreateProviderSection), so
1720
+ // other present ones stay on disk.
1721
+ if ((visible && !visible.has(row.month)) || (stale && !isDurableCachedSource(provider, path, (row.flags & ROW_DURABLE) !== 0) && existsSync(path)))
1722
+ hidden.set(path, row);
1723
+ else if (!ranged || fileNeeded(path, row, ranged.startMs, ranged.endMs))
1724
+ pushTo(inFull, row.day, [path, row]);
1725
+ else
1726
+ pushTo(asStubs, row.day, [path, row]);
1727
+ }
1728
+ const members = new Map();
1729
+ // A member or key list that cannot be read is dirtied without an entry: the
1730
+ // save drops its line and the file re-parses like any uncached one.
1731
+ // A full read takes every piece at once, as v9 read its shards; a ranged one
1732
+ // goes piece by piece, so it holds one read buffer at a time.
1733
+ const whole = ranged ? [] : [...inFull.keys()].map(day => base.pieces[day] ? loadShardMemoized(state.dir, base.pieces[day]) : null);
1734
+ const scratch = { buf: Buffer.allocUnsafe(0) };
1735
+ for (const [i, [day, rows]] of [...inFull].entries()) {
1736
+ const name = base.pieces[day];
1737
+ let files = null;
1738
+ if (!ranged)
1739
+ files = await whole[i] ?? null;
1740
+ else if (name)
1741
+ files = await readMembersAt(join(state.dir, name), rows, scratch);
1742
+ for (const [path] of rows) {
1743
+ const file = files instanceof Map ? files.get(path) : files?.[path];
1744
+ if (file)
1745
+ members.set(path, file);
1746
+ else
1747
+ markPathDirty(state, provider, path);
1748
+ }
1749
+ }
1750
+ for (const [day, rows] of asStubs) {
1751
+ const lists = base.pieces[day] ? await readKeyLists(state.dir, base.pieces[day], rows) : null;
1752
+ for (const [path, row] of rows) {
1753
+ const list = lists?.get(path);
1754
+ if (!list) {
1755
+ markPathDirty(state, provider, path);
1756
+ continue;
1757
+ }
1758
+ members.set(path, { fingerprint: row.fingerprint, hasPr: (row.flags & ROW_PR) !== 0, keys: list, lo: row.lo, hi: row.hi, seq: 0 });
1759
+ }
1760
+ }
1761
+ let seq = 0;
1762
+ for (const path of base.rows.keys()) {
1763
+ const entry = members.get(path);
1764
+ const at = seq++;
1765
+ if (!entry)
1766
+ continue;
1767
+ if (isCacheStub(entry)) {
1768
+ entry.seq = at;
1769
+ stubs.set(path, entry);
1770
+ }
1771
+ else {
1772
+ if (stubs)
1773
+ state.seq.set(entry, at);
1774
+ section.files[path] = entry;
1775
+ }
1776
+ }
1777
+ }
1778
+ // The piece directory is absent/unreadable. Prefer a LOSSLESS re-layout of the
1779
+ // newest prior layout that is present (v9 is handled by loadCache itself, then
1780
+ // v8 provider shards, then the v7 single file — all hold the current turn shape,
1781
+ // so nothing re-parses); failing that, adopt the prior versions' expired-source
1782
+ // PR orphans, then the legacy unversioned file. Either way the piece directory
1783
+ // is minted on the next save.
1784
+ async function afterMissingShardCache() {
1785
+ const relaid = await migrateProviderShardCache() ?? await migrateSingleFileCache();
1786
+ if (relaid)
1787
+ return relaid;
1788
+ const prior = await adoptNewestPriorCache();
1789
+ if (prior)
1790
+ return prior;
1791
+ // validateCache requires the version to match, so a different-version legacy
1792
+ // file is ignored (left intact). We copy it into the piece layout once via
1793
+ // saveCache; the legacy file is never modified.
1794
+ return adoptLegacyCache();
1795
+ }
1796
+ // Migration appends each member to its day piece as it arrives. Only this many
1797
+ // pieces are held open at once; a piece closed early is reopened for append.
1798
+ const MIGRATION_OPEN_PIECES = 32;
1799
+ // One-time, lossless re-layout of the v9 month shards into day pieces. It
1800
+ // streams: every shard is read a member at a time (a single-line shard main
1801
+ // wrote included) and each member is appended, verbatim, to its piece, so the
1802
+ // peak is one member plus the open pieces, never the cache. Rows keep v9's full
1803
+ // load order. Publishing the v10 envelope commits it; the v9 directory is
1804
+ // removed only after that.
1805
+ async function migrateMonthShardCache(dir) {
1806
+ const v9 = join(getCodeburnCacheDir(), MONTH_SHARD_DIR_NAME);
1807
+ let prior;
1808
+ try {
1809
+ const parsed = JSON.parse(await readFile(join(v9, ENVELOPE_FILE), 'utf-8'));
1810
+ if (parsed['version'] !== 9 || !parsed['providers'] || typeof parsed['providers'] !== 'object')
1811
+ return false;
1812
+ prior = parsed;
1813
+ }
1814
+ catch {
1815
+ return false;
1816
+ }
1817
+ const written = [];
1818
+ const open_ = new Map();
1819
+ const closeOne = async (day) => {
1820
+ const handles = open_.get(day);
1821
+ open_.delete(day);
1822
+ for (const handle of handles ?? []) {
1823
+ await handle.sync();
1824
+ await handle.close();
1825
+ }
1826
+ };
1827
+ try {
1828
+ if (!existsSync(dir))
1829
+ await mkdir(dir, { recursive: true, mode: 0o700 });
1830
+ const providers = {};
1831
+ for (const [provider, meta] of Object.entries(prior.providers)) {
1832
+ const shards = meta?.['shards'];
1833
+ if (typeof meta?.['envFingerprint'] !== 'string' || !shards || typeof shards !== 'object')
1834
+ continue;
1835
+ const rows = new Map();
1836
+ const sinks = new Map();
1837
+ const stale = new Set();
1838
+ const append = async (day, key, value, keys) => {
1839
+ let sink = sinks.get(day);
1840
+ if (!sink) {
1841
+ sink = { name: pieceFileName(provider, day), pos: 0, count: 0 };
1842
+ sinks.set(day, sink);
1843
+ written.push(sink.name, keysFileName(sink.name));
1844
+ }
1845
+ let handles = open_.get(day);
1846
+ if (handles) {
1847
+ open_.delete(day);
1848
+ }
1849
+ else {
1850
+ if (open_.size >= MIGRATION_OPEN_PIECES)
1851
+ await closeOne(open_.keys().next().value);
1852
+ handles = [await open(join(dir, sink.name), 'a', 0o600), await open(join(dir, keysFileName(sink.name)), 'a', 0o600)];
1853
+ }
1854
+ open_.set(day, handles);
1855
+ const head = sink.count === 0 ? '{\n' : ',\n';
1856
+ const line = `${JSON.stringify(key)}:${value}`;
1857
+ await handles[0].write(head + line);
1858
+ await handles[1].write(head + memberText(key, keys));
1859
+ const offset = sink.pos + 2;
1860
+ const length = Buffer.byteLength(line);
1861
+ sink.pos = offset + length;
1862
+ sink.count++;
1863
+ return [offset, length];
1864
+ };
1865
+ for (const ref of Object.values(shards)) {
1866
+ const name = ref?.name;
1867
+ if (typeof name !== 'string')
1868
+ continue;
1869
+ try {
1870
+ for await (const [key, value] of objectMembers(join(v9, name))) {
1871
+ const file = JSON.parse(value);
1872
+ if (!validateCachedFile(file))
1873
+ continue;
1874
+ // A path in two shards resolves to the freshest copy, at the first
1875
+ // copy's place, as a v9 load did.
1876
+ const seen = rows.get(key);
1877
+ if (seen && seen.fingerprint.mtimeMs >= file.fingerprint.mtimeMs)
1878
+ continue;
1879
+ if (seen)
1880
+ stale.add(seen.day);
1881
+ const row = rowFor(key, file);
1882
+ const [offset, length] = await append(row.day, key, value, keysOf(file));
1883
+ rows.set(key, { ...row, offset, length });
1884
+ }
1885
+ }
1886
+ catch { /* an unreadable shard costs the files it still held, as on v9 */ }
1887
+ }
1888
+ for (const [day, sink] of sinks) {
1889
+ let handles = open_.get(day);
1890
+ if (!handles)
1891
+ handles = [await open(join(dir, sink.name), 'a', 0o600), await open(join(dir, keysFileName(sink.name)), 'a', 0o600)];
1892
+ open_.set(day, handles);
1893
+ await handles[0].write('\n}');
1894
+ await handles[1].write('\n}');
1895
+ await closeOne(day);
1896
+ }
1897
+ // A piece still holding a duplicate's stale line is rewritten without it.
1898
+ for (const day of stale) {
1899
+ const sink = sinks.get(day);
1900
+ const dayRows = [...rows].filter(([, row]) => row.day === day);
1901
+ if (dayRows.length === 0)
1902
+ sinks.delete(day);
1903
+ const piece = await writePiece(dir, provider, day, sink.name, dayRows, {}, new Map(), written);
1904
+ for (const [path, row] of dayRows) {
1905
+ const span = piece.spans.get(path);
1906
+ if (span)
1907
+ rows.set(path, { ...row, offset: span[0], length: span[1] });
1908
+ }
1909
+ for (const name of [sink.name, keysFileName(sink.name)])
1910
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
1911
+ sink.name = piece.name;
1912
+ }
1913
+ const index = indexFileName(provider);
1914
+ await writeFileAtomic(join(dir, index), indexText(Object.fromEntries([...sinks].map(([day, sink]) => [day, sink.name])), rows));
1915
+ written.push(index);
1916
+ providers[provider] = {
1917
+ envFingerprint: meta['envFingerprint'],
1918
+ ...(meta['durable'] === true ? { durable: true } : {}),
1919
+ ...(meta['complete'] === true ? { complete: true } : {}),
1920
+ ...(isNum(meta['completeFrom']) ? { completeFrom: meta['completeFrom'] } : {}),
1921
+ index,
1922
+ };
1923
+ await yieldToEventLoop();
1924
+ }
1925
+ if (await readEnvelope(dir))
1926
+ throw new Error('another process published first');
1927
+ const envelope = { version: CACHE_VERSION, complete: prior.complete === true, nonce: randomBytes(8).toString('hex'), providers };
1928
+ await writeFileAtomic(join(dir, ENVELOPE_FILE), JSON.stringify(envelope));
1929
+ }
1930
+ catch {
1931
+ for (const day of [...open_.keys()])
1932
+ await closeOne(day).catch(() => { });
1933
+ for (const name of written)
1934
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
1935
+ return false;
1936
+ }
1937
+ await retryCacheFileMutation(() => rm(v9, { recursive: true, force: true }));
1938
+ return true;
1939
+ }
1940
+ // One-time, lossless re-layout of the v8 per-provider shard directory: v8's
1941
+ // turn shape is the current one, so every entry moves across verbatim and
1942
+ // nothing re-parses. The v8 directory is removed only once the save has
1943
+ // published.
1944
+ async function migrateProviderShardCache() {
1945
+ const dir = join(getCodeburnCacheDir(), PRIOR_SHARD_DIR_NAME);
1946
+ let envelope;
1947
+ try {
1948
+ const parsed = JSON.parse(await readFile(join(dir, ENVELOPE_FILE), 'utf-8'));
1949
+ if (parsed['version'] !== 8 || !parsed['shards'] || typeof parsed['shards'] !== 'object')
1950
+ return null;
1951
+ envelope = parsed;
1952
+ }
1953
+ catch {
1954
+ return null;
1955
+ }
1956
+ const cache = { version: CACHE_VERSION, providers: {}, complete: envelope.complete === true };
1957
+ await Promise.all(Object.entries(envelope.shards).map(async ([provider, name]) => {
1958
+ try {
1959
+ const parsed = JSON.parse(await readFile(join(dir, name), 'utf-8'));
1960
+ if (validateProviderSection(parsed))
1961
+ cache.providers[provider] = parsed;
1962
+ }
1963
+ catch { /* one unreadable v8 shard costs that provider, as it already did */ }
1964
+ }));
1965
+ return publishRelaidCache(cache, () => rm(dir, { recursive: true, force: true }));
1966
+ }
1967
+ // One-time, lossless re-layout of the v7 single-file cache. v7 never wrote a
1968
+ // shard directory, so it is migrated straight to the current layout.
1969
+ async function migrateSingleFileCache() {
1970
+ const v7Path = join(getCodeburnCacheDir(), priorCacheFile(7));
1971
+ let parsed;
1972
+ try {
1973
+ parsed = JSON.parse(await readFile(v7Path, 'utf-8'));
1974
+ }
1975
+ catch {
1976
+ return null;
1977
+ }
1978
+ if (!validateCache(parsed, 7))
1979
+ return null;
1980
+ return publishRelaidCache({ version: CACHE_VERSION, providers: parsed.providers, complete: parsed.complete === true }, () => unlink(v7Path));
1981
+ }
1982
+ // Every section is marked dirty so the save writes every piece; the old layout
1983
+ // is retired only once that save has published.
1984
+ async function publishRelaidCache(cache, retire) {
1985
+ for (const provider of Object.keys(cache.providers))
1986
+ markCacheDirty(cache, provider);
1987
+ const published = await saveCache(cache).catch(() => false);
1988
+ if (published)
1989
+ await retryCacheFileMutation(async () => { await retire(); });
1990
+ return cache;
1991
+ }
1992
+ async function adoptLegacyCache() {
1993
+ try {
1994
+ const raw = await readFile(getLegacyCachePath(), 'utf-8');
1995
+ const parsed = JSON.parse(raw);
1996
+ if (!validateCache(parsed, CACHE_VERSION))
1997
+ return emptyCache();
1998
+ for (const provider of Object.keys(parsed.providers))
1999
+ markCacheDirty(parsed, provider);
2000
+ await saveCache(parsed).catch(() => { });
2001
+ return parsed;
2002
+ }
2003
+ catch {
2004
+ return emptyCache();
2005
+ }
2006
+ }
2007
+ // File names carry a fresh nonce on every write, so a save never overwrites a
2008
+ // file the currently-published envelope points at: readers keep seeing a
2009
+ // consistent set until the envelope rename publishes the new one, and a writer
2010
+ // that loses the ownership fence leaves the canonical files untouched.
2011
+ function providerFilePart(provider) {
2012
+ return provider.replace(/[^A-Za-z0-9_-]/g, '_');
2013
+ }
2014
+ function pieceFileName(provider, day) {
2015
+ return `${providerFilePart(provider)}.${day}.${randomBytes(8).toString('hex')}.json`;
2016
+ }
2017
+ function keysFileName(piece) {
2018
+ return piece.replace(/\.json$/, '.keys.json');
2019
+ }
2020
+ function indexFileName(provider) {
2021
+ return `index.${providerFilePart(provider)}.${randomBytes(8).toString('hex')}.json`;
2022
+ }
2023
+ // The temp name carries a nonce: two processes writing the SAME final path
2024
+ // (the envelope, every save) would otherwise share one temp file and interleave
2025
+ // their writes into a torn or foreign payload.
2026
+ async function writeFileAtomic(finalPath, payload, sync = true) {
2027
+ const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`;
2028
+ const handle = await open(tempPath, 'w', 0o600);
2029
+ try {
2030
+ if (typeof payload === 'string') {
2031
+ await handle.writeFile(payload, { encoding: 'utf-8' });
2032
+ }
2033
+ else {
2034
+ let pending = '';
2035
+ for await (const chunk of payload) {
2036
+ pending += chunk;
2037
+ if (pending.length < SHARD_READ_CHUNK)
2038
+ continue;
2039
+ await handle.writeFile(pending, { encoding: 'utf-8' });
2040
+ pending = '';
2041
+ }
2042
+ if (pending)
2043
+ await handle.writeFile(pending, { encoding: 'utf-8' });
2044
+ }
2045
+ if (sync)
2046
+ await handle.sync();
2047
+ }
2048
+ finally {
2049
+ await handle.close();
2050
+ }
2051
+ try {
2052
+ for (let attempt = 0; attempt < 3; attempt++) {
2053
+ try {
2054
+ await rename(tempPath, finalPath);
2055
+ return;
2056
+ }
2057
+ catch (err) {
2058
+ const code = err.code;
2059
+ if ((code !== 'EPERM' && code !== 'EBUSY') || attempt === 2)
2060
+ throw err;
2061
+ await new Promise(resolve => { setTimeout(resolve, 10 * (attempt + 1)); });
2062
+ }
2063
+ }
2064
+ }
2065
+ catch (err) {
2066
+ await retryCacheFileMutation(() => unlink(tempPath));
2067
+ throw err;
2068
+ }
2069
+ }
2070
+ // Surrender the event loop without microtask overhead. Used inside saveCache
2071
+ // between piece writes so an interactive TTY's stdin handler (Ink's useInput)
2072
+ // can run while a long save publishes a 21k-file cache (#1141).
2073
+ function yieldToEventLoop() {
2074
+ return new Promise(resolve => setImmediate(resolve));
2075
+ }
2076
+ // The order a v9 save would leave these files in, which is the order the next
2077
+ // full load holds them in (see IndexRow). v9 kept files in month shards: a
2078
+ // month the load read is rewritten from memory in load order, a month it did
2079
+ // not read that gained a file (a re-parse) keeps its published order with the
2080
+ // new file after it, behind every month the load read, and the months it
2081
+ // neither read nor touched follow as they were.
2082
+ function nextOrder(base, rows, loadOrder, visible) {
2083
+ const read = (month) => visible === null || visible.has(month);
2084
+ const before = new Map();
2085
+ for (const [path, row] of base)
2086
+ pushTo(before, row.month, path);
2087
+ const now = new Map();
2088
+ for (const path of loadOrder) {
2089
+ const row = rows.get(path);
2090
+ if (row)
2091
+ pushTo(now, row.month, path);
2092
+ }
2093
+ const out = [];
2094
+ const placed = new Set();
2095
+ const put = (path) => {
2096
+ if (placed.has(path) || !rows.has(path))
2097
+ return;
2098
+ placed.add(path);
2099
+ out.push(path);
2100
+ };
2101
+ const stayed = (month) => (path) => { if (rows.get(path)?.month === month)
2102
+ put(path); };
2103
+ for (const [month, paths] of now)
2104
+ if (!before.has(month) || read(month))
2105
+ paths.forEach(put);
2106
+ for (const [month, paths] of now) {
2107
+ if (!before.has(month) || read(month))
2108
+ continue;
2109
+ before.get(month).forEach(stayed(month));
2110
+ paths.forEach(put);
2111
+ }
2112
+ for (const [month, paths] of before)
2113
+ if (!now.has(month) && !read(month))
2114
+ paths.forEach(stayed(month));
2115
+ // Rows this process never held (a concurrent writer's), then anything left.
2116
+ for (const path of base.keys())
2117
+ put(path);
2118
+ for (const path of rows.keys())
2119
+ put(path);
2120
+ return out;
2121
+ }
2122
+ // Rewrite one piece: the lines of rows that stay are copied from the published
2123
+ // piece, the rest come from memory. A piece whose lines all come out the same
2124
+ // keeps its published name (#1032). Returns each written row's byte span; a
2125
+ // row the published piece no longer holds has none.
2126
+ async function writePiece(dir, provider, day, from, rows, files, fromMemory, written) {
2127
+ const copied = new Map();
2128
+ const pending = new Map();
2129
+ for (const [path, row] of rows) {
2130
+ if (fromMemory.has(path))
2131
+ pending.set(path, files[path]);
2132
+ else
2133
+ copied.set(path, row);
2134
+ }
2135
+ const baseKeys = from && copied.size > 0 ? await readKeys(dir, from) : null;
2136
+ const order = [];
2137
+ const keyLines = [];
2138
+ let changed = !from;
2139
+ const members = async function* () {
2140
+ if (from) {
2141
+ try {
2142
+ for await (const line of shardLines(join(dir, from))) {
2143
+ const file = pending.get(line.key);
2144
+ const row = copied.get(line.key);
2145
+ if (file) {
2146
+ pending.delete(line.key);
2147
+ const text = memberText(line.key, file);
2148
+ if (text !== shardLineText(line))
2149
+ changed = true;
2150
+ order.push(line.key);
2151
+ keyLines.push(memberText(line.key, keysOf(file)));
2152
+ yield text;
2153
+ }
2154
+ else if (row && row.offset === line.offset) {
2155
+ copied.delete(line.key);
2156
+ const keys = baseKeys?.[line.key];
2157
+ order.push(line.key);
2158
+ keyLines.push(memberText(line.key, isKeyList(keys) ? keys : keysOf(JSON.parse(line.value))));
2159
+ yield shardLineText(line);
2160
+ }
2161
+ else {
2162
+ changed = true;
2163
+ }
2164
+ }
2165
+ }
2166
+ catch {
2167
+ changed = true;
2168
+ }
2169
+ }
2170
+ for (const [path, file] of pending) {
2171
+ changed = true;
2172
+ order.push(path);
2173
+ keyLines.push(memberText(path, keysOf(file)));
2174
+ yield memberText(path, file);
2175
+ }
2176
+ };
2177
+ const name = pieceFileName(provider, day);
2178
+ const positions = [];
2179
+ await writeFileAtomic(join(dir, name), shardPayload(members(), positions));
2180
+ const spans = new Map(order.map((path, i) => [path, positions[i]]));
2181
+ if (!changed && copied.size === 0) {
2182
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
2183
+ return { name: from, spans };
2184
+ }
2185
+ written.push(name);
2186
+ await writeFileAtomic(join(dir, keysFileName(name)), shardPayload(keyLines), false);
2187
+ written.push(keysFileName(name));
2188
+ return { name, spans };
2189
+ }
2190
+ // One provider's part of a save: rows changed in memory (dirty paths) over the
2191
+ // rows of `base`, the pieces those changes touch rewritten, the rest kept.
2192
+ async function saveProvider(dir, state, cache, provider, section, base, reset, written) {
2193
+ const dirty = state.dirtyPaths.get(provider);
2194
+ const all = dirty?.has(ALL_PATHS) === true;
2195
+ const isDirty = (path) => all || dirty?.has(path) === true;
2196
+ const stubs = stubsOf(state, cache, provider);
2197
+ const hidden = hiddenOf(state, cache, provider);
2198
+ const priorRows = reset ? new Map() : base.rows;
2199
+ const rows = new Map();
2200
+ const fromMemory = new Map();
2201
+ const touched = new Set();
2202
+ for (const [path, row] of priorRows) {
2203
+ if (!isDirty(path) || (!section.files[path] && (stubs?.has(path) || hidden?.has(path))))
2204
+ rows.set(path, row);
2205
+ else if (!section.files[path])
2206
+ touched.add(row.day);
2207
+ }
2208
+ for (const [path, file] of Object.entries(section.files)) {
2209
+ const prior = priorRows.get(path);
2210
+ if (prior && !isDirty(path))
2211
+ continue;
2212
+ const row = rowFor(path, file);
2213
+ rows.set(path, row);
2214
+ fromMemory.set(path, row);
2215
+ touched.add(row.day);
2216
+ if (prior)
2217
+ touched.add(prior.day);
2218
+ }
2219
+ const order = nextOrder(priorRows, rows, entriesInLoadOrder(state, section, stubs).map(([path]) => path), reset ? null : state.visible.get(provider) ?? null);
2220
+ const byDay = new Map();
2221
+ for (const path of order)
2222
+ pushTo(byDay, rows.get(path).day, [path, rows.get(path)]);
2223
+ const priorPieces = reset ? {} : base.pieces;
2224
+ const pieces = {};
2225
+ const retire = [];
2226
+ const lost = new Set();
2227
+ const spansOf = new Map();
2228
+ for (const [day, name] of Object.entries(base.pieces))
2229
+ if (reset || !byDay.has(day))
2230
+ retire.push(name);
2231
+ for (const [day, dayRows] of byDay) {
2232
+ const from = priorPieces[day];
2233
+ if (from && !touched.has(day)) {
2234
+ pieces[day] = from;
2235
+ continue;
2236
+ }
2237
+ const piece = await writePiece(dir, provider, day, from, dayRows, section.files, fromMemory, written);
2238
+ pieces[day] = piece.name;
2239
+ if (from && piece.name !== from)
2240
+ retire.push(from);
2241
+ for (const [path] of dayRows) {
2242
+ const span = piece.spans.get(path);
2243
+ if (span)
2244
+ spansOf.set(path, span);
2245
+ else
2246
+ lost.add(path);
2247
+ }
2248
+ await yieldToEventLoop();
2249
+ }
2250
+ const finalRows = new Map();
2251
+ for (const path of order) {
2252
+ if (lost.has(path))
2253
+ continue;
2254
+ const row = rows.get(path);
2255
+ const span = spansOf.get(path);
2256
+ finalRows.set(path, span && (span[0] !== row.offset || span[1] !== row.length) ? { ...row, offset: span[0], length: span[1] } : row);
2257
+ }
2258
+ if (lost.size > 0) {
2259
+ const held = new Set([...finalRows.values()].map(row => row.day));
2260
+ for (const day of byDay.keys())
2261
+ if (!held.has(day)) {
2262
+ retire.push(pieces[day]);
2263
+ delete pieces[day];
2264
+ }
2265
+ }
2266
+ const text = indexText(pieces, finalRows);
2267
+ const hash = textHash(text);
2268
+ let index = base.index;
2269
+ if (reset || !index || hash !== base.hash) {
2270
+ index = indexFileName(provider);
2271
+ await writeFileAtomic(join(dir, index), text);
2272
+ written.push(index);
2273
+ if (base.index)
2274
+ retire.push(base.index);
2275
+ }
2276
+ return { index, pieces, rows: finalRows, hash, retire, lost };
2277
+ }
2278
+ export async function saveCache(cache, verifyStillOwner) {
2279
+ const dir = sessionCacheDir();
2280
+ if (!existsSync(dir))
2281
+ await mkdir(dir, { recursive: true, mode: 0o700 });
2282
+ const state = stateOf(cache);
2283
+ for (let attempt = 0;; attempt++) {
2284
+ const written = [];
2285
+ try {
2286
+ // Another process may have published since this cache was read. Its
2287
+ // envelope is then the base: what this process did not change stays as
2288
+ // that process left it, and what it did change is applied on top.
2289
+ const live = await readEnvelope(dir);
2290
+ const rebased = live !== null && live.nonce !== state.nonce;
2291
+ const saves = new Map();
2292
+ for (const [provider, section] of Object.entries(cache.providers)) {
2293
+ const base = rebased
2294
+ ? await readIndex(dir, live.providers[provider]?.index) ?? emptyBase()
2295
+ : state.base.get(provider) ?? emptyBase();
2296
+ const baseFingerprint = rebased ? live.providers[provider]?.envFingerprint : state.fingerprints.get(provider);
2297
+ // A fingerprint change discards the section outright (see
2298
+ // getOrCreateProviderSection), so nothing is carried from the base.
2299
+ const reset = baseFingerprint !== undefined && baseFingerprint !== section.envFingerprint;
2300
+ saves.set(provider, await saveProvider(dir, state, cache, provider, section, base, reset, written));
2301
+ }
2302
+ // One optimistic retry when a publish landed while this one was being
2303
+ // built: redone from that publish. The remaining window is the envelope
2304
+ // rename below; a save that loses it has its changes re-derived by the
2305
+ // next parse (the reconcile finds no row and re-reads the file).
2306
+ if (attempt === 0 && (await readEnvelope(dir))?.nonce !== live?.nonce) {
2307
+ for (const name of written)
2308
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
2309
+ continue;
2310
+ }
2311
+ // The warm refresh transaction passes an ownership fence. It must be the
2312
+ // final operation before publication so a displaced writer cannot replace
2313
+ // the canonical cache with its stale snapshot. Files written above are
2314
+ // unreferenced until the envelope names them, so a lost fence publishes
2315
+ // nothing.
2316
+ if (verifyStillOwner && !await verifyStillOwner()) {
2317
+ for (const name of written)
2318
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
2319
+ return false;
2320
+ }
2321
+ const providers = {};
2322
+ for (const [provider, save] of saves) {
2323
+ const section = cache.providers[provider];
2324
+ providers[provider] = {
2325
+ envFingerprint: section.envFingerprint,
2326
+ ...(section.durable ? { durable: true } : {}),
2327
+ ...(section.complete === true ? { complete: true } : {}),
2328
+ ...(section.completeFrom !== undefined ? { completeFrom: section.completeFrom } : {}),
2329
+ index: save.index,
2330
+ };
2331
+ }
2332
+ const envelope = {
2333
+ version: CACHE_VERSION,
2334
+ complete: cache.complete === true,
2335
+ nonce: randomBytes(8).toString('hex'),
2336
+ providers,
2337
+ };
2338
+ await writeFileAtomic(join(dir, ENVELOPE_FILE), JSON.stringify(envelope));
2339
+ // Files the new envelope no longer references are garbage; a reader that
2340
+ // already opened one keeps reading it, and any failure here is swept later
2341
+ // by cleanupOrphanedTempFiles.
2342
+ const retired = new Set();
2343
+ for (const save of saves.values())
2344
+ for (const name of save.retire)
2345
+ retired.add(name);
2346
+ for (const [provider, base] of state.base) {
2347
+ if (saves.has(provider))
2348
+ continue;
2349
+ if (base.index)
2350
+ retired.add(base.index);
2351
+ for (const name of Object.values(base.pieces))
2352
+ retired.add(name);
2353
+ }
2354
+ state.dirty = false;
2355
+ state.dirtyPaths.clear();
2356
+ state.base.clear();
2357
+ state.fingerprints.clear();
2358
+ state.nonce = envelope.nonce;
2359
+ for (const [provider, save] of saves) {
2360
+ state.base.set(provider, { index: save.index, pieces: save.pieces, rows: save.rows, hash: save.hash });
2361
+ state.fingerprints.set(provider, envelope.providers[provider].envFingerprint);
2362
+ const section = cache.providers[provider];
2363
+ const hidden = hiddenOf(state, cache, provider);
2364
+ const stubs = stubsOf(state, cache, provider);
2365
+ for (const path of save.lost) {
2366
+ hidden?.delete(path);
2367
+ stubs?.delete(path);
2368
+ }
2369
+ if (!stubs)
2370
+ continue;
2371
+ // Load order continues as it stood in memory, as it does for v9's
2372
+ // in-memory `files` after a save.
2373
+ let seq = 0;
2374
+ for (const [, entry] of entriesInLoadOrder(state, section, stubs)) {
2375
+ if (isCacheStub(entry))
2376
+ entry.seq = seq++;
2377
+ else
2378
+ state.seq.set(entry, seq++);
2379
+ }
2380
+ }
2381
+ // Write-through: the object just published IS the freshest state, so the
2382
+ // next loadCache in this process reuses it instead of re-reading. Its
2383
+ // scope is whatever was loaded, not `all` — a save never widens what is
2384
+ // in memory.
2385
+ cacheMemo = { dir, nonce: envelope.nonce, scope: state.scope, cache };
2386
+ for (const name of retired) {
2387
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
2388
+ if (!name.startsWith('index.'))
2389
+ await retryCacheFileMutation(() => unlink(join(dir, keysFileName(name))));
2390
+ }
2391
+ return true;
2392
+ }
2393
+ catch (err) {
2394
+ for (const name of written)
2395
+ await retryCacheFileMutation(() => unlink(join(dir, name)));
2396
+ throw err;
2397
+ }
2398
+ }
2399
+ }
2400
+ async function retryCacheFileMutation(operation) {
2401
+ for (let attempt = 0; attempt < 3; attempt++) {
2402
+ try {
2403
+ await operation();
2404
+ return true;
2405
+ }
2406
+ catch (err) {
2407
+ const code = err.code;
2408
+ if (code === 'ENOENT')
2409
+ return true;
2410
+ if ((code !== 'EPERM' && code !== 'EBUSY') || attempt === 2)
2411
+ return false;
2412
+ await new Promise(resolve => { setTimeout(resolve, 10 * (attempt + 1)); });
2413
+ }
2414
+ }
2415
+ return false;
2416
+ }
2417
+ // ── File Fingerprinting ────────────────────────────────────────────────
2418
+ //
2419
+ // Fingerprints cover the source's transcript file only. Providers that keep
2420
+ // metadata in a companion file (kiro CLI: credits in `<id>.json` next to the
2421
+ // `.jsonl`; kiro v2: modelId in `session.json` next to `messages.jsonl`) have
2422
+ // a blind spot: a parse that races the companion write caches the turn with
2423
+ // fallback values, and if the transcript never changes again (a session's
2424
+ // final turn) the entry never invalidates. Mid-session turns self-heal since
2425
+ // append-only transcripts keep changing. Fixing this properly means
2426
+ // multi-file fingerprints per source.
2427
+ // SQLite database files by extension. Bare-db sources (copilot's
2428
+ // agent-traces.db) and the virtual-suffix bases below all match one of these.
2429
+ const SQLITE_DB_PATH = /\.(db|sqlite3?|vscdb)$/i;
2430
+ /// Fingerprint a SQLite database file together with its `-wal` sibling.
2431
+ ///
2432
+ /// A database in WAL mode parks committed writes in `<db>-wal`; the main
2433
+ /// file's stat only moves on checkpoint, and a long-lived writer connection
2434
+ /// (hermes, cursor and opencode keep their state DBs open for the life of
2435
+ /// the agent process) can defer checkpoints for hours or days. A fingerprint
2436
+ /// built from the main file alone then (a) carries an mtime older than the
2437
+ /// newest committed data, so the date-range mtime pre-filter in
2438
+ /// parseProviderSources skips the source and sessions committed after the
2439
+ /// last checkpoint never parse (issue #913: today's Hermes sessions missing
2440
+ /// from every report), and (b) does not change between checkpoints, so
2441
+ /// reconcileFile keeps serving stale cached turns for sessions that grew.
2442
+ /// Folding the WAL sibling in fixes both: the newest mtime wins, and the
2443
+ /// sizes add so both WAL growth and a checkpoint (db grows, wal truncates)
2444
+ /// move the fingerprint. `-shm` is deliberately ignored — it mutates on
2445
+ /// reads too and would churn the fingerprint without any data change.
2446
+ async function fingerprintSqliteFile(dbPath) {
2447
+ try {
2448
+ const s = await stat(dbPath);
2449
+ const wal = await stat(dbPath + '-wal').catch(() => null);
2450
+ return {
2451
+ dev: s.dev,
2452
+ ino: s.ino,
2453
+ mtimeMs: wal ? Math.max(s.mtimeMs, wal.mtimeMs) : s.mtimeMs,
2454
+ sizeBytes: s.size + (wal?.size ?? 0),
2455
+ };
2456
+ }
2457
+ catch {
2458
+ return null;
2459
+ }
2460
+ }
2461
+ let fingerprintCalls = 0;
2462
+ export function fingerprintFileCount() {
2463
+ return fingerprintCalls;
2464
+ }
2465
+ export async function fingerprintFile(filePath) {
2466
+ fingerprintCalls++;
2467
+ try {
2468
+ const s = await stat(filePath);
2469
+ // Unified Vibe publishes immutable generations through CURRENT, but live
2470
+ // usage first lands in its bounded recovery journal without moving CURRENT.
2471
+ if (basename(filePath) === 'CURRENT' && basename(dirname(dirname(filePath))) === 'unified') {
2472
+ const dir = dirname(filePath);
2473
+ const journal = join(dir, 'journal');
2474
+ const names = (await readdir(journal).catch(() => []))
2475
+ .filter(name => /^\d{16}\.jsonl$/.test(name)).sort();
2476
+ const hash = createHash('sha256').update(`${s.ino}:${s.mtimeMs}:${s.size}`);
2477
+ let mtimeMs = s.mtimeMs;
2478
+ let sizeBytes = s.size;
2479
+ for (const path of [join(dir, 'meta.json'), ...names.map(name => join(journal, name))]) {
2480
+ const info = await stat(path).catch(() => null);
2481
+ hash.update(`\0${path}:${info?.ino}:${info?.mtimeMs}:${info?.size}`);
2482
+ if (info) {
2483
+ mtimeMs = Math.max(mtimeMs, info.mtimeMs);
2484
+ sizeBytes += info.size;
2485
+ }
2486
+ }
2487
+ // Composite identity changes even when a non-newest segment is rewritten;
2488
+ // keep sizeBytes real because the parser also uses it for workload sizing.
2489
+ return { dev: s.dev, ino: parseInt(hash.digest('hex').slice(0, 12), 16), mtimeMs, sizeBytes };
2490
+ }
2491
+ // Cline-family tasks key on ui_messages.json, but the model and workspace
2492
+ // come from api_conversation_history.json, which can appear or change
2493
+ // without ui_messages.json moving. A missing sibling hashes as undefined.
2494
+ if (basename(filePath) === 'ui_messages.json') {
2495
+ const sibling = await stat(join(dirname(filePath), 'api_conversation_history.json')).catch(() => null);
2496
+ const hash = createHash('sha256').update(`${s.ino}:${s.mtimeMs}:${s.size}\0${sibling?.ino}:${sibling?.mtimeMs}:${sibling?.size}`);
2497
+ return {
2498
+ dev: s.dev,
2499
+ ino: parseInt(hash.digest('hex').slice(0, 12), 16),
2500
+ mtimeMs: Math.max(s.mtimeMs, sibling?.mtimeMs ?? 0),
2501
+ sizeBytes: s.size + (sibling?.size ?? 0),
2502
+ };
2503
+ }
2504
+ // A source path that IS a SQLite database (copilot OTel's agent-traces.db)
2505
+ // needs the same WAL fold as the virtual-suffix forms below.
2506
+ if (SQLITE_DB_PATH.test(filePath))
2507
+ return fingerprintSqliteFile(filePath);
2508
+ // WSL's 9P share (`\\wsl$\...`) synthesizes dev/ino per mount, so they can
2509
+ // differ run to run for an unchanged file — keying on them would re-parse
2510
+ // every WSL session every time. mtime+size only for those paths (#1059).
2511
+ if (isWslUncPath(filePath))
2512
+ return { dev: 0, ino: 0, mtimeMs: s.mtimeMs, sizeBytes: s.size };
2513
+ return { dev: s.dev, ino: s.ino, mtimeMs: s.mtimeMs, sizeBytes: s.size };
2514
+ }
2515
+ catch {
2516
+ // Providers encode extra context into source paths using virtual suffixes:
2517
+ // - Cursor: `<dbPath>#cursor-ws=<workspace>` (workspace-aware routing)
2518
+ // - OpenCode: `<dbPath>:<sessionId>` (session scoping)
2519
+ // - Hermes: `<dbPath>#hermes-session=<sessionId>` (session scoping)
2520
+ // These compound paths don't exist on disk; strip the suffix to stat the
2521
+ // underlying database. Try `#` first (rare in real paths), then `:` (must
2522
+ // use lastIndexOf to tolerate Windows drive letters like C:\...).
2523
+ const hashIdx = filePath.indexOf('#');
2524
+ if (hashIdx > 0) {
2525
+ const fp = await fingerprintSqliteFile(filePath.slice(0, hashIdx));
2526
+ if (fp)
2527
+ return fp;
2528
+ // fall through to colon check
2529
+ }
2530
+ const colonIdx = filePath.lastIndexOf(':');
2531
+ if (colonIdx > 0) {
2532
+ return fingerprintSqliteFile(filePath.slice(0, colonIdx));
2533
+ }
2534
+ return null;
2535
+ }
2536
+ }
2537
+ // The on-disk paths a source path may resolve to, mirroring fingerprintFile's
2538
+ // virtual-suffix fallbacks above. A caller that got a null fingerprint and
2539
+ // must distinguish "gone" (every candidate ENOENT) from "present but
2540
+ // unreadable" (any candidate erroring some other way — data may be changing
2541
+ // behind the failure) has to check the same underlying paths the fingerprint
2542
+ // would have read, or a compound path's guaranteed ENOENT masks the real
2543
+ // file's EACCES.
2544
+ export function sourcePathStatCandidates(filePath) {
2545
+ const candidates = [filePath];
2546
+ const hashIdx = filePath.indexOf('#');
2547
+ if (hashIdx > 0)
2548
+ candidates.push(filePath.slice(0, hashIdx));
2549
+ const colonIdx = filePath.lastIndexOf(':');
2550
+ if (colonIdx > 0) {
2551
+ // Only a prefix that still looks like a path is a candidate: a plain
2552
+ // Windows path (`C:\...`) would otherwise yield the bare drive letter,
2553
+ // and a stat error on that cwd-relative name must never hold hydration.
2554
+ const prefix = filePath.slice(0, colonIdx);
2555
+ if (prefix.includes('/') || prefix.includes('\\'))
2556
+ candidates.push(prefix);
2557
+ }
2558
+ return candidates;
2559
+ }
2560
+ export function reconcileFile(current, cached) {
2561
+ if (!cached)
2562
+ return { action: 'new' };
2563
+ const fp = cached.fingerprint;
2564
+ if (fp.dev === current.dev &&
2565
+ fp.ino === current.ino &&
2566
+ fp.mtimeMs === current.mtimeMs &&
2567
+ fp.sizeBytes === current.sizeBytes) {
2568
+ return { action: 'unchanged' };
2569
+ }
2570
+ if (cached.lastCompleteLineOffset !== undefined &&
2571
+ // Defensive: never resume past the file's current end. A truncate-then-regrow
2572
+ // can leave the cached offset stranded beyond live bytes; reading from there
2573
+ // would silently drop the appended tail, so fall back to a full re-parse.
2574
+ cached.lastCompleteLineOffset <= current.sizeBytes &&
2575
+ fp.dev === current.dev &&
2576
+ fp.ino === current.ino &&
2577
+ current.sizeBytes > fp.sizeBytes) {
2578
+ return { action: 'appended', readFromOffset: cached.lastCompleteLineOffset };
2579
+ }
2580
+ return { action: 'modified' };
2581
+ }
2582
+ // ── Dedup Merge ────────────────────────────────────────────────────────
2583
+ // When appending incremental data, streaming Claude messages can re-emit
2584
+ // the same dedup key with updated usage. Merge by key: keep the earliest
2585
+ // timestamp, take incoming usage/tools/bashCommands/skills (latest wins).
2586
+ export function mergeCallByDedupKey(existing, incoming) {
2587
+ return {
2588
+ ...incoming,
2589
+ timestamp: existing.timestamp < incoming.timestamp
2590
+ ? existing.timestamp
2591
+ : incoming.timestamp,
2592
+ };
2593
+ }
2594
+ // ── Temp Cleanup ───────────────────────────────────────────────────────
2595
+ async function unlinkIfOlderThan(path, maxAgeMs, now) {
2596
+ try {
2597
+ const s = await stat(path);
2598
+ if (now - s.mtimeMs > maxAgeMs)
2599
+ await unlink(path);
2600
+ }
2601
+ catch { }
2602
+ }
2603
+ // Sweeps our own shard directory: interrupted temp writes, plus shards the
2604
+ // published envelope no longer references. Also retires the single-file layout's
2605
+ // leftover temps in the parent directory, which nothing writes anymore.
2606
+ export async function cleanupOrphanedTempFiles() {
2607
+ const now = Date.now();
2608
+ const parent = getCodeburnCacheDir();
2609
+ // `session-cache.v<n>.json.<nonce>.tmp` from a pre-v8 binary interrupted
2610
+ // mid-write. Age-guarded, so an old binary's in-flight write is left alone.
2611
+ // `status-snapshot.<queryKeyHash>.json.<nonce>.tmp` (see
2612
+ // writeStatusSnapshotRecord below — one file per queryKey) is swept here
2613
+ // too: it lives in this same parent dir, orthogonal to the month-shard
2614
+ // layout below, so the shard-dir sweep further down never sees it. Same
2615
+ // atomic temp+rename pattern, same narrow crash window between the write
2616
+ // and the rename as the versioned cache file above.
2617
+ try {
2618
+ for (const entry of await readdir(parent)) {
2619
+ if (!entry.endsWith('.tmp'))
2620
+ continue;
2621
+ if (!/^session-cache\.v\d+\.json\./.test(entry) && !entry.startsWith(`${STATUS_SNAPSHOT_FILE}.`))
2622
+ continue;
2623
+ await unlinkIfOlderThan(join(parent, entry), TEMP_FILE_MAX_AGE_MS, now);
2624
+ }
2625
+ }
2626
+ catch { }
2627
+ const dir = sessionCacheDir();
2628
+ if (!existsSync(dir))
2629
+ return;
2630
+ const referenced = new Set([ENVELOPE_FILE]);
2631
+ let envelope = await readEnvelope(dir);
2632
+ if (envelope) {
2633
+ for (const meta of Object.values(envelope.providers)) {
2634
+ referenced.add(meta.index);
2635
+ const memo = cacheMemo?.nonce === envelope.nonce ? stateOf(cacheMemo.cache).base : undefined;
2636
+ const pieces = [...(memo?.values() ?? [])].find(base => base.index === meta.index)?.pieces
2637
+ ?? (await readIndex(dir, meta.index))?.pieces;
2638
+ // An index that cannot be read (a concurrent save may just have retired
2639
+ // it) leaves its pieces unknown, so nothing is swept this time.
2640
+ if (!pieces) {
2641
+ envelope = null;
2642
+ break;
2643
+ }
2644
+ for (const name of Object.values(pieces)) {
2645
+ referenced.add(name);
2646
+ referenced.add(keysFileName(name));
2647
+ }
2648
+ }
2649
+ // A published envelope means the re-layout completed. Its retirement of
2650
+ // the old layout is a separate, unsynchronised step, so a crash in between
2651
+ // leaves 100MB+ of superseded cache behind forever. Age-guarded for the
2652
+ // same reason the piece sweep is: an OLD binary may still be writing there.
2653
+ await unlinkIfOlderThan(join(getCodeburnCacheDir(), priorCacheFile(7)), UNREFERENCED_SHARD_MAX_AGE_MS, now);
2654
+ for (const name of [PRIOR_SHARD_DIR_NAME, MONTH_SHARD_DIR_NAME]) {
2655
+ const old = join(getCodeburnCacheDir(), name);
2656
+ try {
2657
+ const s = await stat(join(old, ENVELOPE_FILE));
2658
+ if (now - s.mtimeMs > UNREFERENCED_SHARD_MAX_AGE_MS)
2659
+ await rm(old, { recursive: true, force: true });
2660
+ }
2661
+ catch { }
2662
+ }
2663
+ }
2664
+ try {
2665
+ for (const entry of await readdir(dir)) {
2666
+ if (entry.endsWith('.tmp')) {
2667
+ await unlinkIfOlderThan(join(dir, entry), TEMP_FILE_MAX_AGE_MS, now);
2668
+ continue;
2669
+ }
2670
+ if (!envelope || referenced.has(entry))
2671
+ continue;
2672
+ await unlinkIfOlderThan(join(dir, entry), UNREFERENCED_SHARD_MAX_AGE_MS, now);
2673
+ }
2674
+ }
2675
+ catch { }
2676
+ }
2677
+ // ── Hydration Lock ─────────────────────────────────────────────────────
2678
+ //
2679
+ // Advisory, cross-process coordination for the expensive cold hydration. When
2680
+ // two live processes (e.g. an old launchd menubar and the desktop app) both
2681
+ // cold-start against the same cache dir, without this they each parse full
2682
+ // history and race their writes. The first to arrive creates the lock and
2683
+ // hydrates; a second live process waits for release, then reads the now-warm
2684
+ // cache instead of re-parsing. It is strictly an optimization: on any
2685
+ // uncertainty we proceed with the parse, so it can never wedge a cold start.
2686
+ const HYDRATION_LOCK_FILE = 'hydrating.lock';
2687
+ const LOCK_FRESH_MS = 15 * 60_000;
2688
+ const LOCK_WAIT_MAX_MS = 10 * 60_000;
2689
+ const LOCK_POLL_MS = 250;
2690
+ const NOOP_HANDLE = { waited: false, release: async () => { } };
2691
+ function lockPath() {
2692
+ return join(getCodeburnCacheDir(), HYDRATION_LOCK_FILE);
2693
+ }
2694
+ // Our own pid never counts as a foreign holder: a same-process lock is either
2695
+ // re-entrant or leaked, and waiting on ourselves risks a self-hang. Cross-process
2696
+ // coordination is the only thing this lock is for. EPERM means the pid exists but
2697
+ // belongs to another user — still alive.
2698
+ function pidLooksAlive(pid) {
2699
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
2700
+ return false;
2701
+ try {
2702
+ process.kill(pid, 0);
2703
+ return true;
2704
+ }
2705
+ catch (err) {
2706
+ return err.code === 'EPERM';
2707
+ }
2708
+ }
2709
+ async function readLockRecord() {
2710
+ try {
2711
+ const parsed = JSON.parse(await readFile(lockPath(), 'utf-8'));
2712
+ if (typeof parsed?.pid === 'number' && typeof parsed?.at === 'number')
2713
+ return { pid: parsed.pid, at: parsed.at };
2714
+ return null;
2715
+ }
2716
+ catch {
2717
+ return null;
2718
+ }
2719
+ }
2720
+ async function writeOurLock() {
2721
+ try {
2722
+ const dir = getCodeburnCacheDir();
2723
+ if (!existsSync(dir))
2724
+ await mkdir(dir, { recursive: true });
2725
+ const handle = await open(lockPath(), 'wx', 0o600);
2726
+ try {
2727
+ await handle.writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }), { encoding: 'utf-8' });
2728
+ }
2729
+ finally {
2730
+ await handle.close();
2731
+ }
2732
+ return true;
2733
+ }
2734
+ catch {
2735
+ return false;
2736
+ }
2737
+ }
2738
+ async function removeOurLock() {
2739
+ try {
2740
+ const cur = await readLockRecord();
2741
+ if (cur && cur.pid === process.pid)
2742
+ await unlink(lockPath());
2743
+ }
2744
+ catch { /* best-effort; a leaked lock is reclaimed as stale next cold start */ }
2745
+ }
2746
+ // Synchronous variant for the signal path: a handler can't await, so read + unlink
2747
+ // synchronously. Only unlinks a lock we actually own.
2748
+ function removeOurLockSync() {
2749
+ try {
2750
+ const parsed = JSON.parse(readFileSync(lockPath(), 'utf-8'));
2751
+ if (parsed?.pid === process.pid)
2752
+ unlinkSync(lockPath());
2753
+ }
2754
+ catch { /* best-effort; nothing to clean or already gone */ }
2755
+ }
2756
+ /** Terminate an interactive CLI after synchronously releasing both cache-lock
2757
+ * families it can own. The process cannot wait for background parsing to drain,
2758
+ * but a direct exit must not make the next launch recover a stale live-pid lock. */
2759
+ export function exitAfterCacheCleanup(exitCode) {
2760
+ releaseOwnedRefreshLocksForExit();
2761
+ removeOurLockSync();
2762
+ process.exit(exitCode);
2763
+ }
2764
+ // Arm once, only while we hold the lock: on a catchable termination (Ctrl-C, or a
2765
+ // SIGTERM from a parent) clean our lock before dying so a killed cold parse leaves
2766
+ // no leftover. SIGKILL can't be caught, so that path still relies on the next cold
2767
+ // start's stale-lock takeover. process.once + re-raise preserves the default exit.
2768
+ let signalCleanupArmed = false;
2769
+ function armSignalCleanup() {
2770
+ if (signalCleanupArmed)
2771
+ return;
2772
+ signalCleanupArmed = true;
2773
+ for (const sig of ['SIGINT', 'SIGTERM']) {
2774
+ process.once(sig, () => {
2775
+ removeOurLockSync();
2776
+ process.kill(process.pid, sig);
2777
+ });
2778
+ }
2779
+ }
2780
+ const releaseHandle = { waited: false, release: removeOurLock };
2781
+ function sleep(ms) {
2782
+ return new Promise(resolve => { setTimeout(resolve, ms); });
2783
+ }
2784
+ /**
2785
+ * Coordinate a cold hydration. Pass `isCold = true` only when the on-disk cache
2786
+ * is empty (a genuine full parse is imminent). Returns a handle:
2787
+ * - `waited: true` → another live process was hydrating; we waited for it to
2788
+ * finish (or timed out). The caller should RELOAD the cache and let its normal
2789
+ * reconcile serve the now-warm entries instead of re-parsing. `release` is a
2790
+ * no-op (we never held the lock).
2791
+ * - `waited: false` with a real `release` → we hold the lock; hydrate, then call
2792
+ * `release()` in a finally.
2793
+ * - `waited: false` with a no-op `release` → proceed with the parse unlocked
2794
+ * (not cold, or the lock state was uncertain).
2795
+ */
2796
+ export async function beginColdHydration(isCold) {
2797
+ if (!isCold)
2798
+ return NOOP_HANDLE;
2799
+ try {
2800
+ if (await writeOurLock()) {
2801
+ armSignalCleanup();
2802
+ return releaseHandle;
2803
+ }
2804
+ const existing = await readLockRecord();
2805
+ const fresh = existing !== null && Date.now() - existing.at < LOCK_FRESH_MS;
2806
+ if (existing && fresh && pidLooksAlive(existing.pid)) {
2807
+ // Another live process owns a fresh lock: wait for it to release, go stale,
2808
+ // or die. A CLEAN release means the cache is warm — reload it. Going stale or
2809
+ // dying (e.g. a SIGKILLed cold scan) means the holder left partial data AND a
2810
+ // leftover lock file: take over — clean the stale lock and re-acquire — so we
2811
+ // re-parse under our own lock and remove the leftover on release, instead of
2812
+ // leaving it for the next cold start to reclaim.
2813
+ const deadline = Date.now() + LOCK_WAIT_MAX_MS;
2814
+ let takeover = false;
2815
+ while (Date.now() < deadline) {
2816
+ await sleep(LOCK_POLL_MS);
2817
+ const cur = await readLockRecord();
2818
+ if (!cur)
2819
+ break;
2820
+ if (Date.now() - cur.at >= LOCK_FRESH_MS) {
2821
+ takeover = true;
2822
+ break;
2823
+ }
2824
+ if (!pidLooksAlive(cur.pid)) {
2825
+ takeover = true;
2826
+ break;
2827
+ }
2828
+ }
2829
+ if (takeover) {
2830
+ try {
2831
+ await unlink(lockPath());
2832
+ }
2833
+ catch { /* another process may have; fine */ }
2834
+ if (await writeOurLock()) {
2835
+ armSignalCleanup();
2836
+ return releaseHandle;
2837
+ }
2838
+ }
2839
+ return { waited: true, release: async () => { } };
2840
+ }
2841
+ // Stale, dead-pid, or unreadable lock: replace it and take over.
2842
+ try {
2843
+ await unlink(lockPath());
2844
+ }
2845
+ catch { /* another process may have; fine */ }
2846
+ if (await writeOurLock())
2847
+ return releaseHandle;
2848
+ return NOOP_HANDLE;
2849
+ }
2850
+ catch {
2851
+ return NOOP_HANDLE;
2852
+ }
2853
+ }
2854
+ // ── Status Snapshot ────────────────────────────────────────────────────
2855
+ //
2856
+ // `codeburn status --format menubar-json` is spawned as a fresh CLI process
2857
+ // on every menubar poll tick, so every in-process reuse layer above
2858
+ // (`cacheMemo`, and `parser.ts`'s TTL/burst maps) starts cold on every poll —
2859
+ // none of them survive between invocations. Live profiling of a repeat poll
2860
+ // against an already-warm, unchanged ~386MB session cache showed the cost is
2861
+ // dominated by re-running `JSON.parse` on that whole file plus re-running the
2862
+ // full aggregation pipeline over it, every single time, even when nothing in
2863
+ // the underlying session corpus changed.
2864
+ //
2865
+ // This snapshot persists the last computed menubar payload keyed by a
2866
+ // caller-supplied corpus fingerprint (see `computeCorpusFingerprint` in
2867
+ // parser.ts — a cheap stat-only pass over every discovered source, with no
2868
+ // session-cache.json read/parse and no transcript content read) plus the
2869
+ // resolved query that produced it. A poll whose corpus fingerprint and query
2870
+ // both still match is served straight from this tiny file with no corpus
2871
+ // parse or aggregation at all; the instant either changes, the lookup misses
2872
+ // and the caller recomputes for real. Best-effort throughout: any read/write
2873
+ // failure just falls back to a full recompute, never to stale or corrupt
2874
+ // data.
2875
+ const STATUS_SNAPSHOT_FILE = 'status-snapshot';
2876
+ // Bump on any incompatible change to the *shape* of the payload this snapshot
2877
+ // persists (i.e. whenever `buildMenubarPayloadForRange`'s return shape
2878
+ // changes) or to this record's own envelope fields. Without this, an on-disk
2879
+ // snapshot written by an older binary would be blindly cast and served
2880
+ // verbatim by a newer one on a corpus-fingerprint+query match — the payload
2881
+ // shape has no other correctness gate, unlike the main session cache, which
2882
+ // already guards exactly this class of drift via `CACHE_VERSION`/
2883
+ // `validateCache`. A version mismatch is treated as a miss (same as a
2884
+ // missing/corrupt file): the caller recomputes for real and persists a fresh,
2885
+ // current-shaped snapshot.
2886
+ //
2887
+ // v2 (was v1): the file is now keyed by `queryKey` in its NAME (see
2888
+ // `statusSnapshotPath` below) instead of being one shared slot — two
2889
+ // concurrent callers with different queryKeys (a menubar poll for "today"
2890
+ // racing a manual refresh for "week") used to unconditionally evict each
2891
+ // other's save. A v1 file at the old fixed path is simply never looked at
2892
+ // again under v2 (harmless leftover, not actively cleaned).
2893
+ //
2894
+ // v3: every record carries the binary/render semantic key and the high-
2895
+ // resolution time at which its corpus scan began. The latter is the ordering
2896
+ // fence for competing writers: max(file mtime) is not monotonic because
2897
+ // deleting the newest file legitimately makes it decrease.
2898
+ //
2899
+ // v4: the payload carries `telemetrySnapshot`, which a v3 record predates.
2900
+ const STATUS_SNAPSHOT_VERSION = 4;
2901
+ // Each distinct queryKey gets its OWN file (`status-snapshot.<hash>.json`)
2902
+ // rather than sharing one slot — see the v2 note above / review finding
2903
+ // B-G1's "amplifier." This means two writers for different queryKeys never
2904
+ // touch each other's file at all, so there is no read-merge-write race to
2905
+ // close between them (a shared-map-file design was tried and demonstrably
2906
+ // races: two concurrent writers for different keys can each read before
2907
+ // either has written, then each overwrite the whole file with only their
2908
+ // own key — verified by a failing test before this per-file design replaced
2909
+ // it).
2910
+ function statusSnapshotHash(queryKey) {
2911
+ return createHash('sha256').update(queryKey).digest('hex').slice(0, 16);
2912
+ }
2913
+ function statusSnapshotPath(queryKey) {
2914
+ const hash = statusSnapshotHash(queryKey);
2915
+ return join(getCodeburnCacheDir(), `${STATUS_SNAPSHOT_FILE}.${hash}.json`);
2916
+ }
2917
+ function statusSnapshotLockFile(queryKey) {
2918
+ return `${STATUS_SNAPSHOT_FILE}.${statusSnapshotHash(queryKey)}.write.lock`;
2919
+ }
2920
+ async function readStatusSnapshotRecord(queryKey) {
2921
+ try {
2922
+ const raw = await readFile(statusSnapshotPath(queryKey), 'utf-8');
2923
+ const parsed = JSON.parse(raw);
2924
+ if (parsed.version !== STATUS_SNAPSHOT_VERSION ||
2925
+ typeof parsed.semanticKey !== 'string' ||
2926
+ typeof parsed.corpusFingerprint !== 'string' ||
2927
+ typeof parsed.newestMtimeMs !== 'number' || !Number.isFinite(parsed.newestMtimeMs) ||
2928
+ typeof parsed.observedAtMs !== 'number' || !Number.isFinite(parsed.observedAtMs) ||
2929
+ parsed.queryKey !== queryKey)
2930
+ return null;
2931
+ return parsed;
2932
+ }
2933
+ catch {
2934
+ return null;
2935
+ }
2936
+ }
2937
+ /** Shared best-effort atomic writer for both `saveStatusSnapshot` (a fresh,
2938
+ * settled recompute) and `loadStatusSnapshot`'s own bookkeeping write (a
2939
+ * first-observed-mismatch timestamp, so the settle clock survives across
2940
+ * the one-shot processes that call this — each CLI poll is a fresh process
2941
+ * with no in-memory state to carry it). A failed write just means the next
2942
+ * poll recomputes, or re-observes the mismatch as if it were first, instead
2943
+ * of reusing/deferring — never stale or corrupt data either way.
2944
+ *
2945
+ * The guard/read/write/rename transaction runs under a per-query cross-
2946
+ * process lock. A pre-rename re-read alone is not a CAS: two processes can
2947
+ * both pass it before either renames, after which the older writer is free to
2948
+ * land last. The lock makes that decision and publication one atomic critical
2949
+ * section while distinct query keys remain independent. */
2950
+ async function writeStatusSnapshotRecord(queryKey, record, guard) {
2951
+ const dir = getCodeburnCacheDir();
2952
+ try {
2953
+ if (!existsSync(dir))
2954
+ await mkdir(dir, { recursive: true });
2955
+ }
2956
+ catch {
2957
+ return false;
2958
+ }
2959
+ // A waiter reports `completed-by-other` when the owner releases cleanly.
2960
+ // Writers still need their own critical section to evaluate their guard, so
2961
+ // retry acquisition a bounded number of times instead of treating another
2962
+ // writer's completion as ours.
2963
+ for (let attempt = 0; attempt < 3; attempt++) {
2964
+ const lock = await acquireCacheRefreshLock({
2965
+ cacheDir: dir,
2966
+ lockFile: statusSnapshotLockFile(queryKey),
2967
+ waitMs: 2_000,
2968
+ pollMs: 10,
2969
+ });
2970
+ if (lock.outcome === 'completed-by-other')
2971
+ continue;
2972
+ if (lock.outcome !== 'acquired')
2973
+ return false;
2974
+ let tempPath = null;
2975
+ try {
2976
+ const finalPath = statusSnapshotPath(queryKey);
2977
+ const existing = await readStatusSnapshotRecord(queryKey);
2978
+ if (!guard(existing))
2979
+ return false;
2980
+ tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`;
2981
+ const handle = await open(tempPath, 'w', 0o600);
2982
+ try {
2983
+ await handle.writeFile(JSON.stringify(record), { encoding: 'utf-8' });
2984
+ await handle.sync();
2985
+ }
2986
+ finally {
2987
+ await handle.close();
2988
+ }
2989
+ // Fail closed if takeover or an I/O fault displaced us before publish.
2990
+ if (!await lock.handle.verifyStillOwner())
2991
+ return false;
2992
+ await rename(tempPath, finalPath);
2993
+ tempPath = null;
2994
+ return true;
2995
+ }
2996
+ catch {
2997
+ return false;
2998
+ }
2999
+ finally {
3000
+ if (tempPath)
3001
+ await unlink(tempPath).catch(() => { });
3002
+ await lock.handle.release().catch(() => { });
3003
+ }
3004
+ }
3005
+ return false;
3006
+ }
3007
+ /** Returns the previously-saved payload only when the query and the corpus
3008
+ * fingerprint both still match. Any fingerprint change is a miss, so the
3009
+ * caller recomputes and persists a fresh snapshot: serving the old payload
3010
+ * would replay an answer from before the change, however old it is. */
3011
+ export async function loadStatusSnapshot(corpusFingerprint, queryKey, semanticKey) {
3012
+ const stored = await readStatusSnapshotRecord(queryKey);
3013
+ if (!stored)
3014
+ return null;
3015
+ if (stored.semanticKey !== semanticKey)
3016
+ return null;
3017
+ // Belt-and-braces mirror of the save gate in main.ts: a payload marked
3018
+ // degraded (`stale === true` or a `hydration` block) must never have been
3019
+ // persisted, so one that somehow was (an older build, a hand-edited file)
3020
+ // is treated as a miss and recomputed rather than served.
3021
+ const candidate = stored.payload;
3022
+ if (candidate !== null && typeof candidate === 'object' && (candidate.stale === true || candidate.hydration !== undefined))
3023
+ return null;
3024
+ if (stored.corpusFingerprint !== corpusFingerprint)
3025
+ return null;
3026
+ return stored.payload ?? null;
3027
+ }
3028
+ /** Best-effort: a failed write just means the next poll recomputes instead
3029
+ * of reusing. Only ever called by the caller when `loadStatusSnapshot`
3030
+ * missed, so a settled recompute's result should supersede whatever was
3031
+ * there before — UNLESS a concurrent recompute already published one based
3032
+ * on a strictly fresher corpus observation (`observedAtMs`), in which case
3033
+ * this (slower, now-stale) write is refused rather than clobbering it. Ties
3034
+ * proceed: both reflect a correct recompute of the same corpus state. */
3035
+ export async function saveStatusSnapshot(corpusFingerprint, newestMtimeMs, observedAtMs, queryKey, semanticKey, payload) {
3036
+ return writeStatusSnapshotRecord(queryKey, { version: STATUS_SNAPSHOT_VERSION, semanticKey, corpusFingerprint, newestMtimeMs, observedAtMs, queryKey, payload }, existing => !existing
3037
+ || existing.semanticKey !== semanticKey
3038
+ || existing.observedAtMs < observedAtMs
3039
+ || (existing.observedAtMs === observedAtMs && existing.corpusFingerprint === corpusFingerprint));
3040
+ }