codeburn/src/daily-cache.ts
Matthew Kelch a5a0ddaeac
feat(copilot): read per-request input/cache from session-store.db
The Copilot CLI and the GitHub Copilot desktop app both write
~/.copilot/session-store.db unconditionally; its assistant_usage_events
table holds one row per API request. Until now input/cache tokens for
these surfaces came only from the session.shutdown rollups in
events.jsonl, which are written only on clean shutdown (a crash loses
the whole leg's input/cache accounting) and lump each session leg into
one per-model total. The rollup also RESETS its counters at in-session
compaction (traced on a clean single-process 107-request session whose
sole rollup covered exactly its five post-compaction requests), so even
cleanly-closed long sessions were truncated; on a long-history machine
the store recovered ~35% of real Copilot spend lost to crashes and
compaction resets. The DB rows are per-request, crash-proof, and carry
real timestamps.

The store's input_tokens is cache-INCLUSIVE (input + cache_read +
cache_write), the same convention as the shutdown rollups — verified
against each row's token_details_json and by reconciling per-session
sums against the CLI's own footers and rollups across two machines
(1,380+ rows, 8 models, CLI 1.0.70–1.0.79, schema_version 6): every
divergence was a rollup gap. Emitted calls mirror the shutdown-call
contract: input/cache/reasoning only, output 0 — per-turn output stays
owned by the events.jsonl assistant.message calls.

Rollup-vs-store precedence is RECONCILED at serve time, per
(session, model), and only there. Both representations always parse and
cache; parseProviderSources aggregates the cached calls and, wherever
store rows exist for a (session, model), drops the rollup calls and
serves the rows plus per-leg RESIDUAL calls: each rollup leg subtracts
only the rows in its own interval — rows commit strictly before their
leg's shutdown line, so a leg at time T covers exactly the rows in
(previous leg's T, T] — and any remainder (per token component, floored
at zero) serves once at that leg's own timestamp. A store missing
requests a leg covered — adopted mid-session, rows pruned before ever
being read — therefore still serves that tail exactly once ON THAT
LEG'S DAY, a crash-tail row the rollup never saw can never cancel it,
and a complete store serves pure per-request granularity with every
residual retired to zero. The decision reads only cached contents, never discovery:
deleting or resetting the store changes nothing served, so finalized
daily history can never flip on an absence epoch; cached rows of a
deleted store remain the record until the 90-day orphan age-out (which
exempts still-discovered paths). The serve set is the one coherent
snapshot — nothing a writer does between discovery and a parse can
change what one pass sees — and read-time precedence heals persisted
duplication (stale epochs, runtimes without node:sqlite, restored
files) instead of preserving it, following the buildDurablePeriod
pattern.

Store rows and rollups carry supplementary accounting weight. A rollup
(or its residual) is aggregate accounting, never a request: zero
api-call/model-call/turn weight, tokens and cost fully retained. A
store row is one real request, but when it pairs with a served per-turn
call it is supplementary too; rows pair with same-model per-turn calls
by timestamp adjacency (monotone matching, tight 2-minute window — the
two are written at the same completion moment, and a wide window would
let a crash-only row pair against a neighbor whose own row is missing),
computed once over the FULL serve set so a date-range boundary that
separates a row from its call cannot double the request across adjacent
day queries. Only the unpaired rows — store-only requests, exactly
where crash-lost requests sit — count. Supplementary-only turns fold
into the nearest behavioral turn within 30 minutes; with no behavioral
turn to fold into they stay separate weightless turns, each on its own
day, with apiCalls 0 — and the session emission gate admits
usage-bearing zero-call sessions. The weight
propagates into the daily cache: aggregateProjectsIntoDays applies the
same rule to every calls counter and category-turn count it seals, so
v19 history and live summaries can never disagree about what was a
request.

A changed source whose read defers on the busy shape (locked, EACCES,
corrupt mid-replace — discovery still emits the source; only true
absence or a schema mismatch reads as absent) now marks session
hydration incomplete, so the daily backfill holds its watermark instead
of finalizing a day the deferred rows never reached; an unchanged
unreadable store defers nothing. The verdict travels with its result —
the 180s memo and the serve burst-reuse restore the hydration verdict
their cached data was parsed under, so a memoized partial parse cannot
inherit a later parse's complete — and a discovered source whose
FINGERPRINT cannot be read (EACCES on a present file) defers instead of
silently skipping, while a genuinely deleted file stays a silent skip. Copilot reasoning tokens are no longer
double-billed at the report layer: they are a subset of the output the
per-turn calls already price, and copilot joins claude in the
reasoning-inside-output case of the query-time cost recompute.

Store dedup keys are content-discriminated —
copilot-store:<sid>:<rowId>:<fnv1a64(created_at|tokens|model)> —
because AUTOINCREMENT prevents id reuse only within one database
lifetime: a same-path DB reset reusing row ids now mints new keys
instead of the durable union swallowing the new usage, while a
byte-identical re-insert still collapses (64-bit: 32-bit FNV
collisions between plausible token tuples are constructible). Every
call of a session serves under one project label resolved at serve
time — the session-state-derived label when the serve set knows it,
else the store rows' own — so neither rows cached before events.jsonl
existed nor an events.jsonl orphaned by a session-state prune can
split the session across two grouping keys.

CODEBURN_COPILOT_SESSION_STORE_DB is read but deliberately NOT
fingerprinted, per the #927 ruling (any copilot fingerprint change
drops cached entries whose path still exists, destroying pruned history
only the cache holds); the read is allowlisted in the #927 guard, and
serve-time reconciliation makes repointing safe without a fingerprint —
the new store's rows parse on sight and the old path's entries persist
as durable orphans. The copilot parse version appends session-store-v2
and the daily cache bumps v17 → v19: per-day attribution, call counts
and costs all change against pre-store builds. 19, not 18: an earlier
pushed head of this PR already claimed v18 under different accounting,
and the carry-forward would adopt those days as finalized without
re-deriving them.

Verified by A/B on snapshots of two real stores, a live SIGKILL crash
test (row present, no rollup, tokens recovered exactly), live resumes
whose warm-cache deltas matched new rows to the token, upgrade-healing
at 4,800-session scale, and serve-level regressions pinning every
maintainer finding from six review rounds: the rows-then-shutdown race,
stale-cache healing, age-out exemption, absence-epoch identity,
progressive row landing with residual retirement, behavioral weight
across all four pinned scenarios, the hydration fence, project
unification in both directions, the same-path reset, mixed
coverage (crash tail vs covered-leg gap), multi-leg residual day
attribution, range-invariant pairing, memo-scoped hydration verdicts,
and the fingerprint-failure fence.
2026-08-17 17:52:01 -04:00

