* feat(cli): cache the menubar-json base payload on the optimize path (#1135)
The status snapshot keyed on a corpus fingerprint (#999) currently
excludes the default optimize path: persisting scanAndDetect's
findings alongside the base payload would pin a moment-in-time render
of the mutable, non-fingerprinted inputs the corpus fingerprint cannot
observe (settings.json, CLAUDE.md, defined skills/agents/commands,
MCP config) under a key with no way to invalidate them. That is the
exact defect commit 113ebb1c excluded the optimize path to avoid.
This change picks option (b) from the #1135 plan: the snapshot now
covers BOTH optimize=true and optimize=false (the queryKey already
carries optimize as a boolean, so the two are naturally partitioned
without a separate cache namespace). On a hit, the base payload is
served from disk and only the optimize block is re-derived fresh
through a new computeOptimizeBlock helper (re-running scanAndDetect
over a fresh parseAllSessions of the unchanged corpus). On a save,
the optimize block is stripped from the persisted record and
replaced with an empty placeholder, so a mutation in the
non-fingerprinted inputs between two requests at the same fingerprint
is reflected in the second response even though the rest of the
payload is byte-identical to the first. The save gate from #999 is
preserved verbatim (payload.stale !== true, payload.hydration ===
undefined, isSessionHydrationComplete()), the resident codeburn serve
in-memory output memo already keys on the full argv so the two
optimize values land in different memo entries, and the desktop
app's buildOverviewArgs has always sent the menubar-json query
without --no-optimize, so the new hit rate lights up with zero app
changes. (#1135)
* fix(cli): revert optimize-path snapshot reuse, re-validate snapshots on load (#1135)
Post-build review fix round on the optimize-path snapshot change:
1. Snapshot reuse is no longer attempted for one-shot optimize polls.
One-shot codeburn status invocations behave exactly as on main:
fresh compute, fresh generated timestamp. The pre-existing
--no-optimize one-shot save-gate behavior is unchanged.
2. The corpus-change test now holds --provider constant across both
calls, so the only delta is the appended session line and the test
proves a corpus change is picked up, not a queryKey change.
3. loadStatusSnapshot now mirrors the save gate: a persisted record
whose payload carries stale === true or a hydration block is treated
as a miss and recomputed. Belt-and-braces only; the save gate that
prevents such records is unchanged.
4. The optimize block cannot be re-derived on a snapshot hit without
the parsed corpus. scanAndDetect consumes the full ProjectSummary
trees plus a transcript scan plus ~/.claude state, so re-deriving it
pays the full fresh parse the snapshot exists to avoid on exactly
the cold processes the disk snapshot serves, and the resident serve
child gains nothing because its in-memory output memo already
dedupes a repeated argv. Deriving from warm caches is therefore not
honestly achievable, so this takes the plain exit: optimize-carrying
requests are excluded from reuse (useSnapshot = !queryScope.optimize
everywhere, the main semantics) and the computeOptimizeBlock helper,
the save-time optimize stripping, and the optimize-path snapshot
tests are reverted. Honesty over cleverness.
The CHANGELOG entry this branch added now describes the final
semantics. Full suite green, tsc clean.
* fix(tui): show quit feedback during the cold-start fill and exit on the second q (#1143)
Follow-up to #1142. With the input fix in place, q pressed during the
post-paint background index landed instantly but the exit path drained the
fill first - a deterministic ~16.5s silent wait on a 21k-file corpus.
The first q while the fill is active now arms a confirmation and renders
'Finishing background index so the next launch starts warm - press q or
Ctrl+C again to quit now' in the footer area, styled to match the
StatusBar (DIM border, ORANGE accent on the action key). The second q
takes the abrupt path, which #1109 already proved kill-safe (nothing
marked seen without being parsed, resume converges). Ctrl+C is unchanged:
it always exits through the abrupt path, whether or not the confirmation
is armed. q with no fill active exits immediately as before, with no
status-line flicker. The confirmation auto-clears the moment the fill
lands so a stale flag can never trap a later q.
The fill's indexing signal already flows to the dashboard (the #1109
banner reuses it), so no new global state was introduced. Pinning tests
added to tests/dashboard-exit.test.ts.
BREAKING NOTE FOR 0.9.22: ships in 0.9.22, not Unreleased.
* test: flush the unmount frame before the no-flicker assertion
The progressive cold start introduced by #1109 paints the dashboard from
recent files, then runs a background fill that parses the deferred
history and writes the per-file session cache. On a real 21k-file corpus
that fill's cache save publishes one JSON.stringify + fsync per provider
shard in a tight loop, and the whole save held the event loop long
enough that Ink's stdin reader never ran - a q or Ctrl+C pressed in the
post-paint window was swallowed, not buffered, and the user saw a
frozen terminal (#1139, #1141).
saveCache now yields to the event loop between every shard write, so
the Ink input handler fires between publishes. The yield sits BETWEEN
shards, never inside one, so each shard's temp+rename atomicity and the
lost-fence cleanup that owns the canonical envelope are preserved;
nothing marked seen without being parsed, the kill-safe resume
invariant from #1109 is intact, and the floored-parse memo key suffix
keeps warm reads byte-identical. The fill still parses every deferred
file, so money totals are unchanged.
The dashboard's useInput now exits on Ctrl+C through the same path as
q, so a raw 0x03 from the terminal lands as soon as the loop breathes.
Pinning tests:
- tests/save-cache-yields.test.ts: a setImmediate probe must interleave
with saveCache's shard writes.
- tests/dashboard-exit.test.ts: a raw \x03 exits the dashboard the
same way q does.
- tests/parser.test.ts: the copilot validated-clean re-parse test
tightens its fake-timer scope to only Date, so the new event-loop
yield inside saveCache still resolves under vitest's fake timers.
The #1109 cold-start one-shots (report, sessions, models, json/csv/
markdown, the desktop and menubar payloads) are unchanged.
Wire the SessionLineage field on SessionSummary and CachedFile. The
relationship is captured ONLY when a provider writes it on disk in a
durable form: a child file that names its parent (Claude's
transcript-internal sessionId on a sidechain; Kimi Code's state.json
agents[<id>].parentAgentId for any non-main agent), or a parent file
whose spawn / child manifest names the children (Claude's
agentSpawnLinks; Kimi Code's state.json agents map listing any non-main
entry). The brief forbids inference from time adjacency or directory
layout, so a parent whose only evidence is the child file living under
its directory does not yet qualify, and stays lineage-less.
Per provider:
- claude: child (parentSessionId present) or root (agentSpawnLinks
non-empty). Captured at install time and through the append-merge in
scanProjectDirs, where lineage is sticky and cached-first.
- kimicode: child (parentAgentId === 'main') or root (sibling non-main
entry alongside the main agent). state.json is read by
kimicodeLineageForSource, called from the per-provider install path.
Bump PROVIDER_PARSE_VERSIONS for both providers to session-lineage-capture-v1
so already-cached sessions gain the new field on the next cold parse
(env fingerprint change forces the re-parse; the field is purely
additive, no cost / token / call total moves).
Invariant: byte-identical report totals with and without the field.
The new parser-lineage-capture test asserts this on a Claude corpus
(parent + two children) and covers Claude two-sided linkage, Claude
one-sided (child file names parent while parent's spawn result was
compacted away), Kimi Code nested subagent (child and root variants),
no-evidence (no lineage field at all, not 'unknown'), and the cache
round-trip across a warm-disk reload.
Co-authored-by: codeburn <dev@codeburn.local>
The save gate re-read the module-level hydration global at a point the
codebase itself documents as unsafe: buildMenubarPayloadForRange runs
further parses (its own 365-day history re-parse included) after
capturing the verdict, and the last parse wins. A poll that went
read-only under a held refresh lock could therefore persist its
under-reported payload once a later parse reset the global, pinning
degraded dollars to disk until the corpus next changed. The gate now
requires the payload's own markers (stale !== true, no hydration
block), captured at the one safe read point, with the global kept as a
belt-and-braces conjunct. Regression holds the refresh lock, asserts
no snapshot file is written for the degraded pass, and that the next
clean pass writes one. Post-merge review follow-up to #999.
Round 3 adversarial-panel fixes for PR #999:
- Snapshot writes now go through a per-queryKey file plus a CAS re-read
guard before rename, closing the last-writer-wins race where a slower
recompute against an older corpus could clobber a fresher save, and
where distinct queryKeys used to evict each other's single shared slot
(B-G1).
- cline-cli's discoverSessions now fingerprints the growing
<sessionId>.messages.json sibling instead of the static
<sessionId>.json metadata file, so new turns in a live session are no
longer invisible to computeCorpusFingerprint (C-G1).
- computeCorpusFingerprint folds in computeEnvFingerprint per discovered
provider, so non-discovery env vars like CODEBURN_CURSOR_MAX_BUBBLES
and KIMI_MODEL_NAME can no longer serve a stale-forever snapshot (A-G1).
- collectFilesRecursive now resolves symlinked subdirectories and
recurses into them (with a visited-inode guard against cycles) instead
of misclassifying them as leaf files (C-G2).
- Added tests/session-cache-status-snapshot.test.ts covering concurrent
writers against the snapshot file, mirroring session-cache-shards.test.ts's
existing coverage for the main cache (D-G9).
Version 0.9.21 across CLI, desktop app, and Windows menubar; refreshed
LiteLLM pricing snapshot and fallback (catches the 2026-08-24 OpenAI
GPT-5.6 cut and DeepSeek v4 repricing mid-rollout, #1134 tracks
re-tightening); CHANGELOG stamped for 0.9.21; README release links to
0.9.21. Snapshot-pinned model tests updated to current catalog truth.
Second-round review fixes for the persisted menubar status snapshot
(getagentseal/codeburn#999, ozymandiashh review 2026-08-21):
- queryKey now folds in getPricingGenerationKey() (src/models.ts): the
live LiteLLM cache's freshness, the bundled snapshot's own content
digest, and the existing CACHE_SCHEMA_VERSION pricing-behavior
version. None of these moved the corpus fingerprint before, so a
repricing fetch or pricing-logic fix could keep serving old rendered
costs against an unchanged session corpus.
- The optimize path (default; --no-optimize unaffected) no longer
reads or writes the persisted snapshot at all. Optimize findings
depend on mutable project/config/prompt/hook state with no single
enumerable fingerprint, and computing them already requires the same
full parse the snapshot exists to skip, so excluding them from the
snapshot loses no additional performance versus fingerprinting that
input surface.
Adds two regression tests exercising both fixes end-to-end.
A turn anchored before the range start survives range slicing whole, so
the aggregator can emit a residue day the parse never covered (#1130,
found in #1127's root-cause work). The merge guards already defuse the
overwrite; this stops the residue from reaching durable history at all.
Applied at both ranged call sites (re-derive and gap); the aggregator
and slicer semantics are untouched — whole-corpus callers still
aggregate undated parses freely.
Diagnosed via #1127. Three guards:
- The gap-fill path no longer overwrites cached days wholesale: a
complete parse wins per (date, provider) through the same guarded
merge the re-derive path uses; a partial parse only fills days and
slices the baseline lacks. Previously a parse degraded by the
refresh lock (menubar running) could replace a good day with its
undercount permanently. The gap path also stops dropping
pendingRederive.
- A day whose only content is turn-anchored residue (a midnight-
straddling turn's category counts with zero cost/calls/tokens) is
never sealed: the watermark pulls back so the next launch re-derives
it — self-healing for every broken cache in the wild, no version
bump. Bounded to the settle window and never for the oldest cached
day.
- codeburn doctor gains a read-only Cache health section listing
residue-only dates and failed/empty session-cache entries, so the
next report like #1127 is diagnosable in one command.
Tests: residue-shape pin (day-aggregator), partial-gap cannot shrink a
populated day (fails on the old code), complete-gap parity, watermark
pull-back re-derive.
rolloutFileSessionId sliced 8192 bytes then JSON.parse. Production
session_meta first lines are 22-27 KB, so both trees returned
undefined ids and the overlapping nest source was kept. Read up to
the existing 1 MiB first-line cap and parse payload.session_id from
the complete line. Pin billed-A / nest-A / nest-B at 30 KB on the
exported no-arg singleton.
foldCopilotSupplementaryTurns will not fold a supplementary twin across
a local-day boundary, so the pair can occupy separate turns. Credit
spend now groups at session scope.
filterOverlap required an explicit nest path, so export const codex =
createCodexProvider() never deduped. When the resolved dir is a launcher
nest and ~/.codex is a distinct existing tree, discover both and drop nest
sources whose session id is already billed. Unique nest and billed sessions
stay. Soften the Buzz doctor note to a presence heuristic.
Providers that bill reasoning separately from output (the exclusive set)
were under-reported on the wire by exactly their reasoning volume —
measured on a real pilot push: opencode short by 37,848 tokens, the
summed reasoningTokens of the window. Cost was already correct (priced
locally before export). Route ai.output_tokens through
billableOutputTokens, the same correction the display layer took in
PR #1115. Inclusive providers (claude, codex, copilot) are byte-identical.
Span ids derive from dedup keys that carry no token counts, so nothing
re-sends and nothing duplicates.
Several providers key a project by its sanitized absolute path
("-Users-me-Projects-app"), and sync shipped that verbatim as ai.project
on usage and attribution spans — contradicting docs/sync/README.md's
promise that file paths stay local. Confirmed on real exports.
One choke point after parseAllSessions maps project to the leaf directory
name before either wire path reads it; codeburn yield's local output is
untouched. Never-lose: usage span ids and commit attribution keys carry
no project (unchanged, no re-send); session attribution keys hash the
record, so each already-synced session re-emits once and the receiver
upserts by (org, trace) — replaced, not duplicated. Two directories with
the same leaf name now collapse to one wire project identity; that is
the documented contract, and git.repo still disambiguates.
Owner ruling: state.db restored from backup without wiping the ledger
re-credits regrowth. Wipe both stores or accept the overcount. A
high-water-mark guard is rejected because it would eat 150→0→40 resets.
Parser sessions key modelBreakdown by getShortModelName. Leftover
raw-id buckets (overview fixtures, cached summaries) were minting a
second $0 / 0-call short-name row that findUnpricedModels flagged as
Unpriced and failed CI on #1116.
Spent credits are finite nanoAiu / 1e9. Token-priced costUSD does not
fill the Copilot bar. Thread nanoAiu through cachedCallToApiCall with
no cache-version bump.
Share one discovery-root resolver per provider so doctor reports the exact
paths discoverSessions reads: all three Codebuff CHANNELS, Devin's
transcripts + sessions.db children, Gemini's tmp parent, Kiro's pre-filter
candidates with empty CLI/v2 skipped, and Mistral Vibe's joined sessions dir.
Later observations with costBasis calculated were emitted as measured.
Derive the estimate marker from the stored basis so LiteLLM-priced
growth stays estimated, persist it through the session cache, and
lock the path with a discover/parse/ledger fresh+warm regression.
Per-call billable output was written under raw call.model while
parser buckets use getShortModelName. Display aliases split into a
zero-output named row and a phantom raw-id row. Aggregate-only
sessions fall back to each existing bucket.
Hermes rows are lifetime totals stamped at started_at. After a day is
sealed, later growth was dropped. A sidecar ledger records last-seen
totals per (profile, sessionId) and emits weight-0 observation-time
deltas so sealed days stay put while today's growth still lands.
Closes#916
Compare, export, report JSON, overview Top-model/By-tool/day, and
menubar localModelSavings still summed raw output. Session totals
stay defined on aggregate-only and stub calls. Upgrade verifier
expects daily-cache.v28.json.
The 0.9.20 menubar never completed a fetch on a large corpus: the cache
version bump forced a full rehydration, DataClient's fixed 45s kill ended
it mid-transaction, cache-refresh-lock had no signal cleanup so the dead
holder's lock survived, and DEFAULT_WAIT_MS (30s) < DEFAULT_STALE_MS (90s)
meant no waiter could ever recover it.
A. Swift port of #1096's watchdog. CLIWatchdog holds the constants and the
pure verdict; spawns and the resident serve child set CODEBURN_PROGRESS=1;
the window restarts on any stdout/stderr byte; 45s silence, 10min cold
floor until the first payload, 15min ceiling, SIGTERM then SIGKILL after
5s. ServeConnection's fixed 60s warm cap becomes the same silence window,
re-armed by each progress frame, and a spent death budget is now a
5-minute cooldown instead of disabling the resident for the app run.
B. cache-refresh-lock arms SIGINT/SIGTERM cleanup the way session-cache does
for hydrating.lock, so a SIGTERMed holder unlinks its own lock.
C. Staleness also opens on a dead holder pid, and the waiter budget derives
from staleMs so it can never expire before the gate it waits for. A live
holder - fresh heartbeat, pid answers signal 0 - is never taken from.
parser.ts heartbeats through the lock wait, the one silent stretch left.
D. The app closes its end of a retired child's stdin (dropping the handle
left the pipe alive inside the Process), reaps every serve child
synchronously at quit, and records pid+argv so a crash-orphaned child is
reaped next launch. serve's final exit no longer runs through a
monkeypatched process.exit, and its post-drain cleanup is bounded.
Closes#1117
The upgrade-path gate asserts serve menubar-json == the spawned one-shot
payload; an always-present hydration block on serve broke that on every
platform. Absence already means complete (the rule one-shot consumers live
by), so the explicit complete:true block bought nothing the invariant did
not already guarantee. Consumers were written for the optional field and
need no change.
Each surface holds its OWN serve child: the Swift menubar (mac/), GNOME and
Windows clients spawn `codeburn serve --stdio` too, and their payload
decoders ignore an unknown key — so they would have shown a partial total
with no way to say so. The paint is now opt-in via
CODEBURN_SERVE_PROGRESSIVE, which the Electron app sets on its own serve
child because its renderer shows the indexing banner. Unset means the child
answers only with complete data, so no surface can present partial totals
unlabelled.