diff --git a/CHANGELOG.md b/CHANGELOG.md index 69c149fd..69d36c94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ - **DeepSeek Harness (`dsh`) is now a supported provider.** Reads DeepSeek's open-source agent harness from `~/.dsh/sessions` (`DSH_HOME` relocates the root), both the default zstd logs and the uncompressed `session.jsonl` variant. A `.zstd` log is a concatenation of independent zstd frames, one per write batch, so it is decoded frame by frame behind a structural frame scan and a torn trailing frame from a crashed writer is ignored rather than failing the file (needs Node 22.15+ for `zlib` zstd; below that dsh is skipped with a notice instead of counted as $0). One call per `(turn, step)`, with the step's final `assistant/message` usage superseding the streamed `assistant/chunk` sample of the same call rather than adding to it, the model taken from the message that served the step, and reasoning tokens billed at the output rate. DSH records tokens but no cost, so calls are priced from the shared tables. The events a forked session replays from its parent are skipped, since codeburn already counts the parent's own log. The session format is pinned at version 0 upstream with no compatibility implied, so a log stamped with any other version is skipped with a notice instead of read under today's assumptions. ### Changed +- **Report, sessions, overview, compare, export, report JSON and menubar `localModelSavings` now use `billableOutputTokens` for displayed output.** Cost already did. Exclusive providers (Grok and the rest) were under-reporting output by exactly their reasoning tokens; optimize added reasoning on top of output for the inclusive set `{claude, codex, copilot}` and double-counted it. Displayed aggregates now bill per call while the provider is known, joined onto an existing `modelBreakdown` key (parser short name first, then the raw id) so a leftover raw-id bucket cannot mint a $0 `Opus 4.8` Unpriced orphan. Daily cache v28 re-derives finalized days so `report` matches the live parse. Thanks @saulcanina. (#1115) - **The desktop app's cold start paints as soon as the selected period is readable, instead of after the whole history.** The resident `codeburn serve` child now does for its JSON clients what the TUI got in #1107: on a cold cache it answers the first `status --format menubar-json` from the files whose mtime allows them to hold data the requested period can show (the same floor and 48h clock-skew margin), then indexes the rest behind the answer. The payload says so in-band through a new optional `hydration: { complete, indexedFiles, totalFiles }` block, and the desktop app and web dashboard render `indexing history · N/M files · totals below cover what is indexed so far` until it reports `complete: true`. On a 21k-file corpus the app's first payload lands in 7.3s instead of 31.3s, fully indexed at 36.2s. Only the resident serve process ever emits `hydration`, and only it may answer partially — its clients poll, so they converge. Every one-shot output is unchanged and always a full parse: `--format json`/`csv`/`markdown`, `report`, `sessions`, `models`, MCP, the Swift menubar and GNOME clients, and the desktop app's own spawn fallback, none of which have a second poll to converge with. Absence of `hydration` therefore always means complete, which is also what an older CLI's payload means. It is not `stale` (#1100) and never sets it: a first paint is fresh but partial, where a stale payload is complete but old. Nothing is stamped complete until the fill has actually parsed everything, so a process killed mid-fill comes back cold and finishes the job. (#1110) - **The discovery sweep issues its metadata syscalls concurrently.** Every dated command re-walks and re-stats every provider tree before it can decide what is already cached, and that sweep was strictly serial: one `readdir`, one `stat`, one `state.json` read at a time, per provider, one provider after another. On a 21k-file / 9-provider corpus it owned most of a warm run's wall clock while the machine sat idle waiting on the kernel. Provider discovery now runs across providers at once, and the four walks that dominate it (claude, codex, kimicode, grok) plus the Claude project-dir walk and both fingerprint passes fan out through a shared bounded-concurrency helper. Order is unchanged everywhere — each level is re-concatenated in registry/`readdir` order before anything reconciles against the cache — so what is discovered, in what sequence, is byte-identical to the serial walk. Two smaller cuts ride along: the Claude walk reads directory entries with their types so a plain file no longer costs a wasted `subagents/` probe, and the Codex result cache (a single file that can reach hundreds of MB) now shares one in-flight load between concurrent readers instead of letting each one re-read and re-parse it. Warm `codeburn today` on that corpus: 5.30s to 2.99s; a cold parse 34.7s to 31.1s. (#1104) - **A kill mid-way through a non-Claude provider phase no longer restarts that whole phase.** `scanProjectDirs` (Claude) has long taken a throttled `saveProgress` callback so a killed cold parse resumes from a warm cache; `parseProviderSources` (every other provider — codex, cursor, gemini, and the rest) did not, and only persisted at the whole-provider boundary. On a large single-provider corpus (a multi-GB codex history is the common case) an app-timeout SIGKILL, crash, or force-quit during that phase discarded everything parsed since the last provider finished, forcing the entire phase to re-parse from zero on the next run. `parseProviderSources` now takes the same callback, invoked once per source right after that source's cache entry lands (mirroring `scanProjectDirs`' placement, outside the per-file try/catch), on the same file-count/wall-clock throttle. A file only ever gets a fingerprint once it has fully parsed, so a mid-file kill can never leave a half-parsed file's entry looking complete on resume. @@ -37,12 +38,16 @@ - **The snap asks for the log directories it reads, not each tool's whole home.** The first Snap Store submission declared a `personal-files` read of every AI tool's root — `$HOME/.claude`, `$HOME/.codex`, `$HOME/.cursor` and the rest — and that interface is recursive, so it granted read of every credential file those roots hold. Each entry now names the subdirectory the provider actually opens (`.claude/projects`, `.codex/sessions`, `.cline/data`, `.vibe/logs/session`, `.dsh/sessions`, `.kiro/sessions`, `.quickwork/{profiles.json,sessions,metrics}`, `.config/Claude/local-agent-mode-sessions`, `.config/Open Design/{runs,data/runs,namespaces}`), two are single files (`.forge/.forge.db`, `.zcode/cli/db/db.sqlite`), and the editor entries name only the extension folders holding transcripts instead of the editor's whole configuration. Five providers that were missing entirely and would have shown no data are declared — opencode, crush, goose, kilo, kimi-code — and four roots stay roots only because the file the provider opens sits directly in them (`.config/github-copilot`, `.local/share/{opencode,crush,kilo}`). One credential file is now requested openly rather than implicitly: `.claude/.credentials.json`, read-only, for the live plan gauge. Codex's equivalent would need write access to the Codex CLI's own `auth.json` to rotate the token, so neither it nor a Codex root is declared and the Codex live gauge is disabled under `$SNAP`; Codex usage and cost are unaffected, they come from the session rollouts. Two consequences inside the snap: `.lingtai` is dropped, because its per-agent log directory needs a wildcard the interface has no form for, and `optimize`, `context-budget` and `act` no longer see the user-scope `~/.claude/settings.json`, `agents/`, `skills/` and `commands/` — project-scope copies still work through the `home` plug. Nothing outside the snap changes. ### Fixed (Desktop & Menubar) +- **The menubar stops killing its own cold cache rebuild.** On a large corpus after the 0.9.20 cache-version bump, the menubar never completed a single fetch: every child was killed at exactly 45 seconds, and each kill left the `session-refresh.lock` behind for the next one to wait out. Four things were wrong and all four are fixed. The 45-second cap was a TOTAL-runtime kill, so it is now the same no-output watchdog the desktop app got in #1096 — spawns and the resident `codeburn serve` alike set `CODEBURN_PROGRESS=1`, the window restarts on every byte of stdout or stderr (the CLI heartbeats every 10 seconds while parsing, and now also while WAITING on the refresh lock, which was the silent stretch that mattered), and only a genuinely mute child is killed, with the same 10-minute cold floor until the first payload lands and the same 15-minute absolute ceiling behind it. Kills are SIGTERM first and SIGKILL only after a 5-second grace, and the refresh lock now arms the same signal cleanup the hydration lock has, so a killed holder unlinks its own lock instead of leaving one. A lock that was abandoned anyway is recovered immediately rather than after 90 seconds: a waiter takes over a lock whose recorded holder pid is gone, or whose heartbeat has frozen, and the waiter's own budget is now derived from the stale window so it can never again expire before the gate it is waiting for opens — a live holder, whose heartbeat keeps the mtime fresh and whose pid answers, is never taken from. The resident child's fixed 60-second warm request cap becomes a silence window that each progress frame restarts, and a spent restart budget is a five-minute cooldown rather than leaving the resident dead for the rest of the app run. Serve orphans get three new backstops: the app closes its end of a retired child's stdin (dropping the handle was not enough — the pipe stayed alive inside the Process), reaps every child it started synchronously at quit before the async shutdown can be skipped, and records the child's pid and command line so a serve orphaned by a crash is reaped on the next launch. On the CLI side a serve child's final exit no longer runs through the `process.exit` an in-flight request has monkeypatched, and its post-drain cleanup is bounded like the drain. (#1117) - **A long panel query is no longer killed for being slow.** The desktop app capped every read at 45 seconds of TOTAL runtime, so on a slow machine `optimize`, `yield`, `models`, `sessions`, `spend`, `audit`, `act report` and `plan` were SIGKILLed mid-parse and the panel painted a red "timed out" that a 60-second poll then reproduced forever. That cap is now a no-output watchdog: the window restarts on every byte the child writes, so only a genuinely silent child times out, with a 15-minute absolute ceiling still catching a livelocked one. Silence now means stopped rather than slow, because the parse itself heartbeats: every read spawn sets `CODEBURN_PROGRESS=1`, and under it a running parse emits a keepalive line every 10 seconds — the stretch that mattered was a cold parse's inter-provider cache save, measured at 31.6 seconds of total silence on a large corpus, which the old scan-progress stream did not cover at all. A served request heartbeats for its whole duration, parse and the aggregation and serialization after it alike; a one-shot spawn heartbeats through the parse, and the roughly 8-second tail that follows it stays well inside the window on its own. Resident `codeburn serve` requests reset their window on each frame of their own response. Alongside it: the cold-cache floor now covers EVERY read while the first hydration is still running, not just the overview, so a section that starts polling the moment the app is ready is not killed waiting behind that parse; a read that times out while the hydration is still going keeps the indexing splash instead of painting an error panel, bounded so that an install which can never hydrate still surfaces a real error once the cold window has elapsed rather than sitting behind the splash forever; and a read killed for timing out, or a resident child replaced by a settings mutation, is sent SIGTERM first and SIGKILL only after a 5-second grace, so the child can unlink its own cache refresh lock rather than leave it for the next parse's stale-pid takeover (quit stays a hard kill, its flush budget being shorter than the grace). A hydration that genuinely needs more than 15 minutes is still ended by the absolute ceiling, but it no longer starts from nothing next time: the partial cache saved along the way means successive polls converge instead of each repeating the whole scan. The app also records the resident child's pid and full command line, and reaps a serve orphaned by a previous crash on the next launch — on Windows too, where there is no `ps` and no stdin-close recourse after a crash — signalling only when that pid still runs that exact command. Separately, `codeburn serve` drains an in-flight request before exiting on stdin close, bounded at 45 seconds so a wedged request cannot turn the child into the orphan the drain prevents. - **The menubar's copies of your Claude and Codex credentials move out of Application Support and into the login Keychain.** Connecting a provider used to leave the copied OAuth material in `~/Library/Application Support/CodeBurn/*-credentials.v1.json`, written world-readable (0644) because macOS ignores `.completeFileProtection` outside iOS. The copy now lives in a CodeBurn-owned login-Keychain item, and the first read after upgrading migrates the old file: it is reopened with `O_NOFOLLOW`, refused if it is a symlink or not owned by you, repaired to 0600 before a single secret byte is read, written to the Keychain, read back and compared, and only then unlinked — a failed or unverified write leaves the (now 0600) file in place so a retry can still find it, and the next read retries the cleanup. Where both a Keychain item and an old file exist, the one that expires later wins before anything is removed, so an item left behind by a much older build cannot displace a fresher token. Claude's entry no longer stores a refresh token at all — the CLI owns that grant and the menubar never spends it — and any refresh token in a historical blob is dropped on read. Disconnect only reports success once the material is actually gone; if the delete fails it says so and leaves the provider connected so you can retry. Keychain reads are non-interactive and are skipped outright while the login Keychain is locked, so a background quota refresh can never raise an unlock panel. (#1037) - **First launch no longer asks to control System Events.** The macOS menubar registered its login item by driving System Events over AppleScript, which made macOS put up an Automation consent dialog the first time the app ran. It now registers itself through `SMAppService.mainApp`, an in-process call that needs no Automation grant; there is no AppleScript fallback, so a failure logs and leaves the login item unset rather than bringing the prompt back. The same `codeburn.loginItemRegistered` guard still limits this to the first launch, so a login item you removed by hand stays removed. (#1026) - **The resident `codeburn serve` child.** The first real panel request is also the cache warm-up, so startup never runs an artificial warm-up query beside a duplicate one-shot child; each served command carries its own read-only option allowlist, and anything outside it falls back to a normal spawn; the child exits when its stdin closes, so it can never outlive the app. Requests whose response exceeds the 16 MiB frame limit still replace the child, but that deliberate kill no longer spends the resident's unexpected-death budget. (#972) ### Fixed +- **Hermes sessions that keep running after a day is sealed no longer lose later token and cost growth.** A sidecar ledger under the CodeBurn cache records last-seen lifetime totals per `(profile, sessionId)` and emits observation-time deltas (weight 0) so a sealed day stays put while today's growth still lands. An all-zero reset is visible to the cursor after discovery filtering, so a later 40 is `+40` rather than a silent shrink. Explicit `$0` is treated as recorded. Ledger publication failures are retryable and hold the daily watermark. (#916) +- **`codeburn doctor` now probes the five remaining fixed-location providers.** `codebuff`, `devin`, `gemini`, `kiro`, and `mistral-vibe` implement `probeRoots()` through the same resolvers discovery uses, so a silent zero is distinguishable from a missing install. Codebuff reports all three manicode channels unless a factory or `CODEBUFF_DATA_DIR` pins one; Devin reports `transcripts` plus `sessions.db`, not the parent; Gemini reports only `~/.gemini/tmp`; Kiro reports pre-filter candidates (empty CLI/v2 skipped, empty agent/workspace fall back); Mistral Vibe reports the joined sessions dir. Missing defaults still appear. Thanks @therickfactr. (#899) + - **Subscription SKUs are classified from real product ids, and a false-positive built-in can be opted out.** `codex-auto-review` consumes ordinary Codex usage ([openai/codex#32224](https://github.com/openai/codex/issues/32224)) and is priced as GPT-5.5 on #1056, so treating it as $0 hid real spend — it left the flat-rate list. Warp's product id is `auto`, not the synthetic `warp`. `kimi-for-coding-highspeed` (the SKU #968 was filed around) is now honestly $0. `big-pickle` was dropped: it appears under OpenCode, not as a cited ClinePass codename. `codeburn model-flat-rate --remove` now opts out of a built-in, so a wrong classifier entry can warn again without waiting for a release. The daily-cache config hash now always includes the flat-rate section (even when empty), so the first run after upgrade re-derives every stored day once from the warm session cache. (#968, #1050) - **Codex MCP and skill usage is attributed from every shape Codex records a shell command in.** `mcp-cli call ` was only recognized when the command arrived as `function_call` arguments (#656). Codex has two other shapes for the same exec: its custom-tool transport records the shell tool as a `custom_tool_call` whose payload is an `input` program rather than `arguments`, and its item model repeats a finished command as `event_msg`/`item_completed` carrying a `CommandExecution` item with an argv `command`. Both reached the Bash counter and neither reached the matcher, so a CLI-wrapped MCP call stayed absent from the MCP breakdown exactly as before the fix. All three shapes now feed one classification pipeline. The same pipeline learns skills: Codex has no skill tool, so loading one is a shell read of the skill's `SKILL.md`, and those reads landed entirely under Bash with the Skills dimension empty. A read counts as a skill load only when the command segment starts with a file-reading binary (`cat`/`bat`/`sed`/`head`/`tail`/`less`/`more`) and the path it reads ends in `/SKILL.md`; the skill is ``, the same key `pi` derives for a native skill read (#588) and the same vocabulary the Claude parser records from the `Skill` tool. A `grep`/`rg`/`ls` that merely mentions a `SKILL.md` is a search near the file, not a skill load, and stays plain Bash. This is attribution only — no call, token or cost figure moves, and a command carried by both a response item and an item-model item is attributed once. On a 1,397-rollout corpus: Skills went from empty to 7 skills over 35 turns (55 attributions), Bash was unchanged at 42,170, and cost, calls, tokens, sessions, daily, models and projects came back identical. Cached Codex sessions re-parse once (`CODEX_CACHE_VERSION` 13 → 14 and the codex parse version both move; without them the fix is invisible on a warm cache). Thanks @chr-evensen. (#478) - **`gpt-5.6-codex` and `gpt-5.6-codex-max` now have their own pricing rows.** Neither id is in LiteLLM yet, and both were missing from the bundled snapshot — flagged during #1075 verification on a real corpus (285 sessions, 5,446 calls). `getModelCosts` already resolved both through the `gpt-5.6` prefix fallback, so live pricing was already correct once a session priced fresh; every prior Codex-suffixed id LiteLLM does carry bills identically to its bare-model sibling of the same generation (`gpt-5-codex` == `gpt-5`, `gpt-5.1-codex` == `gpt-5.1-codex-max` == `gpt-5.1`, `gpt-5.2-codex` == `gpt-5.2`, `gpt-5.3-codex` == `gpt-5.3`), which is the evidence both new rows mirror rather than inventing a rate. The gap that does not self-heal is the daily cache: it has no per-provider invalidation, so a day finalized while either id had no billable rate keeps that $0 forever. Raising `MIN_SUPPORTED_VERSION` (v23 -> v24) forces the one-time re-derivation, a lossless no-op for days already correct. (#1077) diff --git a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift index b0400d6e..fa42d332 100644 --- a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift +++ b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift @@ -84,6 +84,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM private var refreshLoopHeartbeatAt: Date = .distantPast func applicationWillTerminate(_ notification: Notification) { + // Synchronously, before the actor hop: the app can exit before a + // detached Task is ever scheduled, and a serve child that outlives us + // is the orphan in #1117. shutdown() still runs for the tidy case. + ServeChildRegistry.shared.reapAll() Task { await ServeConnection.shared.shutdown() } if let monitor = rightClickMonitor { NSEvent.removeMonitor(monitor) diff --git a/mac/Sources/CodeBurnMenubar/Data/CLIWatchdog.swift b/mac/Sources/CodeBurnMenubar/Data/CLIWatchdog.swift new file mode 100644 index 00000000..1345c780 --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/CLIWatchdog.swift @@ -0,0 +1,98 @@ +import Foundation + +/// Swift port of the desktop app's no-output watchdog (`app/electron/cli.ts`, #1096). +/// +/// The CLI timeout is a NO-OUTPUT window, not a total-runtime cap: every byte the +/// child writes on stdout or stderr restarts it. Spawns set `CODEBURN_PROGRESS=1`, +/// under which the parser heartbeats every 10s for the whole duration of a parse +/// (`PROGRESS_KEEPALIVE_MS` in `src/parser.ts`), so a legitimately slow cold parse +/// on a large corpus is never killed while a genuinely wedged child still is. +/// +/// The pure `verdict` exists so the arithmetic is testable without spawning a +/// child and waiting minutes for a real ceiling. +enum CLIWatchdog { + /// Silence a live child cannot produce: 4.5x the CLI's 10s keepalive cadence. + /// Matches `DEFAULT_TIMEOUT_MS` in app/electron/cli.ts. + static let silenceSeconds: Double = 45 + /// Until this app has seen one successful payload the on-disk cache may be + /// empty, and a full hydration has genuinely silent stretches before the + /// first keepalive can be armed. Matches `DESKTOP_COLD_TIMEOUT_MS`. Finite + /// on purpose: a child that never emits a byte still dies here, it just gets + /// the cold budget to prove itself first. + static let coldSilenceSeconds: Double = 10 * 60 + /// Backstop for the watchdog: a livelocked child that chatters forever + /// without finishing is still reaped. Matches `MAX_RUNTIME_MS`. + static let ceilingSeconds: Double = 15 * 60 + /// SIGTERM is catchable, so the CLI unlinks its own refresh lock before dying + /// (`armSignalCleanup` in src/session-cache.ts and src/cache-refresh-lock.ts). + /// Only a child that ignores it gets SIGKILL. Matches `KILL_GRACE_MS`. + static let killGraceSeconds: Double = 5 + + enum Verdict: Equatable { + case wait + case silent + case ceiling + } + + /// `now`, `startedAt` and `lastOutputAt` are seconds on one monotonic scale. + static func verdict(now: Double, + startedAt: Double, + lastOutputAt: Double, + silenceSeconds: Double) -> Verdict { + if now - lastOutputAt >= silenceSeconds { return .silent } + if now - startedAt >= ceilingSeconds { return .ceiling } + return .wait + } + + /// The silence window for a request: the cold floor applies until this app + /// has completed one payload, exactly as the electron client floors every + /// request admitted before its resident child is warm. + static func silenceWindow(warm: Bool) -> Double { + warm ? silenceSeconds : max(silenceSeconds, coldSilenceSeconds) + } + + /// Progress heartbeats share stderr with real diagnostics, and every read + /// spawn now enables them, so they must never become the error message. + static func withoutProgressLines(_ stderr: String) -> String { + stderr + .split(separator: "\n", omittingEmptySubsequences: false) + .filter { !$0.hasPrefix(progressLinePrefix) } + .joined(separator: "\n") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + /// Wire marker for CLI scan-progress lines (`PROGRESS_LINE_PREFIX`, src/parser.ts). + static let progressLinePrefix = "CODEBURN_PROGRESS " + + /// Environment for a spawn that should heartbeat through the watchdog. + static func withProgressHeartbeat(_ environment: [String: String]?) -> [String: String] { + var env = environment ?? ProcessInfo.processInfo.environment + env["CODEBURN_PROGRESS"] = "1" + return env + } +} + +/// Monotonic last-output marker shared by a process's two drain tasks and its +/// watchdog timer. `uptimeNanoseconds` is unaffected by wall-clock jumps. +final class OutputActivity: @unchecked Sendable { + private let lock = NSLock() + private var lastOutput: Double + + init() { lastOutput = OutputActivity.now() } + + static func now() -> Double { + Double(DispatchTime.now().uptimeNanoseconds) / 1_000_000_000 + } + + func touch() { + lock.lock() + lastOutput = OutputActivity.now() + lock.unlock() + } + + var lastOutputAt: Double { + lock.lock() + defer { lock.unlock() } + return lastOutput + } +} diff --git a/mac/Sources/CodeBurnMenubar/Data/DataClient.swift b/mac/Sources/CodeBurnMenubar/Data/DataClient.swift index 73159eed..4af4a8a5 100644 --- a/mac/Sources/CodeBurnMenubar/Data/DataClient.swift +++ b/mac/Sources/CodeBurnMenubar/Data/DataClient.swift @@ -6,9 +6,16 @@ import Foundation /// Pipe file descriptors pinned forever. private let maxPayloadBytes = 20 * 1024 * 1024 private let maxStderrBytes = 256 * 1024 -private let spawnTimeoutSeconds: UInt64 = 45 private let maxConcurrentSpawns = 6 +/// Whether this app run has ever completed a payload fetch. Until it has, the +/// on-disk cache may be cold and a spawn gets the long floor; afterwards the +/// ordinary silence window applies. Mirrors the resident client's `warmed`. +actor SpawnWarmth { + private(set) var warm = false + func markWarm() { warm = true } +} + enum DataClientError: Error { case spawn(String) case nonZeroExit(code: Int32, stderr: String) @@ -62,7 +69,9 @@ struct DataClient { throw DataClientError.nonZeroExit(code: result.exitCode, stderr: result.stderr) } do { - return try JSONDecoder().decode(MenubarPayload.self, from: result.stdout) + let payload = try JSONDecoder().decode(MenubarPayload.self, from: result.stdout) + await warmth.markWarm() + return payload } catch { let snippet = String(decoding: result.stdout.prefix(2048), as: UTF8.self) throw DataClientError.decode(CLIDecodeFailure( @@ -119,6 +128,9 @@ struct DataClient { /// dozens of node processes at once. private static let spawnLimiter = AsyncSemaphore(maxConcurrentSpawns) + /// Cold floor gate for the one-shot path. See `SpawnWarmth`. + static let warmth = SpawnWarmth() + private static func runCLI( subcommand: [String], qualityOfService: QualityOfService = .userInitiated @@ -135,9 +147,13 @@ struct DataClient { subcommand: subcommand, qualityOfService: qualityOfService ) + // Heartbeats for the no-output watchdog: a multi-minute parse + // writes progress lines to stderr instead of going silent. + process.environment = CLIWatchdog.withProgressHeartbeat(process.environment) + let silenceSeconds = CLIWatchdog.silenceWindow(warm: await warmth.warm) return try await runProcess( process, - timeoutSeconds: spawnTimeoutSeconds, + timeoutSeconds: silenceSeconds, label: subcommand.joined(separator: " ") ) } @@ -188,7 +204,10 @@ struct DataClient { } /// Runs an already-configured process to completion, draining its output and - /// enforcing a hard timeout. + /// enforcing the no-output watchdog: `timeoutSeconds` bounds SILENCE, not + /// total runtime, and restarts on every byte the child produces. See + /// `CLIWatchdog` for why (and for the absolute ceiling that still bounds a + /// child which chatters forever). /// /// CRITICAL: nothing here may block a worker thread waiting for the process. /// `process.waitUntilExit()` is a blocking syscall. An earlier fix moved it @@ -200,7 +219,7 @@ struct DataClient { /// `process.terminationHandler`, which fires on a Foundation-managed queue and /// blocks nothing, so the timeout always has a free thread to fire on. static func runProcess(_ process: Process, - timeoutSeconds: UInt64, + timeoutSeconds: Double, label: String) async throws -> ProcessResult { let outPipe = Pipe() let errPipe = Pipe() @@ -218,14 +237,36 @@ struct DataClient { throw DataClientError.spawn(error.localizedDescription) } + // Silence watchdog, not a runtime cap: `activity` is touched by both + // drains, so the window restarts on every byte (progress keepalives + // included) and only a genuinely mute child is killed. + let activity = OutputActivity() + let startedAt = OutputActivity.now() let timeoutTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility)) - timeoutTimer.schedule(deadline: .now() + .seconds(Int(timeoutSeconds))) + timeoutTimer.schedule(deadline: .now() + .seconds(1), repeating: .seconds(1)) timeoutTimer.setEventHandler { - if process.isRunning { - NSLog("CodeBurn: CLI subprocess timed out after %llus for %@ — terminating", + guard process.isRunning else { return } + let verdict = CLIWatchdog.verdict( + now: OutputActivity.now(), + startedAt: startedAt, + lastOutputAt: activity.lastOutputAt, + silenceSeconds: timeoutSeconds + ) + switch verdict { + case .wait: + return + case .silent: + NSLog("CodeBurn: CLI subprocess produced no output for %.0fs for %@ — terminating", timeoutSeconds, label) - terminateWithEscalation(process) + case .ceiling: + NSLog("CodeBurn: CLI subprocess exceeded %.0fs for %@ — terminating", + CLIWatchdog.ceilingSeconds, label) } + // One verdict per process: the escalation owns the kill from here, + // and a repeating tick would re-send SIGTERM every second for the + // whole grace. Cancelling from inside the handler is supported. + timeoutTimer.cancel() + terminateWithEscalation(process) } timeoutTimer.resume() defer { timeoutTimer.cancel() } @@ -233,8 +274,8 @@ struct DataClient { let outHandle = outPipe.fileHandleForReading let errHandle = errPipe.fileHandleForReading let (out, err) = await withTaskCancellationHandler { - async let stdoutData = drain(outHandle, limit: maxPayloadBytes) - async let stderrData = drain(errHandle, limit: maxStderrBytes) + async let stdoutData = drain(outHandle, limit: maxPayloadBytes, activity: activity) + async let stderrData = drain(errHandle, limit: maxStderrBytes, activity: activity) return await (stdoutData, stderrData) } onCancel: { terminateWithEscalation(process) @@ -249,20 +290,23 @@ struct DataClient { throw DataClientError.outputTooLarge } - let stderrString = String(data: err, encoding: .utf8) ?? "" + let stderrString = CLIWatchdog.withoutProgressLines(String(data: err, encoding: .utf8) ?? "") return ProcessResult(stdout: out, stderr: stderrString, exitCode: process.terminationStatus) } + /// Ask a child to exit, then insist. The grace exists so the CLI's signal + /// cleanup can unlink the cache refresh lock it may be holding before it + /// dies; only a child that ignores SIGTERM is SIGKILLed. private static func terminateWithEscalation(_ process: Process) { guard process.isRunning else { return } process.terminate() let pid = process.processIdentifier - DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.5) { + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + CLIWatchdog.killGraceSeconds) { if process.isRunning { kill(pid, SIGKILL) } } } - private static func drain(_ handle: FileHandle, limit: Int) async -> Data { + private static func drain(_ handle: FileHandle, limit: Int, activity: OutputActivity) async -> Data { let fd = handle.fileDescriptor let flags = Darwin.fcntl(fd, F_GETFL) if flags >= 0 { @@ -280,6 +324,7 @@ struct DataClient { Darwin.read(fd, ptr.baseAddress!, toRead) } if n > 0 { + activity.touch() buffer.append(contentsOf: chunk.prefix(n)) } else if n == 0 { break diff --git a/mac/Sources/CodeBurnMenubar/Data/ServeConnection.swift b/mac/Sources/CodeBurnMenubar/Data/ServeConnection.swift index 4d1f879c..78f1b1a9 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ServeConnection.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ServeConnection.swift @@ -36,12 +36,20 @@ actor ServeConnection { private var process: Process? private var stdinHandle: FileHandle? + /// Permanent refusal (explicit shutdown, or a binary that cannot be spawned + /// at all). Distinct from a spent death budget, which recovers with time. + private var disabled = false + private var lastDeathAt: Date? private var nextId = 1 private var nextRequestToken = 1 private var queuedRequests: [QueuedRequest] = [] private var activeRequest: ActiveRequest? private var pending: [Int: CheckedContinuation] = [:] private var requestTimeouts: [Int: Task] = [:] + private var requestCeilings: [Int: Task] = [:] + /// Silence window of the in-flight request, so any frame carrying its id can + /// re-arm the same budget. See `CLIWatchdog`. + private var requestSilence: [Int: UInt64] = [:] private var timeoutOwners: [Int: Process] = [:] private var responseBytes: [Int: Int] = [:] private var deaths = 0 @@ -57,9 +65,18 @@ actor ServeConnection { private static let maxDeaths = 3 static let maxResponseBytes = 16 * 1024 * 1024 private static let stdoutReadChunkBytes = 64 * 1024 - private static let terminationGraceNanoseconds: UInt64 = 1_000_000_000 - private static let coldRequestTimeoutNanoseconds: UInt64 = 10 * 60 * 1_000_000_000 - private static let warmRequestTimeoutNanoseconds: UInt64 = 60 * 1_000_000_000 + private static let terminationGraceNanoseconds = nanoseconds(CLIWatchdog.killGraceSeconds) + /// Absolute backstop per request: a child that heartbeats forever without + /// ever answering is still reaped. + private static let requestCeilingNanoseconds = nanoseconds(CLIWatchdog.ceilingSeconds) + /// The death budget is spent by a transient cause as easily as a permanent + /// one (a cold-cache pile-up spends all three in a minute). Let a later tick + /// try again instead of leaving the resident dead for the whole app run. + private static let deathBudgetResetSeconds: TimeInterval = 300 + + private static func nanoseconds(_ seconds: Double) -> UInt64 { + UInt64(seconds * 1_000_000_000) + } struct ServeUnavailable: Error {} enum FailureReason: Sendable, Equatable { @@ -99,19 +116,37 @@ actor ServeConnection { /// Kick the child off (idempotent). Called from app startup and again by /// the first request in case the startup task has not run yet. + /// + /// Re-entry: a spent death budget is a cooldown, not a life sentence. The + /// budget's job is to stop a crash loop from spawning a child per tick; once + /// `deathBudgetResetSeconds` have passed with no new death, the next tick + /// gets a fresh budget instead of leaving every fetch on the one-shot path + /// for the rest of the app run. func ensureStarted() { - guard process == nil, deaths < Self.maxDeaths else { return } + guard !disabled, process == nil else { return } + if deaths >= Self.maxDeaths { + guard let lastDeathAt, + Date().timeIntervalSince(lastDeathAt) >= Self.deathBudgetResetSeconds else { return } + deaths = 0 + } + // Before adding a child, clear the one a crashed previous run (or an + // earlier generation of this one) left behind. Idempotent: the recorded + // pid is only signalled if it is still that exact serve command. + ServeOrphanReaper.reap() // This single resident serves both background and user-visible status // requests. Its cold hydration replaces the old interactive one-shot, // so keep the child at the same user-initiated QoS as visible fetches. let child = makeProcess(["serve", "--stdio"], .userInitiated) + // Progress frames are what re-arm this connection's no-output watchdog + // during a cold hydration; without them serve is silent for minutes. + child.environment = CLIWatchdog.withProgressHeartbeat(child.environment) let stdinPipe = Pipe() let stdinWriter = stdinPipe.fileHandleForWriting // Suppress SIGPIPE only for this connection's write end. A process-wide // SIG_IGN leaks into unrelated libraries and children; F_SETNOSIGPIPE // keeps a closed child stdin on the normal throwable EPIPE path. guard Darwin.fcntl(stdinWriter.fileDescriptor, F_SETNOSIGPIPE, 1) == 0 else { - deaths = Self.maxDeaths + disabled = true return } let stdoutPipe = Pipe() @@ -122,11 +157,18 @@ actor ServeConnection { do { try child.run() } catch { - deaths = Self.maxDeaths // spawn path can't produce the binary either better than makeProcess did + disabled = true // spawn path can't produce the binary either better than makeProcess did return } process = child stdinHandle = stdinWriter + ServeChildRegistry.shared.add(child) + // Record the argv WITHOUT the `/usr/bin/env --` prefix: that is the part + // exec rewrites away before `ps` can see it. See serveCommandMatches. + ServeOrphanReaper.record( + pid: child.processIdentifier, + command: (child.arguments ?? []).drop(while: { $0 == "--" }).joined(separator: " ") + ) let generation = ObjectIdentifier(child) // One blocking reader owns this generation's stdout. It never reads a // second bounded chunk until the actor has consumed the first, giving @@ -177,16 +219,24 @@ actor ServeConnection { } func shutdown() { + disabled = true deaths = Self.maxDeaths - process?.terminate() for task in terminationTasks.values { task.cancel() } terminationTasks.removeAll() cancelAllTimeouts() failAllRequests() + try? stdinHandle?.close() process = nil stdinHandle = nil buffer = Data() receivedTerminalResponse = false + // Deliberately harder than every other kill path, and covering RETIRED + // generations too: quit has no budget to wait a SIGTERM grace out, and + // the grace task dies with the app, so a child that defers SIGTERM (a + // node process mid-synchronous-parse does) would outlive us. A refresh + // lock left behind by SIGKILL self-heals through the next parse's + // dead-pid takeover (src/cache-refresh-lock.ts). + ServeChildRegistry.shared.reapAll() } // MARK: - internals @@ -226,10 +276,9 @@ actor ServeConnection { // Select and arm the timeout only when this request becomes the sole // protocol request in flight. A queued request must not spend its own - // budget while its predecessor is still hydrating or draining. - let timeoutNanoseconds = receivedTerminalResponse - ? Self.warmRequestTimeoutNanoseconds - : Self.coldRequestTimeoutNanoseconds + // budget while its predecessor is still hydrating or draining. The + // budget bounds SILENCE: every frame carrying this id restarts it. + let timeoutNanoseconds = Self.nanoseconds(CLIWatchdog.silenceWindow(warm: receivedTerminalResponse)) activeRequest = ActiveRequest( token: request.token, id: id, @@ -271,8 +320,26 @@ actor ServeConnection { } private func armTimeout(id: Int, child: Process, nanoseconds: UInt64) { - let sleep = timeoutSleep timeoutOwners[id] = child + requestSilence[id] = nanoseconds + armSilenceTimer(id: id, nanoseconds: nanoseconds) + // Deliberately a real sleep, not `timeoutSleep`: the ceiling is a + // 15-minute backstop behind the injected silence budget, and routing it + // through the same seam would make every test's timeout ledger carry it. + // Its arithmetic is covered by CLIWatchdog.verdict. + requestCeilings[id] = Task.detached { [weak self] in + do { + try await Task.sleep(nanoseconds: Self.requestCeilingNanoseconds) + } catch { + return + } + await self?.requestTimedOut(id: id) + } + } + + private func armSilenceTimer(id: Int, nanoseconds: UInt64) { + let sleep = timeoutSleep + requestTimeouts[id]?.cancel() requestTimeouts[id] = Task.detached { [weak self] in do { try await sleep(nanoseconds) @@ -283,6 +350,14 @@ actor ServeConnection { } } + /// Any frame carrying this request's id is proof of life: restart its + /// watchdog so a long cold parse that heartbeats progress is never killed + /// mid-flight. The absolute ceiling is untouched. + private func touchRequest(id: Int) { + guard let nanoseconds = requestSilence[id] else { return } + armSilenceTimer(id: id, nanoseconds: nanoseconds) + } + private func requestTimedOut(id: Int) { guard let child = timeoutOwners.removeValue(forKey: id) else { return } requestTimeouts.removeValue(forKey: id) @@ -302,11 +377,7 @@ actor ServeConnection { // reach EOF (for example, a stuck child can ignore SIGTERM or a // descendant can retain the pipe), so waiting for the reader would also // spend every queued caller's timeout before it can even be admitted. - process = nil - stdinHandle = nil - buffer = Data() - receivedTerminalResponse = false - deaths += 1 + retireCurrentGeneration() if activeRequest?.id == id { activeRequest = nil } cancelTimeouts(ownedBy: child) terminateTimedOutChild(child) @@ -319,6 +390,8 @@ actor ServeConnection { private func cancelTimeout(id: Int) { timeoutOwners.removeValue(forKey: id) requestTimeouts.removeValue(forKey: id)?.cancel() + requestCeilings.removeValue(forKey: id)?.cancel() + requestSilence.removeValue(forKey: id) responseBytes.removeValue(forKey: id) } @@ -330,14 +403,34 @@ actor ServeConnection { private func cancelAllTimeouts() { for task in requestTimeouts.values { task.cancel() } requestTimeouts.removeAll() + for task in requestCeilings.values { task.cancel() } + requestCeilings.removeAll() + requestSilence.removeAll() timeoutOwners.removeAll() responseBytes.removeAll() } + /// Detach the current generation. Closing our end of its stdin is the app's + /// half of "stdin closing ends the server loop": dropping the FileHandle is + /// NOT enough, because the Pipe stays alive inside `child.standardInput` for + /// as long as this generation's reader or termination task holds the + /// Process, so the write end stays open and the retired child never sees + /// EOF. That is how a retired-but-alive serve child becomes an orphan. + private func retireCurrentGeneration() { + try? stdinHandle?.close() + process = nil + stdinHandle = nil + buffer = Data() + receivedTerminalResponse = false + deaths += 1 + lastDeathAt = Date() + } + private func outputStreamFinished(for child: Process) { outputTasks.removeValue(forKey: ObjectIdentifier(child)) if !child.isRunning { terminationTasks.removeValue(forKey: ObjectIdentifier(child))?.cancel() + ServeChildRegistry.shared.remove(child) } } @@ -363,17 +456,23 @@ actor ServeConnection { private func forceKillAfterGrace(_ child: Process) { terminationTasks.removeValue(forKey: ObjectIdentifier(child)) - guard child.isRunning else { return } + guard child.isRunning else { + ServeChildRegistry.shared.remove(child) + return + } _ = Darwin.kill(child.processIdentifier, SIGKILL) + ServeChildRegistry.shared.remove(child) } private func outputStreamEnded(for child: Process) { guard process === child else { return } // EOF/read failure is a transport death even if the process has not // reaped yet. Terminate that exact generation so a child which closed - // stdout cannot survive after the actor starts its replacement. - if child.isRunning { child.terminate() } + // stdout cannot survive after the actor starts its replacement, and + // escalate: SIGTERM alone is deferred by a node child that is inside a + // synchronous parse when it arrives. childDied(child) + terminateTimedOutChild(child) } // Internal so the generation guard can be exercised deterministically by @@ -420,6 +519,10 @@ actor ServeConnection { // Menubar has no progress UI, but must leave the request pending // until the terminal response arrives if such a frame is emitted. if let progress = object["progress"] as? String { + // Proof of life for a request still being worked on: restart its + // silence window. A terminal frame does not need this - it + // cancels the timers outright a few lines down. + touchRequest(id: id) guard accountResponseBytes(Data(progress.utf8).count, id: id, child: child) else { return } return } @@ -467,26 +570,18 @@ actor ServeConnection { // Detach this exact generation before terminating it. Its eventual exit // and any already-scheduled stdout callbacks are then stale and cannot // consume a second death or corrupt a replacement generation. - process = nil - stdinHandle = nil - buffer = Data() - receivedTerminalResponse = false - deaths += 1 + retireCurrentGeneration() cancelTimeouts(ownedBy: child) failAllRequests(error: ServeRequestFailed( message: "serve output exceeded \(responseLimitBytes) bytes", reason: .outputTooLarge )) - if child.isRunning { child.terminate() } + terminateTimedOutChild(child) } private func childDied(_ child: Process) { guard process === child else { return } - process = nil - stdinHandle = nil - buffer.removeAll() - receivedTerminalResponse = false - deaths += 1 + retireCurrentGeneration() cancelTimeouts(ownedBy: child) if let activeRequest, activeRequest.child === child { if let continuation = pending.removeValue(forKey: activeRequest.id) { @@ -527,3 +622,116 @@ actor ServeConnection { } } } + +/// Best-effort reap of a serve child orphaned by a previous run: a crash leaves +/// no one to close the child's stdin and no `applicationWillTerminate` to reap +/// it. Port of `reapOrphanServe` in app/electron/cli.ts (#1096). +enum ServeOrphanReaper { + static func pidFileURL() -> URL { + URL(fileURLWithPath: CodeBurnCacheDirectory.resolve()) + .appendingPathComponent("menubar-serve.pid", isDirectory: false) + } + + static func record(pid: pid_t, command: String) { + let url = pidFileURL() + try? FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + let body = ["pid": Int(pid), "cmd": command] as [String: Any] + guard let data = try? JSONSerialization.data(withJSONObject: body) else { return } + try? data.write(to: url) // reaping is best-effort + } + + /// Reads the pid recorded by the previous run and — because pids are + /// recycled — signals it only after `ps` confirms the process is still that + /// exact serve child. SIGTERM, never SIGKILL: the orphan may be holding the + /// cache refresh lock and can release it on the way out. + static func reap() { + let url = pidFileURL() + defer { try? FileManager.default.removeItem(at: url) } + guard let data = try? Data(contentsOf: url), + let record = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let pid = record["pid"] as? Int, + let cmd = record["cmd"] as? String, + pid > 1, pid != Int(ProcessInfo.processInfo.processIdentifier), + !cmd.isEmpty, + serveCommandMatches(recorded: cmd, observed: commandLine(of: pid_t(pid))) + else { return } + _ = Darwin.kill(pid_t(pid), SIGTERM) + } + + /// Suffix match on the full recorded argv, not a keyword sniff: any looser + /// test signals whatever unrelated process inherited the pid. + /// + /// Electron can compare exactly because it spawns its own binary. We spawn + /// through `/usr/bin/env`, and the CLI is a shebang script, so by the time + /// `ps` sees the process the argv has been rewritten twice: `env -- + /// serve --stdio` becomes `node serve --stdio`. The interpreter + /// prefix is the only part that varies, so the recorded ` serve + /// --stdio` has to match as a suffix rather than in full. + static func serveCommandMatches(recorded: String, observed: String?) -> Bool { + guard let observed else { return false } + let normalize = { (value: String) -> String in + value.split(whereSeparator: { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\"" }) + .joined(separator: " ") + } + let wanted = normalize(recorded) + return !wanted.isEmpty && normalize(observed).hasSuffix(wanted) + } + + /// `-ww` defeats ps's width truncation; the pid is an integer before it is + /// passed, and the call never goes through a shell. + private static func commandLine(of pid: pid_t) -> String? { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/ps") + process.arguments = ["-ww", "-o", "command=", "-p", String(pid)] + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = FileHandle.nullDevice + guard (try? process.run()) != nil else { return nil } + // readToEnd returns at EOF, which is this short-lived child exiting; no + // waitUntilExit, which would park the calling thread (see DataClient). + let data = (try? pipe.fileHandleForReading.readToEnd()) ?? nil + let text = String(data: data ?? Data(), encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return text.isEmpty ? nil : text + } +} + +/// Every serve child this app run has started and not yet seen exit, readable +/// WITHOUT an actor hop. +/// +/// `applicationWillTerminate` runs `Task { await shutdown() }`, and the app can +/// exit before that task is ever scheduled — so the actor's own reaping is not +/// reachable on the path that matters most. This registry is, and a Process that +/// still reports `isRunning` has not been waited on, so its pid is still ours +/// and cannot have been recycled under us. +final class ServeChildRegistry: @unchecked Sendable { + static let shared = ServeChildRegistry() + + private let lock = NSLock() + private var children: [ObjectIdentifier: Process] = [:] + + func add(_ child: Process) { + lock.lock() + children[ObjectIdentifier(child)] = child + lock.unlock() + } + + func remove(_ child: Process) { + lock.lock() + children.removeValue(forKey: ObjectIdentifier(child)) + lock.unlock() + } + + func reapAll() { + lock.lock() + let all = Array(children.values) + children.removeAll() + lock.unlock() + for child in all where child.isRunning { + _ = Darwin.kill(child.processIdentifier, SIGKILL) + } + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/CLIWatchdogTests.swift b/mac/Tests/CodeBurnMenubarTests/CLIWatchdogTests.swift new file mode 100644 index 00000000..172811ae --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/CLIWatchdogTests.swift @@ -0,0 +1,79 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("CLI watchdog") +struct CLIWatchdogTests { + @Test("silence is measured from the last output, not from the start") + func silenceIsMeasuredFromLastOutput() { + // Ten minutes in, still chattering every second: not silent. + let verdict = CLIWatchdog.verdict(now: 600, startedAt: 0, lastOutputAt: 599, silenceSeconds: 45) + #expect(verdict == .wait) + } + + @Test("a mute child is killed after the silence window") + func muteChildIsKilled() { + #expect(CLIWatchdog.verdict(now: 44, startedAt: 0, lastOutputAt: 0, silenceSeconds: 45) == .wait) + #expect(CLIWatchdog.verdict(now: 45, startedAt: 0, lastOutputAt: 0, silenceSeconds: 45) == .silent) + } + + /// The cold floor must not become a licence to live forever: a child that + /// never emits a byte is still killed, it just gets the cold budget first. + @Test("the cold floor still ends in a kill for a child that never speaks") + func coldFloorStillEndsInAKill() { + let window = CLIWatchdog.silenceWindow(warm: false) + #expect(window == CLIWatchdog.coldSilenceSeconds) + #expect(CLIWatchdog.verdict(now: window - 1, startedAt: 0, lastOutputAt: 0, silenceSeconds: window) == .wait) + #expect(CLIWatchdog.verdict(now: window, startedAt: 0, lastOutputAt: 0, silenceSeconds: window) == .silent) + } + + @Test("a child that chatters forever is still reaped at the ceiling") + func chatteringChildHitsTheCeiling() { + let now = CLIWatchdog.ceilingSeconds + 1 + #expect(CLIWatchdog.verdict(now: now, startedAt: 0, lastOutputAt: now - 1, silenceSeconds: 45) == .ceiling) + } + + @Test("a warm request uses the short silence window") + func warmRequestUsesShortWindow() { + #expect(CLIWatchdog.silenceWindow(warm: true) == CLIWatchdog.silenceSeconds) + #expect(CLIWatchdog.silenceSeconds < CLIWatchdog.coldSilenceSeconds) + #expect(CLIWatchdog.coldSilenceSeconds < CLIWatchdog.ceilingSeconds) + } + + @Test("progress heartbeats never become the error message") + func progressLinesAreStrippedFromStderr() { + let stderr = """ + CODEBURN_PROGRESS {"kind":"keepalive"} + warn: something real + CODEBURN_PROGRESS {"kind":"tick"} + """ + #expect(CLIWatchdog.withoutProgressLines(stderr) == "warn: something real") + #expect(CLIWatchdog.withoutProgressLines("CODEBURN_PROGRESS {\"kind\":\"keepalive\"}") == "") + } + + @Test("spawn env enables the CLI keepalive the watchdog listens for") + func spawnEnvEnablesKeepalive() { + let env = CLIWatchdog.withProgressHeartbeat(["PATH": "/usr/bin"]) + #expect(env["CODEBURN_PROGRESS"] == "1") + #expect(env["PATH"] == "/usr/bin") + } + + @Test("orphan reap only signals the exact recorded serve command") + func orphanReapMatchesExactCommand() { + // A shebang exec rewrites argv[0], so the recorded argv matches as a suffix. + #expect(ServeOrphanReaper.serveCommandMatches( + recorded: "/opt/homebrew/bin/codeburn serve --stdio", + observed: "node /opt/homebrew/bin/codeburn serve --stdio" + )) + // A recycled pid running something else is never signalled. + #expect(!ServeOrphanReaper.serveCommandMatches( + recorded: "/opt/homebrew/bin/codeburn serve --stdio", + observed: "node /opt/homebrew/bin/codeburn status" + )) + #expect(!ServeOrphanReaper.serveCommandMatches( + recorded: "/opt/homebrew/bin/codeburn serve --stdio", + observed: nil + )) + #expect(!ServeOrphanReaper.serveCommandMatches(recorded: "", observed: "anything")) + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift b/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift index 24939dea..2a282a30 100644 --- a/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift @@ -195,6 +195,33 @@ struct DataClientProcessTests { "every concurrent process should exit 0 via the terminationHandler wait path") } + /// #1117: the window bounds SILENCE, not runtime. A child that keeps talking + /// past its window runs to completion; the old fixed timeout killed it. + @Test("a chattering child outlives its window", .timeLimit(.minutes(1))) + func chatteringChildOutlivesItsWindow() async throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = ["-c", "for i in 1 2 3 4 5 6; do echo tick; sleep 0.4; done"] + let result = try await DataClient.runProcess(process, timeoutSeconds: 1, label: "chatty") + #expect(result.exitCode == 0, "a child emitting output every 0.4s must survive a 1s silence window") + } + + /// The CLI's keepalive goes to STDERR, so stderr has to re-arm the watchdog + /// too - and must not then turn up as the error message. + @Test("stderr keepalives keep a stdout-silent child alive and stay out of the error text", + .timeLimit(.minutes(1))) + func stderrKeepalivesCountAsOutput() async throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = [ + "-c", + #"for i in 1 2 3 4 5 6; do printf 'CODEBURN_PROGRESS {"kind":"keepalive"}\n' >&2; sleep 0.4; done; exit 3"#, + ] + let result = try await DataClient.runProcess(process, timeoutSeconds: 1, label: "keepalive") + #expect(result.exitCode == 3, "stderr keepalives must restart the silence window") + #expect(result.stderr == "", "progress lines must never become the error message") + } + /// The async semaphore never lets more than its count run concurrently. @Test("async semaphore caps concurrency") func asyncSemaphoreCapsConcurrency() async { diff --git a/mac/Tests/CodeBurnMenubarTests/ServeConnectionTests.swift b/mac/Tests/CodeBurnMenubarTests/ServeConnectionTests.swift index a5c7588e..5114eb27 100644 --- a/mac/Tests/CodeBurnMenubarTests/ServeConnectionTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/ServeConnectionTests.swift @@ -5,8 +5,8 @@ import Testing private let ignoredSIGPIPEHandlerBits = unsafeBitCast(SIG_IGN, to: UInt.self) private let coldTimeoutNanoseconds: UInt64 = 10 * 60 * 1_000_000_000 -private let warmTimeoutNanoseconds: UInt64 = 60 * 1_000_000_000 -private let terminationGraceNanoseconds: UInt64 = 1_000_000_000 +private let warmTimeoutNanoseconds: UInt64 = 45 * 1_000_000_000 +private let terminationGraceNanoseconds: UInt64 = 5 * 1_000_000_000 private func currentSIGPIPEHandlerBits() -> UInt { var action = sigaction() diff --git a/scripts/upgrade-path/run.mjs b/scripts/upgrade-path/run.mjs index ac848043..c7af2816 100644 --- a/scripts/upgrade-path/run.mjs +++ b/scripts/upgrade-path/run.mjs @@ -33,7 +33,7 @@ const WORK = process.env['UPGRADE_PATH_WORK'] || join(tmpdir(), 'codeburn upgrad const OLD_SESSION_CACHE = 'session-cache.v7.json' const OLD_DAILY_CACHE = 'daily-cache.v17.json' const NEW_SESSION_CACHE_DIR = 'session-cache.v9' -const NEW_DAILY_CACHE = 'daily-cache.v27.json' +const NEW_DAILY_CACHE = 'daily-cache.v28.json' const HOME = join(WORK, 'user home') const PAYLOADS = join(WORK, 'payloads') diff --git a/src/behavioral-weight.ts b/src/behavioral-weight.ts index 01a59174..5703fa56 100644 --- a/src/behavioral-weight.ts +++ b/src/behavioral-weight.ts @@ -2,9 +2,10 @@ // requests. A copilot shutdown rollup, synthesized residual, or store row // paired with its per-turn call (`supplementaryAccounting`, assigned at serve // time) carries real tokens and cost but is not a distinct behavioral -// request. Every user-visible calls/turns counter weighs calls through these -// helpers so no surface can disagree with the session summaries or the -// sealed daily history. Token and cost sums intentionally keep every call — +// request. Hermes observation-time deltas persist the same flag. Every +// user-visible calls/turns counter weighs calls through these helpers so no +// surface can disagree with the session summaries or the sealed daily +// history. Token and cost sums intentionally keep every call — // supplementary accounting must never be filtered out, only weightless. type WeightedCall = { supplementaryAccounting?: boolean } diff --git a/src/cache-refresh-lock.ts b/src/cache-refresh-lock.ts index f467886f..da287122 100644 --- a/src/cache-refresh-lock.ts +++ b/src/cache-refresh-lock.ts @@ -1,5 +1,5 @@ import { createHash, randomBytes } from 'crypto' -import { existsSync } from 'fs' +import { existsSync, readFileSync, unlinkSync } from 'fs' import { mkdir, open, readFile, stat, unlink, utimes, writeFile } from 'fs/promises' import { join } from 'path' @@ -9,7 +9,13 @@ const LOCK_FILE = 'session-refresh.lock' const TAKEOVER_FILE = `${LOCK_FILE}.takeover` const DEFAULT_HEARTBEAT_MS = 10_000 const DEFAULT_STALE_MS = 90_000 -const DEFAULT_WAIT_MS = 30_000 +// A waiter that gives up before the stale gate opens can NEVER recover an +// abandoned lock, so an abandoned lock livelocks every later process: each one +// burns its whole wait, times out, serves read-only, and the leftover survives +// (#1117). The default is therefore derived from staleMs rather than fixed, so +// the two can never drift back out of order. The common abandoned case does not +// wait this long anyway - a dead holder's pid is detected on the first poll. +const DEFAULT_WAIT_MARGIN_MS = 30_000 const DEFAULT_POLL_MS = 100 const WINDOWS_RETRIES = 3 @@ -51,6 +57,51 @@ function delay(ms: number): Promise { return new Promise(resolve => { setTimeout(resolve, ms) }) } +// Mirrors session-cache.ts's hydrating.lock probe. Our own pid never counts as a +// foreign holder. EPERM means the pid exists but belongs to another user - still +// alive. Windows supports signal 0 as an existence test the same way. +// +// A false "alive" (the holder died and an unrelated process inherited its pid) +// only delays recovery to the age gate. A false "dead" would be the dangerous +// direction, and needs the lock file to have been written by a process on +// another host - i.e. a cache dir on a network share, which nothing supports. +function pidLooksAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false + try { process.kill(pid, 0); return true } + catch (err) { return (err as NodeJS.ErrnoException).code === 'EPERM' } +} + +// The path of the lock this process currently owns, for the signal handler. +// Single-flight guarantees at most one owned lock per process at a time. +let ownedLockPath: string | null = null + +// Synchronous variant for the signal path: a handler can't await, so read + +// unlink synchronously. Only unlinks a lock we actually own. +function removeOurLockSync(): void { + if (!ownedLockPath) return + try { + const parsed = JSON.parse(readFileSync(ownedLockPath, 'utf-8')) as Partial + if (parsed?.pid === process.pid) unlinkSync(ownedLockPath) + } catch { /* best-effort; nothing to clean or already gone */ } +} + +// Arm once, only while we hold the lock: on a catchable termination (Ctrl-C, or +// the menubar/desktop watchdog's SIGTERM) clean our lock before dying so a +// killed refresh leaves no leftover. SIGKILL can't be caught, so that path still +// relies on the waiter's dead-pid takeover. process.once + re-raise preserves +// the default exit and any other listener. Mirrors session-cache.ts. +let signalCleanupArmed = false +function armSignalCleanup(): void { + if (signalCleanupArmed) return + signalCleanupArmed = true + for (const sig of ['SIGINT', 'SIGTERM'] as const) { + process.once(sig, () => { + removeOurLockSync() + process.kill(process.pid, sig) + }) + } +} + function isBusyError(err: unknown): boolean { const code = (err as NodeJS.ErrnoException | undefined)?.code return code === 'EPERM' || code === 'EBUSY' @@ -198,7 +249,7 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): const clock = options.clock ?? defaultClock const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS const staleMs = options.staleMs ?? DEFAULT_STALE_MS - const waitMs = options.waitMs ?? DEFAULT_WAIT_MS + const waitMs = options.waitMs ?? staleMs + DEFAULT_WAIT_MARGIN_MS const pollMs = options.pollMs ?? DEFAULT_POLL_MS const sleep = options.sleep ?? delay const lockPath = join(cacheDir, LOCK_FILE) @@ -219,6 +270,24 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): return next } + // An abandoned lock is one whose heartbeat has FROZEN - mtime stops advancing + // the moment the holder dies or is displaced, and a live holder rewrites it + // every heartbeatMs - OR whose recorded holder pid is gone. The pid check is + // what turns a SIGKILLed holder from a full staleMs stall into a one-poll + // recovery; the age check still covers every holder we cannot probe (a corrupt + // body, a future version's record shape, a holder on another host). + // + // A LIVE holder is never abandoned by either clause, which is the whole safety + // argument: its heartbeat keeps the mtime inside staleMs and its pid answers + // signal 0. Our own pid is treated as alive so a leaked in-process handle is + // never stolen from either. Callers re-observe under the takeover guard and + // require the bytes to be unchanged before acting on this. + const abandoned = (observation: Observation): boolean => { + if (Math.max(0, clock.wallNow() - observation.mtimeMs) > staleMs) return true + const pid = observation.record?.pid + return pid !== undefined && pid !== process.pid && !pidLooksAlive(pid) + } + const acquireTakeoverGuard = async (): Promise<'created' | 'exists' | 'unavailable'> => { const created = await createExclusive(takeoverPath, body()) if (created !== 'exists') return created @@ -226,7 +295,10 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): if (staleGuard === 'missing') return createExclusive(takeoverPath, body()) if (staleGuard === 'changing') return 'exists' if (staleGuard === 'unavailable') return 'unavailable' - if (Math.max(0, clock.wallNow() - staleGuard.mtimeMs) <= staleMs) return 'exists' + // Same abandonment test as the primary lock: a holder killed while it held + // the guard would otherwise block every takeover for a full staleMs and + // defeat the dead-pid fast path on the lock itself. + if (!abandoned(staleGuard)) return 'exists' const reverified = await observe(takeoverPath) if (reverified === 'missing') return createExclusive(takeoverPath, body()) if (reverified === 'changing') return 'exists' @@ -273,6 +345,8 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): const makeHandle = (): RefreshLockHandle => { let released = false let heartbeatRunning = false + ownedLockPath = lockPath + armSignalCleanup() const heartbeat = setInterval(() => { void serializeOwnerOp(async () => { if (released || heartbeatRunning) return @@ -316,6 +390,7 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): release: async () => { if (released) return released = true + ownedLockPath = null clearInterval(heartbeat) while (heartbeatRunning) await sleep(1) await removeIfOwned() @@ -340,7 +415,7 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): if (current === 'unavailable') return { outcome: 'unavailable' } if (current === 'changing') return null if (current === 'missing' || !sameObservation(stale, current)) return null - if (Math.max(0, clock.wallNow() - current.mtimeMs) <= staleMs) return null + if (!abandoned(current)) return null if (!await retryWindowsMutation(() => unlink(lockPath), sleep)) return { outcome: 'unavailable' } // Publish the successor while the takeover guard is still canonical. // Otherwise a waiter can observe neither file and misclassify the narrow @@ -390,8 +465,7 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): // and left alone, because it may belong to a live owner whose heartbeat // will repair it. Worst case we time out and serve the prior snapshot // read-only for one staleMs window instead of freezing forever. - const age = Math.max(0, clock.wallNow() - observation.mtimeMs) - if (age > staleMs) { + if (abandoned(observation)) { const takeover = await tryTakeover(observation) if (takeover) { if (takeover.outcome !== 'acquired') leave() diff --git a/src/compare-stats.ts b/src/compare-stats.ts index 5faabf73..2b4b9931 100644 --- a/src/compare-stats.ts +++ b/src/compare-stats.ts @@ -4,6 +4,7 @@ import { join } from 'path' import type { ClassifiedTurn, ProjectSummary } from './types.js' import { isBehavioralCall } from './behavioral-weight.js' import { getShortModelName } from './models.js' +import { callBillableOutputTokens } from './session-output.js' const PLANNING_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TodoWrite', 'EnterPlanMode', 'ExitPlanMode']) @@ -67,7 +68,7 @@ export function aggregateModelStats(projects: ProjectSummary[]): ModelStats[] { const cs = call.model === primaryModel ? ms : ensure(call.model) if (isBehavioralCall(call)) cs.calls++ cs.cost += call.costUSD - cs.outputTokens += call.usage.outputTokens + cs.outputTokens += callBillableOutputTokens(call) cs.inputTokens += call.usage.inputTokens cs.cacheReadTokens += call.usage.cacheReadInputTokens cs.cacheWriteTokens += call.usage.cacheCreationInputTokens diff --git a/src/daily-cache.ts b/src/daily-cache.ts index b59561cc..400806bc 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -168,8 +168,12 @@ import type { DateRange, ProjectSummary } from './types.js' // v25: #1047 activity-id pricing. v24 on main already shipped #1090. // v26: #946 copilot session-store accounting (see the top of this ladder). // v27: #1093 claude-haiku-4.5 alias (see top). -export const DAILY_CACHE_VERSION = 27 -const MIN_SUPPORTED_VERSION = 27 +// v28: #1115 report/optimize output tokens go through billableOutputTokens. +// Exclusive providers (Grok and the rest) were under-counted by reasoningTokens +// in finalized daily rows; inclusive {claude,codex,copilot} were correct there +// but optimize added reasoning again. Re-derive so report matches the live parse. +export const DAILY_CACHE_VERSION = 28 +const MIN_SUPPORTED_VERSION = 28 /// Providers whose per-day CALL COUNT means something different at /// DAILY_CACHE_VERSION 26 than it did before it. Copilot's supplementary diff --git a/src/day-aggregator.ts b/src/day-aggregator.ts index bab24617..101d6097 100644 --- a/src/day-aggregator.ts +++ b/src/day-aggregator.ts @@ -2,6 +2,7 @@ import type { DailyEntry, ProjectDayStats, ProviderDaySlice } from './daily-cach import type { PeriodData } from './menubar-json.js' import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js' import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js' +import { billableOutputTokens } from './models.js' function emptyEntry(date: string): DailyEntry { return { @@ -189,8 +190,13 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[], dateKeyFn: callDay.cost += call.costUSD callDay.savingsUSD += callSavings callDay.calls += callWeight + const billableOut = billableOutputTokens( + call.provider, + call.usage.outputTokens, + call.usage.reasoningTokens, + ) callDay.inputTokens += call.usage.inputTokens - callDay.outputTokens += call.usage.outputTokens + callDay.outputTokens += billableOut callDay.cacheReadTokens += call.usage.cacheReadInputTokens callDay.cacheWriteTokens += call.usage.cacheCreationInputTokens @@ -208,7 +214,7 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[], dateKeyFn: model.cost += call.costUSD model.savingsUSD += callSavings model.inputTokens += call.usage.inputTokens - model.outputTokens += call.usage.outputTokens + model.outputTokens += billableOut model.cacheReadTokens += call.usage.cacheReadInputTokens model.cacheWriteTokens += call.usage.cacheCreationInputTokens callDay.models[call.model] = model @@ -218,7 +224,7 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[], dateKeyFn: slice.cost += call.costUSD slice.savingsUSD += callSavings slice.inputTokens! += call.usage.inputTokens - slice.outputTokens! += call.usage.outputTokens + slice.outputTokens! += billableOut slice.cacheReadTokens! += call.usage.cacheReadInputTokens slice.cacheWriteTokens! += call.usage.cacheCreationInputTokens @@ -236,7 +242,7 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[], dateKeyFn: sliceModel.cost += call.costUSD sliceModel.savingsUSD += callSavings sliceModel.inputTokens += call.usage.inputTokens - sliceModel.outputTokens += call.usage.outputTokens + sliceModel.outputTokens += billableOut sliceModel.cacheReadTokens += call.usage.cacheReadInputTokens sliceModel.cacheWriteTokens += call.usage.cacheCreationInputTokens slice.models![call.model] = sliceModel diff --git a/src/export.ts b/src/export.ts index 733dff72..961e5b8e 100644 --- a/src/export.ts +++ b/src/export.ts @@ -6,6 +6,7 @@ import { getCurrency, convertCost, roundForActiveCurrency } from './currency.js' import { dateKey } from './day-aggregator.js' import { behavioralTurnCount, isBehavioralCall } from './behavioral-weight.js' import { aggregateModelEfficiency } from './model-efficiency.js' +import { callBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js' function escCsv(s: string): string { const sanitized = /^[\t\r=+\-@]/.test(s) ? `'${s}` : s @@ -65,7 +66,7 @@ function buildDailyRows(projects: ProjectSummary[], period: string): Row[] { // so daily.csv call counts must reconcile with summary.csv. if (isBehavioralCall(call)) daily[day].calls++ daily[day].input += call.usage.inputTokens - daily[day].output += call.usage.outputTokens + daily[day].output += callBillableOutputTokens(call) daily[day].cacheRead += call.usage.cacheReadInputTokens daily[day].cacheWrite += call.usage.cacheCreationInputTokens } @@ -149,17 +150,25 @@ function buildActivityRows(projects: ProjectSummary[], period: string): Row[] { function buildModelRows(projects: ProjectSummary[], period: string): Row[] { const modelTotals: Record = {} const modelEfficiency = aggregateModelEfficiency(projects) + const ensure = (model: string) => { + if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0, savings: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } + return modelTotals[model] + } for (const project of projects) { for (const session of project.sessions) { for (const [model, d] of Object.entries(session.modelBreakdown)) { - if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0, savings: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } - modelTotals[model].calls += d.calls - modelTotals[model].cost += d.costUSD - modelTotals[model].savings += d.savingsUSD - modelTotals[model].input += d.tokens.inputTokens - modelTotals[model].output += d.tokens.outputTokens - modelTotals[model].cacheRead += d.tokens.cacheReadInputTokens ?? 0 - modelTotals[model].cacheWrite += d.tokens.cacheCreationInputTokens ?? 0 + const acc = ensure(model) + acc.calls += d.calls + acc.cost += d.costUSD + acc.savings += d.savingsUSD + acc.input += d.tokens.inputTokens + acc.cacheRead += d.tokens.cacheReadInputTokens ?? 0 + acc.cacheWrite += d.tokens.cacheCreationInputTokens ?? 0 + } + // Output must be billed per call while provider identity is still known. + // Join on the same key as parser modelBreakdown (getShortModelName), not raw call.model. + for (const [model, output] of Object.entries(sessionModelBillableOutputTokens(session))) { + ensure(model).output += output } } } diff --git a/src/hermes-session-ledger.ts b/src/hermes-session-ledger.ts new file mode 100644 index 00000000..7d176d4c --- /dev/null +++ b/src/hermes-session-ledger.ts @@ -0,0 +1,465 @@ +import { open, rename, unlink, mkdir } from 'fs/promises' +import { existsSync, readFileSync } from 'fs' +import { randomBytes } from 'crypto' +import { join } from 'path' + +import { getCodeburnCacheDir } from './cache-dir.js' +import type { CachedCall, ProviderSection } from './session-cache.js' + +// Sidecar ledger for Hermes lifetime totals that keep growing after a day is +// sealed. Contract (iamtoruk #1121 review): +// +// - Reset 150 → 0 → 40 is in contract: an all-zero (or shrinking) snapshot +// advances last-seen without a negative observation; later growth is new +// spend on the observation day. +// - Restores are out of contract: state.db restored from backup without +// wiping the ledger ⇒ regrowth is re-credited; wipe both or accept it. +// A post-reset high-water-mark guard is rejected: it would eat genuine +// 150→0→40 resets, which are treated as new spend by design. +// - Recovery horizon is the warm session-cache baseline. `seedHermesCursorsFromProviderSection` +// copies cached lifetime totals into missing cursors so growth *since the +// last warm parse* is recovered. Growth dropped *before* that parse stays +// dropped: sealed days are not re-read. This slice does not bump +// DAILY_CACHE_VERSION (one cold re-parse for every user) to recover history. + +export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v1.json' +export const HERMES_SESSION_LEDGER_VERSION = 1 as const + +export type HermesCostBasis = 'actual' | 'estimated' | 'calculated' + +export type HermesTokenTotals = { + inputTokens: number + outputTokens: number + cacheReadTokens: number + cacheWriteTokens: number + reasoningTokens: number +} + +export type HermesObservation = HermesTokenTotals & { + /** 0 = first behavioral observation; 1+ = later weight-0 observations. */ + index: number + timestamp: string + costUSD: number + costBasis: HermesCostBasis + supplementaryAccounting: boolean +} + +export type HermesLastSeen = HermesTokenTotals & { + costUSD: number + costBasis: HermesCostBasis +} + +export type HermesSessionCursor = { + profile: string + sessionId: string + lastSeen: HermesLastSeen + observations: HermesObservation[] +} + +export type HermesSessionLedger = { + version: typeof HERMES_SESSION_LEDGER_VERSION + cursors: Record> +} + +export class HermesLedgerPublicationError extends Error { + override readonly name = 'HermesLedgerPublicationError' + constructor(message: string, options?: { cause?: unknown }) { + super(message, options) + } +} + +export function isHermesLedgerPublicationError(err: unknown): boolean { + return err instanceof HermesLedgerPublicationError +} + +const ZERO_TOKENS: HermesTokenTotals = { + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + reasoningTokens: 0, +} + +let nowFn: () => Date = () => new Date() +let memory: HermesSessionLedger | null = null +let memoryDir: string | null = null + +export function setHermesLedgerNow(fn: () => Date): void { + nowFn = fn +} + +export function resetHermesLedgerNow(): void { + nowFn = () => new Date() +} + +export function hermesLedgerNow(): Date { + return nowFn() +} + +export function hermesSessionLedgerPath(): string { + return join(getCodeburnCacheDir(), HERMES_SESSION_LEDGER_FILENAME) +} + +export function emptyHermesSessionLedger(): HermesSessionLedger { + return { version: HERMES_SESSION_LEDGER_VERSION, cursors: {} } +} + +export function resetHermesSessionLedgerForTests(): void { + memory = null + memoryDir = null + nowFn = () => new Date() +} + +export function parseHermesDedupKey(key: string): { profile: string; sessionId: string; observationIndex?: number } | null { + if (!key.startsWith('hermes:')) return null + const rest = key.slice('hermes:'.length) + const obsMatch = rest.match(/^(.*):obs:(\d+)$/) + const body = obsMatch ? obsMatch[1]! : rest + const colon = body.indexOf(':') + if (colon <= 0) return null + const profile = body.slice(0, colon) + const sessionId = body.slice(colon + 1) + if (!profile || !sessionId) return null + return { + profile, + sessionId, + observationIndex: obsMatch ? Number(obsMatch[2]) : undefined, + } +} + +export function isHermesObservationKey(key: string): boolean { + return key.startsWith('hermes:') && /:obs:\d+$/.test(key) +} + +export function hermesBaselineKey(profile: string, sessionId: string): string { + return `hermes:${profile}:${sessionId}` +} + +export function hermesObservationKey(profile: string, sessionId: string, n: number): string { + return `hermes:${profile}:${sessionId}:obs:${n}` +} + +export function getHermesCursor(ledger: HermesSessionLedger, profile: string, sessionId: string): HermesSessionCursor | undefined { + return ledger.cursors[profile]?.[sessionId] +} + +export function listHermesCursorSessionIds(ledger: HermesSessionLedger, profile: string): string[] { + return Object.keys(ledger.cursors[profile] ?? {}) +} + +export function zeroHermesTokens(): HermesTokenTotals { + return { ...ZERO_TOKENS } +} + +function tokenList(t: HermesTokenTotals): number[] { + return [t.inputTokens, t.outputTokens, t.cacheReadTokens, t.cacheWriteTokens, t.reasoningTokens] +} + +function tokensGte(curr: HermesTokenTotals, last: HermesTokenTotals): boolean { + const a = tokenList(curr) + const b = tokenList(last) + return a.every((v, i) => v >= b[i]!) +} + +function tokensEqual(a: HermesTokenTotals, b: HermesTokenTotals): boolean { + return tokenList(a).every((v, i) => v === tokenList(b)[i]) +} + +function subtractTokens(curr: HermesTokenTotals, last: HermesTokenTotals): HermesTokenTotals { + return { + inputTokens: curr.inputTokens - last.inputTokens, + outputTokens: curr.outputTokens - last.outputTokens, + cacheReadTokens: curr.cacheReadTokens - last.cacheReadTokens, + cacheWriteTokens: curr.cacheWriteTokens - last.cacheWriteTokens, + reasoningTokens: curr.reasoningTokens - last.reasoningTokens, + } +} + +function hasPositiveTokenDelta(delta: HermesTokenTotals): boolean { + return tokenList(delta).some(v => v > 0) +} + +export type HermesSnapshot = { + profile: string + sessionId: string + startedAt: string + observedAt: string + tokens: HermesTokenTotals + costUSD: number + costBasis: HermesCostBasis +} + +export function applyHermesSnapshot( + existing: HermesSessionCursor | undefined, + snapshot: HermesSnapshot, +): { cursor: HermesSessionCursor; dirty: boolean } { + if (!existing) { + const first: HermesObservation = { + index: 0, + timestamp: snapshot.startedAt, + ...snapshot.tokens, + costUSD: snapshot.costUSD, + costBasis: snapshot.costBasis, + supplementaryAccounting: false, + } + return { + cursor: { + profile: snapshot.profile, + sessionId: snapshot.sessionId, + lastSeen: { + ...snapshot.tokens, + costUSD: snapshot.costUSD, + costBasis: snapshot.costBasis, + }, + observations: [first], + }, + dirty: true, + } + } + + const last = existing.lastSeen + const sameCost = snapshot.costUSD === last.costUSD && snapshot.costBasis === last.costBasis + if (tokensEqual(snapshot.tokens, last) && sameCost) { + return { cursor: existing, dirty: false } + } + + // Shrink, including all-zero: new baseline. Do not emit a negative. Keep sealed history. + if (!tokensGte(snapshot.tokens, last)) { + return { + cursor: { + ...existing, + lastSeen: { + ...snapshot.tokens, + costUSD: snapshot.costUSD, + costBasis: snapshot.costBasis, + }, + }, + dirty: true, + } + } + + const tokenDelta = subtractTokens(snapshot.tokens, last) + const positiveTokens = hasPositiveTokenDelta(tokenDelta) + const costGrew = snapshot.costUSD >= last.costUSD + const costDelta = costGrew ? snapshot.costUSD - last.costUSD : 0 + + if (!positiveTokens && costDelta === 0) { + // Tokens held (or only cost reset / basis change). Advance last-seen, no observation. + return { + cursor: { + ...existing, + lastSeen: { + ...snapshot.tokens, + costUSD: snapshot.costUSD, + costBasis: snapshot.costBasis, + }, + }, + dirty: true, + } + } + + const nextIndex = existing.observations.reduce((max, obs) => Math.max(max, obs.index), 0) + 1 + const observation: HermesObservation = { + index: nextIndex, + timestamp: snapshot.observedAt, + ...tokenDelta, + costUSD: costDelta, + costBasis: snapshot.costBasis, + supplementaryAccounting: true, + } + return { + cursor: { + ...existing, + lastSeen: { + ...snapshot.tokens, + costUSD: snapshot.costUSD, + costBasis: snapshot.costBasis, + }, + observations: [...existing.observations, observation], + }, + dirty: true, + } +} + +function putCursor(ledger: HermesSessionLedger, cursor: HermesSessionCursor): HermesSessionLedger { + return { + version: HERMES_SESSION_LEDGER_VERSION, + cursors: { + ...ledger.cursors, + [cursor.profile]: { + ...(ledger.cursors[cursor.profile] ?? {}), + [cursor.sessionId]: cursor, + }, + }, + } +} + +function isNum(v: unknown): v is number { + return typeof v === 'number' && Number.isFinite(v) +} + +function isCostBasis(v: unknown): v is HermesCostBasis { + return v === 'actual' || v === 'estimated' || v === 'calculated' +} + +function validateTokens(o: Record): o is Record & HermesTokenTotals { + return isNum(o['inputTokens']) + && isNum(o['outputTokens']) + && isNum(o['cacheReadTokens']) + && isNum(o['cacheWriteTokens']) + && isNum(o['reasoningTokens']) +} + +function validateObservation(v: unknown): v is HermesObservation { + if (!v || typeof v !== 'object') return false + const o = v as Record + return validateTokens(o) + && isNum(o['index']) + && typeof o['timestamp'] === 'string' + && isNum(o['costUSD']) + && isCostBasis(o['costBasis']) + && typeof o['supplementaryAccounting'] === 'boolean' +} + +function validateCursor(v: unknown): v is HermesSessionCursor { + if (!v || typeof v !== 'object') return false + const o = v as Record + if (typeof o['profile'] !== 'string' || typeof o['sessionId'] !== 'string') return false + if (!o['lastSeen'] || typeof o['lastSeen'] !== 'object') return false + const last = o['lastSeen'] as Record + if (!validateTokens(last) || !isNum(last['costUSD']) || !isCostBasis(last['costBasis'])) return false + if (!Array.isArray(o['observations']) || !o['observations'].every(validateObservation)) return false + return true +} + +function validateLedger(raw: unknown): raw is HermesSessionLedger { + if (!raw || typeof raw !== 'object') return false + const o = raw as Record + if (o['version'] !== HERMES_SESSION_LEDGER_VERSION) return false + if (!o['cursors'] || typeof o['cursors'] !== 'object' || Array.isArray(o['cursors'])) return false + for (const profileCursors of Object.values(o['cursors'] as Record)) { + if (!profileCursors || typeof profileCursors !== 'object' || Array.isArray(profileCursors)) return false + if (!Object.values(profileCursors as Record).every(validateCursor)) return false + } + return true +} + +function readLedgerFromDisk(): HermesSessionLedger { + const path = hermesSessionLedgerPath() + if (!existsSync(path)) return emptyHermesSessionLedger() + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8')) + if (!validateLedger(parsed)) return emptyHermesSessionLedger() + return parsed + } catch { + return emptyHermesSessionLedger() + } +} + +export function loadHermesSessionLedger(): HermesSessionLedger { + const dir = getCodeburnCacheDir() + if (memory && memoryDir === dir) return memory + const loaded = readLedgerFromDisk() + memory = loaded + memoryDir = dir + return loaded +} + +async function writeFileAtomic(finalPath: string, payload: string): Promise { + const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp` + const handle = await open(tempPath, 'w', 0o600) + try { + await handle.writeFile(payload, { encoding: 'utf-8' }) + await handle.sync() + } finally { + await handle.close() + } + try { + for (let attempt = 0; attempt < 3; attempt++) { + try { + await rename(tempPath, finalPath) + return + } catch (err) { + const code = (err as NodeJS.ErrnoException).code + if ((code !== 'EPERM' && code !== 'EBUSY') || attempt === 2) throw err + await new Promise(resolve => { setTimeout(resolve, 10 * (attempt + 1)) }) + } + } + } catch (err) { + await unlink(tempPath).catch(() => undefined) + throw err + } +} + +export async function persistHermesSessionLedger(ledger: HermesSessionLedger): Promise { + const dir = getCodeburnCacheDir() + const finalPath = join(dir, HERMES_SESSION_LEDGER_FILENAME) + try { + await mkdir(dir, { recursive: true }) + await writeFileAtomic(finalPath, JSON.stringify(ledger)) + } catch (err) { + throw new HermesLedgerPublicationError( + `failed to publish Hermes session ledger at ${finalPath}`, + { cause: err }, + ) + } + memory = ledger + memoryDir = dir +} + +export async function recordHermesSnapshot(snapshot: HermesSnapshot): Promise { + const ledger = loadHermesSessionLedger() + const existing = getHermesCursor(ledger, snapshot.profile, snapshot.sessionId) + const { cursor, dirty } = applyHermesSnapshot(existing, snapshot) + if (dirty) await persistHermesSessionLedger(putCursor(ledger, cursor)) + return cursor +} + +function cachedCallToSnapshotTokens(call: CachedCall): HermesTokenTotals { + return { + inputTokens: call.usage.inputTokens, + outputTokens: call.usage.outputTokens, + cacheReadTokens: call.usage.cacheReadInputTokens, + cacheWriteTokens: call.usage.cacheCreationInputTokens, + reasoningTokens: call.usage.reasoningTokens, + } +} + +export async function seedHermesCursorsFromProviderSection(section: ProviderSection): Promise { + // Seeds missing cursors from the already-loaded warm cache so the next + // observation is a delta against last-seen lifetime, not a dump of the + // whole session at `now`. Does not re-read sealed days: historically + // dropped growth stays dropped (see file-level contract). + const ledger = loadHermesSessionLedger() + let next = ledger + let dirty = false + for (const file of Object.values(section.files)) { + for (const turn of file.turns) { + for (const call of turn.calls) { + if (call.provider !== 'hermes') continue + const parsed = parseHermesDedupKey(call.deduplicationKey) + if (!parsed || parsed.observationIndex != null) continue + if (getHermesCursor(next, parsed.profile, parsed.sessionId)) continue + const tokens = cachedCallToSnapshotTokens(call) + const costUSD = call.costUSD ?? 0 + const costBasis: HermesCostBasis = call.isEstimated ? 'calculated' : 'actual' + const cursor: HermesSessionCursor = { + profile: parsed.profile, + sessionId: parsed.sessionId, + lastSeen: { ...tokens, costUSD, costBasis }, + observations: [{ + index: 0, + timestamp: call.timestamp, + ...tokens, + costUSD, + costBasis, + supplementaryAccounting: false, + }], + } + next = putCursor(next, cursor) + dirty = true + } + } + } + if (dirty) await persistHermesSessionLedger(next) +} diff --git a/src/main.ts b/src/main.ts index 61efb9ba..174239d4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -10,6 +10,7 @@ import { convertCost, formatCost } from './currency.js' import { renderStatusBar } from './format.js' import { toDateString } from './daily-cache.js' import { dateKey } from './day-aggregator.js' +import { sessionModelBillableOutputTokens } from './session-output.js' import { isBehavioralCall } from './behavioral-weight.js' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import type { AppliedFix } from './act/types.js' @@ -542,10 +543,17 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey: modelMap[model].savings += d.savingsUSD modelMap[model].estimatedCost += d.estimatedCostUSD ?? 0 modelMap[model].inputTokens += d.tokens.inputTokens - modelMap[model].outputTokens += d.tokens.outputTokens modelMap[model].cacheReadTokens += d.tokens.cacheReadInputTokens modelMap[model].cacheWriteTokens += d.tokens.cacheCreationInputTokens } + // Output must be billed per call while provider identity is still known. + // Join on the same key as parser modelBreakdown (getShortModelName), not raw call.model. + for (const [model, output] of Object.entries(sessionModelBillableOutputTokens(sess))) { + if (!modelMap[model]) { + modelMap[model] = { calls: 0, cost: 0, savings: 0, estimatedCost: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, baselineModel: '' } + } + modelMap[model].outputTokens += output + } } // Pull the active baseline model name out of the savings config so the // report can show what the local calls were mapped against without @@ -2442,11 +2450,16 @@ return program if (process.argv[2] === 'serve') { const { runStdioServe } = await import('./serve.js') + // Bind the REAL exit before serving. runCaptured() replaces process.exit with + // a throw for the duration of a request, and a request still in flight when + // the drain bound expires never restores it - so the exit below would throw + // instead of exiting, which is exactly the orphan this line prevents. + const hardExit = process.exit.bind(process) await runStdioServe(buildProgram) // stdin closed, so the owning app is gone. Exit outright: any handle that // outlives the transport (a watcher, a pending timer) would otherwise leave // this child running as an orphan for as long as the machine is up. - process.exit(0) + hardExit(0) } else { buildProgram().parse() } diff --git a/src/optimize.ts b/src/optimize.ts index 134424c4..77de130a 100644 --- a/src/optimize.ts +++ b/src/optimize.ts @@ -16,6 +16,7 @@ import { formatTokens } from './format.js' import { recommendModelDefault, type ModelDefaultRecommendation } from './act/model-defaults.js' import { appliedFixGlyph, formatAppliedFix, type AppliedFix } from './act/types.js' import { isUserStartedSession, userStartedProjects } from './session-population.js' +import { sessionBillableOutputTokens } from './session-output.js' import { aggregateFileChurn, buildCoachingNotes, scanUserCorrections, medianTimeToFirstEditMs, worstOneShotCategory, type ReworkedFile } from './workflow-insights.js' // ============================================================================ @@ -3030,7 +3031,7 @@ export function detectRecurringContext(openers: SessionOpener[]): WasteFinding | function sessionTokenTotal(session: ProjectSummary['sessions'][number]): number { return session.totalInputTokens - + session.totalOutputTokens + + sessionBillableOutputTokens(session) + session.totalCacheReadTokens + session.totalCacheWriteTokens } @@ -3268,9 +3269,9 @@ export function findContextBloatCandidates(projects: ProjectSummary[]): ContextB for (const session of sessions) { const inputTokens = sessionEffectiveContextTokens(session) - // Reasoning is stored separately from ordinary output, but both are - // generated tokens for this detector. Reports already use their sum. - const outputTokens = session.totalOutputTokens + session.totalReasoningTokens + // Generated tokens: exclusive providers add reasoning; inclusive ones + // already folded it into totalOutputTokens (#1078 / #1115). + const outputTokens = sessionBillableOutputTokens(session) const ratio = inputTokens / Math.max(outputTokens, 1) const currentMs = new Date(session.firstTimestamp).getTime() const gapMs = previousTimestampMs !== null ? currentMs - previousTimestampMs : null diff --git a/src/overview.ts b/src/overview.ts index 52992464..879c3b4d 100644 --- a/src/overview.ts +++ b/src/overview.ts @@ -5,6 +5,7 @@ import { homedir } from 'os' import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js' import { formatCost as baseCost, getCurrency } from './currency.js' import { findUnpricedModels, getShortModelName, unpricedModelHint } from './models.js' +import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js' import { markEstimated } from './format.js' import { dateKey } from './day-aggregator.js' import type { DailyEntry } from './daily-cache.js' @@ -140,7 +141,7 @@ export function renderOverview( byProject.set(pname, pe) for (const s of p.sessions) { inTok += s.totalInputTokens - outTok += s.totalOutputTokens + outTok += sessionBillableOutputTokens(s) cacheR += s.totalCacheReadTokens cacheW += s.totalCacheWriteTokens for (const [m, d] of Object.entries(s.modelBreakdown)) { @@ -148,7 +149,14 @@ export function renderOverview( e.cost += d.costUSD e.calls += d.calls e.estimatedCost += d.estimatedCostUSD ?? 0 - e.tokens += d.tokens.inputTokens + d.tokens.outputTokens + d.tokens.cacheReadInputTokens + d.tokens.cacheCreationInputTokens + e.tokens += d.tokens.inputTokens + d.tokens.cacheReadInputTokens + d.tokens.cacheCreationInputTokens + byModel.set(m, e) + } + // Output must be billed per call while provider identity is still known. + // Join on the same key as parser modelBreakdown (getShortModelName), not raw call.model. + for (const [m, output] of Object.entries(sessionModelBillableOutputTokens(s))) { + const e = byModel.get(m) ?? { cost: 0, calls: 0, tokens: 0, estimatedCost: 0 } + e.tokens += output byModel.set(m, e) } for (const [cat, d] of Object.entries(s.categoryBreakdown)) { @@ -163,7 +171,9 @@ export function renderOverview( for (const t of s.turns) { const day = dateKey(t.timestamp || t.assistantCalls[0]?.timestamp || '') for (const call of t.assistantCalls) { - const tk = call.usage.inputTokens + call.usage.outputTokens + call.usage.cacheReadInputTokens + call.usage.cacheCreationInputTokens + const usage = call.usage + const billableOut = callBillableOutputTokens(call) + const tk = (usage?.inputTokens ?? 0) + billableOut + (usage?.cacheReadInputTokens ?? 0) + (usage?.cacheCreationInputTokens ?? 0) const pv = byProvider.get(call.provider) ?? { cost: 0, tokens: 0 } pv.cost += call.costUSD pv.tokens += tk diff --git a/src/parser.ts b/src/parser.ts index 80842d72..205b5fd4 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -11,6 +11,11 @@ import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntig import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js' import { isSqliteBusyError } from './sqlite.js' import { getCodeburnCacheDir } from './cache-dir.js' +import { + isHermesLedgerPublicationError, + isHermesObservationKey, + seedHermesCursorsFromProviderSection, +} from './hermes-session-ledger.js' import { type CachedCall, type CachedFile, @@ -31,7 +36,7 @@ import { saveCache, sourcePathStatCandidates, } from './session-cache.js' -import { acquireCacheRefreshLock, type RefreshLockHandle } from './cache-refresh-lock.js' +import { acquireCacheRefreshLock, type RefreshLockHandle, type RefreshLockOutcome } from './cache-refresh-lock.js' import { decideParseWorkers, parseFilesInOrder, ParseWorkerPool, type ClaudeWorkerParse, type ParseJob } from './parse-workers.js' import type { CodexFullParse } from './providers/codex.js' import { dateKey } from './day-aggregator.js' @@ -2541,6 +2546,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall { ...(call.requestMultiplier != null ? { requestMultiplier: call.requestMultiplier } : {}), ...(call.compactedAt ? { compactedAt: call.compactedAt } : {}), ...(call.initiator ? { initiator: call.initiator } : {}), + ...(call.supplementaryAccounting ? { supplementaryAccounting: true } : {}), activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, @@ -2700,6 +2706,9 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall { activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, + ...(call.supplementaryAccounting || isHermesObservationKey(call.deduplicationKey) + ? { supplementaryAccounting: true } + : {}), }) } @@ -3230,6 +3239,19 @@ export async function parseProviderSources( const antigravityCacheDir = providerName === 'antigravity' ? getCodeburnCacheDir() : undefined const section = getOrCreateProviderSection(diskCache, providerName) + if (providerName === 'hermes' && !readOnly) { + try { + // Isolated migration: seed missing cursors from the already-loaded + // hermes section before any source is deleted in this parse loop. + await seedHermesCursorsFromProviderSection(section) + } catch (err) { + if (isHermesLedgerPublicationError(err)) { + deferredRetryableSource = true + } else { + throw err + } + } + } const allDiscoveredFiles = new Set() const servedSources = [...sources] @@ -3503,7 +3525,7 @@ export async function parseProviderSources( didParse = true markCacheDirty(diskCache, providerName, source.path) } catch (err) { - if (isSqliteBusyError(err)) { + if (isSqliteBusyError(err) || isHermesLedgerPublicationError(err)) { // Deferred, not failed: the cache keeps serving this source's // previous rows and the next refresh retries. But the data this // read would have added is MISSING from this parse, so the run is a @@ -4948,7 +4970,18 @@ async function parseAllSessionsInCacheScope(dateRange?: DateRange, providerFilte // Keep the snapshot loaded before acquisition: timeout/unavailable paths serve // exactly this complete snapshot and never mutate or invalidate the holder. const priorSnapshot = diskCache - const refresh = await acquireCacheRefreshLock() + // Heartbeat the WAIT too, not just the parse behind it. This is the one place + // a healthy process is deliberately idle for a long stretch, and the desktop + // and menubar watchdogs read silence as a dead child - which is how a waiter + // blocked on an abandoned lock got killed at 45s and minted the next stale + // lock (#1117). runParse arms its own keepalive; this covers the gap before it. + startProgressKeepalive() + let refresh: RefreshLockOutcome + try { + refresh = await acquireCacheRefreshLock() + } finally { + stopProgressKeepalive() + } if (refresh.outcome === 'timed-out' || refresh.outcome === 'unavailable') { return runParse(key, priorSnapshot, dateRange, providerFilter, { readOnly: true, burstSig, parseStartedAt }) } diff --git a/src/providers/codebuff.ts b/src/providers/codebuff.ts index 6ee746c1..41824107 100644 --- a/src/providers/codebuff.ts +++ b/src/providers/codebuff.ts @@ -4,7 +4,7 @@ import { homedir } from 'os' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' -import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' // Codebuff (formerly Manicode) uses a credit-based billing system. The local // chat-messages.json doesn't record per-call token counts the way Claude Code @@ -123,11 +123,15 @@ type CodebuffChatMessage = { metadata?: CodebuffMetadata } -function getCodebuffBaseDir(override?: string): string { - if (override && override.trim()) return override +// Shared by discoverSessions and probeRoots. Factory / CODEBUFF_DATA_DIR win +// as a single root; otherwise discovery walks every CHANNEL before existence +// filtering. Empty / blank factory is unset (same as #938 truthiness). +export function getCodebuffRootSet(override?: string): string[] { + if (override && override.trim()) return [override] const envPath = process.env['CODEBUFF_DATA_DIR'] - if (envPath && envPath.trim()) return envPath - return join(homedir(), '.config', 'manicode') + if (envPath && envPath.trim()) return [envPath] + const configDir = join(homedir(), '.config') + return CHANNELS.map(channel => join(configDir, channel)) } function pickNumber(...vals: Array): number | undefined { @@ -294,23 +298,9 @@ async function discoverChannel(root: string): Promise { return sources } -async function discoverSessionsInBase(baseDir: string): Promise { +async function discoverSessionsInRoots(roots: string[]): Promise { const results: SessionSource[] = [] - - // Honor an explicit override: walk only the provided directory even if it - // matches one of the channel names literally. - if (process.env['CODEBUFF_DATA_DIR'] || baseDir !== join(homedir(), '.config', 'manicode')) { - const rootStat = await stat(baseDir).catch(() => null) - if (!rootStat?.isDirectory()) return results - results.push(...await discoverChannel(baseDir)) - return results - } - - const configDir = join(homedir(), '.config') - for (const channel of CHANNELS) { - const root = join(configDir, channel) - const rootStat = await stat(root).catch(() => null) - if (!rootStat?.isDirectory()) continue + for (const root of roots) { results.push(...await discoverChannel(root)) } return results @@ -433,7 +423,7 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars } export function createCodebuffProvider(baseDir?: string): Provider { - const dir = getCodebuffBaseDir(baseDir) + const roots = getCodebuffRootSet(baseDir) return { name: 'codebuff', @@ -447,8 +437,12 @@ export function createCodebuffProvider(baseDir?: string): Provider { return toolNameMap[rawTool] ?? rawTool }, + async probeRoots(): Promise { + return roots.map(path => ({ path, label: 'chats' })) + }, + async discoverSessions(): Promise { - return discoverSessionsInBase(dir) + return discoverSessionsInRoots(roots) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/src/providers/devin.ts b/src/providers/devin.ts index b41e7bb4..c97a0472 100644 --- a/src/providers/devin.ts +++ b/src/providers/devin.ts @@ -6,6 +6,7 @@ import { getShortModelName } from "../models.js"; import { openDatabase } from "../sqlite.js"; import { readConfig } from "../config.js"; import type { + ProbeRoot, Provider, SessionParser, SessionSource, @@ -524,8 +525,24 @@ class DevinSessionParser implements SessionParser { } } -export function createDevinProvider(cliDir: string): Provider { - const sessionsDbPath = join(cliDir, DEVIN_SESSIONS_DB); +function resolveDevinCliDir(override?: string): string { + return override && override.trim() ? override : DEFAULT_DEVIN_CLI_DIR; +} + +function getDevinDiscoveryRoots(cliDir: string): { + transcriptsDir: string; + sessionsDbPath: string; +} { + return { + transcriptsDir: join(cliDir, DEVIN_TRANSCRIPTS_SUBDIR), + sessionsDbPath: join(cliDir, DEVIN_SESSIONS_DB), + }; +} + +export function createDevinProvider(cliDir?: string): Provider { + const resolvedCliDir = resolveDevinCliDir(cliDir); + const { transcriptsDir, sessionsDbPath } = + getDevinDiscoveryRoots(resolvedCliDir); let sessionMetadata: Map | null = null; const getSessionMetadata = () => { @@ -545,10 +562,16 @@ export function createDevinProvider(cliDir: string): Provider { return rawTool; }, + async probeRoots(): Promise { + return [ + { path: transcriptsDir, label: "transcripts" }, + { path: sessionsDbPath, label: "sessions.db" }, + ]; + }, + async discoverSessions(): Promise { if ((await getCostFactor()) === null) return []; - const transcriptsDir = join(cliDir, DEVIN_TRANSCRIPTS_SUBDIR); const entries = await readdir(transcriptsDir).catch(() => []); const metadata = getSessionMetadata(); const sources: SessionSource[] = []; diff --git a/src/providers/gemini.ts b/src/providers/gemini.ts index e0333f0e..cffeb9b4 100644 --- a/src/providers/gemini.ts +++ b/src/providers/gemini.ts @@ -5,7 +5,7 @@ import { homedir } from 'os' import { readSessionFile } from '../fs-utils.js' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' -import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' const toolNameMap: Record = { read_file: 'Read', @@ -213,7 +213,7 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars } } -function getGeminiTmpDir(): string { +export function getGeminiTmpDir(): string { return join(homedir(), '.gemini', 'tmp') } @@ -272,6 +272,10 @@ export function createGeminiProvider(): Provider { return toolNameMap[rawTool] ?? rawTool }, + async probeRoots(): Promise { + return [{ path: getGeminiTmpDir(), label: 'tmp' }] + }, + async discoverSessions(): Promise { return discoverSessions() }, diff --git a/src/providers/hermes.ts b/src/providers/hermes.ts index b7041f17..a8c8e80e 100644 --- a/src/providers/hermes.ts +++ b/src/providers/hermes.ts @@ -7,6 +7,20 @@ import { calculateCost, getShortModelName } from '../models.js' import { isSqliteAvailable, getSqliteLoadError, openDatabase, isSqliteBusyError, type SqliteDatabase } from '../sqlite.js' import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' import type { ToolCall } from '../types.js' +import { + getHermesCursor, + hermesBaselineKey, + hermesLedgerNow, + hermesObservationKey, + listHermesCursorSessionIds, + loadHermesSessionLedger, + recordHermesSnapshot, + zeroHermesTokens, + isHermesLedgerPublicationError, + type HermesCostBasis, + type HermesObservation, + type HermesTokenTotals, +} from '../hermes-session-ledger.js' type HermesSessionRow = { id: string @@ -430,6 +444,82 @@ function resolveHermesWorkspace( return { project: provider, provider } } +function tokenSum(tokens: HermesTokenTotals): number { + return tokens.inputTokens + tokens.outputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens + tokens.reasoningTokens +} + +function resolveHermesCost( + row: HermesSessionRow | undefined, + model: string, + tokens: HermesTokenTotals, +): { costUSD: number; costIsEstimated: boolean; costBasis: HermesCostBasis } { + const calculatedCost = calculateCost( + model, + tokens.inputTokens, + tokens.outputTokens + tokens.reasoningTokens, + tokens.cacheWriteTokens, + tokens.cacheReadTokens, + 0, + ) + // This slice treats explicit $0 as recorded. null still falls through. + if (row && row.actual_cost_usd != null) { + return { costUSD: row.actual_cost_usd, costIsEstimated: false, costBasis: 'actual' } + } + if (row && row.estimated_cost_usd != null) { + return { costUSD: row.estimated_cost_usd, costIsEstimated: false, costBasis: 'estimated' } + } + return { costUSD: calculatedCost, costIsEstimated: true, costBasis: 'calculated' } +} + +function observationToCall( + observation: HermesObservation, + args: { + profile: string + sessionId: string + model: string + tools: string[] + bashCommands: string[] + toolSequence: ToolCall[][] + userMessage: string + project: string + projectPath?: string + prLinks?: string[] + costIsEstimated: boolean + }, +): ParsedProviderCall { + const later = observation.index > 0 + return { + provider: 'hermes', + model: args.model, + inputTokens: observation.inputTokens, + outputTokens: observation.outputTokens, + cacheCreationInputTokens: observation.cacheWriteTokens, + cacheReadInputTokens: observation.cacheReadTokens, + cachedInputTokens: observation.cacheReadTokens, + reasoningTokens: observation.reasoningTokens, + webSearchRequests: 0, + costUSD: observation.costUSD, + // Later observations keep the stored basis: calculated stays estimated; + // provider-recorded actual/estimated keep main's measured behavior. + costIsEstimated: later ? observation.costBasis === 'calculated' : args.costIsEstimated, + tools: later ? [] : args.tools, + bashCommands: later ? [] : args.bashCommands, + timestamp: observation.timestamp, + speed: 'standard', + deduplicationKey: later + ? hermesObservationKey(args.profile, args.sessionId, observation.index) + : hermesBaselineKey(args.profile, args.sessionId), + turnId: later ? `${args.sessionId}:obs:${observation.index}` : `${args.sessionId}:session`, + toolSequence: later || args.toolSequence.length === 0 ? undefined : args.toolSequence, + userMessage: later ? '' : args.userMessage, + sessionId: args.sessionId, + project: args.project, + projectPath: args.projectPath, + ...(later || !args.prLinks?.length ? {} : { prLinks: args.prLinks }), + ...(later ? { supplementaryAccounting: true } : {}), + } +} + function inferProject(messages: HermesMessageRow[], fallback: string): { project: string; projectPath?: string } { const cwdPattern = /^Current working directory:\s*([a-zA-Z]:\\[^\r\n`"]+|\/[^\r\n`"\\]+)/m for (const msg of messages) { @@ -471,11 +561,25 @@ async function discoverFromDb(dbPath: string, profile: string): Promise ({ + const sources = rows.map(row => ({ path: encodeSourcePath(dbPath, row.id), project: displayProjectForProfile(profile), - provider: 'hermes', + provider: 'hermes' as const, })) + // After the >0 filter, reconcile every already-ledgered identity against + // this state.db so an all-zero (or missing) row still reaches the cursor. + // Without this, 150→0 is invisible and the later 40 is treated as a shrink. + const discoveredIds = new Set(rows.map(row => row.id)) + const ledger = loadHermesSessionLedger() + for (const sessionId of listHermesCursorSessionIds(ledger, profile)) { + if (discoveredIds.has(sessionId)) continue + sources.push({ + path: encodeSourcePath(dbPath, sessionId), + project: displayProjectForProfile(profile), + provider: 'hermes', + }) + } + return sources } catch (err) { if (isSqliteBusyError(err)) throw err process.stderr.write(`codeburn: error querying Hermes database: ${err instanceof Error ? err.message : err}\n`) @@ -505,7 +609,9 @@ function createParser(source: SessionSource, seenKeys: Set, hermesHome: return } - let result: ParsedProviderCall | undefined + let result: { + calls: ParsedProviderCall[] + } | undefined try { if (!validateSchema(db)) return const columns = getSessionColumns(db) @@ -533,7 +639,39 @@ function createParser(source: SessionSource, seenKeys: Set, hermesHome: [decoded.sessionId], ) const row = rows[0] - if (!row) return + const ledger = loadHermesSessionLedger() + const existingCursor = getHermesCursor(ledger, profile, decoded.sessionId) + if (!row) { + if (!existingCursor) return + const baselineKey = hermesBaselineKey(profile, decoded.sessionId) + if (seenKeys.has(baselineKey)) return + seenKeys.add(baselineKey) + const cursor = await recordHermesSnapshot({ + profile, + sessionId: decoded.sessionId, + startedAt: existingCursor.observations[0]?.timestamp || hermesLedgerNow().toISOString(), + observedAt: hermesLedgerNow().toISOString(), + tokens: zeroHermesTokens(), + costUSD: 0, + costBasis: 'calculated', + }) + for (const observation of cursor.observations) { + if (observation.index > 0) seenKeys.add(hermesObservationKey(profile, decoded.sessionId, observation.index)) + } + result = { + calls: cursor.observations.map(observation => observationToCall(observation, { + profile, + sessionId: decoded.sessionId, + model: 'unknown', + tools: [], + bashCommands: [], + toolSequence: [], + userMessage: '', + project: displayProjectForProfile(profile), + costIsEstimated: false, + })), + } + } else { const messageColumns = getMessageColumns(db) const orderColumns = ['timestamp', 'id'].filter(name => messageColumns.has(name)) @@ -556,15 +694,22 @@ function createParser(source: SessionSource, seenKeys: Set, hermesHome: const cacheReadTokens = row.cache_read_tokens ?? 0 const cacheWriteTokens = row.cache_write_tokens ?? 0 const reasoningTokens = row.reasoning_tokens ?? 0 - if (inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + reasoningTokens === 0) return + const tokens: HermesTokenTotals = { + inputTokens, + outputTokens, + cacheReadTokens, + cacheWriteTokens, + reasoningTokens, + } + if (tokenSum(tokens) === 0 && !existingCursor) return const model = row.model ?? 'unknown' const { tools, toolSequence, bashCommands } = collectTools(messages) const workspace = resolveHermesWorkspace(row, messages) const timestamp = parseTimestamp(row.started_at) - const dedupKey = `hermes:${profile}:${row.id}` - if (seenKeys.has(dedupKey)) return - seenKeys.add(dedupKey) + const baselineKey = hermesBaselineKey(profile, row.id) + if (seenKeys.has(baselineKey)) return + seenKeys.add(baselineKey) const identity = workspace.projectPath ? githubOwnerRepoFromRoot(workspace.projectPath) @@ -576,62 +721,50 @@ function createParser(source: SessionSource, seenKeys: Set, hermesHome: identity, ) - // Hermes bills reasoning tokens at the output rate (same as Gemini). - // The LiteLLM model table is used as a fallback when Hermes has not - // stored an actual or estimated cost for the session. - const calculatedCost = calculateCost( - model, - inputTokens, - outputTokens + reasoningTokens, - cacheWriteTokens, - cacheReadTokens, - 0, - ) - const recordedCost = - (row.actual_cost_usd ?? 0) > 0 ? row.actual_cost_usd! - : (row.estimated_cost_usd ?? 0) > 0 ? row.estimated_cost_usd! - : null - // When Hermes stored no cost (e.g. subscription-billed sessions), the - // figure is our LiteLLM-priced estimate from the session token totals. - const costUSD = recordedCost ?? calculatedCost - const costIsEstimated = recordedCost === null - - result = { - provider: workspace.provider, - model, - inputTokens, - outputTokens, - cacheCreationInputTokens: cacheWriteTokens, - cacheReadInputTokens: cacheReadTokens, - cachedInputTokens: cacheReadTokens, - reasoningTokens, - webSearchRequests: 0, - costUSD, - costIsEstimated, - tools, - bashCommands, - timestamp, - speed: 'standard', - deduplicationKey: dedupKey, - turnId: `${row.id}:session`, - toolSequence: toolSequence.length > 0 ? toolSequence : undefined, - userMessage: firstUserMessage(messages), + const cost = resolveHermesCost(row, model, tokens) + const cursor = await recordHermesSnapshot({ + profile, sessionId: row.id, - project: workspace.project, - projectPath: workspace.projectPath, - ...(prLinks.length > 0 ? { prLinks } : {}), + startedAt: timestamp || hermesLedgerNow().toISOString(), + observedAt: hermesLedgerNow().toISOString(), + tokens, + costUSD: cost.costUSD, + costBasis: cost.costBasis, + }) + for (const observation of cursor.observations) { + if (observation.index > 0) seenKeys.add(hermesObservationKey(profile, row.id, observation.index)) + } + result = { + calls: cursor.observations.map(observation => observationToCall(observation, { + profile, + sessionId: row.id, + model, + tools, + bashCommands, + toolSequence, + userMessage: firstUserMessage(messages), + project: workspace.project, + projectPath: workspace.projectPath, + prLinks, + costIsEstimated: cost.costIsEstimated, + })), + } } } catch (err) { - // A transient lock on the live state.db must propagate so the caller - // retries, not get swallowed into an empty (negatively cached) result. - if (isSqliteBusyError(err)) throw err - process.stderr.write(`codeburn: error querying Hermes database: ${err instanceof Error ? err.message : err}\n`) + // A transient lock on the live state.db, or a ledger publication + // failure, must propagate so the caller retries — not get swallowed + // into an empty (negatively cached) result. + if (isSqliteBusyError(err) || isHermesLedgerPublicationError(err)) throw err + const detail = err instanceof Error ? err.message : err + process.stderr.write(`codeburn: error querying Hermes database: ${detail}\n`) return } finally { db.close() } - if (result) yield result + if (result) { + for (const call of result.calls) yield call + } }, } } diff --git a/src/providers/kiro.ts b/src/providers/kiro.ts index 4e0308d9..b5adc916 100644 --- a/src/providers/kiro.ts +++ b/src/providers/kiro.ts @@ -9,7 +9,7 @@ import { flatSlice, flatString } from '../content-utils.js' import { calculateCost } from '../models.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' -import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' // Kiro bills in credits: individual plans are $20/mo for 1,000 credits and // overage is billed at $0.04 per additional credit. We price credits at the @@ -925,7 +925,10 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars // --- Discovery --- -function getKiroAgentDir(override?: string): string[] { +// Pre-filter candidate list shared by probeRoots and discovery. Must not +// existsSync-filter: Linux discovery still trims in getKiroAgentDir, but +// doctor has to report missing defaults. Empty / blank override is unset. +export function getKiroAgentDirCandidates(override?: string): string[] { if (override) return [override] if (process.platform === 'darwin') { return [join(homedir(), 'Library', 'Application Support', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent')] @@ -933,17 +936,21 @@ function getKiroAgentDir(override?: string): string[] { if (process.platform === 'win32') { return [join(homedir(), 'AppData', 'Roaming', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent')] } + return [ + join(homedir(), '.kiro-server', 'data', 'User', 'globalStorage', 'kiro.kiroagent'), + join(homedir(), '.config', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent'), + ] +} + +function getKiroAgentDir(override?: string): string[] { + const candidates = getKiroAgentDirCandidates(override) + if (override || process.platform !== 'linux') return candidates // On Linux, scan both ~/.kiro-server/data/... (remote dev boxes) and // ~/.config/Kiro/... (local installs). Both can have data simultaneously // if the user switches between local and remote, or if .kiro-server exists // but is stale while .config/Kiro has current sessions. - const paths: string[] = [] - const kiroServer = join(homedir(), '.kiro-server', 'data', 'User', 'globalStorage', 'kiro.kiroagent') - const kiroConfig = join(homedir(), '.config', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent') - if (existsSync(kiroServer)) paths.push(kiroServer) - if (existsSync(kiroConfig)) paths.push(kiroConfig) - // Fallback to config path if neither exists (will just find nothing) - return paths.length > 0 ? paths : [kiroConfig] + const existing = candidates.filter(p => existsSync(p)) + return existing.length > 0 ? existing : [candidates[candidates.length - 1]!] } function getKiroWorkspaceStorageDir(override?: string): string { @@ -986,26 +993,29 @@ async function resolveWorkspaceProject(agentDir: string, workspaceStorageDir: st return workspaceHash } -async function discoverSessions(agentDir: string, workspaceStorageDir: string, cliSessionsDir: string): Promise { +async function discoverSessions(agentDir: string, workspaceStorageDir: string, cliSessionsDir: string | undefined): Promise { const sources: SessionSource[] = [] // --- Kiro CLI sessions (~/.kiro/sessions/cli/) --- - try { - const cliEntries = await readdir(cliSessionsDir, { withFileTypes: true }) - for (const entry of cliEntries) { - if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue - const jsonlPath = join(cliSessionsDir, entry.name) - // Derive project from companion .json - const metaPath = jsonlPath.replace(/\.jsonl$/, '.json') - let project = 'kiro-cli' - try { - const raw = await readFile(metaPath, 'utf-8') - const meta = JSON.parse(raw) as { cwd?: string } - if (meta.cwd) project = basename(meta.cwd) - } catch {} - sources.push({ path: jsonlPath, project, provider: 'kiro' }) - } - } catch {} + // Empty CLI is skipped (do not readdir '' or '.'). Same skip in probeRoots. + if (cliSessionsDir) { + try { + const cliEntries = await readdir(cliSessionsDir, { withFileTypes: true }) + for (const entry of cliEntries) { + if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue + const jsonlPath = join(cliSessionsDir, entry.name) + // Derive project from companion .json + const metaPath = jsonlPath.replace(/\.jsonl$/, '.json') + let project = 'kiro-cli' + try { + const raw = await readFile(metaPath, 'utf-8') + const meta = JSON.parse(raw) as { cwd?: string } + if (meta.cwd) project = basename(meta.cwd) + } catch {} + sources.push({ path: jsonlPath, project, provider: 'kiro' }) + } + } catch {} + } // --- Kiro IDE sessions --- let workspaceDirs: string[] @@ -1123,18 +1133,24 @@ async function discoverV2Sessions(sessionsRoot: string): Promise/sess_*/, a sibling of the - // CLI store (.../sessions/cli). Derive the root from cliDir ONLY when cliDir was - // itself explicit (default path or cliSessionsDirOverride). When only - // agentDirOverride is set (tests), the derived cliDir parent would point at an - // arbitrary directory (e.g. the system tmpdir) — scan nothing in that case. - const v2Root = v2SessionsRootOverride ?? - (cliSessionsDirOverride ? dirname(cliSessionsDirOverride) : - agentDirOverride ? undefined : dirname(cliDir)) + // CLI store (.../sessions/cli). Derive the root from an explicit CLI override + // or the default CLI parent. Empty CLI does not drop default v2; empty v2 + // is skipped on its own. When only agentDirOverride is set (tests), do not + // derive v2 from the test tmpdir. + const v2Root = v2SessionsRootOverride === '' + ? undefined + : v2SessionsRootOverride ?? + (cliSessionsDirOverride ? dirname(cliSessionsDirOverride) : + agentDirOverride ? undefined : dirname(defaultCliDir)) return { name: 'kiro', @@ -1153,6 +1169,16 @@ export function createKiroProvider(agentDirOverride?: string, workspaceStorageDi return toolNameMap[rawTool] ?? rawTool }, + async probeRoots(): Promise { + const roots: ProbeRoot[] = [ + ...agentCandidates.map(path => ({ path, label: 'agent' })), + { path: wsDir, label: 'workspace' }, + ] + if (cliDir) roots.push({ path: cliDir, label: 'cli' }) + if (v2Root) roots.push({ path: v2Root, label: 'v2' }) + return roots + }, + async discoverSessions(): Promise { const allSources: SessionSource[] = [] for (const agentDir of agentDirs) { diff --git a/src/providers/mistral-vibe.ts b/src/providers/mistral-vibe.ts index 158a53a4..23c3667f 100644 --- a/src/providers/mistral-vibe.ts +++ b/src/providers/mistral-vibe.ts @@ -5,7 +5,7 @@ import { homedir } from 'os' import { readSessionFile, readSessionLines } from '../fs-utils.js' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' -import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' import { safeNumber } from '../parser.js' const METADATA_FILENAME = 'meta.json' @@ -82,7 +82,7 @@ type VibeMessage = { tool_calls?: VibeToolCall[] | null } -function getMistralVibeSessionsDir(override?: string): string { +export function getMistralVibeSessionsDir(override?: string): string { if (override) return override const configuredHome = process.env['VIBE_HOME'] const vibeHome = configuredHome ? expandHome(configuredHome) : join(homedir(), '.vibe') @@ -409,6 +409,10 @@ export function createMistralVibeProvider(sessionsDir?: string): Provider { return toolNameMap[rawTool] ?? rawTool }, + async probeRoots(): Promise { + return [{ path: dir, label: 'sessions' }] + }, + async discoverSessions(): Promise { const dirs = await discoverSessionDirs(dir) const sources: SessionSource[] = [] diff --git a/src/providers/types.ts b/src/providers/types.ts index b9671d9d..45e5456b 100644 --- a/src/providers/types.ts +++ b/src/providers/types.ts @@ -82,6 +82,9 @@ export type ParsedProviderCall = { projectPath?: string // GitHub PR URLs observed in this call's transcript (Hermes and similar). prLinks?: string[] + // Hermes observation-time deltas persist this flag (and reconstruct it at + // serve time from a `:obs:` key). Copilot still assigns it only at serve time. + supplementaryAccounting?: boolean // Exact provider-recorded cwd, kept separately because projectPath may later // canonicalize a linked worktree to its main repository. workingDirectory?: string diff --git a/src/serve.ts b/src/serve.ts index a55b1b55..8ea073ca 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -643,7 +643,15 @@ export async function runStdioServe(buildProgram: () => Command): Promise let drainTimer: ReturnType | undefined await Promise.race([queue, new Promise(resolve => { drainTimer = setTimeout(resolve, drainMs) })]) clearTimeout(drainTimer) - await watcherSetup + // 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 | undefined + await Promise.race([ + watcherSetup.catch(() => undefined), + new Promise(resolve => { watcherTimer = setTimeout(resolve, drainMs) }), + ]) + clearTimeout(watcherTimer) rootReuseValidation = null try { watcherLifecycle.resetValidator?.() diff --git a/src/session-cache.ts b/src/session-cache.ts index 30047f2e..07a9bb62 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -65,6 +65,10 @@ export type CachedCall = { // Copilot session-store rows only: the store's `initiator` label when // present. See ParsedProviderCall.initiator. initiator?: string + // Hermes observation-time deltas persist this so a warm read does not + // depend on the `:obs:` key regex alone. Copilot still assigns the flag + // at serve time and does not persist it. + supplementaryAccounting?: boolean } export type CachedTurn = { @@ -625,6 +629,7 @@ function validateCall(c: unknown): c is CachedCall { && isOptionalBool(o['userModified']) && isOptionalNum(o['toolErrors']) && isOptionalNum(o['editFailed']) + && isOptionalBool(o['supplementaryAccounting']) && validateUsage(o['usage']) } diff --git a/src/session-output.ts b/src/session-output.ts new file mode 100644 index 00000000..133c042d --- /dev/null +++ b/src/session-output.ts @@ -0,0 +1,112 @@ +import { billableOutputTokens, getShortModelName } from './models.js' +import type { SessionSummary } from './types.js' + +type UsageLike = { + outputTokens?: number + reasoningTokens?: number +} + +type CallLike = { + provider?: string + model?: string + usage?: UsageLike +} + +/** Same key the parser uses for non-Devin `modelBreakdown` buckets. */ +export function modelBreakdownKey(call: { provider?: string; model?: string }): string | undefined { + if (!call.model) return undefined + return call.provider === 'devin' ? call.model : getShortModelName(call.model) +} + +/** + * Prefer a key that already exists on this session's modelBreakdown. + * Parser sessions are keyed by getShortModelName. Fixtures and leftover + * summaries may still use the raw id. Inventing the other spelling + * creates a $0 / 0-call orphan that findUnpricedModels flags as Unpriced. + */ +export function resolveModelBreakdownKey( + call: { provider?: string; model?: string }, + breakdown: Record | undefined, +): string | undefined { + const derived = modelBreakdownKey(call) + if (derived && breakdown && Object.hasOwn(breakdown, derived)) return derived + if (call.model && breakdown && Object.hasOwn(breakdown, call.model)) return call.model + return derived ?? call.model +} + +/** + * Per-model displayed output, keyed like this session's `modelBreakdown`. + * Call usage wins while provider identity is known. Aggregate-only / + * stub sessions fall back to each existing bucket so a finite + * sessionBillableOutputTokens cannot leave model Output Tokens at 0. + */ +export function sessionModelBillableOutputTokens(session: SessionSummary): Record { + const breakdown = session.modelBreakdown ?? {} + const out: Record = {} + let sawUsage = false + for (const turn of session.turns ?? []) { + for (const call of turn.assistantCalls ?? []) { + if (!call.usage) continue + sawUsage = true + const key = resolveModelBreakdownKey(call, breakdown) + if (!key) continue + out[key] = (out[key] ?? 0) + callBillableOutputTokens(call) + } + } + if (sawUsage) return out + const provider = inferSessionProvider(session) + for (const [model, d] of Object.entries(session.modelBreakdown ?? {})) { + out[model] = billableOutputTokens( + provider, + d.tokens?.outputTokens ?? 0, + d.tokens?.reasoningTokens ?? 0, + ) + } + return out +} + +/** First on-call provider, then a model-name fallback. Sessions are usually one provider. */ +export function inferSessionProvider(session: SessionSummary): string { + for (const turn of session.turns ?? []) { + const provider = turn.assistantCalls?.[0]?.provider + if (provider) return provider + } + + const models = Object.keys(session.modelBreakdown ?? {}) + const model = models[0]?.toLowerCase() ?? '' + if (model.startsWith('claude')) return 'claude' + if (model.startsWith('gpt-') || model.startsWith('o1') || model.startsWith('o3') || model.startsWith('o4')) return 'codex' + if (model.startsWith('gemini')) return 'gemini' + if (model.includes('/')) return model.split('/', 1)[0] || 'unknown' + return 'unknown' +} + +/** Per-call displayed output. Missing usage/fields are 0 so aggregate-only and stub calls cannot crash. */ +export function callBillableOutputTokens(call: CallLike): number { + const usage = call.usage + if (!usage) return 0 + return billableOutputTokens( + call.provider ?? 'unknown', + usage.outputTokens ?? 0, + usage.reasoningTokens ?? 0, + ) +} + +/** Display/report output: exclusive providers add reasoning; inclusive ones do not. */ +export function sessionBillableOutputTokens(session: SessionSummary): number { + let fromCalls = 0 + let sawUsage = false + for (const turn of session.turns ?? []) { + for (const call of turn.assistantCalls ?? []) { + if (!call.usage) continue + sawUsage = true + fromCalls += callBillableOutputTokens(call) + } + } + if (sawUsage) return fromCalls + return billableOutputTokens( + inferSessionProvider(session), + session.totalOutputTokens ?? 0, + session.totalReasoningTokens ?? 0, + ) +} diff --git a/src/sessions-report.ts b/src/sessions-report.ts index 84fb5a98..cba88b88 100644 --- a/src/sessions-report.ts +++ b/src/sessions-report.ts @@ -1,5 +1,6 @@ import { behavioralCallCount, behavioralTurnCount } from './behavioral-weight.js' import { getShortModelName } from './models.js' +import { inferSessionProvider, sessionBillableOutputTokens } from './session-output.js' import { CATEGORY_LABELS } from './types.js' import type { ProjectSummary, SessionSummary, TaskCategory } from './types.js' @@ -23,21 +24,6 @@ export type SessionRow = { durationMs: number } -function inferProvider(session: SessionSummary): string { - for (const turn of session.turns) { - const provider = turn.assistantCalls[0]?.provider - if (provider) return provider - } - - const models = Object.keys(session.modelBreakdown) - const model = models[0]?.toLowerCase() ?? '' - if (model.startsWith('claude')) return 'claude' - if (model.startsWith('gpt-') || model.startsWith('o1') || model.startsWith('o3') || model.startsWith('o4')) return 'codex' - if (model.startsWith('gemini')) return 'gemini' - if (model.includes('/')) return model.split('/', 1)[0] || 'unknown' - return 'unknown' -} - function durationMs(startedAt: string, endedAt: string): number { const duration = new Date(endedAt).getTime() - new Date(startedAt).getTime() return Number.isFinite(duration) ? duration : 0 @@ -48,14 +34,14 @@ export function aggregateSessions(projects: ProjectSummary[]): SessionRow[] { sessionId: session.sessionId, title: session.title ?? '', project: session.project || project.project, - provider: inferProvider(session), + provider: inferSessionProvider(session), models: Object.keys(session.modelBreakdown), cost: session.totalCostUSD, savingsUSD: session.totalSavingsUSD, calls: session.apiCalls, turns: behavioralTurnCount(session.turns), inputTokens: session.totalInputTokens, - outputTokens: session.totalOutputTokens, + outputTokens: sessionBillableOutputTokens(session), cacheReadTokens: session.totalCacheReadTokens, cacheWriteTokens: session.totalCacheWriteTokens, startedAt: session.firstTimestamp, @@ -374,7 +360,7 @@ const KEY_SEP = String.fromCharCode(0) function linkageProvider(session: SessionSummary): string { if (session.parentSessionId || session.agentSpawnLinks || session.spawnPrSets) return 'claude' - return inferProvider(session) + return inferSessionProvider(session) } function providerSessionKey(session: SessionSummary): string { return `${linkageProvider(session)}${KEY_SEP}${session.sessionId}` diff --git a/src/types.ts b/src/types.ts index 34451ac1..f869fd65 100644 --- a/src/types.ts +++ b/src/types.ts @@ -158,9 +158,10 @@ export type ParsedApiCall = { toolWaitMs?: number /// Supplementary accounting: this call's tokens/cost are real but the call is /// not a distinct behavioral request (copilot shutdown rollups and store rows - /// that pair with an already-counted per-turn call). Aggregates keep its - /// tokens/cost but skip it in apiCalls / model-call / turn counts. Transient: - /// assigned at serve time, never cached. + /// that pair with an already-counted per-turn call; Hermes observation-time + /// deltas). Aggregates keep its tokens/cost but skip it in apiCalls / + /// model-call / turn counts. Hermes deltas persist the flag on CachedCall; + /// Copilot remains serve-time / never cached. supplementaryAccounting?: boolean } diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index d45f8f4b..a8fcb009 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -13,6 +13,7 @@ import { aggregateModels } from './models-report.js' import { scanUserCorrections, medianTimeToFirstEditMs, aggregateFileChurn, computePricingCoverage } from './workflow-insights.js' import { buildPrAttribution, aggregateByBranch } from './sessions-report.js' import { scanAndDetect } from './optimize.js' +import { callBillableOutputTokens, sessionBillableOutputTokens } from './session-output.js' import { getDaysInRange, ensureCacheHydrated, emptyCache, BACKFILL_DAYS, toDateString, type DailyCache, type DailyEntry, type ProjectDayStats, type ProviderDaySlice } from './daily-cache.js' import { buildGranularHistory } from './granular-history.js' @@ -27,7 +28,7 @@ export function buildPeriodData(label: string, projects: ProjectSummary[]): Peri for (const sess of sessions) { inputTokens += sess.totalInputTokens - outputTokens += sess.totalOutputTokens + outputTokens += sessionBillableOutputTokens(sess) cacheReadTokens += sess.totalCacheReadTokens cacheWriteTokens += sess.totalCacheWriteTokens for (const [cat, d] of Object.entries(sess.categoryBreakdown)) { @@ -769,7 +770,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: savingsUSD: s.totalSavingsUSD, calls: s.apiCalls, inputTokens: s.totalInputTokens, - outputTokens: s.totalOutputTokens, + outputTokens: sessionBillableOutputTokens(s), date: s.firstTimestamp?.split('T')[0] ?? '', models: Object.entries(s.modelBreakdown) .map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD })) @@ -946,7 +947,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: acc.savingsUSD += call.savingsUSD acc.baselineModel = acc.baselineModel || (call.savingsBaselineModel ?? '') acc.inputTokens += call.usage.inputTokens - acc.outputTokens += call.usage.outputTokens + acc.outputTokens += callBillableOutputTokens(call) savingsByModel.set(modelKey, acc) const provAcc = savingsByProvider.get(call.provider) ?? { calls: 0, savingsUSD: 0 } provAcc.calls += callWeight diff --git a/tests/billable-output-1115.test.ts b/tests/billable-output-1115.test.ts new file mode 100644 index 00000000..57c9c90e --- /dev/null +++ b/tests/billable-output-1115.test.ts @@ -0,0 +1,299 @@ +import { mkdtemp, readFile, rm } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { describe, expect, it } from 'vitest' + +import { aggregateModelStats, computeComparison } from '../src/compare-stats.js' +import { aggregateProjectsIntoDays } from '../src/day-aggregator.js' +import { exportJson } from '../src/export.js' +import { billableOutputTokens, getShortModelName } from '../src/models.js' +import { findContextBloatCandidates } from '../src/optimize.js' +import { renderOverview } from '../src/overview.js' +import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from '../src/session-output.js' +import { aggregateSessions } from '../src/sessions-report.js' +import { buildPeriodData } from '../src/usage-aggregator.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' + +function makeCall(provider: string, outputTokens: number, reasoningTokens: number) { + return { + provider, + model: provider === 'codex' ? 'gpt-5.4' : 'grok-4', + usage: { + inputTokens: 0, + outputTokens, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens, + webSearchRequests: 0, + }, + costUSD: 0, + tools: [], + mcpTools: [], + skills: [], + hasAgentSpawn: false, + hasPlanMode: false, + speed: 'standard' as const, + timestamp: '2026-08-01T12:00:00Z', + bashCommands: [], + deduplicationKey: `${provider}-${outputTokens}-${reasoningTokens}`, + savingsUSD: 1, + savingsBaselineModel: 'gpt-4o', + } +} + +function makeSession(provider: string, outputTokens: number, reasoningTokens: number): SessionSummary { + const call = makeCall(provider, outputTokens, reasoningTokens) + return { + sessionId: `${provider}-s`, + project: 'p', + firstTimestamp: call.timestamp, + lastTimestamp: call.timestamp, + totalCostUSD: 0, + totalSavingsUSD: 0, + totalInputTokens: 0, + totalOutputTokens: outputTokens, + totalReasoningTokens: reasoningTokens, + totalCacheReadTokens: 0, + totalCacheWriteTokens: 0, + apiCalls: 1, + turns: [{ + userMessage: 'x', + timestamp: call.timestamp, + sessionId: `${provider}-s`, + category: 'coding', + retries: 0, + hasEdits: true, + assistantCalls: [call], + }], + modelBreakdown: { + [getShortModelName(call.model)]: { + calls: 1, + costUSD: 0, + savingsUSD: 0, + tokens: call.usage, + }, + }, + toolBreakdown: {}, + mcpBreakdown: {}, + bashBreakdown: {}, + categoryBreakdown: {} as never, + skillBreakdown: {} as never, + } as unknown as SessionSummary +} + +function makeProject(session: SessionSummary): ProjectSummary { + return { + project: 'p', + projectPath: '/p', + totalCostUSD: 0, + totalSavingsUSD: 0, + totalProxiedCostUSD: 0, + totalApiCalls: 1, + sessions: [session], + } as ProjectSummary +} + +describe('#1115 billableOutputTokens on report/optimize totals', () => { + it('exclusive grok: 10 output + 3 reasoning = 13', () => { + expect(billableOutputTokens('grok', 10, 3)).toBe(13) + expect(sessionBillableOutputTokens(makeSession('grok', 10, 3))).toBe(13) + }) + + it('inclusive codex: 10 output already contains reasoning = 10', () => { + expect(billableOutputTokens('codex', 10, 3)).toBe(10) + expect(sessionBillableOutputTokens(makeSession('codex', 10, 3))).toBe(10) + }) + + it('day-aggregator uses billable output per call', () => { + const grokDays = aggregateProjectsIntoDays([makeProject(makeSession('grok', 10, 3))]) + expect(grokDays[0]!.outputTokens).toBe(13) + expect(grokDays[0]!.providers.grok!.outputTokens).toBe(13) + + const codexDays = aggregateProjectsIntoDays([makeProject(makeSession('codex', 10, 3))]) + expect(codexDays[0]!.outputTokens).toBe(10) + expect(codexDays[0]!.providers.codex!.outputTokens).toBe(10) + }) + + it('sessions report and period data match the helper', () => { + const grok = makeProject(makeSession('grok', 10, 3)) + const codex = makeProject(makeSession('codex', 10, 3)) + expect(aggregateSessions([grok])[0]!.outputTokens).toBe(13) + expect(aggregateSessions([codex])[0]!.outputTokens).toBe(10) + expect(buildPeriodData('t', [grok]).outputTokens).toBe(13) + expect(buildPeriodData('t', [codex]).outputTokens).toBe(10) + }) + + it('optimize context-bloat denominator does not double-count inclusive reasoning', () => { + const inclusive = makeSession('codex', 100_000, 50_000) + inclusive.totalInputTokens = 2_000_000 + const exclusive = makeSession('grok', 100_000, 50_000) + exclusive.totalInputTokens = 2_000_000 + + const inc = findContextBloatCandidates([makeProject(inclusive)]) + const exc = findContextBloatCandidates([makeProject(exclusive)]) + // ratio = input / billableOut. Inclusive 2e6/1e5 = 20; exclusive 2e6/1.5e5 ≈ 13.3 + // Both clear CONTEXT_BLOAT_MIN_RATIO if that threshold is below 13. + if (inc.length && exc.length) { + expect(inc[0]!.growthRatio === null || typeof inc[0]!.growthRatio === 'number').toBe(true) + } + // Direct contract: helper is what the detector uses. + expect(sessionBillableOutputTokens(inclusive)).toBe(100_000) + expect(sessionBillableOutputTokens(exclusive)).toBe(150_000) + }) + + it('compare-stats Output tok/call uses per-call billable output', () => { + const grok = aggregateModelStats([makeProject(makeSession('grok', 10, 3))]) + const codex = aggregateModelStats([makeProject(makeSession('codex', 10, 3))]) + expect(grok[0]!.outputTokens).toBe(13) + expect(codex[0]!.outputTokens).toBe(10) + const rows = computeComparison(grok[0]!, codex[0]!) + const outputRow = rows.find(r => r.label === 'Output tok / call')! + expect(outputRow.valueA).toBe(13) + expect(outputRow.valueB).toBe(10) + }) + + it('export daily/model Output Tokens use per-call billable output', async () => { + const dir = await mkdtemp(join(tmpdir(), 'cb-1115-export-')) + try { + const path = await exportJson([ + { label: '30 Days', projects: [makeProject(makeSession('grok', 10, 3)), makeProject(makeSession('codex', 10, 3))] }, + ], join(dir, 'out.json')) + const data = JSON.parse(await readFile(path, 'utf-8')) as { + periods: Array<{ daily: Array<{ 'Output Tokens': number }>; models: Array<{ Model: string; 'Output Tokens': number }> }> + records: Array<{ outputTokens: number; reasoningTokens: number }> + } + expect(data.periods[0]!.daily[0]!['Output Tokens']).toBe(23) + const grokRow = data.periods[0]!.models.find(r => r.Model === getShortModelName('grok-4'))! + const codexRow = data.periods[0]!.models.find(r => r.Model === getShortModelName('gpt-5.4'))! + expect(grokRow['Output Tokens']).toBe(13) + expect(codexRow['Output Tokens']).toBe(10) + // Record-level export stays raw columns, not the billable sum. + expect(data.records.map(r => r.outputTokens).sort()).toEqual([10, 10]) + expect(data.records.map(r => r.reasoningTokens).sort()).toEqual([3, 3]) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('overview Top-model / By-tool / day totals use per-call billable output', () => { + const out = renderOverview( + [makeProject(makeSession('grok', 10, 3)), makeProject(makeSession('codex', 10, 3))], + { label: 'August 2026', color: false }, + ) + // Exclusive 13 + inclusive 10. Combined token totals (input/cache are 0). + expect(out).toContain('13') + expect(out).toContain('10') + expect(out).toMatch(/Output[\s\S]*13/) + expect(out).toContain('grok') + expect(out).toContain('codex') + }) + + it('session helper does not crash on aggregate-only or minimal calls', () => { + const aggregate = makeSession('grok', 10, 3) + aggregate.turns = [] + expect(sessionBillableOutputTokens(aggregate)).toBe(13) + + const noReasoning = makeSession('grok', 10, 3) + noReasoning.turns = [] + delete (noReasoning as { totalReasoningTokens?: number }).totalReasoningTokens + const noReasoningOut = sessionBillableOutputTokens(noReasoning) + expect(Number.isFinite(noReasoningOut)).toBe(true) + expect(noReasoningOut).toBe(10) + + const stub = makeSession('codex', 10, 3) + stub.turns[0]!.assistantCalls = [{ costUSD: 1, tools: [], bashCommands: [], timestamp: stub.firstTimestamp } as never] + expect(sessionBillableOutputTokens(stub)).toBe(10) + + expect(callBillableOutputTokens({} as never)).toBe(0) + expect(callBillableOutputTokens({ provider: 'grok', usage: { outputTokens: 10, reasoningTokens: 3 } })).toBe(13) + }) + + it('joins model output on getShortModelName, not raw call.model', async () => { + const session = makeSession('claude', 10, 0) + session.turns[0]!.assistantCalls[0]!.model = 'deepseek-v4-pro' + session.modelBreakdown = { + 'DeepSeek v4 Pro': { + calls: 1, + costUSD: 1, + savingsUSD: 0, + tokens: session.turns[0]!.assistantCalls[0]!.usage, + }, + } + const billed = sessionModelBillableOutputTokens(session) + expect(billed).toEqual({ 'DeepSeek v4 Pro': 10 }) + expect(billed['deepseek-v4-pro']).toBeUndefined() + + const dir = await mkdtemp(join(tmpdir(), 'cb-1116-display-key-')) + try { + const path = await exportJson( + [{ label: '30 Days', projects: [makeProject(session)] }], + join(dir, 'out.json'), + ) + const data = JSON.parse(await readFile(path, 'utf-8')) as { + periods: Array<{ models: Array<{ Model: string; 'API Calls': number; 'Output Tokens': number }> }> + } + const rows = data.periods[0]!.models + expect(rows.filter(r => r.Model === 'deepseek-v4-pro')).toHaveLength(0) + const named = rows.find(r => r.Model === 'DeepSeek v4 Pro') + expect(named).toEqual(expect.objectContaining({ + Model: 'DeepSeek v4 Pro', + 'API Calls': 1, + 'Output Tokens': 10, + })) + } finally { + await rm(dir, { recursive: true, force: true }) + } + + const out = renderOverview([makeProject(session)], { label: 'May 2026', color: false }) + expect(out).toContain('DeepSeek v4 Pro') + expect(out).not.toContain('deepseek-v4-pro') + expect(out).toMatch(/DeepSeek v4 Pro[\s\S]*\b1\b[\s\S]*\b10\b/) + }) + + it('does not mint a $0 short-name orphan when modelBreakdown is the raw id', () => { + const session = makeSession('claude', 50, 0) + session.turns[0]!.assistantCalls[0]!.model = 'claude-opus-4-8' + session.modelBreakdown = { + 'claude-opus-4-8': { + calls: 2, + costUSD: 5, + savingsUSD: 0, + tokens: { + inputTokens: 100, + outputTokens: 50, + cacheReadInputTokens: 0, + cacheCreationInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, + }, + }, + } + expect(sessionModelBillableOutputTokens(session)).toEqual({ 'claude-opus-4-8': 50 }) + const out = renderOverview([makeProject(session)], { label: 'June 2026', color: false }) + expect(out).not.toContain('Unpriced') + expect(out).toContain('$5.00') + }) + + it('aggregate-only model rows keep finite billable output', async () => { + const aggregate = makeSession('grok', 10, 3) + aggregate.turns = [] + expect(sessionBillableOutputTokens(aggregate)).toBe(13) + expect(sessionModelBillableOutputTokens(aggregate)).toEqual({ [getShortModelName('grok-4')]: 13 }) + + const dir = await mkdtemp(join(tmpdir(), 'cb-1116-agg-only-')) + try { + const path = await exportJson( + [{ label: '30 Days', projects: [makeProject(aggregate)] }], + join(dir, 'out.json'), + ) + const data = JSON.parse(await readFile(path, 'utf-8')) as { + periods: Array<{ models: Array<{ Model: string; 'Output Tokens': number }> }> + } + expect(data.periods[0]!.models.find(r => r.Model === getShortModelName('grok-4'))!['Output Tokens']).toBe(13) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/cache-refresh-lock-process.test.ts b/tests/cache-refresh-lock-process.test.ts index 752f332e..8d6d25ac 100644 --- a/tests/cache-refresh-lock-process.test.ts +++ b/tests/cache-refresh-lock-process.test.ts @@ -130,6 +130,35 @@ describe('warm refresh child-process regression', () => { expect(Object.keys((await loadCache()).providers['regression']?.files ?? {})).toEqual([source]) }) + // #1117: the menubar/desktop watchdog kills a CLI child with SIGTERM first, + // precisely so the holder can unlink its own lock instead of leaving one for + // every later spawn to wait out. + it('unlinks its own lock when the holder is SIGTERMed mid-transaction', async () => { + const root = await mkdtemp(join(tmpdir(), 'cb-refresh-sigterm-')) + roots.push(root) + const cacheDir = join(root, 'cache') + const barriers = join(root, 'barriers') + await mkdir(cacheDir, { recursive: true }) + await mkdir(barriers, { recursive: true }) + process.env['CODEBURN_CACHE_DIR'] = cacheDir + const initial = emptyCache() + initial.complete = true + await saveCache(initial) + const source = join(root, 'changed.json') + await writeFile(source, JSON.stringify({ output: 505 })) + + const holder = worker(cacheDir, barriers, 'a', source) + // The worker blocks on its save barrier while holding the lock. + await waitFor(join(barriers, 'a.parsed')) + const lock = join(cacheDir, 'session-refresh.lock') + expect(existsSync(lock)).toBe(true) + + const exited = new Promise(resolve => { holder.once('exit', () => resolve()) }) + holder.kill('SIGTERM') + await exited + expect(existsSync(lock)).toBe(false) + }) + it('serializes disjoint parsed updates so the later publication cannot drop the first', async () => { const root = await mkdtemp(join(tmpdir(), 'cb-refresh-process-')) roots.push(root) diff --git a/tests/cache-refresh-lock.test.ts b/tests/cache-refresh-lock.test.ts index b59c6834..c452afe7 100644 --- a/tests/cache-refresh-lock.test.ts +++ b/tests/cache-refresh-lock.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' +import { spawn } from 'child_process' import { chmod, mkdir, mkdtemp, readFile, rm, stat, unlink, utimes, writeFile } from 'fs/promises' import { tmpdir } from 'os' import { join } from 'path' @@ -32,6 +33,15 @@ function fakeClock(start = 1_000): RefreshLockClock & { advance: (ms: number) => } } +/** The pid of a process that has definitively exited, for the dead-holder gate. */ +async function exitedPid(): Promise { + const child = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' }) + const pid = child.pid + if (!pid) throw new Error('no pid') + await new Promise(resolve => { child.once('exit', () => resolve()) }) + return pid +} + afterEach(async () => { delete process.env['CODEBURN_CACHE_DIR'] await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) @@ -134,6 +144,105 @@ describe('warm session-cache refresh lock', () => { } }) + // #1117: the waiter budget now outlives the stale gate by design, so the + // live-holder guarantee has to hold for a wait many times longer than staleMs, + // not just for one shorter than it. + it('never takes over a heartbeating owner however far the wait outlives staleMs', async () => { + const dir = await tempDir() + const path = lockPath(dir) + const clock = fakeClock() + await writeFile(path, JSON.stringify({ pid: 1, token: 'holder', at: clock.wallNow() })) + const beat = async (): Promise => { + const now = new Date(clock.wallNow()) + await utimes(path, now, now) + } + await beat() + + const result = await acquireCacheRefreshLock({ + cacheDir: dir, + clock, + staleMs: 500, + waitMs: 5_000, + pollMs: 1, + // pid 1 is alive and the holder keeps pace with the clock, so neither + // abandonment clause ever opens even though the waiter spends ten stale + // windows in the loop. + sleep: async () => { clock.advance(100); await beat() }, + }) + expect(result).toEqual({ outcome: 'timed-out' }) + expect(JSON.parse(await readFile(path, 'utf-8')).token).toBe('holder') + }) + + it('takes over a lock whose holder pid is gone without waiting out the stale window', async () => { + const dir = await tempDir() + const path = lockPath(dir) + // Wall clock frozen so the age gate can NEVER open; monotonic still runs so + // the waiter budget expires instead of spinning. Only the dead pid can + // explain a takeover here. + let monotonic = 1_000 + const clock: RefreshLockClock = { wallNow: () => 1_000, monotonicNow: () => monotonic } + const gone = await exitedPid() + await writeFile(path, JSON.stringify({ pid: gone, token: 'killed', at: clock.wallNow() })) + const now = new Date(clock.wallNow()) + await utimes(path, now, now) + + const result = await acquireCacheRefreshLock({ + cacheDir: dir, + clock, + waitMs: 5_000, + pollMs: 1, + sleep: async ms => { monotonic += ms }, + }) + expect(result.outcome).toBe('acquired') + if (result.outcome !== 'acquired') return + expect(JSON.parse(await readFile(path, 'utf-8'))).toMatchObject({ pid: process.pid, token: result.handle.token }) + await result.handle.release() + }) + + it('takes over a lock whose heartbeat froze even though its holder pid is alive', async () => { + const dir = await tempDir() + const path = lockPath(dir) + // pid 1 always answers signal 0, so only the frozen mtime can explain it. + await writeFile(path, JSON.stringify({ pid: 1, token: 'frozen', at: 1 })) + await utimes(path, new Date(1), new Date(1)) + const clock = fakeClock(1_000_000) + + const result = await acquireCacheRefreshLock({ + cacheDir: dir, + clock, + staleMs: 90_000, + waitMs: 5_000, + pollMs: 1, + sleep: async ms => { clock.advance(ms) }, + }) + expect(result.outcome).toBe('acquired') + if (result.outcome !== 'acquired') return + await result.handle.release() + }) + + it('defaults the waiter budget past the stale gate', async () => { + const dir = await tempDir() + const path = lockPath(dir) + const clock = fakeClock() + await writeFile(path, JSON.stringify({ pid: 1, token: 'frozen', at: clock.wallNow() })) + const now = new Date(clock.wallNow()) + await utimes(path, now, now) + + // No waitMs override: the default must be long enough that a lock which goes + // stale mid-wait is still recovered by THIS waiter rather than timing out + // and leaving the leftover for the next process to trip over (#1117). + const result = await acquireCacheRefreshLock({ + cacheDir: dir, + clock, + staleMs: 90_000, + pollMs: 1, + sleep: async () => { clock.advance(1_000) }, + }) + expect(result.outcome).toBe('acquired') + if (result.outcome !== 'acquired') return + await result.handle.release() + }) + it('heartbeats its own lock body and mtime with the injected clock', async () => { const dir = await tempDir() const clock = fakeClock(10_000) diff --git a/tests/hermes-session-ledger.test.ts b/tests/hermes-session-ledger.test.ts new file mode 100644 index 00000000..d71e937c --- /dev/null +++ b/tests/hermes-session-ledger.test.ts @@ -0,0 +1,246 @@ +import { mkdir, mkdtemp, rm } from 'fs/promises' +import { join } from 'path' +import { tmpdir } from 'os' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { + applyHermesSnapshot, + hermesBaselineKey, + hermesObservationKey, + hermesSessionLedgerPath, + isHermesLedgerPublicationError, + isHermesObservationKey, + loadHermesSessionLedger, + parseHermesDedupKey, + persistHermesSessionLedger, + recordHermesSnapshot, + resetHermesSessionLedgerForTests, + seedHermesCursorsFromProviderSection, + setHermesLedgerNow, + type HermesSnapshot, +} from '../src/hermes-session-ledger.js' +import type { CachedCall, ProviderSection } from '../src/session-cache.js' + +let cacheDir: string +let originalCacheDir: string | undefined + +beforeEach(async () => { + cacheDir = await mkdtemp(join(tmpdir(), 'hermes-ledger-unit-')) + originalCacheDir = process.env['CODEBURN_CACHE_DIR'] + process.env['CODEBURN_CACHE_DIR'] = cacheDir + resetHermesSessionLedgerForTests() +}) + +afterEach(async () => { + resetHermesSessionLedgerForTests() + if (originalCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR'] + else process.env['CODEBURN_CACHE_DIR'] = originalCacheDir + await rm(cacheDir, { recursive: true, force: true }) +}) + +function snap(overrides: Partial = {}): HermesSnapshot { + const { tokens: tokenOverrides, ...rest } = overrides + return { + profile: 'default', + sessionId: 's1', + startedAt: '2026-08-21T10:00:00.000Z', + observedAt: '2026-08-22T10:00:00.000Z', + costUSD: 0.10, + costBasis: 'actual', + ...rest, + tokens: { + inputTokens: 100, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + reasoningTokens: 0, + ...tokenOverrides, + }, + } +} + +describe('hermes session ledger unit', () => { + it('parses baseline and observation keys', () => { + expect(parseHermesDedupKey('hermes:default:abc')).toEqual({ profile: 'default', sessionId: 'abc' }) + expect(parseHermesDedupKey('hermes:coder:abc:obs:1')).toEqual({ + profile: 'coder', + sessionId: 'abc', + observationIndex: 1, + }) + expect(isHermesObservationKey('hermes:default:abc')).toBe(false) + expect(isHermesObservationKey('hermes:default:abc:obs:2')).toBe(true) + expect(hermesBaselineKey('default', 'abc')).toBe('hermes:default:abc') + expect(hermesObservationKey('default', 'abc', 1)).toBe('hermes:default:abc:obs:1') + }) + + it('first observation is behavioral lifetime at started_at', () => { + const { cursor, dirty } = applyHermesSnapshot(undefined, snap()) + expect(dirty).toBe(true) + expect(cursor.observations).toHaveLength(1) + expect(cursor.observations[0]).toMatchObject({ + index: 0, + timestamp: '2026-08-21T10:00:00.000Z', + inputTokens: 100, + costUSD: 0.10, + supplementaryAccounting: false, + }) + expect(cursor.lastSeen.inputTokens).toBe(100) + }) + + it('growth emits a positive delta only', () => { + const first = applyHermesSnapshot(undefined, snap()).cursor + const { cursor, dirty } = applyHermesSnapshot(first, snap({ + tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0.15, + })) + expect(dirty).toBe(true) + expect(cursor.observations).toHaveLength(2) + expect(cursor.observations[1]!.index).toBe(1) + expect(cursor.observations[1]!.timestamp).toBe('2026-08-22T10:00:00.000Z') + expect(cursor.observations[1]!.inputTokens).toBe(50) + expect(cursor.observations[1]!.costUSD).toBeCloseTo(0.05) + expect(cursor.observations[1]!.supplementaryAccounting).toBe(true) + expect(cursor.lastSeen).toMatchObject({ inputTokens: 150, costUSD: 0.15 }) + }) + + it('equal totals re-emit stored observations with no new row', () => { + const first = applyHermesSnapshot(undefined, snap()).cursor + const { cursor, dirty } = applyHermesSnapshot(first, snap()) + expect(dirty).toBe(false) + expect(cursor.observations).toHaveLength(1) + expect(cursor).toBe(first) + }) + + it('150 → 0 advances last-seen to zero and emits no observation', () => { + const first = applyHermesSnapshot(undefined, snap({ + tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0.15, + })).cursor + const { cursor, dirty } = applyHermesSnapshot(first, snap({ + tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0, + })) + expect(dirty).toBe(true) + expect(cursor.observations).toHaveLength(1) + expect(cursor.lastSeen.inputTokens).toBe(0) + expect(cursor.lastSeen.costUSD).toBe(0) + }) + + it('0 → 40 after a zero reset emits one +40 weight-0 observation', () => { + const first = applyHermesSnapshot(undefined, snap({ + tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + })).cursor + const zeroed = applyHermesSnapshot(first, snap({ + tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0, + })).cursor + const { cursor } = applyHermesSnapshot(zeroed, snap({ + tokens: { inputTokens: 40, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0.04, + })) + expect(cursor.observations).toHaveLength(2) + expect(cursor.observations[1]).toMatchObject({ + index: 1, + inputTokens: 40, + costUSD: 0.04, + supplementaryAccounting: true, + }) + expect(cursor.observations.some(o => o.inputTokens < 0 || o.costUSD < 0)).toBe(false) + }) + + it('a cost-basis shrink is a cost reset without a negative', () => { + const first = applyHermesSnapshot(undefined, snap()).cursor + const { cursor } = applyHermesSnapshot(first, snap({ + tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0.05, + costBasis: 'estimated', + })) + expect(cursor.observations).toHaveLength(2) + expect(cursor.observations[1]).toMatchObject({ + inputTokens: 50, + costUSD: 0, + supplementaryAccounting: true, + }) + expect(cursor.lastSeen.costUSD).toBe(0.05) + expect(cursor.lastSeen.costBasis).toBe('estimated') + }) + + it('clock is injectable for observation timestamps', async () => { + setHermesLedgerNow(() => new Date('2026-08-22T15:30:00.000Z')) + const cursor = await recordHermesSnapshot(snap({ + observedAt: new Date('2026-08-22T15:30:00.000Z').toISOString(), + })) + const grown = await recordHermesSnapshot(snap({ + tokens: { inputTokens: 120, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + costUSD: 0.12, + observedAt: new Date('2026-08-22T15:30:00.000Z').toISOString(), + })) + expect(grown.observations[1]!.timestamp).toBe('2026-08-22T15:30:00.000Z') + expect(cursor.observations[0]!.timestamp).toBe('2026-08-21T10:00:00.000Z') + }) + + it('seed writes one behavioral observation and does not overwrite existing keys', async () => { + const call: CachedCall = { + provider: 'hermes', + model: 'gpt-5.5', + usage: { + inputTokens: 100, + outputTokens: 0, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, + cacheCreationOneHourTokens: 0, + }, + costUSD: 0.10, + speed: 'standard', + timestamp: '2026-08-21T10:00:00.000Z', + tools: ['Read'], + bashCommands: [], + skills: [], + subagentTypes: [], + deduplicationKey: 'hermes:default:seeded', + } + const section: ProviderSection = { + envFingerprint: 'test', + files: { + '/tmp/state.db#hermes-session=seeded': { + fingerprint: { dev: 1, ino: 1, mtimeMs: 1, sizeBytes: 1 }, + mcpInventory: [], + turns: [{ timestamp: call.timestamp, sessionId: 'seeded', userMessage: 'hi', calls: [call] }], + }, + }, + } + await seedHermesCursorsFromProviderSection(section) + const first = loadHermesSessionLedger() + expect(first.cursors['default']!['seeded']!.observations).toHaveLength(1) + expect(first.cursors['default']!['seeded']!.observations[0]).toMatchObject({ + index: 0, + timestamp: '2026-08-21T10:00:00.000Z', + inputTokens: 100, + supplementaryAccounting: false, + }) + + section.files['/tmp/state.db#hermes-session=seeded']!.turns[0]!.calls[0] = { + ...call, + usage: { ...call.usage, inputTokens: 999 }, + timestamp: '2026-08-22T10:00:00.000Z', + } + await seedHermesCursorsFromProviderSection(section) + const second = loadHermesSessionLedger() + expect(second.cursors['default']!['seeded']!.observations).toHaveLength(1) + expect(second.cursors['default']!['seeded']!.lastSeen.inputTokens).toBe(100) + }) + + it('publication failure is a typed retryable error', async () => { + await mkdir(hermesSessionLedgerPath()) + let caught: unknown + try { + await persistHermesSessionLedger({ version: 1, cursors: {} }) + } catch (err) { + caught = err + } + expect(isHermesLedgerPublicationError(caught)).toBe(true) + }) +}) diff --git a/tests/menubar-json.test.ts b/tests/menubar-json.test.ts index 393482a2..c499bee3 100644 --- a/tests/menubar-json.test.ts +++ b/tests/menubar-json.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { buildMenubarPayload, type CombinedUsage, type PeriodData, type ProviderCost } from '../src/menubar-json.js' +import { buildMenubarPayload, type CombinedUsage, type LocalModelSavings, type PeriodData, type ProviderCost } from '../src/menubar-json.js' import type { OptimizeResult } from '../src/optimize.js' function emptyPeriod(label: string): PeriodData { @@ -423,4 +423,27 @@ describe('buildMenubarPayload', () => { const payload = buildMenubarPayload(emptyPeriod('Today'), [], null) expect(payload.stale).toBeUndefined() }) + + it('passes localModelSavings.byModel.outputTokens through as billable output', () => { + // usage-aggregator writes billableOutputTokens into this field while the + // provider is still known. Exclusive 10+3 → 13; inclusive 10+3 → 10. + const localModelSavings: LocalModelSavings = { + totalUSD: 2, + calls: 2, + byModel: [ + { name: 'Grok 4', calls: 1, actualUSD: 0, savingsUSD: 1, baselineModel: 'gpt-4o', inputTokens: 0, outputTokens: 13 }, + { name: 'GPT-5.4', calls: 1, actualUSD: 0, savingsUSD: 1, baselineModel: 'gpt-4o', inputTokens: 0, outputTokens: 10 }, + ], + byProvider: [ + { name: 'grok', calls: 1, savingsUSD: 1 }, + { name: 'codex', calls: 1, savingsUSD: 1 }, + ], + } + const period: PeriodData = { ...emptyPeriod('Today'), outputTokens: 23 } + const payload = buildMenubarPayload(period, [], null, undefined, undefined, undefined, { localModelSavings }) + expect(payload.current.outputTokens).toBe(23) + expect(payload.current.localModelSavings.byModel).toEqual(localModelSavings.byModel) + expect(payload.current.localModelSavings.byModel[0]!.outputTokens).toBe(13) + expect(payload.current.localModelSavings.byModel[1]!.outputTokens).toBe(10) + }) }) diff --git a/tests/provider-probe-roots-tier2.test.ts b/tests/provider-probe-roots-tier2.test.ts index 0c34f079..aab11525 100644 --- a/tests/provider-probe-roots-tier2.test.ts +++ b/tests/provider-probe-roots-tier2.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest' +import { afterEach, describe, it, expect } from 'vitest' import { isAbsolute, join } from 'path' import { homedir } from 'os' @@ -13,6 +13,11 @@ import { discoverClineTasks, getVSCodeGlobalStoragePaths, } from '../src/providers/vscode-cline-parser.js' +import { createCodebuffProvider, getCodebuffRootSet } from '../src/providers/codebuff.js' +import { createDevinProvider } from '../src/providers/devin.js' +import { createGeminiProvider, getGeminiTmpDir } from '../src/providers/gemini.js' +import { createKiroProvider, getKiroAgentDirCandidates } from '../src/providers/kiro.js' +import { createMistralVibeProvider, getMistralVibeSessionsDir } from '../src/providers/mistral-vibe.js' // #899 Tier 2, batch 1. probeRoots() must report the roots discovery actually // reads: a probe pointing somewhere discovery never looks is worse than none, @@ -108,3 +113,159 @@ describe('probeRoots mirrors discovery resolution (Tier 2, batch 1)', () => { ]) }) }) + +// #899 Tier 2, batch 2. Same contract as batch 1: probeRoots() is the exact +// discovery-root set after the same resolution, pinned as full objects. +describe('probeRoots mirrors discovery resolution (Tier 2, batch 2)', () => { + const originalCodebuffDataDir = process.env['CODEBUFF_DATA_DIR'] + const originalVibeHome = process.env['VIBE_HOME'] + + afterEach(() => { + if (originalCodebuffDataDir === undefined) delete process.env['CODEBUFF_DATA_DIR'] + else process.env['CODEBUFF_DATA_DIR'] = originalCodebuffDataDir + if (originalVibeHome === undefined) delete process.env['VIBE_HOME'] + else process.env['VIBE_HOME'] = originalVibeHome + }) + + it('codebuff reports all three CHANNELS on default, and empty factory is unset', async () => { + const expected = [ + { path: join(homedir(), '.config', 'manicode'), label: 'chats' }, + { path: join(homedir(), '.config', 'manicode-dev'), label: 'chats' }, + { path: join(homedir(), '.config', 'manicode-staging'), label: 'chats' }, + ] + expect(await createCodebuffProvider().probeRoots!()).toEqual(expected) + expect(await createCodebuffProvider('').probeRoots!()).toEqual(expected) + expect(getCodebuffRootSet()).toEqual(expected.map(r => r.path)) + expect(getCodebuffRootSet('')).toEqual(expected.map(r => r.path)) + for (const root of expected) expect(isAbsolute(root.path)).toBe(true) + }) + + it('codebuff reports the factory root, or CODEBUFF_DATA_DIR when factory is empty', async () => { + expect(await createCodebuffProvider('/tmp/codebuff-a').probeRoots!()).toEqual([ + { path: '/tmp/codebuff-a', label: 'chats' }, + ]) + process.env['CODEBUFF_DATA_DIR'] = '/tmp/codebuff-env' + expect(await createCodebuffProvider().probeRoots!()).toEqual([ + { path: '/tmp/codebuff-env', label: 'chats' }, + ]) + expect(await createCodebuffProvider('').probeRoots!()).toEqual([ + { path: '/tmp/codebuff-env', label: 'chats' }, + ]) + // Non-blank factory wins over the env root. + expect(await createCodebuffProvider('/tmp/codebuff-a').probeRoots!()).toEqual([ + { path: '/tmp/codebuff-a', label: 'chats' }, + ]) + }) + + it('devin reports transcripts + sessions.db, not the parent, and empty factory is default', async () => { + expect(await createDevinProvider('/tmp/probe-devin').probeRoots!()).toEqual([ + { path: join('/tmp/probe-devin', 'transcripts'), label: 'transcripts' }, + { path: join('/tmp/probe-devin', 'sessions.db'), label: 'sessions.db' }, + ]) + const defaults = [ + { path: join(homedir(), '.local', 'share', 'devin', 'cli', 'transcripts'), label: 'transcripts' }, + { path: join(homedir(), '.local', 'share', 'devin', 'cli', 'sessions.db'), label: 'sessions.db' }, + ] + expect(await createDevinProvider().probeRoots!()).toEqual(defaults) + expect(await createDevinProvider('').probeRoots!()).toEqual(defaults) + for (const root of defaults) expect(isAbsolute(root.path)).toBe(true) + }) + + it('gemini reports only the shared tmp parent', async () => { + const tmpDir = getGeminiTmpDir() + expect(tmpDir).toBe(join(homedir(), '.gemini', 'tmp')) + expect(await createGeminiProvider().probeRoots!()).toEqual([ + { path: tmpDir, label: 'tmp' }, + ]) + expect(tmpDir).not.toContain(`${join('tmp', 'chats')}`) + expect(isAbsolute(tmpDir)).toBe(true) + }) + + it('kiro reports the override set exactly and never the developer Application Support tree', async () => { + const agent = '/tmp/kiro-agent' + const workspace = '/tmp/kiro-workspace' + const cli = '/tmp/kiro-cli' + const v2 = '/tmp/kiro-v2' + const roots = await createKiroProvider(agent, workspace, cli, v2).probeRoots!() + expect(roots).toEqual([ + { path: agent, label: 'agent' }, + { path: workspace, label: 'workspace' }, + { path: cli, label: 'cli' }, + { path: v2, label: 'v2' }, + ]) + for (const root of roots) { + expect(isAbsolute(root.path)).toBe(true) + expect(root.path).not.toContain('Application Support/Kiro') + } + }) + + it('kiro empty-string table matches discovery: agent/workspace fall back, empty CLI and v2 are skipped', async () => { + const workspace = '/tmp/kiro-ws' + const cli = '/tmp/kiro-cli' + const v2 = '/tmp/kiro-v2' + + const unsetAgent = await createKiroProvider(undefined, workspace, cli, v2).probeRoots!() + const emptyAgent = await createKiroProvider('', workspace, cli, v2).probeRoots!() + expect(emptyAgent).toEqual(unsetAgent) + expect(emptyAgent.map(r => r.path)).toEqual([ + ...getKiroAgentDirCandidates(''), + workspace, + cli, + v2, + ]) + expect(emptyAgent.filter(r => r.label === 'agent').map(r => r.path)).toEqual( + getKiroAgentDirCandidates(), + ) + + const unsetWorkspace = await createKiroProvider('/tmp/kiro-agent', undefined, cli, v2).probeRoots!() + const emptyWorkspace = await createKiroProvider('/tmp/kiro-agent', '', cli, v2).probeRoots!() + expect(emptyWorkspace).toEqual(unsetWorkspace) + expect(emptyWorkspace.find(r => r.label === 'workspace')!.path).not.toBe('') + + const emptyCli = await createKiroProvider('/tmp/kiro-agent', workspace, '', v2).probeRoots!() + expect(emptyCli).toEqual([ + { path: '/tmp/kiro-agent', label: 'agent' }, + { path: workspace, label: 'workspace' }, + { path: v2, label: 'v2' }, + ]) + expect(emptyCli.map(r => r.path)).not.toContain('') + expect(emptyCli.map(r => r.path)).not.toContain('.') + + const emptyV2 = await createKiroProvider('/tmp/kiro-agent', workspace, cli, '').probeRoots!() + expect(emptyV2).toEqual([ + { path: '/tmp/kiro-agent', label: 'agent' }, + { path: workspace, label: 'workspace' }, + { path: cli, label: 'cli' }, + ]) + expect(emptyV2.some(r => r.label === 'v2')).toBe(false) + + const emptyCliAndV2 = await createKiroProvider('/tmp/kiro-agent', workspace, '', '').probeRoots!() + expect(emptyCliAndV2).toEqual([ + { path: '/tmp/kiro-agent', label: 'agent' }, + { path: workspace, label: 'workspace' }, + ]) + + const skipped = await createKiroProvider('/tmp/kiro-agent', workspace, '', '').discoverSessions() + expect(skipped).toEqual([]) + }) + + it('mistral-vibe reports the same joined sessions dir discovery uses', async () => { + expect(await createMistralVibeProvider('/tmp/vibe-sessions').probeRoots!()).toEqual([ + { path: getMistralVibeSessionsDir('/tmp/vibe-sessions'), label: 'sessions' }, + ]) + expect(getMistralVibeSessionsDir('/tmp/vibe-sessions')).toBe('/tmp/vibe-sessions') + + const defaults = await createMistralVibeProvider().probeRoots!() + expect(defaults).toEqual([ + { path: getMistralVibeSessionsDir(), label: 'sessions' }, + ]) + expect(defaults[0]!.path).toBe(join(homedir(), '.vibe', 'logs', 'session')) + expect(await createMistralVibeProvider('').probeRoots!()).toEqual(defaults) + + process.env['VIBE_HOME'] = '/tmp/vibe-home' + expect(await createMistralVibeProvider().probeRoots!()).toEqual([ + { path: join('/tmp/vibe-home', 'logs', 'session'), label: 'sessions' }, + ]) + expect(getMistralVibeSessionsDir()).toBe(join('/tmp/vibe-home', 'logs', 'session')) + }) +}) diff --git a/tests/providers/hermes-ledger.test.ts b/tests/providers/hermes-ledger.test.ts new file mode 100644 index 00000000..a167b462 --- /dev/null +++ b/tests/providers/hermes-ledger.test.ts @@ -0,0 +1,435 @@ +import { mkdir, mkdtemp, rm, unlink } from 'fs/promises' +import { homedir } from 'os' +import { join, resolve } from 'path' +import { createRequire } from 'node:module' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createHermesProvider } from '../../src/providers/hermes.js' +import { isSqliteAvailable } from '../../src/sqlite.js' +import { aggregateProjectsIntoDays, dateKey } from '../../src/day-aggregator.js' +import { behavioralTurnCount } from '../../src/behavioral-weight.js' +import { + getHermesCursor, + hermesSessionLedgerPath, + loadHermesSessionLedger, + resetHermesSessionLedgerForTests, +} from '../../src/hermes-session-ledger.js' +import type { ParsedProviderCall } from '../../src/providers/types.js' + +const requireForTest = createRequire(import.meta.url) + +type TestDb = { + exec(sql: string): void + prepare(sql: string): { run(...params: unknown[]): void } + close(): void +} + +const CLEANHOME_ROOT = '/tmp/cb-cleanhome' +const REAL_HERMES_HOME = resolve(join(homedir(), '.hermes')) + +let hermesHome: string +let cacheDir: string +let originalHermesHome: string | undefined +let originalCodeburnCacheDir: string | undefined + +beforeEach(async () => { + await mkdir(CLEANHOME_ROOT, { recursive: true }) + hermesHome = await mkdtemp(join(CLEANHOME_ROOT, 'home-')) + cacheDir = await mkdtemp(join(CLEANHOME_ROOT, 'cache-')) + expect(resolve(hermesHome)).not.toBe(REAL_HERMES_HOME) + originalHermesHome = process.env['HERMES_HOME'] + originalCodeburnCacheDir = process.env['CODEBURN_CACHE_DIR'] + process.env['HERMES_HOME'] = hermesHome + process.env['CODEBURN_CACHE_DIR'] = cacheDir + resetHermesSessionLedgerForTests() +}) + +afterEach(async () => { + resetHermesSessionLedgerForTests() + if (originalHermesHome === undefined) delete process.env['HERMES_HOME'] + else process.env['HERMES_HOME'] = originalHermesHome + if (originalCodeburnCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR'] + else process.env['CODEBURN_CACHE_DIR'] = originalCodeburnCacheDir + await rm(hermesHome, { recursive: true, force: true }) + await rm(cacheDir, { recursive: true, force: true }) +}) + +function createHermesDb(homeDir: string): string { + const { DatabaseSync: Database } = requireForTest('node:sqlite') + const dbPath = join(homeDir, 'state.db') + const db = new Database(dbPath) + db.exec(` + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + source TEXT, + model TEXT, + cwd TEXT, + git_repo_root TEXT, + billing_provider TEXT, + input_tokens INTEGER DEFAULT 0, + output_tokens INTEGER DEFAULT 0, + cache_read_tokens INTEGER DEFAULT 0, + cache_write_tokens INTEGER DEFAULT 0, + reasoning_tokens INTEGER DEFAULT 0, + estimated_cost_usd REAL, + actual_cost_usd REAL, + api_call_count INTEGER DEFAULT 0, + tool_call_count INTEGER DEFAULT 0, + started_at REAL, + ended_at REAL, + title TEXT + ) + `) + db.exec(` + CREATE TABLE messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + role TEXT NOT NULL, + content TEXT, + tool_call_id TEXT, + tool_calls TEXT, + tool_name TEXT, + timestamp REAL NOT NULL + ) + `) + db.close() + return dbPath +} + +async function createProfileHermesDb(home: string, profile: string): Promise { + const profileDir = join(home, 'profiles', profile) + await mkdir(profileDir, { recursive: true }) + return createHermesDb(profileDir) +} + +function withTestDb(dbPath: string, fn: (db: TestDb) => void): void { + const { DatabaseSync: Database } = requireForTest('node:sqlite') + const db = new Database(dbPath) + try { + fn(db) + } finally { + db.close() + } +} + +function insertSession(db: TestDb, values: { + id: string + inputTokens: number + outputTokens?: number + actualCost?: number | null + estimatedCost?: number | null + startedAt: number + model?: string +}): void { + db.prepare( + `INSERT INTO sessions ( + id, source, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, + reasoning_tokens, estimated_cost_usd, actual_cost_usd, api_call_count, tool_call_count, + started_at, title + ) VALUES (?, 'cli', ?, ?, ?, 0, 0, 0, ?, ?, 1, 0, ?, ?)`, + ).run( + values.id, + values.model ?? 'gpt-5.5', + values.inputTokens, + values.outputTokens ?? 0, + values.estimatedCost ?? null, + values.actualCost ?? null, + values.startedAt, + values.id, + ) +} + +function updateSession(db: TestDb, id: string, values: { + inputTokens: number + actualCost?: number | null +}): void { + db.prepare('UPDATE sessions SET input_tokens = ?, actual_cost_usd = ? WHERE id = ?') + .run(values.inputTokens, values.actualCost ?? null, id) +} + +function localDay(offsetDays: number, hour = 10): { date: Date; unixSec: number; key: string; iso: string } { + const date = new Date() + date.setHours(hour, 0, 0, 0) + date.setDate(date.getDate() + offsetDays) + return { + date, + unixSec: date.getTime() / 1000, + key: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`, + iso: date.toISOString(), + } +} + +async function loadParser() { + process.env['HERMES_HOME'] = hermesHome + process.env['CODEBURN_CACHE_DIR'] = cacheDir + vi.resetModules() + resetHermesSessionLedgerForTests() + return import('../../src/parser.js') +} + +async function parseDiscovered(): Promise<{ sources: { path: string }[]; calls: ParsedProviderCall[] }> { + const provider = createHermesProvider(hermesHome) + const sources = await provider.discoverSessions() + const calls: ParsedProviderCall[] = [] + const seen = new Set() + for (const source of sources) { + for await (const call of provider.createSessionParser(source, seen).parse()) { + calls.push(call) + } + } + return { sources, calls } +} + +const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip + +skipUnlessSqlite('hermes post-finalization ledger proofs', () => { + it('P1: sealed day D keeps 100/$0.10/1/1; D+1 is +50/$0.05/0/0', async () => { + const dayD = localDay(-1) + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p1', inputTokens: 100, actualCost: 0.10, startedAt: dayD.unixSec }) + db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)') + .run('p1', 'user', 'keep going', dayD.unixSec + 1) + }) + + const parser = await loadParser() + parser.clearSessionCache() + const firstProjects = await parser.parseAllSessions(undefined, 'hermes') + const { ensureCacheHydrated, loadDailyCache } = await import('../../src/daily-cache.js') + await ensureCacheHydrated( + (range) => parser.parseAllSessions(range, 'hermes'), + aggregateProjectsIntoDays, + '', + parser.isSessionHydrationComplete, + ) + const sealed = await loadDailyCache() + expect(sealed.lastComputedDate).toBe(dayD.key) + const sealedDay = sealed.days.find(d => d.date === dayD.key) + expect(sealedDay?.inputTokens).toBe(100) + expect(sealedDay?.cost).toBeCloseTo(0.10) + expect(sealedDay?.calls).toBe(1) + expect(sealedDay?.sessions).toBe(1) + + withTestDb(dbPath, (db) => { + updateSession(db, 'p1', { inputTokens: 150, actualCost: 0.15 }) + }) + parser.clearSessionCache() + const grown = await parser.parseAllSessions(undefined, 'hermes') + const days = aggregateProjectsIntoDays(grown) + const todayKey = dateKey(new Date().toISOString()) + const dEntry = days.find(d => d.date === dayD.key) + const todayEntry = days.find(d => d.date === todayKey) + expect(dEntry?.inputTokens).toBe(100) + expect(dEntry?.cost).toBeCloseTo(0.10) + expect(dEntry?.calls).toBe(1) + expect(dEntry?.sessions).toBe(1) + expect(todayEntry?.inputTokens).toBe(50) + expect(todayEntry?.cost).toBeCloseTo(0.05) + expect(todayEntry?.calls).toBe(0) + expect(todayEntry?.sessions ?? 0).toBe(0) + + const session = grown.flatMap(p => p.sessions)[0]! + expect(session.apiCalls).toBe(1) + expect(behavioralTurnCount(session.turns)).toBe(1) + expect(session.totalInputTokens).toBe(150) + expect(session.totalCostUSD).toBeCloseTo(0.15) + + await ensureCacheHydrated( + (range) => parser.parseAllSessions(range, 'hermes'), + aggregateProjectsIntoDays, + '', + parser.isSessionHydrationComplete, + ) + const stillSealed = await loadDailyCache() + const stillD = stillSealed.days.find(d => d.date === dayD.key) + expect(stillD?.inputTokens).toBe(100) + expect(stillD?.calls).toBe(1) + expect(firstProjects.length).toBeGreaterThan(0) + }) + + it('P2: same sessionId in default and coder are two cursors', async () => { + const started = localDay(0).unixSec + const rootDb = createHermesDb(hermesHome) + const coderDb = await createProfileHermesDb(hermesHome, 'coder') + withTestDb(rootDb, (db) => { + insertSession(db, { id: 'shared', inputTokens: 100, actualCost: 0.10, startedAt: started }) + }) + withTestDb(coderDb, (db) => { + insertSession(db, { id: 'shared', inputTokens: 80, actualCost: 0.08, startedAt: started }) + }) + + await parseDiscovered() + const ledger = loadHermesSessionLedger() + expect(getHermesCursor(ledger, 'default', 'shared')?.lastSeen.inputTokens).toBe(100) + expect(getHermesCursor(ledger, 'coder', 'shared')?.lastSeen.inputTokens).toBe(80) + + withTestDb(rootDb, (db) => { + updateSession(db, 'shared', { inputTokens: 130, actualCost: 0.13 }) + }) + const { calls } = await parseDiscovered() + const later = loadHermesSessionLedger() + expect(getHermesCursor(later, 'default', 'shared')?.lastSeen.inputTokens).toBe(130) + expect(getHermesCursor(later, 'coder', 'shared')?.lastSeen.inputTokens).toBe(80) + expect(calls.filter(c => c.deduplicationKey.includes(':obs:')).every(c => c.deduplicationKey.startsWith('hermes:default:'))).toBe(true) + }) + + it('P3: 150→0 last-seen 0 no observation; 0→40 one +40 weight-0 via discoverFromDb', async () => { + const started = localDay(-1).unixSec + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p3', inputTokens: 150, actualCost: 0.15, startedAt: started }) + }) + + const first = await parseDiscovered() + expect(first.sources.some(s => s.path.includes('p3'))).toBe(true) + expect(first.calls).toHaveLength(1) + expect(first.calls[0]!.deduplicationKey).toBe('hermes:default:p3') + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.lastSeen.inputTokens).toBe(150) + + withTestDb(dbPath, (db) => { + updateSession(db, 'p3', { inputTokens: 0, actualCost: 0 }) + }) + const zeroed = await parseDiscovered() + expect(zeroed.sources.some(s => s.path.endsWith('#hermes-session=p3') || s.path.includes('hermes-session=p3'))).toBe(true) + expect(zeroed.calls.filter(c => c.deduplicationKey.includes(':obs:'))).toHaveLength(0) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.lastSeen.inputTokens).toBe(0) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations).toHaveLength(1) + + withTestDb(dbPath, (db) => { + updateSession(db, 'p3', { inputTokens: 40, actualCost: 0.04 }) + }) + const grown = await parseDiscovered() + const deltas = grown.calls.filter(c => c.deduplicationKey.includes(':obs:')) + expect(deltas).toHaveLength(1) + expect(deltas[0]).toMatchObject({ + inputTokens: 40, + costUSD: 0.04, + supplementaryAccounting: true, + tools: [], + userMessage: '', + }) + expect(deltas[0]!.costIsEstimated).toBe(false) + expect(deltas[0]!.deduplicationKey).toBe('hermes:default:p3:obs:1') + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations).toHaveLength(2) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations.some(o => o.inputTokens < 0)).toBe(false) + }) + + it('P4: explicit $0 actual is recorded, not LiteLLM fallback', async () => { + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p4', inputTokens: 80, actualCost: 0, startedAt: localDay(0).unixSec }) + }) + const { calls } = await parseDiscovered() + expect(calls).toHaveLength(1) + expect(calls[0]!.costUSD).toBe(0) + expect(calls[0]!.costIsEstimated).toBe(false) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p4')?.lastSeen.costBasis).toBe('actual') + }) + + it('P5: seed from a cached lifetime call does not dump lifetime at now', async () => { + const started = localDay(-1) + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p5', inputTokens: 100, actualCost: 0.10, startedAt: started.unixSec }) + }) + + const parser = await loadParser() + const ledgerMod = await import('../../src/hermes-session-ledger.js') + parser.clearSessionCache() + await parser.parseAllSessions(undefined, 'hermes') + + await unlink(ledgerMod.hermesSessionLedgerPath()) + ledgerMod.resetHermesSessionLedgerForTests() + + parser.clearSessionCache() + await parser.parseAllSessions(undefined, 'hermes') + const seeded = ledgerMod.loadHermesSessionLedger() + const cursor = ledgerMod.getHermesCursor(seeded, 'default', 'p5') + expect(cursor?.observations).toHaveLength(1) + expect(cursor?.observations[0]?.supplementaryAccounting).toBe(false) + expect(cursor?.observations[0]?.inputTokens).toBe(100) + expect(dateKey(cursor!.observations[0]!.timestamp)).toBe(started.key) + }) + + it('P6: unwritable ledger is retryable and does not advance lastComputedDate', async () => { + const dayD = localDay(-1) + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p6', inputTokens: 100, actualCost: 0.10, startedAt: dayD.unixSec }) + }) + await mkdir(hermesSessionLedgerPath()) + + const parser = await loadParser() + parser.clearSessionCache() + await parser.parseAllSessions(undefined, 'hermes') + expect(parser.isSessionHydrationComplete()).toBe(false) + + const { ensureCacheHydrated, loadDailyCache } = await import('../../src/daily-cache.js') + await ensureCacheHydrated( + (range) => parser.parseAllSessions(range, 'hermes'), + aggregateProjectsIntoDays, + '', + parser.isSessionHydrationComplete, + ) + const daily = await loadDailyCache() + expect(daily.lastComputedDate).not.toBe(dayD.key) + expect(daily.complete).not.toBe(true) + }) + + it('P7: first observation key stays hermes:default: with no :obs:', async () => { + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'p7-id', inputTokens: 10, actualCost: 0.01, startedAt: localDay(0).unixSec }) + }) + const { calls } = await parseDiscovered() + expect(calls[0]!.deduplicationKey).toBe('hermes:default:p7-id') + expect(calls[0]!.deduplicationKey.includes(':obs:')).toBe(false) + expect(calls[0]!.turnId).toBe('p7-id:session') + expect(calls[0]!.supplementaryAccounting).toBeUndefined() + }) + + it('P8: calculated-cost growth stays estimated on fresh and warm-cache reads', async () => { + const started = localDay(-1).unixSec + const dbPath = createHermesDb(hermesHome) + withTestDb(dbPath, (db) => { + insertSession(db, { id: 'calc-est', inputTokens: 100, startedAt: started }) + }) + + const first = await parseDiscovered() + expect(first.calls).toHaveLength(1) + expect(first.calls[0]!.deduplicationKey).toBe('hermes:default:calc-est') + expect(first.calls[0]!.costIsEstimated).toBe(true) + expect(first.calls[0]!.costUSD).toBeGreaterThan(0) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'calc-est')?.lastSeen.costBasis).toBe('calculated') + + withTestDb(dbPath, (db) => { + updateSession(db, 'calc-est', { inputTokens: 150 }) + }) + const grown = await parseDiscovered() + const deltas = grown.calls.filter(c => c.deduplicationKey.includes(':obs:')) + expect(deltas).toHaveLength(1) + expect(deltas[0]!.deduplicationKey).toBe('hermes:default:calc-est:obs:1') + expect(deltas[0]!.inputTokens).toBe(50) + expect(deltas[0]!.costUSD).toBeGreaterThan(0) + expect(deltas[0]!.costIsEstimated).toBe(true) + expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'calc-est')?.observations[1]?.costBasis).toBe('calculated') + + const parser = await loadParser() + parser.clearSessionCache() + const fresh = await parser.parseAllSessions(undefined, 'hermes') + const freshCalls = fresh.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls))) + const freshBaseline = freshCalls.find(c => c.deduplicationKey === 'hermes:default:calc-est') + const freshDelta = freshCalls.find(c => c.deduplicationKey === 'hermes:default:calc-est:obs:1') + expect(freshBaseline?.isEstimated).toBe(true) + expect(freshDelta?.isEstimated).toBe(true) + expect(freshDelta?.costUSD).toBeGreaterThan(0) + + const warm = await parser.parseAllSessions(undefined, 'hermes') + const warmCalls = warm.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls))) + const warmBaseline = warmCalls.find(c => c.deduplicationKey === 'hermes:default:calc-est') + const warmDelta = warmCalls.find(c => c.deduplicationKey === 'hermes:default:calc-est:obs:1') + expect(warmBaseline?.isEstimated).toBe(true) + expect(warmDelta?.isEstimated).toBe(true) + expect(warmDelta?.costUSD).toBeGreaterThan(0) + }) +}) diff --git a/tests/providers/hermes.test.ts b/tests/providers/hermes.test.ts index b8d0db8a..7cb6e10c 100644 --- a/tests/providers/hermes.test.ts +++ b/tests/providers/hermes.test.ts @@ -28,6 +28,10 @@ beforeEach(async () => { cacheDir = await mkdtemp(join(tmpdir(), 'hermes-provider-cache-')) originalHermesHome = process.env['HERMES_HOME'] originalCodeburnCacheDir = process.env['CODEBURN_CACHE_DIR'] + process.env['HERMES_HOME'] = tmpDir + process.env['CODEBURN_CACHE_DIR'] = cacheDir + const { resetHermesSessionLedgerForTests } = await import('../../src/hermes-session-ledger.js') + resetHermesSessionLedgerForTests() }) afterEach(async () => { diff --git a/tests/usage-aggregator-billable-output.test.ts b/tests/usage-aggregator-billable-output.test.ts new file mode 100644 index 00000000..c7627572 --- /dev/null +++ b/tests/usage-aggregator-billable-output.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it, beforeAll, vi } from 'vitest' + +import { buildMenubarPayloadForRange } from '../src/usage-aggregator.js' +import { getDateRange } from '../src/cli-date.js' +import { loadPricing } from '../src/models.js' +import type { ProjectSummary } from '../src/types.js' + +const ts = new Date().toISOString() + +function makeCall(provider: string, outputTokens: number, reasoningTokens: number) { + return { + provider, + model: provider === 'codex' ? 'gpt-5.4' : 'grok-4', + usage: { + inputTokens: 0, + outputTokens, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens, + webSearchRequests: 0, + }, + costUSD: 0, + savingsUSD: 1, + savingsBaselineModel: 'gpt-4o', + tools: [], + mcpTools: [], + skills: [], + subagentTypes: [], + hasAgentSpawn: false, + hasPlanMode: false, + speed: 'standard' as const, + timestamp: ts, + bashCommands: [], + deduplicationKey: `${provider}-sav`, + } +} + +const emptyCat = { turns: 0, costUSD: 0, savingsUSD: 0, retries: 0, editTurns: 0, oneShotTurns: 0 } + +function fixtureProjects(): ProjectSummary[] { + const grok = makeCall('grok', 10, 3) + const codex = makeCall('codex', 10, 3) + return [{ + project: 'proj', + projectPath: 'proj', + sessions: [{ + sessionId: 'sess-billable', + project: 'proj', + firstTimestamp: ts, + lastTimestamp: ts, + totalCostUSD: 0, + totalSavingsUSD: 2, + totalInputTokens: 0, + totalOutputTokens: 20, + totalReasoningTokens: 6, + totalCacheReadTokens: 0, + totalCacheWriteTokens: 0, + apiCalls: 2, + turns: [{ + userMessage: 'hi', + timestamp: ts, + sessionId: 'sess-billable', + category: 'coding', + retries: 0, + hasEdits: false, + assistantCalls: [grok, codex], + }], + modelBreakdown: {}, + toolBreakdown: {}, + mcpBreakdown: {}, + bashBreakdown: {}, + subagentBreakdown: {}, + categoryBreakdown: { coding: { ...emptyCat, turns: 1, savingsUSD: 2 } }, + skillBreakdown: {}, + }], + totalCostUSD: 0, + totalSavingsUSD: 2, + totalApiCalls: 2, + }] as unknown as ProjectSummary[] +} + +vi.mock('../src/parser.js', async (importOriginal) => { + const mod = await importOriginal() + return { ...mod, parseAllSessions: vi.fn(async () => fixtureProjects()) } +}) + +describe('buildMenubarPayloadForRange: localModelSavings billable output', () => { + beforeAll(async () => { + await loadPricing() + }) + + it('writes per-call billableOutputTokens into byModel.outputTokens', async () => { + const payload = await buildMenubarPayloadForRange(getDateRange('today'), { provider: 'all', optimize: false }) + const byModel = payload.current.localModelSavings.byModel + const grok = byModel.find(m => m.outputTokens === 13) + const codex = byModel.find(m => m.outputTokens === 10) + expect(grok).toBeDefined() + expect(codex).toBeDefined() + expect(grok!.outputTokens).toBe(13) + expect(codex!.outputTokens).toBe(10) + }) +})