Skip to content

feat(plugin): status and insights savings show saved tokens on a subscription - #989

Merged
amiddavid merged 4 commits into
mainfrom
feat/cmd-subscription
Nov 10, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/cmd-subscription

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (the owner asked for it on 2026-11-09, and decided the token form for #998):

  • Who: Claude subscription users of /context-guru:status and /context-guru:insights savings (also the Savings part of /context-guru:insights).
  • Old: the screens show dollars.
  • New: the screens show everything in tokens, by tier, and no dollars. One estimate line shows the 5-hour share.
  • How to turn it off: it is on only when the proxy reports a subscription (GET /api/me/limits). API key, Bedrock and Vertex users see no change.

Closes #986. Part 2 of #998 for the commands. #999 (part 1, the tokens fields in /api/stats) is in main.

Summary

On a subscription, the two screens show tokens only. The source is tokens.saved and tokens.caused in /api/stats (#999). They cover every feature: compaction, cache split, keep-alive and the 1-hour cache.

/context-guru:status:

This session:       saved 42.0k wr · 610.0k rd
This 5-hour window: saved 85.0k wr · 1.2M rd · cost 9.0k rd
                    ≈ 3% of the 5-hour limit (estimate at API-price weights)

Today:              saved 31.0k wr · 240.0k rd · cost 15.0k rd
Yesterday:          saved 26.0k wr · 190.0k rd
7 days:             saved 214.0k wr · 1.6M rd · 12.0k in · cost 3.0k wr · 96.0k rd
                    3 requests not measured in tokens

/context-guru:insights savings has the same head, then one line per feature:

✓ By feature   (tokens by tier: wr = cache write, wr1h = 1-hour cache write, rd = cache read, in = input)
  mask                                 saved 160.0k wr · 1.3M rd · cost 3.0k wr
  toolfilter                           saved 30.0k wr · 300.0k rd · 12.0k in
  Keep-alive rescue                    saved 24.0k wr · cost 96.0k rd
  Keep-alive pings (not in the total)  cost 900 wr · 410.0k rd · 30 in

What changed

  • scripts/cg.py (and the identical Codex copy):
    • Display rule (shared with the dashboard and the band): the tiers never add into one number. The order is wr, wr1h, rd, in. A tier at 0 does not show. Paid tiers show after cost.
    • Session and window lines read tokens from the lean /api/stats reads. The old saved_unique / replay_tokens source is gone.
    • status: Today, Yesterday and the period in tokens, from the full reads. The "≈ Estimated" list keeps its order, without dollar amounts.
    • insights savings: one line per tokens.by_feature entry. Compaction components show by name, then Cache split, Keep-alive rescue, 1-hour cache, Ended change. cachesplit is one entry. The pings (keepalive_ping_tokens) show apart, because they are not in the total.
    • Not measured: when tokens_unmeasured_requests > 0, the period line has a note N requests not measured in tokens.
    • No dollars on a subscription: the "At API prices" dollar screen, the sparklines, the manual-pings row and the details bill line do not show.
    • 5-hour estimate: unchanged (dollar-ratio formula, cap, thresholds).
    • A subscription with no session id and no open window still shows the period in tokens. Before, it showed the dollar view.
  • Docs: docs/plugin/status.md and docs/plugin/savings.md show the new screens and explain the tiers. docs/data-dependence.md row updated.

Data dependence

Metadata only: token counts by tier and dollar totals the dashboard already keeps, and the 5-hour usage share from the limit headers (#984). The same at each storage level. With storage off, /api/stats has no data and the screen says so, as today.

How it was tested

  • cg_subscription_test.go:
    • Goldens home-subscription and insights-savings-subscription, regenerated.
    • {}, 404, 500, bad JSON and subscription:false give exactly the existing dollar goldens.
    • New TestCGSubscriptionTokenLines: all four tiers in order, cost only, no tokens field, the not-measured note.
    • Estimate cases (low use, small spend, nothing saved, cap, below the cap) now also check that no $ shows.
    • TestCGSubscriptionNoSessionNoWindow now expects the period in tokens, for both screens.
  • The stats fixtures gained tokens, tokens_unmeasured_requests and keepalive_ping_tokens. The dollar goldens do not change.
  • TestDocsExamplesAreTheGoldens and TestCGScriptsAreVendoredIntoCodex pass.
  • go test -count=1 -v ./context-guru-plugin/... on the eval box at 639b73d0: ok in 362 s. 777 PASS, 0 FAIL, 3 SKIP.
  • claude plugin test context-guru-plugin (local): 98 pass, 1 fail. The fail (no data: the band is left to the engine, no clock.now) also fails on origin/main. It is not from this PR.

Open questions

  1. The period total is tokens.saved / tokens.caused, as the shared rule says. It does not include the keep-alive pings, which show as their own line in insights. Should the total subtract the pings, as the dollar total does?
  2. The "≈ Estimated" list on status and insights keeps its items, but without the dollar amounts. Is that right, or should a subscription drop the list?
  3. Manual pings (the Ping button) have only a dollar figure, so the subscription screen does not show them.

🤖 Generated with Claude Code

…cription

On a Claude subscription, /context-guru:status and /context-guru:insights
savings now lead with the tokens saved in this session and in the current
5-hour window. One line below gives the 5-hour share as an estimate at
API-price weights, only with enough data (window cost >= $0.50, use >= 2%).
The dollar screen follows, marked as API prices.

- cg.py reads GET /api/me/limits (#984). On {}, 404, an error or the
  Codex copy, the screens are exactly as before.
- Reuses the status line's _saved_tokens_text and _human.
- New goldens, Go tests and docs; the Codex copy of cg.py stays identical.

Closes #986

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 17c583ed461e approve

Verdict: approve

Findings

None. I found no real defect.

Non-blocking

  • context-guru-plugin/scripts/cg.py:475 — the Codex gate is untested. subscription() turns off only because import statusline fails in the Codex copy. No test runs that copy without statusline.py. A stray statusline module on sys.path would pass the gate and crash on sl._saved_tokens_text. The tip command already uses the same pattern, so the risk is not new.
  • context-guru-plugin/scripts/cg.py:523 — a failed lean read prints "nothing saved yet". An unreachable proxy and an empty session read the same way. The status line has the same wording, so I leave it.
  • context-guru-plugin/scripts/cg.py:517 — insights without a subcommand runs all three screens. Each calls subscription_head, so /api/me/limits is read up to 3 times. The /api/stats reads hit the server cache; the limits read does not. Cheap to dedupe if it ever matters.
  • The estimate uses the utilization of the latest answer the proxy saw. That value can be stale inside the window. The docs say "your last response", so it is disclosed.

What I checked

  • Read the full diff and the code around each change: both cg.py copies, the new Go test, both goldens, the three docs.
  • Verified the two cg.py copies are byte-identical (cmp), as TestCGScriptsAreVendoredIntoCodex requires.
  • Traced every fail-open path. Api.get catches OSError and ValueError, so 404, 500, bad JSON and no answer all return None. Then subscription() returns None and the screen is the dollar view. TestCGSubscriptionAbsentKeepsTheDollarView covers {}, 404, 500, bad JSON and subscription:false.
  • Confirmed the endpoint contract against PR #984 (feat/limit-headers, commit 0d8cfe0b): GET /api/me/limits returns subscription, five_hour.utilization as 0..1 and reset_s in unix seconds. cg.py reads the same names and units. This PR depends on #984; the PR body says so, and a proxy without it answers 404, which fails open.
  • Confirmed the window math: start = reset_s*1000 - 5h, and since is epoch ms, which is what dash/api.go's filterFrom parses.
  • Ran the new Python functions locally with fake API answers (no Go, no network): subscription, limit_estimate and subscription_head. Results match the goldens and the test table: 54% × $0.70 / $12.40 → ≈ 3%; low use, small spend, nothing saved and an ended window all hide the estimate; the session-only layout pads to its own width.
  • Checked the estimate gates against the docs: used >= 2% and cost >= $0.50, both stated in docs/plugin/status.md and savings.md.
  • Verified both new goldens appear verbatim in their doc pages, which TestDocsExamplesAreTheGoldens asserts.
  • Checked statusline.py import safety: it has a __main__ guard, and cg.py already imported it lazily before this PR.
  • Checked the rules: fail open holds; the data-dependence row is added and is accurate (metadata only); the behavior change is named at the top of the PR body with the old and new behavior and how it is off.

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 17c583ed461e blocking

Verdict: blocking

Findings

  1. context-guru-plugin/scripts/cg.py:523 — the rd half of both new token lines is always empty on a real proxy, because the lean /api/stats handler never computes replay_tokens.
    • What fails: a subscription user runs /context-guru:home. The proxy answers GET /api/stats?lean=1&session=… and GET /api/stats?lean=1&since=… with "replay_tokens": 0. So _saved_tokens_text drops the rd part (it omits counts below 1), and both lines show only wr: This session: saved 42.0k wr. The golden promises saved 610.0k rd / 42.0k wr. The docs (status.md, savings.md) tell the user rd is "tokens that would have been re-sent as cache reads". That half never renders.
    • Proof: the lean path is dash/overview_lean.go:62 (overviewLeanWindow). Its scan fills Requests, TokensBefore, TokensAfter, SavedUnique, CostUSD, … — it never sets SavedGross or ReplayTokens. The only assignment of Overview.ReplayTokens in the repo is dash/overview.go:720, inside the full Overview() path, which lean bypasses (dash/api.go:1360 sends every lean=1 read with a session or a since to OverviewLean). Both new reads carry a session or a since, so both get 0. The goldens show a rd count only because the test stub fabricates it (cg_subscription_test.go:47 and :63 write replay_tokens by hand); no dash test asserts replay_tokens for lean, and the sibling dash PR (e3c6dc5) does not fix the lean handler either.
    • Fix: in overviewLeanWindow, after the scan, add o.SavedGross = o.TokensBefore - o.TokensAfter and o.ReplayTokens = max(0, o.SavedGross - o.SavedUnique) — both columns are already scanned, same agent-only population as the full path. The dash change can be its own PR, but it must land with or before this one, or the screens and docs must drop rd. Note the same gap already hides rd in the status line (#511) and the mod band (#735); this PR makes it the lead of two screens.

Non-blocking

  • context-guru-plugin/scripts/cg.py:472 — the Codex copy can import an unrelated statusline module and crash. _statusline() only catches a failed import. In the Codex scripts folder there is no statusline.py, so import statusline falls through to the rest of sys.path; any installed module of that name is returned. Then sl._saved_tokens_text (line 524) raises AttributeError, and nothing catches it, so /context-guru:home exits with a traceback. The tip command and status_extras wrap their statusline use in try/except; this code does not. A hasattr(sl, "_saved_tokens_text") check in _statusline() closes it.
  • No test for "subscription on, no session id, no open window". subscription_head then returns [] (cg.py:529-530), so the screen is the dollar view with no At API prices note. That path is unreachable in the tests because runCG always sets CLAUDE_CODE_SESSION_ID.

What I checked

  • Read CLAUDE.md, docs/design.md, the full diff, and the code around every change: cg.py (both copies), cg_subscription_test.go, cg_test.go, both goldens, docs/data-dependence.md, docs/plugin/status.md, docs/plugin/savings.md.
  • Verified the two cg.py copies are byte-identical (diff clean), and that TestCGScriptsAreVendoredIntoCodex covers them.
  • Traced every new proxy read: GET /api/me/limits (shape checked against PR #984's handler, commit 0d8cfe0: subscription:true, five_hour.utilization as a fraction, five_hour.reset_s in seconds — the parser matches); /api/stats?lean=1&session= and ?lean=1&since= (both hit the lean branch, dash/api.go:1360).
  • Verified the window math: start = reset_s*1000 − 5h, an expired window (reset_s*1000 <= now) treated as absent, utilization bounds 0..10, bools rejected by _real.
  • Verified the estimate math: pct = used% * saved / cost is the savings' share of the limit at API-price weights; the $0.50 and 2% gates match the docs.
  • Verified fail-open on every read: Api.get returns None on 404, 500, bad JSON, and timeout; _saved_tokens_text(None) returns None; the screens then fall back to the dollar view. Confirmed by the {} / 404 / 500 / bad-JSON / subscription:false test against the existing goldens.
  • Verified the goldens: the tails below the new head are byte-identical to home.golden and insights-savings.golden; the padding math (w = 20) and the ≈ 3% value (54 × 0.7 / 12.4) reproduce; both docs pages embed the golden text exactly (TestDocsExamplesAreTheGoldens mapping added).
  • Verified the test stub routing: non-lean /api/stats reads pass through to the existing warm stub; unexpected lean reads fail the test; the fixed clock (1791473400000 ms) is consistent with subReset and subWindowStart.
  • Checked the repo rules: behavior change named at the top of the PR with the owner's 2026-11-09 request and an off switch; data-dependence row added (metadata only, consistent with the neighbors); no request-path code touched, so no fail-open risk to the proxy itself.

Review round 1 of #989.

- The estimate is min(used x saved / cost, 100 - used). The provider
  stops a user at 100%. At the cap the line says "without context-guru
  you would have hit the 5-hour limit", with the same words as #988.
- /api/me/limits is read once per run; `insights` draws three screens.
- _statusline() accepts only a module that has _saved_tokens_text, so a
  stray statusline module in the Codex copy cannot crash the screens.
- Tests: over, at and just below the cap; one limits read per run;
  subscription with no session id and no open window.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. Fixes are in 563828b2.

Reviewer 1

  1. Lean /api/stats gives replay_tokens 0, so rd never shows (blocking). Agreed. The cause is a bug in main, not in this PR. PR fix(dash): lean /api/stats fills replay_tokens and saved_gross #992 (issue dash: lean /api/stats never fills replay_tokens, so rd is always missing #990) fixes it: the lean handler now fills saved_gross and replay_tokens. This PR does not change dash/. The PR body now says "Depends on feat(proxy): record the subscription limit headers and serve GET /api/me/limits #991 and fix(dash): lean /api/stats fills replay_tokens and saved_gross #992 (merge those first)".
  2. The Codex copy can import an unrelated statusline module and crash (non-blocking). Fixed. _statusline() returns the module only when it has _saved_tokens_text. Otherwise the screen keeps the dollar view.
  3. No test for "subscription on, no session id, no open window" (non-blocking). Added TestCGSubscriptionNoSessionNoWindow. With no tokens to show, the screen is the home golden, unchanged.

Reviewer 2

  1. The Codex gate is untested; a stray statusline module would crash. Fixed with the same hasattr check as reviewer 1's item 2.
  2. A failed lean read says "nothing saved yet". No change. The status line uses the same words, and the screens should agree.
  3. insights reads /api/me/limits up to 3 times. Fixed. The result is kept for the run. TestCGSubscriptionReadsLimitsOncePerRun checks 1 read.
  4. The utilization can be stale inside the window. No change. The docs say the window comes from the last response the proxy saw.

Also fixed (found in the #988 review, it applies here too)

Tests: go test -count=1 -timeout 30m ./context-guru-plugin/... on the eval box at 563828b2: ok in 335.8 s. 776 PASS, 0 FAIL, 3 SKIP (-v test and subtest lines).

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 563828b2dfa7 approve

Verdict: approve

Findings

None. The new commit is correct, and I accept the author's replies.

Earlier findings

  • Reviewer 1, finding 1 (blocking): lean /api/stats never fills replay_tokens, so rd never shows. Fixed the right way. I verified the defect is in main, not in this PR: at base 569c609b, dash/overview_lean.go never assigns SavedGross or ReplayTokens, and this PR still does not touch dash/. PR #992 (fix/lean-replay-tokens, open, based on main) adds exactly the proposed arithmetic (SavedGross = TokensBefore - TokensAfter, ReplayTokens clamped at 0) plus a lean-vs-full test. The repo rule says a main defect gets its own PR, and the PR body now names both dependencies and what breaks without each. I accept the reason. See Non-blocking for the merge-order note.
  • Reviewer 1, non-blocking 2 and my non-blocking 1: a stray statusline module crashes the Codex copy. Fixed. _statusline() now returns the module only when it has _saved_tokens_text. I checked it in Python with a fake statusline module in sys.modules: the gate returns None.
  • Reviewer 1, non-blocking 3: no test for "subscription on, no session, no window". Fixed. TestCGSubscriptionNoSessionNoWindow empties CLAUDE_CODE_SESSION_ID, and the screen is the home golden.
  • My non-blocking 3: /api/me/limits read up to 3 times under insights. Fixed, and I must correct myself: my count was wrong. Only the Savings screen calls subscription_head, so one run already read it once. The memoization (o["_sub"]) is harmless, and TestCGSubscriptionReadsLimitsOncePerRun pins the count at 1.
  • My non-blocking 2 ("nothing saved yet" on a failed read) and 4 (stale utilization). Rejected by the author, with reasons I checked and accept: the status line uses the same words, and the docs say the window comes from the last response the proxy saw.

Non-blocking

  • Merge order is now a hard requirement: #991, then #992, then this PR. Both dependencies are open today. If this PR merges first, the rd half of the token lines is silently absent until #992 lands. The PR body discloses this, so I only record it.
  • limit_estimate with used > 100 (an over-limit user): 100 - used is negative, so the cap line always shows. The wording "would have hit the 5-hour limit" is past tense for a user already over it. Cosmetic; the message is still true in spirit.

What I checked

  • Last review: round 1, 17c583ed461ebdb0497b88bae51c1cf97293571c, 2026-11-09T16:44:55Z.
  • New commits read: 1 (563828b2 "fix(plugin): cap the 5-hour estimate and read the limits once per run").
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 1's round-1 review (blocking replay_tokens finding, 2 non-blocking), the author's round-1 reply comment, and the fix commit. I checked each one as above.
  • Read the full new diff and the code around it: both cg.py copies, cg_subscription_test.go, both docs pages. Verified the two cg.py copies are still byte-identical (cmp).
  • Verified the dependency story: PR #991 is the old #984 (GET /api/me/limits), PR #992 fixes the lean replay_tokens; both are open and based on main. Confirmed the gap is real in main by grepping dash/overview_lean.go at base 569c609b.
  • Ran the changed Python functions locally with fake answers (no Go, no network): the memoization reads /api/me/limits once across 3 calls; the cap table matches the new tests exactly (135 → cap line, 55.2 ≥ 55 → cap line, 54 → ≈ 54%, 3.05 → ≈ 3%); a statusline module without _saved_tokens_text turns the gate off.
  • Checked the new tests' assertions for false positives: the cap line does not contain the substring est ("of the 5-hour limit …"), because it reads "hit the 5-hour limit", so the notLines checks are sound.
  • Checked the unchanged goldens still hold: the ≈ 3% case stays below the cap (3.05 < 46), and TestDocsExamplesAreTheGoldens is unaffected because the docs' code blocks did not change.

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 563828b2dfa7 approve

Verdict: approve

Findings

None. Everything from round 1 is fixed or answered, and the new commit adds no defect.

Round 1 findings

  1. rd never shows: lean /api/stats returns replay_tokens 0 — fixed by a declared dependency. PR #992 (fix/lean-replay-tokens) adds to overviewLeanWindow exactly the missing arithmetic (SavedGross = TokensBefore − TokensAfter, ReplayTokens = max(0, gross − unique), from the same agent-only columns) plus a test that compares lean to the full read on a 3-turn fixture (gross/unique/replay 1200/400/800). I read the whole #992 diff. The #989 body now says "Depends on #991 and #992 (merge those first)" and names what is missing until each lands. This follows the repo rule: the main defect gets its own PR off main. The stub-fabricated replay_tokens in this PR's tests is now fine, because #992 makes the real endpoint match.

Non-blocking from round 1

  • Codex stray statusline import — fixed. _statusline() now returns the module only when it has _saved_tokens_text (cg.py:478). A stray module keeps the dollar view instead of crashing.
  • No test for "no session id, no open window" — fixed. TestCGSubscriptionNoSessionNoWindow compares against the home golden.

New in this round

  • Reviewer 2's items: the Codex gate is fixed by the same hasattr check; the "nothing saved yet" wording and the stale utilization were declined with reasons I accept (the status line uses the same words; the docs disclose the source of the window). The repeated limits read is fixed by memoizing in o["_sub"], with TestCGSubscriptionReadsLimitsOncePerRun. Note insights calls subscription_head only from its savings screen, so the limits read was already 1 per run; the memoization makes it robust if the other screens adopt the head later. Either way, correct.
  • The estimate cap (pct >= 100 - used → "≈ without context-guru you would have hit the 5-hour limit"): the logic is right — savings worth more than the headroom mean the user would have crossed 100%. I recomputed all three new test cases (45 × 45/15 = 135 → cap; 45 × 18.4/15 = 55.2 ≥ 55 → cap; 45 × 18/15 = 54 → "≈ 54%") and the golden case (54 × 0.7/12.4 = 3%). The docs state the cap in both pages. The cap message does not contain the substring the notLines assertions forbid, so the tests check the right thing.
  • Memoization safety: "_sub" not in o keeps a None result cached; nothing iterates or serializes o; o is built once per run.
  • Fail-open: unchanged from round 1 — every read still returns None on failure and the screen falls back to the dollar view.

Non-blocking

  • cg_subscription_test.go:144 — the env override in TestCGSubscriptionNoSessionNoWindow works only on Linux. The test appends CLAUDE_CODE_SESSION_ID= after the harness's CLAUDE_CODE_SESSION_ID=session-A, relying on the child seeing the last duplicate. I checked the semantics with a raw execve: on Linux, Python's os.environ keeps the last duplicate, so the override clears the id and the test passes (the author's eval-box run confirms it). On macOS, execve itself keeps the first duplicate, so the id would stay session-A and the test would fail there. CI is ubuntu-latest only and Go runs on the Linux eval box, so this only bites someone who runs the plugin tests on a Mac. A runCGCode that drops an earlier duplicate of a key the case sets would make it portable.

What I checked

  • Last review: round 1, 17c583e, 2026-11-09T16:48:11Z.
  • New commits read: 1 — 563828b2 "fix(plugin): cap the 5-hour estimate and read the limits once per run".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: the author's round-1 reply (checked every line: each fix verified in the diff, each decline checked and accepted), the fix commit 563828b2 (full diff and the code around each change), and the two dependency PRs it names.
  • Read PR #992's full diff: the lean replay_tokens fix is the arithmetic I proposed, with a lean-vs-full test; #991 is the limit-headers PR this stack already depended on. The #989 body names both and says what breaks until each lands.
  • Verified the two cg.py copies are still byte-identical after the fix commit.
  • Recomputed the estimate cap for all new test cases and the golden; confirmed the cap message and the notLines substrings cannot collide.
  • Checked the new tests' mechanics: the counted stub's atomic counter, the insights single-run assertion, and the duplicate-env override (verified Linux vs macOS execve semantics with a raw execve test; the passing eval-box run confirms Linux behavior).
  • Confirmed both docs pages still embed their goldens verbatim, so TestDocsExamplesAreTheGoldens holds.
  • Checked the repo rules: no request-path change, so no fail-open surface; the cap is a display change inside the already-declared behavior change, covered by the owner's 2026-11-09 request.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

On hold (owner's decision, 2026-11-09). This PR is approved, but it waits for #998 part 1.

#998 stores the accountant's tier tokens, so that every saving can be shown in tokens: compaction, cache split, keep-alive and TTL. Today only compaction has a token count. Once #998 part 1 merges, this PR switches its token source to those fields, and the dollar figures go away on a subscription.

amiddavid added a commit that referenced this pull request Nov 10, 2026
The lean stats read never set saved_gross or replay_tokens. It always
answered 0. The status line, the mod band and the status screens
then showed only "wr", never "rd".

overviewLeanWindow now computes both as the full read does, from the
columns it already scans. No new query.

Closes #990

Behavior change: a fix of wrong output.
- Who: everyone who reads /api/stats?lean=1 with a session or a time
  window (status line, mod band, subscription screens in #988, #989).
- Old: "saved 593 wr". The "rd" half never showed.
- New: "saved 1.2M rd / 593 wr".
- Turn off: no switch. Revert this PR.
Owner's yes, 2026-11-10, in the integrator session: "I approve the chhange in 981, 991 and 992".

Data dependence: metadata only (token counts). No change.

Reviews: 2 offload reviews (GLM), round 1, both approve at 0cbd4d7. c3662e6 changes only comment lines (approval-still-valid: comments only).

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
…pi/stats (#999)

Part 1 of #998. The dashboard stored only the dollars of each saving.
The tokens were lost after the write. This PR stores the tokens
by tier beside the dollars.

- 8 new columns in request_components and 32 in requests
  (default 0). Tokens follow the same attribution as the dollars.
- /api/stats (full and lean=1) now returns tokens,
  tokens_unmeasured_requests and the two keepalive_ping token fields.
  Both paths call one function, DB.AccTokens.
- PRs #988 and #989 use the new fields as their token source.

Behavior change: none stated; new fields in /api/stats. No existing
figure, field or column changes its value.
Owner's yes, 2026-11-10, in the integrator session: "999 approve".

Data dependence: metadata only. The new columns are token counts.
They are the same at each storage level. docs/data-dependence.md
row "Accountant savings" is updated.

Reviews: 2 offload reviews (GLM), round 4 (owner granted round 4), both approve at 3ae7056. Round 4 reviewed the rebase onto main after #991, which merged #991's limit columns and #999's token columns by hand in 4 files.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
…tats

On a Claude subscription, /context-guru:status and /context-guru:insights
savings now show everything in tokens, with no dollars (#998 part 2).

- The totals come from tokens.saved and tokens.caused (#999), not from
  saved_unique and replay_tokens. They cover every feature, not only
  compaction.
- The tiers show apart, in the order wr, wr1h, rd, in. A tier that a
  change paid shows after "cost".
- status: this session, the 5-hour window with the estimate, then
  today, yesterday and the period. The estimates show without dollars.
- insights savings: the totals, then one line per feature from
  tokens.by_feature. The keep-alive pings show apart, outside the total.
- A note counts the requests with no token figure.
- The 5-hour estimate is unchanged.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Changes since the last review round (round 1 fixes were at 563828b2; now at 639b73d0). #999 is in main, so the hold is over.

  1. Merged origin/main (no conflicts). No force-push.
  2. Token source. The session, window and period lines read tokens.saved and tokens.caused from /api/stats. The old saved_unique / replay_tokens source is gone. The lines now cover every feature, not only compaction.
  3. Display rule (shared with feat(dash): on a Claude subscription show saved tokens, with the 5-hour share as an estimate #988 and the band): tiers apart, order wr, wr1h, rd, in, zeros left out, paid tiers after cost. Example: saved 85.0k wr · 1.2M rd · cost 9.0k rd.
  4. No dollars on a subscription (owner's decision). The "At API prices" dollar screen is gone.
    • status: Today, Yesterday and the period in tokens. The estimates list has no dollar amounts.
    • insights savings: one line per tokens.by_feature entry. cachesplit is one entry. The keep-alive pings show apart, as "not in the total".
  5. Not measured: a note N requests not measured in tokens when tokens_unmeasured_requests > 0.
  6. 5-hour estimate: unchanged.
  7. Changed result: a subscription with no session id and no open window now shows the period in tokens, not the dollar view.
  8. Tests and docs: goldens regenerated, new TestCGSubscriptionTokenLines, docs updated. Box: go test ./context-guru-plugin/... ok, 777 PASS, 0 FAIL, 3 SKIP. Local plugin tests: 98 pass, 1 fail that also fails on origin/main.

Open questions are in the PR body.

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 639b73d051fe approve

Verdict: approve

Findings

None. The rework is correct, and the earlier findings stay resolved.

Earlier findings

  • Reviewer 1, round 1 (blocking): lean /api/stats gave replay_tokens 0. Resolved for good: #992 is in main, and this PR no longer reads replay_tokens at all. The token source is now tokens.saved / tokens.caused (#999, also in main). My round-2 merge-order note is resolved the same way: #991, #992 and #999 are all in main, and this branch merged main (e52495f5, no conflicts).
  • Stray statusline module (reviewer 1 round 1, my round 1). Still fixed, and the gate moved with the code: _statusline() now checks hasattr(sl, "_human"), which is the only statusline attribute the subscription path uses (tier_text). I checked that no other sl. call remains in the new code.
  • My round 2, non-blocking: over-limit users always see the cap line. Unchanged. Still cosmetic.

What is new in 639b73d0

I reviewed it as a first review:

  • Token source. tokens, tokens_unmeasured_requests and keepalive_ping_tokens come from /api/stats. I verified the dash side serves them on both paths: AccTokensRead.apply is called from the full read (dash/overview.go:823) and the lean read (dash/overview_lean.go:92), and the JSON tags (input, cache_read, cache_write_5m, cache_write_1h, by_feature) match the plugin's TIERS keys. The lean read has the totals only, and the plugin uses by_feature only from the full read — the two sides agree.
  • No dollars on a subscription. This is a second behavior change on top of round 1. The PR body names it at the top with the owner's decision, the old and new behavior, and the off switch. The docs state it. I accept it as declared.
  • End-to-end check. I ran cmd_home and cmd_savings in Python against the PR's own fixtures with a fake API (no Go, no network). The subscription screens reproduce the new goldens' heads line for line, and no line contains $. With subscription absent, both screens reproduce the existing dollar goldens byte-for-byte (the savings body; the "More:" footer is added by the insights wrapper, which my harness bypassed).
  • Formatting functions. tier_text, flow_text, tokens_text, unmeasured_note, feature_rows and aligned match every case in TestCGSubscriptionTokenLines and the estimate table: all four tiers in order, zeros left out, cost apart, N requests not measured in tokens singular/plural, blank rows and continuation lines aligned at width 20.
  • Fail-open. Every read goes through Api.get, which returns None on failure. A missing tokens field prints "nothing saved yet"; a failed Today read skips the row. TestCGSubscriptionAbsentKeepsTheDollarView still pins the dollar goldens for {}, 404, 500, bad JSON and subscription:false, and the fixture changes (added tokens fields) do not change the dollar output — I verified both dollar goldens still reproduce.
  • Housekeeping. The two cg.py copies are byte-identical (cmp). Both new goldens appear verbatim in docs/plugin/status.md and savings.md, so TestDocsExamplesAreTheGoldens holds. The data-dependence row is updated and is accurate (token counts by tier, dollar totals for the estimate, the limit share; metadata only).

Non-blocking

  • Reviewer 1's round-2 note (the CLAUDE_CODE_SESSION_ID= override relies on last-duplicate env semantics, Linux-only): the test still writes the env that way, but the rework made it moot. With the session id kept (the macOS behavior), the output gains only the session line, which has no $ and no "5-hour" when no window is open, so the assertions pass either way.
  • The PR body's open questions (pings outside the period total, the estimate list without dollars, manual pings invisible on a subscription) are owner questions, not defects. I have nothing to add to them.
  • The author reports one local plugin-test failure that also fails on origin/main. Disclosed, and outside this PR's diff.

What I checked

  • Last review: round 2, 563828b2dfa77722fb028b07e68f160a81668474, 2026-11-09T17:24:36Z.
  • New commits read: 2 (e52495f5 "Merge remote-tracking branch 'origin/main' into feat/cmd-subscription", 639b73d0 "feat(plugin): show subscription savings in tokens by tier from /api/stats"). The merge brought main in; I checked that it carries #991, #992 and #999, the three dependencies named in the earlier rounds.
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 1's round-2 review (approve; one macOS env note, see above), the author's hold comment (waiting for #998 part 1, now in main), the author's changes comment, and the two new commits. I checked each one as described above.
  • Read the full 639b73d0 diff (both cg.py copies, cg_subscription_test.go, both goldens, the three stats fixtures, the three docs pages) and the code around each change.
  • Verified the dash contract for the new fields (dash/acctokens.go, dash/overview.go, dash/overview_lean.go): field names, JSON tags, lean vs full scope, pings held out of the total.
  • Ran the new code locally in Python against the PR's fixtures: both subscription screens, the dollar fallback, and every formatting function.
  • Checked the tests' assertions for false positives: the "no $" check is sound because the token screens print no prices; the notLines substrings cannot collide with the cap line.

@amiddavid amiddavid 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 639b73d051fe approve

Verdict: approve

Findings

None. The round-3 rewrite is correct, and every path I could break fails open.

Earlier findings

  1. Round 1, blocking: lean /api/stats gave replay_tokens 0, so rd never showed. Superseded, and resolved. The token source is now tokens.saved / tokens.caused from #999, which is in the base. I verified the lean path serves them: dash/overview_lean.go:92 calls tok.read().apply(o), leanAgg.read() returns the totals and the unmeasured count, and the lean branch of the stats handler serializes the same Overview (json:"tokens", dash/overview.go:439). The old saved_unique / replay_tokens reads are gone from cg.py. The session and window lines can no longer render empty for a missing field.
  2. Round 1, non-blocking: a stray statusline module could crash the Codex copy. Fixed, and the round-3 gate is stronger. _subscription returns None whenever _statusline() is None (cg.py:502), so the whole token view needs the module, not just one line. The guard now checks _human, which exists (statusline.py:337).
  3. Round 1, non-blocking: no test for "subscription on, no session id, no open window". Fixed. TestCGSubscriptionNoSessionNoWindow exists and now expects the period in tokens on both screens.
  4. Reviewer 2's round-1 items were answered at 563828b2; I checked them in round 2 and have nothing to add.

What I checked

  • Last review: round 2, 563828b2dfa77722fb028b07e68f160a81668474, 2026-11-09T17:26:10Z.
  • New commits read: 2 — e52495f5 (merge origin/main, no conflicts), 639b73d0 (feat(plugin): show subscription savings in tokens by tier from /api/stats). The merged main tip 7fd26dcd (#999) read as the new base.
  • Read in full: 4 reviews, 3 comments, 0 inline comments.
  • New items since my last review:
    • Author comment 2026-11-09T20:07:59Z ("On hold, owner's decision, waits for #998 part 1"): the hold is over, #999 is in main. Nothing to do.
    • Author comment 2026-11-10T08:38:16Z (round-3 changes, 8 points): each point checked against the code, below.
    • Commit 639b73d0: full re-review, as a first review.

Checks on the round-3 change:

  • Token source vs the #999 contract. TIERS in cg.py reads cache_write_5m, cache_write_1h, cache_read, input — the exact JSON names of TierTokens (dash/acctokens.go:22-27). EFFECTS keys cachesplit, keepalive, ttl, ended_change match the feature names the server writes (requestTokenEffects, EndedChangeComponent = "ended_change").
  • Lean vs full split. by_feature is absent on the lean read (AccTokenStats.ByFeature, omitempty). The plugin reads by_feature only from st, which comes from the full stats() read in home_tokens and savings_tokens. The lean reads in subscription_head use only tokens.saved / tokens.caused, which lean serves. Consistent.
  • Fail-open. No tokens field → tokens_text → "nothing saved yet". Empty by_feature → "Nothing saved yet" table row. A failed window read → limit_estimate returns None. subscription() still memoizes into o["_sub"]. TestCGSubscriptionAbsentKeepsTheDollarView still covers {}, 404, 500, bad JSON and subscription:false.
  • The statusline gate. tier_text calls sl._human, which the round-3 _statusline() guard requires. The Codex copy has no statusline.py, _subscription returns None there, and the dollar view stays.
  • Helpers the new code calls. Every recommendations item carries short and cls (cgcost.py:425-454), so r["short"] and r["cls"].split(";")[0] cannot raise. C.table(rows, "ll") exists and pads as the goldens show.
  • The two cg.py copies are byte-identical (diff clean), so TestCGScriptsAreVendoredIntoCodex holds.
  • Docs. docs/plugin/status.md and docs/plugin/savings.md embed home-subscription and insights-savings-subscription verbatim, in the exact ```text block form TestDocsExamplesAreTheGoldens requires. I ran the same containment check.
  • Behavior change. The PR body names it at the top: who, old and new behavior, the owner's decision of 2026-11-09, and the off switch (the view is on only when /api/me/limits reports a subscription). The docs/data-dependence.md row is updated.
  • The changed result (no session id and no open window → period in tokens, not dollars) has a test and is named in the PR body.

Non-blocking

  • From round 2, unchanged: TestCGSubscriptionReadsLimitsOncePerRun overrides CLAUDE_CODE_SESSION_ID by appending a duplicate entry. Linux Python keeps the last duplicate, so the test works; macOS execve keeps the first, so it would not. CI runs Linux only. Test mechanics, no user-facing effect.
  • The PR body's open questions (pings vs the period total, the unpriced "≈ Estimated" list, manual pings with no token figure) are for the owner. Each one is already visible in the output as designed: the pings row says "not in the total", and the list keeps its order without dollar amounts.

@amiddavid
amiddavid merged commit fd2722f into main Nov 10, 2026
9 checks passed
amiddavid added a commit that referenced this pull request Nov 10, 2026
main was red since d058b33 (#1018):
TestCGCachestateCarriesTheStatusLinesExtras and
TestCGCachestateWindowTokensByCase failed with window_saved empty.

Cause: cg.py defined tokens_text twice. #1018 added
tokens_text(stats, human) at line 259; #989 (merged just before it)
added tokens_text(st) at line 572, which shadowed it. status_extras
then called the wrong one with 2 arguments; it swallows the
TypeError, so window_saved stayed empty. Each PR was green alone:
#1018's branch never had #989, so the collision appeared only after
both merged (a semantic merge conflict).

Fix: rename #1018's helper to band_tokens_text, with its one call and
one doc mention, in both copies of cg.py (the Codex copy too). No
test changes.

Behavior change: none intended; it restores the band's window saving
that #1018 added (owner-approved).
Data dependence: none.

Reviews: 2 offload reviews (GLM), round 1, both approve at 753bcc4.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
The owner's rule for every screen: the keep-alive ping tokens are not
in the total and not in any card's cost. The band's lean read has no
ping tokens, so this is the one rule all screens can follow.

- totalTokens: the cost is tokens.caused only.
- featureTokens: the keep-alive and Cache flows leave the pings out.
- A line "Keep-alive pings (not in the total): cost ..." shows under
  the total and on the Cache card, with the same words as #989.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
…0.2.12, Pi 0.1.1)

Claude Code plugin 0.6.7 -> 0.7.2:
- #981, #989, #1018, #1035: subscription band and savings show saved tokens.
- #1038: insights drop the finding that credits a user's own removal.
- #1039, #1040: dash and keep-alive fixes that touch the plugin files.

Codex plugin 0.2.11 -> 0.2.12:
- #1051: read the cache strategies and presets from the proxy.
- The vendored cg.py gets the same plugin changes.

Pi package 0.1.0 -> 0.1.1:
- #1010: chain the proxy in front of an existing base URL.
- #1011: check the proxy at session start and restart it once.
- #1049, #1058: write the cache strategy by name; review fixes.

OpenCode plugin (#483): new in v0.7.2, no version file, not changed.
Bob plugin 0.1.0: no change since v0.7.1, not changed.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
Bump the plugin versions for v0.7.2.

- Claude Code plugin 0.6.7 -> 0.7.2: #981, #989, #1018, #1035 (savings
  in tokens on a subscription), #1038, #1039, #1040, #1055 (cache
  strategies read from the proxy).
- Codex plugin 0.2.11 -> 0.2.12: #1051 (cache strategies and presets
  read from the proxy), plus the vendored cg.py changes.
- Pi package 0.1.0 -> 0.1.1: #1010, #1011, #1049, #1058, and the #1040
  README line.
- OpenCode plugin: new in v0.7.2 (#483), no version file. Its first
  start now downloads proxy v0.7.2 (was v0.7.1). Nothing compares
  against PINNED_VERSION; the floor stays "v0.7.1 or later". The README
  lines, the install guide and 3 tests follow.
- Bob plugin: 0.1.0, no change since v0.7.1.

Behavior change: the OpenCode plugin's first download is proxy v0.7.2,
not v0.7.1. Owner's yes, 2026-11-11, in the integrator session: "option1
it is"; the version bumps: "I approve the version bumps for the
plugins".

Data dependence: none.

Reviews: 3 offload review rounds (GLM; round 3 pre-approved by the
owner). Both reviewers approve at 3cf6176, which is the PR head.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

status and insights: on a subscription show saved tokens, with the 5-hour share as an estimate

1 participant