- Catch errors in 'sync setup' action: AuthError/DiscoveryError (login
timeout, port exhaustion, discovery failures) now print a clean one-line
message and exit 1 instead of crashing Node with an unhandled rejection
stack trace. Also guard the double rejection when all callback ports are
in use (both 'ready' and the callback promise reject).
- Windows: open the auth URL via 'rundll32 url.dll,FileProtocolHandler'
instead of 'cmd /c start'. cmd.exe splits its command line on '&', which
truncated the OAuth query string at the first parameter, so the IdP
received a bare /authorize request ('no parameters'). rundll32 receives
the URL as a plain process argument with no shell parsing.
- Theme the OAuth callback landing pages to match the dashboard (warm
paper background, ink text, forest-green success / terracotta failure),
fully inline with no network or asset dependencies.
AI-Origin: human
The desktop sessions resolver returned a single per-platform path, so
Microsoft Store (MSIX) installs of Claude Desktop were invisible: their
data lives under %LOCALAPPDATA%\Packages\<Claude package>\LocalCache\Roaming\Claude\local-agent-mode-sessions
and a filesystem junction workaround breaks Cowork's own file access
(reported and verified in #611).
getDesktopSessionsDir() becomes getDesktopSessionsDirs(): an ordered,
deduped candidate list (override, then classic APPDATA, then MSIX packages
matching Claude_* or *.Claude_*, existence-checked, lexicographically
sorted; .config on Linux). Results are memoized per env-input tuple so the
parser's per-file classification never rescans Packages. All call sites
scan every candidate; macOS, Linux and classic Windows behavior unchanged.
Fixes#611
- Resolve k3/k3-agent/k2d6-agent model aliases to canonical Kimi names
- Discover sessions across all Kimi Code homes (CLI + desktop runtime)
- Accept conv-*/ctitle-* session directory naming, not just session_*
- Add Kimi Code provider tab with brand color to the menubar
- Show short model names (Kimi K3, Kimi K2.6) in the menubar payload
* sessions: fold subagent runs into PR attribution
Sidechain (subagent) session cost never reached the by-PR view, so a
session orchestrated on one model with subagent lanes on another showed
only the parent model on every PR row. Fold each sidechain's cost, calls,
models, and categories into the parent turn that spawned it, so it
inherits that turn's PR set under the existing turn-level state machine.
Linkage, in priority order: the spawn result's toolUseResult.agentId
pairs the child's agent id with the Agent/Task tool_use id that launched
it (recorded per turn), which is the true launch point and wins even when
the child's first activity landed during a later turn; else the child's
first-activity timestamp is bucketed into the containing turn span; else
the child folds into the parent's unattributed spend. Children of parents
that referenced no PR, and orphans whose parent is absent from the scan,
contribute nothing, unchanged.
Cache v6 to v7 (neither shipped, so one combined bump from v5): per-turn
spawnToolUseIds, per-file parentSessionId and agentSpawnLinks; the
validator and the append/compact paths thread them like prRefs. By-PR
footers now count parents plus folded subagent runs and the payload gains
an additive subagentSessions field. distinctCost now includes folded
subagent spend, documented in the payload comment.
* sessions: address adversarial review of subagent PR attribution
Rework child attribution to resolve each subagent to the PR its launching
turn was working on, using the parent's UNFILTERED turn data, and enforce
that every dollar is counted exactly once.
- Mutual exclusion: a child that referenced its own PR attributes
standalone and is never folded; a child with no links is folded only.
Fixes a double-charge where a self-linking child was both folded and
self-attributed.
- Recursion: a fold aggregates a child plus its non-self-linking
descendants (depth-first, cycle-guarded), so grandchildren spawned by
subagents reach the PR report.
- Global linkage: the subagent index keys by parentSessionId alone
(UUIDs are globally unique), so a child whose worktree resolves to a
different project still links.
- Date-range correctness: spawn-to-PR sets are built at assembly from the
full turn list, so a spawn in a pre-range turn attributes to the right
PR; a PR-linked parent whose own turns fall out of range is kept as a
0-cost fold anchor so its in-range child is not lost.
- Timestamp fallback compares epoch ms (mixed UTC offsets order right) and
is end-bounded: a child active after the parent's last turn is unlinked
(contributes nothing), matching orphan semantics.
- Cache adoption tries the newest prior versioned file (v6 then v5) so the
preceding build's expired-PR history survives the v7 bump; an invariant
note requires the list to cover every version that can exist on disk.
- Spawn-result pairing matches the tool_result block that carries the
agentId, not the first block, when a record batches several results.
- resolveSubagentAttribution is computed once and shared by aggregateByPr
and prLinkedTotals.
subagentSessions now counts folded subtrees (children plus descendants).
Verified on real data: attributed + unattributed reconciles to cost, and
parent-only cost plus folded-children cost equals the folded total to the
cent (no double-count).
* sessions: round-2 hardening of subagent PR attribution
Address a second adversarial review of the new machinery.
- ID collision: parents and a child's parent reference are keyed by
provider + sessionId, not bare sessionId. When two distinct parents
still share a key (true duplicate/imported data), the child folds into
NEITHER (deterministic skip, stays standalone): correctness over
coverage.
- Recursion dedup is global: one claimed-set spans all of a parent's
direct children, so a descendant reachable through two paths (a diamond
or duplicate id) folds exactly once and a parent-link cycle terminates.
- Cache adoption migrates every prior version oldest-to-newest and MERGES
per source path (newer wins per entry), so a sparse or partial newer
file no longer masks older-only expired-PR orphans.
- Fold anchors (0-cost PR-linked parents kept only for attribution) live
in a new ProjectSummary.subagentAnchors, never in `sessions`, so they no
longer contaminate session counts, averages, or any per-session report.
Folded PR rows take their date span from the contributing child activity
rather than the anchor's empty timestamps.
- One-pass buildPrAttribution computes rows and totals together; the
payload builder and CLI call it once. Drops the identity-keyed
memoization, which could return stale folds if the array was mutated.
- Ambiguous multi-block spawn-result pairing leaves the spawn link unset
on purpose; the child then folds via the timestamp fallback rather than
pairing with the wrong id or disappearing.
Every fix is mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent (parent-only cost plus folded cost
equals the folded total) and that the PR rows sum to attributedCost.
* sessions: round-3 hardening of subagent PR attribution
Third adversarial review pass.
- Ambiguity counts ALL candidate parents (and anchors) sharing a
provider+sessionId key, not just PR-bearing ones, and uses a
per-record fingerprint: a key carried by more than one DISTINCT record
folds its child/subtree into NEITHER (identical duplicates still fold
once). This unifies the parent-collision and duplicate-descendant rules
and is deterministic across input order.
- Project-rebuilding filters (by day, by date range, by config source)
now carry subagentAnchors through, and a date filter CONVERTS a spawn
parent whose in-range turns are all filtered out into an anchor so a
surviving in-range child still folds. Rebuilt sessions also keep their
PR + subagent-linkage metadata (prLinks, parentSessionId, spawnPrSets,
...), which buildSessionSummary otherwise drops, so by-PR and folding
work on a filtered slice (menubar/dashboard flow).
- Fold anchors leave ProjectSummary.sessions entirely and folded PR rows
take their span from the child, so 0-cost anchors never touch session
counts or averages.
- Ambiguous spawn pairing (parent named the agent but its exact launching
tool_use could not be paired) is recorded per parent; a late child of
such a pairing folds to the parent's last turn within a 30 minute grace
window, else stays unlinked. A truly-absent pairing gets no grace.
- Row session key is NUL-delimited and provider-prefixed, so a project
name or session id containing a space no longer collides and
undercounts distinct sessions.
Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent, and a day-filtered drive proves the
filter fix end to end (anchors created, subagents fold, identity holds).
* sessions: round-4 hardening of subagent PR attribution
Fourth adversarial review pass.
- sessionFingerprint now covers the COMPLETE linkage-relevant payload,
not just headline stats: a canonical (sorted-key) serialization of
agentSpawnLinks, spawnPrSets, prRefsAtRangeStart, ambiguousSpawnAgentIds,
parent/agent identity, and the per-turn prRefs timeline. Two records
that share an id and headline stats but map the child to different
spawns/PRs now fingerprint DISTINCT, so the ambiguity rule fires and
they fold into neither, deterministically rather than order-dependent
first-wins.
- A date/day filter recomputes prRefsAtRangeStart at the new slice
boundary by replaying the original full turn sequence, instead of
copying the wide range's value. A PR switch between the wide start and
the slice start (July 1 A, July 10 B, slice July 20) now carries B, not
a stale A; a turn exactly on the boundary stays in-slice and applies its
own refs. The recompute selects by timestamp, so it is order-independent.
Non-contiguous day selections are documented as treated contiguous from
the earliest selected day (a single session-level seed cannot represent
multiple segments; the menubar selection is a single day or a run).
- The anchor-carry path drops an anchor that duplicates a surviving
session id, so malformed merged input cannot double-count.
Also: rebuilt filtered sessions were losing their PR/subagent-linkage
metadata (a child its parentSessionId, a parent its prLinks), which
carryLinkageFields now restores, so by-PR and folding work on any filtered
slice.
Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity and reconciliation to the cent for both a
lifetime scan and a day-filtered slice (anchors created, subagents fold
through the filter).
* sessions: round-5 hardening of subagent PR attribution
Fifth adversarial review pass; closed-form fixes.
- sessionFingerprint serializes the COMPLETE fold-determining state via a
real recursive canonical encoder: session-level linkage AND, per turn in
sequence, timestamp, prRefs, cost, calls, savings, and per-model cost.
Object keys are sorted recursively and set-semantic arrays (PR-ref lists,
ambiguous ids, spawnPrSets values) are sorted, while the turn list keeps
order; the structure is emitted through JSON.stringify (no delimiter
concatenation). Two same-id parents that differ only in a turn timestamp
now fingerprint DISTINCT (fold neither), and records differing only in
set-array order fingerprint EQUAL (no false ambiguity).
- recomputeRangeStartPrRefs breaks an exact-same-millisecond tie
deterministically by the lexicographically-last sorted-ref key, so the
recomputed seed is stable regardless of turn order.
- A day filter seeds EACH selected day's first ref-less turn by replaying
the original full turn sequence up to that day's start (per-day seeding),
so a PR switch on an UNSELECTED day between two selected days carries to
the later day. Contiguous and non-contiguous selections are both correct.
- The anchor dedupe drops an anchor only when a surviving session shares
the full provider-aware, fingerprint-qualified identity (a proven
duplicate): a different-provider or different-record same-id session no
longer wrongly drops the anchor.
Also fixed a double-count the fingerprint test exposed: two duplicate
parent sessions share a key and the SAME resolved children, so folding is
now done once per parent key.
Every fix mutation-verified. Fresh real-data drives (lifetime, single-day,
and a NON-CONTIGUOUS day selection) re-prove no-double-count and
reconciliation to the cent.
---------
Co-authored-by: reviewer <review@local>
* sessions: attribute PR spend per turn instead of per session
The by-PR surfaces attributed a session's full cost to every PR it
referenced, so one orchestration session that touched many PRs rendered
identical full-session rows. Capture per-turn PR references during
transcript parsing and attribute each turn's cost to the PR set active at
that turn (split evenly across a multi-PR merge-sweep turn), carrying the
most recent PR set forward across turns that reference nothing. Turns
before the first reference form an unattributed bucket.
A session whose transcript expired before per-turn capture keeps its
session-level prLinks but has no per-turn refs; it falls back to an even
whole-session split, and any row carrying such a portion is flagged
approximate.
Rows are now summable: the CLI and app footers report the attributed sum
plus the unattributed remainder instead of a distinct-session total.
Bumps the session cache version so surviving transcripts re-parse and
populate the new per-turn field. Daily-cache versioning is untouched.
* sessions: harden PR attribution and add models + category breakdown
Addresses the review findings on the per-turn PR attribution and adds the
model and task-category surfaces.
Correctness:
- Cache migration: the 5 -> 6 session-cache bump now adopts the prior v5
file's expired-source PR entries instead of abandoning them, and the claude
scan preserves and surfaces PR-bearing orphans, so a session whose transcript
was deleted still appears as a legacy even-split instead of vanishing. The
daily cache is untouched.
- Date-range carry: the parser captures the PR set active at the start of the
in-range turn slice and seeds the state machine with it, so a PR referenced
before the window still owns its later, in-range, ref-less turns instead of
the session falling back to a whole-session approx split.
- Calls are split across a multi-PR turn by largest-remainder, keeping per-PR
counts whole (a 1-call, 2-PR turn no longer renders as 2 calls).
- The CLI and app footers reconcile to the rounded row values actually shown.
- Distinct sessions are keyed by project + sessionId, not sessionId alone.
- The app tolerates an older by-reference payload (no attributedCost): it keeps
the old non-summable footer and never renders NaN.
Features:
- Each PR contribution records the models of its calls and the turn's task
category (split by the same share on a multi-PR turn); legacy even-split rows
carry the model union but no category breakdown.
- Payload rows gain models (short names, cost-desc) and categories (label + cost,
cost-desc, omitted when empty); the payload gains otherPrCount/otherPrCost for
the PRs beyond the sent top 20.
- CLI --by-pr gains a Models column. The desktop table is now full-width with a
Models column and click-to-expand rows showing a per-category cost breakdown
with proportional bars, keyboard accessible, with an "Other (N more PRs)" row
when capped.
Tests: state-machine seed/models/categories/largest-remainder/dedup, the prRefs
round-trip through the real incremental-append path (continuation + straddle),
v5 adoption of an expired PR session, payload round-trip, and the desktop
expansion/models/old-payload cases.
* sessions: reconcile mixed PR rows, harden v5 adoption, bound models
Round-2 review follow-ups.
- Mixed legacy/live category breakdown: a PR row that combines an expired
legacy contribution (even-split, no turn data) with a live per-turn
contribution now emits an explicit "Legacy estimate (no per-turn detail)"
category carrying the legacy share, so the expansion reconciles to the row
cost instead of silently dropping it. A legacy-only row still shows no
breakdown.
- v5 adoption is now per cached file: one malformed entry is skipped instead
of rejecting the whole v5 cache and dropping every valid expired PR session.
- The desktop "Other (N more PRs)" line moved to the table footer as a muted,
separated summary rather than a sorted row.
- Row expansion resets when the PR set changes (period/provider/data), so a
stale expansion cannot linger on a row that is gone.
- Payload models per row are capped to the top 4 by attributed cost, with a
name-ascending tie-break; categories get the same stable tie-break.
Tests: mixed live+legacy reconciliation, legacy-only omission, model cap and
tie-break, corrupt-plus-valid v5 adoption, and the desktop expansion-reset.
* session-cache: validate optional agentType and failed during v5 adoption; app: reset PR expansion on period switch
A v5 entry that was valid except for a malformed optional field (agentType,
failed) passed per-file validation and flowed downstream as a non-string.
The expansion reset keyed only on the row URL set, so a period switch that
returned the same PRs kept a stale expansion open over changed numbers.
---------
Co-authored-by: reviewer <review@local>
Part 1 (src): expose two add-only, optional aggregations on the menubar
payload's `current`, computed on the unscoped all-provider path from the
surviving-session parse (carried history cannot contribute, as expected).
- current.pullRequests: aggregateByPr rows (top 20 by cost) plus the
multi-link-safe distinctCost/distinctSessions. Rows are by-reference, so
they are never summed.
- current.byBranch: new aggregateByBranch, per-branch spend (top 15 by cost)
that carries each session's last-seen git branch forward across its turns.
The cache stores a turn's branch only when it changes, so the parser now
resolves the branch at reconstruction (before the date slice) and records
SessionSummary.everHadBranch from the full transcript. That lets the report
keep a branch-bearing session's pre-branch spend in an explicit null row
even when the range clipped the anchor turn, while a provider that never
captures a branch still contributes nothing.
Part 2 (app): new "Pull requests" sidebar entry between Sessions and Spend
(shortcuts reflow to number 8 for Plans). It renders the pullRequests rows as
a refined table with the PR label linking out via openExternal, cost,
sessions, calls and an active-date span, plus a footnote stating the distinct
total and the by-reference attribution. A quiet explanatory line shows when no
PR links exist, never a fake table.
Tests: aggregateByBranch unit tests (carry-forward, null bucket, clipped
anchor, by-reference session counts) and the Pull requests component tests
(table, external link, footnote, both empty states). Nav-reflow assertions in
Sidebar and App tests updated.
Co-authored-by: reviewer <review@local>
* Resolve Fireworks-hosted models to friendly display names
Fireworks fleet models arrive as `accounts/fireworks/models/<slug>` and
were leaking the raw path/slug in reports and the dashboard (e.g.
`fireworks/mode…`, `glm-5p2`). getShortModelName's path fallback now takes
the last path segment and re-resolves it, so a known slug earns a friendly
name (GLM-5.2, Qwen 3.7 Plus, Kimi K2.7 Code, DeepSeek v4 Pro/Flash) while
an unmapped slug still falls through to the raw segment.
Display-only: getModelCosts prices off the full id, so dollar amounts are
unchanged. The By Model dashboard panel now renders through getShortModelName
too, so already-cached raw keys normalize without a cache rebuild.
* Merge By Model rows that resolve to the same display name
Once path-style ids normalize, a mixed-vintage cache can hold more than one
raw key for the same model (the full accounts/fireworks/models/<slug> path
from an older build and the bare slug/friendly name from a newer one). The
dashboard By Model panel aggregated by raw id, so those rendered as duplicate
rows once both mapped to the same display name.
Extract the aggregation into a pure, tested aggregateModelTotals() keyed by the
resolved display name so the rows merge into one. This also aligns the panel
with modelEfficiency, which is already keyed by getShortModelName.
Same threading as prLinks: the cache-level title (last ai-title entry)
rides onto SessionSummary in both the Claude and generic provider
pipelines, and the sessions table gains a TITLE column (truncated at 38
chars, empty when a transcript never produced one, as subagent
transcripts typically do not). JSON rows carry it verbatim. Groundwork
for titles in the context browser, desktop Sessions view, and payload.
Co-authored-by: reviewer <review@local>
The rich session capture (#758) stores every PR URL a transcript
references, but nothing displayed it. codeburn sessions --by-pr now
groups spend by pull request: cost, savings, sessions, calls, and the
date span per PR, sorted by cost, with a GitHub-shortened label and
json output. Attribution is by reference, so a session that mentions
several PRs counts fully toward each row; the footer reports the
distinct-session total so overlapping rows are never mistaken for a
grand total. prLinks now ride from the cached file onto SessionSummary
in both the Claude pipeline and the generic provider path.
Co-authored-by: reviewer <review@local>
0.9.18 was packaged from the pre-fix commit (364eed4) before the final
nine commits landed; npm versions are immutable, so the corrected
release ships as 0.9.19 everywhere. The changelog entry carries over
with a supersede note.
Co-authored-by: reviewer <review@local>
The incremental-append path groups the appended region before the file's
own cached keys join the dedup set, so a streamed assistant id restated
across the append boundary counted twice, and the boundary merge could
splice it into the wrong turn (reproduced on real image-heavy sessions:
one id streamed across several records over seconds, 111 calls vs the
110 a full re-parse yields). Suppressing the restatement instead would
freeze the stale first emission, so neither shortcut matches a full
re-parse. On any id overlap between the appended entries and the cached
turns the shortcut is abandoned and the file re-parses from byte 0.
Rare (about 0.3 percent of real files) and bounded to one file per
refresh. Regression test uses the cold-reparse oracle; mutation-verified
against the unguarded code.
Co-authored-by: reviewer <review@local>
* cache: strict cross-process gate for the warm session-cache refresh transaction (#645)
* lock: serialize the fence against the owner's own heartbeat
verifyStillOwner and the heartbeat tick both take the takeover guard;
without in-process serialization the fence could observe its own
heartbeat's guard file, read it as displacement, and abort a legitimate
publication. Fail-safe, but it discarded the parse the lock exists to
protect (~6% of verifies at a 1ms heartbeat in the repro). Owner-side
guard operations now run through one serializer; cross-process guard
semantics are unchanged. Regression test at heartbeatMs 1, mutation-
verified against the unserialized code.
---------
Co-authored-by: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com>
Co-authored-by: reviewer <review@local>
* daily-cache: coverage-gated carry on re-derive + single-slice turn attribution
P2: a tz-change re-derive no longer double-counts turns whose day bucket
moved across midnight — secondary slices are carried only outside the
provider's fresh coverage (floor widened by one day on tzChanged).
P3: a turn's editTurns/oneShotTurns/category counts are attributed to the
turn's primary provider slice only, so slice sums equal day-level counts
and partial carries cannot inflate day totals.
* daily-cache: document coverage-widening and rebuild-projects limits; cover empty-call turns
Review addendum: the one-day tz widening assumes an offset delta of at
most 24h (date-line crossings are a known limit); day-level projects of
skinny kept slices are dropped by the coverage rebuild by design. Adds a
regression test pinning the existing skip of empty-call turns.
* split: keep single-slice turn attribution, drop the coverage floor
The P2 coverage floor is reverted pending redesign: on a forced tz
re-derive against a real cache copy it dropped a genuine, non-duplicated
day (claude 2026-06-18, 399.70 USD, 1572 calls) that exists nowhere
else, and the floor also applied to every non-tz re-derive where the
same class of drop is latent. Trading a bounded midnight double-count
for unbounded history loss inverts the never-lose priority; the surgical
alternative (drop only the migrated turn's old-day contribution) is
tracked separately.
P3 stands as authored: turn-level stats attribute to exactly one slice
(majority-calls provider, tie broken by first call), restoring
slice-sums equal day-counts on fresh builds, with its regression tests.
---------
Co-authored-by: reviewer <review@local>
The one cache module still hardcoding ~/.cache/codeburn; every other
cache (session, daily, codex, pricing) honors the relocation override,
so a user moving the cache dir kept getting this single file in the
default location. Found by the pre-release functional sweep.
Three review leftovers plus one inconsistency found while fixing them.
computePace returns undefined for a non-finite usedFraction instead of
letting NaN sail through the clamp into every pace field.
Daily-cache retention goes from 730 days to 3650: the cache is the only
durable record of carried days and lifetime now reads from it, so the
2-year prune would have replayed the lost-history bug in slow motion at
that horizon. Measured cost stays small (~2.3 MB / ~11 ms parse per 730
dense days).
The vercel-gateway dashboard-range test pins a relative day instead of
2026-06-01, which would have started failing once the rolling 6-month
window moved past it around December.
Five verified findings from the #756 review, each with a regression test:
Corrections now count only follow-up prompts. The session-opening prompt
cannot be correcting this assistant, however correction-shaped its task
text reads, and the revert pattern no longer matches ordinary 'revert
the <noun>' requests (undo was already guarded; the doc claimed both
were).
Time-to-first-edit returns null when the first edit's timestamp is
unparseable instead of silently measuring to the first parseable one.
File churn normalizes backslashed paths before keying, relativizing, and
basenaming. Previously the payload's basename-only privacy redaction was
a no-op on Windows and shipped the full absolute path, username
included; mixed separators also split one file across churn entries.
Pricing coverage excludes deliberately-free models (local-looking,
local-savings mapped, zero-rate overrides) from the denominator via the
same exclusions findUnpricedModels applies, so a mostly-ollama user no
longer reads high coverage while every cost-bearing call is unpriced.
An absent coverage value now reaches the payload as null, never as a
fabricated 100%.
Also shares the one-shot minimum-edit-turns threshold between
worstOneShotCategory and the coaching gate so they cannot drift.
* feat(insights): workflow intelligence (corrections, time-to-first-edit, file churn, coverage) + dash wire-up
* menubar: propagate workflow-intelligence fields onto the cache-backed headline
The carry-forward headline (#755) serves totals from the durable day set
and merges only session-derived fields from the scan. The new workflow,
topReworkedFiles, and pricingCoverage fields were computed by the scan
but never propagated, so they silently defaulted on the all-provider
path (pricingCoverage rendered a dishonest 1.0). Propagate them like the
other scan-only fields and pin it with a carried-headline regression
test.
Claude Code deletes session transcripts after cleanupPeriodDays (default
30) at startup. Daily totals survive in the daily cache, but per-session
detail older than the cutoff is unrecoverable, and most users learn this
only after losing months of history. Doctor now reports the effective
retention and, below one year, warns with the exact settings.json edit
that preserves transcripts.
Re-apply the CLI/dashboard Lifetime split from #391/#416 on current main.
- add lifetime as a first-class period (all stays last 6 months)
- wire period through cli-date, dashboard key 6, and CLI commands
- refresh cli-date and cli-json-daily regression coverage
Part of #389. Supersedes #416.
Reuse one concrete six-month scan for interactive history and selected-period totals. This restores network-backed providers, removes concurrent refresh scans, and keeps non-interactive reports scoped to their requested period.
* daily-cache: never lose history the sources can no longer re-derive (v14)
Session files are ephemeral (Claude Code deletes transcripts after ~30
days), so a cached day whose sources are gone exists nowhere else. Every
invalidation path (schema bump, savings-config change, timezone change,
incomplete-hydration retry) used to discard all cached days and re-derive
from surviving sources, silently truncating history to the source
retention window. Five bumps between June 22 and July 16 erased
everything before April 24 on a machine with usage since March.
Invalidations now re-derive what they can and carry forward every
(day, provider) slice they cannot, marked 'carried'. Loading a missing or
corrupt cache file adopts days from every older daily-cache file in the
cache dir (legacy, versioned, .bak copies, orphaned .tmp) as a union per
(day, provider), higher schema version winning per pair. Provider slices
now store the full per-provider breakdown (tokens, models, categories,
sessions) so carry-forwards stay exact across future rebuilds.
Merge rules hardened by adversarial review: opaque pre-v5 days (totals
without provider slices) merge all-or-nothing so partial parses cannot
double-count into them; zero-data placeholder slices neither block nor
lose carried data (session counts deduplicated by max); a partial parse
never overwrites finalized baseline slices, only fills gaps; adoption
purges today/future entries, applies retention, and clamps a stale
lastComputedDate so a purged day cannot be skipped forever.
Verified end-to-end against a copy of a real cache dir: the rebuilt v14
cache holds every (day, provider) pair present in any older cache file,
including Claude days from early April that the July rebuilds had
dropped.
* daily-cache: per-project daily rollups in the durable record (v15)
Project history previously lived only in the session layer, so it faded
with the source files even though day totals now survive. Days and
provider slices carry a projects breakdown (cost/calls/savings/sessions
per project) filled by the day aggregator and folded through carry
merges, making the By Project dimension as durable as models and
categories. Days recorded before v15 keep their totals with no project
split; nothing can reconstruct one once sources are gone.
This is the first bump to ride the v14 carry-forward: the v14 cache is
adopted losslessly and only source-backed days re-derive (verified on a
real cache dir: identical totals, zero lost pairs, project splits on
every derivable day).
Hardening from adversarial review: placeholder-aware project session
dedup so totals reconcile; migrateDays sanitizes provider slices and
nested projects from foreign caches; all foreign-keyed map access in the
merge path uses hasOwn reads and defineProperty writes, closing a real
prototype-pollution path a regression test caught when a cache key is
named __proto__.
* menubar: serve headline totals and projects from the durable day set
Review finding on this PR: the all-provider headline built cache-backed
totals and then replaced them wholesale with a rebuild from the
surviving-session parse, so current.cost/calls, the models table, and
topProjects stayed truncated to the source-retention window even though
history.daily carried the full record. The replacement existed only to
keep the estimated-cost markers alive.
The cache-backed period data is now the authority; the scan contributes
exactly what day entries lack: estimated-cost markers, unpriced-model
detection, per-session drill-downs, and a fresher project path. Project
totals come from the same day set as the headline, with ProjectDayStats
gaining a path so carried-only projects still display a friendly name.
Sessions merge by max: the cache buckets a session on its start day, the
scan counts it on any active day, and both undercount differently.
End-to-end regression test seeds a cache whose only day is carried (no
session files exist) and asserts the headline, models, and topProjects
all reflect it. Verified on a real cache dir: the 6-month headline now
equals the history sum to the cent.
* daily-cache: close residual corrupt-input gaps in v15 ingestion sanitization
v15 sanitizes provider slices and projects at ingestion and guards merge
lookups with Object.hasOwn/setOwn. Three residual gaps versus the
invariant (no JSON-parseable cache content may throw or produce
NaN/garbage), plus one found in review:
- Day-level models/categories were not sanitized: a day with
models:'bad' survived load and buildPeriodDataFromDays iterated the
string per-character, yielding NaN in period model totals. Day-level
maps now reuse the same sanitizers as slice-level maps.
- Map keys shadowing Object.prototype (constructor, toString, ...) still
entered the cache from foreign files; modelTotals[name] ?? init in
buildPeriodDataFromDays resolves such a key to the inherited prototype
member and produces NaN. All sanitized maps now drop these keys at
ingestion (deliberate tradeoff: such names are reclassified invalid).
- Top-level lastComputedDate was unvalidated; a non-string later hit
.slice() in the gap-start parse and threw. Kept only when it is a
YYYY-MM-DD string, else null (forces a plain re-backfill).
- Stale savingsConfigHash comment still described pre-v14 discard
behavior; reworded to re-derive + carry forward.
3 regression tests, each verified to fail on the pre-fix code. Relevant
suites 71/71 green, tsc clean. Valid-input behavior unchanged except the
prototype-key reclassification above.
---------
Co-authored-by: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com>
Follow-up to #719, closing the two deltas flagged in the #714 discussion:
- fs.realpathSync preserves the caller's path casing on case-insensitive
filesystems (macOS APFS, Windows), so the same repo reached through
differently cased paths produced distinct canonical keys and split into
separate groups. fs.realpathSync.native returns the on-disk casing, making
the canonical key truly canonical. Regression test creates a real repo,
references it through altered casing (guarded to case-insensitive
filesystems), and asserts one group.
- Documents the accepted residual: a main repo moved on disk after
'git worktree add' leaves git's linked-worktree metadata stale, so its
worktrees may not unify; that is git-state staleness, not a grouping bug.
Adds a provider for Kimi Code CLI (MoonshotAI/kimi-code, the successor of
kimi-cli), reading ~/.kimi-code/sessions/wd_*/session_*/: state.json for
session metadata and per-agent agents/<id>/wire.jsonl event streams.
- Usage from usage.record events: inputOther->input, output->output,
inputCacheRead->cacheRead, inputCacheCreation->cacheWrite. The store has
no cost fields, so cost is computed from tokens and flagged estimated.
- Real model attribution: usage.record.model carries the config ALIAS; the
real model id lives on llm.request events. Rows resolve the alias through
the alias->model map first, with the nearest preceding request as
fallback, so aliases never leak into reports.
- Subagent wire files parse as separate sources under one session without
double counting; multi-turn continuations in one wire.jsonl are one
session with multiple turns; retry-only failed sessions parse to zero
usage; malformed JSONL lines are skipped.
- Tool calls feed the tool breakdown; tool state resets at turn boundaries
so a failed turn cannot bleed its tools into the next row.
- KIMI_CODE_HOME override, eager registration, PROVIDER_ENV_VARS and
PROVIDER_PARSE_VERSIONS entries, probeRoots for doctor, docs page.
Skill attribution was gated on the turn classifying as 'general', but
classifyByToolPattern checks hasSkill last, so any turn invoking the Skill
tool alongside Read/Bash/Edit/MCP got a real category and its skill was
silently dropped. Skill turns virtually always carry other tools, which is
why skills came back empty in all 25 usage snapshots (#741) while mcpServers
populated.
subCategory is now set for any turn with Skill tool_use; category assignment
is untouched. The claude parse version is bumped so cached session summaries
(which lack skill attribution) re-parse on upgrade.
Adds an eager provider for Amazon Quick Desktop (aws.amazon.com/quick/desktop),
which stores local data under ~/.quickwork. Usage source of truth is the
per-day EMF metrics JSONL (Model, InputTokens, OutputTokens, CostUSD,
session_id); real CostUSD passes through the cache like kiro/devin/hermes.
sessions.db (SQLite, read-only) enriches calls with titles, first user
message, and tool names, and provides estimated usage (quickdesk-auto,
costIsEstimated) for sessions that predate metrics coverage. Multi-profile
layout via profiles.json entries plus the migrated legacy root; honors
QUICKWORK_HOME; schema-tolerant (sqlite_master and PRAGMA introspection,
per-line JSONL error isolation). The on-disk schema is reverse-engineered and
documented as such in docs/providers/quickdesk.md.
Bump the version and refresh the bundled LiteLLM pricing snapshots.
Since 0.9.15, roughly sixty merged changes: the /advisor escalation
billing and unified large-line scanners for Claude, Copilot CLI
session.shutdown billing and skill extraction, the CodeWhale provider,
kiro v2 credit pricing, OpenCode custom dirs and legacy-store merging,
archived Codex sessions, antigravity timestamp stability, estimated-cost
markers across every surface, the doctor command, spend budgets, act
apply-model with a per-project quality tripwire, honest yield attribution
with an ambiguous bucket, MCP tool-deferral detection and fixes, agent by
model cross-breakdowns and per-record exports, granular dashboard
timelines, a scrollable daily history, the Electron desktop app with mac,
Windows and Linux packaging, menubar rate-limit handling and idle-cadence
energy fixes, team sync in preview, and the four-surface README.
Every merged PR was re-verified against this exact tree before the bump:
full JS suite (3527 tests), Swift suite (97), release build smoked, and
eight area audits with live functional probes.