Skip to content

feat(plugin): five cost commands (today, unused, cold, compact, trends) - #441

Merged
amiddavid merged 1 commit into
mainfrom
feat/plugin-insights
Oct 12, 2026
Merged

amiddavid merged 1 commit into
mainfrom
feat/plugin-insights

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Refs #436 (Workstream C). Design note: #436 (comment)

What

Five cost commands for the Claude Code plugin, each a skill, replacing the question "what is my setup costing me" with answers that are ranked, priced at the gateway's rates, labelled observed / modelled / estimate, and netted against Context Guru's own overhead.

skill answers
cost-today what cost most and why: by token type, model, project, session; top 3 causes in plain words
cost-unused tools / MCP servers / skills carried but never called, ranked by dollars, with the removal command and a caution if used in the last 30 days
cost-cold where the cache went cold: rewrites by cause, pause-length bands, costliest events
cost-compact warm or cold per session, cost of the next turn, break-even chance of being away
cost-trends per-model and per-project sparklines, recommendations ranked by dollars

Two read-only Go endpoints (tests included): GET /api/spend/explain (one pass over the window; rewrites are cache_write >= 0.8 x context, read from token columns, not cache_miss_reason; the cause is inferred from idle gap and message count and says so) and GET /api/tools/last-used (names and times). Logic lives in scripts/cgcost.py, stdlib-only with the fetcher passed in, so the Codex plugin can vendor it unchanged. Old insights skills and the status line are untouched.

Rules enforced by tests: Context Guru's own server and skills are never offered for removal; built-ins are never offered; a tool called in the last 30 days is flagged; a cold cache is never described as avoidable by compacting; no ANSI escapes without a tty or with NO_COLOR.

Before / after

Before: /context-guru:insights lists findings from a 30-day window and has no answer to "what cost me most today", no per-session or per-project view, no rewrite classification, and no "compact now?" answer. The status line's unused-tool nudge ranks by use share and once named our own skill.

After (synthetic fixture, 14 days, not production data):

What cost you most in the last 14 days: $856.85  (11983 requests, observed, gateway rates)

Top causes
  1.  $445.56  52%  Re-reading the conversation each turn (cache reads, normal)
  2.  $128.53  15%  Model output
  3.  $123.96  14%  Pauses longer than the cache lives: the whole conversation was re-sent and re-cached  [$107.79 more than a cache hit would have cost, 214x]

Where the money went by token type
  cache reads     $445.56  52%  █████░░░░░
  cache writes    $257.05  30%  ███░░░░░░░
  output          $128.53  15%  ██░░░░░░░░
  uncached input   $25.71   3%  ░░░░░░░░░░

By model
  claude-opus-5     $574.31  67%  ███████░░░
  claude-sonnet-5   $237.78  28%  ███░░░░░░░
  claude-haiku-4-5   $44.75   5%  █░░░░░░░░░
Cache state of your recent sessions  (context and last touch observed; the rest is estimate)
  project    context   cache    state            cost of the next turn (estimate)
  api        212k tok  5m tier  warm 3:25 left   next turn if cold $1.01, if warm $0.081
  dashboard  96k tok   5m tier  COLD 20:00 ago   next turn if cold $0.182, if warm $0.015
  scripts    18k tok   1h tier  warm 30:00 left  next turn if cold $0.034, if warm $0.003

  api: warm for 3:25. Compact now costs ~$0.153 extra if you come back in time and saves ~$0.773 if you stay away past the TTL. Worth it if you think there is more than a 17% chance you will be away that long.
  dashboard: cache already expired. Your next message rewrites 96k tokens ($0.182) whatever you do - /compact now would pay that same rewrite, so it saves nothing on this turn. Compact (or /clear with a handoff note) only to shrink every later turn.
  scripts: warm, but the context is small enough that compacting does not pay. Leave it.
Carried but never called in 14 days: $37.70  (observed: declaration tokens re-read each turn, priced at the tier each turn billed)
  Removing the 6 below saves about $82.88/month if your usage stays the same  [estimate]

  MCP server   playwright     9k/turn  $18.40                             claude mcp remove playwright
  MCP server   sentry         3k/turn   $7.10  last used 62d ago          claude mcp remove sentry
  MCP server   figma          6k/turn   $6.20  used 4d ago - check first  claude mcp remove figma
  client tool  NotebookEdit   1k/turn   $3.30                             claude --disallowedTools "NotebookEdit"
  skill        brand-voice   420/turn   $1.60                             set "skillOverrides": {"brand-voice": "off"} in ~/.claude/settings.json
  skill        pdf           310/turn   $1.10  last used 40d ago          set "skillOverrides": {"pdf": "off"} in ~/.claude/settings.json

Never listed: Context Guru's own components and Claude Code's built-in tools (carrying the unused built-ins costs $2.40; you cannot remove them).
Spend, last 14 days: $856.85  ▆▆▁▁▇▇▅▆▇▂▁▇█▆  (peak $108.60/day, observed)
  rewrite cost ▆▆▁▁▇▇▅▆▇▂▁▇█▆  $145.67 extra paid over cache hits

By model   (last column: second half of the window vs first)
  claude-opus-5     ▅▆▁▁▇█▅▅▇▂▁▇█▆  $574.31  67%  +12%
  claude-sonnet-5   ▆▅▁▁▇▇▅▆▆▂▁▇█▆  $237.78  28%  +16%
  claude-haiku-4-5  ▅▆▁▁▇▇▆▆▇▂▁█▇▆   $44.75   5%  +15%

