Commit graph

2668 commits

Author SHA1 Message Date
Resham Joshi
40d58800c1
fix(quota): unwrap the Cursor safe-storage token for Grok Bot quota (#1926)
Some checks failed
CI / semgrep (push) Has been cancelled
macOS Menubar CI / test (push) Has been cancelled
Tests / test (22) (push) Has been cancelled
Tests / test (22.15.0) (push) Has been cancelled
Tests / test (24) (push) Has been cancelled
Tests / test (26) (push) Has been cancelled
Tests / test-platforms (macos-latest) (push) Has been cancelled
Tests / test-platforms (windows-latest) (push) Has been cancelled
Tests / desktop (push) Has been cancelled
Tests / vscode (push) Has been cancelled
* fix(quota): unlock Cursor safe-storage token for Grok Bot quota

Cursor 3.27+ stores its session as cursor-safe-storage:v1 ciphertext. The
Grok Bot reader sent that blob as the bearer, so every request got a 401 and
asked the user to sign in again. It now unlocks the token the way the Cursor
reader does, under the same keychain consent rule, and reports a locked
keychain with the Cursor locked message. In codeburn quota both readers share
one keychain read, so one prompt covers both. The menu bar Grok Bot service
uses CursorSafeStorage.unlock like its Cursor service.

Fixes #1924

* test(quota): one keychain read covers Cursor and Grok Bot

* fix(quota): scope the shared Cursor keychain read to one quota run

* fix(quota): one Cursor keychain read per menu bar refresh for Cursor and Grok Bot

A user refresh unlocked the Cursor session twice, once for Cursor and once
for Grok Bot, so it could prompt twice. An allowed read now reuses the
previous allowed read's answer for 30 seconds, a Deny included. Background
reads are unchanged.

* test(quota): open the Grok Bot test defaults through TestDefaults
2026-11-09 18:28:51 +01:00
Resham Joshi
c19e2c9fdd
fix(quota): let Retry and a new Claude login clear the stored rate-limit block (#1925)
* fix(menubar): let Retry and a new Claude login clear the stored quota block

* fix(desktop): let a forced refresh and a new Claude login clear the stored quota block

* fix(quota): report an expired Claude login instead of a rate limit

* fix(menubar): keep the Claude quota block when no credential can be read

* fix(desktop): say that Refresh retries a rate-limited Claude quota now
2026-11-09 18:28:45 +01:00
Resham Joshi
bb95255292
chore(flathub): point the manifest at the published 0.9.28 deb hash (#1921)
Some checks failed
Tests / test (22.15.0) (push) Has been cancelled
Tests / test-platforms (macos-latest) (push) Has been cancelled
Tests / test-platforms (windows-latest) (push) Has been cancelled
Tests / desktop (push) Has been cancelled
CI / semgrep (push) Has been cancelled
Tests / test (22) (push) Has been cancelled
Tests / test (24) (push) Has been cancelled
Tests / test (26) (push) Has been cancelled
Tests / vscode (push) Has been cancelled
2026-11-08 09:12:27 +01:00
Resham Joshi
517ad938bf
chore(vscode): release extension 1.0.3 with CLI 0.9.28 (#1920)
* chore(vscode): release extension 1.0.3 with CLI 0.9.28

Extension 1.0.3 bundles CodeBurn CLI 0.9.28.

* docs(vscode): note the Node.js 22.15 requirement in the 1.0.3 changelog
2026-11-08 09:03:55 +01:00
Resham Joshi
92d8d08149
Keep the bundled price list from repricing ids upstream only reshuffled (#1919)
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
Windows Menubar CI / check (ubuntu-latest) (push) Has been cancelled
Windows Menubar CI / check (windows-latest) (push) Has been cancelled
* fix(pricing): keep a price snapshot refresh from repricing ids upstream only reshuffled

Bundler rules, each with a synthetic-input test:

- A previous primary row upstream no longer produces stays in the primary
  snapshot. In the fallback it was reached only after prefix matching, so
  mistral-large fell to a $0 mistral row and built-in aliases to z-ai/glm-5.x
  and xiaomi/mimo-v2.5 stopped resolving.
- Router ids stay out of the gap-fill: models.dev families auto and
  model-router, OpenRouter's Router tokenizer and its openrouter/ namespace.
  A priced auto row priced every <gateway>/auto id.
- A reseller's namespaced key (perplexity/openai/x -> openai/x) takes the
  maker's row when the namespace matches that row's provider. A key only
  resellers claim keeps its previous value while a reseller still quotes it
  or its source row was dropped, and a reseller row added since never tops
  up a slot an existing id lacked; only a reseller repricing its own row
  moves it.
- A long-context tier upstream drops from a row that still exists is kept.
- A maker row more than 2x off the median reseller quote for the same model
  does not reprice an existing id.
- A rate that turns exactly $0 on a row still priced on input is treated as
  missing and keeps its previous slot.

Carried, held, kept-tier, off-market and zeroed ids are listed in
src/data/litellm-snapshot.meta.json.

* fix(pricing): never let a $0 prefix sibling price an id with its own fallback row

chat-bison and chat-bison-001 have priced fallback rows, but a new $0
gateway row strips to a bare `chat` key whose prefix match won first. A $0
prefix hit now yields to the id's exact fallback row; a priced sibling still
wins, since fallback rows are resale or carried figures. This also prices
mistral/mistral-embed, mistral-saba and intfloat/multilingual-e5-large-instruct,
which resolved to $0 on main.

* chore: refresh the bundled price snapshot

Regenerated with npm run bundle-litellm from LiteLLM main at 5bc25ff8
(2026-11-07T20:01:36Z), plus models.dev and the OpenRouter models API
fetched 2026-11-07.

Upstream removed every openrouter/ row on 9 Oct; those 929 rows are
carried in the primary snapshot. Upstream #45647 set claude-sonnet-4-5 to a
200k context and dropped its 200k tier ($6 / $22.50); the previous tier is
kept on claude-sonnet-4-5, claude-sonnet-4-5-20250929 and the two Bedrock
Claude 3.5 Sonnet rows, so past 1M-context requests keep their price.

* fix(pricing): bound the snapshot carry and hold rules

- A reseller-only key keeps its previous value only while a current
  reseller row still quotes it; once none does, it takes the claim.
- An off-market maker row is held back only when it is more than 2x above
  the median reseller quote; a maker row below it is the maker's own price.
- A dropped long-context tier, and a slot that turns exactly $0, are kept
  only while the row's other rates are unchanged; a row upstream re-priced
  takes upstream's shape.
- Router and meta ids are not carried forward either. A `~` version pointer
  is, since it bills as the model it names.

* chore: regenerate the bundled price snapshot with the bounded rules

Same upstream: LiteLLM main at 5bc25ff8 (2026-11-07T20:01:36Z).

* docs: changelog entry for the bundled price refresh

* fix(pricing): expire snapshot holds after one refresh

A reseller-only key held at its previous value (rule c) or an id held
against an off-market maker row (rule e) is recorded in the meta file with
the date the hold began. The next refresh that would hold it again takes
the current upstream value instead, so a stale quote or a wrong maker row
delays a reprice once, never forever. A hold whose stale quote disappears
releases at once. Carried retired rows are not holds and stay.

* chore: record hold start dates in the snapshot meta

Snapshot and fallback are byte-identical to the previous regeneration (LiteLLM 5bc25ff8, 2026-11-07T20:01:36Z); only the meta format changes.

* fix(pricing): expire every snapshot hold after one refresh and price reseller keys at the median quote

A kept long-context tier and a restored $0 slot now expire like the other
holds: kept for one refresh with the date in the meta file, then upstream's
shape. A key only resellers quote takes the median quote (lower middle when
even, priced before $0) instead of the first row in upstream's JSON order,
so a reordered upstream file prices it the same. Snapshot regenerated from
the same upstream (LiteLLM 5bc25ff8, 2026-11-07T20:01:36Z).
2026-11-08 02:16:10 +01:00
Resham Joshi
b58244e1b2
chore: bump version to 0.9.28 (#1918)
* chore: bump version to 0.9.28

* chore: stamp the 0.9.28 changelog
2026-11-08 02:00:52 +01:00
Resham Joshi
8ff04079f1
docs: changelog entries for 0.9.28 (#1917)
* docs: changelog entries for 0.9.28

* docs: drop PR numbers from the 0.9.28 changelog entries

* docs: tighten three 0.9.28 changelog entries

* docs: credit contributors and closed issues in the 0.9.28 changelog
2026-11-07 16:18:26 -08:00
Resham Joshi
f0e0902b71
test: use synthetic figures in the carry-forward fixture and drop a timing log (#1916)
Some checks are pending
CI / semgrep (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
2026-11-08 00:20:25 +01:00
Resham Joshi
d657b88862
fix(sessions): keep --why for a session with thousands of helpers under the heap limit (#1915)
* fix(sessions): keep --why for a session with thousands of helpers under the heap limit

Each helper's transcript was held whole (tool output, tool input, every
detail) until the steps were built, so a 1,893-helper session ran the
desktop's CLI child out of heap. Details are now decided against the budget
as each transcript is read, in the same order as before, and a helper keeps
only what its steps show. fitWhyJson sizes the payload one step list at a
time instead of as one string. Output is unchanged byte for byte.

* test(sessions): smaller fixture, longer timeout and no Windows run for the 2,000-helper heap test

One two-byte tool output per helper keeps the old retention with about 40%
of the bytes on disk; the limit moves to 128 MB, which the fix clears at
96 MB and main fails up to at least 176 MB.
2026-11-07 20:59:13 +01:00
Resham Joshi
4964238c1c
fix: bill Cursor agent streams past the lookup cap on an unchanged DB, keep JetBrains Copilot turns on their first day (#1910)
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
* fix(cursor): keep re-reading an unchanged DB until the agent-stream lookup past its cap is done

A parse looks up at most 9,000 agent-only request ids and leaves the rest
for the next parse. The result was still stored under the DB fingerprint,
and the session cache kept the source as unchanged, so on a DB that no
longer changes the ids past the cap were never billed.

A parse that leaves ids no longer writes cursor-results and reports itself
incomplete. The session cache then parks the source on a fingerprint no
file matches, so the next refresh reads it again, and holds the pass as
partial so no day is sealed without those calls.

* fix(copilot): keep a JetBrains turn on the day it was first seen when its store is written again

JetBrains turns carry the store file's mtime, not their own time. The
durable merge replaced each cached call with the fresh one of the same key,
so every store write moved the store's whole history to the newest write
day. Sealed days still held the turn on its old day, so the all-provider
30-day total counted it twice and came out above the Copilot-only total.

The merge now keeps the cached timestamp for copilot:jb: keys.

* fix(cursor): re-parse results stored before the lookup-cap fix

An install that already holds cursor-results written while ids were left
past the cap, on a DB that no longer changes, would keep serving them and
its session-cache entry. CURSOR_CACHE_VERSION goes to 9 and the cursor parse
version gains cap-resume-v1, so such an install re-parses once.

* fix(cursor): state the bound on holding the pass partial for a lookup backlog

Hydration is one flag for all providers, so an incomplete Cursor source holds
sealing for every provider. Each refresh resolves 9,000 more ids, so a backlog
of n ids clears in ceil(n / 9000) refreshes; a test shows the second refresh
of a 9,001-id DB completes the pass.
2026-11-07 13:29:45 +01:00
Resham Joshi
b823f98f2e
Fix upgrade-path script safety and currency labels (#1914)
* fix(upgrade-path): build the Copilot fixture under the corpus home on every platform

On win32 the fixture path came from the real APPDATA and the generator rmSync'd the user's real agent-traces.db. It now derives from the throwaway home and throws if the path resolves outside it. Checked by loading the generator with process.platform mocked to darwin, win32 and linux and APPDATA pointing elsewhere: all three wrote under the corpus home.

* fix(upgrade-path): fail parity on unclassified provider differences

A provider outside the exact and changed lists only added a note, so parity could never fail for it. Differences now push a failure; identical stays a note. Checked with a two-dir fixture: differing zzz tokens print FAIL and parity reports 1 difference; identical dirs report parity ok.

* fix(upgrade-path): a warm run with no pending-parse line passes

The warm check was skipped when no 'parse workers=' line printed, but that line only prints when work is pending. No line is now a pass; a line with pending work still fails.

* fix(gnome): budget alert converted currency twice

Cost was multiplied by the FX rate and then _fmt multiplied again. Before, EUR at 0.9 with 100 USD spent over a 50 USD limit: cost 90 -> _fmt 81.00 EUR / thresholdConverted 45 -> 40.50. After: 90.00 EUR / 45.00 EUR.

* fix(mac): cost per edit honours the selected currency

Both cost-per-edit labels printed a literal dollar sign with no FX rate; they now use the currency symbol and rate like the neighbouring values.

* fix(mac): menubar placeholder uses the currency symbol

The no-data title showed a dollar sign under other currencies.

* test(upgrade-path): containment via path.relative, warm check proves no cache file changed, add vitest coverage

Helpers moved to scripts/upgrade-path/lib.mjs so they can be imported. The guard no longer breaks on drive or UNC roots. The warm check now compares mtime and size of every cache file before and after the warm run; the parse-workers line is secondary.

* fix(upgrade-path): anchor the pending-files match, hash cache contents, allow dot-prefixed child names

Adds tests for each, plus a wiring test that runs gen-corpus under a mocked win32 platform and checks run.mjs uses the shared warm helpers.

* test(upgrade-path): run the gen-corpus wiring test on the host platform

* fix(mac): route the cost-per-edit suffix through the localization catalog

The localization coverage test flagged the new interpolated literal. Adds the %@/edit key to every locale.

* fix(upgrade-path): warm snapshot ignores the envelope and index files

A warm run rewrites envelope.json and republishes the codex month index under a new name with identical content (known #1032 churn), so those two cannot be part of a no-change snapshot. Their content is already covered by the existing shard check (piece, key file and index bodies unchanged); every piece and key file is still content-hashed here.

* fix(upgrade-path): classify the copilot input carve-out from #1830

#1830 f846b630: OTel input_tokens is cache-inclusive, cache reads carved out of inputTokens. inputTokens and cost may only drop; calls, output, reasoning, cache read and cache write stay exact. Tests: the corpus-shaped drop passes, a cost rise, input rise or cache-read change fails.

* fix(upgrade-path): pin the copilot #1830 figures exactly, tolerate unreadable cache entries

Seeded corpus is deterministic, so copilot must land on inputTokens 627176 and cost 3.015976 with every other field exact; anything else fails naming #1830. treeStats skips an unreadable entry or dangling symlink with a note. Index/envelope exclusion stays: a real re-parse rewrites piece files, which are hashed.

* test(upgrade-path): import gen-corpus by file URL so the wiring test runs on Windows

A bare drive-letter path is not a valid ESM specifier (ERR_UNSUPPORTED_ESM_URL_SCHEME), so the child died at startup on Windows. The test now uses pathToFileURL and reports status, stderr and the fixture path on failure.

* test(upgrade-path): skip the corpus-generating wiring test on Windows

The Windows upgrade-path job is the end-to-end check there; the child that builds the whole corpus exceeds the test timeout on that runner.
2026-11-07 12:44:24 +01:00
Resham Joshi
12d5643109
fix(guard): keep the loop stop in place after a deny, let failing polls wait, count env and multi-line waits (#1909)
* fix(guard): a denied call never counts as a changed answer, so the loop stop holds

The API gives every tool_use a tool_result, so a call the hook denied lands in
the transcript with the deny reason as an is_error result. That result was
hashed like a real answer and broke the identical run at the denied call, so
after the stop at call 8 the next seven identical calls passed again. The hook
now records the deny on the call and the fold never takes a result for it.

* fix(guard): a waiting check is exempt from the retry stop too

The sleep-then-check exemption only reset the loop run. A poll whose check
exits non-zero while it waits (gh pr checks exits 8 while checks are pending)
was still counted as a failed retry, warned at the 4th poll and denied from
the 6th.

* fix(guard): a sleep before env or a second line of work still counts as a loop

The waiting-check exemption trusted the shared read list after the sleep, and
that list counts env as a read and does not split on newlines. So
`sleep 5 && env CI=1 npm run build` or a sleep, a read and a build on the next
line were never counted. Those are now rejected in the guard's own check; the
shared list is unchanged, so the stored optimize facts keep their version.

* fix(guard): drop guard caches written before failures became consecutive

The retry count changed from every failure in the session to failures in a
row, but the cache version stayed at 4, so a session live across the upgrade
kept its old totals and could deny a command on its next run. Version 5 makes
each session re-fold its transcript once.

* fix(guard): a retry deny does not count its own result as another failure

A denied shell call lands with the deny reason as an is_error result, which
was folded as one more failure of that command, so the count in each further
deny grew with the guard's own denies.

* fix(guard): recognise the guard's own deny results when state is rebuilt

Deny marks live only in the guard's session cache. When that state is rebuilt
from the transcript (a version bump, a truncated file), the deny reasons read
as real answers again and the loop stop could lift. Every deny reason carries
a fixed mark, and a short is_error result with that mark is treated as a deny:
no result for the loop rule and no failure for the retry rule.

* fix(guard): a check run under env with only assignments is still a wait

Rejecting every env token also caught `sleep 5 && env GH_HOST=x gh pr checks N`,
a normal poll. An env that only sets variables is now dropped and the command
it runs is checked; env running a command that does work still counts.

* fix(guard): comment and blank lines after a waiting check keep the exemption

Rejecting any newline also caught a poll followed by a comment or blank lines.
Only a later line that holds a command now makes the call count as work.

* fix(guard): only the hook's exact deny reasons read as its own results

Any short is_error result that contained the mark was taken as a guard deny,
so a real failure printing it was never counted. Each deny reason now starts
with the mark, and only text in one of the hook's own reason shapes matches.

* fix(guard): a waiting check needs a numeric sleep duration

`sleep nope` waits on nothing, yet it matched the waiting check and was never
counted. The sleep argument must now be a number with an optional s/m/h/d unit.

* fix(guard): env with quoted assignments before a check is still a wait

`env X='a b' gh pr checks N` split the quoted value at its space and left a
fragment that read as a command. Quoted values are now part of the assignment,
and the assignments are dropped before the command is checked.

* fix(guard): a sleep with a dangling operator is not a waiting check

`sleep 5 &&` with nothing after it, or a check ending in && or |, passed as
a wait. Such a command is unfinished, so it now counts like any other.

* fix(guard): keep a deny mark until its result lands

The mark lived on the call in the 16-call recent window, so a denied call
whose result arrived after more than 16 other calls lost it, and its deny
result could count as a failure. Denied ids are now kept in their own list
until their result is folded.

* fix(guard): env -i or -u before a read-only check is still a wait

`sleep 5 && env -i GH_TOKEN=x gh pr checks N` only clears the environment
before a check, yet the flag made it count as work. -i, -u NAME and their long
forms are now dropped with the assignments before the command is checked.

* fix(guard): command substitution in a waiting check counts as work

`sleep 5 && env X="$(npm test)" gh pr checks N` ran the tests inside an
assignment that the env parser dropped, so the call passed as a wait. A check
with $( or a backtick anywhere, or an assignment value with ${, is now work.

* fix(guard): a variable sleep duration is still a wait

`sleep "$POLL_INTERVAL" && gh pr checks N` is a normal poll, but the numeric
duration rule counted it as a loop. A plain variable ($NAME, ${NAME}, quoted
or not) is accepted as the duration; a substitution is not.

* fix(guard): cap the deny marks waiting for a result at 64

Denied calls whose results never land would grow the list without end. The
oldest marks are dropped past 64; a result arrives right after its call.

* fix(guard): only a strict NAME=value counts as an assignment in a waiting check

A loose value pattern let `X=x;npm gh pr checks N` (and the same under env)
pass as a check, since the value swallowed the ; and the command after it. An
assignment value is now one bare word or one quoted string with no shell
metacharacter, in the gh prefix, the env prefix and every leading assignment
of a segment.

* fix(guard): env -C or --chdir before a read-only check is still a wait

Changing directory runs no command, so `sleep 5 && env --chdir=/tmp gh pr
checks N` is a poll. -C DIR and --chdir=DIR are now dropped with the other env
options that only shape the environment.

* fix(guard): a waiting check that writes a file counts as work

`sleep 5 && gh pr checks N > report.txt` writes a file on every run, yet it
passed as a read-only check. Output redirects now count as work unless they go
to /dev/null or another stream (2>&1), and gh checks may use those.

* fix(guard): read the deny shape only when no live mark exists

A genuine failure whose text matched a deny reason exactly was dropped even in
a live session, where the hook knows which calls it denied. Calls the hook
recorded itself are now flagged live, and the deny-shape match only applies to
calls without a live record or a pending deny (a rebuild or a call out of the
window).

* fix(guard): a quoted ; inside an assignment does not split the command

The assignment check split segments on every ; & |, so `X='a;b' gh pr checks N`
broke inside the quotes and read as a loose assignment. Segments now split only
outside quoted strings.

* fix(guard): process substitution in a waiting check counts as work

`sleep 5 && gh pr checks N <(npm test)` runs the tests on every poll. <( and
>( now make the call work, like $( and backticks.

* fix(guard): a plain variable in an assignment value keeps a check a wait

`sleep 5 && GH_HOST=$HOST gh pr checks N` is a normal poll, but the strict
assignment shape refused any $. A plain $NAME or ${NAME}, bare or in double
quotes, is now allowed; any other expansion still is not.

* fix(guard): a quoted argument spanning lines keeps a check a wait

`gh pr checks N --jq '.[]\n| .name'` was split inside the quotes and read as a
second line of work, and a quoted | was refused by the gh check. Lines and
segments now split only outside quoted strings, and the gh check accepts
quoted arguments.

* fix(guard): a backgrounded command is work, a single-quoted $( is not

`sleep 5 && gh pr checks 1&npm test` ran the tests in the background yet passed
as a check; a bare & outside quotes now counts as work (&& and 2>&1 are
fine). Substitution is now looked for outside single quotes only, so a jq
filter like '$(.name)' stays a wait while $( in double quotes still counts.

* fix(guard): resolver variables make a check work; escaped quotes stay quoted

PATH, LD_PRELOAD, DYLD_*, BASH_ENV, IFS and the like change which program a
read-only command runs, so setting one before a check now counts as work. The
quote-aware splitter also honours backslash escapes inside double quotes, so a
jq filter with \"foo;bar\" stays one check.
2026-11-07 12:44:20 +01:00
Resham Joshi
3b7b6b32e9
fix(cursor): skip malformed agentKv values instead of dropping every row (#1907)
* fix(cursor): keep the agent stream when an agentKv value is not valid JSON

agentKv blobs are content-addressed and also hold JSONL logs and files that
start with '{'. One such value made json_extract throw for the whole agent
stream query, which then dropped every tool and bash breakdown, every stream
input estimate and every agent-only session. Values that are not valid JSON
are now skipped and counted in the unreadable-entries notice. The bubble and
conversation queries get the same guard. Result cache v9 so a dormant
database re-parses.

* fix(cursor): re-parse session caches written before the agentKv json_valid guard

Installs that already ran a build with the previous Cursor parse version keep
serving its calls from the session cache, so the parser never runs and the
v9 result cache bump never applies.

* fix(cursor): admit JSON5 and JSONB values in the json_valid guard

One-argument json_valid accepts only canonical JSON, while json_extract also
reads JSON5 text and JSONB, so such rows were dropped and counted as
unreadable. Flag 6 matches what json_extract reads (SQLite 3.45+, which every
supported Node bundles).

* fix(cursor): require strictly valid JSONB in the json_valid guard

Flag 6 checks JSONB only superficially, so a structurally malformed blob
passed the guard and json_extract still aborted the whole query. Flag 10
accepts JSON5 text and strictly valid JSONB.

* fix(cursor): date an agent-only request from its prompt timestamp

A request with no bubble was billed at the database's last write. Cursor
opens each user turn with a <timestamp> tag, so the request now takes that
time, and a request whose prompt predates the lookback is dropped like one
with an old bubble. The tag also wins over a recorded first-seen stamp.

* fix(cursor): date an untagged agent-only request from the conversation that names it

A conversation records its latest request, and a subagent conversation the
request that spawned it. Such a request with no bubble and no prompt
timestamp now takes that conversation's start.

* fix(cursor): date an agent-only request between two same-day requests

A request with no bubble, no prompt timestamp and no conversation link takes
the time of the dated request written just before it in the agent stream,
when the dated request just after it falls on the same day. Otherwise it
keeps the first-seen stamp.

* fix(cursor): ignore a prompt timestamp with an impossible date or zone

Feb 30 rolled into March and an offset like UTC+99:99 shifted the time by
days, so such a tag dated or dropped the request. The calendar date, the
hour and the offset are now checked, and a tag that fails falls through to
the next dating rule.
2026-11-07 12:44:16 +01:00
Resham Joshi
81f86bf327
fix(desktop): keychain reads only on an explicit click; Copilot enterprise host and Windows path (#1912)
* fix(desktop): read the keychain for quota only on an explicit Refresh or Check now

Provider toggles, plan, currency, alias and price changes, project picks
and every other refreshToken bump polled quota with force=true, so main
granted keychain access and forgot an earlier Deny. Only the card's own
Refresh / Check now nonce forces now. The quota cache is keyed on the
disabled provider set, so switching a provider back on re-reads it
without forcing.

* fix(desktop): send a Copilot enterprise tenant token only to its own API host

The Electron Copilot quota twin picked github.com or the first entry and
always called api.github.com, so a hosts.json or apps.json holding only a
GitHub Enterprise Cloud tenant sent that tenant's token to dotcom every
poll. Port credentialFromMap, copilotAPIHost and copilotUsageEndpoint from
src: the token and the host now come from the same entry, *.ghe.com goes to
api.<tenant>.ghe.com, and any other host fails naming it without a request.

* fix(desktop): read the Windows Copilot login under %LOCALAPPDATA%

The Electron twin looked only at ~/.config/github-copilot, which the
plugins do not use on Windows, so the desktop showed Copilot as not
connected while the CLI and tray saw it. Port copilotConfigDirs from src:
%LOCALAPPDATA%\github-copilot first on Windows, the XDG path as fallback.

* fix(desktop): never join a quota run started for another provider set

A provider toggled during a fetch joined the in-flight run and got the
rows of the previous set. A run now carries its disabled-provider key and
only a call for the same set joins it or takes its hand-off. The test for
the forced-IPC refusal reset now runs the real service, stubbing only the
provider fan-out.

* fix(desktop): keep ⌘R a keychain-allowed quota refresh

refreshToken also bumps after config changes and project picks, so the
views no longer force on it. ⌘R and the IDE refresh command now bump a
separate token that Plans and Settings > Plans treat like the card's
Refresh button.

* fix(copilot): try the next credential folder when the first one cannot connect

On Windows the first folder (%LOCALAPPDATA%) won outright, so a stale
token or a host we cannot address there hid a working login under
~/.config. Both quota twins now take the first login of each folder in
order, skip hosts with no endpoint, and move on when a folder's token is
refused and the disk holds no rotated one.

* fix(copilot): fall back to apps.json in the same folder

A folder's hosts.json still won outright, so an unaddressable host or a
refused token there hid a working apps.json login beside it. Every
credential file is now its own candidate, in folder then file order, and
a token found in several files is tried once.

* fix(desktop): let an IDE refresh that opens Plans force its quota read

The command bumped the explicit-refresh token in the same render that
mounted Plans, so the view started from the new value and polled
unforced. The bump now runs after the navigation commits.

* fix(copilot): try every stored host, and move on after a 403 too

A credential file listing several hosts still yielded only its preferred
entry, a 403 ended the search, and a token shared with an unsupported
entry suppressed its supported twin. Each host entry is now a candidate
(preferred first), a 401 or 403 with no rotated token moves on to the
next one, and attempts are deduped by token plus host.

* fix(copilot): re-read a refused credential by its own map key

The re-read after a refusal matched by host, so with two entries for the
same host a rotation of the second one was never seen. Each credential
now carries the map key it came from and the re-read looks that key up.

* fix(copilot): read the host after a scheme, and dedupe logins only when sending

An apps.json key with a scheme (https://acme.ghe.com:Iv1.x) split at the
scheme's colon and read as hostless, so the tenant token went to dotcom.
The host is now read after an optional scheme. Entries are no longer
dropped at read time: a login already sent this run is skipped at send
time, after a re-read of its own entry, so a duplicate that rotated is
still tried.
2026-11-07 12:44:12 +01:00
Resham Joshi
b651f20f41
fix: keep slid-out Grok Bot requests through resets and partial slides, Hermes rebuild keeps observation days, drop Quick Desktop estimates once metered, Warp running exchanges and rung changes (#1913)
* fix(cache): keep a per-source durable entry across a fingerprint change and a failed parse

Grok Bot marks each mirror source durable, but the stale-section reset, the
dropStale load and the parse-failure path only looked at provider durability,
so a grokbot parse-version bump or a throwing parse dropped every request that
had slid out of the mirror. The cached file now records durable, its index row
carries a flag, and all three paths honour it.

* fix(grokbot): keep a request whole while its oldest entries slide out of the mirror

The durable merge replaced a cached request with the fresh one under the same
key, so a request that was partly past the 200-entry window lost its prompt and
most of its output, and moved to its last entry's day. For a per-source durable
file the merge now keeps the larger count of each token class and the earlier
start.

* fix(hermes): reprice a v3 ledger cursor in place instead of collapsing it onto the start day

The v4 rebuild replaced a multi-day cursor with one observation stamped at the
session start, so every later observation day lost its share and the cost moved
to a day that may already be sealed. Each observation now keeps its index and
timestamp and is scaled by the recomputed cost over the stored one; growth
since the v3 write lands as a new observation. The stored shape is unchanged,
so the ledger version stays 4.

* fix(quickdesk): drop a session's estimate at serve time once a metered call for it is cached

The sessions.db estimate was only dropped when sessions.db re-parsed, so
metrics that landed after the parse left the estimate served beside the
metered call until the user chatted again, and a day sealed in that window kept
both. The drop is now decided over the whole cached section on every serve.
That also holds when the metrics file is later removed: the metered call stays
cached as a durable orphan, so a sessions.db re-parse cannot bring the estimate
back, which folding the metrics files into the sessions.db fingerprint would
not cover.

* fix(warp): hold back a running exchange's share and re-split when the cost changes rung

Warp's conversation total also grows while an exchange runs, but that exchange
was left out until it finished, so the spend landed on the finished exchange
before it and stayed there. The newest exchange now takes its share of the
total while it runs, and that share is held back until it finishes. The cost
rung is stored on the cached call, so a cost that moves from credits to the
provider's own figure (or between any two rungs) is split fresh instead of
being booked as growth on the new exchange, as the comment already said.

* fix(cache): keep Grok Bot mirror entries written before the durable stamp across a fingerprint change

The first run after the upgrade that also changes env or parse version saw
index rows and files with no durable stamp and hid them before a re-parse could
stamp them. Without the stamp, a cached source now falls back to the provider's
per-source rule, the same transcript-slice match discovery uses to mark the
mirror durable.

* fix(grokbot): tell a slid tail from a correction by the request's first entry

Taking the larger count of each token class mixed a legitimate downward
re-read with the cached call (100/10 and 50/20 became 100/20). A call stamps
its request's first entry, so a fresh call that starts later than the cached
one has lost its head to the window and the cached call stays; one that starts
at the same entry is a re-read of the whole request and replaces it.

* fix(hermes): keep the rebuild flag through a snapshot smaller than the observations it reprices

A temporarily shrunken snapshot consumed the v3 rebuild flag without repricing,
so the later full snapshot booked the regrowth as new spend and the v3 figures
stayed. The flag is now consumed only by a snapshot at least as large as the
cursor's observation set, and the reprice is measured against that set.

* test(warp): pin where a held share goes when the running exchange is pruned

The held share is not lost: Warp's conversation total still carries it, and
the next parse books the growth on the latest remaining exchange. Billing it at
the running exchange's own time would need that exchange cached while it runs,
which is what holding it back avoids.

* docs(quickdesk): say why the serve-time estimate drop is not scoped to a day

* fix(warp): re-split once when a cached billed call predates the stored rung

A cache written before the rung was stored skipped the rung check, so a rung
change on the first re-parse after the upgrade was still booked as growth. A
billed call with no rung now counts as a mismatch, so it splits fresh once and
the rung is stored from then on.

* fix(grokbot): add a slid tail's growth to the cached request

When the head had left the window the cached call was kept as is, so output
added to the tail afterwards was dropped. A tail now keeps the cached call with
the larger count of each token class; a re-read from the same first entry still
replaces it.

* fix(hermes): reprice $0 observations by token share instead of dropping the rebuild unpriced

Observations stored at $0 beside their tokens cannot be scaled by recomputed
over stored, and the rebuild returned them unpriced while consuming the flag.
They now take the recomputed cost by token share.

* test(quickdesk): a migrated session's estimate is dropped when its metrics land in the profile store

The legacy root store and the profile store it migrated into hold the same
session under the same id, and the parse-time suppression matches across
stores for that reason. A store-scoped serve-time drop would serve both the
cached estimate and the metered call for such a session.

* fix(hermes): keep a priced observation's known cost beside a $0 one in the rebuild

Pricing every observation by token share moved known cost onto observations
stored at $0 (a $10 and a $0 observation became $5 and $5). Priced
observations are now scaled by recomputed over their stored sum, never up when
$0 observations sit beside them, and only the remainder goes to the $0 ones
by token share.

* fix(warp): release a running exchange whose conversation has not been written for a day

Warp's status values cannot be confirmed from this machine (only Cancelled
appears in the local store), so an exchange a crash left unfinished could hold
its share back forever. Warp writes the conversation while an exchange streams,
so a conversation untouched for 24 hours releases its newest unfinished exchange
as finished, with its share.
2026-11-07 12:44:08 +01:00
Resham Joshi
e88bff0678
fix(optimize, serve): count a last line read before its newline once, and stop dropping memos for garbage or non-scanning requests (#1911)
* fix(optimize): fold a last line read before its newline only once

A transcript read while its last line was complete JSON but still missing
its newline folded that line, yet stored the resume offset before it. When
the file grew, the resumed read folded the same line again, so the stored
record kept duplicate tool calls, cache writes and user entries until a full
rescan. A last line that parses now moves the stored offset past it; one
that does not parse is still re-read whole. Stored facts move to v3 so
records that already hold a duplicate are rebuilt.

* test(facts): pin the helpers that shape stored optimize facts

The FACTS_VERSION pin hashed scanFileRecord and compactOptimizeInput but not
the tool sets and caps compactOptimizeInput reads (isReadTool,
BASH_TOOL_NAMES, cappedString) or readSessionLines, which decides the lines
read and the resume offset. A change to any of them kept serving facts
stored under the old rule with no failing test. No rule changes here, so
the digest of the unreleased v3 is re-recorded.

* fix(serve): keep the scan headroom check to requests that scan transcripts

Every status request without --no-optimize counted as a transcript scan, so
`status --format json`, which the desktop polls for Plans and Settings and
which only reads two durable totals, had to start with 60% of the heap free.
Above that line it dropped every memo and the next panel paid a full reload.
Only optimize and menubar-json status run the scan now.

* fix(serve): collect garbage before a heap reading drops the memos

Used heap counts unreachable objects until the next collection, so right
after a large request the reading could sit far above the live heap and
release every memo of a healthy child, making the next request pay a full
reload. A heap verdict is now confirmed by a second reading taken after a
collection; resident size and a heap that stays high still release as
before.

* fix(optimize): resume past a last line only when it is a closed object or array

A last line without its newline that parsed as a bare scalar moved the
stored offset past it, so "1" followed by "23\n" was read as 1 and then 23
instead of 123. The tail now moves the offset only when it parsed into an
object or array, which later bytes cannot extend into a different valid
line; anything else is re-read whole.

The session cache keeps re-reading such a line on purpose: a prompt with no
reply yet forms no turn in the cached region, and the resumed read is what
puts it in front of the reply. A test pins that an append after an
unanswered prompt matches a fresh parse.

* fix(serve): release memos when the confirming collection fails

A collector that threw made the pressure check reject, which failed the
request instead of shedding memory. A failed collection now keeps the first
heap verdict and releases. A test also pins that the resident check goes
through the confirming helper.
2026-11-07 12:44:05 +01:00
Resham Joshi
760eadc4b6
fix(daily-cache): re-derive sealed days for the provider fixes (#1908)
* fix(cache): re-derive settled days after the November provider fixes

The codex, copilot, cursor, goose, quickdesk, qwen, hermes, droid, cline,
antigravity and warp fixes only bumped parse versions, so an existing install
kept serving the old figures for days already sealed in the daily cache:
Codex totals stayed at 51,450 calls while the session list showed 51,136.

DAILY_CACHE_VERSION goes to 79, which re-derives every surviving day from the
warm session cache. Providers whose calls can leave a settled day (codex,
copilot, cursor, goose, quickdesk) join PENDING_REDERIVE_PROVIDER_VERSIONS at
79 so the partial-survival guard lets those days shrink once.

A day whose only Codex calls were turn-start rate-limit pings re-derives to
no Codex slice at all, which the merge would carry as pruned history. Such a
slice has no output and no cache reads, so it is dropped on that one
re-derive, next to the existing cursor-agent rule.

* fix(cache): carry Codex ping-only days instead of dropping them by shape

The Codex rule dropped any carried Codex day slice with no output and no
cache reads that the fresh parse lacked. A day slice records no estimated
share, so that shape cannot tell a removed rate-limit ping from a pruned day
of real input-only calls, and dropping it could lose history. The rule is
removed and the Hermes fixture restored.

Such days now stay carried. On the validation data that is 17 Codex calls,
$0.0030704, on 27 Sep, 29 Sep, 3 Oct and 4 Oct: the report shows 51,153
calls / $4,838.31062 against 51,136 / $4,838.30755 in the session list.

* fix(cache): drop a pending provider's emptied day inside its fresh span once

A pending provider's new accounting can empty a settled day outright: a
Codex day of rate-limit pings, a Goose session moved across midnight by the
UTC fix (counted again on the day it moved to), a Quick Desktop estimate its
metrics replaced. The merge carried those slices as pruned history, so the
days stayed stale or double counted. On the validation data that was 17
Codex calls, $0.0030704, on four days.

On the hydration that spends the entitlement, a carried slice of a pending
provider with no fresh slice is dropped when its day is on or after that
provider's earliest fresh day. Sources are pruned oldest first, so days
before it stay carried as pruned history.

Trade-off: a user who deleted one mid-history source file for a pending
provider loses that day's carried slice once.

* test(cache): pin a spent re-derive as idempotent and a pending provider without fresh rows as carried
2026-11-07 12:44:00 +01:00
Resham Joshi
7eaf8967fc
fix(copilot): keep chat journals beside a trace database, count each chat once, price Auto-mode requests, make the JetBrains parse linear (#1901)
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(copilot): keep chat-session journals of sessions agent-traces.db never recorded

Any agent-traces.db on disk used to hide every VS Code chatSessions journal,
including sessions OTel never saw and their copilotCredits billing. Journals
are now always discovered, and only the journal of a session the trace
database holds is left out at serve time.

* fix(copilot): count a chat once when OTel and its VS Code transcript both record it

A transcript of a conversation agent-traces.db also holds became an extra
$0 estimated call beside every OTel call, inflating call and request counts
and marking the session partly estimated. The transcript of such a session is
now left out at serve time, which also clears transcripts already cached.

* fix(copilot): attribute JetBrains turns to conversations in one pass

Every turn scanned the whole store backwards once per conversation, so the
parse grew with conversations x turns x store size. A synthetic store of 80
conversations x 20 turns (3.7 MB) took 81.7 s and now takes 49 ms. Every GUID
occurrence is collected once and each turn takes the last one at or before
its offset, the same rule as before.

* fix(copilot): keep the cached agent-traces.db entry when a read fails

A corrupt, half-rewritten or otherwise unreadable agent-traces.db raised a
plain error, so the parse recorded a failed entry over the cached one. Once
the extension pruned old spans, that history was gone for good. Every open or
query failure now defers like a locked database, as the session-store parser
already does: the cached spans keep serving and the next refresh retries.

* fix(copilot): keep estimated thinking tokens in the served price of legacy chats

Legacy chat JSON without token counts estimates thinking separately. The
provider priced it as output plus reasoning, but serving re-prices Copilot
from outputTokens alone (reasoning is inside output there), so a request with
100k thinking tokens served at almost $0. The estimate now puts reasoning
inside outputTokens, so cold and cached reads agree. Copilot parse version
bumped so cached calls re-parse once.

* fix(copilot): price Auto-mode journal requests that name no resolved model

A chatSessions journal request in Auto mode with token counts but no
resolvedModel or copilotCredits served as model 'auto' at $0, flagged nowhere
as estimated. It now takes the same inference as the legacy chat JSON path
(tool-call id prefix, else the session's model) and is marked estimated
unless billing credits price it. Copilot parse version bumped so cached calls
re-parse once.

* fix(copilot): report uninferable Auto journal requests as unpriced and keep credit-priced labels

An Auto request with nothing to infer a model from still served as 'auto' at
$0, which no unpriced check flags. It now serves as 'unknown', not marked
estimated, so it reports as unpriced. A request copilotCredits already price
keeps its own label instead of an inferred one.

* fix(copilot): defer only locked agent-traces.db reads, keep cached turns on other failures

Treating every OTel read failure as busy made a permanently corrupt
agent-traces.db retry on every refresh and hold daily-cache finalisation
forever. Only SQLITE_BUSY/LOCKED defer again. Any other parse failure of a
durable provider's source now keeps the cached turns under the failed marker,
so the pruned history survives, the file is not retried until it changes,
finalisation proceeds and doctor lists the failure. A later good parse clears
the marker.

* fix(copilot): match OTel twins by VS Code storage as well as session id

The serve-time dedupe keyed on session id alone, so an OTel session in one
workspace dropped an unrelated journal or transcript with the same id in
another. OTel calls now record the storage of their session's newest journal
or transcript, and only that storage's copy is dropped. OTel calls cached
before this still match by id until they re-parse; the Copilot parse version
is bumped so live spans re-parse once.

* fix(copilot): drop OTel twins only when one VS Code storage holds the session

Picking the newest copy guessed which workspace an OTel session belonged to,
and spans carry nothing that names one. A journal or transcript is now dropped
only when its session id lives in exactly one storage; with copies in several,
every copy is kept, preferring a possible double count over dropping the wrong
workspace. The twin keys are collected in a full pass first, so file order
cannot change the result. The per-call chatStorage field and its parse-version
bump are removed again.

* fix(copilot): match OTel twins per request, not per session

A session OTel recorded had every journal and transcript call dropped,
including requests the trace never saw (before it was enabled, or after the
database was deleted while its cached spans kept the session classified as
traced). Spans carry no VS Code request id, so the match is by time within the
session: a journal request is dropped only when an OTel span starts between
its timestamp and the next request's, a transcript message only when one
starts since the previous message. Anything else is kept.

* fix(copilot): keep the lowest-path copy of a chat session found in two storages

A session VS Code copied into a second storage carries the same dedup keys,
and the copy parsed first kept them, so which workspace it served under
depended on directory listing order. Journals and transcripts are now parsed
in path order, so the copy under the lowest storage path wins on a fresh
parse. A copy already cached keeps its keys.

* fix(cache): retry a failed provider source once a day

A failed-parse marker kept the file's fingerprint, so a repair that left size
and mtime unchanged was never re-read. The marker now records when it failed,
and a provider source whose marker is a day old is parsed again even at the
same fingerprint. Markers written before this carry no stamp and retry once.

* test(cache): a failing durable source keeps its rows, shows in doctor, retries daily

The failed-marker change in this branch applies to every provider with
durableSources, today Copilot and Quick Desktop, not only Copilot: when a
source that already has cached turns fails to parse with an error other than
a locked database, its cached turns are kept under the failed marker instead
of being replaced by an empty one. Doctor lists the entry as failed, daily
finalisation is not held back, and the source is re-read when it changes or
once a day. This covers Quick Desktop end to end.

* fix(copilot): give journal requests stamped alike one shared OTel window

Two journal requests with the same timestamp sorted into a zero-width window
for the first, so a span at that stamp dropped only one of them. Calls stamped
alike now share one window bounded by the nearest distinct stamps.

On same-id twins across workspaces: the journal's session id is the VS Code
chat session UUID (file name and sessionId), and Copilot Chat sets
gen_ai.conversation.id, copilot_chat.session_id and copilot_chat.chat_session_id
on its chat spans from that same id. A pair sharing the id is the same session,
not an unrelated one; two storages holding it are a copy VS Code made, which
is why the multi-storage case keeps both copies instead of guessing.

* fix(copilot): attribute JetBrains turns to uppercase conversation GUIDs

Conversation records and the owner scan matched lowercase GUIDs only, so a
turn under an uppercase GUID fell back to the store id (as it already did
before the one-pass scan). Both now match either case. Java's
UUID.toString() writes lowercase, so no cached store is expected to move;
one written with uppercase ids would re-key its turns from the store id to
the GUID.

On the daily retry of failed sources (previous commits): it applies to every
provider parsed through parseProviderSources, that is every provider except
Claude's transcript scan, durable or not. That is intended: a failed marker
only caches a negative result, so one re-read per broken file per day is
cheap, and it is the only way to pick up a repair that kept size and mtime.

* fix(copilot): match JetBrains conversation GUIDs case-insensitively

Conversation ids were stored as written and looked up case-sensitively, so a
GUID declared in uppercase but referenced in lowercase before a turn handed the
turn to whichever conversation was declared last. Ids are now lowercased on
insert and lookup, which is also the form Java's UUID.toString() writes.

The OTel request window stays strict, with no backward tolerance. This machine
has no agent-traces.db, so no real skew could be measured. VS Code core stamps
a journal request with Date.now() when it creates the request model
(queuePendingRequest), before the extension handler that starts the chat
spans runs, on the same clock. So a request's spans start at or after its
stamp. A queued request is stamped while the previous one is still running,
so that request's late spans can start after the next stamp. A backward
tolerance would give those late spans to the next request.

* fix(copilot): re-parse cached JetBrains stores for the GUID-case fix

Bumps the Copilot parse version so an already-cached JetBrains store is
re-read under case-insensitive conversation matching. Stores with lowercase
GUIDs (Java's UUID.toString() form) attribute exactly as before, so their
dedup keys and totals do not move. A store using uppercase or mixed-case ids
gets new conversation ids in its keys, and the durable union keeps the old
copies beside them, so such a store would count those turns twice.

* fix(copilot): let a re-attributed JetBrains reply replace its cached copy

A parse-version bump does not evict anything for Copilot: the section is
carried forward with a forced re-read (getOrCreateProviderSection), and the
durable merge replaces calls whose key the re-read produces, appends new keys
and keeps every other cached key. A JetBrains reply that the GUID-case fix
files under a different conversation gets a new key, so its old copy stayed
beside it and counted twice. JetBrains keys end in the reply's content hash.
The merge now drops a cached JetBrains call whose hash the re-read produced
under another key. Replies the store no longer holds produce no fresh hash
and stay. No other key changes in this branch: the estimated-reasoning and
Auto-model fixes keep their keys and are replaced in place.

* fix(copilot): drop a cached JetBrains reply only when the re-read restamps the same turn

Matching on the reply hash alone let a live conversation's "OK" remove a
pruned conversation's cached "OK". A cached JetBrains call is now dropped only
when the re-read produced the same reply hash, the same :n index and the same
timestamp under another key. JetBrains calls carry the store's mtime, so this
removes the old copy when a store is re-attributed without changing (the
parse-version bump), and keeps a same-text reply cached at another stamp. A
store that changed between its last parse and the re-read keeps both copies
of a re-attributed reply.

* test(copilot): fix the time base once so stamped-alike requests share a stamp

at() read Date.now() on every call, so two requests meant to share a stamp
could land a millisecond apart and fall into different windows.
2026-11-06 18:02:02 +01:00
Resham Joshi
3df99229cf
fix(cursor): stop re-billing old conversations as today, refresh the workspace map, read each prompt from its own row (#1900)
* fix(cursor): stop billing old agent streams at the latest database write

A request whose bubbles predate the six-month window was treated as an
agent-only session and stamped with the database mtime, so every Cursor
write moved old conversations into today. Such requests are now skipped,
and real agent-only sessions keep the time they were first seen.

* fix(cursor): rebuild the workspace map on every discovery

The map was cached for the life of the process, so in the desktop app and
menubar every chat started after launch landed in the catch-all cursor
project until a restart.

* fix(cursor): take each turn's prompt from its own bubble

Prompts came from a second query that also admitted user bubbles without
createdAt, which the turn scan skips. One such draft shifted every later
reply in the conversation onto the previous prompt. Each user turn now
reads the text of the bubble it was scanned from.

* fix(cursor): keep agent-only first-seen times in their own file

The first-seen time came from the previous result cache, so clearing it or
bumping its version re-stamped every agent-only session at the current
database write. It now lives in cursor-first-seen.json, written atomically
and only when a new request appears.

* fix(cursor): look up only the unjoined request ids among the bubbles

The lookup returned every request id in the bubble table; it now asks for
the ids of the agent-only streams alone and is skipped when there are none.

* test(cursor): pin prompt pairing when the scan budget cuts a user bubble

* fix(cursor): rebuild the workspace map only when workspace storage changed

Discovery now stats the workspace storage directory and each workspace's
state.vscdb and keeps the map when none moved, instead of reopening every
workspace database on each scan.

* test(cursor): pin first-seen with a fake clock

* fix(cursor): merge first-seen entries under a lock instead of overwriting

Two parses that each added a request could overwrite each other, and a
later result-cache clear then re-stamped the lost one. The write now
re-reads the file under its own lock and keeps every recorded time.

* fix(cursor): bind at most 900 request ids per bubble lookup

Older SQLite builds cap bound parameters at 999, so a 10,000-id chunk could
fail with too many SQL variables.

* fix(cursor): ignore first-seen values that are not ISO timestamps

A hand-edited or corrupt entry was emitted as the call's timestamp; such
entries now fall back to the database mtime like a new request.

* fix(cursor): keep billing a recent stream whose bubbles the scan budget cut

The bubble lookup suppressed any stream whose request id appeared on a
bubble, including recent ones the scan budget left out. It now suppresses
only when the newest such bubble predates the window, and bills a cut
stream at that bubble's time.

* fix(cursor): write first-seen fragments when the sidecar lock is busy

An unlocked merged write could still replace another writer's entries.
Without the lock a parse now writes its own per-process fragment; reads
merge every fragment, and the next lock holder folds them into the main
file and removes them.

* docs(cursor): note the limits of the workspace storage stamp

* fix(cursor): bill an agent-only stream whose bubble has no createdAt

A stream whose only bubble carried its request id but no createdAt was
suppressed as if that bubble were old. Only a bubble dated before the
window suppresses a stream now; an undated one falls back to the
first-seen time.

* fix(cursor): serialise first-seen writes within one process

Two concurrent writes that both missed the lock read the same per-process
fragment and the last rename dropped the other's entries. Writes in one
process now queue behind each other.

* perf(cursor): take the newest bubble time per request outside SQL

Measured read-only on the owner's Cursor database (3.75 GB, 60,438
bubbles, 644 request ids that would be unjoined, one 900-id chunk):
GROUP BY with MAX took about 3.0 s per run (2.7 to 3.2 s over five runs)
because it re-reads every bubble's JSON; selecting the matching rows
(379) and taking the newest time in code takes about 0.87 s. For scale,
the window's own bubble scan takes about 1.3 s and an unbounded DISTINCT
over all request ids about 0.9 s. On that machine the lookup does not run
today: the agent-stream query fails on malformed JSON, so no stream is
unjoined.

* perf(cursor): cap the unjoined request-id lookup at ten chunks

Each 900-id chunk is one bubble-table scan, about 0.9 s on a 3.75 GB
database, so tens of thousands of unjoined ids could block for a minute.
The lookup now stops at 9,000 ids (about 9 s); ids past the cap are
billed at their first-seen time or the database mtime, like ids no
bubble carries.

* fix(cursor): leave ids past the lookup cap for the next parse

Ids past the cap were billed at the database mtime, which re-billed old
conversations exactly as before the window fix. They are now neither
emitted nor stamped; each looked-up id's newest bubble time is kept in the
first-seen file, so the next parse skips resolved ids and resumes in sorted
order until every id has had the old-bubble rule applied.

* fix(cursor): treat an unparseable bubble createdAt as undated

A numeric createdAt became the call's timestamp, and a string that sorts
below the window start suppressed a billable stream. The lookup now keeps
only times that parse, normalised to ISO; anything else takes the
first-seen time or the database mtime.

* test(cursor): pin prompts for user bubbles with null or missing text

* fix(cursor): retire v7 Cursor results

A v7 cursor-results file built by the old parser keeps serving its calls,
including old agent streams billed at the database mtime, for as long as
the database is unchanged; on a dormant install that is forever. Bumping
to v8 forces one re-parse. On today's real data it changes nothing beyond
that one re-parse.

* test(cursor): insert bulk agent-stream fixtures in one transaction

Each row was its own autocommit write, which pushed the 9,000-row test
past the 30 s timeout on the Windows runner. One transaction and one
prepared statement take it from about 6.5 s to about 0.1 s locally.
2026-11-06 17:58:14 +01:00
Resham Joshi
402b49b7ff
fix(codex): no phantom call from a rate-limit ping, no negative output on a counter restart, fork replays counted once; Goose UTC timestamps; Kimi subagents per session (#1903)
* 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.

* fix(codex): keep the file stem as the session id, use the thread id only in dedup keys

The previous commit also moved the visible session id of payload.id-only
rollouts from the file stem to the UUID, which changes their label and
identity in session views. Only the dedup keys need the thread id, so keep
sessionId as it was and carry the thread id separately, across append
resumes too.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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).

* 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.

* 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.

* 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.

* 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 17:11:52 +01:00
Resham Joshi
889f2fac1d
fix(providers): Cline family keeps recorded costs, Antigravity RPC output, Warp day attribution, busy stores deferred for Zed, Quick Desktop, Grok Bot and Vercel (#1905)
* fix(cline): keep the cost each Cline, KiloCode and IBM Bob request recorded

The parser read Cline's per-request cost but never marked it as billed, so the
cache dropped it and every read re-priced the tokens at a list price, or at a
stand-in model when the task named none. A positive recorded cost now survives
the cache; requests without one stay re-priceable. Parse versions bumped for
cline, kilo-code and ibm-bob so cached tasks pick the cost up.

* fix(cline): key Cline-family tasks on ui_messages.json, not the task directory

Cline rewrites ui_messages.json in place, which never moves the task
directory's mtime or size, so a growing task kept serving its first cached
snapshot. The source is now the file itself; the new path re-parses every
task once on its own, so no parse-version bump is needed.

* fix(antigravity): keep RPC output tokens when the response/thinking split is absent

Generator metadata from the language server omits unset proto3 fields, so an
entry carrying only outputTokens was stored and priced with 0 output. The RPC
path now reconciles the split the way the SQLite path already does. Results
cache v11 and an antigravity parse-version bump re-read cached cascades.

* fix(parser): label Devin and Antigravity token-priced costs as calculated

Both providers keep the cost they priced from tokens at parse time through the
cache, and that kept cost was served with costBasis 'recorded', the label for
a tool's own billed figure. They now serve as 'calculated'. Decided at serve
time, so cached calls change label without a re-parse and totals are
unchanged; serve-time re-pricing still needs the pricing id stored.

* fix(warp): put a conversation's new spend on its new exchanges

Warp records cost and tokens per conversation, and each parse re-split the
running total over every finished exchange, so a later exchange's spend moved
onto earlier days. Exchanges already in the cache now keep their share and
only the growth since the last parse is split over the new ones. No new state:
the previous split is read from the cache entry being replaced.

* fix(warp): discover Warp on Linux and Windows

Only the macOS group-container paths were tried, so Warp on Linux or Windows
reported nothing unless WARP_DB_PATH was set. Adds the default locations from
Warp's file-locations docs: $XDG_STATE_HOME/warp-terminal (and -preview) on
Linux, %LOCALAPPDATA%\warp\Warp\data on Windows. Both variables join warp's
cache fingerprint.

* fix(zed): defer a locked threads.db instead of reading it as empty

Zed's whole history is one source, so a SQLITE_BUSY on open or on the threads
query parsed as zero calls and replaced every cached Zed thread for the run.
Busy errors now reach the parse loop, which keeps the cached rows and retries
on the next refresh, like the other SQLite providers.

* fix(quickdesk): stop counting a session's estimate after its metrics arrive

Quick Desktop sources are merged durably, so a sessions.db estimate cached
before the session's metrics landed was never removed and the session counted
twice from then on. The sessions.db source is now marked as a snapshot of the
store, replaced on each re-parse; a locked store defers the parse (cached rows
kept, retried next refresh) instead of reading as empty. Parse version bumped
so cached double counts re-parse.

* fix(grokbot): keep requests that slide out of Grok Bot's mirror window

The app mirrors only about the last 200 transcript entries per bot, and each
re-parse replaced the cached calls with the current window, so older requests
vanished from live views as a busy bot kept working. Grok Bot sources are now
durable: requests the window dropped stay cached, ones still in it are
refreshed in place.

* fix(vercel-gateway): keep the cached report when a refresh cannot fetch it

An unreachable gateway, a rate limit or a server error parsed as an empty
report, so the run showed $0 of gateway spend with nothing but a stderr line.
Those failures now defer the source the way a busy SQLite store does: the
cached report keeps serving, the run is marked not fully hydrated, and the
next refresh retries. A refused credential still reads as no report.

* fix(grokbot): make only the mirror slices durable, not the import source

Marking the whole provider durable also kept a removed usage import's rows,
so removing an import no longer restored the local figures. Durability is now
a per-source override (SessionSource.durable, which replaces the snapshot flag
from the Quick Desktop fix): Grok Bot's mirror slices merge, Quick Desktop's
sessions.db replaces, and orphan handling stays with the provider.

* test(warp): expect the platform's own Warp candidates in probe roots

* fix(cline): keep a recorded zero cost at zero

A request Cline recorded at cost 0 (a free model) was re-priced from tokens
into a positive charge. Any recorded cost, zero included, is now kept; only a
request with no cost field is priced from its tokens.

* test(warp): pin per-conversation allocation of new spend

Each Warp conversation is its own source and keepCachedWarpShares only sees
that source's cached entry and calls, so one conversation's growth can never
land on another's new exchanges. Two conversations gaining exchanges together,
only one with billed growth, now pin that.

* fix(warp): probe Warp's Linux paths only on Linux

Every non-macOS, non-Windows platform fell through to the Linux locations.
Candidates are now exact per platform: macOS bundles, Linux state dirs,
Windows LOCALAPPDATA, and none elsewhere.

* fix(vercel-gateway): stop retrying a gateway that keeps failing every refresh

A permanently unreachable gateway (DNS failure, persistent 5xx) deferred
every refresh forever: stale rows served, the run never fully hydrated. A
network source now counts consecutive retryable failures on its cache entry;
the third marks it failed with its rows kept, so it serves those rows without
fetching until the next day (a credential change still invalidates it) and
shows in doctor as a cached failure. A successful fetch resets the count.

* fix(warp): split fresh when a cached exchange disappears

When an exchange the cache held is no longer in Warp's table, the kept shares
no longer add up to the reported total and the gap went wholly to the latest
exchange. A current exchange set that is not a superset of the cached one now
discards the cached split and splits the current total fresh.

* fix(vercel-gateway): treat 408, 409 and 425 as retryable report failures

A request timeout, conflict or too-early answer was read as a definitive empty
report. They now keep the cached report and retry like 429 and 5xx: the
statuses Vercel's own AI SDK retries, plus 425, which asks for a retry.

* test(grokbot): a removed import's rows go while the mirror's rows stay

* test(cline): a task cached under its old directory key is evicted, not doubled

* test(warp): two conversations in one database are allocated independently

A Warp source is exactly one conversation: discoverFromDb (src/providers/
warp.ts) emits one source per agent_conversations row with path
'<db>:<conversation_id>', the parser reads only rows WHERE conversation_id = ?
for that id, and parser.ts hands keepCachedWarpShares only
section.files[source.path], the cache entry of that one conversation. Nothing
is pooled across conversations. Pinned with the case where A gains $3.75 and
an exchange while B gains a zero-spend exchange: A's new exchange carries
$3.75, B's $0.

* test(vercel-gateway): pin every retryable status and the refused-credential case

* fix(cline): re-read a task when api_conversation_history.json changes

The Cline-family source is ui_messages.json, but the task's model and
workspace come from api_conversation_history.json. A history file written
after the first parse never moved the fingerprint, so the task kept its
stand-in model and pricing. The fingerprint of a ui_messages.json now folds in
the sibling's inode, mtime and size, a missing sibling being its own state,
while ui_messages.json stays the source key.

* fix(antigravity): let the output total win whenever the split disagrees

Rule: ModelUsageStats' output total (field 3 / outputTokens, documented as
thinking + response) is authoritative whenever it is set. The existing
reconciliation already trusted it over a disagreeing split, but skipped the
case where thinking alone exceeded the total, so outputTokens 100 with
thinking 200 and response 50 kept 250. That case now caps thinking at the
total and leaves response at 0. One shared helper applies the rule on the RPC
and SQLite paths; the unreleased rpc-output-total-v1 bump already re-parses
cached cascades.

* fix(antigravity): apply the output-total rule to a total of 0 as well

A record with output total 0 beside a nonzero thinking/response split kept
the split, against the total-wins rule. Antigravity never writes that shape:
a read-only scan of every gen_metadata row in the owner's Antigravity
conversation databases (166 rows, 9 files) found 165 whose split sums exactly
to the total and none with a zero total beside a nonzero split. The .pb
conversations are readable only through the running app, so they were not
scanned. A total of 0 now caps the split at 0 like any other total.

* fix(antigravity): keep the split when the output total is absent

The previous commit treated a missing output total like an explicit 0 and cut
a recorded thinking/response split down to nothing. An absent total (no
outputTokens key on the RPC path, field 3 not set in the SQLite proto) now
keeps the split as before; a total that is present, 0 included, still wins
over a split that disagrees. Same rule on both paths.

* fix(antigravity): treat an unreadable output total as absent

An RPC usage entry whose outputTokens is present but not a number (an empty
string) was reconciled as NaN and produced NaN output. A total that does not
parse to a finite number now counts as absent and the split stands. On the
SQLite path a varint cannot be non-numeric; a field 3 of the wrong wire type
(no varint value) is likewise treated as absent.

* fix(warp): bump the parse version so cached databases take the share rule

An unchanged Warp database kept serving calls split by the old re-spread,
because nothing invalidated its cache entry. exchange-share-v1 re-parses it
once; the version is pinned in a test. Also pins that a conversation whose
exchanges are no longer finished clears its cached calls: keepCachedWarpShares
returns the empty set before reading any call, since every cached key is then
missing from the current set.

* test(warp): a cached conversation with no current exchanges yields no calls
2026-11-06 17:11:48 +01:00
Resham Joshi
5d9d7a0b2f
fix(quota): one keychain prompt per action, exact ZCode token boundary, expired Gemini login reported once (#1904)
* fix(quota): stop at the first keychain Deny instead of prompting again for the same item

A refused or unanswered lookup on the user account fell through to the
service-only lookup, which matches the same item and raised a second
prompt. An unanswered dialog then waited twice, past the quota timeout,
and ended as "Timed out." The reader now returns accessDenied at the
first refusal; only a genuine miss tries the next account. The CLI row
says the access was denied or not answered.

* fix(quota): end the ZCode token at its journal frame length

The token was read greedily up to the first non-token byte, so when the
login ended a write batch the next record's checksum bytes could be
appended to it, and every poll sent a corrupted token and reported a
false "Login expired". The reader now decodes the value's varint length
and slices exactly the string after the encoding flag.

* fix(quota): report an expired Gemini login as needing the user

Without a refresh client an expired Gemini CLI token was sent as-is and
the 401 read as a transient failure on every poll, so the row stayed
"Temporarily unavailable" and never said what to do. A 401 on a token
whose expiry has passed and that nothing refreshed is now terminal, with
a footer to run Gemini CLI once, as Claude already does.

* fix(quota): stop only at a keychain Deny or unanswered prompt, and remember it for the run

An error that showed no prompt (an I/O failure, interaction not allowed) moves on to the next account again, as before. A Deny or a prompt left open until the timeout ends the lookup, and the CLI keeps that refusal for the rest of the process, so a second read of the same service answers without a prompt. Nothing is persisted, so the next run asks once. The Claude row now says which it was: denied, or not answered.

* fix(quota): treat a rejected Gemini login without a refresher as terminal

The stored expiry can be missing or skewed, so it no longer decides: with no client credentials or refresh token nothing here can mint a new token, and the 401 needs the user to run Gemini CLI. With a refresher configured the 401 stays transient.

* fix(quota): pick the newest ZCode login by journal position across encodings

Latin-1 matches were preferred over UTF-16LE ones, so a rotation that changed the string encoding returned the older token. The last write by offset now wins regardless of encoding.

* fix(quota): remember a keychain refusal per account and classify only our own timeout as unanswered

The run's refusal memo is keyed by service and account, so denying one account no longer hides another account's item. Only the kill from our own timeout counts as an unanswered prompt; any other signal is an ordinary error that moves on. A string exit code is normalised, so "128" is a Deny like 128.

* fix(quota): report a ZCode login the app cleared as expired

An empty newest write for the key means the app cleared the login. It used to be skipped, so an older token in the same or an older journal was sent instead. It now reads as an expired login without a request.

* fix(quota): skip a refused keychain account, time prompts with our own timer, and remember refusals in the desktop app

A refusal remembered for one account now skips that account (and the service-only lookup, which can match the same item) and goes on to the next named account, instead of ending the read. An unanswered prompt is now only our own 90 s timer firing: the lookup runs under an AbortSignal whose timer sets a flag, and a kill or signal we did not cause is an ordinary error that moves on. The desktop app keeps the same service-plus-account refusals; a keychain-allowed refresh, which is the user acting again, clears them, so one action asks at most once per item.

* fix(quota): treat a malformed newest ZCode write as unreadable, not as the older token

Only the newest write of the key is read now. If its frame does not parse (no length, zero length, a length past the end of the file, an unknown flag, or bytes that are not a token) the poll reports a transient failure without a request, instead of falling back to an older token the app already replaced. This cannot be narrowed to in-progress writes: the leveldb log splits a record that crosses a 32 KiB block boundary with a 7-byte header, so a complete write can also fail to parse as one contiguous frame, and a torn tail after a crash looks the same. Both are treated as unreadable for this poll.

* fix(quota): count only real leveldb records of the ZCode key as writes

The newest write was the last place the key name appeared, so another entry whose value mentions the key (a settings blob, say) was read as a newer, malformed write and the login was reported unreadable. A token value itself cannot hold the key, since ':' is outside the token alphabet. An occurrence now counts only when it ends the key of a leveldb record: tag, varint key length, then `_`, origin, NUL, string flag and the name. A delete record of the key reads as a cleared login.

* fix(desktop): say whether the Claude keychain prompt was denied or left unanswered

The desktop keychain reader now carries the same refusal reason as the CLI's, and the Claude adapter turns it into the same footer line. The Plans card and the Settings row show that line in place of the generic keychain message for an access-denied row, keeping the generic copy when no reason is known.

* fix(quota): read the ZCode key only under its own origin and reject odd UTF-16 frames

A record now counts as a write of the login only when its key is ZCode's own origin prefix (`_https://zcode.z.ai`, a NUL, the string flag) followed by the key name, as in the recorded journal from #1347 (tag 01, key length 2b, `_https://zcode.z.ai`, 00 01, `oauth:zai:access_token`); the same key under another origin is ignored. A UTF-16 value with an odd byte count was trimmed by the decoder and could still look like a token; it is now read as unreadable for this poll, with no request and no older token.

Not changed: a counterfeit record header embedded inside another entry's value. The journal is ZCode's own local storage on the user's machine, not input from anyone else; whoever can write those bytes already holds the account, and with the origin check a forged record would also have to carry ZCode's exact origin prefix and a matching key length.

* fix(quota): skip a later service-only keychain lookup once an account of the service was refused

A service-only lookup can match the item the user just refused, so a refusal for any account now also marks the service-only lookup as refused for the run. A later read with only the service-only candidate answers from memory instead of prompting again. Named accounts that were not refused are still read.

Not changed: a Deny for one account still ends that read without trying the next account. That is deliberate: the consent policy is stop at Deny, and prompting for the next account right after the user declined is the double prompt this branch exists to remove.
2026-11-06 17:11:44 +01: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
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
0cb5644889
fix(desktop): decode CLI output as UTF-8, cap the decoded answer, stop rescanning the buffer (#1896)
* fix(desktop): decode CLI output across pipe chunks so split UTF-8 characters survive

* fix(desktop): cap serve answers by decoded size and fall back instead of killing the resident

* perf(desktop): scan only the new chunk for a serve line break

* fix(desktop): an over-cap answer fails its request without a cold retry

* fix(desktop): an oversized serve frame fails its request without a cold retry

* fix(desktop): give the serve frame room for an answer that escaping doubles

* test(desktop): feed serve frame boundaries and split UTF-8 as explicit chunks, count the newline scan
2026-11-06 09:27:36 +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
2ef2c20230
perf(app): stop prefetching Compare and Optimize through the serve queue (#1885)
The resident serve child answers one request at a time. A background
compare (about a minute) or optimize (10 to 70 s) made any click queue
behind it. Both payloads are small and persist, so a revisit still
paints from the snapshot; the first visit pays its own time only.
2026-11-05 22:55:24 +01:00
Resham Joshi
c1d6071add
fix(desktop): the punchcard request no longer runs the optimize scan (#1884) 2026-11-05 22:55:19 +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
fe901efc02
feat(windows): quota run-out forecast and crossing alerts in the tray (#1880)
* feat(windows): quota run-out forecast and crossing notices

Pace math and crossing state ported from the menubar. Readings stay in
memory per window for six hours; the forecast uses only the current
cycle, drops readings before the last fall, looks back 60 minutes on
short windows and six hours on long ones, and speaks only after two
readings ten minutes apart with a rise of two points. Notices fire at
the chosen threshold, at 100%, and once when the pace runs the window
out before it resets, deduped per cycle with the reset bucketed to the
minute.

* feat(windows): show the quota forecast and post crossing toasts

Every fresh quota answer records the readings, writes the forecast into
the windows it watches and posts a toast through the notification
plugin. The hover card shows "out 15:40" in place of the reset
countdown while a forecast exists, the plan rows caption it ("hits 100%
in 3h" or "lasts until reset") instead of the whole-window ETA, and
Settings gets the alert switch, default on, with a 70/80/90 threshold.
2026-11-05 18:02:04 +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
9ad37f2b1f
chore(telemetry): default on in every region (#1874)
* chore(telemetry): default on in every region, consent screen and toggle unchanged

The desktop app, the macOS menu bar and the Windows tray no longer pick the
telemetry default from the country. A fresh install starts with telemetry on
everywhere, including the EU, EEA, UK, Switzerland and an unknown region.
The country lists and the helpers that read them are gone.

A stored choice, on or off, is kept as before. The first-launch flow and the
Settings toggle are unchanged. The README and the code comments now say the
default is on in every region and that Settings turns it off.

* docs(telemetry): say what each surface does
2026-11-05 07:31:19 +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
c0a6917f0e
test(menubar): the 20x tier parses as Ultra in the named-windows case (#1873) 2026-11-05 05:28:04 +01:00