0.9.25: correctness, energy, menu bar and installer fixes (#1511)

* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG

CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed;
codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate;
openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp;
sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty);
codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+
grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export
subfolder; providers pane fixed window; Warp credit-based cost.
Desktop/menubar: unified flame logo; default DMG; docs signed+notarized.

* menubar: one running instance, self-relaunch on language change

The single-instance guard only retired strictly older copies, so two login
items starting in the same instant both survived, and a copy whose bundle
identity did not survive install was never seen at all. The decision is now
total (newest launch wins, ties break on pid) and peers are matched on bundle
id or executable name. --keep-both opts one launch out.

Language changes no longer have the desktop app quit and reopen the menu bar,
which made macOS attribute the new process to the desktop app and re-ask for
the data-access grant. The menu bar relaunches itself via the existing remote
command key; older menu bars that do not watch the key fall back to the old
path after 5s.

* desktop: export toast shows the saved path; resource buckets on app_close

The export toast showed the folder that was picked, not the dated subfolder
the files land in. The handler already parsed the CLI's saved line; it now
returns that path and the toast uses it.

app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket
labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb
to its answer frames. Unmeasured figures are omitted, never sent as zero.

* menubar guard never leaves zero instances; installer replaces in place; JSON export into folder

Guard: an unreadable launch date on either side could make two copies retire
each other. Unreadable peers now count only when their pid is lower, and a copy
that cannot read its own date retires lower pids only, so a disagreement keeps
at least one instance.

Installer: an existing bundle in /Applications or ~/Applications is replaced
where it lives instead of a second copy being added. The old bundle is moved
aside and restored on any failure; a cross-volume move falls back to a copy that
is re-verified with codesign. An unwritable location is never escalated: the
install goes to ~/Applications and the leftover is named.

Export: -o pointing at an existing folder writes the JSON inside it. Short
sessions omit the cpu buckets. setLanguage reopens the menu bar if its own
relaunch never comes back. AppRelaunch passes the bundle path as an argument.

* menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install

Guard: launch dates could be unreadable and pid order can disagree with start
order after pid reuse, so two copies could still retire each other. Ordering now
uses the kernel-reported process start time, which both sides read identically.
A copy whose start time cannot be read is left out, so the worst case is two
menu bars, never none.

Installer: with the only copy in an unwritable /Applications, a plain run tried
to open a path that did not exist. It now opens the installed copy. A placement
killed mid-way is recovered on the next run, a concurrent install is refused,
and a failed restore names where the previous bundle is. Process matching uses
the exact executable name.

Export: a trailing separator names a folder. Telemetry cpu is measured from
telemetry start.

* installer: a recycled pid can no longer block installs; language change waits for the replacement process

An aside left by an earlier install counted as an active install whenever its
pid was live, so once that pid was reused every install was refused for good.
It now also has to be recent (ctime within 10 minutes), a pid we may not signal
is not ours, the refusal names the file, and an orphan that cannot be cleared is
reported instead of aborting the install.

setLanguage confirmed the relaunch with a matcher the dying process still
satisfied, so the reopen fallback never fired. It now waits for a pid that was
not running before.

* desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers

An open window ran act report (a fresh CLI process each time), yield and an
optimize scan on every refresh. The headline poll now passes --no-optimize and
takes the snapshot path; act report refreshes on mount, on manual refresh and
every 10 minutes, yield every 5. The optimize scan runs at most once a day per
query scope, is stored in userData with its time, and is forced fresh by the
Optimize page or a manual refresh. Figures that are not live show their age,
and no stored scan means no savings clause rather than a zero.

On battery the live interval doubles; the chosen cadence stays the base.

* desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch

The scan cache is keyed on the argv, which says 'today' or '30days', not a date,
so yesterday's scan was served as today's. It is now reused only on the same
local day. Stored findings in Signals carry their age, a failed scan shows the
error instead of scanning forever, and the cold-boot label uses the time the app
received the payload.

usePolled fetched immediately whenever its interval changed, so every power
transition (and launching on battery) refetched every live hook and could spawn
an extra act report. Fetching and timer arming are now separate effects.
Optimize's yield is on the same 5 minute tier as Overview.

* desktop: re-ask for the optimize scan on the first render of a new local day

An app left open across midnight kept yesterday's stored savings under Today,
because the scan was only requested on mount, scope change or manual refresh.
The local day is now one of the hook's triggers; the previous day's figure is
dropped while the new scan runs.

* serve: a menubar poll is never answered from the status snapshot

Inside its settle window the status snapshot returns the pre-change payload on
purpose. The resident serve process then memoized that answer as clean, so after
a single write followed by quiet the headline stayed on the old figure until the
next write or the five minute memo cap. The snapshot is for one-shot runs; the
resident process already holds the parsed state, so it now skips it.

* tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card

ServeConnection takes its pid file as a parameter, so the Swift tests no longer
share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the
reaper only signals a record that is a serve --stdio command.

