Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(costs): model-aware savings pricing + surface MCP savings + hero results card (#419)

Raghav Chamadiya029e4746cd61
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index ea445db7e..2a8bdba6b 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [Unreleased]
+
+### Added
+- **Costs page savings hero.** The Costs page now leads with a results card
+ showing every token and dollar repowise saved your coding agent, combining
+ the `repowise distill` ledger with MCP tool-response savings that were
+ already on disk but previously invisible (`source='mcp:*'` in the omission
+ store). The dollar estimate is **priced at the agent's actual model** —
+ detected from your local Claude Code / Codex transcripts (read-only,
+ on-machine), falling back to a default rate when undetectable — because saved
+ tokens are input the agent never had to read. Missed savings now read as an
+ "unlock more" prompt rather than a footnote.
+
+---
+
## [0.17.1] — 2026-06-07
### Added
diff --git a/docs/DISTILL.md b/docs/DISTILL.md
index e91b996b8..63ad91c8e 100644
--- a/docs/DISTILL.md
+++ b/docs/DISTILL.md
@@ -260,9 +260,22 @@ an empty report, never an error.
> machine; nothing is uploaded, recorded, or sent anywhere. Codex transcripts
> are not yet scanned.
-The local dashboard mirrors this: the Costs page's *Cache & savings* tab shows
-a Distill savings card with the same rollup, plus a missed-savings secondary
-stat sourced from the same local scan.
+The local dashboard goes further. The Costs page leads with a **savings hero
+card** that combines two surfaces into one honest number:
+
+- **Distill** — the `repowise distill` command/hook ledger above.
+- **MCP tool savings** — tokens trimmed from oversized MCP tool responses,
+ read straight from the omission store (`source='mcp:*'`). These were always
+ saved but never showed up in the ledger before.
+
+The dollar figure is **priced at the coding agent's actual model**, not a flat
+guess: saved tokens are *input* the agent never read, so they are worth that
+agent's input rate. The dashboard detects the model from your local agent
+transcripts — the most-recent model that touched the repo across Claude Code
+(`~/.claude/projects/…`) and Codex (`~/.codex/sessions/…`) — and falls back to
+a sensible default when nothing is detectable. Detection is read-only and stays
+on this machine. The missed-savings scan rides along as an "unlock more"
+prompt.
---
diff --git a/packages/core/src/repowise/core/distill/session_model.py b/packages/core/src/repowise/core/distill/session_model.py
new file mode 100644
index 000000000..539cfdb2b
--- /dev/null
+++ b/packages/core/src/repowise/core/distill/session_model.py
@@ -0,0 +1,265 @@
+"""Detect the coding agent's model, for pricing savings at the real rate.
+
+Saved tokens are *input* tokens the coding agent never had to read, so the
+dollar value of a saving should be priced at that agent's actual input rate —
+not a flat guess. This module scans the local agent transcripts to find the
+most-recent model that touched a repo:
+
+ - **Claude Code** — ``~/.claude/projects/<munged-cwd>/*.jsonl``; the model is
+ each assistant entry's ``message.model`` (e.g. ``claude-opus-4-8``).
+ - **Codex** — ``~/.codex/sessions/**/*.jsonl``; the model appears on a turn
+ context / session record (``model`` field, sometimes nested under
+ ``payload``). The exact shape varies across Codex versions, so the parser
+ is deliberately tolerant and checks several plausible locations.
+
+The newest transcript (by file mtime) across both agents wins. Everything is
+best-effort and read-only: an unreadable file, an absent directory, or a shape
+we don't recognize degrades to the Sonnet default, never an error — this runs
+inside a dashboard endpoint that must not break because a transcript changed.
+
+Privacy: transcripts are read from the user's own machine and never leave it
+(same posture as :mod:`repowise.core.distill.missed`).
+
+Layering note: this lives in ``core`` (the server costs endpoint, which cannot
+import ``cli``, is the primary caller), so the Codex/Claude transcript shapes
+live here rather than in the ``cli`` agent adapters — ``core`` must not depend
+on ``cli``.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+
+#: Pricing fallback when no agent transcript is detectable.
+DEFAULT_MODEL = "claude-sonnet-4-6"
+
+#: Explicit raw→pricing-key aliases. Empty today; the bracket-suffix strip in
+#: :func:`normalize_model_id` covers the known cases (``claude-opus-4-8[1m]``).
+#: Add entries here when a transcript reports a name the pricing table spells
+#: differently — keeping the pricing table the single source of truth.
+_ALIASES: dict[str, str] = {}
+
+#: Trailing bracketed qualifier such as the context-window tag ``[1m]``.
+_BRACKET_SUFFIX = re.compile(r"\s*\[[^\]]*\]\s*$")
+
+
+@dataclass(frozen=True)
+class ResolvedModel:
+ """The agent model to price savings at, plus how it was determined."""
+
+ #: Pricing-table key, e.g. ``"claude-opus-4-8"``.
+ model: str
+ #: As seen in the transcript, e.g. ``"claude-opus-4-8[1m]"``.
+ raw: str
+ #: ``"claude_code"`` | ``"codex"`` | ``"unknown"``.
+ agent: str
+ #: Human label, e.g. ``"detected from Claude Code session"``.
+ source: str
+
+
+_DEFAULT = ResolvedModel(DEFAULT_MODEL, DEFAULT_MODEL, "unknown", "default")
+
+
+@dataclass(frozen=True)
+class _Sighting:
+ """One agent's most-recent model and the transcript mtime it came from."""
+
+ model: str
+ ts: float
+
+
+def normalize_model_id(raw: str) -> str:
+ """Normalize a transcript model id to a pricing-table key.
+
+ Strips a trailing bracketed qualifier (the ``[1m]`` context-window tag) and
+ applies the explicit alias map. Conservative on purpose — it does *not*
+ strip date suffixes, since some real keys carry one
+ (``claude-3-5-sonnet-20241022``).
+ """
+ cleaned = _BRACKET_SUFFIX.sub("", (raw or "").strip())
+ return _ALIASES.get(cleaned, cleaned)
+
+
+def resolve_session_model(
+ repo_root: Path,
+ *,
+ projects_root: Path | None = None,
+ codex_sessions_root: Path | None = None,
+) -> ResolvedModel:
+ """Most-recent agent model that touched *repo_root*, for savings pricing.
+
+ *projects_root* / *codex_sessions_root* override the Claude Code and Codex
+ transcript roots (for tests); both default to their real ``~/`` locations.
+ Returns the Sonnet :data:`_DEFAULT` when nothing is detectable.
+ """
+ try:
+ return _resolve(Path(repo_root), projects_root, codex_sessions_root)
+ except Exception:
+ return _DEFAULT
+
+
+def _resolve(
+ repo_root: Path, projects_root: Path | None, codex_sessions_root: Path | None
+) -> ResolvedModel:
+ candidates: list[tuple[str, str, _Sighting]] = []
+ claude = _claude_code_sighting(repo_root, projects_root)
+ if claude is not None:
+ candidates.append(("claude_code", "Claude Code", claude))
+ codex = _codex_sighting(repo_root, codex_sessions_root)
+ if codex is not None:
+ candidates.append(("codex", "Codex", codex))
+ if not candidates:
+ return _DEFAULT
+ agent, label, sighting = max(candidates, key=lambda c: c[2].ts)
+ return ResolvedModel(
+ model=normalize_model_id(sighting.model),
+ raw=sighting.model,
+ agent=agent,
+ source=f"detected from {label} session",
+ )
+
+
+# -- Claude Code ----------------------------------------------------------
+
+
+def _claude_code_sighting(repo_root: Path, projects_root: Path | None) -> _Sighting | None:
+ """Newest Claude Code transcript for *repo_root* that names a model."""
+ from repowise.core.distill.missed import transcript_dir_for
+
+ directory = transcript_dir_for(repo_root, projects_root)
+ if not directory.is_dir():
+ return None
+ for path in _by_mtime_desc(directory.glob("*.jsonl")):
+ model = _last_claude_model(path)
+ if model:
+ try:
+ return _Sighting(model, path.stat().st_mtime)
+ except OSError:
+ continue
+ return None
+
+
+def _last_claude_model(path: Path) -> str | None:
+ """The last assistant ``message.model`` in a Claude Code transcript."""
+ model: str | None = None
+ try:
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ if '"model"' not in raw or '"assistant"' not in raw:
+ continue
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ continue
+ if not isinstance(entry, dict) or entry.get("type") != "assistant":
+ continue
+ value = (entry.get("message") or {}).get("model")
+ if isinstance(value, str) and value:
+ model = value
+ except OSError:
+ return None
+ return model
+
+
+# -- Codex ----------------------------------------------------------------
+
+
+def _codex_sighting(repo_root: Path, sessions_root: Path | None) -> _Sighting | None:
+ """Newest Codex session under *repo_root* that names a model.
+
+ Sessions whose recorded cwd lies outside *repo_root* are skipped; a session
+ with no recoverable cwd is kept (best-effort — better a model than nothing).
+ """
+ root = sessions_root if sessions_root is not None else Path.home() / ".codex" / "sessions"
+ if not root.is_dir():
+ return None
+ repo_prefix = str(repo_root).lower().rstrip("\\/")
+ best: _Sighting | None = None
+ for path in _by_mtime_desc(root.rglob("*.jsonl")):
+ try:
+ mtime = path.stat().st_mtime
+ except OSError:
+ continue
+ if best is not None and mtime <= best.ts:
+ break # files are mtime-desc; nothing later can beat the current best
+ found = _codex_model_and_cwd(path)
+ if found is None:
+ continue
+ model, cwd = found
+ if cwd and not cwd.lower().rstrip("\\/").startswith(repo_prefix):
+ continue
+ best = _Sighting(model, mtime)
+ return best
+
+
+def _codex_model_and_cwd(path: Path) -> tuple[str, str | None] | None:
+ """Last model id and a session cwd from a Codex rollout file, if any."""
+ model: str | None = None
+ cwd: str | None = None
+ try:
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ if '"model"' not in raw and '"cwd"' not in raw:
+ continue
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ continue
+ if not isinstance(entry, dict):
+ continue
+ found_model, found_cwd = _extract_codex_fields(entry)
+ if found_model:
+ model = found_model
+ if found_cwd:
+ cwd = found_cwd
+ except OSError:
+ return None
+ if model is None:
+ return None
+ return model, cwd
+
+
+def _extract_codex_fields(entry: dict) -> tuple[str | None, str | None]:
+ """Pull a model id and cwd from a Codex record across known shapes.
+
+ Codex versions have placed the model at the top level, under ``payload``,
+ and nested in a ``turn_context``/``info`` object; cwd similarly. We check
+ each plausible spot and take whatever is present.
+ """
+ payload = entry.get("payload") if isinstance(entry.get("payload"), dict) else {}
+ turn = payload.get("turn_context") if isinstance(payload.get("turn_context"), dict) else {}
+ info = entry.get("info") if isinstance(entry.get("info"), dict) else {}
+
+ model = _first_str(
+ entry.get("model"), payload.get("model"), turn.get("model"), info.get("model")
+ )
+ cwd = _first_str(
+ entry.get("cwd"), payload.get("cwd"), turn.get("cwd"), info.get("cwd")
+ )
+ return model, cwd
+
+
+def _first_str(*values: object) -> str | None:
+ """First non-empty string among *values*, else None."""
+ for value in values:
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+# -- shared ---------------------------------------------------------------
+
+
+def _by_mtime_desc(paths) -> list[Path]:
+ """*paths* sorted newest-first by mtime; unreadable files sort last."""
+
+ def _mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return float("-inf")
+
+ return sorted(paths, key=_mtime, reverse=True)
diff --git a/packages/core/src/repowise/core/distill/surfaces.py b/packages/core/src/repowise/core/distill/surfaces.py
new file mode 100644
index 000000000..1b9af09c7
--- /dev/null
+++ b/packages/core/src/repowise/core/distill/surfaces.py
@@ -0,0 +1,28 @@
+"""Surface taxonomy for savings sources.
+
+Every savings/omission row carries a ``source`` string. Distill writes
+``cli`` / ``hook-bash`` / ``hook-powershell`` / ``hook-codex``; the MCP server
+writes ``mcp:<tool>``. Callers that split totals into a *distill* block and an
+*mcp* block route the source through these two helpers so the prefix convention
+lives in exactly one place.
+"""
+
+from __future__ import annotations
+
+#: Prefix every MCP-originated source carries (``mcp:get_risk`` etc.).
+MCP_PREFIX = "mcp:"
+
+
+def is_mcp(source: str) -> bool:
+ """True when *source* came from an MCP tool (``mcp:<tool>``)."""
+ return source.startswith(MCP_PREFIX)
+
+
+def surface_of(source: str) -> str:
+ """Coarse surface for *source* — ``"mcp"`` or ``"distill"``.
+
+ Everything that is not an ``mcp:`` source is distill (CLI command or any
+ of the rewrite-hook shells), so the hero card can group the ledger into
+ two honest buckets.
+ """
+ return "mcp" if is_mcp(source) else "distill"
diff --git a/packages/core/src/repowise/core/distill/tracking.py b/packages/core/src/repowise/core/distill/tracking.py
index cad8e040d..3a5d809ca 100644
--- a/packages/core/src/repowise/core/distill/tracking.py
+++ b/packages/core/src/repowise/core/distill/tracking.py
@@ -69,6 +69,47 @@ def savings_summary(
}
+def mcp_drops_summary(
+ conn: sqlite3.Connection, *, since: float | None = None
+) -> dict[str, Any]:
+ """Truncation savings the MCP server already wrote to the omissions store.
+
+ MCP tools drop content past their response budget into the ``omissions``
+ table under ``source='mcp:<tool>'`` but never call
+ :func:`record_saving`, so these savings are invisible to
+ :func:`savings_summary`. This reads them straight from ``omissions``:
+ total dropped tokens plus a per-tool rollup (with the ``mcp:`` prefix
+ stripped). It is the *truncation-only* view — Phase 2 additionally records
+ counterfactual ``mcp:*`` rows into the ``savings`` ledger.
+
+ *since* is a Unix timestamp lower bound on ``created_at``.
+ """
+ where = "source LIKE 'mcp:%'"
+ params: tuple[float, ...] = ()
+ if since is not None:
+ where += " AND created_at >= ?"
+ params = (since,)
+ events, tokens = conn.execute(
+ f"SELECT COUNT(*), COALESCE(SUM(original_tokens), 0) FROM omissions WHERE {where}",
+ params,
+ ).fetchone()
+ per_tool = {
+ _strip_mcp_prefix(row[0]): {"events": row[1], "tokens": row[2]}
+ for row in conn.execute(
+ "SELECT source, COUNT(*), COALESCE(SUM(original_tokens), 0)"
+ f" FROM omissions WHERE {where} GROUP BY source ORDER BY SUM(original_tokens) DESC",
+ params,
+ )
+ }
+ return {"events": events, "tokens": tokens, "per_tool": per_tool}
+
+
+def _strip_mcp_prefix(source: str) -> str:
+ """``mcp:get_risk`` → ``get_risk`` (passthrough for anything else)."""
+ prefix = "mcp:"
+ return source[len(prefix):] if source.startswith(prefix) else source
+
+
#: Grouping dimensions accepted by :func:`savings_rollup`. ``day`` buckets by
#: the event's local calendar date; ``filter``/``source`` group on the raw
#: ledger columns.
diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.py
index ebf357d9e..d02c08c3d 100644
--- a/packages/core/src/repowise/core/generation/cost_tracker.py
+++ b/packages/core/src/repowise/core/generation/cost_tracker.py
@@ -18,12 +18,21 @@ log = structlog.get_logger(__name__)
# ---------------------------------------------------------------------------
_PRICING: dict[str, dict[str, float]] = {
- # Anthropic
+ # Anthropic — Opus tier $15/$75, Sonnet $3/$15, Haiku $0.8/$4 per 1M.
+ # 4-7/4-8 added for savings pricing: these are the models the session
+ # detector surfaces from current Claude Code transcripts.
+ "claude-opus-4-8": {"input": 15.0, "output": 75.0},
+ "claude-opus-4-7": {"input": 15.0, "output": 75.0},
"claude-opus-4-6": {"input": 15.0, "output": 75.0},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0},
"claude-haiku-4-5": {"input": 0.8, "output": 4.0},
"claude-3-5-sonnet-20241022": {"input": 3.0, "output": 15.0},
- # OpenAI
+ # OpenAI — GPT-5 family (the models Codex sessions report). Rates per 1M
+ # input/output; verify against current OpenAI pricing before relying on
+ # the dollar figure for billing.
+ "gpt-5": {"input": 1.25, "output": 10.0},
+ "gpt-5-codex": {"input": 1.25, "output": 10.0},
+ "gpt-5-mini": {"input": 0.25, "output": 2.0},
"gpt-4o": {"input": 2.5, "output": 10.0},
"gpt-4o-mini": {"input": 0.15, "output": 0.6},
# Google Gemini
diff --git a/packages/server/src/repowise/server/routers/costs.py b/packages/server/src/repowise/server/routers/costs.py
index 7516b58cf..b1b2e949a 100644
--- a/packages/server/src/repowise/server/routers/costs.py
+++ b/packages/server/src/repowise/server/routers/costs.py
@@ -18,6 +18,7 @@ from repowise.server.schemas import (
CostSummaryResponse,
DistillSavingsGroup,
DistillSavingsResponse,
+ McpDropGroup,
)
router = APIRouter(
@@ -118,22 +119,17 @@ async def list_costs(
]
-#: Pricing model for the savings dollar estimate — saved tokens are
-#: input-side tokens the coding agent never had to read.
-_SAVINGS_PRICING_MODEL = "claude-sonnet-4-6"
-
-
@router.get("/{repo_id}/distill-savings", response_model=DistillSavingsResponse)
async def get_distill_savings(
repo_id: str,
since: str | None = Query(None, description="ISO date filter, e.g. 2025-01-01"),
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> DistillSavingsResponse:
- """Savings-ledger rollup from the repo's omission store sidecar.
+ """Savings rollup from the repo's omission store sidecar.
- Covers the ``repowise distill`` command/hook path only; MCP response
- truncation is not recorded in the ledger. Returns ``available=False``
- when the repo has no omission store on disk.
+ Combines the ``repowise distill`` ledger with the MCP truncation drops
+ already on disk (``source='mcp:*'``), priced at the coding agent's detected
+ model. Returns ``available=False`` when the repo has no omission store.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
@@ -149,6 +145,7 @@ async def get_distill_savings(
since_ts = since_dt.timestamp() if since_dt is not None else None
from repowise.core.distill import tracking
+ from repowise.core.distill.session_model import resolve_session_model
from repowise.core.generation.cost_tracker import get_model_pricing
# Read-only stdlib sqlite3 on the sidecar: tiny aggregate queries, and a
@@ -161,6 +158,7 @@ async def get_distill_savings(
summary = tracking.savings_summary(conn, since=since_ts)
per_filter = tracking.savings_rollup(conn, by="filter", since=since_ts)
per_day = tracking.savings_rollup(conn, by="day", since=since_ts)
+ mcp = tracking.mcp_drops_summary(conn, since=since_ts)
except sqlite3.Error:
return DistillSavingsResponse(available=False)
finally:
@@ -172,17 +170,29 @@ async def get_distill_savings(
missed = scan_missed_savings(Path(repo.local_path))
- rate = get_model_pricing(_SAVINGS_PRICING_MODEL)["input"]
+ # Price at the coding agent's actual model — saved tokens are input tokens
+ # that agent never had to read. Detection is best-effort (sonnet default).
+ resolved = resolve_session_model(Path(repo.local_path))
+ rate = get_model_pricing(resolved.model)["input"]
+ total_saved = summary["saved_tokens"] + mcp["tokens"]
return DistillSavingsResponse(
available=True,
events=summary["events"],
raw_tokens=summary["raw_tokens"],
distilled_tokens=summary["distilled_tokens"],
saved_tokens=summary["saved_tokens"],
- estimated_usd_saved=summary["saved_tokens"] * rate / 1_000_000,
- pricing_model=_SAVINGS_PRICING_MODEL,
+ estimated_usd_saved=total_saved * rate / 1_000_000,
+ pricing_model=resolved.model,
+ pricing_agent=resolved.agent,
+ pricing_source=resolved.source,
per_filter=[DistillSavingsGroup(**row) for row in per_filter],
per_day=[DistillSavingsGroup(**row) for row in per_day],
+ mcp_events=mcp["events"],
+ mcp_tokens=mcp["tokens"],
+ mcp_per_tool=[
+ McpDropGroup(tool=tool, events=stats["events"], tokens=stats["tokens"])
+ for tool, stats in mcp["per_tool"].items()
+ ],
missed_events=missed["events"],
missed_tokens_est=missed["est_saved_tokens"],
missed_window_days=missed["window_days"],
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index b9430e6f4..0a30d4085 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -141,6 +141,7 @@ from .ui_helpers import (
CostSummaryResponse,
DistillSavingsGroup,
DistillSavingsResponse,
+ McpDropGroup,
SetActiveProviderRequest,
SetApiKeyRequest,
WebhookResponse,
@@ -216,6 +217,7 @@ __all__ = [
"DirectRiskEntry",
"DistillSavingsGroup",
"DistillSavingsResponse",
+ "McpDropGroup",
"EgoGraphResponse",
"ExecutionFlowEntry",
"ExecutionFlowsResponse",
diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.py
index 676c38d57..db4aee696 100644
--- a/packages/server/src/repowise/server/schemas/ui_helpers.py
+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py
@@ -43,12 +43,24 @@ class DistillSavingsGroup(BaseModel):
saved_tokens: int
-class DistillSavingsResponse(BaseModel):
- """Savings ledger rollup for the Costs page card.
+class McpDropGroup(BaseModel):
+ """Per-tool MCP truncation drops (``tool`` with the ``mcp:`` prefix stripped)."""
+
+ tool: str
+ events: int
+ tokens: int
- Covers the ``repowise distill`` command/hook path only — MCP response
- truncation is not recorded in the ledger. ``available`` is False when
- the repo has no omission store on disk (feature unused).
+
+class DistillSavingsResponse(BaseModel):
+ """Savings rollup for the Costs page hero card.
+
+ The ``distill`` block (``saved_tokens`` etc.) covers the ``repowise
+ distill`` command/hook path. The ``mcp`` block surfaces tokens already
+ dropped past MCP response budgets (the ``omissions`` store), which the
+ distill ledger never recorded. Savings are priced at the *coding agent's*
+ detected model (``pricing_model`` / ``pricing_agent`` / ``pricing_source``)
+ — they are input tokens that agent never had to read. ``available`` is
+ False when the repo has no omission store on disk (feature unused).
"""
available: bool
@@ -58,8 +70,16 @@ class DistillSavingsResponse(BaseModel):
saved_tokens: int = 0
estimated_usd_saved: float = 0.0
pricing_model: str = ""
+ # How the pricing model was resolved (Phase 1 model-aware pricing).
+ pricing_agent: str = "unknown"
+ pricing_source: str = "default"
per_filter: list[DistillSavingsGroup] = []
per_day: list[DistillSavingsGroup] = []
+ # MCP truncation drops already on disk (omissions store, source='mcp:*'),
+ # never recorded in the distill ledger.
+ mcp_events: int = 0
+ mcp_tokens: int = 0
+ mcp_per_tool: list[McpDropGroup] = []
# Missed savings — raw (non-distilled) agent commands a filter would have
# caught, scanned best-effort from local Claude Code transcripts.
missed_events: int = 0
diff --git a/packages/ui/__tests__/costs/distill-savings-card.test.tsx b/packages/ui/__tests__/costs/distill-savings-card.test.tsx
new file mode 100644
index 000000000..3ea4dcbf4
--- /dev/null
+++ b/packages/ui/__tests__/costs/distill-savings-card.test.tsx
@@ -0,0 +1,77 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import {
+ DistillSavingsCard,
+ type DistillSavingsData,
+} from "../../src/costs/distill-savings-card";
+
+function makeData(overrides: Partial<DistillSavingsData> = {}): DistillSavingsData {
+ return {
+ available: true,
+ events: 12,
+ raw_tokens: 70_000,
+ distilled_tokens: 5_000,
+ saved_tokens: 65_000,
+ estimated_usd_saved: 1.5,
+ pricing_model: "claude-opus-4-8",
+ pricing_agent: "claude_code",
+ pricing_source: "detected from Claude Code session",
+ per_filter: [
+ { group: "git_log", events: 1, raw_tokens: 31_000, distilled_tokens: 500, saved_tokens: 30_500 },
+ ],
+ per_day: [],
+ mcp_events: 5,
+ mcp_tokens: 39_000,
+ mcp_per_tool: [
+ { tool: "get_risk", events: 3, tokens: 29_000 },
+ { tool: "get_dead_code", events: 1, tokens: 7_000 },
+ ],
+ missed_events: 0,
+ missed_tokens_est: 0,
+ missed_window_days: 7,
+ ...overrides,
+ };
+}
+
+describe("DistillSavingsCard", () => {
+ it("shows the hero total as distill + mcp saved tokens", () => {
+ render(<DistillSavingsCard data={makeData()} />);
+ // 65K + 39K = 104K → formatTokens → "104K"
+ expect(screen.getByText("104K")).toBeInTheDocument();
+ expect(screen.getByText(/priced at Claude Code/)).toBeInTheDocument();
+ });
+
+ it("breaks savings down by surface", () => {
+ render(<DistillSavingsCard data={makeData()} />);
+ expect(screen.getByText("Distill — by filter")).toBeInTheDocument();
+ expect(screen.getByText("MCP — by tool")).toBeInTheDocument();
+ expect(screen.getByText("get_risk")).toBeInTheDocument();
+ });
+
+ it("renders the missed-as-opportunity CTA with a docs link", () => {
+ render(
+ <DistillSavingsCard
+ data={makeData({ missed_events: 193, missed_tokens_est: 74_000 })}
+ />,
+ );
+ expect(screen.getByText(/Unlock ~74K more/)).toBeInTheDocument();
+ const link = screen.getByRole("link");
+ expect(link).toHaveAttribute("href", expect.stringContaining("DISTILL.md"));
+ });
+
+ it("shows the empty state when nothing is saved", () => {
+ render(<DistillSavingsCard data={makeData({ available: false, saved_tokens: 0, mcp_tokens: 0 })} />);
+ expect(screen.getByText(/No agent token savings recorded yet/)).toBeInTheDocument();
+ });
+
+ it("renders MCP-only savings even with no distill events", () => {
+ render(
+ <DistillSavingsCard
+ data={makeData({ events: 0, saved_tokens: 0, per_filter: [] })}
+ />,
+ );
+ // 0 + 39K = 39K total (hero) — also appears as the MCP sub-stat, so match
+ // at least one occurrence rather than asserting uniqueness.
+ expect(screen.getAllByText("39K").length).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsx
index 38b590a1f..93193d07b 100644
--- a/packages/ui/src/costs/distill-savings-card.tsx
+++ b/packages/ui/src/costs/distill-savings-card.tsx
@@ -1,7 +1,7 @@
"use client";
-import { Scissors } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { Scissors, Sparkles, Zap } from "lucide-react";
+import { Card, CardContent } from "../ui/card";
import { formatCost, formatTokens } from "../lib/format";
export interface DistillSavingsGroup {
@@ -12,6 +12,12 @@ export interface DistillSavingsGroup {
saved_tokens: number;
}
+export interface McpDropGroup {
+ tool: string;
+ events: number;
+ tokens: number;
+}
+
export interface DistillSavingsData {
available: boolean;
events: number;
@@ -20,8 +26,13 @@ export interface DistillSavingsData {
saved_tokens: number;
estimated_usd_saved: number;
pricing_model: string;
+ pricing_agent?: string;
+ pricing_source?: string;
per_filter: DistillSavingsGroup[];
per_day: DistillSavingsGroup[];
+ mcp_events?: number;
+ mcp_tokens?: number;
+ mcp_per_tool?: McpDropGroup[];
/** Raw (non-distilled) agent commands a filter would have caught. */
missed_events?: number;
missed_tokens_est?: number;
@@ -33,100 +44,234 @@ export interface DistillSavingsCardProps {
data?: DistillSavingsData;
}
+const DISTILL_DOCS = "https://github.com/repowise-dev/repowise/blob/main/docs/DISTILL.md";
+
+/** Humanize the resolved pricing agent for the "priced at" caption. */
+function agentLabel(agent: string | undefined): string {
+ if (agent === "claude_code") return "Claude Code";
+ if (agent === "codex") return "Codex";
+ return "";
+}
+
/**
- * Tokens saved by `repowise distill` (command + hook path). MCP response
- * truncation is not part of this ledger, and the card says so — the number
- * shown is real avoided agent input, not budget-capped responses.
+ * Hero results card for the Costs page: every token & dollar repowise saved the
+ * coding agent, across the `repowise distill` ledger (CLI + hook) and the MCP
+ * tools whose oversized responses were trimmed. Priced at the agent's *real*
+ * model — saved tokens are input the agent never had to read.
*/
export function DistillSavingsCard({ data }: DistillSavingsCardProps) {
- const hasData = data?.available && data.events > 0;
- const pct =
- hasData && data.raw_tokens > 0
- ? Math.round((data.saved_tokens / data.raw_tokens) * 100)
- : 0;
- const topFilters = hasData ? data.per_filter.slice(0, 3) : [];
- const missed = data?.available && (data.missed_events ?? 0) > 0;
+ const distillSaved = data?.saved_tokens ?? 0;
+ const mcpSaved = data?.mcp_tokens ?? 0;
+ const total = distillSaved + mcpSaved;
+ const hasData = !!data?.available && total > 0;
+
+ if (!data) {
+ return (
+ <Card>
+ <CardContent className="py-10">
+ <div className="h-24 w-full animate-pulse rounded-lg bg-[var(--color-bg-inset)]" />
+ </CardContent>
+ </Card>
+ );
+ }
+
+ if (!hasData) {
+ return (
+ <Card>
+ <CardContent className="py-8">
+ <div className="flex items-center gap-3">
+ <Scissors className="h-5 w-5 shrink-0 text-cyan-500" />
+ <div>
+ <p className="text-sm font-medium text-[var(--color-text-primary)]">
+ No agent token savings recorded yet
+ </p>
+ <p className="mt-1 text-xs text-[var(--color-text-secondary)] max-w-[420px]">
+ Route noisy commands through <code>repowise distill &lt;cmd&gt;</code> or install the
+ rewrite hook (<code>repowise hook rewrite install</code>) to start trimming agent
+ context — savings show up here automatically.
+ </p>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ const distillPct = total > 0 ? Math.round((distillSaved / total) * 100) : 0;
+ const mcpPct = 100 - distillPct;
+ const topFilters = data.per_filter.slice(0, 3);
+ const topTools = (data.mcp_per_tool ?? []).slice(0, 3);
+ const priced = agentLabel(data.pricing_agent) || data.pricing_model;
+ const detected = data.pricing_source && data.pricing_source !== "default";
+ const missed = (data.missed_tokens_est ?? 0) > 0;
return (
<Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm flex items-center gap-2">
- <Scissors className="h-4 w-4 text-cyan-500" />
- Distill savings
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- {hasData ? (
- <div className="space-y-3">
- <div className="flex items-baseline gap-2">
- <span className="text-2xl font-semibold text-[var(--color-text-primary)] tabular-nums">
- {formatTokens(data.saved_tokens)}
+ <CardContent className="py-6">
+ {/* Headline */}
+ <div className="flex flex-wrap items-end justify-between gap-4">
+ <div>
+ <div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <Sparkles className="h-3.5 w-3.5 text-cyan-500" />
+ Tokens saved for your agent
+ </div>
+ <div className="mt-1 flex items-baseline gap-3">
+ <span className="text-4xl font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {formatTokens(total)}
</span>
- <span className="text-xs text-[var(--color-text-secondary)]">
- tokens saved ({pct}%) ·{" "}
- <span className="font-medium text-green-500">
- {formatCost(data.estimated_usd_saved)}
- </span>{" "}
- est.
+ <span className="text-2xl font-semibold tabular-nums text-green-500">
+ {formatCost(data.estimated_usd_saved)}
</span>
</div>
- <div className="space-y-1">
- {topFilters.map((f) => {
- const width =
- data.saved_tokens > 0
- ? Math.max(4, Math.round((f.saved_tokens / data.saved_tokens) * 100))
- : 0;
- return (
- <div key={f.group} className="flex items-center gap-2 text-xs">
- <span className="w-24 shrink-0 truncate text-[var(--color-text-secondary)]">
- {f.group}
- </span>
- <div className="flex-1 h-1.5 rounded bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded bg-[var(--color-accent-primary)]"
- style={{ width: `${width}%` }}
- />
- </div>
- <span className="w-14 shrink-0 text-right tabular-nums text-[var(--color-text-primary)]">
- {formatTokens(f.saved_tokens)}
- </span>
- </div>
- );
- })}
- </div>
- {missed && (
- <div className="flex items-baseline gap-2 border-t border-[var(--color-border-secondary)] pt-2">
- <span className="text-sm font-medium text-amber-500 tabular-nums">
- ~{formatTokens(data.missed_tokens_est ?? 0)}
- </span>
- <span className="text-xs text-[var(--color-text-secondary)]">
- missed — {(data.missed_events ?? 0).toLocaleString()} raw command
- {(data.missed_events ?? 0) === 1 ? "" : "s"} bypassed distill in the last{" "}
- {data.missed_window_days ?? 7} days
- </span>
- </div>
- )}
- <p className="text-[10px] text-[var(--color-text-tertiary)] leading-snug">
- {data.events.toLocaleString()} distillation{data.events === 1 ? "" : "s"} via the{" "}
- <code>repowise distill</code> command/hook path. MCP response truncation is not
- counted. Estimate at {data.pricing_model} input rate.
- {missed && (
- <>
+ <p className="mt-1 text-xs text-[var(--color-text-secondary)]">
+ priced at {priced}
+ {detected ? (
+ <span className="text-[var(--color-text-tertiary)]"> · {data.pricing_source}</span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">
{" "}
- Missed savings are scanned from local agent transcripts (nothing leaves this
- machine) — see <code>repowise saved --missed</code>.
- </>
+ · no agent session detected, default rate
+ </span>
)}
</p>
</div>
- ) : (
- <p className="text-xs text-[var(--color-text-tertiary)] leading-snug max-w-[300px]">
- No distillation savings recorded yet. Run noisy commands through{" "}
- <code>repowise distill &lt;cmd&gt;</code> or install the rewrite hook (
- <code>repowise hook rewrite install</code>) to start trimming agent context.
- </p>
+ <div className="flex gap-6 text-right">
+ <div>
+ <div className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {formatTokens(distillSaved)}
+ </div>
+ <div className="text-[11px] text-[var(--color-text-tertiary)]">
+ distill · {data.events.toLocaleString()} event{data.events === 1 ? "" : "s"}
+ </div>
+ </div>
+ <div>
+ <div className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {formatTokens(mcpSaved)}
+ </div>
+ <div className="text-[11px] text-[var(--color-text-tertiary)]">
+ MCP · {(data.mcp_events ?? 0).toLocaleString()} drop
+ {(data.mcp_events ?? 0) === 1 ? "" : "s"}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Two-segment breakdown bar */}
+ <div className="mt-4 flex h-2.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ {distillSaved > 0 && (
+ <div
+ className="h-full bg-cyan-500"
+ style={{ width: `${distillPct}%` }}
+ title={`Distill — ${formatTokens(distillSaved)} (${distillPct}%)`}
+ />
+ )}
+ {mcpSaved > 0 && (
+ <div
+ className="h-full bg-violet-500"
+ style={{ width: `${mcpPct}%` }}
+ title={`MCP tools — ${formatTokens(mcpSaved)} (${mcpPct}%)`}
+ />
+ )}
+ </div>
+ <div className="mt-1.5 flex items-center gap-4 text-[11px] text-[var(--color-text-secondary)]">
+ <span className="flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full bg-cyan-500" /> Distill {distillPct}%
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full bg-violet-500" /> MCP tools {mcpPct}%
+ </span>
+ </div>
+
+ {/* Per-surface detail */}
+ <div className="mt-4 grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">
+ {topFilters.length > 0 && (
+ <SurfaceDetail
+ title="Distill — by filter"
+ rows={topFilters.map((f) => ({
+ label: f.group,
+ tokens: f.saved_tokens,
+ }))}
+ max={distillSaved}
+ barClass="bg-cyan-500"
+ />
+ )}
+ {topTools.length > 0 && (
+ <SurfaceDetail
+ title="MCP — by tool"
+ rows={topTools.map((t) => ({ label: t.tool, tokens: t.tokens }))}
+ max={mcpSaved}
+ barClass="bg-violet-500"
+ />
+ )}
+ </div>
+
+ {/* Missed → opportunity CTA */}
+ {missed && (
+ <a
+ href={DISTILL_DOCS}
+ target="_blank"
+ rel="noreferrer"
+ className="mt-5 flex items-center gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2.5 transition-colors hover:bg-amber-500/10"
+ >
+ <Zap className="h-4 w-4 shrink-0 text-amber-500" />
+ <div className="text-xs text-[var(--color-text-secondary)]">
+ <span className="font-medium text-amber-500">
+ Unlock ~{formatTokens(data.missed_tokens_est ?? 0)} more
+ </span>{" "}
+ — {(data.missed_events ?? 0).toLocaleString()} raw command
+ {(data.missed_events ?? 0) === 1 ? "" : "s"} bypassed distill in the last{" "}
+ {data.missed_window_days ?? 7} days. Enable auto-capture →
+ </div>
+ </a>
)}
+
+ <p className="mt-3 text-[10px] leading-snug text-[var(--color-text-tertiary)]">
+ Distill counts <code>repowise distill</code> command/hook savings; MCP counts tokens
+ trimmed from oversized tool responses already on disk. Saved tokens are agent input,
+ priced at the agent&apos;s input rate. Transcript scans stay on this machine.
+ </p>
</CardContent>
</Card>
);
}
+
+interface SurfaceDetailRow {
+ label: string;
+ tokens: number;
+}
+
+function SurfaceDetail({
+ title,
+ rows,
+ max,
+ barClass,
+}: {
+ title: string;
+ rows: SurfaceDetailRow[];
+ max: number;
+ barClass: string;
+}) {
+ return (
+ <div className="space-y-1.5">
+ <div className="text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {title}
+ </div>
+ {rows.map((row) => {
+ const width = max > 0 ? Math.max(4, Math.round((row.tokens / max) * 100)) : 0;
+ return (
+ <div key={row.label} className="flex items-center gap-2 text-xs">
+ <span className="w-28 shrink-0 truncate text-[var(--color-text-secondary)]">
+ {row.label}
+ </span>
+ <div className="h-1.5 flex-1 overflow-hidden rounded bg-[var(--color-bg-inset)]">
+ <div className={`h-full rounded ${barClass}`} style={{ width: `${width}%` }} />
+ </div>
+ <span className="w-14 shrink-0 text-right tabular-nums text-[var(--color-text-primary)]">
+ {formatTokens(row.tokens)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/ui/src/costs/index.ts b/packages/ui/src/costs/index.ts
index 7a4974ef3..5cc9f8915 100644
--- a/packages/ui/src/costs/index.ts
+++ b/packages/ui/src/costs/index.ts
@@ -11,4 +11,5 @@ export type {
DistillSavingsCardProps,
DistillSavingsData,
DistillSavingsGroup,
+ McpDropGroup,
} from "./distill-savings-card";
diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsx
index 3f7b1fa17..5d5dafb53 100644
--- a/packages/web/src/app/repos/[id]/costs/page.tsx
+++ b/packages/web/src/app/repos/[id]/costs/page.tsx
@@ -74,6 +74,10 @@ export default function CostsPage() {
</p>
</div>
+ {/* Hero: the honest results surface — all tokens & dollars saved for the
+ coding agent, across distill (CLI + hook) and MCP tool responses. */}
+ <DistillSavingsCard data={distillSavings} />
+
{loadingSummary ? (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{Array.from({ length: 4 }).map((_, i) => (
@@ -109,7 +113,7 @@ export default function CostsPage() {
<Tabs value={tab} onValueChange={setTab} className="w-full">
<TabsList>
<TabsTrigger value="daily">Daily</TabsTrigger>
- <TabsTrigger value="cache">Cache & savings</TabsTrigger>
+ <TabsTrigger value="cache">Cache</TabsTrigger>
<TabsTrigger value="hotspots">Hotspots</TabsTrigger>
<TabsTrigger value="providers">Providers</TabsTrigger>
<TabsTrigger value="operations">Operations</TabsTrigger>
@@ -173,7 +177,6 @@ export default function CostsPage() {
<TabsContent value="cache" className="mt-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
- <DistillSavingsCard data={distillSavings} />
<CacheHitRatioCard />
<Card>
<CardHeader className="pb-2">
diff --git a/packages/web/src/lib/api/costs.ts b/packages/web/src/lib/api/costs.ts
index c2399b58c..5365e0d4d 100644
--- a/packages/web/src/lib/api/costs.ts
+++ b/packages/web/src/lib/api/costs.ts
@@ -28,6 +28,12 @@ export interface DistillSavingsGroup {
saved_tokens: number;
}
+export interface McpDropGroup {
+ tool: string;
+ events: number;
+ tokens: number;
+}
+
export interface DistillSavings {
available: boolean;
events: number;
@@ -36,8 +42,15 @@ export interface DistillSavings {
saved_tokens: number;
estimated_usd_saved: number;
pricing_model: string;
+ /** How the pricing model was resolved (Phase 1 model-aware pricing). */
+ pricing_agent: string;
+ pricing_source: string;
per_filter: DistillSavingsGroup[];
per_day: DistillSavingsGroup[];
+ /** MCP truncation drops already on disk (omissions store, source mcp:*). */
+ mcp_events: number;
+ mcp_tokens: number;
+ mcp_per_tool: McpDropGroup[];
/** Raw (non-distilled) agent commands a filter would have caught. */
missed_events: number;
missed_tokens_est: number;
diff --git a/tests/unit/distill/test_session_model.py b/tests/unit/distill/test_session_model.py
new file mode 100644
index 000000000..c946f940e
--- /dev/null
+++ b/tests/unit/distill/test_session_model.py
@@ -0,0 +1,107 @@
+"""Session-model detection for savings pricing.
+
+Builds fixture transcript trees in the Claude Code and Codex shapes and asserts
+the resolver picks the newest model across agents, normalizes the ``[1m]``
+context-window tag, and falls back to the Sonnet default when nothing matches.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from repowise.core.distill.missed import transcript_dir_for
+from repowise.core.distill.session_model import (
+ DEFAULT_MODEL,
+ normalize_model_id,
+ resolve_session_model,
+)
+
+
+def _write_claude(projects_root: Path, repo_root: Path, model: str, *, mtime: float) -> Path:
+ """Write a one-line Claude Code transcript naming *model* for *repo_root*."""
+ directory = transcript_dir_for(repo_root, projects_root)
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / f"{model}.jsonl".replace("[", "_").replace("]", "_")
+ line = {"type": "assistant", "message": {"role": "assistant", "model": model}}
+ path.write_text(json.dumps(line) + "\n", encoding="utf-8")
+ os.utime(path, (mtime, mtime))
+ return path
+
+
+def _write_codex(sessions_root: Path, repo_root: Path, model: str, *, mtime: float) -> Path:
+ """Write a Codex rollout file naming *model* with cwd under *repo_root*."""
+ day = sessions_root / "2026" / "06" / "08"
+ day.mkdir(parents=True, exist_ok=True)
+ path = day / f"rollout-{model}.jsonl"
+ lines = [
+ {"type": "session_meta", "payload": {"cwd": str(repo_root)}},
+ {"type": "turn_context", "payload": {"model": model, "cwd": str(repo_root)}},
+ ]
+ path.write_text("\n".join(json.dumps(line) for line in lines) + "\n", encoding="utf-8")
+ os.utime(path, (mtime, mtime))
+ return path
+
+
+def test_normalize_strips_context_window_tag() -> None:
+ assert normalize_model_id("claude-opus-4-8[1m]") == "claude-opus-4-8"
+ assert normalize_model_id(" claude-opus-4-8 ") == "claude-opus-4-8"
+ # A legit date-suffixed key must survive untouched.
+ assert normalize_model_id("claude-3-5-sonnet-20241022") == "claude-3-5-sonnet-20241022"
+
+
+def test_no_transcripts_falls_back_to_sonnet(tmp_path: Path) -> None:
+ resolved = resolve_session_model(
+ tmp_path / "repo",
+ projects_root=tmp_path / "projects",
+ codex_sessions_root=tmp_path / "codex",
+ )
+ assert resolved.model == DEFAULT_MODEL
+ assert resolved.agent == "unknown"
+ assert resolved.source == "default"
+
+
+def test_newest_claude_model_wins_and_normalizes(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ projects = tmp_path / "projects"
+ _write_claude(projects, repo, "claude-sonnet-4-6", mtime=1000.0)
+ _write_claude(projects, repo, "claude-opus-4-8[1m]", mtime=2000.0)
+
+ resolved = resolve_session_model(
+ repo, projects_root=projects, codex_sessions_root=tmp_path / "codex"
+ )
+ assert resolved.model == "claude-opus-4-8"
+ assert resolved.raw == "claude-opus-4-8[1m]"
+ assert resolved.agent == "claude_code"
+ assert "Claude Code" in resolved.source
+
+
+def test_most_recent_agent_wins_across_agents(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ projects = tmp_path / "projects"
+ codex = tmp_path / "codex"
+ _write_claude(projects, repo, "claude-opus-4-8", mtime=1000.0)
+ _write_codex(codex, repo, "gpt-5-codex", mtime=3000.0) # newer
+
+ resolved = resolve_session_model(
+ repo, projects_root=projects, codex_sessions_root=codex
+ )
+ assert resolved.model == "gpt-5-codex"
+ assert resolved.agent == "codex"
+ assert "Codex" in resolved.source
+
+
+def test_codex_session_outside_repo_is_ignored(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ other = tmp_path / "elsewhere"
+ projects = tmp_path / "projects"
+ codex = tmp_path / "codex"
+ _write_claude(projects, repo, "claude-opus-4-8", mtime=1000.0)
+ _write_codex(codex, other, "gpt-5-codex", mtime=3000.0) # newer but wrong repo
+
+ resolved = resolve_session_model(
+ repo, projects_root=projects, codex_sessions_root=codex
+ )
+ assert resolved.model == "claude-opus-4-8"
+ assert resolved.agent == "claude_code"
diff --git a/tests/unit/distill/test_store.py b/tests/unit/distill/test_store.py
index f594d2ca2..831796f33 100644
--- a/tests/unit/distill/test_store.py
+++ b/tests/unit/distill/test_store.py
@@ -117,6 +117,33 @@ def test_savings_ledger_roundtrip(store: OmissionStore) -> None:
assert summary["per_filter"]["test_output"]["saved_tokens"] == 900
+def test_mcp_drops_summary_reads_omissions(store: OmissionStore) -> None:
+ from repowise.core.distill.tracking import mcp_drops_summary
+
+ # MCP truncation drops land in the omissions table (kept_tokens=0), never
+ # in the savings ledger.
+ store.put("a" * 400, source="mcp:get_risk", original_tokens=300, kept_tokens=0)
+ store.put("b" * 400, source="mcp:get_risk", original_tokens=200, kept_tokens=0)
+ store.put("c" * 400, source="mcp:get_overview", original_tokens=100, kept_tokens=0)
+ # Distill omissions must not leak into the MCP view.
+ store.put("d" * 400, source="cli:test_output", original_tokens=999, kept_tokens=50)
+
+ summary = mcp_drops_summary(store._conn)
+ assert summary["events"] == 3
+ assert summary["tokens"] == 600
+ assert summary["per_tool"]["get_risk"] == {"events": 2, "tokens": 500}
+ assert summary["per_tool"]["get_overview"] == {"events": 1, "tokens": 100}
+ # Ordered by tokens desc — biggest tool first.
+ assert list(summary["per_tool"]) == ["get_risk", "get_overview"]
+
+
+def test_mcp_drops_summary_empty(store: OmissionStore) -> None:
+ from repowise.core.distill.tracking import mcp_drops_summary
+
+ summary = mcp_drops_summary(store._conn)
+ assert summary == {"events": 0, "tokens": 0, "per_tool": {}}
+
+
def test_default_store_path_finds_repowise_dir(tmp_path: Path) -> None:
repo = tmp_path / "repo"
nested = repo / "src" / "deep"
diff --git a/tests/unit/distill/test_surfaces.py b/tests/unit/distill/test_surfaces.py
new file mode 100644
index 000000000..81ee3bb3a
--- /dev/null
+++ b/tests/unit/distill/test_surfaces.py
@@ -0,0 +1,29 @@
+"""Surface taxonomy helpers."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.distill.surfaces import is_mcp, surface_of
+
+
+ "source, mcp",
+ [
+ ("mcp:get_risk", True),
+ ("mcp:get_context", True),
+ ("cli", False),
+ ("hook-bash", False),
+ ("hook-powershell", False),
+ ("hook-codex", False),
+ ("", False),
+ ],
+)
+def test_is_mcp(source: str, mcp: bool) -> None:
+ assert is_mcp(source) is mcp
+
+
+def test_surface_of() -> None:
+ assert surface_of("mcp:get_dead_code") == "mcp"
+ assert surface_of("cli") == "distill"
+ assert surface_of("hook-bash") == "distill"
diff --git a/tests/unit/server/test_distill_savings.py b/tests/unit/server/test_distill_savings.py
index 80430e3f4..4d40c2066 100644
--- a/tests/unit/server/test_distill_savings.py
+++ b/tests/unit/server/test_distill_savings.py
@@ -48,6 +48,34 @@ async def test_savings_endpoint_returns_rollups(client: AsyncClient, tmp_path: P
assert len(data["per_day"]) == 1 # both events landed today
+async def test_savings_endpoint_surfaces_mcp_drops_and_pricing(
+ client: AsyncClient, tmp_path: Path
+) -> None:
+ """MCP truncation drops (omissions store) ride on the response, and the
+ dollar estimate covers distill + MCP priced at the resolved agent model."""
+ repo = await create_test_repo(client, tmp_path)
+ repo_dir = Path(repo["local_path"])
+ _seed_store(repo_dir) # 10_800 distill saved tokens
+ store = OmissionStore(repo_dir / ".repowise" / "omissions" / "omissions.db")
+ store.put("x" * 400, source="mcp:get_risk", original_tokens=5_000, kept_tokens=0)
+ store.put("y" * 400, source="mcp:get_overview", original_tokens=1_000, kept_tokens=0)
+ store.close()
+
+ resp = await client.get(f"/api/repos/{repo['id']}/distill-savings")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["mcp_events"] == 2
+ assert data["mcp_tokens"] == 6_000
+ tools = {row["tool"]: row for row in data["mcp_per_tool"]}
+ assert tools["get_risk"]["tokens"] == 5_000
+ # Distill saved_tokens stays distill-only; the dollar figure is the union
+ # of distill (10_800) + MCP (6_000) priced at the resolved agent model.
+ assert data["saved_tokens"] == 10_800
+ assert data["pricing_agent"] == "unknown" # no transcripts in a tmp repo
+ assert data["pricing_source"] == "default"
+ assert data["estimated_usd_saved"] > 0
+
+
async def test_savings_endpoint_no_store_is_unavailable(
client: AsyncClient, tmp_path: Path
) -> None: