feat: Claude Code Monitor — lanes, pipelines and a merged workspace

Internal SmartGift build of a Claude Code monitoring dashboard.

Lanes: a durable unit of parallel agent work, one per working directory,
tracked across session restarts. Managed lanes are git worktrees the
dashboard provisions and can reset or remove behind a three-check destroy
guard and a counted preflight; adopted lanes are directories you already
own and are never destroyable.

Pipelines: a lane moves through pipeline stages. A stage the agent declares
with evidence renders green; a stage inferred from the tool-event stream
renders dashed amber and never counts as done. Detection is forward-only
within a 30-minute window, and never writes the declared stage.

Workspace: one page at /run with a lane grid, the selected lane's pipeline,
and a full Claude console behind a disclosure.
This commit is contained in:
2026-07-29 17:07:45 +07:00
commit 57dc91585d
783 changed files with 221743 additions and 0 deletions
@@ -0,0 +1,17 @@
{
"name": "ccam-cost-guard",
"description": "Budget tracking, spend forecasting, and cost-threshold alerts for Claude Code usage via the Agent Monitor pricing engine. Watches spend against a target budget, projects month-end cost from the daily trend, surfaces the priciest sessions, estimates savings from cheaper-model routing, and wires up cost alert rules — all backed by the dashboard at http://localhost:4820.",
"version": "1.0.0",
"author": {
"name": "Nguyễn Ngọc Trí Vĩ",
"url": "https://git.smartgift.io.vn/Smartgift-AI"
},
"homepage": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor",
"repository": {
"type": "git",
"url": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor.git"
},
"license": "MIT",
"keywords": ["budget", "cost", "forecast", "alerts", "spend", "pricing", "claude-code"],
"categories": ["cost", "monitoring", "alerts"]
}
@@ -0,0 +1,70 @@
---
name: budget-sentinel
description: >
Watches Claude Code spend against a target budget from the Agent Monitor
dashboard. Reads the live pricing-engine cost total, splits it per model,
projects month-end (and week-end) spend from the daily session trend
(moving average × remaining days), flags the sessions driving overage,
and recommends concrete cuts ranked by dollar impact. Cross-checks any
configured cost alert rules so its guidance lines up with what will
actually fire. Grounded in /api/pricing/cost, /api/analytics,
/api/sessions, and /api/alerts/rules.
model: sonnet
tools:
- Bash
- Read
- Grep
---
# Budget Sentinel
You are a budget sentinel for Claude Code usage. You query the Agent Monitor
dashboard API at `http://localhost:4820` using `curl -s http://localhost:4820/api/...`
to compare real spend against a target budget, project where the month will land,
and recommend the cheapest path back under budget — every claim backed by a number
the API actually returned.
## Available Data Sources
Query these endpoints using `curl -s http://localhost:4820/api/...`:
| Endpoint | What it returns |
|----------|----------------|
| `/api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — fleet-wide spend, split per model. This is the source of truth for "how much have I spent". |
| `/api/analytics` | `{ tokens (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), total_cost, daily_sessions (365d: [{ date, count }]), daily_events, tool_usage, agent_types, event_types, total_subagents, overview, ... }` — the daily trend feeds the forecast. |
| `/api/sessions?limit=200` | Session list — each has `id`, `status`, `model`, `cwd`, `started_at`, `ended_at`, inline `cost`, and `metadata` (JSON: thinking_blocks, turn_count, total_turn_duration_ms, usage_extras). Used to rank the priciest sessions and spot premium models on cheap work. |
| `/api/alerts/rules` | `{ rules: [{ id, name, rule_type, config, enabled, cooldown_seconds }] }` — existing rules. `token_threshold` rules (`config.total_tokens`) are the spend-relevant guardrails; reconcile your budget advice with them. |
## Key Concepts
- **Spend = pricing engine output.** Always take the live figure from `/api/pricing/cost` `total_cost`; do not re-derive it unless explaining the math.
- **Cost formula**: `(tokens / 1M) × rate_per_mtok` summed over the 4 token types (input, output, cache_read, cache_write); the longest matching `model_pattern` wins.
- **Default rates ($/Mtok in/out/cacheRead/cacheWrite)**: Opus $5/$25/$0.50/$6.25, Sonnet $3/$15/$0.30/$3.75, Haiku $1/$5/$0.10/$1.25.
- **Effective totals**: `/api/analytics` token fields are `current + compaction baseline`, so cost already reflects recovered context — do not double-count.
- **Spend has no native timestamp split.** Approximate daily spend by distributing `total_cost` across `daily_sessions` counts (cost-per-session × sessions/day), or sum inline session `cost` by `started_at` day when you need a sharper daily curve.
- **Alert rules track tokens, not dollars.** The dashboard's `token_threshold` rule fires on cumulative session tokens; convert a dollar budget to an approximate token ceiling using the blended rate from the cost breakdown when advising on rules.
## Analysis Framework
1. **Establish the budget.** Take the target from the user (e.g. "$50/month", "$10/week"). If none is given, ask for one or infer a sensible default and state the assumption.
2. **Read current spend.** Fetch `/api/pricing/cost`; record `total_cost` and the per-model `breakdown`. This is spend-to-date.
3. **Build the daily trend.** Fetch `/api/analytics`; from `daily_sessions` compute a 7-day moving average of sessions/day and an average cost-per-session (`total_cost / total_sessions`). Daily spend ≈ avg sessions/day × avg cost/session.
4. **Project the period.** `projected_spend = spend_to_date + (avg_daily_spend × days_remaining_in_period)`. Compute the projected over/under vs. the budget and the percent of budget consumed so far.
5. **Find the drivers.** From `/api/sessions?limit=200`, rank sessions by inline `cost` descending; identify premium-model sessions (Opus) doing low-turn / low-complexity work (cross-check `metadata.turn_count` and `model`).
6. **Reconcile alerts.** Fetch `/api/alerts/rules`; note whether a spend-relevant `token_threshold` rule exists and whether its ceiling lines up with the budget. Recommend creating or tightening one if there is a gap.
7. **Recommend cuts.** Translate findings into ranked, dollar-quantified actions (route eligible work to Sonnet/Haiku, raise cache reuse, cap expensive session types).
## Output Standards
- Lead with a verdict line: **on track** / **at risk** / **over budget**, with spend-to-date, budget, and projected end-of-period spend.
- Cite specific numbers from the API — never vague qualifiers.
- Format currency as USD to 4 decimal places; token counts with thousands separators; rates as $/Mtok.
- Show deltas and pace vs. budget with ▲/▼ indicators (▲ = trending over, ▼ = trending under).
- Rank recommended cuts by estimated monthly savings (descending); cap at the top 5; attach a confidence level (high/medium/low) to each.
- When you convert a dollar budget to a token ceiling for an alert rule, show the blended rate and the arithmetic.
## Constraints
- Read-only advisory role — never modify data. Recommend alert-rule changes; do not POST them yourself.
- Only use data returned by the API — never fabricate metrics. If a daily split is approximated, say so.
- If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
@@ -0,0 +1,24 @@
---
description: Show current Claude Code spend versus a budget number
argument-hint: "[monthly-$]"
---
Show current Claude Code spend against the budget **$ARGUMENTS** (a monthly dollar
figure, e.g. `50`). If `$ARGUMENTS` is empty, just report spend-to-date and ask for a budget.
1. Fetch current spend:
```
curl -s http://localhost:4820/api/pricing/cost
```
Read `total_cost` (spend-to-date) and the per-model `breakdown`.
2. Print a concise budget status:
- **Spend to date**: `total_cost` as USD to 4 decimals.
- **Budget**: `$ARGUMENTS`/month.
- **Consumed**: `total_cost / budget × 100`% — with a ▲/▼ vs. the linear pace expected for today's day-of-month (`budget × day_of_month / days_in_month`).
- **Verdict**: under budget / on pace / over budget.
- **Top 3 models by cost** from the breakdown (model, cost, % of total).
If the dashboard is unreachable (curl fails / empty), tell the user to start it with
`npm start` from the repo root. Keep the output to a few lines plus one small table.
Currency as USD to 4 decimal places. Read-only — do not modify anything.
@@ -0,0 +1,27 @@
---
description: Quick month-end spend projection from the daily trend
argument-hint: "[week|month]"
---
Give a quick spend projection for the end of the **$ARGUMENTS** period (`week` or
`month`; default `month` if empty).
1. Fetch the trend and current spend in parallel:
```
curl -s http://localhost:4820/api/analytics
curl -s http://localhost:4820/api/pricing/cost
```
From `/api/analytics` read `daily_sessions` (`[{ date, count }]`) and the session
total; from `/api/pricing/cost` read `total_cost`.
2. Project:
- `avg_cost_per_session = total_cost / total_session_count`.
- `avg_daily_spend = mean(last 7 days of daily_sessions[].count) × avg_cost_per_session`.
- `days_remaining` = days left until end of the chosen period (week → Sunday; month → last calendar day).
- `projected_total = total_cost + avg_daily_spend × days_remaining`.
3. Print: spend-to-date, `avg_daily_spend`, `days_remaining`, and the **projected end-of-period total** (USD, 4 decimals), with a ▲/▼ note on whether the 7-day pace is above or below the trailing 14-day pace.
State that daily spend is approximated from session counts. If the dashboard is
unreachable, tell the user to start it with `npm start` from the repo root. Keep it to
a few lines. Read-only — do not modify anything.
@@ -0,0 +1,21 @@
---
description: List the most expensive sessions pushing your spend up
argument-hint: "[top-N]"
---
List the sessions driving Claude Code spend up — the **top $ARGUMENTS** most expensive
(default top 10 if empty).
1. Fetch a wide slice of sessions:
```
curl -s "http://localhost:4820/api/sessions?limit=200"
```
2. Sort the returned sessions by inline `cost` **descending** and take the top N.
3. Print a table — rank, session id/name, `model`, `started_at`, `metadata.turn_count`, and `cost` (USD, 4 decimals). Below it:
- **Sum of the top N** and what share of fleet spend they represent (sum top-N `cost` / sum of all `cost`).
- Flag any Opus session with a low `turn_count` as a downshift candidate (point to the `model-savings` skill).
If the dashboard is unreachable, tell the user to start it with `npm start` from the
repo root. Keep it to one table plus two summary lines. Read-only — do not modify anything.
+15
View File
@@ -0,0 +1,15 @@
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "jq -c '{event_type: \"Stop\", session_id: .session_id, stop_reason: .stop_reason, timestamp: (now | todate)}' 2>/dev/null | curl -s -X POST http://localhost:4820/api/hooks/event -H 'Content-Type: application/json' -d @- > /dev/null 2>&1 || true"
}
]
}
]
}
}
@@ -0,0 +1,80 @@
---
description: >
Define a spend budget for Claude Code and, optionally, create a cost alert
rule that fires when usage crosses the limit, via POST /api/alerts/rules on
the Agent Monitor dashboard. Reads current spend from /api/pricing/cost to
size the budget sensibly and explains every rule field before writing.
Use when setting a spend limit or wiring up a budget guardrail.
---
# Budget Set
Help the user define a spend budget and turn it into a live cost guardrail on the
Agent Monitor dashboard.
## Input
The user provides: **$ARGUMENTS**
This is the budget to set — e.g. `"$50/month"`, `"$10/week"`, or `"200000 tokens"`.
If a period is omitted, treat it as a monthly budget and say so. If no number is
given, read current spend first and propose a target.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — current spend, used to size the budget and compute the blended $/token rate |
| `GET /api/alerts/rules` | `{ rules: [{ id, name, rule_type, config, enabled, cooldown_seconds }] }` — existing rules, so you don't create a duplicate guardrail |
| `POST /api/alerts/rules` | Create a rule. Body: `{ name, rule_type, config, enabled?, cooldown_seconds? }`. Returns `{ rule }` |
## How a budget becomes a rule
The dashboard's alerting engine fires on **tokens**, not dollars. The spend-relevant
rule type is **`token_threshold`**, whose config is `{ total_tokens }` — it fires when
a session's cumulative tokens (input + output + cache_read + cache_write) cross the
threshold. To turn a **dollar** budget into a token ceiling:
```
blended_rate_per_token = total_cost / total_tokens # from /api/pricing/cost
token_ceiling = budget_dollars / blended_rate_per_token
```
Compute `total_tokens` by summing the four token columns across the cost `breakdown`.
### Rule fields explained
| Field | Meaning |
|-------|---------|
| `name` | Human label shown in the alert feed (e.g. `"Monthly $50 budget"`). Required, non-empty. |
| `rule_type` | `"token_threshold"` for a spend guardrail. (Other types: `event_pattern`, `inactivity`, `status_duration` — not spend-related.) |
| `config.total_tokens` | Positive integer token ceiling. A session crossing it fires the alert. Derive from the dollar budget as above. |
| `enabled` | `true` to arm immediately (default), `false` to stage it. |
| `cooldown_seconds` | Minimum seconds between re-fires for the same scope. Default `300`. Raise it (e.g. `3600`) so a single overspending session doesn't spam the feed. |
## Report Sections
### 1. Current spend snapshot
From `/api/pricing/cost`: `total_cost`, total tokens, and the blended $/Mtok rate. State how much of the proposed budget is already consumed.
### 2. Budget interpretation
Restate the parsed budget (amount + period). If converting dollars → tokens, show the blended rate and the `token_ceiling` arithmetic.
### 3. Existing guardrails
List any `token_threshold` rules from `/api/alerts/rules` so the user sees what is already in place; warn before creating a near-duplicate.
### 4. Proposed alert rule
Show the exact JSON body you would POST, with each field annotated. Then give the ready-to-run command (only run it on explicit confirmation):
```
curl -s -X POST http://localhost:4820/api/alerts/rules \
-H 'Content-Type: application/json' \
-d '{"name":"Monthly $50 budget","rule_type":"token_threshold","config":{"total_tokens":12500000},"cooldown_seconds":3600}'
```
### 5. Confirmation
On success, echo the returned `rule` (id, name, config). Remind the user that the rule is per-session token usage — to track a whole-period dollar budget, pair it with `/ccam-cost-guard:forecast` and the `spend-forecast` skill.
## Output
Markdown with the snapshot, the conversion math, and the annotated rule body. Currency as USD to 4 decimal places; token counts with thousands separators. Only POST after the user confirms — never create a rule silently.
@@ -0,0 +1,54 @@
---
description: >
Review the configured cost alert rules and the alerts currently fired on the
Agent Monitor dashboard, then explain exactly what tripped and why. Uses
/api/alerts (fired feed) and /api/alerts/rules (definitions). Use when
checking spend alerts or asking why a cost alarm went off.
---
# Cost Alert
Audit the spend guardrails: which rules exist, which have fired, and what tripped them.
## Input
The user provides: **$ARGUMENTS**
This may be empty (review everything), `"unacked"` (only unacknowledged alerts),
or a rule name to focus on.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/alerts/rules` | `{ rules: [{ id, name, rule_type, config, enabled, cooldown_seconds }] }` — the guardrail definitions |
| `GET /api/alerts` | `{ alerts: [{ id, rule_id, rule_name, rule_type, session_id, agent_id, message, details, triggered_at, acked }], total, unacked, limit, offset }` — the fired-alert feed, newest first. `?unacked=true` filters to unacknowledged |
## What the rule types mean
| `rule_type` | `config` | Fires when |
|-------------|----------|------------|
| `token_threshold` | `{ total_tokens }` | A session's cumulative tokens (input + output + cache_read + cache_write) cross the ceiling — the spend-relevant guardrail |
| `event_pattern` | `{ event_type?, tool_name?, summary_contains?, count?, window_minutes? }` | Matching events reach `count` within the window |
| `inactivity` | `{ minutes }` | An active session goes quiet for `minutes` |
| `status_duration` | `{ status, minutes }` | An agent is stuck in `working`/`waiting` for `minutes` |
For cost work, focus on `token_threshold`. Translate its token ceiling to dollars using the blended rate from `/api/pricing/cost` (`total_cost / total_tokens`) so the user sees the alarm in money terms.
## Report Sections
### 1. Configured guardrails
Table from `/api/alerts/rules`: name, type, the human-readable threshold (e.g. `token_threshold → 12,500,000 tokens ≈ $50.0000`), enabled state, cooldown. Flag rules that are `disabled` or have no spend-relevant guardrail at all.
### 2. Fired alerts
Table from `/api/alerts`: rule name, `triggered_at`, scope (session/agent id), `acked`, and the `message`. Lead with the `unacked` count. Honor `"unacked"` input by querying `?unacked=true`.
### 3. What tripped — per alert
For each fired alert, parse `details` and explain in plain terms: e.g. *"session X crossed 12,500,000 tokens (threshold 12,500,000) ≈ $50.12 at current rates — your `token_threshold` budget rule fired."* Tie the observed value back to the rule's config.
### 4. Next steps
Suggest acknowledging stale alerts (`POST /api/alerts/:id/ack` or `/api/alerts/ack-all`), tightening or loosening a threshold, or arming a missing budget rule (point to the `budget-set` skill).
## Output
Markdown tables. Currency as USD to 4 decimal places; token counts with thousands separators. Make the link between each fired alert and the rule that produced it explicit — never report a raw alert without saying which rule tripped and why.
@@ -0,0 +1,59 @@
---
description: >
Run a daily spend check-in against a daily budget on the Agent Monitor
dashboard — today's spend vs the daily target, pace through the day, and the
projected overage if the current pace holds. Uses /api/pricing/cost and
/api/sessions (grouped by started_at = today). Use for a quick daily spend
check-in or a morning/evening budget pulse.
---
# Daily Budget Check
A fast daily pulse: are you on pace against today's budget?
## Input
The user provides: **$ARGUMENTS**
This is the **daily budget in dollars** — e.g. `"5"` or `"$5/day"`. If omitted, ask
for one or derive it from a monthly budget (`monthly / days_in_month`) and state the
assumption.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — fleet-wide spend and the avg cost-per-session used to value today's sessions |
| `GET /api/sessions?limit=200` | Session list with inline `cost` and `started_at` — filter to today (`DATE(started_at) = today`) to isolate today's spend |
## Method
Spend has no per-day field, so isolate **today** from the session list:
1. **Today's sessions** = sessions whose `started_at` is today (local date).
2. **Today's spend** = sum of inline `cost` over today's sessions. If inline `cost` is absent for some rows, fall back to `today_session_count × (total_cost / total_session_count)` and flag it as approximate.
3. **Pace**: `fraction_of_day_elapsed = hours_since_midnight / 24`. `expected_by_now = daily_budget × fraction_of_day_elapsed`.
4. **Pace delta** = `today_spend expected_by_now` (▲ ahead of budget / ▼ behind).
5. **End-of-day projection**: `projected_today = today_spend / fraction_of_day_elapsed` (linear extrapolation of the current pace). Guard against tiny `fraction_of_day_elapsed` early in the day — if under ~0.1, label the projection low-confidence.
6. **Projected overage** = `projected_today daily_budget` (positive = over).
## Report Sections
### 1. Today vs budget
One headline line: **today's spend / daily budget**, and the percent consumed. Verdict: **under** / **on pace** / **over**.
### 2. Pace
`expected_by_now` vs actual `today_spend`, the ▲/▼ pace delta, and the fraction of the day elapsed.
### 3. End-of-day projection
`projected_today` and the projected overage/headroom vs the daily budget. Note the confidence (low early in the day).
### 4. Today's drivers
Today's sessions ranked by `cost` (top 5): name/id, model, cost. Surface any premium-model session inflating the day.
### 5. Nudge
If projected over: one concrete cut (route the priciest session type cheaper — see `model-savings`; or arm a `token_threshold` rule via `budget-set`). If under: confirm headroom and the remaining daily allowance.
## Output
Compact Markdown — this is a daily check-in, keep it tight. Currency as USD to 4 decimal places; pace deltas with ▲/▼. Lead with the verdict line.
@@ -0,0 +1,72 @@
---
description: >
Estimate the dollars saved by routing eligible Claude Code work to a cheaper
model family, using the Agent Monitor pricing engine. Re-prices each model's
token mix at the target family's rates and quantifies the delta. Uses
/api/pricing (rates), /api/pricing/cost (current per-model spend), /api/sessions,
and /api/analytics. Use when hunting for cost cuts or comparing model tiers.
---
# Model Savings
Quantify how much spend you would recover by moving eligible work to a cheaper model.
## Input
The user provides: **$ARGUMENTS**
This is the routing question — e.g. `"Opus → Sonnet"`, `"move simple work to Haiku"`,
or empty (analyze every premium model against the next tier down). If no target family
is named, default to proposing the next-cheaper tier per model and say so.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/pricing` | `{ pricing: [{ model_pattern, display_name, input_per_mtok, output_per_mtok, cache_read_per_mtok, cache_write_per_mtok }] }` — the rate card for every family |
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — current spend and the exact token mix per model |
| `GET /api/sessions?limit=200` | Sessions with `model`, inline `cost`, and `metadata` (turn_count, thinking_blocks) — used to judge which work is *eligible* to downshift |
| `GET /api/analytics` | `agent_types`, `tool_usage`, `total_subagents` — corroborate which task types are low-complexity and safe to route cheaper |
## Savings method
For each candidate model in the cost `breakdown`, re-price its **exact token mix** at the target family's rates:
```
cost_at_target = (input_tokens / 1M) × target.input_per_mtok
+ (output_tokens / 1M) × target.output_per_mtok
+ (cache_read_tokens / 1M) × target.cache_read_per_mtok
+ (cache_write_tokens/ 1M) × target.cache_write_per_mtok
savings = current_model_cost cost_at_target
```
Pull `target.*_per_mtok` from `/api/pricing` (longest `model_pattern` match wins). Default rates ($/Mtok in/out/cacheRead/cacheWrite): **Opus** $5/$25/$0.50/$6.25, **Sonnet** $3/$15/$0.30/$3.75, **Haiku** $1/$5/$0.10/$1.25.
### Eligibility — don't promise savings on work that needs the big model
Re-pricing the full token mix is the *theoretical ceiling*. Scope it to **eligible** work:
- Low-turn sessions (`metadata.turn_count` small) and simple subagent/tool work are safe to downshift.
- Heavy-reasoning sessions (many thinking_blocks, high turn counts) likely need the premium model — exclude or discount them.
- Report both the **full re-price** (ceiling) and an **eligible-only** estimate, and state the eligibility rule you applied.
## Report Sections
### 1. Current spend by model
Table from `/api/pricing/cost`: each model, its 4 token counts, and current cost. Note its share of `total_cost`.
### 2. Re-priced at target family
For each candidate, show `cost_at_target` and `savings` (absolute $ and %). Make the target rate card explicit.
### 3. Eligible-only estimate
Apply the eligibility rule and recompute savings over just the downshiftable token mix. Show how many sessions / what share of tokens qualified.
### 4. Recommended routing
Rank routing moves by eligible monthly savings (descending), top 5. For each: source → target, the token mix moved, estimated $ saved, and a confidence level (high/medium/low) based on how clearly the work is low-complexity.
### 5. Caveats
Cheaper models may need more turns or produce more output — note that realized savings can be lower than the static re-price, and that quality-sensitive work should stay on the premium tier.
## Output
Markdown tables. Currency as USD to 4 decimal places; token counts with thousands separators; rates as $/Mtok. Always present both the ceiling (full re-price) and the eligible-only estimate so the number is honest.
@@ -0,0 +1,61 @@
---
description: >
Forecast Claude Code spend to the end of the week or month from the daily
session trend on the Agent Monitor dashboard — moving average of daily spend
× days remaining, added to spend-to-date. Uses /api/analytics daily_sessions,
/api/pricing/cost, and /api/sessions for a per-day cost curve.
Use when projecting cost or asking "where will my spend land".
---
# Spend Forecast
Project where Claude Code spend will end up by the close of the current week or month.
## Input
The user provides: **$ARGUMENTS**
This is the forecast horizon — `"week"`, `"month"`, or a specific date. Default to
**month** (calendar month-end) when nothing is given, and state the horizon you used.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/analytics` | `{ total_cost, tokens (effective totals, baselines pre-summed), daily_sessions (365d: [{ date, count }]), daily_events, overview, ... }``daily_sessions` is the trend the forecast extrapolates |
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — authoritative spend-to-date and avg cost-per-session input |
| `GET /api/sessions?limit=200` | Session list with inline `cost` and `started_at` — group by day for a sharper daily-spend curve than the count-based approximation |
## Forecast method
Spend has no native per-day field, so build a daily-spend series and extrapolate:
1. **Spend-to-date** = `total_cost` from `/api/pricing/cost`.
2. **Avg cost per session** = `total_cost / total_session_count`.
3. **Daily spend series**: for the trailing window, `daily_spend[d] ≈ daily_sessions[d].count × avg_cost_per_session`. For a sharper curve, instead sum inline session `cost` grouped by `DATE(started_at)`.
4. **Moving average**: `avg_daily_spend = mean(daily_spend over the trailing 7 days)`. Also compute a 14-day average to gauge whether the trend is accelerating (▲) or cooling (▼).
5. **Remaining days**: days left until the end of the chosen horizon (week = through Sunday; month = through the last calendar day).
6. **Projection**: `projected_total = spend_to_date_this_period + (avg_daily_spend × days_remaining)`.
> Spend-to-date this period: when the trend covers more than the current period, restrict the spend-to-date term to sessions whose `started_at` falls inside the current week/month so the projection isn't inflated by older spend.
## Report Sections
### 1. Spend to date
`total_cost`, session count, avg cost/session, and how much falls inside the current period.
### 2. Daily trend
The 7-day and 14-day moving averages of daily spend, with a ▲/▼ accelerating-vs-cooling read. Show the last 7 days as a compact table (date, sessions, est. spend).
### 3. Projection
`avg_daily_spend × days_remaining` and the resulting `projected_total` for the horizon. State the days-remaining count explicitly.
### 4. Budget check (if a budget is known)
If the user mentions a budget, show projected vs. budget, the over/under delta, and the date the budget is projected to be crossed (`days_to_budget = (budget spend_to_date) / avg_daily_spend`).
### 5. Confidence & caveats
Note that the forecast assumes the recent daily pace holds, that daily spend is approximated from session counts unless an inline-cost curve was used, and call out any low-data horizons (e.g. fewer than 7 active days).
## Output
Markdown with the trend table and the projection. Currency as USD to 4 decimal places; show moving averages and the projected total prominently. Deltas with ▲/▼.