From 792d1ab119e8dfe458682eaf09c93752df3ff0cc Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:56:22 +0100 Subject: [PATCH] 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. --- src/act/report.ts | 105 +++++++++++++++++++++++++++------------ src/optimize.ts | 48 +++++++++++++++++- tests/act-report.test.ts | 101 +++++++++++++++++++++++++++++++++++-- 3 files changed, 215 insertions(+), 39 deletions(-) diff --git a/src/act/report.ts b/src/act/report.ts index ed921f83..263b57d9 100644 --- a/src/act/report.ts +++ b/src/act/report.ts @@ -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, + mcpClaimedServers: ReadonlySet, 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, opts: ActReportOptions, modelDefaultProjectFound = true, + mcpClaimedServers: ReadonlySet, pricing: FindingPricing, opts: ActReportOptions, modelDefaultProjectFound = true, ): Promise { 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 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 r.status === 'measured' && isTokenKind(r.kind)) @@ -607,7 +645,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise 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 = {} - 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 = 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 diff --git a/src/optimize.ts b/src/optimize.ts index 2255a2c8..dd6daf75 100644 --- a/src/optimize.ts +++ b/src/optimize.ts @@ -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 { + 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 { + 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> = { + // 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 { diff --git a/tests/act-report.test.ts b/tests/act-report.test.ts index 8b81be3f..6ce1255c 100644 --- a/tests/act-report.test.ts +++ b/tests/act-report.test.ts @@ -16,8 +16,9 @@ import { import { formatAppliedFix, REPORT_MIN_AGE_DAYS } from '../src/act/types.js' import type { ActionRecord } from '../src/act/types.js' import type { FindingPlan } from '../src/act/plans.js' -import type { WasteFinding } from '../src/optimize.js' +import { aggregateMcpCoverage, detectMcpProfileAdvisor, detectMcpToolCoverage, type WasteFinding } from '../src/optimize.js' import type { ClassifiedTurn, ProjectSummary } from '../src/types.js' +import { getModelCosts } from '../src/models.js' type Session = ProjectSummary['sessions'][number] @@ -133,6 +134,17 @@ function modelEditTurns(model: string, editTurns: number, oneShotTurns: number): })) } +// One call that writes the prompt cache, one that reads it. +function cachedTurns(): ClassifiedTurn[] { + return modelEditTurns('claude-opus-4-6', 2, 2).map((turn, i) => ({ + ...turn, + assistantCalls: turn.assistantCalls.map(call => ({ + ...call, + usage: { ...call.usage, cacheCreationInputTokens: i === 0 ? 50_000 : 0, cacheReadInputTokens: i === 0 ? 0 : 50_000 }, + })), + })) +} + function modelProject( project: string, projectPath: string, model: string, editTurns: number, oneShotTurns: number, ): ProjectSummary { @@ -214,6 +226,43 @@ describe('mcp realized delta', () => { }) }) +describe('realized dollars', () => { + const onModel = (model: string) => sessionsAt(20, daysAgo(5)).map(s => ({ ...s, turns: modelEditTurns(model, 1, 1) })) + const OPUS = 'claude-opus-4-6' + + it('prices realized tokens at the session model rate of the token kind the finding priced', async () => { + const opus = getModelCosts(OPUS) + expect(opus).not.toBeNull() + const projects = load([projectOf(onModel(OPUS))]) + for (const findingId of ['mcp-low-coverage', 'mcp-project-scope', 'unused-mcp']) { + const kind = findingId === 'mcp-project-scope' ? 'mcp-project-scope' : 'mcp-remove' + const actionsDir = await writeJournal([mcpRecord({ kind, findingId })]) + const report = await computeActReport({ actionsDir, now: NOW, loadProjects: projects }) + expect(report.rows[0]!.realizedTokens).toBe(40_000) + expect(report.rows[0]!.estimatedAtApply).toBe(56_000) + expect(report.rows[0]!.realizedCostUSD).toBeCloseTo(40_000 * opus!.inputCostPerToken, 10) + expect(report.rows[0]!.realizedCostUSD).not.toBeCloseTo(40_000 * report.costRate, 6) + const json = buildActReportJson(report) as { totals: { realizedCostUSD: number } } + expect(json.totals.realizedCostUSD).toBeCloseTo(report.rows[0]!.realizedCostUSD, 10) + } + }) + + it('keeps the blended rate for an unpriced model and for findings still on the blended rate', async () => { + const unpriced = await writeJournal([mcpRecord({ findingId: 'mcp-low-coverage' })]) + const report = await computeActReport({ actionsDir: unpriced, now: NOW, loadProjects: load([projectOf(onModel('unpriced-test-model'))]) }) + expect(report.costRate).toBeGreaterThan(0) + expect(report.rows[0]!.realizedTokens).toBe(40_000) + expect(report.rows[0]!.estimatedAtApply).toBe(56_000) + expect(report.rows[0]!.realizedCostUSD).toBeCloseTo(40_000 * report.costRate, 10) + expect(report.totalRealizedCostUSD).toBeCloseTo(40_000 * report.costRate, 10) + + const archived = await writeJournal([mcpRecord({ findingId: 'unused-skills', kind: 'archive-skill' })]) + const onOpus = await computeActReport({ actionsDir: archived, now: NOW, loadProjects: load([projectOf(onModel(OPUS))]) }) + expect(onOpus.rows[0]!.status).toBe('measured') + expect(onOpus.rows[0]!.realizedCostUSD).toBeCloseTo(onOpus.rows[0]!.realizedTokens * onOpus.costRate, 10) + }) +}) + describe('model-default quality tripwire', () => { it('fires for a >5pp same-project regression even when another project would mask it globally', async () => { const actionsDir = await writeJournal([modelDefaultRecord()]) @@ -781,6 +830,7 @@ describe('partial-action baseline capture', () => { } const sessions = sessionsAt(2, daysAgo(1), { mcpInventory: Array.from({ length: 20 }, (_, i) => `mcp__filesystem__t${i}`), + turns: cachedTurns(), }) const baseline = captureBaseline(finding, 'mcp-remove', { @@ -789,7 +839,7 @@ describe('partial-action baseline capture', () => { server: 'filesystem', toolsAvailable: 20, toolsInvoked: 3, - unusedTools: Array.from({ length: 17 }, (_, i) => `mcp__filesystem__unused${i}`), + unusedTools: Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`), invocations: 0, loadedSessions: 2, coverageRatio: 3 / 20, @@ -801,7 +851,7 @@ describe('partial-action baseline capture', () => { expect(baseline).toMatchObject({ estimatedTokens: 20_000, sessions: 2, - metrics: { filesystem: 6_800 }, + metrics: { filesystem: 206.55 }, }) expect(finding.tokensSaved).toBe(40_000) }) @@ -823,6 +873,7 @@ describe('partial-action baseline capture', () => { ...Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`), ...Array.from({ length: 12 }, (_, i) => `mcp__managed__t${i}`), ], + turns: cachedTurns(), }) const coverage = [ { @@ -844,7 +895,7 @@ describe('partial-action baseline capture', () => { expect(baseline).toMatchObject({ estimatedTokens: 10_000, sessions: 2, - metrics: { filesystem: 6_800 }, + metrics: { filesystem: 206.55 }, }) expect(baseline!.metrics).not.toHaveProperty('managed') }) @@ -895,6 +946,7 @@ describe('partial-action baseline capture', () => { ...Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`), ...Array.from({ length: 12 }, (_, i) => `mcp__managed__t${i}`), ], + turns: cachedTurns(), }) await captureBaselinesForPlans([plan], { @@ -904,11 +956,50 @@ describe('partial-action baseline capture', () => { expect(plan.plan?.baseline).toMatchObject({ estimatedTokens: 10_000, - metrics: { filesystem: 6_800 }, + metrics: { filesystem: 206.55 }, }) expect(plan.plan?.baseline?.metrics).not.toHaveProperty('managed') }) + it('stores the per-session schema tokens the mcp-low-coverage finding charges', () => { + const sessions = sessionsAt(4, daysAgo(1), { + mcpInventory: Array.from({ length: 20 }, (_, i) => `mcp__filesystem__t${i}`), + turns: cachedTurns(), + }) + const projects = [projectOf(sessions)] + const coverage = aggregateMcpCoverage(projects) + const finding = detectMcpToolCoverage(projects, coverage, new Set(['filesystem']))! + expect(finding.id).toBe('mcp-low-coverage') + + const baseline = captureBaseline(finding, 'mcp-remove', { projects, coverage, windowDays: 14, now: NOW }) + // 20 deferred name lines at 9 tokens, one write (x1.25) and one read (x0.1) + // per session: 243 per session, where the old 400-per-tool figure was 8,000. + expect(baseline!.metrics.filesystem).toBeCloseTo(243, 10) + expect(baseline!.metrics.filesystem! * sessions.length).toBeCloseTo(finding.tokensSaved, 0) + }) + + it('stores the per-session cold schema tokens the mcp-project-scope finding charges', () => { + const inventory = Array.from({ length: 4 }, (_, i) => `mcp__github__t${i}`) + const cold = (name: string) => projectOf( + sessionsAt(2, daysAgo(1), { mcpInventory: inventory, turns: cachedTurns() }).map(s => ({ ...s, sessionId: `${name}-${s.sessionId}` })), + { project: name, projectPath: `/tmp/${name}` }, + ) + const hot = projectOf( + [makeSession('api-s0', daysAgo(1), { mcpInventory: inventory, mcpBreakdown: { github: { calls: 2 } }, turns: cachedTurns() })], + { project: 'api', projectPath: '/tmp/api' }, + ) + const projects = [hot, cold('web'), cold('docs')] + const coverage = aggregateMcpCoverage(projects) + const finding = detectMcpProfileAdvisor(projects, coverage)! + expect(finding.id).toBe('mcp-project-scope') + + const baseline = captureBaseline(finding, 'mcp-project-scope', { projects, coverage, windowDays: 14, now: NOW }) + // 4 name lines at 9 tokens, one write (x1.25) and one read (x0.1) per + // cold session: 48.6 per session, where the old 400-per-tool figure was 1,600. + expect(baseline!.metrics.github).toBeCloseTo(48.6, 10) + expect(baseline!.metrics.github! * 4).toBeCloseTo(finding.tokensSaved, 0) + }) + it('does not stamp a numeric baseline onto an uncertain partial mutation', async () => { const finding: WasteFinding = { id: 'mcp-low-coverage', title: '1 MCP server', explanation: '', impact: 'medium',