Commit graph

1079 commits

Author SHA1 Message Date
Resham Joshi
0b81ecf676 Merge remote-tracking branch 'origin/main' into fix/codex-goose-kimi 2026-11-06 07:32:47 -08:00
Resham Joshi
2c0eacaea4
fix(pricing): no price across a model version boundary, long-context tier in why, Droid versions kept, Qwen cached tokens once, Hermes reasoning once (#1902)
* fix(pricing): stop the prefix price fallback at a minor version boundary

An unlisted minor version (claude-opus-4-9) took the bare-major row
(claude-opus-4, an older and 3x pricier generation) and counted as priced.
The longest dash prefix now decides: when the rest starts with a 1-2 digit
segment, the same boundary display names use, the id stays unpriced instead
of falling to that row or any shorter one.

* fix(why): price token classes at the call's long-context tier

The per-class split, the hand-back, cache saving, carry and prefix estimates
and the one-tier-down reprice priced without the provider and on a slice of
the prompt, so Claude calls above the long-context threshold split into parts
that added up to a fraction of the call cost. Each slice now takes the tier
its whole call's prompt decides.

* fix(droid): keep the minor version of undated model ids

The trailing-index cleanup meant for custom models ran on every id, so
claude-opus-4-6 was stored and priced as claude-opus-4 (3x) and
claude-haiku-4-5 as an unpriced claude-haiku-4. Only custom ids lose a
trailing number now; others lose only a date. The droid parse version moves
so cached sessions re-parse.

* fix(qwen): stop billing cached prompt tokens twice

promptTokenCount includes cachedContentTokenCount, as in Gemini CLI, so
cached tokens were billed at the full input rate and again at the cache-read
rate. Fresh input now subtracts them. The qwen parse version moves so cached
sessions re-parse.

* fix(hermes): stop counting reasoning tokens twice

Hermes stores output tokens as the API reports them, reasoning included, so
the calculated cost and every output total added reasoning on top. Hermes
joins the providers whose output already holds reasoning, and the calculated
basis prices output alone.

* fix(why): count one-hour cache writes in the tier prompt

calculateCost tiers on the larger of the cache write and its one-hour part,
so a slice priced for a call whose prompt is mostly one-hour writes has to
use the same size.

* fix(qwen): count thoughts once whichever backend reported them

Qwen Code's usage keeps Gemini field names but not one convention: Gemini
reports thoughtsTokenCount beside candidatesTokenCount, while the
OpenAI-compatible, Responses and Qwen OAuth converters put reasoning inside
candidates. Like Qwen Code's own outputTokenCount, a total that lies between
candidates and candidates plus thoughts decides the output; otherwise thoughts
are added as before. The qwen parse version moves again.

* fix(hermes): rebuild ledger cursors that double-counted reasoning

Hermes costs live in the session ledger, so the reasoning fix alone left
every recorded calculated cost overstated. Ledger v4 carries the v3 cursors
and marks those whose calculated observations hold reasoning tokens. The
next snapshot a still-present state.db row supplies replaces such a cursor
with one observation at the recomputed cost; the hermes parse version moves
so every session re-parses once and supplies that snapshot.

Sessions whose source row is gone get no snapshot and keep the v3 figure.
Days the daily cache already sealed also keep their old Hermes totals, as
no DAILY_CACHE_VERSION bump is part of this change.

* fix(why): normalise token counts before picking the tier

calculateCost clamps negative and non-finite counts to zero before it sizes
the prompt, so the tier prompt for a slice does the same; otherwise a corrupt
negative count could price the parts in a lower tier than the call.

* fix(qwen): follow Qwen Code's own rule when the total cannot decide

Without a total in the band, Qwen Code's outputTokenCount falls back to the
auth type: thoughts are inside candidates for openai, openai-responses and
qwen-oauth, beside them otherwise. The auth type rides on user records'
executionContext. Records without one keep thoughts out, the conservative
side Qwen Code's own cost ledger also takes.

* fix(qwen): clamp cached tokens to the prompt before pricing

A record reporting more cached tokens than its prompt billed the excess at
the cache-read rate. Cached now never exceeds the prompt it is part of.

* docs(hermes): say why a gone session keeps its v3 ledger cost

A ledger cursor stores token totals and cost but never the model; a session
whose state.db row is gone is already reported under model unknown. Without
a rate, the reasoning share of its calculated cost cannot be taken out, so
it keeps the v3 figure.

* fix(qwen): clamp cached tokens to zero as well as to the prompt

A negative cached count raised fresh input above the prompt and sent a
negative cache read on. Cached now stays within [0, prompt], and a negative
prompt reads as zero.

* fix(qwen): take the auth type per user record, not per file

Qwen Code stamps each user record's executionContext with the auth type in
force at that moment (chatRecordingService getExecutionContext), and it can
change mid-session. A user record without one now leaves it unknown instead
of inheriting the previous record's.

* fix(droid): strip a trailing eight-digit segment only when it is a date

Any terminal eight-digit run came off as a date. Only a valid YYYYMMDD with
a year from 2020 to 2035 is stripped now; model-12345678 keeps its name.

* test: pin the droid, qwen and hermes parse-version bumps

Each bump is what makes cached sessions re-parse under a pricing fix, and
nothing else fails if one is reverted.
2026-11-06 16:31:15 +01:00
Resham Joshi
72ea2067dc fix(codex): count tool-call output toward a null-ping estimate
A turn whose only output is a tool call (no assistant text) reached the
null-info ping with no pending output, so the ping rule dropped it and a
priceable request vanished. A function or custom tool call's name and
arguments now count as pending output, so such a turn keeps one estimated
call. Owner data: 0 such turns (706 null pings, none after a tool-only
turn), so no real figure moves.

Restart threshold stays at a tenth. All 10 real total drops fall to at most
0.3% of the prior total; none lies between 0.3% and 100%, so any cut in
that range is a judgement. A tenth keeps a 30x margin on the real resets,
while the half rule double counted corrections; a reset to 25% (8800 ->
2200) reads as a correction and undercounts, which no real rollout shows.
2026-11-06 06:32:33 -08:00
Resham Joshi
8eca0cdc9e fix(codex): require a total to fall to a tenth before reading a restart
At half, 8800 -> 4400 still read as a restart and emitted 4000/400. A
restart now needs the total to fall to at most a tenth; anything less is a
correction.
Rule evidence: owner data has 0 cumulative-only records and 10 total drops,
all with every field falling to <=0.3% of the prior total, so a tenth keeps
a 30x margin.
2026-11-06 06:22:53 -08:00
Resham Joshi
f595cc614d fix(codex): key a parent on the id forks reference, ahead of session_id
Dedup keys took session_id before id, so a parent whose session_id differs
from its id kept its own records apart from a fork that names it by id, and
replays past the burst double-counted. Prefer id, falling back to
session_id and then the file stem.
Owner data: all 410 forks with a parent present name the parent's id; 1436
of 1441 metas carry both fields and 5 differ, all forks (keyed on the
parent), so no parent here has a differing pair; the test pins the rule.
2026-11-06 06:22:08 -08:00
Resham Joshi
ea69a08ffb fix(codex): key cumulative calls on resolved totals
An omitted cumulative field reads as unchanged, but the dedup key still
took it as 0, so {input:150,total:160} and the same record with an
explicit unchanged output:10 got different keys. Key on the resolved
running totals so both forms share one key.
2026-11-06 06:17:09 -08:00
Resham Joshi
bfd3437236 fix(codex): read a small cumulative drop as a correction, not a restart
Any drop in the total counted as a restart, so 8000/800 -> 7900/790 emitted
a second 7900/790 call. A restart now needs the total to fall to at most
half; a smaller drop is a correction and adds nothing.
Rule evidence: owner data has 0 cumulative-only records and 10 total drops,
all with every field falling to <=0.3% of the prior total (4 at a new
task, none at a compaction).
2026-11-06 06:16:43 -08:00
Resham Joshi
ca4df66d27 fix(codex): let measured usage replace every ping estimate of the turn
Only the latest ping estimate was tracked, so two text-then-ping pairs
followed by one measured record left the first estimate counted. Track
all of the turn's ping estimates and fold them all into the measured call.
Owner data: 1 of 1,441 rollouts has a ping after output, alone in its task
with no measured usage after it, so this changes no real figure.
2026-11-06 06:02:32 -08:00
Resham Joshi
eadfaca49c fix(codex): drop a ping estimate even when the turn's measured record is a duplicate
Measured usage replaced the turn's ping estimate only after the dedup check,
so a measured record already counted elsewhere (a fork replaying its
parent's response) returned early and left the estimate counted on top.
Fold the estimate back before the dedup check.
2026-11-06 06:02:04 -08:00
Resham Joshi
4ac00d3986 fix(codex): let measured usage replace a ping estimate of the same turn
A null-info ping written after assistant text became an estimated call
even when the turn's measured usage record followed, so the turn counted
twice and the measured call lost its prompt. Keep the ping's estimate only
until measured usage for the same turn and task arrives; then fold its
prompt, tools and edit counts into the measured call and drop it.
2026-11-06 05:54:39 -08:00
Resham Joshi
591cecc6f4 fix(codex): key cumulative calls by restart epoch
After a counter restart the running totals can climb back to a state seen
before it (100/10 -> restart 50/5 -> 100/10), and the third record reused
the first record's dedup key and was dropped. Count restarts per rollout,
carry the count across append resumes, and add it to the cumulative key
once a restart has happened.
2026-11-06 05:53:53 -08:00
Resham Joshi
deb6b3b297 fix(codex): start every counter from zero on a restart
A restart record that left out a counter kept that counter's pre-restart
value as the baseline, so the next record's usage for it was swallowed
(8000/800 -> restart 3000 -> 6000/300 counted no output). On a detected
restart every baseline returns to zero, reported or not.
2026-11-06 05:53:27 -08:00
Resham Joshi
63de339cdc fix(codex): detect a counter restart from the total, not from any single field
Any one cumulative field that fell was read as a restart, so a corrected
component counted its whole running value again (output 800 -> 790 under a
rising total emitted 790 output). Decide the restart on the total falling,
or every reported field falling when no previous total exists; otherwise a
falling field is a correction and adds nothing.
2026-11-06 05:50:56 -08:00
Resham Joshi
fd8c228e36 docs(goose): cite where Goose writes its UTC timestamps
Goose's session_manager.rs creates sessions with CURRENT_TIMESTAMP and
bumps updated_at with datetime('now'), both zoneless UTC text. The test
fixture now declares the same column defaults.
2026-11-06 05:49:11 -08:00
Resham Joshi
bb390cba9c fix(codex): read an omitted cumulative field as unchanged
A cumulative-only record that left out a counter reset its previous value
to zero, so the next record that reported it again counted the whole
running total a second time. Treat an omitted field as no change, both for
the delta and for the running baseline (fork replay seeding too). Also note
why a ping-only turn yields no call and why one thread's resumed rollouts
share the cumulative dedup key.
2026-11-06 05:48:53 -08:00
Resham Joshi
fa231c3eed fix(kimi): give subagent wire logs a session id scoped to their session
A subagent's wire log took its directory name (agent-1, ...) as the
session id. Those names repeat across sessions, so subagents of different
sessions merged into one session, and without a message_id their dedup
keys collided and later sessions' calls were dropped. Prefix the parent
session directory.
2026-11-06 04:48:12 -08:00
Resham Joshi
a5f806a659 fix(goose): read SQLite timestamps as UTC
Goose stores session times as SQLite CURRENT_TIMESTAMP text
('2026-10-01 23:30:00', UTC without a zone). Date parses that shape as
local time, so outside UTC every session moved by the offset and could land
on the wrong day or month. Normalize the zoneless shape to UTC before
parsing; strings with their own zone pass through.
2026-11-06 04:47:50 -08:00
Resham Joshi
7ecf573e5e fix(codex): read a dropping cumulative-only total as a counter restart
Rollouts without last_token_usage are priced from cumulative deltas. When
the running total fell (resume, compaction) the delta went negative and
output and reasoning sums shrank. A counter below its previous value now
counts what it holds as the usage since the restart.
2026-11-06 04:47:13 -08:00
Resham Joshi
4b15470a5f fix(codex): do not turn a turn-start rate-limit ping into a call
Codex writes a token_count with null info (a rate-limit snapshot) at turn
start, before any usage exists. With a prompt pending it became an
estimated call that took the prompt, so the measured call that followed
had an empty prompt. Estimate a null-info record only once assistant
output is pending; otherwise keep the prompt for the measured call.
2026-11-06 04:46:42 -08:00
Resham Joshi
a1284a4234 fix(codex): key rollouts that carry only payload.id on that thread id
Codex builds before session_id was written name the thread only as
payload.id. Those rollouts keyed their calls on the file stem while a fork
keys its replayed history on the parent's UUID, so replays written after
the burst never collided and were counted twice. Read payload.id (also in
the compact decoder for oversized metas) before falling back to the stem.
2026-11-06 04:45:07 -08:00
Resham Joshi
c357b6ce63
fix(guard): stop blocking normal test loops and polling, and keep the stop out of the agent's hands (#1895)
Some checks are pending
CI / semgrep (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / vscode (push) Waiting to run
* fix(guard): count consecutive failures so a test-edit loop is not stopped

A passing run resets that command's failure count and an edit resets all
of them; only back-to-back failures of one command reach the retry stop.

* fix(guard): do not count polling a background task as a loop

BashOutput, TaskOutput and Monitor repeat the same input by design while
waiting, so they never reach the identical-call warn or stop.

* fix(guard): tell only the user how to lift a stop

The deny reason reaches the model, so it no longer names 'codeburn guard
allow' or the guard.json threshold; that hint moves to the systemMessage
the user sees.

* fix(guard): allow without an id names its session and refuses when ambiguous

The cache now keeps the session's cwd. 'codeburn guard allow' prints the
session it lifts (id, cwd, cost) and exits 1 with the candidates listed
when more than one session wrote its cache in the last five minutes.

* fix(guard): prune session caches and allow markers after 30 days

writeCache checks at most once a day and removes per-session files left
untouched for 30 days; an allow marker stays while its session is live.

* fix(guard): write the session cache via temp file and rename

Parallel tool calls run PreToolUse hooks concurrently; an in-place write
could be read half-done, parse as empty and reset the warned flags.

* fix(guard): retry the cache rename on Windows sharing errors

A rename over a cache another hook has open fails with EPERM/EBUSY/EACCES
on Windows; retry with a short backoff, then write in place so the hook
never throws.

* fix(guard): keep the previous cache when the rename keeps failing

An in-place fallback write could be read torn and reset the warned flags.
After the retries the old cache stays, and readCache retries once on a
parse failure before starting over.

* fix(guard): word the Stop retry count as the longest streak

The count is the session's longest run of failures, which an edit may
since have broken. Also cite the hook contract at deny().

* test(guard): prove the rename without an inode check

ext4 can hand the freed inode number straight back on a rename, so count
rename calls and check the last payload won instead.

* fix(guard): treat a sleep-then-check command and calls whose results keep changing as waiting, not looping

A Bash command that starts with sleep is waiting on CI or a server and
never counts toward the loop. Other identical calls count only while
their tool results stay the same; a changing result is progress.

* fix(guard): exempt a sleep only when what follows is a read-only check

'sleep 0; npm test' repeated forever no longer escapes the loop counter.
The part after the sleep must be read-shaped, or a gh view/list/checks/
status/diff/watch call, which the shared read list leaves out.

* fix(guard): only a successful edit resets the retry counts

An edit is held pending until its tool result lands; one that errored,
like an old_string that did not match, changed no code and leaves the
failure counts alone.

* fix(guard): a sleep followed by a bare echo is a wait

'sleep 150 && echo waiting' is a blind timer wait. An echo with no
redirection, chaining or substitution now counts as a read-only check
after a sleep. The echo and gh read patterns also stop at a newline, so
a second command on the next line still counts.
2026-11-06 13:28:42 +01:00
Resham Joshi
5c162600e8
fix(optimize): stop archiving used commands, match MCP servers the way Claude Code names them, count each saving once (#1898)
* fix(optimize): count slash commands named with their leading slash as used

A slash command shows up in the transcript as <command-name>/review</command-name>.
commandNames kept the slash, so "/review" never matched the defined command
"review": every command the user actually ran was reported unused and the apply
plan archived it. The leading slash is now stripped.

commandNames produces stored facts, so FACTS_VERSION goes to 2 and the
optimize facts store rebuilds once on the next run.

* fix(optimize): name MCP servers the way Claude Code namespaces their tools

Claude Code turns every character outside letters, digits, "_" and "-" into
"_" when it builds tool names, so a server "docs.local" is called as
mcp__docs_local__*. Config names were only mapped ":" -> "_", so such a server
was reported as never called and offered for removal, counted twice by the
deferral check, and shown with 0 calls by the alwaysLoad check. One helper,
mcpNamespace, now applies the full rule in the config loader, the local server
names and the remove plan's key lookup.

* fix(optimize): charge a never-called MCP server's schema once

A configured server that was never called is in unused-mcp, and the same
schema was charged again by mcp-deferral-off (unpinned) or
mcp-alwaysload-hygiene (pinned), so potential savings and the share of spend
summed it twice. The servers unused-mcp reports are now passed to both checks
and left out there.

* fix(act): recommend a default model only for Claude Code projects

The model-default plan writes "model" into <project>/.claude/settings.json,
which only Claude Code reads. A Codex project got a gpt model recommended and
apply-model wrote it there, so Claude Code in that project started on a model
it does not know. recommendModelDefault now returns nothing for a non-Claude
provider.

* fix(optimize): read the bash output cap from the settings env block first

Claude Code takes BASH_MAX_OUTPUT_LENGTH from the env block of its settings
files. The check only read shell profiles (lines with export) and the process
env, so a cap of 10000 set in settings.json still reported the 30K default and
the apply plan appended an export to ~/.zshrc that the settings value
overrides. The check now uses the same lookup as the deferral checks: settings
env from the most specific scope, then shell profiles.

* fix(act): plan each optimize fix right before applying it

optimize --apply built every plan up front, each carrying the hash of the
config file as first read. When two fixes edit the same file (remove one MCP
server and unpin another in .mcp.json, or two edits to ~/.claude.json), the
first apply changed the file and the second was refused as "changed since the
plan was built", exit code 1. Each plan is now rebuilt from the file on disk
just before it runs; the baseline captured for it is kept, and the stale-plan
check still guards edits made while the plan is being applied.

* fix(optimize): fast mode on background agents saves dollars, not tokens

Switching subagent calls from fast to standard speed bills the same tokens at
a lower rate. The finding claimed every output token of those calls as tokens
saved, which inflated the token headline and pushed it up the urgency ranking.
tokensSaved is now 0; the dollar figure is unchanged and still carries it.

* fix(optimize): charge an unused MCP server only to Claude sessions

unused-mcp reads servers from Claude Code config, but multiplied their schema
by every session of every provider in the period, so under --provider all a
handful of Claude sessions next to hundreds of Codex or Cursor sessions
produced a large token and dollar figure. It now counts and prices only Claude
sessions, as the deferral checks already do.

* fix(optimize): stop reading MCP servers from ~/.claude/settings.json

Claude Code reads MCP servers from ~/.claude.json and .mcp.json, not from the
mcpServers key of ~/.claude/settings.json or settings.local.json. The MCP
checks read both user settings files, while the remove plan never edits them,
so a server listed only there showed as an unused server with savings under
"Fix now" and apply skipped it as "not found in editable config". The loader
now leaves those two files out; its home directory parameter, and the one on
the alwaysLoad check that only fed it, go with them.

* fix(act): match MCP servers in the report by their namespace

The report's baseline keeps config names such as "docs.local", while sessions
name the server as Claude Code does in tool names ("docs_local"). A removed
server that came back never matched, so act report counted savings instead of
reading it as reverted. sessionLoadsAny now compares through mcpNamespace.

* fix(optimize): keep every config name that maps to one MCP namespace

Claude Code turns "a.b" and "a:b" into the same tool namespace "a_b", so the
MCP config loader keyed both under one entry and kept only the newest name.
unused-mcp then named one of them, and the remove plan left the other config
entry in place. The entry now keeps every config name; unused-mcp and the
alwaysLoad check pass each one to their plans.

* fix(act): read a "__" server name whole from report inventory entries

Inventory entries are mcp__<server>__<tool>, and the report took the server
as the second "__" segment, so a server named "a__b" was read as "a" and a
re-added "a__b" never showed as reverted. The tool is now cut off from the
right, leaving the full server name.

* fix(act): resolve MCP namespaces against the known servers

mcp__a__b__c can be server "a__b" with tool "c" or server "a" with tool
"b__c", and both fixed rules (first segment, or cut from the right) pick the
wrong server for some names. A tool name is now split at the longest server
namespace found in the MCP config (plus the servers being measured in act
report), falling back to the first segment only when none matches. This
applies to act report's inventory reads and to the call names unused-mcp and
mcp-deferral-off count.

* fix(act): replan only for files an earlier fix in this run changed

Rebuilding every plan right before it ran took a fresh hash of the current
file, so under --apply --yes a config file edited outside codeburn between
selection and apply was rewritten anyway, where the stale-plan guard used to
refuse it. The run now records the hash of every file it writes. A plan is
rebuilt only when one of its files differs from the plan solely because an
earlier fix in this run wrote it; any other change keeps the original plan,
and runAction rejects it with "changed since the plan was built".

* docs(optimize): note why an MCP tool name with two known prefixes is ambiguous
2026-11-06 09:27:46 +01:00
Resham Joshi
7b803b293b
fix: survive prototype-named tools and models, never wipe a config on a syntax error, validate plugin names before removal (#1897)
* fix: keep tool and model names like constructor or toString as plain names

Lookups of provider-supplied tool names and model ids into plain-object maps
returned the inherited Object.prototype member, so one session with a tool
named constructor rejected the whole parse, and a model named toString broke
the models report and the menubar payload. Route those lookups through
Object.hasOwn.

* fix: never overwrite an unparseable config.json

readConfig fell back to {} on any error, so one syntax error in a hand-edited
config.json plus any setter (currency, budget, model-alias, ...) saved {} with
one key and erased every other setting. saveConfig now moves an unparseable
file to config.json.corrupt-<timestamp>, says so on stderr and exits 1; read
paths keep the {} fallback with a one-line warning.

* fix: validate the plugin name before plugin remove, info and verify touch disk

plugin remove joined the raw name onto the plugins dir, so
`plugin remove .. --confirm` deleted the whole codeburn config dir. Check the
name against the manifest name pattern first, as the loader already requires.

* fix: keep a model or tool named __proto__ in every running total

The per-model and per-tool totals behind the models report, the menubar
payload, the JSON report and the export assigned into plain objects, so a
name like __proto__ set the prototype instead of adding a row. Build them
prototype-free, and stop the daily cache load from dropping model rows whose
name happens to be an Object.prototype member: they are written own-only.
2026-11-06 09:27:41 +01:00
Resham Joshi
391d6ff9f7
fix(totals): count only the estimated output of a placeholder call as estimated spend (#1899)
* fix(cost): count only the estimated output of a placeholder call as estimated

A pre-2.1.307 subagent call has its output estimated but its input and
cache tokens recorded. The estimated share and costBasis split counted
the whole call as estimated; now only its output cost is, the rest stays
calculated. Totals are unchanged.

* test(cost): cover the estimated output share under discounts, tiers, fallbacks and shares
2026-11-06 09:27:30 +01:00
Resham Joshi
5bda23eed1
fix(totals): aliases in the daily-cache hash, fill missing sealed days for all providers, seven-day weekly budget (#1894)
Some checks are pending
CI / semgrep (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / vscode (push) Waiting to run
* fix(daily-cache): re-derive sealed days when a model alias changes

The daily cache config hash covered savings, price overrides and flat-rate
marks but not model aliases, so after codeburn model-alias the sealed days
kept their old (often $0) cost while live views showed the priced value.
A changed alias set now re-derives the backfill window once on the next run;
carried days keep their stored accounting.

* fix(totals): fill a past date the sealed cache lacks in the all-provider headline

The provider-scoped overlay fills a (date, provider) the cache has no row for
from the live parse, but the all-provider union only reconciled dates the
cache already held. A date missing from a complete cache therefore showed
under --provider and vanished from the all-provider total, so one provider
could total more than all of them. The union now fills an absent historical
date from the live day it already has; the normalized-index path drops its
separate incomplete-cache fill, which the union now covers.

* fix(budget): measure the weekly budget over 7 dates, not 8

The weekly tier reused the 'week' period, which starts at today-7, so
budget --check and the overview budget line summed 8 calendar days against
a 7-day budget. The budget range now starts at today-6; the 'week' period
itself is unchanged.
2026-11-06 06:19:15 +01:00
Resham Joshi
fad852811e
fix(cache): keep ultrafast calls, restore rows on a busy read, never replay a stale status snapshot (#1893)
* fix(cache): accept ultrafast calls when loading the session cache

The cache validator only allowed standard, fast and flex, so a Codex day
piece holding one ultrafast call failed validation as a whole and every
file in it re-parsed on each run. The allowed set now comes from one
SPEEDS constant shared with the types.

* fix(parser): keep a busy SQLite source's cached rows

A changed source's cache entry was deleted before the parse, so a read
that hit SQLITE_BUSY left nothing behind and the report dropped that
source's spend for the run. The prior entry is now put back when the
read is deferred.

* fix(status): recompute the menubar snapshot on any corpus change

On the first fingerprint mismatch the snapshot loader served the last
saved payload for that query, however old, for a 2 s grace window. Back
to back queries could then show lifetime below 30 days, or one provider
above all. A changed fingerprint is now always a miss; an unchanged one
still reuses the saved result.
2026-11-06 06:19:11 +01:00
Resham Joshi
9568ac892c
perf(optimize): keep each transcript's scan record so a period view stops re-reading history (#1891)
* perf(compare): count self-corrections from stored per-file facts

The self-correction scan re-read every transcript of the compared period on
each request, 35-45 s for 30 days and lifetime. Each transcript is now read
once per file version: the messages that matched are kept in
scan-facts.v1 beside the session cache, keyed by path, size and mtime, and a
transcript that only grew is read from where the last read stopped. A period
is then a walk over the stored hits, deduped by model and timestamp across
files as before.

On a frozen copy of a 23 GB history the JSON for today, 30 days, all and
lifetime is byte-identical to the previous scan; lifetime drops from 42 s to
4 s one-shot and from 45 s to 4 s in serve, after one build at today's cost.

* fix(optimize): join scanned files in discovery order

The scan joined each file's result when its read finished, with four reads in
flight, so savings sums, ties in the previews and which project settings file
won all followed I/O timing. Two runs over the same files could differ. Results
are now joined in the order the files were discovered.

* perf(optimize): keep only what the detectors read from each transcript

The scan kept every Bash command and up to 2,000 characters of every user
message, though the read:edit ratio only asks whether a command reads and the
unused-commands check only asks which slash commands a message names. Each
call now keeps the read-shaped flag and each user entry the command names, so
findings are unchanged while a 23 GB history scans into a record about a
tenth of the size.

* test: hash the facts rules with normalized line endings

* perf(optimize): read each transcript once per file version

Optimize re-read every Claude transcript modified since the period start on
every request, 50-60 s for 30 days and lifetime on a 23 GB history, and the
in-process scan memo could hold only a fraction of it. Each file's scan record
is now kept in the scan-facts store, keyed by path, size and mtime; a file that
only grew is read from where the last read stopped, and every request projects
the stored records exactly as it projected fresh scans. Repeated cwd lines are
kept as runs with their instants, and an instant that did not parse round-trips
as NaN, not 0.

On a frozen copy of the history the JSON for today, 30 days, all and lifetime is
byte-identical to the previous scan, with the store empty and warm. Lifetime
drops from 56 s to 6 s one-shot and in serve after one build at today's cost;
the store is 67 MB for 7,332 transcripts.
2026-11-06 03:30:25 +01:00
Resham Joshi
30a112ef6c
perf(compare): keep each transcript's self-correction facts so a period view stops re-reading history (#1890)
* perf(compare): count self-corrections from stored per-file facts

The self-correction scan re-read every transcript of the compared period on
each request, 35-45 s for 30 days and lifetime. Each transcript is now read
once per file version: the messages that matched are kept in
scan-facts.v1 beside the session cache, keyed by path, size and mtime, and a
transcript that only grew is read from where the last read stopped. A period
is then a walk over the stored hits, deduped by model and timestamp across
files as before.

On a frozen copy of a 23 GB history the JSON for today, 30 days, all and
lifetime is byte-identical to the previous scan; lifetime drops from 42 s to
4 s one-shot and from 45 s to 4 s in serve, after one build at today's cost.

* test: hash the facts rules with normalized line endings
2026-11-06 03:11:46 +01:00
Resham Joshi
6ff7204e34
fix(desktop): keep the sessions answer under the pipe cap (#1889)
Some checks failed
CI / semgrep (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / vscode (push) Waiting to run
macOS Menubar CI / test (push) Has been cancelled
Windows Menubar CI / check (ubuntu-latest) (push) Has been cancelled
Windows Menubar CI / check (windows-latest) (push) Has been cancelled
The Sessions drill-through asks for contribution segments over the whole
population, and over all time that answer is 28MB, past the 16MiB cap:
the request failed and the resident child was killed with it. The CLI
now answers one of n fixed slices with --part i/n, keyed by session
identity so a re-derived report never duplicates or drops a row, and the
bridge fetches eight slices in turn and restores the report order. The
renderer receives the same rows in the same order as before.
2026-11-05 22:55:40 +01:00
Resham Joshi
7457382977
fix(serve): shed memory on heap pressure, not resident size (#1888)
The resident child aborted with a V8 out-of-memory at a 4.2GB heap limit
while its resident size (5.4GB) was still under the 6GB guard, so the
guard never fired. Measure the heap instead: drop the memos when used heap
passes 70% of the limit, before and after each request, and keep the RSS
check as a second trigger. A request that runs the optimize transcript scan
adds 1.1-1.6GB on its own, so it starts only with 60% of the heap free.
2026-11-05 22:55:35 +01:00
Resham Joshi
b98f48009b
perf(compare): scan self-corrections only in the compared period, streamed (#1886)
* perf(compare): scan self-corrections only in the compared period, streamed

The self-correction scan read every transcript on disk for any period, so
compare took ~50 s even for today and the Today table showed lifetime counts.
It now reads only the sessions the compare reported on, line by line, so
transcripts over V8's string limit are counted instead of silently skipped.

* fix(compare): count self-corrections by message time, not whole sessions

Calls and cost are attributed by message timestamp, so a self-correction now
counts for a period only when its own message falls inside the compared
range. Sessions are still selected by the reported ids.
2026-11-05 22:55:29 +01:00
Resham Joshi
64d1a6985f
fix(sessions): keep the 0.9.27 step shape (#1883) 2026-11-05 18:44:42 +01:00
Resham Joshi
e6658ed221
fix(cache): do not load a provider section the parse is about to replace (#1882)
When the cached claude section was written under a different parse version
(another CodeBurn version sharing the cache dir, or an upgrade), the parse
loaded every shard of it in full and then replaced it, keeping only entries
whose transcript is gone. On a 23 GB history that load alone was ~500 MB of
heap held alongside the re-parse. A parse load now leaves present sources of
such a section on disk and reads only the gone ones. Other loadCache readers
are unchanged, and the cached and reported numbers are identical.
2026-11-05 18:44:36 +01:00
Resham Joshi
005f8bf2d4
fix(sessions): keep the --why payload under the desktop's 16 MiB pipe (#1881)
Every subagent's step list ships with the session since the agents view,
so a session with 863 helpers grew from 10.8 MiB to 42.4 MiB and the
desktop refused it. Steps now leave out default fields (isError false,
answer false, empty detail, calculated basis), the unused context delta,
and round the cached share. Past a 12 MiB budget the JSON drops whole step
lists, cheapest helper first and then prompts, with a truncatedSteps count
the Inspect, Agents and Story views show.
2026-11-05 18:02:10 +01:00
Resham Joshi
0de7efbc0a
feat(desktop): story view that tells a prompt in plain sentences (#1879)
* feat(desktop): inspect view for a prompt with request cards and insights

An open prompt now reads as one card per model request, newest first, with
the tool calls each request asked for nested under it. Each card shows the
request number and model, tokens in, out and cached share, what the request
did (asked for tool calls or wrote the answer), its duration against the
prompt's longest step, and its output tokens and cost. Tool rows show the
command or target, duration, the context the result added, a parallel label
when one message asked for several calls, and a muted failed state. A search
field and an All / Model / Tools switch narrow the list, and any card or tool
opens the existing step detail.

Above the cards a summary line and an insights strip name the slowest and the
costliest request, the tool that added the most context, how the tool calls
ran, and failed steps when there are any. Rows that cross the existing
slow-call and carried-result thresholds lead. The two-lane waterfall is gone:
the cards carry the same timing.

The session payload gains the fields this needs, computed at serve time:
each tool step names the model step that asked for it, a parallel position
and its result size; each model step carries its cached share, the context
delta to the next request, its tool call count, its cost basis and whether
it wrote the answer.

* fix(desktop): one place for out tokens on a request card

The request card showed output tokens twice, in the meta line and as a pill. The pill is gone; the meta line keeps the count and the dollar pill stays.

* feat(desktop): agents view with each subagent's lifecycle and cost by agent

* feat(desktop): story view that tells a prompt in plain sentences

* fix(desktop): story wording and copy feedback
2026-11-05 16:44:45 +01:00
Resham Joshi
97dc656d40
feat(menubar): show each Claude account inside the provider box (#1876)
* feat(claude): attribute usage to the account that was active

* fix(claude): identify by organization and keep the identity field under a filter

* test(claude): check the log file mode on POSIX only

* feat(menubar): show each Claude account inside the provider box

* fix(claude): record the plan only where the credential is already read

* feat(menubar): record the plan the quota poll already knows

* ci: run the checks

* test: keep real fs and child_process exports in the WSL spawn mocks
2026-11-05 15:54:39 +01:00
Resham Joshi
7103a93778
feat(desktop): agents view with each subagent's lifecycle and cost by agent (#1878)
* feat(desktop): inspect view for a prompt with request cards and insights

An open prompt now reads as one card per model request, newest first, with
the tool calls each request asked for nested under it. Each card shows the
request number and model, tokens in, out and cached share, what the request
did (asked for tool calls or wrote the answer), its duration against the
prompt's longest step, and its output tokens and cost. Tool rows show the
command or target, duration, the context the result added, a parallel label
when one message asked for several calls, and a muted failed state. A search
field and an All / Model / Tools switch narrow the list, and any card or tool
opens the existing step detail.

Above the cards a summary line and an insights strip name the slowest and the
costliest request, the tool that added the most context, how the tool calls
ran, and failed steps when there are any. Rows that cross the existing
slow-call and carried-result thresholds lead. The two-lane waterfall is gone:
the cards carry the same timing.

The session payload gains the fields this needs, computed at serve time:
each tool step names the model step that asked for it, a parallel position
and its result size; each model step carries its cached share, the context
delta to the next request, its tool call count, its cost basis and whether
it wrote the answer.

* fix(desktop): one place for out tokens on a request card

The request card showed output tokens twice, in the meta line and as a pill. The pill is gone; the meta line keeps the count and the dollar pill stays.

* feat(desktop): agents view with each subagent's lifecycle and cost by agent
2026-11-05 15:54:32 +01:00
Resham Joshi
f96b46d8cd
feat(desktop): inspect view for a prompt with request cards and insights (#1877)
Some checks are pending
CI / semgrep (push) Waiting to run
macOS Menubar CI / test (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / vscode (push) Waiting to run
Windows Menubar CI / check (ubuntu-latest) (push) Waiting to run
Windows Menubar CI / check (windows-latest) (push) Waiting to run
* feat(desktop): inspect view for a prompt with request cards and insights

An open prompt now reads as one card per model request, newest first, with
the tool calls each request asked for nested under it. Each card shows the
request number and model, tokens in, out and cached share, what the request
did (asked for tool calls or wrote the answer), its duration against the
prompt's longest step, and its output tokens and cost. Tool rows show the
command or target, duration, the context the result added, a parallel label
when one message asked for several calls, and a muted failed state. A search
field and an All / Model / Tools switch narrow the list, and any card or tool
opens the existing step detail.

Above the cards a summary line and an insights strip name the slowest and the
costliest request, the tool that added the most context, how the tool calls
ran, and failed steps when there are any. Rows that cross the existing
slow-call and carried-result thresholds lead. The two-lane waterfall is gone:
the cards carry the same timing.

The session payload gains the fields this needs, computed at serve time:
each tool step names the model step that asked for it, a parallel position
and its result size; each model step carries its cached share, the context
delta to the next request, its tool call count, its cost basis and whether
it wrote the answer.

* fix(desktop): one place for out tokens on a request card

The request card showed output tokens twice, in the meta line and as a pill. The pill is gone; the meta line keeps the count and the dollar pill stays.
2026-11-05 14:10:28 +01:00
Resham Joshi
9c4eda255d
feat(claude): attribute usage to the account that was active (#1875)
* feat(claude): attribute usage to the account that was active

* fix(claude): identify by organization and keep the identity field under a filter

* test(claude): check the log file mode on POSIX only
2026-11-05 07:31:23 +01:00
Resham Joshi
ee5cf7c38f
fix(menubar): find the desktop app's bundled CLI when no CLI is on PATH (#1871)
Some checks are pending
CI / semgrep (push) Waiting to run
macOS Menubar CI / test (push) Waiting to run
Tests / desktop (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.15.0) (push) Waiting to run
Tests / test (24) (push) Waiting to run
Tests / test (26) (push) Waiting to run
Tests / vscode (push) Waiting to run
Windows Menubar CI / check (ubuntu-latest) (push) Waiting to run
Windows Menubar CI / check (windows-latest) (push) Waiting to run
With only the desktop app installed from the Homebrew cask, the menu bar
failed to load Today with "nonZeroExit (code: 127, stderr: env: codeburn:
No such file or directory)". The menu bar looked for a codeburn in the
path recorded for it and in package-manager folders, then fell back to the
bare name. A desktop-only machine has nothing in those folders, so when the
record was missing or no longer ran, nothing was found and the error named
nothing.

The packaged desktop app now carries a plain launcher at
CodeBurn.app/Contents/Resources/cli/codeburn that runs its bundled CLI
through its own executable and finds its own bundle. The menu bar checks
it, in /Applications and ~/Applications, after the recorded path and the
package-manager folders. When none of them runs, Today says which paths
were tried. The CLI's menubar installer records the same launcher instead
of refusing the install when nothing named codeburn is on PATH.
2026-11-05 05:59:42 +01:00
Resham Joshi
d965273b59
feat(optimize): flag an autoCompactWindow that blocks idle compaction (#1870)
* feat(optimize): flag an autoCompactWindow that blocks idle compaction

* fix(optimize): render a finding without a dollar figure cleanly and gate the idle-compaction rule on the one-hour cache

* fix(optimize): group headers without a figure when the group has none
2026-11-05 05:28:08 +01:00
Resham Joshi
4a8ff6e068
feat(pricing): contracted-rate discounts on calculated costs (#1872)
* feat(pricing): contracted-rate discounts on calculated costs

* fix(sessions): price the why-it-cost parts with the configured discount
2026-11-05 05:02:38 +01:00
Resham Joshi
12ce3148e0
fix(quota): label the Claude 20x tier as Ultra (#1869)
Anthropic renamed the Max 20x plan to Ultra, but the credential's rate-limit tier id is still default_claude_max_20x. A parsed multiplier of 20 now labels Ultra in the CLI, desktop, Windows and menubar twins; other multipliers keep Max Nx.
2026-11-05 02:48:07 +01:00
Resham Joshi
4d1da1a6f0
feat(sessions): mark sessions kept after their transcript was removed (#1868)
* feat(sessions): mark sessions kept after their transcript was deleted

When a write refresh keeps a cached session whose source file is gone
(a Claude session with PR links, or a copilot or quickdesk entry inside
its 90-day window), the cache entry now records retainedSince, the local
date of the first refresh that found the file missing. It is set once and
kept on later refreshes. Offline WSL roots are not deletions and stay
unmarked.

Sessions served from such an entry carry retained.since. The sessions
JSON rows include it, the sessions table puts * after the start time with
a legend line, and the export adds a last retained column to records and
sessions in JSON and CSV. The desktop Sessions list and drawer show a
muted note naming the tool and the date.

Behaviour does not change: the same entries are kept and evicted, and
every total and the by-PR numbers are unchanged. The field is optional,
so the cache version stays.

* fix(sessions): say when the transcript was found missing, not deleted

The desktop note, the sessions table legend, the export readme and the docs no longer give a deletion date. retainedSince is the day CodeBurn first found the transcript missing, so the note now reads that the transcript has been missing since that date.
2026-11-05 02:38:09 +01:00
Resham Joshi
a88dffe7aa
fix(export): give the JSON export stable keys (#1864)
* fix(export): give the JSON export stable keys

The JSON export reused the CSV row builders, so its keys were display
headers with spaces and parentheses, and the money keys changed name
with the configured currency. A program had to reshape the file before
it could read it.

The builders now produce one camelCase row, and a single key to header
map writes the CSV, so every CSV header line stays byte-identical. The
JSON schema moves to codeburn.export.v3; the currency is stated once in
currency.code and the money values stay converted to it.

Before (v2, EUR):
{"Period":"7 Days","Date":"2026-11-02","Cost (EUR)":1.1,"Saved (EUR)":0,"API Calls":1,"Sessions":1,"Input Tokens":100000,"Output Tokens":50000,"Cache Read Tokens":200000,"Cache Write Tokens":30000,"costBasis":{"calculated":1}}

After (v3, EUR):
{"period":"7 Days","date":"2026-11-02","cost":1.1,"saved":0,"apiCalls":1,"sessions":1,"inputTokens":100000,"outputTokens":50000,"cacheReadTokens":200000,"cacheWriteTokens":30000,"costBasis":{"calculated":1}}

v2 consumers must rename keys. New keys can still appear under v3.

* docs: changelog entry for the v3 export JSON

* test: read the v3 export keys
2026-11-05 00:49:36 +01:00
Resham Joshi
615b2ee732
feat(export): say where every dollar comes from (#1863)
Every served call now carries a costBasis: recorded when the tool wrote
its own figure, calculated when CodeBurn priced measured tokens,
estimated when the tokens or price are a guess, included when a
subscription covered it at $0, and unpriced when the model has no known
price. It is derived from fields the cache already stores, so no parse
or cache version moves.

The export JSON gives each record its basis and gives sessions and days
the share of cost from recorded, calculated and estimated; records.csv
gets the column. sessions --format json, the menubar payload and MCP
get_usage carry the same shares. Sync now sets ai.cost_estimated from
the basis instead of guessing from the provider name.
2026-11-05 00:10:27 +01:00
Resham Joshi
b18d42d0b4
feat(optimize): flag one-hour cache writes the next request never needed (#1860)
* fix(optimize): price findings from the calls they point at

Every finding's dollar figure was its token estimate times one blended
rate: 70% of the period's spend over all input-side tokens. That rate is
close to a cache-read price, so it misprices anything that is not a cache
read. Schema findings already weight cache reads at 0.1, so their reads
were discounted twice; findings whose tokens include output were priced
as input.

A finding can now carry savingsUSD, computed from the calls it names.
Every surface reads it through findingUSD: the CLI and TUI optimize
views, the JSON report (and so the desktop Optimize page), the menubar
payload and MCP get_savings, and the --apply list. classTotals sums it,
scaled to the apply-able share for fix findings. Findings without it keep
tokensSaved times the blended rate, and any token whose session or model
has no price still falls back to that rate.

Measured now:
- low-worth-sessions: each session's real cost times its recovery fraction
- retry-heavy-capabilities: the retry turns' real cost times the fraction
- redundant-rereads, build-folder-reads: the reads at the input rate of
  their session's most-called model
- warmup-heavy: the excess cache writes at the session model's write rate
- mcp-low-coverage, mcp-project-scope: each call's charged schema tokens
  at that call model's cache-write or cache-read rate
- unused-mcp, mcp-deferral-off, mcp-alwaysload-hygiene,
  mcp-defer-threshold: the per-session schema at the input rate of the
  sessions charged

Still on the blended rate, because no calls can be named: read-edit-ratio
(reads that never happened), context-heavy-sessions, cost-outliers,
low-cache-hit-sessions, claude-md-too-long, bash-output-cap,
recurring-context and the unused agents, skills and commands.

* feat(optimize): flag one-hour cache writes the next request never needed

A one-hour prompt-cache write is billed at 1.6 times the five-minute
rate and only earns that back when the same model's cache is next used
after a pause of more than five minutes but less than an hour. Reads
refresh either TTL, so a write is judged by the first such pause after
it, not just by the very next call.

The new one-hour-cache-unused nudge walks each session per model in
time order, prices the 60% premium on every one-hour write that never
reached such a pause from the call's own model and tier, and fires at
one dollar or more. Unpriced models and five-minute writes add nothing.

* test(optimize): pin one-hour writes that later hits kept warm

Every cache hit refreshes the TTL, so a one-hour write followed by more
than an hour of steady activity and then a twenty-minute pause still
needed the hour. The detector already judges the length of the first
pause over five minutes, not its distance from the write; this test
pins that. A pause that itself runs past the hour still counts as
wasted, because the one-hour entry expires inside it either way.

Also lists one-hour-cache-unused among the measured findings.
2026-11-05 00:10:23 +01:00
Resham Joshi
bcccfdeb17
feat(sessions): show each session's cache hit rate (#1861)
The sessions table, the interactive sessions view, the JSON rows and the
desktop Sessions page now show a cache hit rate per session. It is cache
reads divided by input plus cache reads plus cache writes, the share of the
prompt that came from cache. A session with no cache reads or writes is
unmeasured and shows a dash instead of 0%.

The session drawer, the compare views, the menubar payload and the JSON
report now use the same formula through one helper, so every surface
reports the same number. Optimize already used it, so its finding does not
move.
2026-11-04 21:56:28 +01:00
Resham Joshi
792d1ab119
fix(act): price realized savings the way the finding priced them (#1859)
* fix(optimize): price findings from the calls they point at

Every finding's dollar figure was its token estimate times one blended
rate: 70% of the period's spend over all input-side tokens. That rate is
close to a cache-read price, so it misprices anything that is not a cache
read. Schema findings already weight cache reads at 0.1, so their reads
were discounted twice; findings whose tokens include output were priced
as input.

A finding can now carry savingsUSD, computed from the calls it names.
Every surface reads it through findingUSD: the CLI and TUI optimize
views, the JSON report (and so the desktop Optimize page), the menubar
payload and MCP get_savings, and the --apply list. classTotals sums it,
scaled to the apply-able share for fix findings. Findings without it keep
tokensSaved times the blended rate, and any token whose session or model
has no price still falls back to that rate.

Measured now:
- low-worth-sessions: each session's real cost times its recovery fraction
- retry-heavy-capabilities: the retry turns' real cost times the fraction
- redundant-rereads, build-folder-reads: the reads at the input rate of
  their session's most-called model
- warmup-heavy: the excess cache writes at the session model's write rate
- mcp-low-coverage, mcp-project-scope: each call's charged schema tokens
  at that call model's cache-write or cache-read rate
- unused-mcp, mcp-deferral-off, mcp-alwaysload-hygiene,
  mcp-defer-threshold: the per-session schema at the input rate of the
  sessions charged

Still on the blended rate, because no calls can be named: read-edit-ratio
(reads that never happened), context-heavy-sessions, cost-outliers,
low-cache-hit-sessions, claude-md-too-long, bash-output-cap,
recurring-context and the unused agents, skills and commands.

* fix(act): price realized savings at the session's own rates

Findings now carry dollars priced from the calls they point at, but act
report still priced the re-measured tokens of an applied fix with the
blended input rate. That rate sits near a cache-read price, so a fix
advertised in optimize came back as roughly a tenth of that in act report
and in the desktop "Saved by applied fixes" line.

Each measured row now carries realizedCostUSD, priced per post-apply
session at that session's most-called model rate through the same
findingPricing helpers the findings use. MCP removals, project scoping
and deferral price the schema tokens once per session that benefited, at
the cache-write rate. Archived skills, agents and commands price their
definition tokens the same way. CLAUDE.md read rules price the credited
reads at the input rate, split across sessions by their edits. Sessions
whose model has no price keep the blended rate. The total, the JSON
totals.realizedCostUSD and the optimize header sum these row figures.
Token figures are unchanged, and nothing stored in the journal changes.

Worked example: an MCP removal drops 8,000 schema tokens from each of
1,280 post-apply Opus 4.6 sessions, 10.24M tokens. Optimize advertised it
at about $64, the same writes at Opus's $6.25 per million cache-write
rate. Before this change act report priced the 10.24M tokens at a blended
$0.60 per million and showed about $6.14 realized. Now it shows $64.00.

* fix(act): price realized savings the way the finding priced them

The first pass priced every realized schema or definition token at the
cache-write rate and every credited read at the input rate, whatever the
finding had advertised. That left advertised and realized on different
footings: unused-mcp and the deferral findings price schema at the input
rate, and the archive and read-edit-ratio findings still use the blended
rate, so their realized figure could read several times their estimate.

FINDING_TOKEN_KIND in optimize.ts now maps each measured finding to the
token kind it prices: cache-write for mcp-low-coverage and
mcp-project-scope, input for unused-mcp, mcp-deferral-off,
mcp-alwaysload-hygiene, mcp-defer-threshold, redundant-rereads and
build-folder-reads. act report prices a fix's realized tokens at that kind
for each benefiting session, and keeps the blended rate for any finding
not in the table and for unpriced models. A detector that moves to
measured pricing adds one line to the table.

Worked example on 1,280 post-apply Opus 4.6 sessions, 8,000 schema tokens
each, 10.24M tokens, blended rate $0.60 per million:
- mcp-low-coverage removal: advertised about $64 at the $6.25 cache-write
  rate; realized $6.14 on the blended rate before, $64.00 now.
- unused-mcp removal: advertised about $51 at the $5 input rate; realized
  $6.14 before, $64.00 after the first pass, $51.20 now.
- archived skills: advertised and realized both stay on the blended rate,
  $6.14.

* fix(act): store the baseline at the finding's own per-tool token figure

Since the deferred-tool fix, mcp-low-coverage charges each unused tool as
one deferred name line of about 9 tokens, once per call: as a cache read
when the call read cache, as a cache write otherwise, weighted into
effective input tokens. The act baseline for that apply still stored 400
tokens per unused tool once per session, so realized tokens and the
at-apply estimate measured different things and realized ran far above
the estimate.

captureBaseline now stores, per server, the effective schema tokens the
finding's own attribution charges over the baseline window divided by the
sessions that loaded the server. mcpLowCoverageSchemaPerSession runs the
same per-call pass the finding runs, so there is no second constant.
Because the stored figure is now effective input tokens (writes x1.25,
reads x0.1), mcp-low-coverage realized dollars use the input rate, which
for Claude models equals the finding's per-call cache-write and
cache-read prices.

Example: 20 unused deferred tools, one cache write and one cache read per
session. The baseline was 8,000 tokens per session (20 x 400); it is now
243 (180 name-line tokens x1.25 + 180 x0.1), and 243 times the sessions
equals the finding's tokensSaved.

Applies recorded before this change keep their stored 400-per-tool
baseline; there is no migration. Their realized dollars now use the input
rate rather than the cache-write rate. Other MCP baselines
(mcp-project-scope, unused-mcp, deferral) are unchanged.

* fix(act): store the project-scope baseline at the finding's figure too

mcp-project-scope has charged each scoped server's tools as deferred name
lines of about 9 tokens, once per call, in its cold projects only, since
the deferred-tool fix. Its act baseline still stored 400 tokens per
available tool once per session.

captureBaseline now stores, per scoped server, the effective cold-project
schema tokens the finding's own pass charges, divided by the cold-project
sessions that loaded the server. mcpProjectScopeSchemaPerSession runs that
pass over the finding's removeProjects; it is a separate helper because
the pass differs from mcp-low-coverage's (available tools in cold projects
rather than unused tools everywhere). The stored figure is effective
input tokens, so realized dollars use the input rate, as for
mcp-low-coverage.

Example: 4 tools loaded in two cold projects, one cache write and one
cache read per session. The baseline was 1,600 tokens per session
(4 x 400); it is now 48.6 (36 x1.25 + 36 x0.1), and 48.6 times the cold
sessions equals the finding's tokensSaved.

Applies recorded before this change keep their stored 400-per-tool
baseline; there is no migration.
2026-11-04 21:56:22 +01:00
Resham Joshi
26bfc4e4c4
feat(optimize): report fast-mode spend on background agents and long-context premiums (#1858)
* fix(optimize): price findings from the calls they point at

Every finding's dollar figure was its token estimate times one blended
rate: 70% of the period's spend over all input-side tokens. That rate is
close to a cache-read price, so it misprices anything that is not a cache
read. Schema findings already weight cache reads at 0.1, so their reads
were discounted twice; findings whose tokens include output were priced
as input.

A finding can now carry savingsUSD, computed from the calls it names.
Every surface reads it through findingUSD: the CLI and TUI optimize
views, the JSON report (and so the desktop Optimize page), the menubar
payload and MCP get_savings, and the --apply list. classTotals sums it,
scaled to the apply-able share for fix findings. Findings without it keep
tokensSaved times the blended rate, and any token whose session or model
has no price still falls back to that rate.

Measured now:
- low-worth-sessions: each session's real cost times its recovery fraction
- retry-heavy-capabilities: the retry turns' real cost times the fraction
- redundant-rereads, build-folder-reads: the reads at the input rate of
  their session's most-called model
- warmup-heavy: the excess cache writes at the session model's write rate
- mcp-low-coverage, mcp-project-scope: each call's charged schema tokens
  at that call model's cache-write or cache-read rate
- unused-mcp, mcp-deferral-off, mcp-alwaysload-hygiene,
  mcp-defer-threshold: the per-session schema at the input rate of the
  sessions charged

Still on the blended rate, because no calls can be named: read-edit-ratio
(reads that never happened), context-heavy-sessions, cost-outliers,
low-cache-hit-sessions, claude-md-too-long, bash-output-cap,
recurring-context and the unused agents, skills and commands.

* feat(optimize): report fast-mode spend on background agents and long-context premiums

Two findings for premium-tier spend the parser already prices, so their
dollars come from the calls themselves.

fast-mode-background (nudge) sums, over fast-mode calls inside subagent
sessions, the call's cost minus the same tokens at standard speed. It
fires at $1 or more in the window. Some background runs need the speed,
so it stays a habit check.

long-context-premium (keep) sums, over calls whose prompt crossed the
model's long-context tier, the tiered cost minus the same tokens at base
rates. Fast calls are priced at standard on both sides so the fast
premium is never counted twice. tokensSaved is the prompt tokens above
the threshold; the fix names each model's threshold from its tier. It
fires at $1 or more and has no apply action.

Both rate high above $20, medium above $5, else low.
2026-11-04 19:48:37 +01:00