Skip to content

feat(plugin): per-agent cache clocks, saved of total, keep-alive hold time - #525

Merged
amiddavid merged 12 commits into
mainfrom
feat/statusline-per-agent
Oct 14, 2026
Merged

amiddavid merged 12 commits into
mainfrom
feat/statusline-per-agent

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

What

The status line now answers per agent and per session:

saved $18.60 of $61.40 session · saved $4.20 of $20.50 subagents
cache ● █████░ 13:40 ↻ │ agents reviewer active ● 11:40 ↻ saved $1.20 of $6.00 · Explore ◐ 0:50 saved $0.30 of $2.10 · 1 cold │ ctx ███░░░░░ 41%
  • saved $x of $y session · saved $x of $y subagents: session is the main thread; subagents is every other thread of the session together (sub-agents, teammates, and side requests such as the auto-mode classifier). In both, $y is what those requests would have cost without context-guru, at the same prices, and $x is the saving against it, net of context-guru's own model calls and keep-alive pings, so $x <= $y. Only savings recorded per request count. The today and lifetime totals are gone from the line. Each listed agent also shows its own saved $z of $q next to its clock; side threads count only in the subagents total. A figure the proxy did not report is left out, never shown as $0.00. The line counts only per-request savings, so it can read lower than the dashboard, which also adds the tool-filter and historical cache-split credits.
  • Per-agent caches by name: every sub-agent's cache under the name Claude Code's agents list shows (read from the session's subagents/agent-*.meta.json), most recently used first, at most five then +N more, active for a request in the last 10 s, cold ones counted.
  • Held warm: when the keep-alive still plans pings for a thread, its clock is the time until the cache goes cold (last planned ping + lifetime) and shows ↻. A plan never revives an entry that already expired.
  • ka N pings $z: this session's keep-alive pings and their cost (balanced and detailed layouts).

Limitation: the status line cannot follow the selected agent

Claude Code (2.1.296) does not pass the status line anything about which agent is selected in its agents view. Checked in the CLI's payload builder and live: the stdin payload is identical before and after selecting a sub-agent. So the line shows the main agent plus every sub-agent by name, and the selected one is found by its name.

Agent-team teammates in their own tmux pane (teammateMode: tmux) are separate Claude Code sessions with their own status line, which shows that teammate's own cache, keep-alive and money (checked live). In-process teammates are listed on the lead's line.

Fixes found on the way

  • Teammate threads: agent-team teammates send x-claude-code-agent-id: <name>@<team>. thread.ValidHeaderID rejected @, so every teammate fell back to a prefix-grouped p: thread. It now gets a:<name>@<team>.
  • Side requests are not agents: Claude Code's side requests (for example the auto-mode classifier) get prefix-grouped p: threads. The status line now lists only header-named a: threads, so they no longer show up as phantom sub-agents.

Proxy changes

  • GET /api/cachestate: money.main / money.others and per-thread saved_usd / baseline_usd, computed in its existing per-thread GROUP BY (one indexed read of the session). Per thread (and top level for the main thread) pings_left and held_until_ms, from a read-only hook into the keeper's in-memory entries (dash.API.SetKeepAlivePlans). No new query.
  • GET /api/stats?lean=1: adds keepalive_pings to the existing single aggregate.
  • Lifetime path removed (Status line: a bounded lifetime total (daily rollup), without the #509 defects #510): the status line's since=0 read, its detached refresher job and OverviewLean's lifetime branch are gone. A lean call with no session and no window is now answered by the full handler, which gives the same exact number, so an older installed plugin that still asks keeps working. The refresher itself stays for the mode layouts (spark, strip, heat).

Tests

  • internal/thread: name@team accepted.
  • dash: lean reports the session's pings and ping cost; cachestate exposes the plan (main thread and sub-agents, none for an unplanned thread); lean lifetime still equals full; golden stats_lean updated (the unbounded lean call is now the full handler's answer).
  • proxy: KeepAlivePlans reports only entries that will still ping, scoped by session and tenant.
  • Plugin goldens: saved $x of $y, named agents in both id forms, p: ignored, cold count, held clock, a plan that cannot revive a cold entry, narrow-width degrade, and no since= read ever made.
  • Live: real Claude Code 2.1.296 sessions through a local proxy with an in-process teammate and a foreground sub-agent (main view and with the sub-agent selected, before and after keep-alive pings), and with a tmux-pane teammate (lead pane and teammate pane).
  • Render time: interleaved A/B against the previous release, 50 renders per cell, no measurable change; the slowest non-mode render was 460 ms (slow-proxy case), under the 0.5 s budget.

Docs: docs/plugin/statusline.md, docs/dashboard.md, the statusline skill, and the affected status line images.

Closes #510.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: APPROVE at fa661aa. (Posted as a comment: GitHub does not let the author account approve.)

Verified:

  • The branch is up to date with main. All 5 commits are by Osher-Elhadad and signed off, with no AI attribution.
  • gofmt and go vet are clean. go test passes for internal/thread, dash, proxy and context-guru-plugin (nice 10, one package at a time).
  • The selected agent is not in the payload. In the 2.1.296 binary the status-line payload builder sets agent:{name} from Kv(), which returns mainThreadAgentType: the agent the session was started as, not the one selected in the agents view. Nothing else in the builder names an agent. The captured payloads agree: agent.name is constant within a session.
  • Only a: threads are agents. a: ids come only from a valid x-claude-code-agent-id header (thread.go), and p: ids are prefix-grouped. That is right for Claude Code, which is the only client this status line serves.
  • A plan never revives a cold entry. KeepAlivePlans holds k.mu only while reading, with no writes, no new pings and no other lock. It applies the sweep's own skip conditions (stopped, on(), MaxPings, pingable()) and is scoped by tenant. The plugin uses held only while the entry is still warm (rem > 0).
  • Tests fail without the changes. I checked each of these, and each fails its test:
    • dropping @ from ValidHeaderID;
    • removing the tenant check or the pingable() condition in KeepAlivePlans;
    • letting held apply to a cold entry;
    • listing p: threads;
    • sending unbounded lean back to the lean path;
    • dropping ping cost from the of $y total.
  • Render time. With the PR's own stub harness on this host (15 renders per cell), every layout stays under 0.5 s. The worst is the slow-proxy case, with a maximum a little under the budget.
  • Older plugins. An unbounded lean call goes to the full handler. That runs the same Overview() plus the two credits the removed lifetime branch ran, so its cost is unchanged and the response is a superset of the fields an older plugin reads.
  • @ in thread ids. The header id goes only into NUL-separated in-memory keys, structured logs (only its length when invalid) and parameterised SQL. It never reaches a file path.
  • saved $x of $y. Both figures are session-scoped, and the total uses the same pricing basis as the saving (agent cost_usd + cg_llm_cost_usd + ping cost).

Non-blocking:

  1. held_until_ms can overstate after a ping the limiter refused. The sweep advances startedAt and pings before fire (pre-existing keeper bookkeeping), so the plan assumes a refresh that never happened. The plugin stays honest about the current entry, because rem comes from recorded rows. Only the ↻ horizon can be too long while the entry is still warm.
  2. KeepAlivePlans scans every live entry under k.mu on each /api/cachestate. That lock is also on the request path. It is fine at today's sizes; a per-session index would make it O(threads) if hosted entry counts grow.
  3. _agent_names lists the session's subagents/ directory and reads every .meta.json on every render. A long session with hundreds of agents pays that on each render, so consider caching by directory mtime.
  4. The slow-proxy render sits just under 0.5 s. That margin is the fetch timeout, not this PR, but a busy host has little headroom.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at fa661aa (the head, which includes 'mark active sub-agents, most recent first, at most five'). (Posted as a comment: GitHub does not let the author account approve.)

  • Clock. ago is the server's now_ms minus the agent's max(last_ts, end_ts), plus the cachestate response's age, so both readings come from one clock and client skew doesn't matter.
  • Order and cap. sorted is stable, so ties keep id order. With 5 named agents there is no +N more; with 6 or 7 it shows +1 / +2 more (the new many-agents-capped golden). With 0 named agents the unnamed form is unchanged.
  • Tests fail without the change. Sorting by id instead of recency fails many-agents-capped, and so does raising the cap to 6.
  • Render time. The stub harness on this host keeps every layout under 0.5 s; the slow-proxy case peaks just under 400 ms.
  • Docs. They now state the selected-agent limitation plainly, and the tmux-pane teammate paragraph matches what the line does.
  • go vet is clean, the plugin status-line goldens pass, the commit is signed off with no AI attribution, and the PR text has no numbers.

Nits (non-blocking):

  • +N more also counts warm agents that have no name on disk, so it means "more warm agents", not "more named ones".
  • If a response ever lacked now_ms, ago would fall back to the response age, and every agent would read as active. The server always sends now_ms, including on the none path, so this is theoretical.

Approved.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at 76145b2. (Posted as a comment: GitHub does not let the author account approve.)

  • refreshedAt is set when the entry is created (the real request's start) and afterwards only in record1 and recordSummarySubstitute under k.mu, when CacheRead > 0. The sweep's pre-send bump of startedAt never touches it, and KeepAlivePlans reads it under the same lock. go test -race ./proxy -run KeepAlivePlan -count=5 passes.
  • heldUntil walks the plan from RefreshedMS + TTL and stops at the first ping that would come after expiry.
  • Mutations: KeepAlivePlans reporting startedAt makes TestKeepAlivePlanCountsOnlyPingsThatRefreshed fail, and dropping the expiry stop in heldUntil makes TestHeldUntilStartsFromTheLastRealRefresh fail.
  • gofmt and go vet are clean, and the dash cache-state tests and plugin status-line goldens pass. The commit is signed off with no AI attribution.

Non-blocking: the CacheRead > 0 gate itself is not pinned. The test's failing ping is a transport error that never reaches record1. With the gate replaced by true in record1, or in the summary-substitute path, every test still passes. Add a ping that answers 200 with cache_read: 0 and a full write, and assert RefreshedMS does not move.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at ea0da82. It adds one test, TestAPingThatReadNothingIsNotARefresh. With record1's u.CacheRead > 0 refresh gate replaced by true, that test fails; with the gate it passes under -race. The summary-substitute path's copy of the gate is still unpinned, as noted. The approval stands.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict

Changes requested. The code is sound and all tests pass. One user requirement is not met (finding 1). Finding 2 is a wording and basis problem in the main figure.

Findings

  1. Requirement gap: no per-agent money.

    • Asked for: main session saved $x of $y, and each sub-agent <name>: saved $z of $q.
    • Today the line shows saved $x of $y once, for the whole session. That figure comes from /api/stats?lean=1&session=<id> (statusline.py _save_segment).
    • Each sub-agent shows only its name, an active mark, a cache clock and ↻ (_agents_segment). No cost. No saving.
    • The data exists. requests rows have thread_id, cost_usd and baseline_cost_usd. dash/cachestate.go:117 already does GROUP BY r.thread_id for the session, bounded to the last 2 h, limit 16.
    • Proposal: add per-thread cost_usd and baseline_cost_usd (and cg_llm_cost_usd) to the /api/cachestate thread rows. Use the same query. The query is one indexed read on idx_requests_session, so cost does not grow with session size. The plugin then shows saved = baseline - cost - cg_llm per agent. Per-thread keep-alive credit and ping cost need the same GROUP BY. If a per-agent figure leaves them out, the line must say so.
    • Do not use a second lean call per agent. That is N queries per render.
  2. saved $x of $y can read as nonsense. x is a saving against the uncompacted baseline. y is what the session actually cost, after the saving. They are not a part and a whole.

    • statusline.py _save_segment, dash/savings.go:56.
    • Failing case: total_saved_usd=9.00, cost_usd=1.00, cg_llm=0.10, ping=0.05. The line shows saved $9.00 of $1.15.
    • This happens on any session with a reduction over 50 %. The reader sees a part larger than the whole.
    • Bases do match otherwise: cost_usd, cg_llm_cost_usd and ping cost come from the same rows, and x is already net of cg_llm and pings.
    • Proposal: use the baseline as y (cost + saved: "saved $9 of $10.15"), or change the wording ("saved $9.00, paid $1.15"). Say which in the docs.
    • Also check: total_saved_usd in a session scope adds CachesplitHistoricalUSD and DeclFilterSavings (overview_lean.go:44-55). Those are read-time-priced credits. Do they belong in a figure shown plainly, with no ≈? Release rule says estimates stay apart from real savings. See Questions.
  3. _agent_names has no bound. It opens every agent-*.meta.json in the session folder on every render, with no cache and no deadline.

    • Measured: 3000 files, warm disk, 0.18 s (about 36 % of the 0.5 s budget). A cold disk is slower.
    • It runs after the parallel gather, so the gather deadline does not cover it.
    • Proposal: look up only the ids that /api/cachestate lists (a:<id> maps to agent-<id>.meta.json, a direct path). Scan the folder only for name@team ids, and cache the result by directory mtime. Cap the scan.
  4. Same name, same label. Two sub-agents of type Explore both show as Explore. The reader cannot tell which clock is which. Minor. Add a suffix (Explore 2) or use the description when names repeat.

What I verified

  • Worktree review-525 at ea0da82. Tests run on box 1: dash, internal/thread, context-guru-plugin (356 s), proxy (KeepAlive/Plan): all pass.
  • Merge with #519: git merge-tree of the PR head and #519 gives no conflict. Meaning is compatible. Main thread keeps id "", and KeepAlivePlans and cachestate both key main on "" / t.Main. Only a: rows are listed, so #519's header-thread rule does not affect them.
  • Held-warm clock (heldUntil, refreshedAt): starts from the last ping that read the cache (CacheRead > 0), not from the sweep's startedAt. A refused, failed or timed-out ping does not move it. A ping in flight shows a shorter hold until it ends (it under-promises, never over-promises). The Python side ignores the plan when the entry already expired (_until_cold). So a cold cache is not shown warm. This covers the #532 60 s timeout case.
  • Lifetime path: no caller of since=0 or overviewLeanLifetimeExact is left in the plugin or the proxy. The golden test asserts no since= read. An older plugin that sends lean=1&since=0 gets the full handler. Answer is exact, same cost as before (it was an unbounded exact read before too).
  • _agent_rows with missing now_ms or a bad last_ts returns [], no exception.
  • ValidHeaderID accepts name@team. Test added.

Questions

  1. Are CachesplitHistorical and DeclFilterSavings measured or modelled? If modelled, should they sit outside saved $x?
  2. With no valid session_id in the payload, _fetch_stats calls lean=1 with no session. That now reaches the full handler on every render (before: the same exact lifetime read). The line then shows the whole-proxy total as "session". Should it show nothing instead?
  3. Held clock assumes every planned ping succeeds (for example a 401 on pings). The clock then over-promises until the first failure. Accepted?

Reviewed by an AI reviewer (Claude)

@amiddavid

amiddavid commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Requirement from the product owner for this PR, for release v0.5.1. It replaces finding 1 of the first review. Confirmed by the owner on 2026-10-14.

The main agent's status line shows its own spend and the total of all its subagents, side by side. Each listed agent also shows its own figure next to its cache clock.

saved $50.32 of $250.00 session · saved $60.03 of $300.00 subagents
cache ● █████░ 13:40 ↻ │ agents reviewer active ● 11:40 ↻ saved $1.20 of $6.00 · Explore ◐ 0:50 saved $0.30 of $2.10 │ ctx ███░░░░░ 41%

Definitions

  1. session = the main thread only (thread id "", the main agent).
  2. subagents = the sum over every other thread of the session: header-named threads (a:<id>, a:<name>@<team>) and prefix-grouped side threads (p:<id>, for example the auto-mode classifier). Side threads cost money, so they count, even though they are not listed as agents.
  3. Each listed agent (a: threads) shows its own saved $z of $q next to its own cache clock. Side threads are not listed, so they count only in the subagents total.
  4. One basis for every figure (finding 2 of the first review):
    • y = what those requests would have cost without context-guru (baseline), on the same prices;
    • x = the saving against that baseline, so x <= y always;
    • the proxy's own model calls and keep-alive pings are a cost of context-guru: they reduce x (net saving), and they are not added to y;
    • only realized savings count in x. Estimates stay out of it (release rule: never add an estimate to a real saving). If a credit is priced at read time and is an estimate, leave it out or show it apart.
  5. If the session has no thread other than the main one, show only the session figure.
  6. A teammate in its own tmux pane is a separate Claude Code session. Its own status line shows its figure as session.

Data

The first review found that the per-thread GROUP BY r.thread_id read in dash/cachestate.go:117 is one indexed session read. Adding per-thread cost_usd, baseline_cost_usd and cg_llm_cost_usd (plus ping cost) to the /api/cachestate thread rows gives every figure above with no new query, and the cost stays bounded as the session grows.

Posted by an AI assistant (Claude), for the release integrator.

Osher-Elhadad added 9 commits October 14, 2026 13:34
…t header

Claude Code sends x-claude-code-agent-id as <name>@<team> for agent-team
teammates. The '@' failed ValidHeaderID, so every teammate fell back to
prefix continuity and got a p: thread that cannot be mapped to an agent.

Signed-off-by: Osher-Elhadad <[email protected]>
/api/cachestate reports, per thread the keeper still plans to ping,
pings_left and held_until_ms (the last planned ping plus the cache
lifetime), from a read-only hook into the keeper's in-memory entries.
Lean /api/stats adds keepalive_pings to its single aggregate.

The lean lifetime path (since=0, no session) is removed: nothing on a
render reads it any more, and a lean call with no bound is now served by
the full handler, which returns the same exact answer (refs #510).

Signed-off-by: Osher-Elhadad <[email protected]>
…p-alive hold

- saved $x of $y: this session's saving out of the session's proxy cost;
  the today and lifetime totals and their background reads are gone.
- agents: every sub-agent's cache under the name Claude Code's agents
  list shows (from the session's subagents/*.meta.json), warm clocks and
  a cold count. Claude Code does not pass the selected agent to the
  status line, so the selected agent is found by name.
- cache: with a keep-alive plan the clock is the time until cold and
  shows ↻; ka N pings $z is the session's pings and their cost.
- docs and images updated.

Signed-off-by: Osher-Elhadad <[email protected]>
A sub-agent with a request in the last 10 s is marked active; the named
list is sorted by recency and capped at five, then +N more. Docs state
the selected-agent limitation plainly and cover tmux-pane teammates,
which are their own sessions with their own status line.

Signed-off-by: Osher-Elhadad <[email protected]>
The sweep advances an entry's startedAt and ping count before a ping is
sent, so after a refused or failed ping the plan's next ping could come
after the entry had already expired, and held_until overstated how long
the cache stays warm. The keeper now keeps refreshedAt (the real
request's start, then each ping that read the cache), and held_until
walks the plan from it, stopping at the first ping that would come too
late.

Signed-off-by: Osher-Elhadad <[email protected]>
…e basis

The money line is now two figures from /api/cachestate:
saved $x of $y session (the main thread) and saved $x of $y
subagents (every other thread together, side requests included).
y is what the requests would have cost without context-guru, on the
same prices; x is the saving against it, net of context-guru's own
model calls and keep-alive pings, so x <= y. Only savings written per
request count; the read-time credits are left out.

/api/cachestate computes both in its existing per-thread GROUP BY: one
indexed read of the session, money over every row, cache fields from
each thread's latest cache-touching row.

Also: without a session id the status line no longer reads the
proxy-wide total (it probes /healthz); sub-agent names are read only
for the threads the proxy lists, with capped opens, bytes and
directory entries; two agents with one name read Explore, Explore 2;
the keeper's refresh time is set outside the entry literal.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad force-pushed the feat/statusline-per-agent branch from ea0da82 to ee7b7f1 Compare October 14, 2026 14:01
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

@amiddavid round 2 is ready at ee7b7f1, rebased on main (after #519). Here is each point.

Finding 1 and the 2026-10-14 requirement: per-agent money. Done as the requirement defines it. The main line now shows saved $x of $y session · saved $x of $y subagents.

  • session is thread "".
  • subagents is the sum over every other thread of the session: a: threads and p: side threads. A side thread with no cache touch also counts.
  • The subagents figure appears only when such a thread exists.
  • It is computed in the existing /api/cachestate per-thread GROUP BY (cacheThreadsQuery). That is one statement over the session's rows, with no call per agent. TestCacheThreadsQueryIsIndexed checks with EXPLAIN that it uses the session index.
  • The money columns sum every row of each thread. The cache columns still come from each thread's latest successful cache-touching row: the select has exactly one MAX(), so SQLite takes the bare columns from the row that holds it.
  • The response has money.main and money.others, and every listed thread has its own saved_usd / baseline_usd.
  • A session with no cache touch yet also gets money on its none answer.
  • On your open question: the per-agent list keeps names and clocks only, as the owner asked. Each agent's own pair is already in the thread rows, if we want to show it later.

Finding 2: basis and wording.

  • y is the baseline without context-guru, on the same prices: the uncompacted baseline plus the cache-split and keep-alive savings, which the baseline does not contain.
  • x = y − (requests + context-guru model calls + pings), the same net as savingsArithmetic. So x <= y, and pings and model calls lower x without being added to y.
  • Your failing case now reads saved $9.00 of $10.15.
  • Tests: TestCacheStateSplitsTheSessionsMoney covers x <= y, ping and model-call cost lowering only x, p: side threads counted, and money on the no-cache path. The goldens cover the line.
  • Live check on a real Claude Code session: the main thread's y equals its rows' summed baseline. x equals baseline − cost − pings, and went negative after keep-alive pings (saved -$0.01 of $0.08 session). The subagents figure equals the sum over its a: and p: rows.

Question 1: read-time credits. CachesplitHistoricalUSD is an estimate, recomputed on read for rows recorded before the cache split was measured. DeclFilterSavings prices measured token counts at read time. Neither is in x now. Only savings written with each request count: compaction against the uncompacted baseline, cachesplit_saved_usd, and the keep-alive credit, which counts only rows a successful ping read. The docs say this and point to the dashboard for the other two.

Question 2: no session_id. Fixed. With no trusted session id the status line makes no /api/stats read. It probes /healthz, so the offline notices still work, and shows no money. The stats cache is no longer used without a session. Tests: TestStatuslineAlwaysRequestsTheLeanPath and TestStatuslineRejectsAMalformedSessionId now assert that no stats read happens.

Question 3: held clock and failed pings. Fixed in two places:

  • The hold now starts from the last real refresh (refreshedAt), not from the sweep's planned time. A 4xx such as a 401 stops the entry at the first failure, which removes the plan.
  • A plan never shows a cache warm after the entry itself expired.

So before the first failure the clock is the plan, and after it the clock is the entry's own expiry. Pinned by TestKeepAlivePlanCountsOnlyPingsThatRefreshed, TestAPingThatReadNothingIsNotARefresh and TestHeldUntilStartsFromTheLastRealRefresh.

Finding 3: unbounded _agent_names. Fixed. Only the a: ids that /api/cachestate lists (at most 16) are looked up.

  • A plain sub-agent's file is opened directly by id (agent-<id>.meta.json).
  • A teammate (name@team) is found by name prefix (agent-a<name>-) in one directory listing. The listing reads names only, at most 20,000 entries (about 7 ms), and the team is checked against the file's teamName.
  • At most 24 files are opened per render, and at most 4 KB is read from each.
  • TestStatuslineAgentNamesAreBounded: 5,000 agent files, a 2 MB file and 16 listed agents render correctly in under 0.1 s.
  • I did not add an mtime cache. Reading the cache file would cost about as much as the capped reads it saves.

Finding 4: duplicate names. Two agents with the same name now read Explore and Explore 2, numbered in id order, so a label stays on its agent while the list is re-sorted by recency.

Non-blocking notes from the earlier reviews.

  • The held overstatement is fixed (above).
  • KeepAlivePlans walks the keeper's map. It is capped at 512 entries and takes microseconds under the lock. I left it as is.
  • The slow-proxy margin is the fetch timeout. It predates this PR and is unchanged.

Render time. Interleaved A/B against main, 50 renders per cell, money and three named agents in the stub: no measurable change, and the slowest render was 425 ms (slow proxy). Every layout stays under 0.5 s; the table is in docs/plugin/statusline.md.

#524. The conflict hunk in record() is gone: refreshedAt is set on its own line after the entry literal. git merge-tree with #524's branch is clean, so either PR can merge first.

Tests: go vet is clean, and go test ./internal/thread ./dash ./proxy ./context-guru-plugin passes.

This is round 2, the last one. Please review at the head.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: REQUEST CHANGES at ee7b7f1, for one formatting fix only. (Posted as a comment: GitHub does not let the author account request changes.)

Blocking:

  • CI build-test fails at lint with gofmt needed: dash/cachestate_test.go. The one-line seed(t, rec, func() *Event { ...; return e }()) near line 167 has to be split; gofmt -w dash/cachestate_test.go is the whole fix. Everything below holds at this head.

Verified:

  • Money basis. threadMoney uses the dashboard's own savingsArithmetic, so x = baseline − cost − cg_llm + cachesplit_saved + keep-alive credit − pings, and y = baseline + cachesplit_saved + keep-alive credit. That makes y − x = cost + cg_llm + pings ≥ 0, so x ≤ y.
    • Every term is summed over the same rows of the thread: agent rows for baseline, cost, cg_llm, cachesplit and the keep-alive credit, and ping rows for the ping cost.
    • baseline_cost_usd is summed per row exactly as savings.go, overview.go and query.go already sum it, so the status line and the dashboard share one basis.
    • A negative x renders with a minus sign.
  • Session and subagents split. thread_id == "" is the main thread and every other thread is in subagents. Flipping that test makes TestCacheStateSplitsTheSessionsMoney fail, and so does dropping cachesplit and the keep-alive credit from y.
  • Bare columns. The select has exactly one MAX(...), so SQLite takes upstream_ms, model, the prefix and the TTL subquery's inputs from the row that holds it. A thread with no such row has a NULL MAX and is used for its money only (last.Valid).
  • No session id. The status line probes /healthz and never reads /api/stats.
  • _agent_names is bounded. On a sub-agent directory with 30,000 meta files and 100 listed ids, one call took about 1 ms and opened exactly 24 files. a:../.. and dot-ids are skipped.
  • Render time. On the stub harness, the minimal, balanced, detailed and watch layouts stay under 0.5 s in every scenario. The slowest is the slow-proxy case, just under 0.4 s.
  • refreshedAt. It is set at creation, and afterwards only by a ping that read the cache (record1 and the summary-substitute path). The sweep's pre-send bump never moves it. The proxy plan tests pass.
  • go vet is clean. The dash CacheState|CacheThreads|Lean|Golden|HeldUntil tests, internal/thread, proxy KeepAlivePlan|Refresh|Thread and the plugin status-line tests all pass. All commits are by Osher-Elhadad and signed off, with no AI lines, and the PR text has no experiment numbers.

Non-blocking:

  1. Nothing pins the single-MAX rule. I changed the ping SUM to a second MAX(...), which makes SQLite's bare columns undefined, and every test still passed, because each fixture thread has at most one ping. A thread with two pings in TestCacheStateSplitsTheSessionsMoney, or an assertion that the query contains exactly one MAX(/MIN(, would pin it.
  2. The status line's saved $x is not the same figure as the dashboard's total. /api/stats also adds DeclFilterSavings and CachesplitHistorical, which threadMoney leaves out, so with the tool filter on the status line shows less. One sentence in docs/plugin/statusline.md would explain the gap.
  3. _num(main, "saved_usd") or 0.0 would render a missing field as $0.00. The proxy always sends it, so this is moot today.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at 9ed9685. The only change since ee7b7f1 is gofmt formatting in dash/cachestate_test.go, and the file is now gofmt-clean. CI is green (build-test, purego, trivy, DCO). Signed off. The earlier review's non-blocking notes stand: no test pins the single-MAX rule, and the saving can read lower than /api/stats with the tool filter on. This approval covers 9ed9685.

Each a: agent on the line now carries its own figure from its
/api/cachestate thread row, on the same basis as the session and
subagents totals; side threads stay in the total only. A narrow
terminal drops the per-agent money first. A figure whose fields are
missing renders nothing instead of $0.00.

Tests pin the single-MAX bare-column rule (a thread with two pings and
an older and a newer cache touch), and goldens cover a main-only
session, two named agents plus a side thread, the narrow degrade and
missing fields. Docs say the line counts only per-request savings, so
it can read lower than the dashboard.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Update at 0686297, for the edited requirement and reviewer-2-2's notes.

  • Per-agent figures (requirement points 3, 5 and 6). Each listed a: agent now shows its own saved $z of $q from its /api/cachestate thread row, on the same basis (x <= y), next to its clock: reviewer active ● 11:40 ↻ saved $1.20 of $6.00.
    • p: side threads are not listed; they count only in the subagents total.
    • A session with no thread other than main shows only the session figure.
    • A tmux-pane teammate is its own session, so its own line shows its figure as session. The docs say this.
    • A narrow terminal drops the per-agent money first, then the subagents total.
  • Missing fields. A figure whose saved_usd or baseline_usd is missing from the response renders nothing instead of $0.00.
  • Keep-alive credit. It is realized: the credit is written per request, and only when a ping that read the cache (cache_read > 0) kept that request warm. It is not priced at read time.
  • Read-time credits. The tool-filter and historical cache-split credits stay out of x. The docs now say the line can read lower than the dashboard for that reason.
  • Single-MAX rule. TestCacheThreadsTakesItsCacheFieldsFromTheLatestTouch puts two pings and an older and a newer cache touch on one thread. It fails if the ping sum becomes a second MAX.
  • Goldens. New ones cover a main-only session, two named agents plus a p: side thread, the narrow degrade with per-agent figures, and missing fields.
  • Render time. Every layout stays under 0.5 s; the slowest was 447 ms, in the slow-proxy case.

@amiddavid this is the head for round 2.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at 0686297. (Posted as a comment: GitHub does not let the author account approve.)

  • Each listed a: agent shows its own saved $z of $q, and p: threads count only in the subagents total. _money_pair returns nothing when either half is missing, so an unknown value never renders as $0.00. A golden covers the missing-fields case.
  • The earlier MAX note is closed. With the ping SUM changed to MAX in cacheThreadsQuery, TestCacheThreadsTakesItsCacheFieldsFromTheLatestTouch fails.
  • The earlier docs note is closed. The statusline page now says the line can read lower than the dashboard's figure.
  • gofmt and go vet are clean, and the dash CacheThreads/CacheState tests and the plugin status-line goldens pass. CI is green, and the commit is signed off with no AI attribution.

This approval covers 0686297.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Point 3 of the edited requirement (per-agent figures) is in the head, 8c95e89. The code went in at 0686297; 9ed9685 did not have it.

  • _agents_segment reads each listed a: thread's saved_usd and baseline_usd from /api/cachestate and shows saved $z of $q after that agent's cache clock. Example: reviewer active ● 11:40 ↻ saved $1.20 of $6.00.
  • p: side threads are not listed and count only in the subagents total.
  • A narrow terminal drops the per-agent figures first (agents level 1), then the subagents total; the counts-only form is now level 2.
  • An agent whose row has no money fields shows no figure. A missing field never renders as $0.00.

Goldens in TestStatuslineGoldenMoney:

  • two named agents with figures plus a p: side thread that appears only in the total;
  • narrow width, where the per-agent figures drop first;
  • an agent with no money in its row;
  • missing fields;
  • a main-only session.

The earlier small items are in too:

  • the docs sentence that the line can read lower than the dashboard;
  • the two-ping single-MAX test TestCacheThreadsTakesItsCacheFieldsFromTheLatestTouch (it fails if the ping sum becomes a MAX).

Live, on a real Claude Code 2.1.296 session with two foreground subagents, the line read:

saved $0.00 of $0.06 session · saved $0.00 of $0.11 subagents
cache ● █████░ 7:24 ↻ │ agents general-purpo… ● 7:47 ↻ saved $0.00 of $0.01 · Explore ● 7:05 ↻ saved $0.00 of $0.01 │ ctx ░░░░░░░░ 2%

Each agent's $q matched the summed baseline of its own thread's rows, and the subagents total matched the sum over its two a: threads and four p: side threads. No compaction acted on these small requests, so $z is $0.00.

Render time: every layout stays under 0.5 s; the slowest was 447 ms, in the slow-proxy case. CI is running on the head.

@amiddavid please review round 2 at 8c95e89.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at 8c95e89. The only change since 0686297, which I approved, is one golden: an agent with no money row shows no figure while the other agent keeps its own. The plugin status-line goldens pass and go vet is clean. CI is green, and the commit is signed off. This approval covers 8c95e89.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict

Ready to merge from my side. All four round-1 points are fixed. The new money split meets the owner's comment. I found no defect. Two minor points and two questions are below. No third round.

Reviewed head: 8c95e89.

Findings

Round-1 points:

  1. Per-agent and split money (old finding 1, now the owner's comment): met.
    • Main line: saved $x of $y session · saved $x of $y subagents. The second part shows only when a thread other than "" exists (_save_segment).
    • Each listed a: agent shows its own saved $z of $q after its clock (_agents_segment). p: threads are not listed. They count only in subagents (ThreadsFor: t.ID == "" is main, all others go to Others).
    • Data comes from /api/cachestate (money, plus saved_usd and baseline_usd per thread). No new query.
    • I rendered a fixture with 1 main, 2 a: and 1 p: thread. Output: saved $50.32 of $250.00 session · saved $60.03 of $300.00 subagents, and reviewer ... saved $1.20 of $6.00. An agent with no money shows no figure.
  2. Basis (old finding 2): fixed. y = baseline + cachesplit + keep-alive credit. x = y - cost - cg_llm - pings (dash/cachestate.go threadMoney). So x <= y. The proxy's own calls and pings lower x and are not added to y. The read-time credits (CachesplitHistoricalUSD, DeclFilterSavings) are out of x. Test TestCacheStateSplitsTheSessionsMoney checks x <= y and that a p: thread, a thread with no cache touch and a ping all count.
  3. Unbounded name reads (old finding 3): fixed. At most 24 files opened, 4096 bytes each, at most 20000 directory entries listed. Plain ids use a direct path.
  4. Same label (old finding 4): fixed. Explore, Explore 2.
  5. No-session read (old question 2): fixed. With no session_id the line calls only /healthz. It no longer reaches the full handler.

New, minor:

  1. Cost of /api/cachestate now grows with the session. The thread query lost its 2 h bound. It reads every row of the session (indexed, same shape as lean). Measured on box 1 with the 20,000-row fixture: 70 ms (lean on the same fixture: 48 ms). The plugin calls both on each render, at most every 2 s, in parallel. This is inside the budget and is the cost the design needs. No change asked. Please note the number in the docs.
  2. Agents with no name on disk show no money. The unnamed form (agents 2 · soonest ◐ 0:50) has no per-agent figure. The owner's text says each listed agent shows one. This affects only non-Claude Code clients or an old Claude Code. Acceptable if you say so in the docs.

What I verified

  • Tests on box 1: dash (72 s), internal/thread, proxy (66 s), context-guru-plugin (362 s). All pass. CI is green.
  • Merge: git merge-tree of 8c95e89 with origin/main (now includes #519): clean. With #524 (9f9980f7): clean, and no conflict in meaning in proxy/keepalive.go. #524 retires entries through k.retire and retireSessionStartedBefore. KeepAlivePlans reads k.live, so a retired entry drops out of the plan. Its compact path retires the main thread only. The held-warm clock of an idle sub-agent stays.
  • Money for a session with no cache touch yet: the none answer carries money, and _main_cs keeps it.
  • Ping events carry the thread id (keepalive.go ping emit uses j.thread). Pings are charged to the right thread.
  • Bare-column rule of the single MAX in cacheThreadsQuery is pinned by TestCacheThreadsTakesItsCacheFieldsFromTheLatestTouch. EXPLAIN test TestCacheThreadsQueryIsIndexed is present.
  • Round-1 items I checked and found sound are unchanged: held-warm clock, lifetime path removal, fail-open.

Questions

  1. Teammate files are found by the name pattern agent-a<name>-<hex>.meta.json. This is from the author's live check on 2.1.296. A different pattern in another Claude Code version leaves the teammate unnamed (shown as the unnamed form), not wrong. Is that accepted?
  2. The status line saved (this thread split) now differs from /api/stats total_saved_usd (it adds the read-time credits). Do the dashboard and the status line need a line in the docs that says why they differ?

Reviewed by an AI reviewer (Claude)

@amiddavid
amiddavid merged commit 68748ea into main Oct 14, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 14, 2026
amiddavid added a commit to AIMikav/context-guru that referenced this pull request Nov 9, 2026
…gin to 0.2.1

Both plugins changed in v0.5.1: the Claude Code plugin gained the lifecycle
signal hooks (rossoctl#520, rossoctl#524) and the per-agent money status line (rossoctl#525); the
Codex plugin gained its SessionEnd and SessionStart hooks (rossoctl#524). A new
version number is what makes an installed plugin update.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Status line: a bounded lifetime total (daily rollup), without the #509 defects

2 participants