feat(serve): resident serve child reuses status snapshots across requests (#1135 part 2) (#1146)

* 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.
This commit is contained in:
Resham Joshi 2026-08-25 10:13:43 -07:00 • committed by GitHub
parent 4da30a5a27
commit d34f32ec87
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 97 additions and 12 deletions

View file

@ -9,6 +9,7 @@
### Added
- **`codeburn status --format menubar-json` can serve from a disk-persisted snapshot.** A background poll whose corpus has not changed since the last computation is answered from a per-query snapshot keyed on a corpus fingerprint (ordered source topology, per-provider env fingerprints, five config hashes, currency, pricing generation, cache and package versions - any mismatch is a miss), eliminating the per-poll re-parse on idle machines. A snapshot is only ever written for a complete, non-degraded parse: the save gate requires the payload's own captured markers (`stale !== true`, no `hydration` block), so a poll that went read-only under a held refresh lock can never pin its under-reported totals to disk - a regression holds the refresh lock and asserts no snapshot file is written. Serve-side and one-shot outputs are unchanged; the optimization currently engages for `--no-optimize` polls (the menubar background refresh). Thanks @dgabehar, hardening @ozymandiashh. (#999)
- **The menubar status snapshot now re-validates persisted records on load, mirroring the save gate.** A snapshot record whose payload carries degradation markers (`stale: true` or a `hydration` block) is treated as a miss and recomputed instead of served, so a record that should never have been written (older build, hand-edited file) can never pin under-reported totals; the save gate from #999 is unchanged. Extending the snapshot to the default optimize path was evaluated on this branch and reverted in post-build review: `scanAndDetect`'s findings depend on mutable state the corpus fingerprint never observes (`~/.claude` and project-level `settings.json`, `CLAUDE.md`, defined skills, agents, commands, MCP config), and re-deriving them on a snapshot hit requires the parsed corpus, which is the full parse the snapshot exists to avoid on exactly the cold processes it serves. The optimize path therefore still never reads or writes the disk snapshot, and one-shot and serve-child outputs are byte-identical to before for both optimize values. (#1135)
- **The parser captures provider-recorded session lineage instead of discarding it.** Claude agent transcripts carry a provider-written parent session reference (and the parent side records the spawned agent id when compaction has not dropped it); Kimi Code subagent sessions live inside their parent session's own directory. Both now populate an optional `lineage` field on the parsed session model - `parentSessionId`, a root/child role, and `evidence: 'provider-recorded'` - persisted through the session cache, with claude and kimicode parse versions bumped for the one-time re-derive. Strictly provider-recorded evidence only: no inference from time adjacency or shared projects, and a session with no evidence carries no lineage field at all. Purely additive metadata: a pinning test asserts every report total is byte-identical with the field present or absent. Groundwork for spend attribution across delegated-agent families (a measured 5.1% of sessions carry direct lineage but 76% of 90-day spend). (#1140)
### Fixed (macOS)

View file

@ -1175,18 +1175,21 @@ program
pricingGenerationKey: getPricingGenerationKey(),
})
// Optimize findings (the default; see --no-optimize) depend on mutable
// project/config/prompt/hook state — ~/.claude and project-level
// settings.json, CLAUDE.md, defined skills/agents/commands, MCP config
// — that computeCorpusFingerprint and queryKey never observe and that
// has no single enumerable fingerprint. Persisting THIS class of output
// would mean editing a hook or removing an unused skill leaves the
// menubar showing stale findings with no session change to ever
// invalidate them. Simplest correct fix: the optimize path never reads
// or writes the disk snapshot at all, it always recomputes fresh.
// (Computing scanAndDetect's findings requires the same parsed project
// data the snapshot exists to avoid recomputing, so skipping the
// snapshot loses no additional work versus fingerprinting these inputs
// — that path would still force a fresh parse to re-scan them.)
// project/config/prompt/hook state: ~/.claude and project-level
// settings.json, CLAUDE.md, defined skills/agents/commands, MCP config.
// computeCorpusFingerprint and queryKey never observe those inputs, and
// they have no single enumerable fingerprint. Persisting THAT class of
// output would leave an agent edit with no session change serving stale
// findings indefinitely. Caching only the base payload and re-deriving
// the findings on each hit (#1135 part 2) was tried on this branch and
// reverted in post-build review: scanAndDetect needs the parsed corpus,
// so the re-derivation pays the full parse the snapshot exists to avoid
// on exactly the cold processes the snapshot is for, and the resident
// serve child gains nothing either because its in-memory output memo
// already dedupes a repeated argv. Simplest correct stance: the
// optimize path never reads or writes the disk snapshot at all, it
// always recomputes fresh. One-shot and serve-child behavior are
// identical for both optimize values.
const useSnapshot = !queryScope.optimize
const corpus = useSnapshot ? await computeCorpusFingerprint(pf) : null
const snapshot = corpus ? await loadStatusSnapshot(corpus.hash, queryKey, STATUS_SNAPSHOT_SEMANTIC_KEY) : null