1172 lines
60 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { randomBytes } from 'crypto'
import { existsSync } from 'fs'
import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'fs/promises'
import { join } from 'path'
import { getCodeburnCacheDir } from './cache-dir.js'
import type { DateRange, ProjectSummary } from './types.js'
// Bumped to 19, deliberately skipping 18: an earlier head of this same change
// (#946) was pushed publicly claiming v18 under DIFFERENT accounting — no
// supplementary-call weighting, whole-session rollup suppression — and
// adoptOlderDailyCaches/isMigratableCache would take those days forward as
// finalized without re-deriving them. A distinct version is the only thing
// that stops one version number meaning two accountings.
//
// v18 (never released): copilot input/cache tokens for sessions covered by the CLI's
// session-store.db moved from one shutdown-rollup lump (stamped at session
// end) to per-request DB rows with real timestamps, supplementary accounting
// calls (rollups, covered rows) stopped counting as api/model calls, and
// reasoning tokens left the copilot cost recompute (they are inside the
// output the per-turn calls already bill). Per-day attribution, call counts
// and costs all move, so days finalized at v17 would disagree with the live
// parse. Re-derivation rides the v14 carry-forward semantics; sourceless
// days carry forward as-is.
//
// v17: copilot CLI sessions were misclassified as VS Code transcripts
// (#944), so days finalized at v16 or earlier carry output-only copilot costs —
// the session.shutdown rollup's input/cache tokens were dropped. Raising
// MIN_SUPPORTED_VERSION forces the one-time re-derivation under the
// provenance-based classification; sourceless days carry forward as-is.
//
// v16: Codex discovery is structural instead of originator-gated
// (#873/#626), so rollouts written by third-party frontends driving
// `codex app-server` ("t3code_desktop", "JetBrains.IntelliJ IDEA", ...) now
// contribute usage that v15 rollups never contained. Those files were rejected
// before they were ever parsed, so nothing downstream can notice on its own:
// `usage-aggregator` serves every day before today from this cache, and
// retention is ten years, so an upgrading user with a warm cache would keep the
// pre-fix history forever while today's numbers silently disagreed with it.
// Raising MIN_SUPPORTED_VERSION forces the one-time re-derivation.
//
// v15: per-project daily rollups. Days and provider slices now carry
// a `projects` breakdown (cost/calls/savings/sessions per project) so project
// history outlives the session files, like models and categories already do.
// This bump is the first to ride the v14 carry-forward: the old cache is
// adopted losslessly and only days whose sources survive are re-derived (now
// with projects); days already sourceless keep their totals and simply have
// no project split.
//
// v14: NEVER-LOSE history. Session files are ephemeral (Claude Code
// deletes transcripts after ~30 days), so a day that can no longer be re-derived
// from sources exists ONLY in this cache. Every earlier version treated the
// cache as disposable — schema bumps, savings-config changes, timezone changes
// and incomplete-hydration retries all dropped the days and re-derived from
// whatever sources survived, silently truncating history to the source-retention
// window (five bumps between 2026-06-22 and 2026-07-16 erased everything before
// 2026-04-24 on a machine with usage since March). From v14 on, invalidation
// re-derives what it can and CARRIES FORWARD every (day, provider) slice it
// cannot, and loading a missing/unsupported cache file adopts days from every
// older daily-cache file in the cache dir instead of starting empty. Bumping
// the version now only forces re-derivation of days whose sources still exist;
// it must never again lose the rest. DailyEntry.providers slices carry a full
// per-provider breakdown (tokens, models, categories) so those carry-forwards
// stay exact across rebuilds.
//
// v13: day bucketing is now TURN-anchored (a turn's whole cost/calls
// land on the day of its user-message timestamp) to match the live headline/
// report rollup. v12 bucketed each call by its own timestamp, so a midnight-
// straddling turn split across two days and history.daily / the provider
// breakdown never reconciled to current.cost. Raising MIN_SUPPORTED_VERSION
// forces the one-time re-hydration that rebuilds history under turn bucketing.
//
// v12: CodeWhale support adds historical usage that earlier rollups
// did not contain. Both the CodeWhale branch and the kiro credit-pricing
// change (below) claimed v11 independently, so v12 is the first version that
// contains both; raising MIN_SUPPORTED_VERSION forces the one-time
// re-hydration for days finalized at either v11.
//
// v11: kiro cost accounting changed (metered credits pass through
// the session cache instead of being re-priced from estimated tokens), so
// days finalized at v10 carry token-estimated kiro costs that were off by up
// to 16× per model. Raising MIN_SUPPORTED_VERSION forces the one-time full
// re-hydration that backfills history under credit-based pricing.
//
// v10: cursor accounting changed (real composer context tokens on
// conversation-anchored records, Cursor-published composer pricing), so days
// finalized at v9 carry the old double-counted agentKv estimates and
// sonnet-proxy composer costs.
//
// v9: providers added since the v8 rollup (Grok, Hermes, ZCode) parse usage
// that older binaries skipped. v8 added local-model savings to the daily
// rollup; the `savingsConfigHash` field is invalidated separately when the
// user changes their `localModelSavings` mapping.
export const DAILY_CACHE_VERSION = 19
const MIN_SUPPORTED_VERSION = 19
// Version-suffixed so different binaries each own a distinct file and never
// clobber an incompatible schema. Bumping the version mints a fresh filename;
// adoptOlderDailyCaches then unions days out of every previous file (including
// the pre-versioning `daily-cache.json`, which old binaries still own and we
// never write or delete).
const DAILY_CACHE_FILENAME = `daily-cache.v${DAILY_CACHE_VERSION}.json`
export type ModelDayStats = {
calls: number
cost: number
savingsUSD: number
inputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
}
export type CategoryDayStats = { turns: number; cost: number; savingsUSD: number; editTurns: number; oneShotTurns: number }
/// `path` is the project's filesystem path when known — it is what display
/// layers derive a friendly name from once the sessions that carried the
/// mapping are gone.
export type ProjectDayStats = { cost: number; calls: number; savingsUSD: number; sessions: number; path?: string }
export type ProviderDaySlice = {
calls: number
cost: number
savingsUSD: number
/// Full per-provider breakdown, written since v14. Slices adopted from older
/// caches carry only the three fields above; carrying such a slice forward
/// restores exact cost/calls/savings but not the day's token/model/category
/// split for that provider.
sessions?: number
inputTokens?: number
outputTokens?: number
cacheReadTokens?: number
cacheWriteTokens?: number
editTurns?: number
oneShotTurns?: number
models?: Record<string, ModelDayStats>
categories?: Record<string, CategoryDayStats>
projects?: Record<string, ProjectDayStats>
}
export type DailyEntry = {
date: string
cost: number
savingsUSD: number
calls: number
sessions: number
inputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
editTurns: number
oneShotTurns: number
models: Record<string, ModelDayStats>
categories: Record<string, CategoryDayStats>
providers: Record<string, ProviderDaySlice>
/// Per-project rollup (session-level project attribution). Absent on days
/// recorded before v15 — those days keep their totals but have no project
/// split, and nothing can reconstruct one once the sources are gone.
projects?: Record<string, ProjectDayStats>
/// Present when some of this day's data was carried forward from an earlier
/// cache generation instead of re-derived from session files (the files no
/// longer exist). Carried values keep the accounting of the version that
/// recorded them — stale accounting beats a silent zero.
carried?: true
}
export type DailyCache = {
version: number
/// Hash of the active `localModelSavings` config at the time the cache
/// was last written. When the user changes their baseline mapping the
/// hash mismatches and `ensureCacheHydrated` re-derives available history,
/// then carries forward slices whose sources are gone.
savingsConfigHash: string
/// IANA local timezone the days were bucketed under (day boundaries are
/// local-time). If the machine's timezone changes, previously-cached days are
/// bucketed against the wrong midnight, so a mismatch forces a full re-hydrate
/// (same self-heal as `savingsConfigHash`). Absent on caches written before
/// this field existed → not treated as a mismatch (no gratuitous rebuild).
tzKey?: string
lastComputedDate: string | null
days: DailyEntry[]
/// True only once the full backfill window has been hydrated from a COMPLETE
/// session parse. A cache that was finalized against a partial (interrupted)
/// session hydration — the "chart is empty for the first ~20 days" bug — reads
/// as incomplete and is fully re-backfilled. Absent on caches written before
/// this field existed → treated as incomplete (one self-healing re-backfill).
complete?: boolean
/// True once a COMPLETE parse finalized this watermark. The pull-back below
/// only distrusts caches WITHOUT this stamp: a degraded parse can no longer
/// set `complete`, so a stamped cache whose watermark sits past its newest
/// populated day is a legitimately idle tail (recent days had no activity),
/// not a frozen hole, and re-deriving it every launch is pure waste. Absent
/// on caches written before this field: distrusted once (one healing
/// pull-back), then stamped.
watermarkTrusted?: boolean
}
/** IANA name of the current local timezone (respects the TZ env var). Days are
* bucketed by local midnight, so this tags the cache for TZ-change invalidation. */
export function currentTzKey(): string {
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || '' } catch { return '' }
}
function getCachePath(): string {
return join(getCodeburnCacheDir(), DAILY_CACHE_FILENAME)
}
/** Absolute path of the active (version-suffixed) daily cache file. */
export function dailyCachePath(): string {
return getCachePath()
}
export function emptyCache(savingsConfigHash = ''): DailyCache {
return { version: DAILY_CACHE_VERSION, savingsConfigHash, tzKey: currentTzKey(), lastComputedDate: null, days: [], complete: false }
}
function isMigratableCache(parsed: unknown): parsed is { version: number; lastComputedDate: string | null; savingsConfigHash?: string; tzKey?: string; days: Record<string, unknown>[]; complete?: boolean } {
if (!parsed || typeof parsed !== 'object') return false
const c = parsed as Partial<DailyCache>
if (typeof c.version !== 'number') return false
if (!Array.isArray(c.days)) return false
return c.version >= MIN_SUPPORTED_VERSION && c.version <= DAILY_CACHE_VERSION
}
function num(v: unknown): number {
return typeof v === 'number' && Number.isFinite(v) ? v : 0
}
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
function sanitizeModels(raw: unknown): DailyEntry['models'] {
if (!isRecord(raw)) return {}
const out: DailyEntry['models'] = {}
for (const [name, m] of Object.entries(raw)) {
if (name in Object.prototype || !isRecord(m)) continue
setOwn(out, name, {
calls: num(m.calls),
cost: num(m.cost),
savingsUSD: num(m.savingsUSD),
inputTokens: num(m.inputTokens),
outputTokens: num(m.outputTokens),
cacheReadTokens: num(m.cacheReadTokens),
cacheWriteTokens: num(m.cacheWriteTokens),
})
}
return out
}
function sanitizeCategories(raw: unknown): DailyEntry['categories'] {
if (!isRecord(raw)) return {}
const out: DailyEntry['categories'] = {}
for (const [name, c] of Object.entries(raw)) {
if (name in Object.prototype || !isRecord(c)) continue
setOwn(out, name, {
turns: num(c.turns),
cost: num(c.cost),
savingsUSD: num(c.savingsUSD),
editTurns: num(c.editTurns),
oneShotTurns: num(c.oneShotTurns),
})
}
return out
}
const OPTIONAL_SLICE_NUMERICS = ['sessions', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'editTurns', 'oneShotTurns'] as const
/// Same junk-tolerance as sanitizeProjects, one level up: a foreign cache can
/// hold anything under a provider slice, and structuredClone in the merge
/// would faithfully preserve that junk into the next cache generation. Numeric
/// fields and nested maps are sanitized before the slice enters the cache.
function sanitizeProviders(raw: unknown): DailyEntry['providers'] {
if (!isRecord(raw)) return {}
const out: DailyEntry['providers'] = {}
for (const [name, s] of Object.entries(raw)) {
if (name in Object.prototype || !isRecord(s)) continue
const slice = s
const clean: ProviderDaySlice = { calls: num(slice.calls), cost: num(slice.cost), savingsUSD: num(slice.savingsUSD) }
for (const key of OPTIONAL_SLICE_NUMERICS) {
if (slice[key] !== undefined) clean[key] = num(slice[key])
}
if (isRecord(slice.models)) clean.models = sanitizeModels(slice.models)
if (isRecord(slice.categories)) clean.categories = sanitizeCategories(slice.categories)
const projects = sanitizeProjects(slice.projects).projects
if (projects) clean.projects = projects
setOwn(out, name, clean)
}
return out
}
/// Foreign or hand-edited caches can hold anything under `projects`; keep only
/// a plain record of finite numeric stats (arrays and null entries dropped) so
/// later carry merges can't crash on junk.
function sanitizeProjects(raw: unknown): { projects?: DailyEntry['projects'] } {
if (!isRecord(raw)) return {}
const out: NonNullable<DailyEntry['projects']> = {}
for (const [name, p] of Object.entries(raw)) {
// A project key is a directory basename, so it can legitimately be a
// prototype-member name ("constructor", "valueOf", ...). `setOwn` writes it
// as an own property via defineProperty, so keeping it is pollution-safe —
// and dropping it would silently subtract that project's cost from a
// --project/--exclude total (the day's split would no longer sum to its own
// cost, which the filtered headline relies on).
if (!isRecord(p)) continue
setOwn(out, name, {
cost: num(p.cost),
calls: num(p.calls),
savingsUSD: num(p.savingsUSD),
sessions: num(p.sessions),
...(typeof p.path === 'string' && p.path.length > 0 ? { path: p.path } : {}),
})
}
return Object.keys(out).length > 0 ? { projects: out } : {}
}
const DATE_KEY_RE = /^\d{4}-\d{2}-\d{2}$/
function migrateDays(days: Record<string, unknown>[]): DailyEntry[] {
return days
.filter(d => d && typeof d === 'object' && typeof d.date === 'string' && DATE_KEY_RE.test(d.date))
.map(d => ({
date: d.date as string,
cost: num(d.cost),
savingsUSD: num(d.savingsUSD),
calls: num(d.calls),
sessions: num(d.sessions),
inputTokens: num(d.inputTokens),
outputTokens: num(d.outputTokens),
cacheReadTokens: num(d.cacheReadTokens),
cacheWriteTokens: num(d.cacheWriteTokens),
editTurns: num(d.editTurns),
oneShotTurns: num(d.oneShotTurns),
models: sanitizeModels(d.models),
categories: sanitizeCategories(d.categories),
providers: sanitizeProviders(d.providers),
...(sanitizeProjects(d.projects)),
...(d.carried === true ? { carried: true as const } : {}),
}))
}
function migratedFrom(parsed: { version: number; lastComputedDate: string | null; savingsConfigHash?: string; tzKey?: string; days: Record<string, unknown>[]; complete?: boolean; watermarkTrusted?: boolean }): DailyCache {
return {
version: DAILY_CACHE_VERSION,
savingsConfigHash: parsed.savingsConfigHash ?? '',
tzKey: parsed.tzKey,
lastComputedDate: typeof parsed.lastComputedDate === 'string' && DATE_KEY_RE.test(parsed.lastComputedDate)
? parsed.lastComputedDate
: null,
days: migrateDays(parsed.days),
// Only a cache explicitly marked complete stays trusted; one written before
// the marker existed reads false and is re-backfilled once.
complete: parsed.complete === true,
// Absent on a pre-fix cache: the watermark is distrusted once (healing
// pull-back), then re-stamped by the finalize that follows.
watermarkTrusted: parsed.watermarkTrusted === true,
}
}
export async function loadDailyCache(): Promise<DailyCache> {
const path = getCachePath()
if (existsSync(path)) {
try {
const parsed: unknown = JSON.parse(await readFile(path, 'utf-8'))
if (isMigratableCache(parsed)) {
const migrated = migratedFrom(parsed)
if (parsed.version < DAILY_CACHE_VERSION) await saveDailyCache(migrated).catch(() => {})
return migrated
}
} catch {
// fall through to adoption — a corrupt current file must not cost history
// that older cache files still hold.
}
return adoptOlderDailyCaches()
}
return adoptOlderDailyCaches()
}
type AdoptableCache = { version: number; lastComputedDate?: string | null; savingsConfigHash?: string; tzKey?: string; days: Record<string, unknown>[]; complete?: boolean }
function isAdoptableCache(parsed: unknown): parsed is AdoptableCache {
if (!parsed || typeof parsed !== 'object') return false
const c = parsed as Partial<DailyCache>
return typeof c.version === 'number' && Array.isArray(c.days)
}
/// Versioned file absent (or unreadable): adopt days from EVERY other
/// daily-cache file in the cache dir — the legacy unversioned file, older
/// versioned files, and manual .bak copies. Files are read, never written or
/// deleted (old binaries still own theirs). A candidate at exactly our version
/// (the legacy file written by a same-version binary) is fully trusted and
/// becomes the base; every other candidate contributes per-(day, provider)
/// slices it alone still has, marked `carried`. This is what makes a schema
/// bump lossless: the new version starts from the union of everything every
/// previous version ever recorded, then re-derives what sources still support.
async function adoptOlderDailyCaches(): Promise<DailyCache> {
const dir = getCodeburnCacheDir()
let names: string[] = []
try {
names = await readdir(dir)
} catch {
return emptyCache()
}
const candidates: { parsed: AdoptableCache; mtimeMs: number }[] = []
for (const name of names) {
if (!name.startsWith('daily-cache') || !name.includes('.json')) continue
if (name === DAILY_CACHE_FILENAME) continue
// .tmp files are included deliberately: a crash between the atomic write
// completing and the rename landing leaves the NEWEST state only in the
// .tmp. A truncated half-write fails JSON.parse below and is skipped.
const path = join(dir, name)
try {
const parsed: unknown = JSON.parse(await readFile(path, 'utf-8'))
if (!isAdoptableCache(parsed)) continue
candidates.push({ parsed, mtimeMs: (await stat(path)).mtimeMs })
} catch {
continue
}
}
if (candidates.length === 0) return emptyCache()
// Priority: newer schema first, then most recently written. Higher priority
// wins per (day, provider); lower priority only fills what is missing.
candidates.sort((a, b) => (b.parsed.version - a.parsed.version) || (b.mtimeMs - a.mtimeMs))
let base: DailyCache
let rest = candidates
if (candidates[0]!.parsed.version === DAILY_CACHE_VERSION && isMigratableCache(candidates[0]!.parsed)) {
base = migratedFrom(candidates[0]!.parsed as Parameters<typeof migratedFrom>[0])
rest = candidates.slice(1)
} else {
base = emptyCache()
}
let days = base.days
for (const { parsed } of rest) {
days = mergeDayEntries(days, migrateDays(parsed.days), true)
}
// loadDailyCache has standalone readers, so the adopted result must already
// satisfy the cache's own invariants: no today/future entries (they would be
// served frozen instead of recomputed live) and nothing past retention.
const now = new Date()
const todayStr = toDateString(now)
const yesterdayStr = toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1))
days = applyRetention(days.filter(d => d.date < todayStr), yesterdayStr)
// A trusted base can carry lastComputedDate >= today (clock skew wrote a
// frozen today entry that the purge above just removed). Left as-is it would
// make hydration skip the gap parse forever and the purged day would never
// be recomputed. Clamp back to the retained data.
let lastComputedDate = base.lastComputedDate
if (lastComputedDate && lastComputedDate > yesterdayStr) {
lastComputedDate = days.length > 0 ? days[days.length - 1]!.date : null
}
const adopted: DailyCache = {
...base,
lastComputedDate,
days,
// An untrusted base means nothing here was derived under the current
// accounting: leave complete unset so the next hydration re-derives every
// day whose sources survive (the merge keeps the rest).
complete: rest.length === candidates.length ? false : base.complete,
watermarkTrusted: rest.length === candidates.length ? false : base.watermarkTrusted,
}
await saveDailyCache(adopted).catch(() => {})
return adopted
}
export async function saveDailyCache(cache: DailyCache): Promise<void> {
const dir = getCodeburnCacheDir()
if (!existsSync(dir)) await mkdir(dir, { recursive: true })
const finalPath = getCachePath()
const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`
const payload = JSON.stringify(cache)
const handle = await open(tempPath, 'w', 0o600)
try {
await handle.writeFile(payload, { encoding: 'utf-8' })
await handle.sync()
} finally {
await handle.close()
}
try {
await rename(tempPath, finalPath)
} catch (err) {
try { await unlink(tempPath) } catch { /* ignore */ }
throw err
}
}
export function addNewDays(cache: DailyCache, incoming: DailyEntry[], newestDate: string): DailyCache {
const byDate = new Map(cache.days.map(d => [d.date, d]))
for (const day of incoming) {
byDate.set(day.date, day)
}
const merged = Array.from(byDate.values()).sort((a, b) => a.date.localeCompare(b.date))
const nextLast = cache.lastComputedDate && cache.lastComputedDate > newestDate
? cache.lastComputedDate
: newestDate
return {
version: DAILY_CACHE_VERSION,
savingsConfigHash: cache.savingsConfigHash,
tzKey: cache.tzKey,
lastComputedDate: nextLast,
days: applyRetention(merged, newestDate),
complete: cache.complete,
watermarkTrusted: cache.watermarkTrusted,
}
}
/// Prune entries older than the retention window so the cache file does not
/// grow unbounded over years of daily use. Anchor the cutoff on newestDate so
/// a stale or stuck clock can't accidentally evict everything. Skip the prune
/// entirely if newestDate is malformed — an invalid Date would produce a NaN
/// cutoff and `d.date >= "Invalid Date"` would silently drop every entry.
function applyRetention(days: DailyEntry[], newestDate: string): DailyEntry[] {
const cutoffDate = new Date(`${newestDate}T00:00:00Z`)
if (isNaN(cutoffDate.getTime())) return days
cutoffDate.setUTCDate(cutoffDate.getUTCDate() - DAILY_CACHE_RETENTION_DAYS)
const cutoff = toDateString(cutoffDate)
return days.filter(d => d.date >= cutoff)
}
function hasSliceData(slice: ProviderDaySlice): boolean {
return slice.cost > 0 || slice.calls > 0 || (slice.savingsUSD ?? 0) > 0
}
/// A day from a pre-v5-era cache: day-level totals exist but the providers map
/// is empty, so nothing can be attributed per provider. Such a day merges
/// all-or-nothing — filling slices into it would double-count whatever share
/// of its totals the incoming provider already contributed.
function isOpaqueDay(day: DailyEntry): boolean {
return (day.cost > 0 || day.calls > 0) && Object.keys(day.providers).length === 0
}
function emptyModelStats(): ModelDayStats {
return { calls: 0, cost: 0, savingsUSD: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
}
/// Fold one provider's day slice into a day: the providers map, the day-level
/// totals, and (when the slice carries them — v14+ slices do) the model and
/// category breakdowns. Skinny slices from pre-v14 caches restore only
/// cost/calls/savings; the day's other totals simply don't grow. A zero-data
/// placeholder already present for the provider (a session that started this
/// day but whose turns all landed on another) only contributes its session
/// count, deduplicated by max — the same real session may be counted on both
/// sides.
/// `residual` marks a slice that came out of the tz subtraction (issue #770):
/// the subtraction already removed the placeholder's sessions (the ones the
/// fresh parse explained), so the residual sessions are all distinct from the
/// placeholder's and must ADD to it, not max-dedup against it. Max would clamp
/// max(placeholder, residual) and permanently drop the source-gone sessions the
/// residual still carries.
function addSliceIntoDay(day: DailyEntry, provider: string, slice: ProviderDaySlice, residual = false): void {
// Reads keyed by names from foreign caches use hasOwn throughout: a plain
// lookup of "__proto__" returns the prototype object, and accumulating into
// it pollutes every object in the process.
const placeholder = Object.hasOwn(day.providers, provider) ? day.providers[provider] : undefined
const placeholderSessions = placeholder?.sessions ?? 0
const merged = structuredClone(slice)
if (residual) {
// The subtraction removed the placeholder's sessions from this residual, so
// every remaining session is distinct from the placeholder's - add, don't
// max (max would clamp 1 + 1 to 1 and lose the source-gone session).
merged.sessions = placeholderSessions + (merged.sessions ?? 0)
} else if (placeholderSessions > (merged.sessions ?? 0)) {
merged.sessions = placeholderSessions
}
setOwn(day.providers, provider, merged)
day.cost += slice.cost
day.calls += slice.calls
day.savingsUSD += slice.savingsUSD ?? 0
day.sessions += residual ? (slice.sessions ?? 0) : Math.max(0, (slice.sessions ?? 0) - placeholderSessions)
day.inputTokens += slice.inputTokens ?? 0
day.outputTokens += slice.outputTokens ?? 0
day.cacheReadTokens += slice.cacheReadTokens ?? 0
day.cacheWriteTokens += slice.cacheWriteTokens ?? 0
day.editTurns += slice.editTurns ?? 0
day.oneShotTurns += slice.oneShotTurns ?? 0
for (const [name, m] of Object.entries(slice.models ?? {})) {
const acc = Object.hasOwn(day.models, name) ? day.models[name]! : emptyModelStats()
acc.calls += m.calls
acc.cost += m.cost
acc.savingsUSD += m.savingsUSD ?? 0
acc.inputTokens += m.inputTokens
acc.outputTokens += m.outputTokens
acc.cacheReadTokens += m.cacheReadTokens
acc.cacheWriteTokens += m.cacheWriteTokens
setOwn(day.models, name, acc)
}
for (const [cat, c] of Object.entries(slice.categories ?? {})) {
const acc = Object.hasOwn(day.categories, cat) ? day.categories[cat]! : { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 }
acc.turns += c.turns
acc.cost += c.cost
acc.savingsUSD += c.savingsUSD ?? 0
acc.editTurns += c.editTurns
acc.oneShotTurns += c.oneShotTurns
setOwn(day.categories, cat, acc)
}
const placeholderProjects = placeholder?.projects ?? {}
for (const [name, p] of Object.entries(slice.projects ?? {})) {
if (!p || typeof p !== 'object' || Array.isArray(p)) continue
const dayProjects = (day.projects ??= {})
const acc = Object.hasOwn(dayProjects, name) ? dayProjects[name]! : { cost: 0, calls: 0, savingsUSD: 0, sessions: 0 }
acc.cost += num(p.cost)
acc.calls += num(p.calls)
acc.savingsUSD += num(p.savingsUSD)
if (!acc.path && typeof p.path === 'string') acc.path = p.path
// Same session dedup as the slice-level sessions above: a placeholder's
// project sessions were already counted into the day when the fresh day
// was built, so only the excess is added.
const placeholderProjectSessions = Object.hasOwn(placeholderProjects, name) ? num(placeholderProjects[name]?.sessions) : 0
acc.sessions += residual ? num(p.sessions) : Math.max(0, num(p.sessions) - placeholderProjectSessions)
setOwn(dayProjects, name, acc)
}
// Placeholder-only projects (session counted fresh, calls landed elsewhere)
// survive on the merged slice rather than being dropped by the clone above.
const mergedProjects = merged.projects
if (mergedProjects) {
for (const [name, p] of Object.entries(placeholderProjects)) {
if (!p || typeof p !== 'object') continue
if (Object.hasOwn(mergedProjects, name)) {
if (residual) {
mergedProjects[name]!.sessions = num(mergedProjects[name]!.sessions) + num(p.sessions)
} else if (num(p.sessions) > num(mergedProjects[name]!.sessions)) {
mergedProjects[name]!.sessions = num(p.sessions)
}
} else {
setOwn(mergedProjects, name, { cost: 0, calls: 0, savingsUSD: 0, sessions: num(p.sessions) })
}
}
} else if (placeholder?.projects) {
merged.projects = structuredClone(placeholder.projects)
}
}
/// Assign via defineProperty so filesystem-derived keys like "__proto__" become
/// ordinary own properties instead of mutating the prototype link.
function setOwn<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
// --- tz-aware carry subtraction (issue #770) ---------------------------------
//
// After a timezone change the full re-derive re-aggregates the same session
// parse under the CURRENT tz and merges it over the cached (old-tz) days.
// mergeDayEntries carries a baseline slice only when the fresh day has no data
// slice for that (date, provider), so a turn that re-bucketed across local
// midnight leaves its old day sliceless, gets carried there, AND counts again on
// its new day. The fix subtracts from each carried baseline slice the content
// the fresh parse still attributes to that (date, provider) under the OLD
// bucketing (`freshUnderOldTz`): exactly the re-bucketed turns, nothing else.
// A sources-gone slice has no such content and survives untouched; a slice fully
// explained away is dropped.
/// Reduce `base` by `sub` at the slice level, clamping every field at 0 and
/// dropping nested entries that reduce to nothing. Returns null when no positive
/// data remains; the merge then drops the slice instead of carrying an empty
/// one. `sub` is always a subset of `base` in practice (same parse, old bucketing
/// vs cached baseline), so the clamp only guards rounding and cache/baseline skew.
function subtractSlice(base: ProviderDaySlice, sub: ProviderDaySlice): ProviderDaySlice | null {
const calls = Math.max(0, base.calls - (sub.calls ?? 0))
const cost = Math.max(0, base.cost - (sub.cost ?? 0))
const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0))
const sessions = Math.max(0, (base.sessions ?? 0) - (sub.sessions ?? 0))
const inputTokens = Math.max(0, (base.inputTokens ?? 0) - (sub.inputTokens ?? 0))
const outputTokens = Math.max(0, (base.outputTokens ?? 0) - (sub.outputTokens ?? 0))
const cacheReadTokens = Math.max(0, (base.cacheReadTokens ?? 0) - (sub.cacheReadTokens ?? 0))
const cacheWriteTokens = Math.max(0, (base.cacheWriteTokens ?? 0) - (sub.cacheWriteTokens ?? 0))
const editTurns = Math.max(0, (base.editTurns ?? 0) - (sub.editTurns ?? 0))
const oneShotTurns = Math.max(0, (base.oneShotTurns ?? 0) - (sub.oneShotTurns ?? 0))
const models = subtractModels(base.models, sub.models)
const categories = subtractCategories(base.categories, sub.categories)
const projects = subtractProjects(base.projects, sub.projects)
const out: ProviderDaySlice = {
calls, cost, savingsUSD,
...(sessions > 0 ? { sessions } : {}),
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(cacheReadTokens > 0 ? { cacheReadTokens } : {}),
...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),
...(editTurns > 0 ? { editTurns } : {}),
...(oneShotTurns > 0 ? { oneShotTurns } : {}),
...(models ? { models } : {}),
...(categories ? { categories } : {}),
...(projects ? { projects } : {}),
}
return hasSliceData(out) || (out.sessions ?? 0) > 0 ? out : null
}
function subtractModelStats(base: ModelDayStats, sub: ModelDayStats): ModelDayStats | null {
const calls = Math.max(0, base.calls - (sub.calls ?? 0))
const cost = Math.max(0, base.cost - (sub.cost ?? 0))
const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0))
const inputTokens = Math.max(0, base.inputTokens - (sub.inputTokens ?? 0))
const outputTokens = Math.max(0, base.outputTokens - (sub.outputTokens ?? 0))
const cacheReadTokens = Math.max(0, base.cacheReadTokens - (sub.cacheReadTokens ?? 0))
const cacheWriteTokens = Math.max(0, base.cacheWriteTokens - (sub.cacheWriteTokens ?? 0))
if (calls === 0 && cost === 0 && savingsUSD === 0 && inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0) return null
return { calls, cost, savingsUSD, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
}
function subtractModels(base: DailyEntry['models'] | undefined, sub: DailyEntry['models'] | undefined): DailyEntry['models'] | undefined {
if (!base) return undefined
const out: DailyEntry['models'] = {}
for (const [name, stats] of Object.entries(base)) {
const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined
const reduced = s ? subtractModelStats(stats, s) : stats
if (reduced) setOwn(out, name, reduced)
}
return Object.keys(out).length > 0 ? out : undefined
}
function subtractCategoryStats(base: CategoryDayStats, sub: CategoryDayStats): CategoryDayStats | null {
const turns = Math.max(0, base.turns - (sub.turns ?? 0))
const cost = Math.max(0, base.cost - (sub.cost ?? 0))
const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0))
const editTurns = Math.max(0, base.editTurns - (sub.editTurns ?? 0))
const oneShotTurns = Math.max(0, base.oneShotTurns - (sub.oneShotTurns ?? 0))
if (turns === 0 && cost === 0 && savingsUSD === 0 && editTurns === 0 && oneShotTurns === 0) return null
return { turns, cost, savingsUSD, editTurns, oneShotTurns }
}
function subtractCategories(base: DailyEntry['categories'] | undefined, sub: DailyEntry['categories'] | undefined): DailyEntry['categories'] | undefined {
if (!base) return undefined
const out: DailyEntry['categories'] = {}
for (const [name, stats] of Object.entries(base)) {
const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined
const reduced = s ? subtractCategoryStats(stats, s) : stats
if (reduced) setOwn(out, name, reduced)
}
return Object.keys(out).length > 0 ? out : undefined
}
function subtractProjectStats(base: ProjectDayStats, sub: ProjectDayStats): ProjectDayStats | null {
const cost = Math.max(0, base.cost - (sub.cost ?? 0))
const calls = Math.max(0, base.calls - (sub.calls ?? 0))
const savingsUSD = Math.max(0, (base.savingsUSD ?? 0) - (sub.savingsUSD ?? 0))
const sessions = Math.max(0, (base.sessions ?? 0) - (sub.sessions ?? 0))
if (cost === 0 && calls === 0 && savingsUSD === 0 && sessions === 0) return null
return { cost, calls, savingsUSD, sessions, ...(base.path ? { path: base.path } : {}) }
}
function subtractProjects(base: DailyEntry['projects'] | undefined, sub: DailyEntry['projects'] | undefined): DailyEntry['projects'] | undefined {
if (!base) return undefined
const out: DailyEntry['projects'] = {}
for (const [name, stats] of Object.entries(base)) {
const s = sub && Object.hasOwn(sub, name) ? sub[name] : undefined
const reduced = s ? subtractProjectStats(stats, s) : stats
if (reduced) setOwn(out, name, reduced)
}
return Object.keys(out).length > 0 ? out : undefined
}
/// How much a nested stat entry actually lost: `base` before minus `reduced`
/// after, or null when nothing was lost. The raw `sub` is only a lower bound -
/// with tz skew it can exceed the slice, and subtracting it would eat OTHER
/// providers' share of the day-level breakdown.
function modelStatsDelta(base: ModelDayStats, reduced: ModelDayStats): ModelDayStats | null {
const calls = base.calls - reduced.calls
const cost = base.cost - reduced.cost
const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0)
const inputTokens = base.inputTokens - reduced.inputTokens
const outputTokens = base.outputTokens - reduced.outputTokens
const cacheReadTokens = base.cacheReadTokens - reduced.cacheReadTokens
const cacheWriteTokens = base.cacheWriteTokens - reduced.cacheWriteTokens
if (calls === 0 && cost === 0 && savingsUSD === 0 && inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0) return null
return { calls, cost, savingsUSD, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
}
function categoryStatsDelta(base: CategoryDayStats, reduced: CategoryDayStats): CategoryDayStats | null {
const turns = base.turns - reduced.turns
const cost = base.cost - reduced.cost
const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0)
const editTurns = base.editTurns - reduced.editTurns
const oneShotTurns = base.oneShotTurns - reduced.oneShotTurns
if (turns === 0 && cost === 0 && savingsUSD === 0 && editTurns === 0 && oneShotTurns === 0) return null
return { turns, cost, savingsUSD, editTurns, oneShotTurns }
}
function projectStatsDelta(base: ProjectDayStats, reduced: ProjectDayStats): ProjectDayStats | null {
const cost = base.cost - reduced.cost
const calls = base.calls - reduced.calls
const savingsUSD = (base.savingsUSD ?? 0) - (reduced.savingsUSD ?? 0)
const sessions = (base.sessions ?? 0) - (reduced.sessions ?? 0)
if (cost === 0 && calls === 0 && savingsUSD === 0 && sessions === 0) return null
return { cost, calls, savingsUSD, sessions }
}
/// Remove `sub`'s contribution from a carried baseline day (the baseline-only
/// date branch of the merge, where the whole day clones over). Reduces the
/// provider's slice, the day-level totals, and the day-level models/categories/
/// projects maps that `addSliceIntoDay` would have grown them by.
///
/// Every day-level subtraction uses the EFFECTIVE removal - what the provider
/// slice actually lost (current before minus reduced after) - not the raw `sub`.
/// With tz skew (`freshUnderOldTz` content larger than the baseline slice), the
/// raw sub exceeds the slice and subtracting it would over-remove the day's
/// totals and its nested maps, eating unrelated providers' carried history and
/// breaking the invariant that a day's totals sum to its slices. A provider
/// slice that was absent has an effective removal of zero: nothing is subtracted
/// from the day.
function subtractSliceFromDay(day: DailyEntry, provider: string, sub: ProviderDaySlice): void {
const current = Object.hasOwn(day.providers, provider) ? day.providers[provider] : undefined
if (!current) return
const reduced = subtractSlice(current, sub)
if (reduced) setOwn(day.providers, provider, reduced)
else delete day.providers[provider]
day.cost = Math.max(0, day.cost - (current.cost - (reduced?.cost ?? 0)))
day.calls = Math.max(0, day.calls - (current.calls - (reduced?.calls ?? 0)))
day.savingsUSD = Math.max(0, (day.savingsUSD ?? 0) - ((current.savingsUSD ?? 0) - (reduced?.savingsUSD ?? 0)))
day.sessions = Math.max(0, day.sessions - ((current.sessions ?? 0) - (reduced?.sessions ?? 0)))
day.inputTokens = Math.max(0, day.inputTokens - ((current.inputTokens ?? 0) - (reduced?.inputTokens ?? 0)))
day.outputTokens = Math.max(0, day.outputTokens - ((current.outputTokens ?? 0) - (reduced?.outputTokens ?? 0)))
day.cacheReadTokens = Math.max(0, day.cacheReadTokens - ((current.cacheReadTokens ?? 0) - (reduced?.cacheReadTokens ?? 0)))
day.cacheWriteTokens = Math.max(0, day.cacheWriteTokens - ((current.cacheWriteTokens ?? 0) - (reduced?.cacheWriteTokens ?? 0)))
day.editTurns = Math.max(0, day.editTurns - ((current.editTurns ?? 0) - (reduced?.editTurns ?? 0)))
day.oneShotTurns = Math.max(0, day.oneShotTurns - ((current.oneShotTurns ?? 0) - (reduced?.oneShotTurns ?? 0)))
for (const [name, m] of Object.entries(current.models ?? {})) {
const rm = reduced?.models && Object.hasOwn(reduced.models, name) ? reduced.models[name] : undefined
const removed = rm ? modelStatsDelta(m, rm) : m
if (!removed) continue
const acc = Object.hasOwn(day.models, name) ? day.models[name] : undefined
if (!acc) continue
const reducedM = subtractModelStats(acc, removed)
if (reducedM) setOwn(day.models, name, reducedM)
else delete day.models[name]
}
for (const [cat, c] of Object.entries(current.categories ?? {})) {
const rc = reduced?.categories && Object.hasOwn(reduced.categories, cat) ? reduced.categories[cat] : undefined
const removed = rc ? categoryStatsDelta(c, rc) : c
if (!removed) continue
const acc = Object.hasOwn(day.categories, cat) ? day.categories[cat] : undefined
if (!acc) continue
const reducedC = subtractCategoryStats(acc, removed)
if (reducedC) setOwn(day.categories, cat, reducedC)
else delete day.categories[cat]
}
if (!day.projects) return
for (const [name, p] of Object.entries(current.projects ?? {})) {
const rp = reduced?.projects && Object.hasOwn(reduced.projects, name) ? reduced.projects[name] : undefined
const removed = rp ? projectStatsDelta(p, rp) : p
if (!removed) continue
const acc = Object.hasOwn(day.projects, name) ? day.projects[name] : undefined
if (!acc) continue
const reducedP = subtractProjectStats(acc, removed)
if (reducedP) setOwn(day.projects, name, reducedP)
else delete day.projects[name]
}
}
/// Did the tz subtraction leave any positive data on a carried baseline day?
/// Mirrors the merge's own carry criterion (`hasSliceData` or sessions) at the
/// day level, extended to the day's other scalar and nested content.
function hasPositiveDayContent(day: DailyEntry): boolean {
if (day.cost > 0 || day.calls > 0 || (day.savingsUSD ?? 0) > 0 || day.sessions > 0) return true
if (day.inputTokens > 0 || day.outputTokens > 0 || day.cacheReadTokens > 0 || day.cacheWriteTokens > 0) return true
if (day.editTurns > 0 || day.oneShotTurns > 0) return true
if (Object.keys(day.providers).length > 0) return true
if (Object.keys(day.models).length > 0 || Object.keys(day.categories).length > 0) return true
if (day.projects && Object.keys(day.projects).length > 0) return true
return false
}
/// Index `freshUnderOldTz` (the same parse re-aggregated under the cache's OLD
/// tzKey) by date then provider, so the merge can subtract exactly what the
/// fresh parse still explains under the old bucketing.
function buildTzSubtraction(days: DailyEntry[]): ReadonlyMap<string, ReadonlyMap<string, ProviderDaySlice>> {
const byDate = new Map<string, Map<string, ProviderDaySlice>>()
for (const day of days) {
if (Object.keys(day.providers).length === 0) continue
const byProvider = new Map<string, ProviderDaySlice>()
for (const [provider, slice] of Object.entries(day.providers)) {
byProvider.set(provider, slice)
}
byDate.set(day.date, byProvider)
}
return byDate
}
/// Merge two day lists per (date, provider): `primary` wins wherever both have
/// data; `secondary` only fills dates primary lacks entirely and provider
/// slices primary lacks on shared dates. Nothing in secondary can overwrite or
/// double into primary. With markSecondaryCarried, every day that received a
/// secondary contribution is flagged `carried`.
///
/// Days that cannot be attributed per provider merge all-or-nothing:
/// - an OPAQUE primary day (pre-v5-era: totals but empty providers map) is
/// never slice-filled — its totals may already contain the incoming
/// provider's share, so adding would double-count;
/// - an opaque secondary day on a date primary already has contributes
/// nothing — its day-level totals cannot be attributed without slices.
/// A primary slice blocks a secondary one only when it carries DATA; a
/// zero-data placeholder (sessions only) is merged into, not treated as a
/// re-derivation of the provider's day.
/// `subtract`, present ONLY on the tz-change re-derive, maps (date, provider)
/// to the content the fresh parse still attributes there under the OLD
/// bucketing. Every baseline slice the merge would otherwise carry has that
/// content subtracted first (clamped at 0, dropped when nothing positive
/// remains), so turns that re-bucketed across local midnight are not counted on
/// both their old and new days. Absent (undefined) on every other path, which
/// keeps those merges byte-identical to the pre-fix behavior.
export function mergeDayEntries(
primary: DailyEntry[],
secondary: DailyEntry[],
markSecondaryCarried: boolean,
subtract?: ReadonlyMap<string, ReadonlyMap<string, ProviderDaySlice>>,
): DailyEntry[] {
const byDate = new Map<string, DailyEntry>()
for (const day of primary) byDate.set(day.date, structuredClone(day))
for (const day of secondary) {
const existing = byDate.get(day.date)
if (!existing) {
const copy = structuredClone(day)
if (subtract) {
const subForDate = subtract.get(day.date)
if (subForDate) {
for (const [provider, slice] of Object.entries(copy.providers)) {
const subSlice = subForDate.get(provider)
if (!subSlice) continue
subtractSliceFromDay(copy, provider, subSlice)
}
if (!hasPositiveDayContent(copy)) continue
}
}
if (markSecondaryCarried) copy.carried = true
byDate.set(day.date, copy)
continue
}
if (isOpaqueDay(existing)) continue
for (const [provider, slice] of Object.entries(day.providers)) {
// Sessions-only slices (a session whose calls all landed on another
// day) still carry a real session count — worth preserving.
if (!hasSliceData(slice) && !(slice.sessions ?? 0)) continue
const existingSlice = Object.hasOwn(existing.providers, provider) ? existing.providers[provider] : undefined
if (existingSlice && hasSliceData(existingSlice)) continue
let toAdd = slice
let residual = false
if (subtract) {
const subSlice = subtract.get(day.date)?.get(provider)
if (subSlice) {
const reduced = subtractSlice(slice, subSlice)
if (!reduced) continue
toAdd = reduced
// The subtraction already removed the sessions the fresh parse
// explained, so the residual's sessions are distinct from the fresh
// placeholder's: merging over it must ADD, not max-dedup (fix round
// 1 - max would drop the source-gone sessions the residual carries).
residual = true
}
}
addSliceIntoDay(existing, provider, toAdd, residual)
if (markSecondaryCarried) existing.carried = true
}
}
return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date))
}
export function getDaysInRange(cache: DailyCache, start: string, end: string): DailyEntry[] {
return cache.days.filter(d => d.date >= start && d.date <= end)
}
let lockChain: Promise<unknown> = Promise.resolve()
export function withDailyCacheLock<T>(fn: () => Promise<T>): Promise<T> {
const next = lockChain.then(() => fn())
lockChain = next.catch(() => undefined)
return next
}
export const MS_PER_DAY = 24 * 60 * 60 * 1000
export const BACKFILL_DAYS = 365
// Ten years. This cache is the ONLY durable record of carried days (their
// session files are long deleted), and the uncapped `lifetime` period reads
// from it via buildDurablePeriod, so pruning at the old 2-year mark would
// have replayed the lost-history bug in slow motion at that horizon.
// Measured envelope keeps this honest: ~2.3 MB / ~11 ms JSON parse per 730
// days of fully dense data, so even a decade of daily use stays ~11 MB and
// well under 100 ms on the polling path.
export const DAILY_CACHE_RETENTION_DAYS = 3650
export function toDateString(date: Date): string {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
export async function ensureCacheHydrated(
parseSessions: (range: DateRange) => Promise<ProjectSummary[]>,
aggregateDays: (projects: ProjectSummary[]) => DailyEntry[],
/// Hash of the active `localModelSavings` config. When this changes
/// (user re-mapped a baseline) the cached `savingsUSD` totals are no
/// longer accurate, so we treat the cache as stale and force a full
/// re-hydration. Pass `''` for "no savings config" to disable.
savingsConfigHash: string = '',
/// Whether the session parse that fed this backfill left the session cache
/// fully hydrated. A partial (interrupted) session cache yields empty/partial
/// older days; finalizing them would freeze that gap into the daily history.
/// So the backfill is only marked `complete` when this returns true. Defaults
/// to a trusting `true` for callers that don't (or can't) supply it.
sessionComplete: () => boolean = () => true,
/// Re-aggregate the SAME parsed projects under an explicit timezone instead of
/// the machine's local one. Used only on a tz-change re-derive: the result is
/// compared against the fresh local-tz days to subtract the turns that
/// re-bucketed across local midnight from the carried baseline (issue #770).
/// Absent, the tz-change path carries forward exactly as it did before.
aggregateDaysInTz?: (projects: ProjectSummary[], tz: string) => DailyEntry[],
): Promise<DailyCache> {
const now = new Date()
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const yesterdayEnd = new Date(todayStart.getTime() - 1)
const yesterdayStr = toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1))
return withDailyCacheLock(async () => {
let c = await loadDailyCache()
// Drop any cached entry dated today or later BEFORE anything else can
// carry it forward. The cache only ever stores complete past days (up to
// yesterday), so a >= today entry can only come from the clock moving
// backward or a stale older cache; left in place it would be served frozen
// instead of recomputed live. Yesterday and earlier stay cached.
const todayStr = toDateString(now)
if (c.days.some(d => d.date >= todayStr)) {
const freshDays = c.days.filter(d => d.date < todayStr)
const latestFresh = freshDays.length > 0 ? freshDays[freshDays.length - 1].date : null
c = { ...c, days: freshDays, lastComputedDate: latestFresh }
}
// A cache can claim `complete` while its watermark points PAST its newest
// populated day — what a run finalizing off a degraded (read-only) parse
// leaves behind: it advanced lastComputedDate over days the parse never
// covered. Since gapStart is lastComputedDate + 1, that hole is invisible
// to the gap logic forever. Trust the DATA over the marker: pull the
// watermark back to the newest day actually present so the ordinary gap
// parse re-derives the tail. Nothing is dropped — the cached days all stay.
//
// Only UNSTAMPED caches are distrusted here. A degraded parse can no longer
// set `complete` (that is this fix), so the corrupt state can only be
// written by pre-fix code: an unstamped cache. A stamped one whose watermark
// outruns its newest day is a legitimately idle tail (recent days had no
// activity), and re-deriving that empty tail on every launch is the
// regression this guard avoids. A cache with NO days is exempt: it has no
// newest day to trust, and a machine with no history at all must still be
// able to finalize (below) rather than re-backfill on every launch.
const newestCachedDate = c.days.reduce<string | null>((max, d) => (max === null || d.date > max ? d.date : max), null)
if (c.watermarkTrusted !== true && newestCachedDate !== null && c.lastComputedDate !== null && c.lastComputedDate > newestCachedDate) {
c = { ...c, lastComputedDate: newestCachedDate }
}
// Three reasons to re-derive the whole retention window:
// 1. Savings config changed — cached `savingsUSD` totals are stale.
// 2. The cache was never finalized against a COMPLETE session parse (an old
// pre-marker cache, an adoption from older cache files, or one frozen
// from a partial/interrupted hydration).
// 3. The local timezone changed — days are bucketed by local midnight, so a
// TZ change mis-buckets every cached day. Only invalidate when a tzKey is
// present and differs (a cache written before this field, or a test
// fixture, has none → left alone rather than force a spurious rebuild).
//
// Re-derive, NOT discard. Session files are ephemeral; a cached day whose
// sources are gone exists nowhere else, so the old days stay as a baseline
// and the fresh parse overrides per (day, provider) wherever it actually
// produced data. What it could not re-derive is carried forward (marked
// `carried`) with its old accounting — every wipe here before v14 turned
// into permanently lost history.
const tzKey = currentTzKey()
const tzChanged = c.tzKey !== undefined && c.tzKey !== tzKey
if (c.savingsConfigHash !== savingsConfigHash || c.complete !== true || tzChanged) {
const baseline = c.days
const priorWatermark = c.lastComputedDate
const backfillStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - BACKFILL_DAYS)
let freshDays: DailyEntry[] = []
let projects: ProjectSummary[] = []
if (backfillStart.getTime() <= yesterdayEnd.getTime()) {
// Hoisted so a tz-change re-derive can aggregate the SAME parse twice
// (once under the current tz as freshDays, once under the cache's old
// tzKey as freshUnderOldTz) without a second session parse.
//
// The parse stops at yesterdayEnd. Keeping it a HISTORY parse is what
// makes the parser slice a midnight-straddling turn at the yesterday
// boundary: day-N's turn-level category/counts then carry only the
// pre-midnight half and today's live parse carries the rest, so the two
// sides reconcile (issue #852). Widening THIS parse through now would
// leave the full turn on day N while today's half was excluded from the
// cache, breaking that reconciliation - so the subtraction below gets
// its own through-now parse instead.
projects = await parseSessions({ start: backfillStart, end: yesterdayEnd })
freshDays = aggregateDays(projects)
}
const parseWasComplete = sessionComplete()
// A PARTIAL parse must not overwrite finalized baseline days with
// undercounts (if their sources die before the next complete parse, the
// undercount would be what survives). Partial fresh data only fills days
// and slices the baseline lacks; the next complete parse gets to win.
//
// On a complete-parse TZ re-derive (savings config untouched), subtract
// from each carried baseline slice the content the fresh parse still
// attributes to that (date, provider) under the OLD bucketing: the turns
// that re-bucketed across local midnight. That is the issue #770
// double-count; re-pricing drift (a savings-hash change) must never be
// subtracted, so a hash change in the same re-derive skips this entirely.
let tzSubtraction: ReadonlyMap<string, ReadonlyMap<string, ProviderDaySlice>> | undefined
if (parseWasComplete && tzChanged && c.savingsConfigHash === savingsConfigHash && aggregateDaysInTz && c.tzKey !== undefined) {
// The subtraction re-parses THROUGH NOW (fix round 1): a call bucketed
// to OLD-tz yesterday that re-buckets to NEW-tz TODAY sits past the
// history parse's yesterdayEnd, so `freshUnderOldTz` built from `projects`
// would never see it - the baseline slice would be carried un-subtracted
// while today's live parse counts it again. This second parse exists
// ONLY for the subtraction; it never feeds freshDays, so the merged
// days written to the cache stay exactly the history days and today is
// still owned by the caller's live parse.
const wideProjects = await parseSessions({ start: backfillStart, end: now })
tzSubtraction = buildTzSubtraction(aggregateDaysInTz(wideProjects, c.tzKey))
}
const merged = parseWasComplete
? mergeDayEntries(freshDays, baseline, true, tzSubtraction)
: mergeDayEntries(baseline, freshDays, false)
c = {
version: DAILY_CACHE_VERSION,
savingsConfigHash,
tzKey,
// The watermark records how far history has actually been derived, so
// only a COMPLETE parse may advance it. A partial one produced no data
// for whatever it could not read; moving the watermark to yesterday
// anyway would place those days behind the next run's gapStart and
// freeze the hole in (retention still anchors on yesterdayStr — the
// real calendar edge — so holding the watermark can't evict anything).
lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark,
days: applyRetention(merged, yesterdayStr),
complete: parseWasComplete,
// Stamp the watermark as trusted only when a COMPLETE parse produced it,
// so a later idle tail under this watermark is not distrusted above.
watermarkTrusted: parseWasComplete,
}
await saveDailyCache(c)
return c
}
if (c.tzKey === undefined) {
// First write under the tzKey scheme: tag the cache so a later TZ change is
// detectable, without discarding the (still-valid, same-TZ) cached days.
c = { ...c, tzKey }
}
const gapStart = c.lastComputedDate
? new Date(
parseInt(c.lastComputedDate.slice(0, 4)),
parseInt(c.lastComputedDate.slice(5, 7)) - 1,
parseInt(c.lastComputedDate.slice(8, 10)) + 1
)
: new Date(now.getFullYear(), now.getMonth(), now.getDate() - BACKFILL_DAYS)
if (gapStart.getTime() <= yesterdayEnd.getTime()) {
const gapRange: DateRange = { start: gapStart, end: yesterdayEnd }
const gapProjects = await parseSessions(gapRange)
const gapDays = aggregateDays(gapProjects)
const parseWasComplete = sessionComplete()
const priorWatermark = c.lastComputedDate
c = addNewDays(c, gapDays, yesterdayStr)
// Finalize as complete ONLY when the session parse that produced these days
// was itself complete. If it was partial, leave `complete: false` so the
// next launch (once the session cache is whole) re-backfills instead of
// freezing the partial history — and hold the watermark where it was, for
// the same reason as the re-derive path above: a partial parse cannot
// vouch for the days it never read, and gapStart is the only thing that
// will ever bring them back.
c = { ...c, lastComputedDate: parseWasComplete ? c.lastComputedDate : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete }
await saveDailyCache(c)
} else if (c.complete !== true && sessionComplete()) {
// No gap to fill (already current through yesterday) but not yet marked —
// e.g. a brand-new machine whose only data is today. Finalize so future
// launches don't re-backfill the whole window every time.
c = { ...c, complete: true, watermarkTrusted: true }
await saveDailyCache(c)
}
return c
})
}