Commit graph

564 commits

Author SHA1 Message Date
iamtoruk
71812eb60b refactor(pricing): fan-out — openclaw, crush 2026-07-26 08:37:28 -07:00
Resham Joshi
8b0f927cf2
Merge pull request #814 from getagentseal/phase0/fanout-batch2
refactor(pricing): fan-out batch 2 — zed, gemini, kimi, pi/omp
2026-07-26 08:22:07 -07:00
iamtoruk
a3380b2453 refactor(pricing): fan-out batch 2 — zed, gemini, kimi, pi/omp 2026-07-26 08:18:23 -07:00
iamtoruk
e28ff73659 refactor(pricing): fan-out — forge, grok, warp 2026-07-26 08:17:20 -07:00
Resham Joshi
7bc5f3b044
Merge pull request #812 from getagentseal/phase0/kimi-audition
refactor(pricing): fan-out — zcode, cursor-agent
2026-07-26 08:12:05 -07:00
iamtoruk
780c7462b5 refactor(pricing): fan-out — zcode, cursor-agent 2026-07-26 08:07:39 -07:00
iamtoruk
0eb0c6f2da refactor(pricing): fan-out batch 1 — goose, mux, open-design, lingtai-tui, droid 2026-07-26 08:06:53 -07:00
iamtoruk
6020fc8d8c refactor(pricing): host-side pricing pass, decoders emit tokens + basis (phase 0 exemplar) 2026-07-26 07:53:08 -07:00
iamtoruk
d4f85ced71 chore(sync): HTML-escape callback page inputs 2026-07-26 07:05:44 -07:00
Resham Joshi
2c29352d80
Merge pull request #804 from Enclavet/fix-sync-setup-ux
fix(sync): setup error handling, Windows browser open, themed callback pages
2026-07-26 07:03:54 -07:00
Resham Joshi
264e8e1b50
Merge pull request #800 from getagentseal/fix/611-desktop-msix-sessions
fix(claude): discover Claude Desktop/Cowork sessions in Windows MSIX installs
2026-07-26 06:47:18 -07:00
Andrew Lee
f54c48f350 fix(sync): setup error handling, Windows browser open, themed callback pages
- 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
2026-07-24 17:56:50 +00:00
ozymandiashh
d92b9fea43 fix(claude): discover Claude Desktop/Cowork sessions in Windows MSIX installs
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
2026-07-24 00:30:30 +03:00
reviewer
be5c0c00aa kimicode: discover desktop-runtime sessions and fix menubar visibility
- 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
2026-07-23 21:31:25 +02:00
Resham Joshi
6e3c57a9ff
feat(cli): add interactive sessions browser (#793)
Some checks failed
CI / semgrep (push) Has been cancelled
2026-07-21 13:03:47 +02:00
Resham Joshi
2eb4718122
sessions: correlate cross-provider work with pull requests (#792) 2026-07-21 11:50:11 +02:00
Resham Joshi
8e1caae33a
sessions: fold subagent runs into PR attribution (#791)
Some checks are pending
CI / semgrep (push) Waiting to run
* sessions: fold subagent runs into PR attribution

Sidechain (subagent) session cost never reached the by-PR view, so a
session orchestrated on one model with subagent lanes on another showed
only the parent model on every PR row. Fold each sidechain's cost, calls,
models, and categories into the parent turn that spawned it, so it
inherits that turn's PR set under the existing turn-level state machine.

Linkage, in priority order: the spawn result's toolUseResult.agentId
pairs the child's agent id with the Agent/Task tool_use id that launched
it (recorded per turn), which is the true launch point and wins even when
the child's first activity landed during a later turn; else the child's
first-activity timestamp is bucketed into the containing turn span; else
the child folds into the parent's unattributed spend. Children of parents
that referenced no PR, and orphans whose parent is absent from the scan,
contribute nothing, unchanged.

Cache v6 to v7 (neither shipped, so one combined bump from v5): per-turn
spawnToolUseIds, per-file parentSessionId and agentSpawnLinks; the
validator and the append/compact paths thread them like prRefs. By-PR
footers now count parents plus folded subagent runs and the payload gains
an additive subagentSessions field. distinctCost now includes folded
subagent spend, documented in the payload comment.

* sessions: address adversarial review of subagent PR attribution

Rework child attribution to resolve each subagent to the PR its launching
turn was working on, using the parent's UNFILTERED turn data, and enforce
that every dollar is counted exactly once.

- Mutual exclusion: a child that referenced its own PR attributes
  standalone and is never folded; a child with no links is folded only.
  Fixes a double-charge where a self-linking child was both folded and
  self-attributed.
- Recursion: a fold aggregates a child plus its non-self-linking
  descendants (depth-first, cycle-guarded), so grandchildren spawned by
  subagents reach the PR report.
- Global linkage: the subagent index keys by parentSessionId alone
  (UUIDs are globally unique), so a child whose worktree resolves to a
  different project still links.
- Date-range correctness: spawn-to-PR sets are built at assembly from the
  full turn list, so a spawn in a pre-range turn attributes to the right
  PR; a PR-linked parent whose own turns fall out of range is kept as a
  0-cost fold anchor so its in-range child is not lost.
- Timestamp fallback compares epoch ms (mixed UTC offsets order right) and
  is end-bounded: a child active after the parent's last turn is unlinked
  (contributes nothing), matching orphan semantics.
- Cache adoption tries the newest prior versioned file (v6 then v5) so the
  preceding build's expired-PR history survives the v7 bump; an invariant
  note requires the list to cover every version that can exist on disk.
- Spawn-result pairing matches the tool_result block that carries the
  agentId, not the first block, when a record batches several results.
- resolveSubagentAttribution is computed once and shared by aggregateByPr
  and prLinkedTotals.

subagentSessions now counts folded subtrees (children plus descendants).
Verified on real data: attributed + unattributed reconciles to cost, and
parent-only cost plus folded-children cost equals the folded total to the
cent (no double-count).

* sessions: round-2 hardening of subagent PR attribution

Address a second adversarial review of the new machinery.

- ID collision: parents and a child's parent reference are keyed by
  provider + sessionId, not bare sessionId. When two distinct parents
  still share a key (true duplicate/imported data), the child folds into
  NEITHER (deterministic skip, stays standalone): correctness over
  coverage.
- Recursion dedup is global: one claimed-set spans all of a parent's
  direct children, so a descendant reachable through two paths (a diamond
  or duplicate id) folds exactly once and a parent-link cycle terminates.
- Cache adoption migrates every prior version oldest-to-newest and MERGES
  per source path (newer wins per entry), so a sparse or partial newer
  file no longer masks older-only expired-PR orphans.
- Fold anchors (0-cost PR-linked parents kept only for attribution) live
  in a new ProjectSummary.subagentAnchors, never in `sessions`, so they no
  longer contaminate session counts, averages, or any per-session report.
  Folded PR rows take their date span from the contributing child activity
  rather than the anchor's empty timestamps.
- One-pass buildPrAttribution computes rows and totals together; the
  payload builder and CLI call it once. Drops the identity-keyed
  memoization, which could return stale folds if the array was mutated.
- Ambiguous multi-block spawn-result pairing leaves the spawn link unset
  on purpose; the child then folds via the timestamp fallback rather than
  pairing with the wrong id or disappearing.

Every fix is mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent (parent-only cost plus folded cost
equals the folded total) and that the PR rows sum to attributedCost.

* sessions: round-3 hardening of subagent PR attribution

Third adversarial review pass.

- Ambiguity counts ALL candidate parents (and anchors) sharing a
  provider+sessionId key, not just PR-bearing ones, and uses a
  per-record fingerprint: a key carried by more than one DISTINCT record
  folds its child/subtree into NEITHER (identical duplicates still fold
  once). This unifies the parent-collision and duplicate-descendant rules
  and is deterministic across input order.
- Project-rebuilding filters (by day, by date range, by config source)
  now carry subagentAnchors through, and a date filter CONVERTS a spawn
  parent whose in-range turns are all filtered out into an anchor so a
  surviving in-range child still folds. Rebuilt sessions also keep their
  PR + subagent-linkage metadata (prLinks, parentSessionId, spawnPrSets,
  ...), which buildSessionSummary otherwise drops, so by-PR and folding
  work on a filtered slice (menubar/dashboard flow).
- Fold anchors leave ProjectSummary.sessions entirely and folded PR rows
  take their span from the child, so 0-cost anchors never touch session
  counts or averages.
- Ambiguous spawn pairing (parent named the agent but its exact launching
  tool_use could not be paired) is recorded per parent; a late child of
  such a pairing folds to the parent's last turn within a 30 minute grace
  window, else stays unlinked. A truly-absent pairing gets no grace.
- Row session key is NUL-delimited and provider-prefixed, so a project
  name or session id containing a space no longer collides and
  undercounts distinct sessions.

Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent, and a day-filtered drive proves the
filter fix end to end (anchors created, subagents fold, identity holds).

* sessions: round-4 hardening of subagent PR attribution

Fourth adversarial review pass.

- sessionFingerprint now covers the COMPLETE linkage-relevant payload,
  not just headline stats: a canonical (sorted-key) serialization of
  agentSpawnLinks, spawnPrSets, prRefsAtRangeStart, ambiguousSpawnAgentIds,
  parent/agent identity, and the per-turn prRefs timeline. Two records
  that share an id and headline stats but map the child to different
  spawns/PRs now fingerprint DISTINCT, so the ambiguity rule fires and
  they fold into neither, deterministically rather than order-dependent
  first-wins.
- A date/day filter recomputes prRefsAtRangeStart at the new slice
  boundary by replaying the original full turn sequence, instead of
  copying the wide range's value. A PR switch between the wide start and
  the slice start (July 1 A, July 10 B, slice July 20) now carries B, not
  a stale A; a turn exactly on the boundary stays in-slice and applies its
  own refs. The recompute selects by timestamp, so it is order-independent.
  Non-contiguous day selections are documented as treated contiguous from
  the earliest selected day (a single session-level seed cannot represent
  multiple segments; the menubar selection is a single day or a run).
- The anchor-carry path drops an anchor that duplicates a surviving
  session id, so malformed merged input cannot double-count.

Also: rebuilt filtered sessions were losing their PR/subagent-linkage
metadata (a child its parentSessionId, a parent its prLinks), which
carryLinkageFields now restores, so by-PR and folding work on any filtered
slice.

Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity and reconciliation to the cent for both a
lifetime scan and a day-filtered slice (anchors created, subagents fold
through the filter).

* sessions: round-5 hardening of subagent PR attribution

Fifth adversarial review pass; closed-form fixes.

- sessionFingerprint serializes the COMPLETE fold-determining state via a
  real recursive canonical encoder: session-level linkage AND, per turn in
  sequence, timestamp, prRefs, cost, calls, savings, and per-model cost.
  Object keys are sorted recursively and set-semantic arrays (PR-ref lists,
  ambiguous ids, spawnPrSets values) are sorted, while the turn list keeps
  order; the structure is emitted through JSON.stringify (no delimiter
  concatenation). Two same-id parents that differ only in a turn timestamp
  now fingerprint DISTINCT (fold neither), and records differing only in
  set-array order fingerprint EQUAL (no false ambiguity).
- recomputeRangeStartPrRefs breaks an exact-same-millisecond tie
  deterministically by the lexicographically-last sorted-ref key, so the
  recomputed seed is stable regardless of turn order.
- A day filter seeds EACH selected day's first ref-less turn by replaying
  the original full turn sequence up to that day's start (per-day seeding),
  so a PR switch on an UNSELECTED day between two selected days carries to
  the later day. Contiguous and non-contiguous selections are both correct.
- The anchor dedupe drops an anchor only when a surviving session shares
  the full provider-aware, fingerprint-qualified identity (a proven
  duplicate): a different-provider or different-record same-id session no
  longer wrongly drops the anchor.

Also fixed a double-count the fingerprint test exposed: two duplicate
parent sessions share a key and the SAME resolved children, so folding is
now done once per parent key.

Every fix mutation-verified. Fresh real-data drives (lifetime, single-day,
and a NON-CONTIGUOUS day selection) re-prove no-double-count and
reconciliation to the cent.

---------

Co-authored-by: reviewer <review@local>
2026-07-20 20:47:23 -07:00
Resham Joshi
45e93129f2
sessions: attribute PR spend per turn instead of per session (#790)
* sessions: attribute PR spend per turn instead of per session

The by-PR surfaces attributed a session's full cost to every PR it
referenced, so one orchestration session that touched many PRs rendered
identical full-session rows. Capture per-turn PR references during
transcript parsing and attribute each turn's cost to the PR set active at
that turn (split evenly across a multi-PR merge-sweep turn), carrying the
most recent PR set forward across turns that reference nothing. Turns
before the first reference form an unattributed bucket.

A session whose transcript expired before per-turn capture keeps its
session-level prLinks but has no per-turn refs; it falls back to an even
whole-session split, and any row carrying such a portion is flagged
approximate.

Rows are now summable: the CLI and app footers report the attributed sum
plus the unattributed remainder instead of a distinct-session total.
Bumps the session cache version so surviving transcripts re-parse and
populate the new per-turn field. Daily-cache versioning is untouched.

* sessions: harden PR attribution and add models + category breakdown

Addresses the review findings on the per-turn PR attribution and adds the
model and task-category surfaces.

Correctness:
- Cache migration: the 5 -> 6 session-cache bump now adopts the prior v5
  file's expired-source PR entries instead of abandoning them, and the claude
  scan preserves and surfaces PR-bearing orphans, so a session whose transcript
  was deleted still appears as a legacy even-split instead of vanishing. The
  daily cache is untouched.
- Date-range carry: the parser captures the PR set active at the start of the
  in-range turn slice and seeds the state machine with it, so a PR referenced
  before the window still owns its later, in-range, ref-less turns instead of
  the session falling back to a whole-session approx split.
- Calls are split across a multi-PR turn by largest-remainder, keeping per-PR
  counts whole (a 1-call, 2-PR turn no longer renders as 2 calls).
- The CLI and app footers reconcile to the rounded row values actually shown.
- Distinct sessions are keyed by project + sessionId, not sessionId alone.
- The app tolerates an older by-reference payload (no attributedCost): it keeps
  the old non-summable footer and never renders NaN.

Features:
- Each PR contribution records the models of its calls and the turn's task
  category (split by the same share on a multi-PR turn); legacy even-split rows
  carry the model union but no category breakdown.
- Payload rows gain models (short names, cost-desc) and categories (label + cost,
  cost-desc, omitted when empty); the payload gains otherPrCount/otherPrCost for
  the PRs beyond the sent top 20.
- CLI --by-pr gains a Models column. The desktop table is now full-width with a
  Models column and click-to-expand rows showing a per-category cost breakdown
  with proportional bars, keyboard accessible, with an "Other (N more PRs)" row
  when capped.

Tests: state-machine seed/models/categories/largest-remainder/dedup, the prRefs
round-trip through the real incremental-append path (continuation + straddle),
v5 adoption of an expired PR session, payload round-trip, and the desktop
expansion/models/old-payload cases.

* sessions: reconcile mixed PR rows, harden v5 adoption, bound models

Round-2 review follow-ups.

- Mixed legacy/live category breakdown: a PR row that combines an expired
  legacy contribution (even-split, no turn data) with a live per-turn
  contribution now emits an explicit "Legacy estimate (no per-turn detail)"
  category carrying the legacy share, so the expansion reconciles to the row
  cost instead of silently dropping it. A legacy-only row still shows no
  breakdown.
- v5 adoption is now per cached file: one malformed entry is skipped instead
  of rejecting the whole v5 cache and dropping every valid expired PR session.
- The desktop "Other (N more PRs)" line moved to the table footer as a muted,
  separated summary rather than a sorted row.
- Row expansion resets when the PR set changes (period/provider/data), so a
  stale expansion cannot linger on a row that is gone.
- Payload models per row are capped to the top 4 by attributed cost, with a
  name-ascending tie-break; categories get the same stable tie-break.

Tests: mixed live+legacy reconciliation, legacy-only omission, model cap and
tie-break, corrupt-plus-valid v5 adoption, and the desktop expansion-reset.

* session-cache: validate optional agentType and failed during v5 adoption; app: reset PR expansion on period switch

A v5 entry that was valid except for a malformed optional field (agentType,
failed) passed per-file validation and flowed downstream as a non-string.
The expansion reset keyed only on the row URL set, so a period switch that
returned the same PRs kept a stale expansion open over changed numbers.

---------

Co-authored-by: reviewer <review@local>
2026-07-20 20:44:29 -07:00
Resham Joshi
a9d4471d17
payload: spend by pull request and by branch; desktop Pull requests tab (#788)
Some checks are pending
CI / semgrep (push) Waiting to run
Part 1 (src): expose two add-only, optional aggregations on the menubar
payload's `current`, computed on the unscoped all-provider path from the
surviving-session parse (carried history cannot contribute, as expected).

- current.pullRequests: aggregateByPr rows (top 20 by cost) plus the
  multi-link-safe distinctCost/distinctSessions. Rows are by-reference, so
  they are never summed.
- current.byBranch: new aggregateByBranch, per-branch spend (top 15 by cost)
  that carries each session's last-seen git branch forward across its turns.
  The cache stores a turn's branch only when it changes, so the parser now
  resolves the branch at reconstruction (before the date slice) and records
  SessionSummary.everHadBranch from the full transcript. That lets the report
  keep a branch-bearing session's pre-branch spend in an explicit null row
  even when the range clipped the anchor turn, while a provider that never
  captures a branch still contributes nothing.

Part 2 (app): new "Pull requests" sidebar entry between Sessions and Spend
(shortcuts reflow to number 8 for Plans). It renders the pullRequests rows as
a refined table with the PR label linking out via openExternal, cost,
sessions, calls and an active-date span, plus a footnote stating the distinct
total and the by-reference attribution. A quiet explanatory line shows when no
PR links exist, never a fake table.

Tests: aggregateByBranch unit tests (carry-forward, null bucket, clipped
anchor, by-reference session counts) and the Pull requests component tests
(table, external link, footnote, both empty states). Nav-reflow assertions in
Sidebar and App tests updated.

Co-authored-by: reviewer <review@local>
2026-07-20 14:36:53 -07:00
Rick Culpepper
475ff502e0
models: resolve Fireworks-hosted models to friendly display names (#787)
* 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.
2026-07-20 14:22:12 -07:00
Resham Joshi
9676f53d0c
sessions: thread captured titles onto SessionSummary and the report (#782)
Same threading as prLinks: the cache-level title (last ai-title entry)
rides onto SessionSummary in both the Claude and generic provider
pipelines, and the sessions table gains a TITLE column (truncated at 38
chars, empty when a transcript never produced one, as subagent
transcripts typically do not). JSON rows carry it verbatim. Groundwork
for titles in the context browser, desktop Sessions view, and payload.

Co-authored-by: reviewer <review@local>
2026-07-20 13:01:46 -07:00
Resham Joshi
8676f0da01
sessions: spend per pull request via --by-pr (#780)
The rich session capture (#758) stores every PR URL a transcript
references, but nothing displayed it. codeburn sessions --by-pr now
groups spend by pull request: cost, savings, sessions, calls, and the
date span per PR, sorted by cost, with a GitHub-shortened label and
json output. Attribution is by reference, so a session that mentions
several PRs counts fully toward each row; the footer reports the
distinct-session total so overlapping rows are never mistaken for a
grand total. prLinks now ride from the cached file onto SessionSummary
in both the Claude pipeline and the generic provider path.

Co-authored-by: reviewer <review@local>
2026-07-20 12:28:10 -07:00
Resham Joshi
af291ae621
release: 0.9.19 (#774)
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>
2026-07-20 09:35:32 -07:00
Resham Joshi
be748c81aa
parser: full re-parse when an appended region restates a cached message id (#772)
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>
2026-07-20 09:22:52 -07:00
Aditya Vikram Singh
e27fe36bd5
cache: strict cross-process gate for the warm session-cache refresh transaction (#743)
* 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>
2026-07-20 09:06:35 -07:00
ozymandiashh
17a23ead40
daily-cache: fix tz-change double-count and multi-provider turn-stat inflation (#762)
* 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>
2026-07-20 08:57:41 -07:00
Resham Joshi
d8158afb1b
currency: honor CODEBURN_CACHE_DIR for the exchange-rate cache (#766)
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.
2026-07-20 08:28:29 -07:00
Resham Joshi
b30818138e
prerelease: quota NaN guard, 10-year daily retention, test date bomb (#764)
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.
2026-07-20 07:37:56 -07:00
Resham Joshi
db8ef9b466
insights: close the post-merge review findings on workflow intelligence (#763)
Some checks are pending
CI / semgrep (push) Waiting to run
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.
2026-07-20 07:26:08 -07:00
iamtoruk
dea61bad4e fix(report): CLI totals read the durable daily cache, matching the menubar exactly 2026-07-20 06:33:56 -07:00
Resham Joshi
ba56ad72f5
Merge pull request #758 from getagentseal/feat/rich-session-capture
feat(capture): parse-time capture of branch, LOC deltas, interruptions, titles, PR links
2026-07-20 06:03:03 -07:00
iamtoruk
8ced2ed47f feat(capture): parse-time capture of branch, LOC deltas, interruptions, titles, PR links 2026-07-20 05:56:38 -07:00
Resham Joshi
f32c00d2b1
feat(insights): workflow intelligence (corrections, time-to-first-edit, file churn, coverage) + dash wire-up (#756)
* 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.
2026-07-20 05:47:46 -07:00
Resham Joshi
e99ee4bf37
doctor: surface Claude Code transcript retention (#757)
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.
2026-07-20 05:25:12 -07:00
Monish Khandelwal
380be66b4f
feat(cli): add lifetime period for CLI and dashboard (#753)
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.
2026-07-20 05:24:33 -07:00
Aditya Vikram Singh
b8435073ee
quota: provider-agnostic window model with provenance, merge rule, and linear pace (#725 Part 1) (#740)
Co-authored-by: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com>
2026-07-20 05:21:39 -07:00
ihearttokyo
92b2b5ef39
fix(dashboard): Bound Daily Activity scans (#727)
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.
2026-07-20 05:21:35 -07:00
Resham Joshi
7f2739e130
daily-cache: never lose history the sources can no longer re-derive (v14) (#755)
* 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>
2026-07-20 05:21:22 -07:00
Resham Joshi
2312fd2eb0
Merge pull request #751 from ozymandiashh/pr/714-delta
Some checks are pending
CI / semgrep (push) Waiting to run
fix(yield): case-insensitive canonical repo grouping via realpathSync.native
2026-07-19 17:25:39 -07:00
Resham Joshi
49b377616b
Merge pull request #750 from ozymandiashh/pr/747-kimicode
feat(kimicode): Kimi Code CLI provider, parse ~/.kimi-code wire sessions
2026-07-19 16:27:14 -07:00
iamtoruk
56ea38917f perf(parser): single-pass field extraction in the large-line JSONL scanner 2026-07-18 17:23:34 -07:00
ozymandiashh
2c9871b2f2 fix(yield): case-insensitive canonical repo grouping via realpathSync.native
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.
2026-07-19 03:12:03 +03:00
ozymandiashh
2b95aef7e5 feat(kimicode): Kimi Code CLI provider, parse ~/.kimi-code wire sessions (#747)
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.
2026-07-19 02:52:37 +03:00
iamtoruk
8326aee4a6 perf(parser): parse appended session files from the cached offset instead of byte 0 2026-07-18 16:26:12 -07:00
Resham Joshi
5a8a1d0fa4
Merge pull request #745 from ozymandiashh/pr/741-skills
fix(classifier): attribute skills to skillBreakdown regardless of turn category
2026-07-18 14:32:52 -07:00
Resham Joshi
906cb2d550
Merge pull request #735 from ozymandiashh/feat/quickdesk-provider
feat(quickdesk): Amazon Quick Desktop provider (~/.quickwork)
2026-07-18 12:57:08 -07:00
ozymandiashh
56e836fa9e fix(classifier): attribute skills to skillBreakdown regardless of turn category
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.
2026-07-18 22:54:49 +03:00
iamtoruk
b71ec34a21 fix(usage): per-provider snapshot capture, placeholder guard, path-id display fallback 2026-07-18 03:37:42 -07:00
ozymandiashh
bdb1475251 feat(quickdesk): Amazon Quick Desktop provider, parse ~/.quickwork sessions and metrics (#707)
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.
2026-07-18 00:02:01 +03:00
Resham Joshi
c58a705b13
release: 0.9.16 (#720)
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.
2026-07-16 19:15:26 -07:00