Superseded session-cache, codex-results and cursor-results files (100MB+ each)
are removed once untouched for 14 days, at most once a day. daily-cache and the
hermes ledger are never swept: they carry sealed days a version bump adopts.

The menu bar installer's leftover-copy advice is emitted as a marked line under
CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is
debug only. The app's vitest workers turn off Node's built-in web storage.

* menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray

The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows
tray. It now follows the desktop's telemetry.v1.json when that exists (read
only: same install id, same on/off, onboarded required) and otherwise keeps its
own state with the same region default (off in EU/EEA/UK/CH and when the region
is unknown). Settings gains one Privacy toggle, disabled when the desktop owns
the choice. Events use the tray's names; the daily usage snapshot is the CLI's
block passed through a sanitizer and is left to the desktop when it is the
consent source. Debug builds never send.

A resident CLI that gets disabled for the run now says so in the log.

* menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away

The sender used URLSession.shared, so a server or CDN cookie and the default
User-Agent rode along and would have outlived an opt-out. It now owns an
ephemeral session with no cookies, no cache, a fixed agent string and no
redirects. A batch that is out when the toggle goes off is dropped rather than
re-queued under the fresh id. The desktop's answer is recorded locally, so a
missing or damaged state file never falls back to the region default, and the
standalone id is persisted when minted. The toggle stays usable as a local off
switch under desktop consent. Copy states what this app actually sends.

* vercel gateway spend is shown on its own row and kept out of totals by default

The gateway reports daily aggregates per model, with nothing to match against
the local tools that were pointed at it, so every headline counted that traffic
twice. Totals now leave the gateway slice out when all providers are shown; the
row keeps its full amount and is marked not in total, --provider vercel-gateway
is unchanged, and codeburn gateway-totals include folds it back in. The daily
cache still stores the slice, so the choice applies retroactively. Reports with
no gateway credential are byte-identical.

The gateway's request_count now feeds the call count instead of each daily row
counting as one call. Hermes: a mid-session price change lands on the day it is
observed and sealed days are never rewritten; stated in the code and changelog.

* gateway exclusion applies to every report through the parse, and the detail panels follow the headline

The first pass narrowed only the day totals, so By tool, top models, top
projects, activities, status json projects and any project-filtered table still
carried gateway spend next to a headline that did not, and By tool shares could
pass 100%. The rule now lives in parseAllSessions: with all providers in scope
and the opt-in off, aggregate-only sessions are dropped after the memo, and the
callers that derive cached days opt out so stored slices are unchanged.
day.projects is reduced like models. The gateway stays visible once, as a
labelled not-in-total row with no share, and standalone reports note the
excluded amount on stderr so machine output is unchanged.

* dashboard: the background history index follows the gateway exclusion too

The index keeps the whole corpus so it can fill the daily cache, but its
per-period projection handed that unfiltered list to the project, model and
activity panels, so they regained gateway spend once the index landed.

* ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits

The cache-lock step failed 6 of the last 60 runs with no output for five minutes
after the vitest banner; passing runs take 12-18s on every Node version. Each
attempt is now capped at 90s and retried once, with a warning whenever that
happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn
status snapshot test and the c6 parser suite get limits taken from those runs,
each with its reason. Both test jobs print their ten slowest cases.

* desktop: Privacy & data uses the same rows as the rest of Settings

The pane mixed two static claims with two controls in its own layout. It now
uses the about-row pattern every other pane uses: title and hint on the left,
one control on the right. The claims became the subtitle. Rows: anonymous usage
statistics (toggle, link to what is sent), device sharing state with Manage,
local report snapshots with Clear, export with Open export.

* desktop: Privacy & data keeps one bounded column and rows that never squeeze

The card stretched with the window, stranding each control hundreds of pixels
from its text. This pane's heading, subtitle and card now share a 760px column
and one text measure. Rows stack on their own width, because the window can
never be narrow enough for the old viewport rule to fire; row buttons do not
wrap. The what-is-sent link sits on its own line, and the snapshot and export
descriptions fit their measure and say this machine.

* menubar tests clean up their scratch defaults and leave the real Keychain alone

Four test files never removed their UserDefaults suites and the rest removed the
domain but left the plist, so thousands of files piled up in
~/Library/Preferences. A shared helper forgets a suite and deletes its file, and
every test that makes a suite now uses it. cfprefsd still rewrites an empty plist
when the test process exits, so a run leaves about a hundred 42-byte files with
no test data in them. The real-Keychain round trip only runs with
CODEBURN_TEST_REAL_KEYCHAIN=1.

* desktop: the resident parser retires after 15 idle minutes and restarts on demand

The renderer stops polling while the window is hidden, but the serve child stayed
resident with its parsed cache, one to two GB on a large corpus. After 15 minutes
without a request it is stopped the way a settings restart stops it, without
spending the unexpected-death budget, and the next request starts a new resident
through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or
disables it.

* desktop: every settings pane keeps a bounded column, and dark buttons have an edge