View file

@ -1963,6 +1963,12 @@ export async function loadStatusSnapshot(corpusFingerprint: string, queryKey: st
const stored = await readStatusSnapshotRecord(queryKey)
if (!stored) return null
if (stored.semanticKey !== semanticKey) return null
// Belt-and-braces mirror of the save gate in main.ts: a payload marked
// degraded (`stale === true` or a `hydration` block) must never have been
// persisted, so one that somehow was (an older build, a hand-edited file)
// is treated as a miss and recomputed rather than served.
const candidate = stored.payload as { stale?: unknown; hydration?: unknown } | null | undefined
if (candidate !== null && typeof candidate === 'object' && (candidate.stale === true || candidate.hydration !== undefined)) return null
if (stored.corpusFingerprint === corpusFingerprint) return stored.payload ?? null
const now = Date.now()

View file

@ -910,6 +910,51 @@ describe('codeburn status --format menubar-json', () => {
}
})
it('reflects appended session activity on the very next optimize-path call', async () => {
const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-optimize-miss-'))
try {
const projectDir = join(home, '.claude', 'projects', 'myapp')
await mkdir(projectDir, { recursive: true })
const now = new Date()
const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000))
const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z')
await writeFile(
join(projectDir, 'session.jsonl'),
[userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1')].join('\n'),
)
// Same provider for both calls: the only delta between the two
// invocations is the appended session line, so a changed answer can
// only come from the corpus change being picked up, never from a
// queryKey change.
const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'claude']
const first = runCli(args, home)
expect(first.status, `stderr: ${first.stderr}`).toBe(0)
const firstPayload = JSON.parse(first.stdout) as { current: { calls: number } }
expect(firstPayload.current.calls).toBe(1)
// The optimize path never reads the disk snapshot, so the new session
// line shows up immediately, with no settle window to wait out.
await writeFile(
join(projectDir, 'session.jsonl'),
[
userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1'),
userLine('s1', ts(120_000)), assistantLine('s1', ts(180_000), 'msg-2'),
].join('\n'),
)
const second = runCli(args, home)
expect(second.status, `stderr: ${second.stderr}`).toBe(0)
const secondPayload = JSON.parse(second.stdout) as { current: { calls: number } }
expect(secondPayload.current.calls).toBe(2)
} finally {
await rm(home, { recursive: true, force: true })
}
})
it('still emits a valid combined menubar payload when the remotes store is corrupt', async () => {
const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-corrupt-remotes-'))

View file

@ -168,6 +168,36 @@ describe('concurrent writers (status snapshot)', () => {
})
})
// Belt-and-braces mirror of the save gate in main.ts (#1135 fix round): a
// payload marked degraded (`stale === true` or a `hydration` block) must
// never have been persisted, so a record that somehow carries those markers
// (older build, hand-edited file) loads as a miss and is recomputed.
describe('load-time re-validation mirrors the save gate', () => {
it('treats a persisted payload carrying stale === true as a miss', async () => {
const queryKey = 'degraded-stale'
await saveStatusSnapshot('corpus-a', 1_000, 1_000, queryKey, SEMANTIC_KEY, { stale: true, p: 'degraded' })
expect(await loadStatusSnapshot('corpus-a', queryKey, SEMANTIC_KEY)).toBeNull()
})
it('treats a persisted payload carrying a hydration block as a miss', async () => {
const queryKey = 'degraded-hydration'
await saveStatusSnapshot('corpus-a', 1_000, 1_000, queryKey, SEMANTIC_KEY, {
hydration: { complete: false, indexedFiles: 1, totalFiles: 2 },
p: 'partial',
})
expect(await loadStatusSnapshot('corpus-a', queryKey, SEMANTIC_KEY)).toBeNull()
})
it('still serves a clean persisted payload (control)', async () => {
const queryKey = 'clean-control'
await saveStatusSnapshot('corpus-a', 1_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'clean' })
expect(await loadStatusSnapshot('corpus-a', queryKey, SEMANTIC_KEY)).toEqual({ p: 'clean' })
})
})
// Post-merge review of PR #999: a `status --format menubar-json --no-optimize`
// poll that runs while ANOTHER process holds `session-refresh.lock` parses
// read-only and serves a degraded corpus (payload.stale === true), and a later