mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-08-29 18:33:01 +00:00
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.
100 lines
4.9 KiB
TypeScript
100 lines
4.9 KiB
TypeScript
import chalk from 'chalk'
|
|
import type { ProjectSummary } from './types.js'
|
|
import { behavioralCallCount } from './behavioral-weight.js'
|
|
|
|
// Re-exported from currency.ts so existing imports from './format.js' keep working.
|
|
// The currency-aware version applies exchange rate and symbol automatically.
|
|
// Imported locally too since renderStatusBar below uses it directly.
|
|
import { formatCost } from './currency.js'
|
|
export { formatCost }
|
|
|
|
/// Prefix a formatted cost with the estimated marker (`~`) when the figure is
|
|
/// priced from estimated tokens rather than metered. Keeps the marker identical
|
|
/// across the report, overview, and MCP surfaces so a legend line can explain it
|
|
/// once. `isEstimated` is typically `entry.estimatedCostUSD > 0`.
|
|
export function markEstimated(costStr: string, isEstimated: boolean): string {
|
|
return isEstimated ? `~${costStr}` : costStr
|
|
}
|
|
|
|
/// Shared wording for the durable-cache carry-forward footnote: some of a
|
|
/// period's total came from days whose session logs have since expired, but
|
|
/// the figure is real (preserved in the durable daily cache). overview.ts and
|
|
/// dashboard.tsx both show this so a headline that includes carried days
|
|
/// doesn't read as inconsistent with detail views that can only see
|
|
/// surviving session files.
|
|
export function carriedCostNote(carriedCostUSD: number): string | null {
|
|
return carriedCostUSD > 0 ? `includes ${formatCost(carriedCostUSD)} preserved from expired session logs` : null
|
|
}
|
|
|
|
export function formatTokens(n: number): string {
|
|
// Guard against Infinity / NaN / negatives that would otherwise leak into
|
|
// the UI as "Infinity" or "NaN" strings when an upstream calculation glitches.
|
|
if (!Number.isFinite(n)) return '?'
|
|
if (n < 0) return '0'
|
|
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
|
|
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
|
|
return Math.round(n).toString()
|
|
}
|
|
|
|
/// Returns YYYY-MM-DD for the given date in the process-local timezone. Cheaper than shelling
|
|
/// out to Intl.DateTimeFormat for every turn in a loop and avoids the UTC drift that bites
|
|
/// `Date.toISOString().slice(0,10)` whenever the user runs this between local midnight and
|
|
/// UTC midnight.
|
|
function localDateString(d: Date): string {
|
|
const y = d.getFullYear()
|
|
const m = String(d.getMonth() + 1).padStart(2, '0')
|
|
const day = String(d.getDate()).padStart(2, '0')
|
|
return `${y}-${m}-${day}`
|
|
}
|
|
|
|
/// Precomputed today/month totals from the durable daily cache. When supplied,
|
|
/// the status bar renders these instead of bucketing the live parse, so the
|
|
/// figures match the menubar exactly (carried, expired-source days included).
|
|
export type StatusBarTotals = {
|
|
today: { cost: number; calls: number }
|
|
month: { cost: number; calls: number }
|
|
}
|
|
|
|
export function renderStatusBar(projects: ProjectSummary[], totals?: StatusBarTotals): string {
|
|
const now = new Date()
|
|
const today = localDateString(now)
|
|
const monthStart = `${today.slice(0, 7)}-01`
|
|
|
|
let todayCost = 0, todayCalls = 0, monthCost = 0, monthCalls = 0
|
|
if (totals) {
|
|
todayCost = totals.today.cost; todayCalls = totals.today.calls
|
|
monthCost = totals.month.cost; monthCalls = totals.month.calls
|
|
const lines: string[] = ['']
|
|
lines.push(` ${chalk.bold('Today')} ${chalk.yellowBright(formatCost(todayCost))} ${chalk.dim(`${todayCalls} calls`)} ${chalk.bold('Month')} ${chalk.yellowBright(formatCost(monthCost))} ${chalk.dim(`${monthCalls} calls`)}`)
|
|
lines.push('')
|
|
return lines.join('\n')
|
|
}
|
|
|
|
for (const project of projects) {
|
|
for (const session of project.sessions) {
|
|
for (const turn of session.turns) {
|
|
if (turn.assistantCalls.length === 0) continue
|
|
// Bucket by the first assistant call's local date -- the moment the cost was
|
|
// incurred. Bucketing by `turn.timestamp` (the user message time) drops turns
|
|
// that straddle midnight (user asked at 23:58, response arrived at 00:30) and
|
|
// disagrees with parseAllSessions' dateRange filter which is also on assistant
|
|
// time.
|
|
const bucketTs = turn.assistantCalls[0]!.timestamp
|
|
if (!bucketTs) continue
|
|
const day = localDateString(new Date(bucketTs))
|
|
const turnCost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0)
|
|
// Cost keeps every call; the calls figure counts only behavioral ones,
|
|
// so a supplementary-only turn still spends but adds no requests.
|
|
const turnCalls = behavioralCallCount(turn.assistantCalls)
|
|
if (day === today) { todayCost += turnCost; todayCalls += turnCalls }
|
|
if (day >= monthStart) { monthCost += turnCost; monthCalls += turnCalls }
|
|
}
|
|
}
|
|
}
|
|
|
|
const lines: string[] = ['']
|
|
lines.push(` ${chalk.bold('Today')} ${chalk.yellowBright(formatCost(todayCost))} ${chalk.dim(`${todayCalls} calls`)} ${chalk.bold('Month')} ${chalk.yellowBright(formatCost(monthCost))} ${chalk.dim(`${monthCalls} calls`)}`)
|
|
lines.push('')
|
|
|
|
return lines.join('\n')
|
|
}
|