Cards stretched with the window, so on a wide display controls sat up to 1300px
from their labels and intro lines ran past 140 characters. All panes now share
one left-aligned column (760px, 980px for projects, aliases and pricing, which
hold wide rows) and one text measure. Rows stack on their own width instead of a
viewport rule the 900px minimum window could never reach, and a long path in
Projects no longer overflows the pane.

In dark mode the secondary button matched or sat below its surface, and was
invisible on the plugin install dialog. It gets a face and a border from two new
tokens; light is unchanged. The onboarding consent label matches Settings.

* desktop: this device shows its fingerprint on its own line

The local name and the fingerprint are two adjacent inline spans, so they read as
one run of text.

* menubar: the resident parser retires after 15 idle minutes and restarts on demand

The menu bar kept its serve child, and the parsed cache with it, for the whole
run, even with the popover closed and nothing changing. After 15 minutes without
a request the child is retired without counting as a death, and the next request
starts a new resident through ensureStarted, never the one-shot fallback, whose
snapshot settle window would make the figure lag a whole tick. The window sits
above the longest gap between real requests, so a child stays warm while work is
happening. CodeBurnServeIdleSeconds tunes or disables it.

* serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced

With a session being written, every poll re-listed about 2,400 directories and
re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month
shard (49MB on a large corpus) and read it back on the next poll. The resident
process now reuses the previous listing and fingerprints for paths its root
watcher proves untouched, and falls back to the full sweep whenever the watcher
is missing, unhealthy, overflowed, armed after the sweep, does not cover the
path, the memo is older than 4.5 minutes, or the process was suspended. Shard
publication is held for up to 90s and flushed when stdin closes; a held write is
dropped rather than written over something another process published. One-shot
runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence;
time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete,
rename-over, in-flight, watcher overflow and unhealthy watcher.

Changelog: state the telemetry default as it is in this version.

* a retired parser gets to publish its held shards, and durable providers are never held

Both apps retired the serve child with SIGTERM before its stdin-close flush could
run, so every retire discarded the coalesced window. They now close stdin, give
the child a bounded grace to publish and exit, and signal it only if it is still
running; a settings restart does the same. Measured: flushed 0/5 before, 5/5
after, for both clients.

copilot's cache entries are the only record once Copilot prunes its own files, so
a held window that was dropped (retire, crash, kill -9) before the source was
pruned lost that spend for good. A window that a durable provider dirtied is
published on the poll that parsed it, as before coalescing existed. The RSS guard
publishes a held window before it clears the caches instead of discarding it.

* serve: release the lifetime parse after the fill, and make the collection real

The RSS guard dropped its memos and then called globalThis.gc, which exists only
under --expose-gc; no launcher passes it, so the collection had never run and the
freed pages never went back. On a cold start the resident idled at 2.2GB with
364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by
700MB.

After the background fill has sealed its summaries the process now publishes any
held shard window, drops the memos it can re-read from disk (the cold start had
loaded the cache with scope 'all', which then served every later poll), and
collects; it collects again a minute later for as long as a pass returns 64MB,
at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are
leaf-identical cold and warm, time-to-reflect unchanged, a released month scope
reloads in 0.3-0.5s.

* warp: the billed cost reaches reports and survives the cache

The provider derived a dollar cost from Warp's own billing record (provider cents,
charged usage, or credits), but warp was missing from the reported-cost
pass-through, so the cached call kept no cost and every report, cold or warm,
priced the conversation from its tokens. A fixture billed at $1.22 reported
$0.15. A call whose cost came from a billing record now keeps it; a call that
only has the token floor stores none and is still re-priced when prices change.

Warp entries re-parse once (provider parse version), and the daily cache moves to
v34 so days whose Warp source still exists re-derive; call counts do not move, so
nothing is double counted or dropped.

* openclaw and pi: a reported cost survives the cache like every other reported cost

Both providers read the cost their tool recorded for a message, and both were
missing from the reported-cost pass-through, so reports priced every call from
tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013
against $0.410 (pi). A call with a reported cost now keeps it; a call with none,
or an explicit zero, stores none and is still re-priced when prices change. omp
had been added to the list in #1150 and pi, the same parser, was never revisited.

The provider list is one named set, the unreachable providerCallToTurn is gone,
and both providers re-parse once; the v34 daily cache re-derives their days with
call counts unchanged.

* test: pin parse count per report and per resident poll
This commit is contained in:
Resham Joshi 2026-09-21 00:16:21 +02:00 • committed by GitHub
parent ea78d36ccf
commit 2fc62f7876
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
155 changed files with 9251 additions and 783 deletions

View file

