codeburn/src/serve.ts
Resham Joshi 2fc62f7876
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
2026-09-21 00:16:21 +02:00

1009 lines
47 KiB
TypeScript

import { statSync, watch, type FSWatcher } from 'fs'
import { readFile, stat } from 'fs/promises'
import { join } from 'path'
import { createHash } from 'crypto'
import { createInterface } from 'readline'
import type { Command } from 'commander'
import { getDateRange, parseDayFlag, periodInfoFromQuery } from './cli-date.js'
import { getConfigFilePath } from './config.js'
import type { ParseReuseValidation } from './parser.js'
import { SERVE_HYDRATION_ENV } from './usage-aggregator.js'
import { suppressProjectFilterWarnings } from './project-filter-warnings.js'
import { isPathBlocked } from './sqlite.js'
// ---------------------------------------------------------------------------
// codeburn serve --stdio: a resident query server for the desktop app.
//
// Every CLI spawn on a large corpus pays seconds of fixed cost before any
// work: parsing a 100MB+ session-cache JSON, then re-deriving classification
// at query time. The desktop app fetches one payload per panel, so it pays
// that cost per fetch. This server is the same CLI kept warm: the app sends
// one JSON request per line ({id, args}) and gets the command's stdout back
// ({id, ok, output}); the session-cache memo in session-cache.ts makes every
// request after the first skip the JSON reload (a stat() revalidates, so a
// rewrite by another process still forces a fresh read).
//
// Correctness stance:
// - READ-ONLY allowlist. Only the hot panel queries run in-process; anything
// else is rejected and the app falls back to a normal spawn. A rejected
// command is a routing decision, not an error.
// - A FRESH commander program per request (buildProgram()), because commander
// option state is sticky across parses — reusing one program would leak
// `--period week` from one request into the defaults of the next.
// - Requests are strictly serialized. The parse/refresh pipeline is not
// concurrent-safe within one process, and the cross-process refresh lock
// already guards between processes.
// ---------------------------------------------------------------------------
// Past this resident-set size the serve loop drops its in-memory memos and
// re-parses on the next request. 6GB default leaves generous room for the
// largest observed corpora (a warm ~3GB cache survives) while bounding a
// pathological one. CODEBURN_SERVE_MAX_RSS_MB (integer MB) overrides it.
const DEFAULT_SERVE_MAX_RSS_MB = 6144
const SERVE_MAX_RSS_BYTES = (() => {
const mb = Number(process.env['CODEBURN_SERVE_MAX_RSS_MB'])
return (Number.isInteger(mb) && mb > 0 ? mb : DEFAULT_SERVE_MAX_RSS_MB) * 1024 * 1024
})()
// A warm cache holds RSS above the ceiling as a steady state, so clearing on
// every request would thrash the cache. Track the RSS at the last clear and
// require meaningful growth before clearing again — clear once per growth
// plateau, but still clear on real unbounded growth.
const SERVE_RSS_CLEAR_MARGIN_BYTES = 256 * 1024 * 1024
let lastClearRss = 0
// V8 exposes gc() only to a process started with --expose-gc, and no codeburn
// launcher passes it — so `globalThis.gc` was never there for the release below
// to call. Ask V8 for the function directly instead. It is the difference
// between the freed pages going back to the OS and the resident set sitting on
// them for the life of the child: measured on a warm 170MB shard set, a release
// that dropped 323MB of live objects moved RSS by 0MB without this and by
// 712MB with it.
let collect: (() => void) | null | undefined
async function collectGarbage(): Promise<void> {
if (collect === undefined) {
try {
const v8 = await import('v8')
const vm = await import('vm')
v8.setFlagsFromString('--expose-gc')
collect = vm.runInNewContext('gc') as () => void
v8.setFlagsFromString('--no-expose-gc')
} catch {
collect = null
}
}
collect?.()
}
// V8 hands pages back a batch at a time, and only on a LATER collection: on a
// cold start the collection that follows the release took the child from 2767MB
// to 1292MB, one a minute after that to 668MB — with no allocation in between,
// and with V8 returning none of it on its own across ten minutes of idle.
// Calling gc() twice in a row buys nothing; the wait between is what does. So
// keep passing while a pass is still worth the margin, bounded so this can
// never become a standing timer.
const RELEASE_SETTLE_MS = 60_000
const RELEASE_SETTLE_MIN_GAIN_BYTES = 64 * 1024 * 1024
const RELEASE_SETTLE_PASSES = 4
/// Drop every in-memory memo this process can re-read from disk, then hand the
/// pages back.
///
/// Ordering is load-bearing, and not the obvious one: the held shard-publish
/// window strongly references the whole cache (so clearing without publishing
/// it first frees nothing), and clearLoadCacheMemo() makes a later flush see a
/// cache that is no longer current and DISCARD the window. Flushing here, while
/// the memo still matches, publishes it instead. Dirty state therefore only
/// ever leaves memory through a publish; a durable provider never waits in that
/// window at all (parser.ts publishes its section on the poll that parsed it).
/// Safe to await: requests and the background fill share one promise chain, so
/// no parse can be mid-flight.
export async function releaseResidentMemos(): Promise<void> {
const { clearSessionCache, flushPendingShardPublish } = await import('./parser.js')
const { clearLoadCacheMemo } = await import('./session-cache.js')
const { clearCodexMemCaches } = await import('./codex-cache.js')
const { clearAntigravityCacheStates } = await import('./providers/antigravity.js')
const { clearScanFileMemo } = await import('./optimize.js')
await flushPendingShardPublish()
clearSessionCache()
clearLoadCacheMemo()
clearCodexMemCaches()
clearAntigravityCacheStates()
clearScanFileMemo()
await collectGarbage()
}
// How long a closing serve child waits for an already-accepted request before
// giving up and exiting. CODEBURN_SERVE_DRAIN_MS overrides it so the e2e can
// prove the bound without a 45-second test.
const DEFAULT_DRAIN_MS = 45_000
// How long the background fill waits after a cold first paint before taking the
// queue. Long enough for the client's opening burst (it is serial, so its next
// request is already on the wire) to land in front of the fill, short enough
// that a client which then goes quiet still converges promptly.
// CODEBURN_SERVE_FILL_DELAY_MS overrides it for tests.
const DEFAULT_FILL_DELAY_MS = 3_000
type OutputMemoEntry = {
createdAt: number
validatedFrom: number
output: string
configFingerprint: string
generation: ServeGeneration
}
/// Which derivation a response came from: a counter that advances once per
/// answer this process actually derived, and when that derivation happened. A
/// memoized answer carries the stamp of the derivation it came from, so a
/// client holding several panels can tell which of them share one reading of
/// the corpus and show a single clock for it.
///
/// Deliberately NOT the day range of the query. A menubar payload answers for
/// its period but also carries a year of daily history, live sessions and
/// per-period totals, so the request's own period would have described only a
/// part of what the answer covers - a `today` request stamping `today..today`
/// over a payload whose history reaches back months.
export type ServeGeneration = { n: number; at: string }
// Kept as a small seam so the ordering contract can be tested without relying
// on filesystem watcher scheduling: an event arriving while a parse is in
// flight must be newer than the memo produced by that parse.
export function createOutputMemoEntry(
parseStartedAt: number,
parseCompletedAt: number,
output: string,
configFingerprint: string,
generation: ServeGeneration = { n: 0, at: new Date(0).toISOString() },
): OutputMemoEntry {
return { createdAt: parseCompletedAt, validatedFrom: parseStartedAt, output, configFingerprint, generation }
}
/// Today's date in the local zone, `YYYY-MM-DD`.
export function localDateKey(now: Date = new Date()): string {
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
}
/// The key a served answer is memoized under. The argv alone is not enough:
/// `--period today` resolves to a different day after local midnight, and every
/// relative period shifts with it, so an answer built yesterday would be
/// replayed as today's for the rest of the memo's life. The resolved day range
/// rides along for the same reason, and because a period whose bounds moved is
/// a different question even on the same date.
///
/// The local date is also what makes the payload's clock-derived fields safe to
/// memoize: `periodTotals` (one entry per headline period, each window anchored
/// on the current day) and `streak` (days counted back from today) both change
/// only when the local date does.
export function outputMemoKey(args: string[], now: Date = new Date()): string {
const range = servedDayRange(args)
return [args.join('\u0000'), localDateKey(now), range?.from ?? '', range?.to ?? ''].join('\u0001')
}
/// The day range a served request answers for, as `YYYY-MM-DD` bounds. Only the
/// explicit forms are read: a command's own default period lives in main.ts, and
/// guessing it here would stamp a range the answer may not have used.
export function servedDayRange(args: string[]): { from: string; to: string } | null {
const asDay = (d: Date): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
try {
const day = parseDayFlag(readServeOption(args, '--day'))
if (day) return { from: day.day, to: day.day }
const period = readServeOption(args, '--period') ?? readServeOption(args, '-p')
const from = readServeOption(args, '--from')
const to = readServeOption(args, '--to')
if (period === undefined && from === undefined && to === undefined) return null
const info = periodInfoFromQuery({ period, from, to }, period ?? 'today')
return { from: asDay(info.range.start), to: asDay(info.range.end) }
} catch {
return null
}
}
type ServeOptionKind = 'flag' | 'value'
// This is intentionally a positive, command-specific option schema rather
// than a shared denylist. If a command later gains a write-capable option it
// remains a normal one-shot CLI action until it is explicitly reviewed here.
// The entries mirror the Commander definitions in main.ts. In particular,
// optimize omits its apply-only surface (--apply, --yes, --dry-run, --only),
// and report omits --refresh, which only paces the interactive dashboard.
const SERVE_OPTIONS: Readonly<Record<string, Readonly<Record<string, ServeOptionKind>>>> = {
report: {
'-p': 'value', '--period': 'value', '--day': 'value', '--from': 'value',
'--to': 'value', '--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
status: {
'--format': 'value', '--scope': 'value', '--provider': 'value', '--project': 'value',
'--exclude': 'value', '--period': 'value', '--day': 'value', '--from': 'value',
'--to': 'value', '--days': 'value', '--no-optimize': 'flag', '--no-timeline': 'flag',
'--claude-config-source': 'value',
},
overview: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--project': 'value', '--exclude': 'value', '--no-color': 'flag',
},
models: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--route': 'value', '--billing': 'value',
'--task': 'value', '--by-task': 'flag', '--by-agent': 'flag',
'--top': 'value', '--min-cost': 'value', '--no-totals': 'flag', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
sessions: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--route': 'value', '--billing': 'value',
'--format': 'value', '--by-pr': 'flag', '--no-pager': 'flag',
'--project': 'value', '--exclude': 'value',
'--contributions': 'flag',
},
compare: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value',
'--model-a': 'value', '--model-b': 'value',
'--project': 'value', '--exclude': 'value',
'--category': 'value', '--project-id': 'value',
},
yield: {
'-p': 'value', '--period': 'value', '--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
spend: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
optimize: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value', '--json': 'flag',
'--project': 'value', '--exclude': 'value',
},
audit: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--route': 'value', '--billing': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
}
type ServeRequest = { id: string | number; args: string[] }
function isServeRequest(value: unknown): value is ServeRequest {
if (!value || typeof value !== 'object') return false
const r = value as Record<string, unknown>
const idOk = typeof r['id'] === 'string' || typeof r['id'] === 'number'
return idOk && Array.isArray(r['args']) && (r['args'] as unknown[]).every(a => typeof a === 'string')
}
function allowed(args: string[]): boolean {
const first = args[0]
if (!first) return false
const options = SERVE_OPTIONS[first]
if (!options) return false
// Served commands have no positional arguments. Long options may use the
// standard --name=value form; otherwise every value must immediately
// follow an option declared as value-bearing in that command's schema.
for (let i = 1; i < args.length; i++) {
const token = args[i]!
const separator = token.startsWith('--') ? token.indexOf('=') : -1
const option = separator >= 0 ? token.slice(0, separator) : token
const inlineValue = separator >= 0
const kind = options[option]
if (!kind) return false
if (kind === 'flag') {
if (inlineValue) return false
continue
}
if (inlineValue) continue
const value = args[++i]
if (value === undefined || value.startsWith('-')) return false
}
// `report` is the interactive dashboard on every format but json, and a TUI
// cannot run in a resident child whose stdout is the wire. Its JSON form is
// the only servable one; the rest is refused and falls back to a one-shot.
if (first === 'report' && readServeOption(args, '--format') !== 'json') return false
return true
}
/// Read a served option's value. `allowed()` has already proven the argv shape
/// (no positionals, every value-bearing option followed by a value that does
/// not start with '-'), so a token equal to the option name is always the
/// option and never someone's value.
function readServeOption(args: string[], name: string): string | undefined {
for (let i = 1; i < args.length; i++) {
const token = args[i]!
if (token === name) return args[i + 1]
if (token.startsWith(`${name}=`)) return token.slice(name.length + 1)
}
return undefined
}
/// Opt-in by whichever client spawned this child. A partial answer is only
/// honest on a surface that renders the indicator, and each client holds its
/// OWN serve child: the desktop app sets this (app/electron/cli.ts) and shows
/// `indexing history · N/M files`; the Swift menubar, GNOME and Windows clients
/// do not, so their children keep the full cold parse until those UIs can label
/// a partial payload. Unset means "answer only with complete data".
export const SERVE_PROGRESSIVE_ENV = 'CODEBURN_SERVE_PROGRESSIVE'
/// The range start a cold first paint of this request may be floored to, or
/// null when the request must not be answered partially (#1110).
///
/// Only `status --format menubar-json` qualifies, because it is the ONLY served
/// output that carries the `hydration` marker. Every other served command
/// (`models`/`sessions`/`spend` --format json ...) is a one-shot shape whose
/// consumer has no in-band way to tell a partial answer from a final one, so it
/// keeps the full parse. Explicit `--day`/`--from`/`--to`/`--days` are excluded
/// for the same reason the TUI excludes them: the floor is derived from a named
/// period, and a custom range is a deliberate question that deserves a real
/// answer.
export function coldFirstPaintRangeStart(
args: string[],
rangeForPeriod: (period: string) => { range: { start: Date } },
): Date | null {
if (process.env[SERVE_PROGRESSIVE_ENV] !== '1') return null
if (args[0] !== 'status') return null
if (readServeOption(args, '--format') !== 'menubar-json') return null
for (const flag of ['--day', '--from', '--to', '--days']) {
if (readServeOption(args, flag) !== undefined) return null
}
// Mirrors the `status` --period default in main.ts.
const period = readServeOption(args, '--period') ?? 'today'
try {
return rangeForPeriod(period).range.start
} catch {
return null
}
}
/// The request id of a protocol line, without committing to handling it. The
/// client's watchdog is a NO-OUTPUT timer, so a request waiting behind the
/// background fill has to be heartbeated by id before its turn comes.
function peekRequestId(line: string): string | number | null {
try {
const id = (JSON.parse(line) as { id?: unknown } | null)?.id
return typeof id === 'string' || typeof id === 'number' ? id : null
} catch {
return null
}
}
class ExitSignal extends Error {
constructor(public readonly code: number) { super(`exit ${code}`) }
}
function chunkToString(chunk: unknown, encoding: unknown): string {
if (typeof chunk === 'string') return chunk
if (chunk instanceof Uint8Array) {
return Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding as BufferEncoding : 'utf8')
}
return String(chunk)
}
function finishWrite(rest: unknown[]): void {
const callback = rest[rest.length - 1]
if (typeof callback === 'function') (callback as () => void)()
}
/// Run one argv through a fresh program, capturing command stdout for the
/// final response and forwarding command stderr as progress. process.exit
/// inside a handler is converted to a thrown ExitSignal so a failing request
/// can never take the server down.
async function runCaptured(
buildProgram: () => Command,
args: string[],
onProgress: (progress: string) => void,
): Promise<{ output: string; code: number }> {
const chunks: string[] = []
const originalWrite = process.stdout.write.bind(process.stdout)
const originalErrorWrite = process.stderr.write.bind(process.stderr)
const originalExit = process.exit.bind(process)
process.stdout.write = ((chunk: unknown, ...rest: unknown[]) => {
chunks.push(chunkToString(chunk, rest[0]))
finishWrite(rest)
return true
}) as typeof process.stdout.write
process.stderr.write = ((chunk: unknown, ...rest: unknown[]) => {
const progress = chunkToString(chunk, rest[0])
if (progress) onProgress(progress)
finishWrite(rest)
return true
}) as typeof process.stderr.write
process.exit = ((code?: number) => { throw new ExitSignal(code ?? 0) }) as typeof process.exit
try {
const program = buildProgram()
program.exitOverride()
await program.parseAsync(['node', 'codeburn', ...args])
return { output: chunks.join(''), code: 0 }
} catch (err) {
if (err instanceof ExitSignal) return { output: chunks.join(''), code: err.code }
throw err
} finally {
process.stdout.write = originalWrite
process.stderr.write = originalErrorWrite
process.exit = originalExit
}
}
/// A cheap per-request fingerprint for the configuration that affects query
/// rendering and aggregation. Hashing the small config file tracks effective
/// content rather than filesystem churn: a byte-identical rewrite keeps the
/// memo hot, while any real change invalidates immediately. A missing config
/// is a stable state; every other read failure fails closed (no memo reuse).
async function getConfigFingerprint(): Promise<string | null> {
const path = getConfigFilePath()
try {
const content = await readFile(path)
const digest = createHash('sha256').update(content).digest('hex')
return `${path}\u0000sha256:${digest}`
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return `${path}\u0000missing`
return null
}
}
/// Watch every provider's probe roots (the same paths codeburn doctor reports
/// as "where discovery looks") so the parse-reuse validator can answer "did
/// any session data change since T?" without a stat sweep. macOS fs.watch
/// rides FSEvents and supports recursive directory watches. A probe failure or
/// a watch failure for an existing root disables event-driven reuse for this
/// generation; a root absent at setup is rechecked by the parser's hard cap.
type RootWatcherState = {
startedAt: number
/// The roots actually armed. A path outside them has no event source, so the
/// incremental sweep must not trust anything it remembered about it.
roots: string[]
lastEventAt: () => number
changedSince: (sinceTs: number) => string[] | null
healthy: () => boolean
close: () => void
}
// Past this many distinct changed paths the watcher stops naming them and every
// event becomes unscoped, so a burst of churn costs one verdict instead of an
// unbounded map and a stat storm.
const MAX_TRACKED_PATHS = 512
const MS_PER_DAY = 24 * 60 * 60 * 1000
// Changed paths are only useful while some memo could still be reused; past the
// parser's validated-reuse cap they are dead weight.
const WATCHER_PATH_RETENTION_MS = 5 * 60 * 1000
/// The days a changed file can possibly contribute turns to, as a timestamp
/// span. A session transcript is opened when its session starts and appended to
/// until it ends, so the days it can hold are the ones between its creation and
/// its last write. One day of slack below covers a file created just after local
/// midnight whose first turns are stamped on the previous day, and the same
/// conservative widening a provider with a coarse clock would need.
///
/// This is a stat-only rule: a file rewritten with BACKDATED content that its
/// birth time does not cover is outside it. The five-minute reuse cap in
/// parser.ts remains the backstop for that, exactly as it is for a missed
/// filesystem event.
export function fileDaySpan(
info: { birthtimeMs: number; mtimeMs: number },
startOfDay: (ms: number) => number = ms => {
const d = new Date(ms)
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
},
): { startMs: number; endMs: number } {
const first = Math.min(info.birthtimeMs, info.mtimeMs)
return { startMs: startOfDay(first) - MS_PER_DAY, endMs: startOfDay(info.mtimeMs) + MS_PER_DAY - 1 }
}
const daySpanMemo = new Map<string, { mtimeMs: number; span: { startMs: number; endMs: number } }>()
function statDaySpan(path: string): { startMs: number; endMs: number } | null {
let info: ReturnType<typeof statSync>
try {
info = statSync(path)
} catch {
// Deleted or unreadable: nothing proves which days it held.
return null
}
const hit = daySpanMemo.get(path)
if (hit && hit.mtimeMs === info.mtimeMs) return hit.span
const span = fileDaySpan(info)
if (daySpanMemo.size > MAX_TRACKED_PATHS) daySpanMemo.clear()
daySpanMemo.set(path, { mtimeMs: info.mtimeMs, span })
return span
}
export function classifyRootReuse(
sinceTs: number,
state: { startedAt: number; lastEventAt: number; healthy: boolean; changedSince?: (sinceTs: number) => string[] | null },
// The span the reusable result covers. Given, an event is only disqualifying
// when the changed file's own days reach into it: a finalized past range is
// not re-derived because an agent wrote a session file today.
range?: { startMs: number; endMs: number },
daySpanOf: (path: string) => { startMs: number; endMs: number } | null = statDaySpan,
): ParseReuseValidation {
// A known event is conclusive even if watcher coverage degraded afterward.
// Unknown means only that no dirty evidence exists and cleanliness cannot be
// established for the whole interval.
if (state.lastEventAt >= sinceTs) {
if (!range) return 'dirty'
const changed = state.changedSince?.(sinceTs)
if (!changed) return 'dirty'
for (const path of changed) {
const span = daySpanOf(path)
if (!span || (span.startMs <= range.endMs && span.endMs >= range.startMs)) return 'dirty'
}
}
if (!state.healthy || sinceTs < state.startedAt) return 'unknown'
return 'clean'
}
async function startRootWatchers(): Promise<RootWatcherState | null> {
let lastEventAt = 0
let healthy = true
let closed = false
const watchers: FSWatcher[] = []
const armedRoots: string[] = []
// Changed paths, newest write per path, for day-scoped invalidation. An event
// that arrives without a filename, or one past the tracking bound, leaves
// `unscopedAt` behind: from then on nothing older than it can be day-scoped.
const changed = new Map<string, number>()
let unscopedAt = 0
const note = (root: string, filename: string | Buffer | null): void => {
const name = typeof filename === 'string' ? filename : null
// SQLite rewrites the shared-memory index when a database is READ, so a
// provider DB under a watched root reported a change every time codeburn
// itself opened it - this process invalidating the memo it had just
// produced, on every request, forever. Real writes still land in the
// database or its WAL, both of which stay watched.
if (name?.endsWith('-shm')) return
lastEventAt = Date.now()
if (!name) { unscopedAt = lastEventAt; return }
const path = join(root, name)
if (!changed.has(path) && changed.size >= MAX_TRACKED_PATHS) { unscopedAt = lastEventAt; return }
changed.set(path, lastEventAt)
}
const changedSince = (sinceTs: number): string[] | null => {
if (unscopedAt >= sinceTs) return null
const paths: string[] = []
for (const [path, at] of changed) {
// Older than any reuse this validator can bless; drop it rather than
// letting the map grow for the life of the process.
if (at < Date.now() - WATCHER_PATH_RETENTION_MS) { changed.delete(path); continue }
if (at >= sinceTs) paths.push(path)
}
return paths
}
try {
const { getAllProviders } = await import('./providers/index.js')
const providers = await getAllProviders()
const roots = new Set<string>()
for (const provider of providers) {
if (!provider.probeRoots) continue
try {
for (const root of await provider.probeRoots()) roots.add(root.path)
} catch {
// An unknown probe result could hide an existing input root, so no
// global all-roots-quiet claim is safe for this watcher generation.
healthy = false
}
}
for (const root of roots) {
// A root we refuse to open contributes no sessions, so nothing about it
// can go stale; watching it would hang this loop the way opening it does.
if (isPathBlocked(root)) continue
let info: Awaited<ReturnType<typeof stat>>
try {
info = await stat(root)
} catch (err) {
// An absent discovery root contains no sessions at arm time. If it is
// created later there is no child watcher to see that creation, so the
// parser's hard reuse cap remains the eventual revalidation backstop.
// Other stat failures mean an existing input could be uncovered.
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') healthy = false
continue
}
try {
const watcher = watch(root, { recursive: info.isDirectory() }, (_event, filename) => { note(root, filename) })
watcher.on('error', () => { healthy = false })
watchers.push(watcher)
armedRoots.push(root)
} catch {
// stat proved this input exists, so failing to arm it invalidates the
// global quiet predicate even when other roots remain watched.
healthy = false
}
}
} catch {
// Discovery itself failed. Existing watchers are still closed normally,
// but they cannot validate reuse for an incomplete root set.
healthy = false
}
if (watchers.length === 0) return null
// Coverage begins only after at least one watcher has been successfully
// armed. A parse performed while provider probing/stat/watch setup was in
// flight must not be blessed retroactively as watched.
const startedAt = Date.now()
return {
startedAt,
roots: armedRoots,
lastEventAt: () => lastEventAt,
changedSince,
healthy: () => healthy && !closed,
close: () => {
if (closed) return
closed = true
for (const w of watchers) w.close()
},
}
}
export async function runStdioServe(buildProgram: () => Command): Promise<void> {
// Every stderr write becomes a progress frame below, so the project-filter
// warning has to stay quiet for the life of this process.
suppressProjectFilterWarnings()
// Panel bursts (the app fetching every panel for one period) reuse a parse
// whose through-now range end differs by less than this window, instead of
// re-running the discovery sweep per panel. Serve-only: one-shot CLI runs
// never set this, so their results stay byte-exact.
if (!process.env['CODEBURN_PARSE_BURST_MS']) process.env['CODEBURN_PARSE_BURST_MS'] = '10000'
// This process is the one producer allowed to answer partially, because its
// clients poll and therefore converge. The marker makes every menubar payload
// it emits carry `hydration` — including the warm ones, which report
// `complete: true` — so a consumer never has to infer completeness from a
// missing field within a single source.
process.env[SERVE_HYDRATION_ENV] = '1'
// Shard publication is coalesced for this process only: one-shot CLI runs
// keep writing the cache immediately. The flush below is the shutdown half
// of that contract.
const { setShardPublishCoalescing } = await import('./parser.js')
setShardPublishCoalescing(true)
// Event-driven reuse: while no watched session root has changed, a previous
// parse stays valid past the burst window (capped in parser.ts, so a missed
// filesystem event self-heals within minutes). This is what turns a warm
// no-change fetch into a no-op instead of a stat sweep.
let rootReuseValidation: ((sinceTs: number) => ParseReuseValidation) | null = null
// Mutable object properties keep cleanup visible to TypeScript even though
// setup assigns them from an asynchronous continuation.
const watcherLifecycle: {
state: RootWatcherState | null
resetValidator: (() => void) | null
} = { state: null, resetValidator: null }
const watcherSetup = startRootWatchers().then(async (w) => {
watcherLifecycle.state = w
if (!w) return
const { setParseReuseValidator, setSweepWatchSource } = await import('./parser.js')
// Clean means: the watchers were already armed when the parse happened,
// and no filesystem event has landed since. lastEventAt of 0 is a quiet
// system (clean for anything parsed after arming), not an unknown.
const validate = (sinceTs: number, range?: { startMs: number; endMs: number }): ParseReuseValidation => classifyRootReuse(sinceTs, {
startedAt: w.startedAt,
lastEventAt: w.lastEventAt(),
healthy: w.healthy(),
changedSince: w.changedSince,
}, range)
rootReuseValidation = validate
setParseReuseValidator(validate)
// Same watcher, finer grain: the discovery sweep reuses the listing and
// fingerprint of every path no event has named, instead of re-reading the
// whole corpus on each poll.
setSweepWatchSource({ startedAt: w.startedAt, roots: w.roots, healthy: w.healthy, changedSince: w.changedSince })
watcherLifecycle.resetValidator = () => { setParseReuseValidator(null); setSweepWatchSource(null) }
}).catch(() => {
watcherLifecycle.state?.close()
watcherLifecycle.state = null
})
// Output-level memo: an identical panel query while the roots are quiet
// returns the previous stdout verbatim - the aggregation work is skipped
// too, not just the parse. Session data uses the same event-or-cap rule as
// parse reuse; config.json is fingerprinted on every request because it can
// change rendering without touching a provider root.
const OUTPUT_MEMO_CAP_MS = 5 * 60 * 1000
const outputMemo = new Map<string, OutputMemoEntry>()
// Advances once per answer this process derives; a memo hit re-serves the
// stamp its output was derived under.
let generationCounter = 0
let observedConfigFingerprint: string | null | undefined
if (process.stdin.isTTY) {
process.stderr.write('codeburn serve speaks JSON over stdio and exists for the desktop app to hold warm.\nNothing interactive happens here; press Ctrl+C to exit.\n')
}
// Keep the protocol transport anchored to the real stdout. runCaptured()
// temporarily replaces process.stdout.write to collect command output; a
// dynamic lookup here would swallow progress frames into the final payload.
const protocolWrite = process.stdout.write.bind(process.stdout)
const write = (value: unknown): void => { protocolWrite(JSON.stringify(value) + '\n') }
write({ ready: true, pid: process.pid })
// What this resident child costs, riding along on the answers it already
// sends. The desktop app cannot measure it: serve is a plain CLI child, so it
// is absent from Electron's app.getAppMetrics(). The parent turns these into
// bucket labels for its consent-gated app_close event; the numbers themselves
// go no further than the pipe.
let peakRss = 0
const serveUsage = (): { cpuSec: number; rssMb: number } => {
const rss = process.memoryUsage().rss
if (rss > peakRss) peakRss = rss
const cpu = process.cpuUsage()
return { cpuSec: (cpu.user + cpu.system) / 1e6, rssMb: Math.round(peakRss / (1024 * 1024)) }
}
// Strict serialization: each request chains on the previous one.
let queue: Promise<void> = Promise.resolve()
// Progressive cold start (#1110). Ids of requests received but not yet
// answered, so work that holds the queue can heartbeat them.
const awaiting = new Set<string | number>()
const beat = (progress: string): void => {
for (const id of awaiting) write({ id, progress })
}
// Cold detection runs at most once per paintable request until it answers
// "warm"; from then on this child is warm for good and every request takes
// the ordinary full path.
let firstPaintSettled = false
let fillTimer: ReturnType<typeof setTimeout> | undefined
/// Pass over the heap again a minute from now, and keep passing while each
/// one is still handing pages back. Queued, so a collection cannot land
/// inside a request; unref'd, so it cannot hold this child open past its app.
const scheduleSettlingCollection = (pass = 0): void => {
if (pass >= RELEASE_SETTLE_PASSES) return
const timer = setTimeout(() => {
queue = queue.then(async () => {
const before = process.memoryUsage().rss
await collectGarbage()
if (before - process.memoryUsage().rss >= RELEASE_SETTLE_MIN_GAIN_BYTES) scheduleSettlingCollection(pass + 1)
})
}, RELEASE_SETTLE_MS)
timer.unref?.()
}
// The other half of the first paint: the same request, unfloored. It is an
// ordinary parse, so what it writes to the session and daily caches is
// exactly what a full cold parse would have written — the paint only
// sequenced those files behind the answer, it never dropped them. Killed
// mid-fill, nothing is stamped complete and the next launch re-enters cold.
const scheduleBackgroundFill = (args: string[]): void => {
if (fillTimer) return
const delayMs = Number(process.env['CODEBURN_SERVE_FILL_DELAY_MS']) || DEFAULT_FILL_DELAY_MS
fillTimer = setTimeout(() => {
queue = queue.then(async () => {
const { isColdCacheOnDisk } = await import('./session-cache.js')
// A request that landed in front of the fill may already have done the
// full parse (only the menubar payload is ever floored) — then there is
// nothing left to fill, but the cold start is over just the same, so the
// release below still runs.
if (await isColdCacheOnDisk()) {
const { startProgressKeepalive, stopProgressKeepalive } = await import('./parser.js')
startProgressKeepalive()
const startedAt = Date.now()
try {
const { output, code } = await runCaptured(buildProgram, args, beat)
const fingerprint = await getConfigFingerprint()
// Memoized so the poll that follows the fill answers instantly with
// the converged payload instead of re-deriving it.
if (code === 0 && fingerprint !== null) {
outputMemo.set(outputMemoKey(args), createOutputMemoEntry(startedAt, Date.now(), output, fingerprint, { n: ++generationCounter, at: new Date().toISOString() }))
}
} catch {
// Best effort. A failed fill leaves the cache incomplete, which is
// exactly the state the next cold start knows how to resume from.
} finally {
stopProgressKeepalive()
}
}
// The cold start's whole product is on disk: the daily cache holds the
// per-day summaries and the session cache holds the per-call detail,
// and the answers already derived are in the output memo above. What
// stays in memory otherwise is the detail those summaries were derived
// FROM — an unscoped SessionCache the load memo then serves to every
// later request, whatever range it asked for, plus the lifetime
// ProjectSummary trees the parse memo keeps with no sweep to retire
// them once requests stop. A poll needs neither: it re-reads the month
// shards its own range covers. Measured on a cold start over a 170MB
// shard set, holding them was 2198MB resident at idle against 364MB of
// live heap — and the pages only go back with the collection the
// release ends in.
await releaseResidentMemos()
scheduleSettlingCollection()
})
}, delayMs)
// The app owning this child is gone once stdin closes; an unstarted fill
// must not keep the process alive past that.
fillTimer.unref?.()
}
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity })
rl.on('line', (line) => {
const trimmed = line.trim()
if (!trimmed) return
const waitingId = peekRequestId(trimmed)
if (waitingId !== null) awaiting.add(waitingId)
queue = queue.then(async () => {
let request: unknown
try {
request = JSON.parse(trimmed)
} catch {
write({ id: null, ok: false, error: 'malformed request line' })
return
}
if (!isServeRequest(request)) {
write({ id: (request as { id?: unknown })?.id ?? null, ok: false, error: 'malformed request' })
return
}
if (!allowed(request.args)) {
// Routing signal, not a failure: the client falls back to a spawn.
write({ id: request.id, ok: false, refused: true, error: 'command not served' })
return
}
const configFingerprint = await getConfigFingerprint()
if (observedConfigFingerprint !== undefined && configFingerprint !== observedConfigFingerprint) {
outputMemo.clear()
}
observedConfigFingerprint = configFingerprint
// A permission or transient read failure must shorten reuse, never make
// an old result look current.
if (configFingerprint === null) outputMemo.clear()
const memoKey = outputMemoKey(request.args)
const memoHit = outputMemo.get(memoKey)
if (
configFingerprint !== null
&& memoHit?.configFingerprint === configFingerprint
&& Date.now() - memoHit.createdAt < OUTPUT_MEMO_CAP_MS
&& rootReuseValidation?.(memoHit.validatedFrom) === 'clean'
) {
write({ id: request.id, ok: true, output: memoHit.output, generation: memoHit.generation, usage: serveUsage() })
return
}
// Progressive cold start (#1110): on a cold cache the menubar payload is
// answered from the files the requested period can actually show, and the
// rest are indexed behind it. Same cold test as the TUI (session-cache
// envelope missing or complete !== true), same floor, and the answer says
// so in-band via `hydration.complete: false`.
const paintFrom = firstPaintSettled ? null : coldFirstPaintRangeStart(request.args, getDateRange)
let floor: Date | null = null
if (paintFrom) {
const { isColdCacheOnDisk } = await import('./session-cache.js')
floor = await isColdCacheOnDisk() ? paintFrom : null
firstPaintSettled = true
// A warm start has no fill behind it to release after, but it has the
// same opening burst, and V8 sits on those pages just the same: 900MB
// resident against 356MB of live heap, with nothing further returned
// across ten minutes of idle. Nothing is dropped here — only collected.
if (!floor) scheduleSettlingCollection()
}
// Heartbeat the WHOLE request, not just its parse: the aggregation and
// payload serialization after a parse measured ~8s of further silence, and
// it lands back-to-back with the parse's own quiet stretches. Wrapping
// here (rather than at each command's exits) covers every served command
// at one seam, and runCaptured routes the beats out as progress frames.
const { startProgressKeepalive, stopProgressKeepalive, withColdFirstPaintFloor } = await import('./parser.js')
startProgressKeepalive()
try {
const parseStartedAt = Date.now()
const run = () => runCaptured(
buildProgram,
request.args,
progress => write({ id: request.id, progress }),
)
let deferredFiles = 0
let result: Awaited<ReturnType<typeof run>>
if (floor) {
const painted = await withColdFirstPaintFloor(floor, run)
deferredFiles = painted.deferredFiles
result = painted.result
} else {
result = await run()
}
const { output, code } = result
const generation: ServeGeneration = { n: ++generationCounter, at: new Date().toISOString() }
if (code === 0) {
// A partial answer is never memoized. The roots stay quiet while the
// fill converges, so a memo hit would pin the client to the first
// paint for the whole memo cap.
//
// Same invariant, stated generally: nothing DELIBERATELY DEFERRED
// may enter this memo. A deferred answer is stale by construction
// and the event that would retire it has already landed, so the
// reuse check below it stays 'clean' and replays the stale payload
// until the cap. The one deferral a served command had was the
// status snapshot's settle window; main.ts now bypasses the whole
// snapshot path in this process (SERVE_HYDRATION_ENV), so the only
// remaining deferral is the cold first paint, counted right here.
// Any future debounce must either be bypassed in serve too or
// surface a count like `deferredFiles` for this gate.
if (configFingerprint !== null && deferredFiles === 0) {
outputMemo.set(memoKey, createOutputMemoEntry(parseStartedAt, Date.now(), output, configFingerprint, generation))
}
if (outputMemo.size > 32) {
const oldest = [...outputMemo.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt)[0]
if (oldest) outputMemo.delete(oldest[0])
}
write({ id: request.id, ok: true, output, generation, usage: serveUsage() })
if (deferredFiles > 0) scheduleBackgroundFill(request.args)
}
else write({ id: request.id, ok: false, error: `exit ${code}`, output })
} catch (err) {
write({ id: request.id, ok: false, error: err instanceof Error ? err.message : String(err) })
} finally {
stopProgressKeepalive()
}
// Memory guard: a resident process accumulates parse memos that a
// one-shot CLI never lives long enough to hold (up to 10 entries of
// full ProjectSummary trees plus the parsed cache object). Past the
// threshold, drop the in-memory memos — the next request re-parses
// once (seconds), which beats an ever-growing child. The child itself
// never exits here, so the client's death counter is untouched.
const rss = process.memoryUsage().rss
if (rss > peakRss) peakRss = rss
if (rss > SERVE_MAX_RSS_BYTES) {
// Hysteresis: only clear when RSS has grown past the last clear by a
// margin, so a warm cache sitting above the ceiling is not dropped on
// every request.
if (rss > lastClearRss + SERVE_RSS_CLEAR_MARGIN_BYTES) {
await releaseResidentMemos()
lastClearRss = rss
}
} else {
lastClearRss = 0
}
}).finally(() => {
if (waitingId !== null) awaiting.delete(waitingId)
})
})
// The app owns this process: stdin closing (or failing) means the app is
// gone. Always release FSEvents handles and the module-global validator;
// otherwise an existing Claude root keeps a naturally closed child alive.
const transportClosed = new Promise<void>((resolve) => {
rl.once('close', resolve)
process.stdin.once('end', resolve)
process.stdin.once('error', resolve)
})
try {
await transportClosed
} finally {
rl.close()
// Drain the in-flight request BEFORE returning. The caller exits the process
// once this resolves, and runCaptured() has process.exit monkeypatched into
// a thrown ExitSignal - returning mid-request would lose that request's
// response frame and turn a clean exit into a failure.
//
// Bounded, because the app is already gone and this child must not become
// the orphan the drain was added to prevent. The bound is generous: no
// legitimate request answered at EOF comes close to it, and an ASYNC-wedged
// one is released cleanly here. Note the ceiling: a parse wedged in a
// SYNCHRONOUS loop never yields to this timer, or to any other JS path -
// only a signal can end that process.
const drainMs = Number(process.env['CODEBURN_SERVE_DRAIN_MS']) || DEFAULT_DRAIN_MS
let drainTimer: ReturnType<typeof setTimeout> | undefined
await Promise.race([queue, new Promise<void>(resolve => { drainTimer = setTimeout(resolve, drainMs) })])
clearTimeout(drainTimer)
// Publish whatever the coalescing window still holds. Bounded for the same
// reason the drain is, and non-fatal: an unpublished window costs the next
// start a re-parse of those appends, never a wrong number.
let flushTimer: ReturnType<typeof setTimeout> | undefined
const { flushPendingShardPublish } = await import('./parser.js')
await Promise.race([
flushPendingShardPublish().catch(() => undefined),
new Promise<void>(resolve => { flushTimer = setTimeout(resolve, drainMs) }),
])
clearTimeout(flushTimer)
// Bounded and non-fatal for the same reason the drain is: the app is gone,
// and cleanup that hangs (watcher discovery on a stalled mount) or throws
// must not stop this child from reaching its exit.
let watcherTimer: ReturnType<typeof setTimeout> | undefined
await Promise.race([
watcherSetup.catch(() => undefined),
new Promise<void>(resolve => { watcherTimer = setTimeout(resolve, drainMs) }),
])
clearTimeout(watcherTimer)
rootReuseValidation = null
try {
watcherLifecycle.resetValidator?.()
} finally {
watcherLifecycle.state?.close()
}
}
}