fix(act): price realized savings the way the finding priced them (#1859)

* fix(optimize): price findings from the calls they point at

Every finding's dollar figure was its token estimate times one blended
rate: 70% of the period's spend over all input-side tokens. That rate is
close to a cache-read price, so it misprices anything that is not a cache
read. Schema findings already weight cache reads at 0.1, so their reads
were discounted twice; findings whose tokens include output were priced
as input.

A finding can now carry savingsUSD, computed from the calls it names.
Every surface reads it through findingUSD: the CLI and TUI optimize
views, the JSON report (and so the desktop Optimize page), the menubar
payload and MCP get_savings, and the --apply list. classTotals sums it,
scaled to the apply-able share for fix findings. Findings without it keep
tokensSaved times the blended rate, and any token whose session or model
has no price still falls back to that rate.

Measured now:
- low-worth-sessions: each session's real cost times its recovery fraction
- retry-heavy-capabilities: the retry turns' real cost times the fraction
- redundant-rereads, build-folder-reads: the reads at the input rate of
  their session's most-called model
- warmup-heavy: the excess cache writes at the session model's write rate
- mcp-low-coverage, mcp-project-scope: each call's charged schema tokens
  at that call model's cache-write or cache-read rate
- unused-mcp, mcp-deferral-off, mcp-alwaysload-hygiene,
  mcp-defer-threshold: the per-session schema at the input rate of the
  sessions charged

Still on the blended rate, because no calls can be named: read-edit-ratio
(reads that never happened), context-heavy-sessions, cost-outliers,
low-cache-hit-sessions, claude-md-too-long, bash-output-cap,
recurring-context and the unused agents, skills and commands.

* fix(act): price realized savings at the session's own rates

Findings now carry dollars priced from the calls they point at, but act
report still priced the re-measured tokens of an applied fix with the
blended input rate. That rate sits near a cache-read price, so a fix
advertised in optimize came back as roughly a tenth of that in act report
and in the desktop "Saved by applied fixes" line.

Each measured row now carries realizedCostUSD, priced per post-apply
session at that session's most-called model rate through the same
findingPricing helpers the findings use. MCP removals, project scoping
and deferral price the schema tokens once per session that benefited, at
the cache-write rate. Archived skills, agents and commands price their
definition tokens the same way. CLAUDE.md read rules price the credited
reads at the input rate, split across sessions by their edits. Sessions
whose model has no price keep the blended rate. The total, the JSON
totals.realizedCostUSD and the optimize header sum these row figures.
Token figures are unchanged, and nothing stored in the journal changes.

Worked example: an MCP removal drops 8,000 schema tokens from each of
1,280 post-apply Opus 4.6 sessions, 10.24M tokens. Optimize advertised it
at about $64, the same writes at Opus's $6.25 per million cache-write
rate. Before this change act report priced the 10.24M tokens at a blended
$0.60 per million and showed about $6.14 realized. Now it shows $64.00.

* fix(act): price realized savings the way the finding priced them

The first pass priced every realized schema or definition token at the
cache-write rate and every credited read at the input rate, whatever the
finding had advertised. That left advertised and realized on different
footings: unused-mcp and the deferral findings price schema at the input
rate, and the archive and read-edit-ratio findings still use the blended
rate, so their realized figure could read several times their estimate.

FINDING_TOKEN_KIND in optimize.ts now maps each measured finding to the
token kind it prices: cache-write for mcp-low-coverage and
mcp-project-scope, input for unused-mcp, mcp-deferral-off,
mcp-alwaysload-hygiene, mcp-defer-threshold, redundant-rereads and
build-folder-reads. act report prices a fix's realized tokens at that kind
for each benefiting session, and keeps the blended rate for any finding
not in the table and for unpriced models. A detector that moves to
measured pricing adds one line to the table.

Worked example on 1,280 post-apply Opus 4.6 sessions, 8,000 schema tokens
each, 10.24M tokens, blended rate $0.60 per million:
- mcp-low-coverage removal: advertised about $64 at the $6.25 cache-write
  rate; realized $6.14 on the blended rate before, $64.00 now.
- unused-mcp removal: advertised about $51 at the $5 input rate; realized
  $6.14 before, $64.00 after the first pass, $51.20 now.
- archived skills: advertised and realized both stay on the blended rate,
  $6.14.

* fix(act): store the baseline at the finding's own per-tool token figure

Since the deferred-tool fix, mcp-low-coverage charges each unused tool as
one deferred name line of about 9 tokens, once per call: as a cache read
when the call read cache, as a cache write otherwise, weighted into
effective input tokens. The act baseline for that apply still stored 400
tokens per unused tool once per session, so realized tokens and the
at-apply estimate measured different things and realized ran far above
the estimate.

captureBaseline now stores, per server, the effective schema tokens the
finding's own attribution charges over the baseline window divided by the
sessions that loaded the server. mcpLowCoverageSchemaPerSession runs the
same per-call pass the finding runs, so there is no second constant.
Because the stored figure is now effective input tokens (writes x1.25,
reads x0.1), mcp-low-coverage realized dollars use the input rate, which
for Claude models equals the finding's per-call cache-write and
cache-read prices.

Example: 20 unused deferred tools, one cache write and one cache read per
session. The baseline was 8,000 tokens per session (20 x 400); it is now
243 (180 name-line tokens x1.25 + 180 x0.1), and 243 times the sessions
equals the finding's tokensSaved.

Applies recorded before this change keep their stored 400-per-tool
baseline; there is no migration. Their realized dollars now use the input
rate rather than the cache-write rate. Other MCP baselines
(mcp-project-scope, unused-mcp, deferral) are unchanged.

* fix(act): store the project-scope baseline at the finding's figure too

mcp-project-scope has charged each scoped server's tools as deferred name
lines of about 9 tokens, once per call, in its cold projects only, since
the deferred-tool fix. Its act baseline still stored 400 tokens per
available tool once per session.

captureBaseline now stores, per scoped server, the effective cold-project
schema tokens the finding's own pass charges, divided by the cold-project
sessions that loaded the server. mcpProjectScopeSchemaPerSession runs that
pass over the finding's removeProjects; it is a separate helper because
the pass differs from mcp-low-coverage's (available tools in cold projects
rather than unused tools everywhere). The stored figure is effective
input tokens, so realized dollars use the input rate, as for
mcp-low-coverage.