@ -24,6 +24,7 @@ import {
type CachedCall,
type CachedFile,
type CachedTurn,
type FileFingerprint,
type ProviderSection,
type SessionCache,
beginColdHydration,
@ -31,7 +32,9 @@ import {
computeEnvFingerprint,
DURABLE_PROVIDER_NAMES,
fingerprintFile,
hasDirtyDurableProvider,
isCacheComplete,
isCacheCurrent,
isCacheDirty,
loadCache,
markCacheDirty,
@ -46,7 +49,8 @@ import { classifyWslCachePath, isWslUncPath, refreshWslHomes, wslMode } from './
import { decideParseWorkers, parseFilesInOrder, ParseWorkerPool, type ClaudeWorkerParse, type ParseJob } from './parse-workers.js'
import type { CodexFullParse } from './providers/codex.js'
import { dateKey } from './day-aggregator.js'
import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js'
import { behavioralCallWeight, isBehavioralTurn } from './behavioral-weight.js'
import { gatewayIncludedInTotals } from './config.js'
import type { ParsedProviderCall, Provider, SessionSource } from './providers/types.js'
import type {
ApiUsageIteration,
@ -1226,7 +1230,7 @@ function applyLocalModelSavings(call: ParsedApiCall): ParsedApiCall {
const savings = calculateLocalModelSavings(
call.model,
u.inputTokens,
u.outputTokens,
billableOutputTokens(call.provider, u.outputTokens, u.reasoningTokens),
u.cacheCreationInputTokens,
u.cacheReadInputTokens,
u.webSearchRequests,
@ -1798,7 +1802,7 @@ function buildSessionSummary(
totalCacheWrite += call.usage.cacheCreationInputTokens
// Supplementary accounting calls contribute tokens/cost above but are
// not distinct requests: no api-call or per-model call weight.
if (isBehavioralCall(call)) apiCalls++
apiCalls += behavioralCallWeight(call)
const modelKey = call.provider === 'devin' ? call.model : modelRowKey(call.model, call.route)
if (!modelBreakdown[modelKey]) {
@ -1810,7 +1814,7 @@ function buildSessionSummary(
tokens: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0 },
}
}
if (isBehavioralCall(call)) modelBreakdown[modelKey].calls++
modelBreakdown[modelKey].calls += behavioralCallWeight(call)
modelBreakdown[modelKey].costUSD += call.costUSD
modelBreakdown[modelKey].savingsUSD += callSavings
modelBreakdown[modelKey].estimatedCostUSD = (modelBreakdown[modelKey].estimatedCostUSD ?? 0) + callEstimated
@ -2019,8 +2023,12 @@ async function scanProjectDirs(
// order: the reconcile loop feeds order-sensitive state (changedFiles order
// drives the worker-result pairing, seenMsgIds pre-seeding), so only the
// syscalls are allowed to overlap.
const gate = openSweepGate()
const sweptAt = Date.now()
const walked = await mapWithConcurrency(dirs, FS_SCAN_CONCURRENCY, async ({ path: dirPath }) => {
const jsonlFiles = await collectJsonlFiles(dirPath)
const remembered = sweepDirFiles(gate, dirPath)
const jsonlFiles = remembered ?? await collectJsonlFiles(dirPath)
if (!remembered) rememberSweepDir(dirPath, jsonlFiles, sweptAt)
dirsDone++
await discoverProgress.tick(dirsDone)
return jsonlFiles
@ -2030,7 +2038,13 @@ async function scanProjectDirs(
const { name: dirName, source } = dirs[i]!
for (const filePath of walked[i]!) discovered.push({ filePath, dirName, source })
}
const fingerprints = await mapWithConcurrency(discovered, FS_SCAN_CONCURRENCY, e => fingerprintFile(e.filePath))
const fingerprints = await mapWithConcurrency(discovered, FS_SCAN_CONCURRENCY, async (e) => {
const remembered = sweepFingerprint(gate, e.filePath)
if (remembered) return remembered
const fp = await fingerprintFile(e.filePath)
rememberSweepFingerprint(e.filePath, fp, sweptAt)
return fp
})
for (const [i, { filePath, dirName, source }] of discovered.entries()) {
allDiscoveredFiles.add(filePath)
const fp = fingerprints[i]
@ -2541,51 +2555,35 @@ export function extractPrUrlsFromText(text: string): string[] {
return [...new Set(text.match(PR_URL_IN_TEXT_RE) ?? [])].sort()
}
function providerCallToTurn(call: ParsedProviderCall): ParsedTurn {
const tools = call.tools
const usage: TokenUsage = {
inputTokens: call.inputTokens,
outputTokens: call.outputTokens,
cacheCreationInputTokens: call.cacheCreationInputTokens,
cacheReadInputTokens: call.cacheReadInputTokens,
cachedInputTokens: call.cachedInputTokens,
reasoningTokens: call.reasoningTokens,
webSearchRequests: call.webSearchRequests,
}
const apiCall: ParsedApiCall = applyLocalModelSavings({
provider: call.provider,
model: call.model,
usage,
costUSD: call.costUSD,
tools,
mcpTools: extractMcpTools(tools),
skills: call.skills ?? [],
subagentTypes: call.subagentTypes ?? [],
hasAgentSpawn: tools.includes('Agent'),
hasPlanMode: tools.includes('EnterPlanMode'),
speed: call.speed,
timestamp: call.timestamp,
bashCommands: call.bashCommands,
deduplicationKey: call.deduplicationKey,
isEstimated: call.costIsEstimated,
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
...(call.route ? { route: call.route } : {}),
...(call.billing ? { billing: call.billing } : {}),
})
const prRefs = extractPrUrlsFromText(call.userMessage)
return {
userMessage: call.userMessage,
assistantCalls: [apiCall],
timestamp: call.timestamp,
sessionId: call.sessionId,
...(prRefs.length ? { prRefs } : {}),
}
}
// ── Cache Conversion ───────────────────────────────────────────────────
// Providers whose every parsed call carries a cost the tool itself computed or
// was billed, not one derived from that call's tokens. Their cost is stored on
// the cached call and served verbatim; every other provider's is recomputed
// from the cached tokens on read (cachedCallToApiCall), so a pricing update
// still reaches it.
//
// A new provider should set `ParsedProviderCall.costFromBilling` instead of
// joining this set. The flag decides per call, so a provider that reports a
// cost for some calls and falls back to token pricing for the rest keeps that
// fallback re-priceable; membership here is the whole-provider form of the
// same rule, kept for the providers that adopted it before the flag existed.
// Either way, adding a provider needs a `PROVIDER_PARSE_VERSIONS` bump: calls
// cached before the change hold `costUSD: undefined` and would otherwise be
// re-priced from tokens forever.
export const REPORTED_COST_PROVIDERS: ReadonlySet<string> = new Set([
'mistral-vibe',
'antigravity',
'devin',
'vercel-gateway',
'hermes',
'kiro',
'codewhale',
'quickdesk',
'cline-cli',
'omp',
])
function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
return {
provider: call.provider,
@ -2600,7 +2598,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
webSearchRequests: call.webSearchRequests,
cacheCreationOneHourTokens: 0,
},
costUSD: (call.provider === 'mistral-vibe' || call.provider === 'antigravity' || call.provider === 'devin' || call.provider === 'vercel-gateway' || call.provider === 'hermes' || call.provider === 'kiro' || call.provider === 'codewhale' || call.provider === 'quickdesk' || call.provider === 'cline-cli' || call.provider === 'omp') ? call.costUSD : undefined,
costUSD: (REPORTED_COST_PROVIDERS.has(call.provider) || call.costFromBilling === true) ? call.costUSD : undefined,
isEstimated: call.costIsEstimated || undefined,
speed: call.speed,
timestamp: call.timestamp,
@ -2619,6 +2617,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
...(call.locRemoved ? { locRemoved: call.locRemoved } : {}),
...(call.editFailed ? { editFailed: call.editFailed } : {}),
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
...(call.requestCount != null ? { requestCount: call.requestCount } : {}),
...(call.route ? { route: call.route } : {}),
...(call.billing ? { billing: call.billing } : {}),
...(call.requestMultiplier != null ? { requestMultiplier: call.requestMultiplier } : {}),
@ -2790,6 +2789,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall {
activeGeneratedTokens: call.activeGeneratedTokens,
toolWaitMs: call.toolWaitMs,
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
...(call.requestCount != null ? { requestCount: call.requestCount } : {}),
...(call.route ? { route: call.route } : {}),
...(call.billing ? { billing: call.billing } : {}),
...(call.supplementaryAccounting || isHermesObservationKey(call.deduplicationKey)
@ -3185,7 +3185,7 @@ function warnProviderParseFailure(providerName: string, sourcePath: string, err:
// discovery errors are already isolated; this catches a provider-level throw so
// one locked provider skips-and-continues instead of aborting the whole
// hydration (which would empty the cache/daily backfill for every provider).
function isPermissionError(err: unknown): boolean {
export function isPermissionError(err: unknown): boolean {
const code = (err as NodeJS.ErrnoException | undefined)?.code
return code === 'EPERM' || code === 'EACCES'
}
@ -3414,9 +3414,17 @@ export async function parseProviderSources(
// discovery order. Network sources on a write run never reach fingerprintFile
// (they take the synthetic-fingerprint branch below), so they are skipped here.
const skipFingerprint = provider.network && !readOnly
const gate = openSweepGate()
const sweptAt = Date.now()
const sourceFingerprints = skipFingerprint
? []
: await mapWithConcurrency(sources, FS_SCAN_CONCURRENCY, s => fingerprintFile(s.path))
: await mapWithConcurrency(sources, FS_SCAN_CONCURRENCY, async (s) => {
const remembered = sweepFingerprint(gate, s.path)
if (remembered) return remembered
const fp = await fingerprintFile(s.path)
rememberSweepFingerprint(s.path, fp, sweptAt)
return fp
})
for (const [sourceIndex, source] of sources.entries()) {
allDiscoveredFiles.add(source.path)
@ -4438,6 +4446,152 @@ export function setParseReuseValidator(validator: ParseReuseValidator | null): v
parseReuseValidator = validator
}
// ── Incremental discovery sweep (resident process only) ──────────────────────
// Discovery re-readdirs every project directory and re-stats every transcript
// on every parse. In a resident process the root watchers already know which
// paths moved, so a directory listing / file fingerprint the watcher proved
// untouched is reused instead of re-read. Nothing DERIVED is reused: only
// dev/ino/mtime/size, and `reconcileFile` still runs for every file.
export type SweepWatchSource = {
/** When watcher coverage began; anything remembered before it is unproven. */
startedAt: number
/** The roots actually armed. A path outside them is never event-covered. */
roots: readonly string[]
healthy: () => boolean
/** Paths changed since `sinceTs`, or null when coverage was unscoped. */
changedSince: (sinceTs: number) => string[] | null
}
// Held a little shorter than the watcher's own path retention so a remembered
// entry can never outlive the event record that would have invalidated it.
const SWEEP_MEMO_MAX_AGE_MS = VALIDATED_REUSE_CAP_MS - 30_000
// A wall-clock jump this much larger than elapsed monotonic time means the
// process was suspended (sleep/wake) and events could have been missed.
const SWEEP_SUSPEND_SLACK_MS = 2_000
let sweepWatchSource: SweepWatchSource | null = null
let sweepDirMemo = new Map<string, { files: string[]; at: number }>()
let sweepFpMemo = new Map<string, { fp: FileFingerprint; at: number }>()
let sweepClockMark: { wall: number; mono: number } | null = null
export function setSweepWatchSource(source: SweepWatchSource | null): void {
sweepWatchSource = source
sweepDirMemo = new Map()
sweepFpMemo = new Map()
sweepClockMark = null
}
type SweepGate = { minAt: number; changed: Set<string>; touched: Set<string>; roots: readonly string[] }
/// The per-parse decision. Null means "sweep exactly as before": no watcher,
/// degraded coverage, an unscoped event, a suspend, or a first parse.
function openSweepGate(): SweepGate | null {
const src = sweepWatchSource
const now = Date.now()
for (const [key, entry] of sweepDirMemo) if (entry.at < now - SWEEP_MEMO_MAX_AGE_MS) sweepDirMemo.delete(key)
for (const [key, entry] of sweepFpMemo) if (entry.at < now - SWEEP_MEMO_MAX_AGE_MS) sweepFpMemo.delete(key)
const mark = sweepClockMark
const mono = Math.trunc(performance.now())
sweepClockMark = { wall: now, mono }
// A wall clock that moved backwards would keep extending `minAt` backwards
// too, so treat it the same way a forward jump is treated.
if (mark && Math.abs((now - mark.wall) - (mono - mark.mono)) > SWEEP_SUSPEND_SLACK_MS) {
// Nothing remembered before the gap is trustworthy, and the gap is only
// visible once — so drop it all rather than let the next gate bless it.
sweepDirMemo.clear()
sweepFpMemo.clear()
return null
}
if (!src || !src.healthy()) return null
const minAt = Math.max(now - SWEEP_MEMO_MAX_AGE_MS, src.startedAt)
const changed = src.changedSince(minAt)
if (!changed) return null
// A changed path invalidates its own fingerprint and every directory listing
// that could contain it — the path itself (a renamed directory) and every
// ancestor, so a created or deleted file is seen by the next readdir.
const touched = new Set<string>()
for (const path of changed) {
for (let dir = path; ;) {
touched.add(dir)
const parent = dirname(dir)
if (parent === dir) break
dir = parent
}
}
return { minAt, changed: new Set(changed), touched, roots: src.roots }
}
function sweepCovers(gate: SweepGate, path: string): boolean {
// WSL/UNC roots are reached over a network redirector fs.watch does not cover,
// and a path outside every armed root has no event source at all.
if (isWslUncPath(path)) return false
return gate.roots.some(root => path === root || path.startsWith(root.endsWith(sep) ? root : root + sep))
}
function sweepDirFiles(gate: SweepGate | null, dirPath: string): string[] | null {
if (!gate || gate.touched.has(dirPath) || !sweepCovers(gate, dirPath)) return null
const hit = sweepDirMemo.get(dirPath)
return hit && hit.at >= gate.minAt ? hit.files : null
}
function sweepFingerprint(gate: SweepGate | null, path: string): FileFingerprint | null {
// Only plain transcripts. A SQLite source folds its `-wal` sibling in, and a
// virtual-suffix source (`<db>#cursor-ws=…`, `<db>:<session>`) fingerprints
// the underlying database — in both cases the watcher would name a path that
// is not this key, so no event could ever invalidate the entry.
if (!path.endsWith('.jsonl')) return null
if (!gate || gate.changed.has(path) || !sweepCovers(gate, path)) return null
const hit = sweepFpMemo.get(path)
return hit && hit.at >= gate.minAt ? hit.fp : null
}
/// Remember what this sweep read. `at` is captured BEFORE the syscall, so an
/// event that lands while the sweep runs still invalidates the entry.
function rememberSweepDir(dirPath: string, files: string[], at: number): void {
if (sweepWatchSource) sweepDirMemo.set(dirPath, { files, at })
}
function rememberSweepFingerprint(path: string, fp: FileFingerprint | null, at: number): void {
// A null fingerprint means the file was missing or unreadable; remembering
// that would hide its later appearance behind a quiet watcher.
if (sweepWatchSource && fp && path.endsWith('.jsonl')) sweepFpMemo.set(path, { fp, at })
}
// ── Coalesced shard publication (resident process only) ─────────────────────
// One appended transcript dirties one month bucket, and publishing that bucket
// rewrites the whole month — the single most expensive thing on the live poll
// path. A resident process publishes at most once per window and always on
// clean shutdown. A skipped publish writes NOTHING, so the on-disk cache stays
// exactly as consistent as it already was; the cost of losing a window is that
// the next start re-parses those appends, never a wrong number.
// Longer than the desktop's slowest poll (60s), or a window exactly as long as
// the cadence would expire before every poll and coalesce nothing.
const SHARD_PUBLISH_COALESCE_MS = 90_000
let shardPublishCoalescing = false
let lastShardPublishAt = 0
let pendingShardPublish: SessionCache | null = null
export function setShardPublishCoalescing(on: boolean): void {
shardPublishCoalescing = on
pendingShardPublish = null
lastShardPublishAt = 0
}
export function hasPendingShardPublish(): boolean {
return pendingShardPublish !== null
}
export async function flushPendingShardPublish(): Promise<void> {
const cache = pendingShardPublish
pendingShardPublish = null
if (!cache) return
lastShardPublishAt = Date.now()
// Unlike the deferral itself — which is published by a later refresh under
// that refresh's own fence — this one runs outside the lock, so it checks
// that nothing has been published since instead.
try {
if (await isCacheCurrent(cache)) await saveCache(cache)
} catch { /* a lost publish only costs a re-parse */ }
}
function burstReuse(dateRange: DateRange, sig: string): ProjectSummary[] | null {
const windowMs = parseBurstWindowMs()
if (windowMs <= 0) return null
@ -5544,7 +5698,74 @@ function deferToBackgroundFill(path: string, fp: { mtimeMs: number }, cached: un
return true
}
export function parseAllSessions(dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
/// Providers whose records are DAILY AGGREGATES instead of per-request rows:
/// Vercel AI Gateway's `/v1/report` returns one cost/token/request_count per
/// day per model, with no request id, timestamp or attribution. The local
/// tools that were pointed at the gateway (Claude Code via
/// ANTHROPIC_BASE_URL, Codex, OpenCode, Cline/Roo/Kilo, Cursor) record those
/// same requests in their own session files, and nothing in an aggregate row
/// can be matched against them — so a corpus holding both counts the same
/// spend twice.
export const AGGREGATE_ONLY_PROVIDER = 'vercel-gateway'
export const AGGREGATE_ONLY_PROVIDERS: ReadonlySet<string> = new Set([AGGREGATE_ONLY_PROVIDER])
/// True when an all-provider read must drop the aggregate-only corpus. A
/// provider-scoped read never does: `--provider vercel-gateway` exists to
/// inspect the full amount.
export function excludesAggregateOnlyProviders(providerFilter?: string): boolean {
return (providerFilter ?? 'all') === 'all' && !gatewayIncludedInTotals()
}
function hasAggregateOnlyCall(projects: ProjectSummary[]): boolean {
return projects.some(project => project.sessions.some(session =>
session.turns.some(turn => turn.assistantCalls.some(call => AGGREGATE_ONLY_PROVIDERS.has(call.provider)))))
}
/// Drop the aggregate-only providers from a parsed corpus, rebuilding every
/// nested total from the retained calls. Returns the SAME array when nothing
/// matches, so a machine with no gateway credential pays nothing and its
/// output is byte-identical to a build without this rule.
export function excludeAggregateOnlyProjects(projects: ProjectSummary[], providerFilter?: string): ProjectSummary[] {
if (!excludesAggregateOnlyProviders(providerFilter)) return projects
if (!hasAggregateOnlyCall(projects)) return projects
return filterProjectsByCall(projects, call => !AGGREGATE_ONLY_PROVIDERS.has(call.provider))
}
/// Cost the aggregate-only providers contribute to a corpus, for the "what was
/// left out" footnote. Read from the UNFILTERED parse.
export function aggregateOnlyCostUSD(projects: ProjectSummary[]): number {
let total = 0
for (const project of projects) {
for (const session of project.sessions) {
for (const turn of session.turns) {
for (const call of turn.assistantCalls) {
if (AGGREGATE_ONLY_PROVIDERS.has(call.provider)) total += call.costUSD
}
}
}
}
return total
}
/// `includeAggregateOnly` is the WRITE-side opt-out. The session cache and the
/// durable daily cache must keep sealing the gateway slice — it can never be
/// re-fetched for a past day — so the cache writer, and the aggregator paths
/// that derive day entries, ask for the full corpus and hold the provider out
/// of the totals at read time instead (`excludeProviderFromDay`). Every other
/// caller gets the shared default, which is what makes `models`, `sessions`,
/// `export`, `compare`, `spend`, `yield`, `audit`, `budget` and the sync push
/// agree with the headline without each one knowing the rule.
export function parseAllSessions(
dateRange?: DateRange,
providerFilter?: string,
opts?: { includeAggregateOnly?: boolean },
): Promise<ProjectSummary[]> {
const parsed = parseAllSessionsUnfiltered(dateRange, providerFilter)
if (opts?.includeAggregateOnly === true) return parsed
return parsed.then(projects => excludeAggregateOnlyProjects(projects, providerFilter))
}
function parseAllSessionsUnfiltered(dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
const scoped = singlePassParse(dateRange, providerFilter)
if (scoped) return scoped
// Capture synchronously, before the first await. AsyncLocalStorage keeps all
@ -5741,6 +5962,12 @@ async function runParseInner(
deferredRetryableSource = false
firstPaintDeferredThisRun = 0
dateFloorSkippedProviders.clear()
// Providers whose mid-scan read threw EPERM/EACCES: a recoverable permission
// error is "unknown", not "empty", so they are excluded from completeness
// marking (like a failed discovery) and block hydration-complete, so that
// restoring access later reopens the affected days instead of them staying
// sealed as fully scanned.
const permissionSkippedProviders = new Set<string>()
const seenMsgIds = new Set<string>()
const seenKeys = new Set<string>()
const discovery = snapshotOnly
@ -5808,6 +6035,7 @@ async function runParseInner(
if (claudeSources.length > 0) emitScanProgress({ kind: 'provider', provider: 'claude', state: 'done', files: claudeSources.length })
} catch (err) {
if (!isPermissionError(err)) throw err
permissionSkippedProviders.add('claude')
process.stderr.write(`codeburn: skipped claude data (permission denied; grant Full Disk Access to include it)\n`)
emitScanProgress({ kind: 'provider', provider: 'claude', state: 'skipped' })
}
@ -5825,6 +6053,7 @@ async function runParseInner(
// A permission-locked provider skips-and-continues; any other error is a
// real bug and still aborts (per-file/DB-lock cases are handled deeper).
if (!isPermissionError(err)) throw err
permissionSkippedProviders.add(providerName)
process.stderr.write(`codeburn: skipped ${providerName} data (permission denied; grant Full Disk Access to include it)\n`)
emitScanProgress({ kind: 'provider', provider: providerName, state: 'skipped' })
}
@ -5886,7 +6115,7 @@ async function runParseInner(
const deferredForFirstPaint = firstPaintDeferredThisRun > 0
const rangeStartMs = dateRange?.start.getTime()
const scopedRun = !!providerFilter && providerFilter !== 'all'
const discoveryFailed = new Set(discovery.failedProviders)
const discoveryFailed = new Set([...discovery.failedProviders, ...permissionSkippedProviders])
let completenessChanged = false
if (!readOnly && !deferredForFirstPaint) {
const walked = scopedRun ? [providerFilter!] : Object.keys(diskCache.providers)
@ -5901,7 +6130,25 @@ async function runParseInner(
}
}
if (!readOnly && (isCacheDirty(diskCache) || completenessChanged)) {
try {
// A superseded pre-image is dropped rather than carried: another process
// published, so this object's months were reloaded into a different one,
// and what the old one held is simply re-parsed.
if (pendingShardPublish && pendingShardPublish !== diskCache) pendingShardPublish = null
// A durable provider's cache entry is the only record of that spend once
// the provider prunes its own files, so its window is published on the poll
// that parsed it — exactly as it was before coalescing existed. Holding it
// would put the spend one `kill -9` away from being gone for good.
if (shardPublishCoalescing && !completenessChanged && !isCold
&& !hasDirtyDurableProvider(diskCache)
&& Date.now() - lastShardPublishAt < SHARD_PUBLISH_COALESCE_MS) {
// Held, not lost: the entries stay in this cache object — the one the
// next load memo hands back, dirty flags and all — until a later refresh
// publishes them under its own fence, or the shutdown flush does.
pendingShardPublish = diskCache
traceTiming('save', ' coalesced')
} else try {
pendingShardPublish = null
lastShardPublishAt = Date.now()
const published = await saveCache(diskCache, refreshLock?.verifyStillOwner)
if (!published) throw new RefreshFenceLostError()
} catch (err) {
@ -5913,7 +6160,7 @@ async function runParseInner(
// files, or a write run that deferred a changed source on a retryable
// failure, reached the end of the scan without hydrating everything, and
// the daily backfill must not finalize history off it.
sessionHydrationComplete = (!readOnly || !readOnlyServedStale) && !deferredRetryableSource && !deferredForFirstPaint
sessionHydrationComplete = (!readOnly || !readOnlyServedStale) && !deferredRetryableSource && !deferredForFirstPaint && permissionSkippedProviders.size === 0
sessionFirstPaintDeferred = deferredForFirstPaint
// Merge across providers by normalised project path so the same repository