mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
37 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2fc62f7876
|
0.9.25: correctness, energy, menu bar and installer fixes (#1511)
* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed; codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate; openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp; sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty); codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+ grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export subfolder; providers pane fixed window; Warp credit-based cost. Desktop/menubar: unified flame logo; default DMG; docs signed+notarized. * menubar: one running instance, self-relaunch on language change The single-instance guard only retired strictly older copies, so two login items starting in the same instant both survived, and a copy whose bundle identity did not survive install was never seen at all. The decision is now total (newest launch wins, ties break on pid) and peers are matched on bundle id or executable name. --keep-both opts one launch out. Language changes no longer have the desktop app quit and reopen the menu bar, which made macOS attribute the new process to the desktop app and re-ask for the data-access grant. The menu bar relaunches itself via the existing remote command key; older menu bars that do not watch the key fall back to the old path after 5s. * desktop: export toast shows the saved path; resource buckets on app_close The export toast showed the folder that was picked, not the dated subfolder the files land in. The handler already parsed the CLI's saved line; it now returns that path and the toast uses it. app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb to its answer frames. Unmeasured figures are omitted, never sent as zero. * menubar guard never leaves zero instances; installer replaces in place; JSON export into folder Guard: an unreadable launch date on either side could make two copies retire each other. Unreadable peers now count only when their pid is lower, and a copy that cannot read its own date retires lower pids only, so a disagreement keeps at least one instance. Installer: an existing bundle in /Applications or ~/Applications is replaced where it lives instead of a second copy being added. The old bundle is moved aside and restored on any failure; a cross-volume move falls back to a copy that is re-verified with codesign. An unwritable location is never escalated: the install goes to ~/Applications and the leftover is named. Export: -o pointing at an existing folder writes the JSON inside it. Short sessions omit the cpu buckets. setLanguage reopens the menu bar if its own relaunch never comes back. AppRelaunch passes the bundle path as an argument. * menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install Guard: launch dates could be unreadable and pid order can disagree with start order after pid reuse, so two copies could still retire each other. Ordering now uses the kernel-reported process start time, which both sides read identically. A copy whose start time cannot be read is left out, so the worst case is two menu bars, never none. Installer: with the only copy in an unwritable /Applications, a plain run tried to open a path that did not exist. It now opens the installed copy. A placement killed mid-way is recovered on the next run, a concurrent install is refused, and a failed restore names where the previous bundle is. Process matching uses the exact executable name. Export: a trailing separator names a folder. Telemetry cpu is measured from telemetry start. * installer: a recycled pid can no longer block installs; language change waits for the replacement process An aside left by an earlier install counted as an active install whenever its pid was live, so once that pid was reused every install was refused for good. It now also has to be recent (ctime within 10 minutes), a pid we may not signal is not ours, the refusal names the file, and an orphan that cannot be cleared is reported instead of aborting the install. setLanguage confirmed the relaunch with a matcher the dying process still satisfied, so the reopen fallback never fired. It now waits for a pid that was not running before. * desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers An open window ran act report (a fresh CLI process each time), yield and an optimize scan on every refresh. The headline poll now passes --no-optimize and takes the snapshot path; act report refreshes on mount, on manual refresh and every 10 minutes, yield every 5. The optimize scan runs at most once a day per query scope, is stored in userData with its time, and is forced fresh by the Optimize page or a manual refresh. Figures that are not live show their age, and no stored scan means no savings clause rather than a zero. On battery the live interval doubles; the chosen cadence stays the base. * desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch The scan cache is keyed on the argv, which says 'today' or '30days', not a date, so yesterday's scan was served as today's. It is now reused only on the same local day. Stored findings in Signals carry their age, a failed scan shows the error instead of scanning forever, and the cold-boot label uses the time the app received the payload. usePolled fetched immediately whenever its interval changed, so every power transition (and launching on battery) refetched every live hook and could spawn an extra act report. Fetching and timer arming are now separate effects. Optimize's yield is on the same 5 minute tier as Overview. * desktop: re-ask for the optimize scan on the first render of a new local day An app left open across midnight kept yesterday's stored savings under Today, because the scan was only requested on mount, scope change or manual refresh. The local day is now one of the hook's triggers; the previous day's figure is dropped while the new scan runs. * serve: a menubar poll is never answered from the status snapshot Inside its settle window the status snapshot returns the pre-change payload on purpose. The resident serve process then memoized that answer as clean, so after a single write followed by quiet the headline stayed on the old figure until the next write or the five minute memo cap. The snapshot is for one-shot runs; the resident process already holds the parsed state, so it now skips it. * tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card ServeConnection takes its pid file as a parameter, so the Swift tests no longer share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the reaper only signals a record that is a serve --stdio command. Superseded session-cache, codex-results and cursor-results files (100MB+ each) are removed once untouched for 14 days, at most once a day. daily-cache and the hermes ledger are never swept: they carry sealed days a version bump adopts. The menu bar installer's leftover-copy advice is emitted as a marked line under CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is debug only. The app's vitest workers turn off Node's built-in web storage. * menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows tray. It now follows the desktop's telemetry.v1.json when that exists (read only: same install id, same on/off, onboarded required) and otherwise keeps its own state with the same region default (off in EU/EEA/UK/CH and when the region is unknown). Settings gains one Privacy toggle, disabled when the desktop owns the choice. Events use the tray's names; the daily usage snapshot is the CLI's block passed through a sanitizer and is left to the desktop when it is the consent source. Debug builds never send. A resident CLI that gets disabled for the run now says so in the log. * menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away The sender used URLSession.shared, so a server or CDN cookie and the default User-Agent rode along and would have outlived an opt-out. It now owns an ephemeral session with no cookies, no cache, a fixed agent string and no redirects. A batch that is out when the toggle goes off is dropped rather than re-queued under the fresh id. The desktop's answer is recorded locally, so a missing or damaged state file never falls back to the region default, and the standalone id is persisted when minted. The toggle stays usable as a local off switch under desktop consent. Copy states what this app actually sends. * vercel gateway spend is shown on its own row and kept out of totals by default The gateway reports daily aggregates per model, with nothing to match against the local tools that were pointed at it, so every headline counted that traffic twice. Totals now leave the gateway slice out when all providers are shown; the row keeps its full amount and is marked not in total, --provider vercel-gateway is unchanged, and codeburn gateway-totals include folds it back in. The daily cache still stores the slice, so the choice applies retroactively. Reports with no gateway credential are byte-identical. The gateway's request_count now feeds the call count instead of each daily row counting as one call. Hermes: a mid-session price change lands on the day it is observed and sealed days are never rewritten; stated in the code and changelog. * gateway exclusion applies to every report through the parse, and the detail panels follow the headline The first pass narrowed only the day totals, so By tool, top models, top projects, activities, status json projects and any project-filtered table still carried gateway spend next to a headline that did not, and By tool shares could pass 100%. The rule now lives in parseAllSessions: with all providers in scope and the opt-in off, aggregate-only sessions are dropped after the memo, and the callers that derive cached days opt out so stored slices are unchanged. day.projects is reduced like models. The gateway stays visible once, as a labelled not-in-total row with no share, and standalone reports note the excluded amount on stderr so machine output is unchanged. * dashboard: the background history index follows the gateway exclusion too The index keeps the whole corpus so it can fill the daily cache, but its per-period projection handed that unfiltered list to the project, model and activity panels, so they regained gateway spend once the index landed. * ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits The cache-lock step failed 6 of the last 60 runs with no output for five minutes after the vitest banner; passing runs take 12-18s on every Node version. Each attempt is now capped at 90s and retried once, with a warning whenever that happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn status snapshot test and the c6 parser suite get limits taken from those runs, each with its reason. Both test jobs print their ten slowest cases. * desktop: Privacy & data uses the same rows as the rest of Settings The pane mixed two static claims with two controls in its own layout. It now uses the about-row pattern every other pane uses: title and hint on the left, one control on the right. The claims became the subtitle. Rows: anonymous usage statistics (toggle, link to what is sent), device sharing state with Manage, local report snapshots with Clear, export with Open export. * desktop: Privacy & data keeps one bounded column and rows that never squeeze The card stretched with the window, stranding each control hundreds of pixels from its text. This pane's heading, subtitle and card now share a 760px column and one text measure. Rows stack on their own width, because the window can never be narrow enough for the old viewport rule to fire; row buttons do not wrap. The what-is-sent link sits on its own line, and the snapshot and export descriptions fit their measure and say this machine. * menubar tests clean up their scratch defaults and leave the real Keychain alone Four test files never removed their UserDefaults suites and the rest removed the domain but left the plist, so thousands of files piled up in ~/Library/Preferences. A shared helper forgets a suite and deletes its file, and every test that makes a suite now uses it. cfprefsd still rewrites an empty plist when the test process exits, so a run leaves about a hundred 42-byte files with no test data in them. The real-Keychain round trip only runs with CODEBURN_TEST_REAL_KEYCHAIN=1. * desktop: the resident parser retires after 15 idle minutes and restarts on demand The renderer stops polling while the window is hidden, but the serve child stayed resident with its parsed cache, one to two GB on a large corpus. After 15 minutes without a request it is stopped the way a settings restart stops it, without spending the unexpected-death budget, and the next request starts a new resident through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or disables it. * desktop: every settings pane keeps a bounded column, and dark buttons have an edge Cards stretched with the window, so on a wide display controls sat up to 1300px from their labels and intro lines ran past 140 characters. All panes now share one left-aligned column (760px, 980px for projects, aliases and pricing, which hold wide rows) and one text measure. Rows stack on their own width instead of a viewport rule the 900px minimum window could never reach, and a long path in Projects no longer overflows the pane. In dark mode the secondary button matched or sat below its surface, and was invisible on the plugin install dialog. It gets a face and a border from two new tokens; light is unchanged. The onboarding consent label matches Settings. * desktop: this device shows its fingerprint on its own line The local name and the fingerprint are two adjacent inline spans, so they read as one run of text. * menubar: the resident parser retires after 15 idle minutes and restarts on demand The menu bar kept its serve child, and the parsed cache with it, for the whole run, even with the popover closed and nothing changing. After 15 minutes without a request the child is retired without counting as a death, and the next request starts a new resident through ensureStarted, never the one-shot fallback, whose snapshot settle window would make the figure lag a whole tick. The window sits above the longest gap between real requests, so a child stays warm while work is happening. CodeBurnServeIdleSeconds tunes or disables it. * serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced With a session being written, every poll re-listed about 2,400 directories and re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month shard (49MB on a large corpus) and read it back on the next poll. The resident process now reuses the previous listing and fingerprints for paths its root watcher proves untouched, and falls back to the full sweep whenever the watcher is missing, unhealthy, overflowed, armed after the sweep, does not cover the path, the memo is older than 4.5 minutes, or the process was suspended. Shard publication is held for up to 90s and flushed when stdin closes; a held write is dropped rather than written over something another process published. One-shot runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence; time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete, rename-over, in-flight, watcher overflow and unhealthy watcher. Changelog: state the telemetry default as it is in this version. * a retired parser gets to publish its held shards, and durable providers are never held Both apps retired the serve child with SIGTERM before its stdin-close flush could run, so every retire discarded the coalesced window. They now close stdin, give the child a bounded grace to publish and exit, and signal it only if it is still running; a settings restart does the same. Measured: flushed 0/5 before, 5/5 after, for both clients. copilot's cache entries are the only record once Copilot prunes its own files, so a held window that was dropped (retire, crash, kill -9) before the source was pruned lost that spend for good. A window that a durable provider dirtied is published on the poll that parsed it, as before coalescing existed. The RSS guard publishes a held window before it clears the caches instead of discarding it. * serve: release the lifetime parse after the fill, and make the collection real The RSS guard dropped its memos and then called globalThis.gc, which exists only under --expose-gc; no launcher passes it, so the collection had never run and the freed pages never went back. On a cold start the resident idled at 2.2GB with 364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by 700MB. After the background fill has sealed its summaries the process now publishes any held shard window, drops the memos it can re-read from disk (the cold start had loaded the cache with scope 'all', which then served every later poll), and collects; it collects again a minute later for as long as a pass returns 64MB, at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are leaf-identical cold and warm, time-to-reflect unchanged, a released month scope reloads in 0.3-0.5s. * warp: the billed cost reaches reports and survives the cache The provider derived a dollar cost from Warp's own billing record (provider cents, charged usage, or credits), but warp was missing from the reported-cost pass-through, so the cached call kept no cost and every report, cold or warm, priced the conversation from its tokens. A fixture billed at $1.22 reported $0.15. A call whose cost came from a billing record now keeps it; a call that only has the token floor stores none and is still re-priced when prices change. Warp entries re-parse once (provider parse version), and the daily cache moves to v34 so days whose Warp source still exists re-derive; call counts do not move, so nothing is double counted or dropped. * openclaw and pi: a reported cost survives the cache like every other reported cost Both providers read the cost their tool recorded for a message, and both were missing from the reported-cost pass-through, so reports priced every call from tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013 against $0.410 (pi). A call with a reported cost now keeps it; a call with none, or an explicit zero, stores none and is still re-priced when prices change. omp had been added to the list in #1150 and pi, the same parser, was never revisited. The provider list is one named set, the unreachable providerCallToTurn is gone, and both providers re-parse once; the v34 daily cache re-derives their days with call counts unchanged. * test: pin parse count per report and per resident poll |
||
|
|
5fe803440a
|
feat(cli): filter usage by billing route and mode (#1486)
* feat(cli): filter usage by billing route and mode Carry provider-observed billing provenance through Hermes and the session cache, register the real OpenRouter route, and add call-level route/billing filters to models, sessions, export, and audit. Keep unknown billing unclassified, preserve existing pricing, and repair legacy included Hermes ledger baselines without rewriting genuine multi-observation history. * feat(opencode): preserve OpenRouter route provenance Carry OpenCode providerID through legacy SQLite, v2, file, and session-rollup paths so OpenRouter calls remain distinct from direct traffic. Invalidate OpenCode and KiloCode caches and cover strict route matching. * feat(opencode): classify Amazon Bedrock route Map OpenCode's exact amazon-bedrock providerID to the existing metered Bedrock route, including model families that cannot rely on Anthropic/OpenAI ID shapes. Invalidate OpenCode and KiloCode caches across the route expansion. * docs(opencode): document billing route provenance --------- Co-authored-by: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> |
||
|
|
724b9f3621
|
feat(models): carry the billing route on the call and key model rows on it (#1448)
The same model billed through a different door is its own row on every surface. The route rides on the call as a field: the model id names it when the door renames the model (Bedrock's <vendor>.<model>[-vN:M], with the cross-region profile kept as its own SKU), and the provider's own column names it when it does not (Hermes billing_provider). Only bedrock is registered; openrouter and bedrock-mantle wait for real sessions. Every report keys a model row on one function, modelRowKey: short name plus the door's label. models-report folds on that row key rather than the route id, so two doors sharing one label can never print two rows a reader cannot tell apart. codeburn models --format json carries route per row. Daily cache moves to v33: day.models is keyed by the row key so a column-sourced route survives into a finalized day, and hermes joins the pending-rederive table. Hermes sessions re-parse once. Pricing never consults the route and runs on the raw id. granular-history still keys on the raw model id, so the desktop Trend timeline is the one surface outside this. Verified on a real cache: 142 finalized days, $37,898.851498 and 272,985 calls unchanged. |
||
|
|
b79cf40169
|
fix(omp): correct OMP period scoping, cost attribution, and Grok 4.6 prompt tiers (#1150)
* fix(omp): surface nested agent activity * fix(omp): retain reported agent costs * refactor(omp): remove unused message field * fix(status): refresh OMP agent payloads * Fix Grok 4.6 prompt tier pricing * fix(omp): retain timestamps and reprice zero costs * Test aliased Grok tier overrides * refactor(omp): extract tier/model helpers, pass structured subagent fields - models.ts: pull the Grok 4.6 high-tier swap into tieredCostsFor() so the next tiered model extends one branch instead of copy-pasting the inline condition in calculateCost. - pi.ts: extract the message-model resolution chain into resolveMessageModel(); document the zero-reported-cost heuristic (OMP writes cost.total = 0 for xai-oauth, so zero acts as absent). - usage-aggregator.ts: stop formatting a display string into the OMP subagent row's name field; the payload carries agentName plus the structured fields (model, startedAt, token counts) and the menubar formats its own label. Removes the now-unused compactTokenCount. --------- Co-authored-by: AgentSeal <resham0209@gmail.com> |
||
|
|
d4ed055265
|
feat(parser): capture provider-recorded session lineage (CB-1 slice 1) (#1140)
Wire the SessionLineage field on SessionSummary and CachedFile. The relationship is captured ONLY when a provider writes it on disk in a durable form: a child file that names its parent (Claude's transcript-internal sessionId on a sidechain; Kimi Code's state.json agents[<id>].parentAgentId for any non-main agent), or a parent file whose spawn / child manifest names the children (Claude's agentSpawnLinks; Kimi Code's state.json agents map listing any non-main entry). The brief forbids inference from time adjacency or directory layout, so a parent whose only evidence is the child file living under its directory does not yet qualify, and stays lineage-less. Per provider: - claude: child (parentSessionId present) or root (agentSpawnLinks non-empty). Captured at install time and through the append-merge in scanProjectDirs, where lineage is sticky and cached-first. - kimicode: child (parentAgentId === 'main') or root (sibling non-main entry alongside the main agent). state.json is read by kimicodeLineageForSource, called from the per-provider install path. Bump PROVIDER_PARSE_VERSIONS for both providers to session-lineage-capture-v1 so already-cached sessions gain the new field on the next cold parse (env fingerprint change forces the re-parse; the field is purely additive, no cost / token / call total moves). Invariant: byte-identical report totals with and without the field. The new parser-lineage-capture test asserts this on a Claude corpus (parent + two children) and covers Claude two-sided linkage, Claude one-sided (child file names parent while parent's spawn result was compacted away), Kimi Code nested subagent (child and root variants), no-evidence (no lineage field at all, not 'unknown'), and the cache round-trip across a warm-disk reload. Co-authored-by: codeburn <dev@codeburn.local> |
||
|
|
ee6d614557 |
merge: rematch #1123 onto main after #1121
Keep both cachedCallToApiCall spreads: nanoAiu from this PR and supplementaryAccounting / Hermes observation keys from #1121. |
||
|
|
0c7d92a312 |
feat: Copilot AI Credit plan math from total_nano_aiu
Spent credits are finite nanoAiu / 1e9. Token-priced costUSD does not fill the Copilot bar. Thread nanoAiu through cachedCallToApiCall with no cache-version bump. |
||
|
|
8446d3f81e |
fix(hermes): keep post-finalization session growth on the observation day
Hermes rows are lifetime totals stamped at started_at. After a day is sealed, later growth was dropped. A sidecar ledger records last-seen totals per (profile, sessionId) and emits weight-0 observation-time deltas so sealed days stay put while today's growth still lands. Closes #916 |
||
|
|
f060a2d806 |
Merge origin/main into feat/copilot-session-store-landing
Resolved against main's newer invariants: - daily-cache: DAILY_CACHE_VERSION/MIN_SUPPORTED -> 21. Main shipped 19 (#1015 grok); 18 was burned by this branch's earlier public head and 20 is claimed by the unmerged #1040, and isMigratableCache would adopt either as finalized without re-deriving. Header keeps main's v19 note and adds v21's. - session-cache: PROVIDER_PARSE_VERSIONS keeps main's grok/dsh entries and appends this branch's `-session-store-v2` to main's copilot value. - parser: durable age-out takes main's orphan-only rule (#992). retainWhilePresent is now redundant under it rather than load-bearing. - audit-report: both imports (isBehavioralCall + sanitizeModelForDisplay). - tests/parser (e), (l), (sc): re-pinned to the orphan-only age-out. A still-discovered >90d copilot events.jsonl now keeps serving its per-turn output alongside the store rows; the (sc) age-out subject is now an orphan. - daily-cache-version-rederivation: seed 20 so the adjacent-draft-version case is what the test pins. - scripts/upgrade-path: expected daily cache filename -> v21. |
||
|
|
a5a0ddaeac
|
feat(copilot): read per-request input/cache from session-store.db
The Copilot CLI and the GitHub Copilot desktop app both write ~/.copilot/session-store.db unconditionally; its assistant_usage_events table holds one row per API request. Until now input/cache tokens for these surfaces came only from the session.shutdown rollups in events.jsonl, which are written only on clean shutdown (a crash loses the whole leg's input/cache accounting) and lump each session leg into one per-model total. The rollup also RESETS its counters at in-session compaction (traced on a clean single-process 107-request session whose sole rollup covered exactly its five post-compaction requests), so even cleanly-closed long sessions were truncated; on a long-history machine the store recovered ~35% of real Copilot spend lost to crashes and compaction resets. The DB rows are per-request, crash-proof, and carry real timestamps. The store's input_tokens is cache-INCLUSIVE (input + cache_read + cache_write), the same convention as the shutdown rollups — verified against each row's token_details_json and by reconciling per-session sums against the CLI's own footers and rollups across two machines (1,380+ rows, 8 models, CLI 1.0.70–1.0.79, schema_version 6): every divergence was a rollup gap. Emitted calls mirror the shutdown-call contract: input/cache/reasoning only, output 0 — per-turn output stays owned by the events.jsonl assistant.message calls. Rollup-vs-store precedence is RECONCILED at serve time, per (session, model), and only there. Both representations always parse and cache; parseProviderSources aggregates the cached calls and, wherever store rows exist for a (session, model), drops the rollup calls and serves the rows plus per-leg RESIDUAL calls: each rollup leg subtracts only the rows in its own interval — rows commit strictly before their leg's shutdown line, so a leg at time T covers exactly the rows in (previous leg's T, T] — and any remainder (per token component, floored at zero) serves once at that leg's own timestamp. A store missing requests a leg covered — adopted mid-session, rows pruned before ever being read — therefore still serves that tail exactly once ON THAT LEG'S DAY, a crash-tail row the rollup never saw can never cancel it, and a complete store serves pure per-request granularity with every residual retired to zero. The decision reads only cached contents, never discovery: deleting or resetting the store changes nothing served, so finalized daily history can never flip on an absence epoch; cached rows of a deleted store remain the record until the 90-day orphan age-out (which exempts still-discovered paths). The serve set is the one coherent snapshot — nothing a writer does between discovery and a parse can change what one pass sees — and read-time precedence heals persisted duplication (stale epochs, runtimes without node:sqlite, restored files) instead of preserving it, following the buildDurablePeriod pattern. Store rows and rollups carry supplementary accounting weight. A rollup (or its residual) is aggregate accounting, never a request: zero api-call/model-call/turn weight, tokens and cost fully retained. A store row is one real request, but when it pairs with a served per-turn call it is supplementary too; rows pair with same-model per-turn calls by timestamp adjacency (monotone matching, tight 2-minute window — the two are written at the same completion moment, and a wide window would let a crash-only row pair against a neighbor whose own row is missing), computed once over the FULL serve set so a date-range boundary that separates a row from its call cannot double the request across adjacent day queries. Only the unpaired rows — store-only requests, exactly where crash-lost requests sit — count. Supplementary-only turns fold into the nearest behavioral turn within 30 minutes; with no behavioral turn to fold into they stay separate weightless turns, each on its own day, with apiCalls 0 — and the session emission gate admits usage-bearing zero-call sessions. The weight propagates into the daily cache: aggregateProjectsIntoDays applies the same rule to every calls counter and category-turn count it seals, so v19 history and live summaries can never disagree about what was a request. A changed source whose read defers on the busy shape (locked, EACCES, corrupt mid-replace — discovery still emits the source; only true absence or a schema mismatch reads as absent) now marks session hydration incomplete, so the daily backfill holds its watermark instead of finalizing a day the deferred rows never reached; an unchanged unreadable store defers nothing. The verdict travels with its result — the 180s memo and the serve burst-reuse restore the hydration verdict their cached data was parsed under, so a memoized partial parse cannot inherit a later parse's complete — and a discovered source whose FINGERPRINT cannot be read (EACCES on a present file) defers instead of silently skipping, while a genuinely deleted file stays a silent skip. Copilot reasoning tokens are no longer double-billed at the report layer: they are a subset of the output the per-turn calls already price, and copilot joins claude in the reasoning-inside-output case of the query-time cost recompute. Store dedup keys are content-discriminated — copilot-store:<sid>:<rowId>:<fnv1a64(created_at|tokens|model)> — because AUTOINCREMENT prevents id reuse only within one database lifetime: a same-path DB reset reusing row ids now mints new keys instead of the durable union swallowing the new usage, while a byte-identical re-insert still collapses (64-bit: 32-bit FNV collisions between plausible token tuples are constructible). Every call of a session serves under one project label resolved at serve time — the session-state-derived label when the serve set knows it, else the store rows' own — so neither rows cached before events.jsonl existed nor an events.jsonl orphaned by a session-state prune can split the session across two grouping keys. CODEBURN_COPILOT_SESSION_STORE_DB is read but deliberately NOT fingerprinted, per the #927 ruling (any copilot fingerprint change drops cached entries whose path still exists, destroying pruned history only the cache holds); the read is allowlisted in the #927 guard, and serve-time reconciliation makes repointing safe without a fingerprint — the new store's rows parse on sight and the old path's entries persist as durable orphans. The copilot parse version appends session-store-v2 and the daily cache bumps v17 → v19: per-day attribution, call counts and costs all change against pre-store builds. 19, not 18: an earlier pushed head of this PR already claimed v18 under different accounting, and the carry-forward would adopt those days as finalized without re-deriving them. Verified by A/B on snapshots of two real stores, a live SIGKILL crash test (row present, no rollup, tokens recovered exactly), live resumes whose warm-cache deltas matched new rows to the token, upgrade-healing at 4,800-session scale, and serve-level regressions pinning every maintainer finding from six review rounds: the rows-then-shutdown race, stale-cache healing, age-out exemption, absence-epoch identity, progressive row landing with residual retirement, behavioral weight across all four pinned scenarios, the hydration fence, project unification in both directions, the same-path reset, mixed coverage (crash tail vs covered-leg gap), multi-leg residual day attribution, range-invariant pairing, memo-scoped hydration verdicts, and the fingerprint-failure fence. |
||
|
|
7187dd0da0 | fix(optimize): exclude sidechains from session heuristics (#974) | ||
|
|
a6bf81f756 | feat(codex): add tool-excluded active throughput metrics | ||
|
|
2eb4718122
|
sessions: correlate cross-provider work with pull requests (#792) | ||
|
|
8e1caae33a
|
sessions: fold subagent runs into PR attribution (#791)
Some checks are pending
CI / semgrep (push) Waiting to run
* sessions: fold subagent runs into PR attribution Sidechain (subagent) session cost never reached the by-PR view, so a session orchestrated on one model with subagent lanes on another showed only the parent model on every PR row. Fold each sidechain's cost, calls, models, and categories into the parent turn that spawned it, so it inherits that turn's PR set under the existing turn-level state machine. Linkage, in priority order: the spawn result's toolUseResult.agentId pairs the child's agent id with the Agent/Task tool_use id that launched it (recorded per turn), which is the true launch point and wins even when the child's first activity landed during a later turn; else the child's first-activity timestamp is bucketed into the containing turn span; else the child folds into the parent's unattributed spend. Children of parents that referenced no PR, and orphans whose parent is absent from the scan, contribute nothing, unchanged. Cache v6 to v7 (neither shipped, so one combined bump from v5): per-turn spawnToolUseIds, per-file parentSessionId and agentSpawnLinks; the validator and the append/compact paths thread them like prRefs. By-PR footers now count parents plus folded subagent runs and the payload gains an additive subagentSessions field. distinctCost now includes folded subagent spend, documented in the payload comment. * sessions: address adversarial review of subagent PR attribution Rework child attribution to resolve each subagent to the PR its launching turn was working on, using the parent's UNFILTERED turn data, and enforce that every dollar is counted exactly once. - Mutual exclusion: a child that referenced its own PR attributes standalone and is never folded; a child with no links is folded only. Fixes a double-charge where a self-linking child was both folded and self-attributed. - Recursion: a fold aggregates a child plus its non-self-linking descendants (depth-first, cycle-guarded), so grandchildren spawned by subagents reach the PR report. - Global linkage: the subagent index keys by parentSessionId alone (UUIDs are globally unique), so a child whose worktree resolves to a different project still links. - Date-range correctness: spawn-to-PR sets are built at assembly from the full turn list, so a spawn in a pre-range turn attributes to the right PR; a PR-linked parent whose own turns fall out of range is kept as a 0-cost fold anchor so its in-range child is not lost. - Timestamp fallback compares epoch ms (mixed UTC offsets order right) and is end-bounded: a child active after the parent's last turn is unlinked (contributes nothing), matching orphan semantics. - Cache adoption tries the newest prior versioned file (v6 then v5) so the preceding build's expired-PR history survives the v7 bump; an invariant note requires the list to cover every version that can exist on disk. - Spawn-result pairing matches the tool_result block that carries the agentId, not the first block, when a record batches several results. - resolveSubagentAttribution is computed once and shared by aggregateByPr and prLinkedTotals. subagentSessions now counts folded subtrees (children plus descendants). Verified on real data: attributed + unattributed reconciles to cost, and parent-only cost plus folded-children cost equals the folded total to the cent (no double-count). * sessions: round-2 hardening of subagent PR attribution Address a second adversarial review of the new machinery. - ID collision: parents and a child's parent reference are keyed by provider + sessionId, not bare sessionId. When two distinct parents still share a key (true duplicate/imported data), the child folds into NEITHER (deterministic skip, stays standalone): correctness over coverage. - Recursion dedup is global: one claimed-set spans all of a parent's direct children, so a descendant reachable through two paths (a diamond or duplicate id) folds exactly once and a parent-link cycle terminates. - Cache adoption migrates every prior version oldest-to-newest and MERGES per source path (newer wins per entry), so a sparse or partial newer file no longer masks older-only expired-PR orphans. - Fold anchors (0-cost PR-linked parents kept only for attribution) live in a new ProjectSummary.subagentAnchors, never in `sessions`, so they no longer contaminate session counts, averages, or any per-session report. Folded PR rows take their date span from the contributing child activity rather than the anchor's empty timestamps. - One-pass buildPrAttribution computes rows and totals together; the payload builder and CLI call it once. Drops the identity-keyed memoization, which could return stale folds if the array was mutated. - Ambiguous multi-block spawn-result pairing leaves the spawn link unset on purpose; the child then folds via the timestamp fallback rather than pairing with the wrong id or disappearing. Every fix is mutation-verified. A fresh real-data drive re-proves the no-double-count identity to the cent (parent-only cost plus folded cost equals the folded total) and that the PR rows sum to attributedCost. * sessions: round-3 hardening of subagent PR attribution Third adversarial review pass. - Ambiguity counts ALL candidate parents (and anchors) sharing a provider+sessionId key, not just PR-bearing ones, and uses a per-record fingerprint: a key carried by more than one DISTINCT record folds its child/subtree into NEITHER (identical duplicates still fold once). This unifies the parent-collision and duplicate-descendant rules and is deterministic across input order. - Project-rebuilding filters (by day, by date range, by config source) now carry subagentAnchors through, and a date filter CONVERTS a spawn parent whose in-range turns are all filtered out into an anchor so a surviving in-range child still folds. Rebuilt sessions also keep their PR + subagent-linkage metadata (prLinks, parentSessionId, spawnPrSets, ...), which buildSessionSummary otherwise drops, so by-PR and folding work on a filtered slice (menubar/dashboard flow). - Fold anchors leave ProjectSummary.sessions entirely and folded PR rows take their span from the child, so 0-cost anchors never touch session counts or averages. - Ambiguous spawn pairing (parent named the agent but its exact launching tool_use could not be paired) is recorded per parent; a late child of such a pairing folds to the parent's last turn within a 30 minute grace window, else stays unlinked. A truly-absent pairing gets no grace. - Row session key is NUL-delimited and provider-prefixed, so a project name or session id containing a space no longer collides and undercounts distinct sessions. Every fix mutation-verified. A fresh real-data drive re-proves the no-double-count identity to the cent, and a day-filtered drive proves the filter fix end to end (anchors created, subagents fold, identity holds). * sessions: round-4 hardening of subagent PR attribution Fourth adversarial review pass. - sessionFingerprint now covers the COMPLETE linkage-relevant payload, not just headline stats: a canonical (sorted-key) serialization of agentSpawnLinks, spawnPrSets, prRefsAtRangeStart, ambiguousSpawnAgentIds, parent/agent identity, and the per-turn prRefs timeline. Two records that share an id and headline stats but map the child to different spawns/PRs now fingerprint DISTINCT, so the ambiguity rule fires and they fold into neither, deterministically rather than order-dependent first-wins. - A date/day filter recomputes prRefsAtRangeStart at the new slice boundary by replaying the original full turn sequence, instead of copying the wide range's value. A PR switch between the wide start and the slice start (July 1 A, July 10 B, slice July 20) now carries B, not a stale A; a turn exactly on the boundary stays in-slice and applies its own refs. The recompute selects by timestamp, so it is order-independent. Non-contiguous day selections are documented as treated contiguous from the earliest selected day (a single session-level seed cannot represent multiple segments; the menubar selection is a single day or a run). - The anchor-carry path drops an anchor that duplicates a surviving session id, so malformed merged input cannot double-count. Also: rebuilt filtered sessions were losing their PR/subagent-linkage metadata (a child its parentSessionId, a parent its prLinks), which carryLinkageFields now restores, so by-PR and folding work on any filtered slice. Every fix mutation-verified. A fresh real-data drive re-proves the no-double-count identity and reconciliation to the cent for both a lifetime scan and a day-filtered slice (anchors created, subagents fold through the filter). * sessions: round-5 hardening of subagent PR attribution Fifth adversarial review pass; closed-form fixes. - sessionFingerprint serializes the COMPLETE fold-determining state via a real recursive canonical encoder: session-level linkage AND, per turn in sequence, timestamp, prRefs, cost, calls, savings, and per-model cost. Object keys are sorted recursively and set-semantic arrays (PR-ref lists, ambiguous ids, spawnPrSets values) are sorted, while the turn list keeps order; the structure is emitted through JSON.stringify (no delimiter concatenation). Two same-id parents that differ only in a turn timestamp now fingerprint DISTINCT (fold neither), and records differing only in set-array order fingerprint EQUAL (no false ambiguity). - recomputeRangeStartPrRefs breaks an exact-same-millisecond tie deterministically by the lexicographically-last sorted-ref key, so the recomputed seed is stable regardless of turn order. - A day filter seeds EACH selected day's first ref-less turn by replaying the original full turn sequence up to that day's start (per-day seeding), so a PR switch on an UNSELECTED day between two selected days carries to the later day. Contiguous and non-contiguous selections are both correct. - The anchor dedupe drops an anchor only when a surviving session shares the full provider-aware, fingerprint-qualified identity (a proven duplicate): a different-provider or different-record same-id session no longer wrongly drops the anchor. Also fixed a double-count the fingerprint test exposed: two duplicate parent sessions share a key and the SAME resolved children, so folding is now done once per parent key. Every fix mutation-verified. Fresh real-data drives (lifetime, single-day, and a NON-CONTIGUOUS day selection) re-prove no-double-count and reconciliation to the cent. --------- Co-authored-by: reviewer <review@local> |
||
|
|
45e93129f2
|
sessions: attribute PR spend per turn instead of per session (#790)
* sessions: attribute PR spend per turn instead of per session The by-PR surfaces attributed a session's full cost to every PR it referenced, so one orchestration session that touched many PRs rendered identical full-session rows. Capture per-turn PR references during transcript parsing and attribute each turn's cost to the PR set active at that turn (split evenly across a multi-PR merge-sweep turn), carrying the most recent PR set forward across turns that reference nothing. Turns before the first reference form an unattributed bucket. A session whose transcript expired before per-turn capture keeps its session-level prLinks but has no per-turn refs; it falls back to an even whole-session split, and any row carrying such a portion is flagged approximate. Rows are now summable: the CLI and app footers report the attributed sum plus the unattributed remainder instead of a distinct-session total. Bumps the session cache version so surviving transcripts re-parse and populate the new per-turn field. Daily-cache versioning is untouched. * sessions: harden PR attribution and add models + category breakdown Addresses the review findings on the per-turn PR attribution and adds the model and task-category surfaces. Correctness: - Cache migration: the 5 -> 6 session-cache bump now adopts the prior v5 file's expired-source PR entries instead of abandoning them, and the claude scan preserves and surfaces PR-bearing orphans, so a session whose transcript was deleted still appears as a legacy even-split instead of vanishing. The daily cache is untouched. - Date-range carry: the parser captures the PR set active at the start of the in-range turn slice and seeds the state machine with it, so a PR referenced before the window still owns its later, in-range, ref-less turns instead of the session falling back to a whole-session approx split. - Calls are split across a multi-PR turn by largest-remainder, keeping per-PR counts whole (a 1-call, 2-PR turn no longer renders as 2 calls). - The CLI and app footers reconcile to the rounded row values actually shown. - Distinct sessions are keyed by project + sessionId, not sessionId alone. - The app tolerates an older by-reference payload (no attributedCost): it keeps the old non-summable footer and never renders NaN. Features: - Each PR contribution records the models of its calls and the turn's task category (split by the same share on a multi-PR turn); legacy even-split rows carry the model union but no category breakdown. - Payload rows gain models (short names, cost-desc) and categories (label + cost, cost-desc, omitted when empty); the payload gains otherPrCount/otherPrCost for the PRs beyond the sent top 20. - CLI --by-pr gains a Models column. The desktop table is now full-width with a Models column and click-to-expand rows showing a per-category cost breakdown with proportional bars, keyboard accessible, with an "Other (N more PRs)" row when capped. Tests: state-machine seed/models/categories/largest-remainder/dedup, the prRefs round-trip through the real incremental-append path (continuation + straddle), v5 adoption of an expired PR session, payload round-trip, and the desktop expansion/models/old-payload cases. * sessions: reconcile mixed PR rows, harden v5 adoption, bound models Round-2 review follow-ups. - Mixed legacy/live category breakdown: a PR row that combines an expired legacy contribution (even-split, no turn data) with a live per-turn contribution now emits an explicit "Legacy estimate (no per-turn detail)" category carrying the legacy share, so the expansion reconciles to the row cost instead of silently dropping it. A legacy-only row still shows no breakdown. - v5 adoption is now per cached file: one malformed entry is skipped instead of rejecting the whole v5 cache and dropping every valid expired PR session. - The desktop "Other (N more PRs)" line moved to the table footer as a muted, separated summary rather than a sorted row. - Row expansion resets when the PR set changes (period/provider/data), so a stale expansion cannot linger on a row that is gone. - Payload models per row are capped to the top 4 by attributed cost, with a name-ascending tie-break; categories get the same stable tie-break. Tests: mixed live+legacy reconciliation, legacy-only omission, model cap and tie-break, corrupt-plus-valid v5 adoption, and the desktop expansion-reset. * session-cache: validate optional agentType and failed during v5 adoption; app: reset PR expansion on period switch A v5 entry that was valid except for a malformed optional field (agentType, failed) passed per-file validation and flowed downstream as a non-string. The expansion reset keyed only on the row URL set, so a period switch that returned the same PRs kept a stale expansion open over changed numbers. --------- Co-authored-by: reviewer <review@local> |
||
|
|
a9d4471d17
|
payload: spend by pull request and by branch; desktop Pull requests tab (#788)
Some checks are pending
CI / semgrep (push) Waiting to run
Part 1 (src): expose two add-only, optional aggregations on the menubar payload's `current`, computed on the unscoped all-provider path from the surviving-session parse (carried history cannot contribute, as expected). - current.pullRequests: aggregateByPr rows (top 20 by cost) plus the multi-link-safe distinctCost/distinctSessions. Rows are by-reference, so they are never summed. - current.byBranch: new aggregateByBranch, per-branch spend (top 15 by cost) that carries each session's last-seen git branch forward across its turns. The cache stores a turn's branch only when it changes, so the parser now resolves the branch at reconstruction (before the date slice) and records SessionSummary.everHadBranch from the full transcript. That lets the report keep a branch-bearing session's pre-branch spend in an explicit null row even when the range clipped the anchor turn, while a provider that never captures a branch still contributes nothing. Part 2 (app): new "Pull requests" sidebar entry between Sessions and Spend (shortcuts reflow to number 8 for Plans). It renders the pullRequests rows as a refined table with the PR label linking out via openExternal, cost, sessions, calls and an active-date span, plus a footnote stating the distinct total and the by-reference attribution. A quiet explanatory line shows when no PR links exist, never a fake table. Tests: aggregateByBranch unit tests (carry-forward, null bucket, clipped anchor, by-reference session counts) and the Pull requests component tests (table, external link, footnote, both empty states). Nav-reflow assertions in Sidebar and App tests updated. Co-authored-by: reviewer <review@local> |
||
|
|
9676f53d0c
|
sessions: thread captured titles onto SessionSummary and the report (#782)
Same threading as prLinks: the cache-level title (last ai-title entry) rides onto SessionSummary in both the Claude and generic provider pipelines, and the sessions table gains a TITLE column (truncated at 38 chars, empty when a transcript never produced one, as subagent transcripts typically do not). JSON rows carry it verbatim. Groundwork for titles in the context browser, desktop Sessions view, and payload. Co-authored-by: reviewer <review@local> |
||
|
|
8676f0da01
|
sessions: spend per pull request via --by-pr (#780)
The rich session capture (#758) stores every PR URL a transcript references, but nothing displayed it. codeburn sessions --by-pr now groups spend by pull request: cost, savings, sessions, calls, and the date span per PR, sorted by cost, with a GitHub-shortened label and json output. Attribution is by reference, so a session that mentions several PRs counts fully toward each row; the footer reports the distinct-session total so overlapping rows are never mistaken for a grand total. prLinks now ride from the cached file onto SessionSummary in both the Claude pipeline and the generic provider path. Co-authored-by: reviewer <review@local> |
||
|
|
8ced2ed47f | feat(capture): parse-time capture of branch, LOC deltas, interruptions, titles, PR links | ||
|
|
3163ccb5c4
|
fix(report): surface estimated costs distinctly (#688)
* fix(report): surface estimated costs distinctly Providers that estimate tokens or price (kiro, cursor, warp, copilot, grok, hermes, codewhale, and the codex proxy path) set costIsEstimated on their parsed calls, but the flag died at the parser boundary: it was never carried onto ParsedApiCall or into the session aggregates, so a figure whose tokens were synthesized from content length rendered with the same authority as a metered one. Plumb the truth through, mirroring the savingsUSD/isLocalSavings pattern: a call-level boolean (ParsedApiCall.isEstimated, CachedCall.isEstimated, persisted so it survives the session-cache round trip) and an additive aggregate amount (estimatedCostUSD on the model breakdown, session, and project totals, plus PeriodData and the menubar payload). The amount is carried rather than a bare boolean so a row that is mostly metered with a small estimated slice is not indistinguishable from a fully guessed one. Display: report (TUI) and overview per-model rows prefix the cost with a tilde and print one legend line; the MCP tables carry the same marker and legend, and the machine surfaces (report --json, MCP get_usage, menubar / web payload) expose estimatedCostUSD. Totals math is unchanged; the flag is display/metadata only. Bump PROVIDER_PARSE_VERSIONS for every provider that sets the flag so already-cached sessions reparse once and pick it up. Copilot is excluded: it is a durable provider, so changing its env fingerprint would discard OTel cache entries whose source rows may already be pruned. Also fix the cross-provider project merge, which summed totalCostUSD but dropped merged-in projects' totalEstimatedCostUSD, undercounting the project/period estimated total (the same latent gap still affects totalSavingsUSD, left untouched here). * test(parser): pin estimated dollars through the cross-provider merge The merge fix for dropped totalEstimatedCostUSD was not covered: deleting the summing line left every test green. Extract the merge into an exported mergeProjectsByCrossProviderKey (no behavior change) and pin both the measured-plus-estimated and both-estimated merge cases. * docs(parser): honest merge-comment scope and load-bearing overwrite note Re-review nits: the merge doc claimed all additive totals are summed there while totalSavingsUSD still is not (pre-existing gap, tracked separately) and totalProxiedCostUSD is re-derived post-merge; say so. Mark the buildPeriodData overwrite in usage-aggregator as load-bearing for the estimated marker so nobody optimizes it away trusting the daily cache. |
||
|
|
4307542b62
|
feat(claude): account for /advisor escalations under the advisor model (#659)
* feat(claude): account for /advisor escalations under the advisor model Claude Code's advisor tool (/advisor) escalates hard decisions mid-turn to a stronger model. Those tokens are recorded inside message.usage.iterations as advisor_message entries with their own model and are excluded from the top-level message.usage totals. The parser read only the top-level totals, so advisor spend was silently dropped and never attributed to the advisor model. Emit a separate call per advisor_message iteration priced under the advisor model, preserve those iterations through entry compaction and the large-line (>32KB) byte-scanner path, and fold advisor cost into the guard budget. Bump the claude parser and guard cache versions so existing caches re-parse and pick up the advisor spend. * test(guard): pin advisor cost fold in the live budget The guard's advisor fold in computeSessionUsage had no test; dropping advisorCost from the line cost left all 30 guard tests green. Pins the fold (advisor line costs more than the same line without iterations) and the per-message replace semantics under streaming rewrites. |
||
|
|
6b6b6b8df6 |
feat(menubar): Claude config selector, hardened (supersedes #635)
Scopes the menubar to one Claude config for multi-config (CLAUDE_CONFIG_DIRS) setups, with All as the default. Rebased onto main and fixed the review findings from the original #635: - Fix a TS2206 build break (a 'type' modifier inside an import type block). - Reject --claude-config-source with a non-Claude --provider, and scan Claude only in the scoped branch (a config is Claude-only): fixes provider data leaking into a scoped query and avoids parsing every provider's corpus. - Scope the macOS menu-bar figure to the selected config (badge matched the popover), clear the selection when switching to a non-Claude provider tab, and stop the on-disk badge fallback from showing an unscoped number while scoped. - Tag Claude Desktop / Cowork sessions as their own 'claude-desktop' source so they are a selectable bucket instead of silently vanishing from per-config views (sum of options now equals All). - Skip the redundant Claude discovery walk for plain single-config users while keeping idle configs and Claude Desktop selectable. Reviewed by Codex 5.6; all findings addressed. Full suite: 1581 TS tests, 76 Swift tests, tsc clean. |
||
|
|
645b3c2bdd |
feat: add Hermes Agent provider
Reads session-level usage from Hermes SQLite state databases (~/.hermes/state.db and per-profile state.dbs). Tracks input, output, cache read/write, reasoning tokens, stored costs, tools, shell commands, and inferred projects. - Provider reads both root and profile state databases - Cost fallback: actual_cost_usd > estimated_cost_usd > LiteLLM pricing - inferProject filters to user/system messages only - Discovery query capped at LIMIT 10000 - sanitizeProject handles repeated leading separators - All five review items from PR #386 addressed - Tested against real Hermes data (557MB state.db with 198 sessions) Closes #368. Supersedes #386. |
||
|
|
f1bf7a197b |
feat(report): Claude-scoped agent-type breakdown
Some checks are pending
CI / semgrep (push) Waiting to run
Surfaces real subagent-transcript spend grouped by agentType (workflow-subagent / Explore / general-purpose / …), read from each agent's sibling .meta.json (cached on CachedFile; session cache bumped 3→4). This makes ultra/workflow usage visible — the existing Task-input-based "subagents" section never sees workflow agents. Shown in `report --format json` (claudeAgentTypes) and a "Claude Agent Types" dashboard panel that renders only when Claude agent transcripts exist, so it never appears for the other providers. |
||
|
|
e83160f415
|
feat(pricing): proxy-aware cost attribution for subscription-backed Claude (#417) (#459)
Claude Code routed through a GitHub-Copilot-backed proxy (ANTHROPIC_BASE_URL -> claude-code-over-github-copilot / claudegate) costs ~$0 marginal but was priced at full Anthropic API rates, producing a misleading cost figure. The JSONL records only the model name and no endpoint, so proxying cannot be auto-detected; the user declares it. Add a `proxyPaths` config (managed via a new `codeburn proxy-path` subcommand) listing project directories served through a subscription proxy. Sessions whose canonical path is under one keep their full API-rate totalCostUSD (the billable would-be figure is never destroyed) and additionally report totalProxiedCostUSD, so the JSON report overview exposes cost / proxiedCost / netCost (netCost = cost - proxiedCost). With no proxyPaths configured the new fields are 0 and every existing consumer is unchanged. Design: "full cost, flagged" was chosen over zeroing cost so a misconfigured or since-changed path can never silently erase real Anthropic spend. Attribution is project-level (one canonical path per project), computed in a single helper (summarizeProject) that all ProjectSummary builders route through, including the cross-provider merge in parseAllSessions (re-derived from the merged total so a repo used with both Claude and Codex stays correct). The in-memory session-cache key folds in a proxy-config hash so toggling proxyPaths in a long-lived process cannot serve stale attribution. Path matching is segment-boundary anchored (/foo does not match /foobar), trailing-slash and backslash tolerant, leading- slash agnostic (so a non-Claude provider's slash-stripped path matches the same way Claude's absolute path does), and case-folded only on case-insensitive filesystems (macOS/Windows, not Linux). The proxy-path CLI sanitizes a hand-edited config.json (non-array / non-string entries) rather than crashing. Tested: isProxiedPath matching matrix (boundary, case, Windows, empty, root, multi-path, leading-slash form); config-hash distinctness/order-independence; end-to-end attribution through parseAllSessions incl. the critical negative cases (real spend must not be zeroed); cross-provider Claude+Codex merge; Codex-only project under a proxy path; date-range-filtered attribution; cache-staleness after a config change; and the proxy-path CLI add/list/remove, malformed-config robustness, and the report --format json overview. Scope note: proxiedCost/netCost currently surface in `report --format json` only; wiring them into the TUI dashboard and menubar payload is a follow-up. |
||
|
|
8ded6ad6fd |
feat(cli): track local-model cost savings against a paid baseline (#421)
Add a new `localModelSavings` config and `codeburn model-savings` CLI that maps a local-model name (e.g. llama3.1:8b) to a paid baseline (e.g. gpt-4o). The local call still costs $0; the new `savingsUSD` field tracks the counterfactual spend avoided by running locally and is reported separately from `costUSD` everywhere a number is shown. * Parser normalization (`applyLocalModelSavings`) runs on Claude parse, direct provider calls, and the cached-call path. It forces `costUSD` to 0 and attaches `savingsUSD` + `savingsBaselineModel` + `isLocalSavings` on the `ParsedApiCall`. Local-savings wins for actual cost even when the same model is also in `modelAliases`. * Session, project, day, model, category, activity, skill, and subagent rollups all carry `savingsUSD` alongside `costUSD`. * `status --format json` adds `today.savings` and `month.savings`. * `status --format menubar-json` adds a `current.localModelSavings` block (totalUSD, calls, byModel, byProvider) plus savings on topModels, topProjects, topSessions, topActivities, and history daily entries. Schema fields default-decode for backward compat. * `report --format json` adds savings across overview/daily/ projects/models/activities/skills/subagents/topSessions, with the active paid baseline name on each model row. * `models` command gains a `Saved` column on table/markdown/CSV and a `savingsUSD`/`savingsBaselineModel` pair in JSON. Default `--min-cost 0.01` filter now ORs in `savingsUSD >= minCost` so local models with $0 actual cost but >0 savings still surface. * CSV/JSON exports add a `Saved (CODE)` column on summary/daily/ models/projects/sessions. * Dashboard TUI shows a green 'saved $X by local models' footer line in the overview when any savings are present. * macOS Swift payload gains a `LocalModelSavings` Codable block and savings fields on every model/activity/session/daily struct. Hero shows a green leaf 'Saved $X' caption, models section gets a green `Saved` column. `swift build` clean. * GNOME indicator adds 'saved $X' to the hero meta line and a `codeburn-model-saved` column to the model row. * Daily cache schema bumped to v8 (`savingsUSD` on day/model/ category/provider). `savingsConfigHash` invalidates the cache when the user changes their baseline mapping so historical saved-spend numbers never lie about a stale baseline. * Defensive `Object.hasOwn` lookup in `getLocalSavingsBaseline` blocks the prototype-pollution test that previously surfaced via the savings path with a hostile `__proto__` model name. * New tests (5 files, 25 tests, 549 lines) cover pricing helpers, end-to-end parser normalization, day aggregator savings, menubar payload savings, CLI set/list/remove, and daily-cache hash invalidation. Existing tests for daily-cache / day-aggregator / models-report updated for the new fields. Full vitest suite: 1028/1028 passing across 73 test files. `tsc --noEmit` clean. `npm run build` clean. (Note: `mac/Tests` has a pre-existing `no such module 'Testing'` environment error on the installed Swift toolchain, confirmed on `main` before this PR; not caused by these changes.) |
||
|
|
e472e37efd
|
File-aware retry detection with typed ToolCall (#379)
* Fix Antigravity provider detection, Codex fork double-counting, and tab ordering
Antigravity:
- Handle ephemeral port (--https_server_port 0) via lsof fallback
- Force reparse when cached turns are 0 (server may have been unavailable)
- Persist precomputed costUSD in session cache for correct pricing
- Map gemini-pro-agent to gemini-3.1-pro pricing
- Add display names for gemini-pro-agent and gemini-3.5-flash-low
Codex:
- Detect forked sessions via forked_from_id in session_meta
- Skip replayed parent events within 5s of fork creation time
- Use parent session ID in dedup key so parent+fork don't double-count
Menubar:
- Sort provider tabs by cost descending instead of enum declaration order
* Add tooling breakdowns to CLI dashboard and menubar
Surface skills, subagents, tools, and MCP server usage in both the
text dashboard and menubar app. Parse subagent types from Agent/Task
tool calls, aggregate with skills into a merged "Skills & Agents"
panel. Remove Top Sessions panel from CLI dashboard.
* Fix Codex always reporting 100% one-shot rate
Codex parser never set turnId or toolSequence, so retry detection
could not see Edit→Bash→Edit patterns across API calls. Now each
tool event builds a toolSequence step, and user messages generate
a new turnId to group calls into logical turns. Bump Codex cache
version to force re-parse of existing sessions.
* File-aware retry detection with typed ToolCall
Replace name-only Edit→Bash→Edit retry detection with file-aware
tracking. A retry now requires the SAME file to be re-edited after
a bash step, not just any edit after any bash.
- Add ToolCall type ({ tool, file?, command? }) replacing string[][]
for toolSequence across all types, providers, and cache
- Generate per-tool toolSequence in Claude parser with file paths
from Edit/Write tool inputs
- Extract file_path for Edit/Write tools in all three parser paths
(string, buffer, compact)
- Fix apiCallToCachedCall missing toolSequence (Claude data was never
cached with tool sequence info)
- Update Codex, Goose, Kiro parsers for typed ToolCall
- Bump session cache version to 3, codex cache version to 3
* Extract file paths from Codex patch_apply_end and function_call args
Codex stores file paths in patch_apply_end.changes keys and function
call arguments as a JSON string. Parse both to populate ToolCall.file,
enabling file-aware retry detection for Codex sessions.
* Fix retry detection fallback for file-less providers, update docs
- Use __no_file__ sentinel in countRetries so providers without file
paths (Kiro, Gemini, Vibe) fall back to name-based retry detection
- Reset pendingToolSequence on Codex dedup skip to prevent leak
- Update classifier tests to ToolCall[][] format
- Document file-aware one-shot rate in README
- Add unreleased changelog entries for tooling breakdowns and fixes
|
||
|
|
33b1abbbef
|
Add tooling breakdowns to CLI and menubar (#373)
Some checks are pending
CI / semgrep (push) Waiting to run
* Fix Antigravity provider detection, Codex fork double-counting, and tab ordering Antigravity: - Handle ephemeral port (--https_server_port 0) via lsof fallback - Force reparse when cached turns are 0 (server may have been unavailable) - Persist precomputed costUSD in session cache for correct pricing - Map gemini-pro-agent to gemini-3.1-pro pricing - Add display names for gemini-pro-agent and gemini-3.5-flash-low Codex: - Detect forked sessions via forked_from_id in session_meta - Skip replayed parent events within 5s of fork creation time - Use parent session ID in dedup key so parent+fork don't double-count Menubar: - Sort provider tabs by cost descending instead of enum declaration order * Add tooling breakdowns to CLI dashboard and menubar Surface skills, subagents, tools, and MCP server usage in both the text dashboard and menubar app. Parse subagent types from Agent/Task tool calls, aggregate with skills into a merged "Skills & Agents" panel. Remove Top Sessions panel from CLI dashboard. |
||
|
|
06f69484f3
|
Fix one-shot rate detection for all non-Claude providers (#355)
Some checks are pending
CI / semgrep (push) Waiting to run
* Add CodeBurn Pro Mac App Store app SwiftUI MenuBarExtra with litellm-snapshot pricing, Claude/Codex/Copilot parsers, session discovery, auto-refresh timer, and dashboard UI matching the real menubar design. * Add appstore/ to .gitignore Private Mac App Store build, not for the public repo. * Fix one-shot rate detection for Gemini, Vibe, Kiro, and Goose Gemini and Mistral Vibe now emit per-assistant-message calls grouped by user turn via turnId, so the classifier sees Edit->Bash->Edit as retries instead of independent one-shot turns. Kiro and Goose record per-message tool ordering via toolSequence for the same effect on aggregated sessions. Vibe now prefers meta.json.stats.session_cost over price-derived estimates. Session cache bumped to v2. Insight pill switcher scrolls horizontally instead of wrapping. Closes #351. * Remove dead geminiOrdinal variable and add toolSequence cache validation * Restore geminiOrdinal for idx fallback dedup key |
||
|
|
bd41fa3962 |
Add persistent disk cache for parsed session data
Some checks are pending
CI / semgrep (push) Waiting to run
Cache normalized turns/calls to ~/.cache/codeburn/session-cache.json so the CLI skips re-parsing unchanged JSONL files on subsequent runs. File reconciliation uses dev+ino+mtime+size fingerprinting; cost, classification, and summaries are recomputed at query time. Atomic writes via temp+fsync+rename, deep structural validation on load, per-provider env fingerprinting, and best-effort save so cache failures never break the CLI. ~6x speedup on warm cache. |
||
|
|
c85beeaeae
|
Fix Claude 1-hour cache write pricing (#317)
Co-authored-by: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Co-authored-by: iamtoruk <hello@agentseal.org> |
||
|
|
1a080a006f |
feat(optimize): MCP tool coverage detector with cache-aware costing
Adds a per-tool optimizer finding for MCP servers whose schema is loaded
on every turn but rarely invoked. Builds on the existing server-level
`detectUnusedMcp` (zero invocations) by reporting partial-use cases:
"loaded 54 tools, called 0" or "loaded 26 tools, called 2 (8% coverage)".
Inventory comes from Claude Code's JSONL `attachment.deferred_tools_delta`
entries: `addedNames` lists the exact tools available at that turn,
including every fully-qualified `mcp__<server>__<tool>` name. We union
across all delta entries in a session (not just the first) because tool
availability can change mid-session when the user reloads MCP config or
a subagent inherits a different tool set. Names that don't match the
`mcp__<server>__<tool>` shape with both segments non-empty are rejected
at extraction so downstream `split('__')` consumers can't be poisoned.
Token-savings estimates are cache-aware. MCP tool schemas live in the
cached prefix of the system prompt: a session pays the full input price
on each cache-creation turn (rebuilds happen every ~5 minutes of
inactivity) and the cache-read discount on subsequent turns. Each call's
contribution is capped at its observed `cacheCreationInputTokens` /
`cacheReadInputTokens` so we never claim more MCP overhead than the
call's own cache buckets could contain.
When multiple servers are flagged, costing happens in a single combined
pass: the per-call cap applies to the total unused-schema budget across
all flagged servers, not per server. Two flagged servers cannot both
independently claim the same call's cache bucket, which would otherwise
overstate `tokensSaved` and misclassify findings as high impact.
A session counts toward `loadedSessions` (and toward the cost estimate)
only if its observed inventory included the server. Pure invocation-only
sessions, where the server appears in `mcpBreakdown` or `call.mcpTools`
without any matching `deferred_tools_delta`, do not satisfy the
`>= 2 sessions` threshold on their own. The same invariant applies in
`estimateMcpSchemaCost` so the two passes agree.
Coverage is computed against the inventory only: invocations of names
not present in any observed inventory (older config, hallucinated tool,
typo) do not inflate `toolsInvoked` and cannot drive `unusedCount`
negative. `toolsInvoked` is derived as `inventory.size - unusedTools.length`
to keep both numbers consistent.
`detectUnusedMcp` and the new detector are explicitly disjoint:
`detectUnusedMcp` skips servers that the coverage detector will report,
not every server that happens to be in any inventory, so a small
inventoried-but-uninvoked server below the coverage thresholds still
gets flagged as "configured but never called."
Thresholds for the coverage finding:
- > 10 tools available (small servers are noise)
- < 20% coverage
- >= 2 sessions with observed inventory
- High impact when total effective tokens >= 200_000 or >= 3 servers flagged
Smoke-tested on a real account: 7 servers flagged across 93 sessions
(`office-word-mcp` 0/54, `notebooklm-mcp` 0/38, `office-ppt-mcp` 0/37,
`excel-mcp-server` 0/25, `github-mcp-server` 2/26, `peekaboo` 3/22, plus
`claude_ai_Asana`). Combined-cap costing keeps `tokensSaved` honest.
Changes:
- src/types.ts: optional `mcpInventory: string[]` on `SessionSummary`.
Provider-agnostic field; currently populated only by the Claude parser.
- src/parser.ts: `extractMcpInventory` walks all entries, validates
fully-qualified names, returns sorted unique list. `buildSessionSummary`
passes it through; field is omitted when empty so JSON exports stay
clean.
- src/optimize.ts: `aggregateMcpCoverage`, `estimateMcpSchemaCost`
(single- and multi-server signatures), `detectMcpToolCoverage`. Wired
into `scanAndDetect`. `detectUnusedMcp` updated to disjoint with the
new detector.
- tests/mcp-coverage.test.ts: 23 cases covering aggregation, costing,
combined-cap behaviour, threshold gates, invocation-only-session
filtering, foreign-tool invocations, cache rebuild events, write+read
on the same call, multi-server pluralisation.
- tests/parser-mcp-inventory.test.ts: 12 cases for the JSONL extractor
including malformed name rejection and tolerant attachment parsing.
- CHANGELOG.md: entry under Unreleased / Added (CLI).
Closes #2
|
||
|
|
c16b21ec50 |
fix(classifier): surface skill name as subCategory for general turns (#203)
Turns whose only assistant tool is `Skill` collapse to category `general`
because `classifyByToolPattern` returns `'general'` and `refineByKeywords`
only operates on `coding`/`exploration`. In environments that lean on Claude
Code skills, the per-activity dashboard column flattens — every `/init`,
`/review`, `/security-review`, `/claude-api`, plus user-defined skills, all
land in `general` with no signal about which workflow ran.
Implements Option A from the issue:
- `ParsedApiCall.skills: string[]` populated in the Anthropic-path parser
via a new `extractSkillNames` helper that reads `input.skill || input.name`
from each `Skill` ToolUseBlock (mirrors `detectGhostSkills` extraction at
optimize.ts:765 so the two stay in sync).
- `ClassifiedTurn.subCategory?: string` set to the first skill name when the
resolved category is `general` AND any skill identifier was extracted.
Top-level category stays `general` — existing aggregations, exports, and
category-keyed code paths unchanged.
- `SessionSummary.skillBreakdown: Record<string, {turns,costUSD,editTurns,
oneShotTurns}>` populated in the same per-turn loop that builds
`categoryBreakdown`. Provider sessions (Codex/Cursor/etc.) keep `skills:
[]` — they don't expose the Skill tool surface today.
- Dashboard `ActivityBreakdown` renders top-N skill sub-rows beneath the
`general` row when present (indented `/skill-name`, dimmed). Other
categories render exactly as before; if no skills were invoked, the panel
is byte-identical to current output.
Existing 419 tests still pass. New `tests/classifier.test.ts` adds 8 cases:
single skill via `input.skill`, single via `input.name`, first-wins for
multi-skill turns, aggregation across multiple assistant calls in one turn,
no-name fallback (`subCategory` stays undefined), `Skill+Edit` promoting to
`coding` and dropping subCategory, non-Skill general turns, and a legacy
ParsedApiCall shape with `skills` field absent (forward-compat). Pre-fix
verification by stashing the source change reproduces 4/8 failures with the
exact "expected 'init', received undefined" diff; restoring → 8/8 pass.
Closes #203.
🤖 AI assistance disclosure: assistant-scaffolded by Claude (Opus 4.7);
author of record reviewed every line, ran the full vitest suite locally
(`npm test` → 32 files / 427 tests pass), `npx tsc --noEmit` clean, and
`npm run build` produces a clean ESM bundle.
|
||
|
|
391a235d1d |
feat: multi-provider support (Codex + provider plugin system)
Add Codex (OpenAI) as a second provider alongside Claude Code. Provider plugin architecture makes adding future providers (Pi, OpenCode, Amp) a single-file addition. - Provider interface: types, session discovery, stateful JSONL parsing - Codex parser: token_count dedup, tool normalization, model resolution - TUI: press p to cycle All/Claude/Codex with 1-min cache for instant switching - CLI: --provider flag on report, today, month, status, export commands - Pricing: Codex model fallbacks, fixed fuzzy matching for gpt-5.4-mini - Menubar: per-provider cost breakdown when multiple providers detected - 27 tests (10 new: Codex parser, provider registry, tool/model mapping) |
||
|
|
6d8c8643a0 | feat: extract bash commands and add bashBreakdown to session summary | ||
|
|
d20281514c |
feat: one-shot success rate per activity category
Detects edit/test/fix retry cycles (Edit -> Bash -> Edit) within each turn. Shows 1-shot percentage in the By Activity panel for categories that involve code edits. Updated screenshot and README. Fixes #4 |
||
|
|
00afed6930 |
v0.1.0 - initial release
Interactive TUI dashboard for Claude Code token observability. 13-category task classifier, per-project/model/tool breakdowns, gradient bar charts, SwiftBar menu bar widget, CSV/JSON export. |