Example: 4 tools loaded in two cold projects, one cache write and one
cache read per session. The baseline was 1,600 tokens per session
(4 x 400); it is now 48.6 (36 x1.25 + 36 x0.1), and 48.6 times the cold
sessions equals the finding's tokensSaved.

Applies recorded before this change keep their stored 400-per-tool
baseline; there is no migration.
This commit is contained in:
Resham Joshi 2026-11-04 21:56:22 +01:00 • committed by GitHub
parent 26bfc4e4c4
commit 792d1ab119
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 215 additions and 39 deletions

View file

@ -16,6 +16,12 @@ import {
EDIT_TOOL_NAMES,
aggregateMcpCoverage,
computeInputCostRate,
FINDING_TOKEN_KIND,
mcpLowCoverageSchemaPerSession,
mcpProjectScopeSchemaPerSession,
findingPricing,
sessionTokensUSD,
type FindingPricing,
type McpServerCoverage,
type WasteFinding,
} from '../optimize.js'
@ -77,6 +83,8 @@ export type ActReportRow = {
// kinds with no window scaling.
estimatedForWindow: number
realizedTokens: number
// realizedTokens priced the way the fix's finding priced its tokens.
realizedCostUSD: number
status: RealizedStatus
confidence: 'low' | 'normal'
note: string
@ -232,13 +240,24 @@ function confidenceFor(afterSessions: number, baseline: ActionBaseline, afterSta
return 'normal'
}
// Advertised and realized stay comparable: a measured finding's token kind at
// each benefiting session's rate, else the blended rate on the whole figure.
function realizedUSD(
pricing: FindingPricing, rec: ActionRecord, realizedTokens: number,
perSession: Array<[SessionSummary, number]>,
): number {
const kind = rec.findingId ? FINDING_TOKEN_KIND[rec.findingId] : undefined
if (!kind) return realizedTokens * pricing.fallbackRate
return perSession.reduce((sum, [s, tokens]) => sum + sessionTokensUSD(pricing, s.sessionId, tokens, kind), 0)
}
// ---------------------------------------------------------------------------
// Per-kind realized deltas
// ---------------------------------------------------------------------------
function mcpRow(
base: ActReportRow, rec: ActionRecord, sessions: SessionSummary[],
baseline: ActionBaseline, afterStart: Date, now: Date,
baseline: ActionBaseline, afterStart: Date, now: Date, pricing: FindingPricing,
): ActReportRow {
const servers = Object.keys(baseline.metrics)
const perSessionTokens = Object.values(baseline.metrics).reduce((a, b) => a + b, 0)
@ -249,7 +268,8 @@ function mcpRow(
// (and the revert check), so the pair is derived from session counts, not
// independently measured.
const estimatedForWindow = Math.floor(perSessionTokens * sessions.length)
const stillLoading = sessions.filter(s => sessionLoadsAny(s, servers)).length
const saved = sessions.filter(s => !sessionLoadsAny(s, servers))
const stillLoading = sessions.length - saved.length
const confidence = confidenceFor(sessions.length, baseline, afterStart, now)
if (rec.kind === 'mcp-remove' && stillLoading > 0) {
return {
@ -260,14 +280,17 @@ function mcpRow(
note: `reverted by user: ${servers.join(', ')} loaded again in ${stillLoading} post-apply session${stillLoading === 1 ? '' : 's'}`,
}
}
const savedSessions = Math.max(0, sessions.length - stillLoading)
return { ...base, estimatedForWindow, status: 'measured', realizedTokens: Math.floor(perSessionTokens * savedSessions), confidence }
const realizedTokens = Math.floor(perSessionTokens * saved.length)
return {
...base, estimatedForWindow, status: 'measured', confidence, realizedTokens,
realizedCostUSD: realizedUSD(pricing, rec, realizedTokens, saved.map(s => [s, perSessionTokens])),
}
}
function deferRow(
base: ActReportRow, sessions: SessionSummary[],
base: ActReportRow, rec: ActionRecord, sessions: SessionSummary[],
baseline: ActionBaseline, afterStart: Date, now: Date,
mcpClaimedServers: ReadonlySet<string>,
mcpClaimedServers: ReadonlySet<string>, pricing: FindingPricing,
): ActReportRow {
// Sum only the servers no MCP row claims (see mcpClaimedServers in
// computeActReport), so the same schema tokens are never realized twice.
@ -289,9 +312,9 @@ function deferRow(
// begun before the user restarted still run deferral-off — those aren't
// counted, and if none benefited we report it plainly rather than claim a
// saving that hasn't taken effect.
const deferredSessions = sessions.filter(sessionHasDeferralActive).length
const deferred = sessions.filter(sessionHasDeferralActive)
const confidence = confidenceFor(sessions.length, baseline, afterStart, now)
if (deferredSessions === 0) {
if (deferred.length === 0) {
return {
...base,
estimatedForWindow,
@ -300,12 +323,16 @@ function deferRow(
note: `not yet in effect: deferral is still inactive in ${sessions.length} post-apply session${sessions.length === 1 ? '' : 's'} (takes effect on the next session; the client may not have restarted, or the change was reverted)`,
}
}
return { ...base, estimatedForWindow, status: 'measured', realizedTokens: Math.floor(perSessionTokens * deferredSessions), confidence }
const realizedTokens = Math.floor(perSessionTokens * deferred.length)
return {
...base, estimatedForWindow, status: 'measured', confidence, realizedTokens,
realizedCostUSD: realizedUSD(pricing, rec, realizedTokens, deferred.map(s => [s, perSessionTokens])),
}
}
function archiveRow(
base: ActReportRow, rec: ActionRecord, sessions: SessionSummary[],
baseline: ActionBaseline, afterStart: Date, now: Date,
baseline: ActionBaseline, afterStart: Date, now: Date, pricing: FindingPricing,
): ActReportRow {
const perSessionTokens = Object.values(baseline.metrics).reduce((a, b) => a + b, 0)
if (perSessionTokens === 0) return { ...base, note: 'not measurable: empty baseline' }
@ -318,12 +345,16 @@ function archiveRow(
}
// Estimate and realized are the same product by construction; the measured
// signal here is the session count and the revert check, not the multiply.
return { ...base, estimatedForWindow, status: 'measured', realizedTokens: Math.floor(perSessionTokens * sessions.length), confidence }
const realizedTokens = Math.floor(perSessionTokens * sessions.length)
return {
...base, estimatedForWindow, status: 'measured', confidence, realizedTokens,
realizedCostUSD: realizedUSD(pricing, rec, realizedTokens, sessions.map(s => [s, perSessionTokens])),
}
}
function readEditRow(
base: ActReportRow, sessions: SessionSummary[],
baseline: ActionBaseline, afterStart: Date, now: Date,
base: ActReportRow, rec: ActionRecord, sessions: SessionSummary[],
baseline: ActionBaseline, afterStart: Date, now: Date, pricing: FindingPricing,
): ActReportRow {
const editsNow = countToolCalls(sessions, EDIT_TOOL_NAMES)
const readsNow = countToolCalls(sessions, READ_TOOL_NAMES)
@ -337,7 +368,11 @@ function readEditRow(
// by current edits; a worsened ratio claims nothing.
const deficitThen = Math.max(HEALTHY_READ_EDIT_RATIO - ratioThen, 0)
const deficitNow = Math.max(HEALTHY_READ_EDIT_RATIO - ratioNow, 0)
const realized = Math.floor(Math.max(0, deficitThen - deficitNow) * editsNow * AVG_TOKENS_PER_READ)
const readsPerEdit = Math.max(0, deficitThen - deficitNow) * AVG_TOKENS_PER_READ
const realized = Math.floor(readsPerEdit * editsNow)
// Each session's share of the credited reads follows its edits.
const realizedCostUSD = realizedUSD(pricing, rec, realized,
sessions.map(s => [s, readsPerEdit * countToolCalls([s], EDIT_TOOL_NAMES)]))
// Same edits denominator as realized, so realized never exceeds it.
const estimatedForWindow = Math.floor(deficitThen * editsNow * AVG_TOKENS_PER_READ)
return {
@ -345,6 +380,7 @@ function readEditRow(
estimatedForWindow,
status: 'measured',
realizedTokens: realized,
realizedCostUSD,
confidence: confidenceFor(sessions.length, baseline, afterStart, now),
note: `read:edit ${ratioThen.toFixed(1)}:1 -> ${ratioNow.toFixed(1)}:1`,
}
@ -435,7 +471,7 @@ async function modelDefaultRow(
async function computeRow(
rec: ActionRecord, sessions: SessionSummary[], afterStart: Date, now: Date,
mcpClaimedServers: ReadonlySet<string>, opts: ActReportOptions, modelDefaultProjectFound = true,
mcpClaimedServers: ReadonlySet<string>, pricing: FindingPricing, opts: ActReportOptions, modelDefaultProjectFound = true,
): Promise<ActReportRow> {
const estimatedAtApply = rec.baseline?.estimatedTokens ?? 0
const base: ActReportRow = {
@ -447,6 +483,7 @@ async function computeRow(
estimatedAtApply,
estimatedForWindow: estimatedAtApply,
realizedTokens: 0,
realizedCostUSD: 0,
status: 'not-measurable',
confidence: 'normal',
note: '',
@ -454,10 +491,10 @@ async function computeRow(
const baseline = rec.baseline
if (!baseline) return { ...base, note: 'not measurable: no baseline captured at apply time' }
if (MCP_KINDS.has(rec.kind)) return mcpRow(base, rec, sessions, baseline, afterStart, now)
if (DEFER_KINDS.has(rec.kind)) return deferRow(base, sessions, baseline, afterStart, now, mcpClaimedServers)
if (rec.kind in ARCHIVE_DEF_TOKENS) return archiveRow(base, rec, sessions, baseline, afterStart, now)
if (rec.kind === 'claude-md-rule') return readEditRow(base, sessions, baseline, afterStart, now)
if (MCP_KINDS.has(rec.kind)) return mcpRow(base, rec, sessions, baseline, afterStart, now, pricing)
if (DEFER_KINDS.has(rec.kind)) return deferRow(base, rec, sessions, baseline, afterStart, now, mcpClaimedServers, pricing)
if (rec.kind in ARCHIVE_DEF_TOKENS) return archiveRow(base, rec, sessions, baseline, afterStart, now, pricing)
if (rec.kind === 'claude-md-rule') return readEditRow(base, rec, sessions, baseline, afterStart, now, pricing)
if (rec.kind === 'shell-config') return { ...base, note: 'not measurable: bash result token sizes are not retained in the summary' }
if (rec.kind === 'guard-install') return guardRow(base, afterStart, now, baseline, opts)
if (rec.kind === 'model-default') return modelDefaultRow(base, rec, sessions, baseline, afterStart, now, modelDefaultProjectFound)
@ -569,6 +606,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise<Act
const loadProjects = opts.loadProjects ?? ((range: DateRange) => parseAllSessions(range, 'claude'))
const projects = await loadProjects({ start: windowStart, end: now })
const costRate = computeInputCostRate(projects)
const pricing = findingPricing(projects, costRate)
// Servers a same-journal MCP row (mcp-remove / mcp-project-scope) already
// measures. Deferral baselines for defer-enable / defer-threshold span the
@ -591,7 +629,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise<Act
? modelDefaultSessionsInWindow(rec, projects, afterStart, now)
: undefined
const sessions = modelDefaultWindow?.sessions ?? sessionsInWindow(projects, afterStart, now)
rows.push(await computeRow(rec, sessions, afterStart, now, mcpClaimedServers, opts, modelDefaultWindow?.projectFound))
rows.push(await computeRow(rec, sessions, afterStart, now, mcpClaimedServers, pricing, opts, modelDefaultWindow?.projectFound))
}
const measuredRows = rows.filter(r => r.status === 'measured' && isTokenKind(r.kind))
@ -607,7 +645,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise<Act
costRate,
rows,
totalRealizedTokens,
totalRealizedCostUSD: totalRealizedTokens * costRate,
totalRealizedCostUSD: measuredRows.reduce((s, r) => s + r.realizedCostUSD, 0),
measuredCount: measuredRows.length,
activeCount: active.length,
observedDays,
@ -628,7 +666,8 @@ export function buildOptimizeAppliedHeader(report: ActReport): string | null {
report.windowCapDays,
confident.reduce((mx, r) => Math.max(mx, Math.ceil(ageDays(r.appliedAt, generated))), 0),
)
const cost = report.costRate > 0 ? ` (~${formatCost(tokens * report.costRate)})` : ''
const usd = confident.reduce((s, r) => s + r.realizedCostUSD, 0)
const cost = report.costRate > 0 ? ` (~${formatCost(usd)})` : ''
return `Applied fixes: ${report.activeCount} active, realized ~${formatTokens(tokens)} tokens${cost} over ${days} day${days === 1 ? '' : 's'}. Details: codeburn act report`
}
@ -766,17 +805,17 @@ export function captureBaseline(
const servers = mcpServersFromApply(finding, affectedMcpServers)
if (servers.length === 0) return undefined
const covByServer = new Map(ctx.coverage.map(c => [c.server, c]))
const metrics: Record<string, number> = {}
for (const server of servers) {
const cov = covByServer.get(server)
// Removal realizes only the unused schema that the low-coverage
// detector estimated. If coverage is unavailable, omit the numeric
// claim instead of inventing a five-tool baseline.
const tools = finding.id === 'mcp-low-coverage'
? cov?.unusedTools.length ?? 0
: cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER
metrics[server] = tools * TOKENS_PER_MCP_TOOL
}
// Removal and scoping realize only the schema their detector estimated,
// counted the way it counts it. If coverage is unavailable, that is 0
// rather than an invented five-tool baseline.
const metrics: Record<string, number> = finding.id === 'mcp-low-coverage'
? mcpLowCoverageSchemaPerSession(ctx.projects, ctx.coverage, servers)
: finding.apply?.kind === 'mcp-project-scope'
? mcpProjectScopeSchemaPerSession(ctx.projects, ctx.coverage, finding.apply.servers.filter(s => servers.includes(s.server)))
: Object.fromEntries(servers.map(server => {
const cov = covByServer.get(server)
return [server, (cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER) * TOKENS_PER_MCP_TOOL]
}))
const estimatedTokens = finding.applyTokensSavedByServer
? Math.round(servers.reduce((sum, server) => sum + (finding.applyTokensSavedByServer?.[server] ?? 0), 0))
: common.estimatedTokens

View file

@ -1864,6 +1864,20 @@ function estimateMcpSchemaCostAttributed(
}
}
/// The effective schema tokens per loaded session that mcp-low-coverage
/// charges each of `servers`, from the same per-call attribution as the finding.
export function mcpLowCoverageSchemaPerSession(
projects: ProjectSummary[], coverage: McpServerCoverage[], servers: string[],
): Record<string, number> {
const covByServer = new Map(coverage.filter(c => servers.includes(c.server)).map(c => [c.server, c]))
const unused = Object.fromEntries([...covByServer].map(([server, c]) => [server, c.unusedTools]))
const cost = estimateMcpSchemaCostAttributed(unused, projects, servers)
return Object.fromEntries(servers.map(server => {
const loaded = covByServer.get(server)?.loadedSessions ?? 0
return [server, loaded > 0 ? (cost.byServer[server]?.effectiveInputTokens ?? 0) / loaded : 0]
}))
}
/// Cached schema tokens at the call model's own cache rate; unpriced models
/// keep the effective-input weighting at the blended rate.
function schemaChargeUSD(pricing: FindingPricing, model: string, tokens: number, kind: 'cacheWrite' | 'cacheRead'): number {
@ -2118,6 +2132,23 @@ function estimateMcpProfileColdSchemaCost(
return { cacheWriteTokens, cacheReadTokens, effectiveInputTokens, usd }
}
/// The effective cold-project schema tokens per cold loaded session that
/// mcp-project-scope charges each scoped server, from the finding's own pass.
export function mcpProjectScopeSchemaPerSession(
projects: ProjectSummary[], coverage: McpServerCoverage[],
scoped: Array<{ server: string; removeProjects: string[] }>,
): Record<string, number> {
const tools = new Map(coverage.map(c => [c.server, c.toolsAvailable]))
return Object.fromEntries(scoped.map(({ server, removeProjects }) => {
const cold = new Set(removeProjects)
const cost = estimateMcpProfileColdSchemaCost(projects, new Map([[server, tools.get(server) ?? 0]]), new Map([[server, cold]]))
const sessions = projects
.filter(p => cold.has(projectProfileKey(p)))
.reduce((n, p) => n + p.sessions.filter(s => sessionLoadedMcpServer(s, server)).length, 0)
return [server, sessions > 0 ? cost.effectiveInputTokens / sessions : 0]
}))
}
function collectMcpProjectProfiles(
projects: ProjectSummary[],
coverage: McpServerCoverage[],
@ -4262,11 +4293,26 @@ function modelRate(pricing: FindingPricing, model: string | undefined, kind: Tok
}
/// `tokens` of one session at its own model's rate, else at the blended rate.
function sessionTokensUSD(pricing: FindingPricing, sessionId: string | undefined, tokens: number, kind: TokenKind): number {
export function sessionTokensUSD(pricing: FindingPricing, sessionId: string | undefined, tokens: number, kind: TokenKind): number {
const model = sessionId === undefined ? undefined : pricing.sessionModels.get(sessionId)
return tokens * (modelRate(pricing, model, kind) ?? pricing.fallbackRate)
}
/// The token kind a measured finding prices its tokens at, so `act report`
/// prices that fix's realized tokens the same way. Absent: the blended rate.
export const FINDING_TOKEN_KIND: Readonly<Record<string, 'input' | 'cacheWrite'>> = {
// Their act baselines store effective tokens (writes x1.25, reads x0.1),
// which the input rate prices as the finding's per-call cache rates.
'mcp-low-coverage': 'input',
'mcp-project-scope': 'input',
'unused-mcp': 'input',
'mcp-deferral-off': 'input',
'mcp-alwaysload-hygiene': 'input',
'mcp-defer-threshold': 'input',
'redundant-rereads': 'input',
'build-folder-reads': 'input',
}
/// Schema tokens charged once per session, priced at the input rate of each
/// session in `sessions`: the token count times their mean rate.
function perSessionSchemaUSD(pricing: FindingPricing, sessions: SessionSummary[], tokens: number): number {