By project
  api        ▅▆▁▁▇█▅▅▇▂▁▆█▆  $440.89  51%  +10%
  dashboard  ▆▆▁▁█▇▅▇▇▂▁██▇  $266.85  31%  +18%
  scripts    ▆▄▁▁▆▇▄▆▆▁▁▆█▅  $104.36  12%  +14%
  site       ▅▆▁▁▇▇▆▆▇▂▁█▇▆   $44.75   5%  +15%

Ranked by dollars
  1.  $107.79  214 pauses outlived the cache; each re-sent the whole conversation. Compact or /clear before a long break (`compact`), see `cold` for the pause lengths.  [observed]

Verified

  • go test ./dash/ and ./context-guru-plugin/ pass (golden outputs in testdata/cost).
  • Run against a local proxy (distinct binary, port 4121) on a copy of the 2026-10-10 snapshot: usd.total reconciles to sum(cost_usd) minus unpriced rows; a 30-day window (151k requests) answers in about 1 s. Real outputs are kept out of the PR.

Limits

  • Per-project names come from the local transcript directory (the proxy does not know projects); sessions from other machines show as "(unknown project)".
  • cost-compact assumes a 4k-token summary and 15k surviving tokens; it ignores the saving on later turns, so it understates the case for compacting.
  • /api/tools is slow on a large database (about 7 s for 7 days on the snapshot copy); cost-unused and cost-trends wait for it.
  • The old insights skills are not yet pointed at the new ones.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Reviewer: approved, with non-blocking notes. CI all pass; go test ./dash ./context-guru-plugin green; gofmt clean.

Checked:

  • Tenant scoping: both routes are scopeTenant and use a.scope(r), which forces Tenant from the principal; ?tenant= only widens for a manager. I probed with tenant-a's principal and tenant-b rows in tool_uses: /api/tools/last-used (plain, ?tenant=tenant-b, ?tenant=) and /api/spend/explain?tenant= returned nothing of tenant-b.
  • Rewrites come from token columns (write >= 0.8 x ctx, ctx >= 2000, complete accounting only); cause is labelled an inference. Warm-up of 1h before Since is not counted. Net = (baseline - cost, non-ping rows) - cg_llm - ping cost, consistent with the existing SavedUSD = baseline - cost - cgllm.
  • Fixtures are synthetic; no prod ids/hosts.

Non-blocking:

  1. The scope fixture seeds no tool_uses, so TestAPIScopesEveryRouteToTheCaller does not exercise /api/tools/last-used. Add a two-tenant tool_uses case to TestToolsLastUsed (my probe above can be reused).
  2. gross_saved sums the session-accumulative baseline_cost_usd, so 'gross saved (modelled)' is cumulative-style; say 'session-accumulative' in the printed label or the net line can be over-read.
  3. /api/spend/explain with no since scans all requests (bounded only by the heavy timeout); the plugin should always pass a window.

Ordering vs #440: no conflict. #441 adds cgcost.py and does not modify context-guru-plugin/scripts/insights.py, which #440 vendors as insights_core.py, so no rebase is needed in either order. Only a later PR that edits insights.py needs to refresh the Codex copy.

@OsherElhadad OsherElhadad added the ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval label Oct 11, 2026
OsherElhadad pushed a commit that referenced this pull request Oct 12, 2026
…commands

Status line: saved session/today/lifetime, a cache bar that drains to expiry with a
ping marker, a context bar with a rewrite-near warning, one hint, refreshInterval 5.
New cg plugin: /cg, savings, cache, waste, session, doctor, built on the cost engine
from #441 (moved, not copied). Codex gets the same commands as skills.

Signed-off-by: Osher-Elhadad <[email protected]>
Adds GET /api/spend/explain (dollars by token type, full-prefix rewrites
classified from token columns, live cache state, Context Guru ledger) and
GET /api/tools/last-used, and scripts/cgcost.py with five skills: cost-today,
cost-unused, cost-cold, cost-compact, cost-trends. Refs #436.

Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad pushed a commit that referenced this pull request Oct 12, 2026
Commands, all /context-guru:*: status is now the home screen (bottom line, today vs
yesterday, top three actions); new savings, cache, waste, session, doctor. The
insights* and cost-* commands stay for one release as thin redirects. The cost engine
from #441 stays in this plugin; Codex gets the same names as skills.

Status line: saved session/today/lifetime, a cache bar that drains to expiry with a
ping marker, a context bar with a rewrite-near warning, one hint, refreshInterval 5.

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

Copy link
Copy Markdown
Collaborator Author

Rebased on main after #445/#477; the conflict was in dash/api.go (both cache fields and both heavy-route timeout entries kept). Plugin tests pass locally; the dash suite hit a database-locked flake under load in a broad run, the spend and last-used tests pass alone. #478 builds on this commit and turns the five cost-* skills into thin redirects to the new /context-guru:* commands for one release.

@amiddavid
amiddavid merged commit b33f2ce into main Oct 12, 2026
6 checks passed
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review after the rebase (98359cd): mergeable, the dash/api.go conflict resolution keeps both sides, and the diff is the same five cost commands with the spend and last-used endpoints. ready-to-merge stays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants