Merge remote-tracking branch 'upstream/main' into fix/968-subscription-flat-rate

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Aditya Vikram Singh 2026-08-21 20:09:46 +05:30
commit ac96089fd5
23 changed files with 742 additions and 160 deletions

View file

@ -19,7 +19,11 @@ import type { ParsedProviderCall } from './providers/types.js'
// resumeState): they are additive and absence-safe in both directions, so a
// bump would only throw away a warm multi-hundred-MB cache to gain nothing. An
// entry without them simply re-parses in full once and gains them.
const CODEX_CACHE_VERSION = 8
// v9: parse large session_meta records structurally so nested provenance.model
// cannot overwrite the model selected by turn_context.
// v10: same depth-1 window for the rest of session_meta's raw string fields
// (cwd/name/originator/session_id/forked_from_id/model_provider).
const CODEX_CACHE_VERSION = 10
const CACHE_FILE = 'codex-results.json'
export type CodexFileFingerprint = { dev: number; ino: number; mtimeMs: number; sizeBytes: number }

View file

@ -114,6 +114,11 @@ async function getExchangeRate(code: string): Promise<number> {
const cached = await loadCachedRate(code)
if (cached) return cached
// Test-only escape hatch, set for the whole suite in
// tests/setup/env-isolation.ts: skip the live Frankfurter fetch so a real FX
// move can't shift assertions. Same fallback an unreachable network gets.
if (process.env['CODEBURN_FX_NO_FETCH']) return 1
let rate: number
try {
rate = await fetchRate(code)

View file

@ -6,6 +6,24 @@ import { join } from 'path'
import { getCodeburnCacheDir } from './cache-dir.js'
import type { DateRange, ProjectSummary } from './types.js'
// Bumped to 20: the Codex fast-path read a nested
// `base_instructions.provenance.model` out of `session_meta` as if it were
// `payload.model` (#1040), so every call a rollout attributed from session
// metadata - the ones before its first `turn_context`, and every one after a
// mid-file `session_meta` - was credited to the wrong model. The codex parse
// version and CODEX_CACHE_VERSION move with it, but the daily cache has no
// per-provider invalidation, so days already finalized keep the wrong model
// rows forever unless MIN_SUPPORTED_VERSION moves too. This pass re-derives
// ALL days for EVERY provider off the warm session cache, so it costs seconds
// rather than a full re-parse, and it is lossless: adoptOlderDailyCaches keeps
// the superseded v19 file as the baseline, and the partial-survival guard from
// #1033 holds any day whose sources have only partly aged out. On a real
// 110-day cache the 19 -> 20 pass moved ZERO days down and lost none: 100 days
// came back byte-identical and 9 grok days rose by $19.80 in total, clearing
// rollups the grok parse change had left stale, while every codex model row
// stayed identical (that corpus predates the `provenance` field, so the fix it
// carries has nothing to correct there).
//
// Bumped to 19: Grok authoritative usage now keeps one session-level rollup
// from top-level totals, clamps reasoning to reported output, and labels mixed
// authoritative/heuristic coverage. Every day finalized under the previous
@ -92,8 +110,8 @@ import type { DateRange, ProjectSummary } from './types.js'
// that older binaries skipped. v8 added local-model savings to the daily
// rollup; the `savingsConfigHash` field is invalidated separately when the
// user changes their `localModelSavings` mapping.
export const DAILY_CACHE_VERSION = 19
const MIN_SUPPORTED_VERSION = 19
export const DAILY_CACHE_VERSION = 20
const MIN_SUPPORTED_VERSION = 20
// Version-suffixed so different binaries each own a distinct file and never
// clobber an incompatible schema. Bumping the version mints a fresh filename;
// adoptOlderDailyCaches then unions days out of every previous file (including

View file

@ -225,21 +225,30 @@ function mergeSnapshotFallbacks(pricing: Map<string, ModelCosts>): Map<string, M
return applyBuiltinPriceOverrides(pricing)
}
function setPricingCache(pricing: Map<string, ModelCosts>): void {
pricingCache = pricing
sortedPricingKeys = null
lowercasePricingIndex = null
knownNamespaces = null
}
export async function loadPricing(): Promise<void> {
const cached = await loadCachedPricing()
if (cached) {
pricingCache = mergeSnapshotFallbacks(cached)
sortedPricingKeys = null
lowercasePricingIndex = null
knownNamespaces = null
setPricingCache(mergeSnapshotFallbacks(cached))
return
}
// Test-only escape hatch, set for the whole suite in
// tests/setup/env-isolation.ts: skip the live LiteLLM fetch and price purely
// off the bundled snapshot, so an upstream reprice can't turn tests red.
if (process.env['CODEBURN_PRICING_SNAPSHOT_ONLY']) {
setPricingCache(mergeSnapshotFallbacks(new Map()))
return
}
try {
pricingCache = mergeSnapshotFallbacks(await fetchAndCachePricing())
sortedPricingKeys = null
lowercasePricingIndex = null
knownNamespaces = null
setPricingCache(mergeSnapshotFallbacks(await fetchAndCachePricing()))
} catch {
// snapshot already loaded at init; nothing more to do
}

View file

@ -8,7 +8,7 @@ import { homedir } from 'os'
import { isReadShapedBashCommand } from './bash-utils.js'
import { readSessionLines, readSessionFileSync } from './fs-utils.js'
import { discoverAllSessions } from './providers/index.js'
import { discoverAllSessions, providerDisplayName } from './providers/index.js'
import { parseJsonlLine, shouldSkipLine } from './parser.js'
import type { DateRange, ProjectSummary, SessionSummary } from './types.js'
import { formatCost } from './currency.js'
@ -249,6 +249,88 @@ export type PasteDestination =
| 'shell-config' // append to ~/.zshrc / ~/.bashrc
| 'manual' // instructions the user carries out directly
/// Provider-scoped remediation nouns. Cross-provider detectors and both
/// render surfaces (CLI + TUI) share this so `--provider codex` cannot still
/// tell the user to ask Claude or edit CLAUDE.md. Claude / unset / `all`
/// keep the shipped CLAUDE.md copy. Only `codex` has a file CodeBurn already
/// names (`AGENTS.md` in the Codex parser); every other provider stays on
/// the generic "project instructions" rather than inventing a filename.
export type OptimizeRemediationCopy = {
agent: string
instructionFile: string
}
const REMEDIATION_INSTRUCTION_FILES: Record<string, string> = {
claude: 'CLAUDE.md',
codex: 'AGENTS.md',
}
export function isDefaultClaudeProvider(provider?: string): boolean {
return !provider || provider === 'all' || provider === 'claude'
}
export function optimizeRemediationCopy(provider?: string): OptimizeRemediationCopy {
const key = !provider || provider === 'all' ? 'claude' : provider.toLowerCase()
return {
agent: providerDisplayName(key),
instructionFile: REMEDIATION_INSTRUCTION_FILES[key] ?? 'project instructions',
}
}
export function sessionOpenerLabel(copy: OptimizeRemediationCopy): string {
return `Paste at the start of your NEXT expensive thread (one-time, do not add to ${copy.instructionFile}):`
}
export function askAgentLabel(copy: OptimizeRemediationCopy, rest: string): string {
return `Ask ${copy.agent} to ${rest}:`
}
export function optimizePasteHeader(destination: PasteDestination | undefined, copy: OptimizeRemediationCopy): string {
switch (destination) {
case 'claude-md': return `Suggested ${copy.instructionFile} addition (permanent rule)`
case 'session-opener': return `One-time session opener (do NOT add to ${copy.instructionFile})`
case 'prompt': return `Ask ${copy.agent} in the current session`
case 'shell-config': return 'Add to your shell config'
case 'manual': return 'Manual action'
default: return 'Suggested action'
}
}
/// Exact pre-#1049 TUI strings for unset/`all`/`claude`. Non-Claude providers
/// reuse the CLI header table so the two surfaces cannot drift on new copy.
export function optimizeTuiPasteHeader(destination: PasteDestination | undefined, provider?: string): string {
if (isDefaultClaudeProvider(provider)) {
switch (destination) {
case 'claude-md': return '── Suggested CLAUDE.md addition (permanent rule) '.padEnd(64, '─')
case 'session-opener': return '── One-time session opener (do not add to CLAUDE.md) '.padEnd(64, '─')
case 'prompt': return '── Ask Claude in the current session '.padEnd(64, '─')
case 'shell-config': return '── Add to your shell config '.padEnd(64, '─')
case 'manual': return '── Manual action '.padEnd(64, '─')
default: return '── Suggested action '.padEnd(64, '─')
}
}
return `── ${optimizePasteHeader(destination, optimizeRemediationCopy(provider))} `.padEnd(64, '─')
}
export function optimizeEmptyScanLines(provider?: string): [string, string, string] {
if (isDefaultClaudeProvider(provider)) {
return [
'CodeBurn optimize scans your Claude Code sessions and config for',
'token waste: junk directory reads, duplicate file reads, unused',
'agents/skills/MCP servers, bloated CLAUDE.md, and more.',
]
}
const copy = optimizeRemediationCopy(provider)
// scanSessions is Claude-only. Naming the provider's instruction file here
// would claim a scan that did not run (Health A / 100 under --provider
// codex with every listed detector claudeOnly-disabled).
return [
`Session-scan detectors do not cover ${copy.agent} yet.`,
'junk directory reads, duplicate file reads, unused agents/skills/MCP,',
'and bloated instruction files currently scan Claude Code only.',
]
}
export type WasteAction =
| { type: 'paste'; label: string; text: string; destination?: PasteDestination }
| { type: 'command'; label: string; text: string }
@ -1695,6 +1777,7 @@ function collectMcpProjectProfiles(
export function detectMcpProfileAdvisor(
projects: ProjectSummary[],
coverage = aggregateMcpCoverage(projects),
provider?: string,
): WasteFinding | null {
const candidates = collectMcpProjectProfiles(projects, coverage)
if (candidates.length === 0) return null
@ -1733,7 +1816,7 @@ export function detectMcpProfileAdvisor(
fix: {
type: 'paste',
destination: 'prompt',
label: 'Ask Claude to turn this into a project-scoped MCP profile:',
label: askAgentLabel(optimizeRemediationCopy(provider), 'turn this into a project-scoped MCP profile'),
text: [
`Review these MCP profile recommendations before changing config (${preview.length} of ${candidates.length} shown):`,
...preview.map(candidate => {
@ -1926,7 +2009,7 @@ function findCapabilityReliabilityCandidates(projects: ProjectSummary[]): Capabi
return candidates
}
export function detectCapabilityReliability(projects: ProjectSummary[]): WasteFinding | null {
export function detectCapabilityReliability(projects: ProjectSummary[], provider?: string): WasteFinding | null {
projects = userStartedProjects(projects)
const candidates = findCapabilityReliabilityCandidates(projects)
if (candidates.length === 0) return null
@ -1989,7 +2072,7 @@ export function detectCapabilityReliability(projects: ProjectSummary[]): WasteFi
fix: {
type: 'paste',
destination: 'prompt',
label: 'Ask Claude to audit the retry-heavy capability before changing config:',
label: askAgentLabel(optimizeRemediationCopy(provider), 'audit the retry-heavy capability before changing config'),
text: `Investigate these retry-correlated capabilities: ${names}. Compare edit turns with retries against one-shot edit turns, identify whether the MCP server or skill actually caused rework, then propose a scoped MCP config or skill-instruction change with session evidence. Do not remove a capability solely because it appears in this report.`,
},
}
@ -3121,7 +3204,7 @@ export function findLowWorthCandidates(projects: ProjectSummary[]): LowWorthCand
return candidates
}
export function detectLowWorthSessions(projects: ProjectSummary[]): WasteFinding | null {
export function detectLowWorthSessions(projects: ProjectSummary[], provider?: string): WasteFinding | null {
const candidates = findLowWorthCandidates(projects)
if (candidates.length === 0) return null
@ -3156,7 +3239,7 @@ export function detectLowWorthSessions(projects: ProjectSummary[]): WasteFinding
fix: {
type: 'paste',
destination: 'session-opener',
label: 'Paste at the start of your NEXT expensive thread (one-time, do not add to CLAUDE.md):',
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
text: LOW_WORTH_OPENER,
},
}
@ -3231,7 +3314,7 @@ export function findContextBloatCandidates(projects: ProjectSummary[]): ContextB
return candidates
}
export function detectContextBloat(projects: ProjectSummary[], excludedSessionIds?: ReadonlySet<string>): WasteFinding | null {
export function detectContextBloat(projects: ProjectSummary[], excludedSessionIds?: ReadonlySet<string>, provider?: string): WasteFinding | null {
const candidates = findContextBloatCandidates(projects)
.filter(c => !excludedSessionIds?.has(c.sessionId))
if (candidates.length === 0) return null
@ -3272,13 +3355,13 @@ export function detectContextBloat(projects: ProjectSummary[], excludedSessionId
fix: {
type: 'paste',
destination: 'session-opener',
label: 'Paste at the start of your NEXT expensive thread (one-time, do not add to CLAUDE.md):',
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
text: CONTEXT_HEAVY_OPENER,
},
}
}
export function detectSessionOutliers(projects: ProjectSummary[], excludedSessionIds?: ReadonlySet<string>): WasteFinding | null {
export function detectSessionOutliers(projects: ProjectSummary[], excludedSessionIds?: ReadonlySet<string>, provider?: string): WasteFinding | null {
type Outlier = {
project: string
sessionId: string
@ -3353,7 +3436,7 @@ export function detectSessionOutliers(projects: ProjectSummary[], excludedSessio
fix: {
type: 'paste',
destination: 'session-opener',
label: 'Paste at the start of your NEXT expensive thread (one-time, do not add to CLAUDE.md):',
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
text: 'Before making changes, summarize the smallest viable plan. Keep context narrow, avoid broad searches, and stop after the first working patch so I can review before continuing.',
},
}
@ -3551,15 +3634,15 @@ export async function scanAndDetect(
claudeOnly(() => detectDuplicateReads(toolCalls, dateRange)),
claudeOnly(() => detectUnusedMcp(toolCalls, projects, projectCwds, mcpCoverage)),
() => detectMcpToolCoverage(projects, mcpCoverage, localMcpServerNames(projectCwds)),
() => detectMcpProfileAdvisor(projects, mcpCoverage),
() => detectMcpProfileAdvisor(projects, mcpCoverage, provider),
// mcp-deferral-gaps family (#614): detection only, no apply plans yet.
claudeOnly(() => detectMcpDeferralOff(toolCalls, projects, projectCwds, apiCalls)),
claudeOnly(() => detectMcpAlwaysLoadHygiene(projects, projectCwds, apiCalls, mcpCoverage)),
claudeOnly(() => detectMcpDeferThreshold(projects, projectCwds)),
() => detectCapabilityReliability(behavioralProjects),
() => detectLowWorthSessions(behavioralProjects),
() => detectContextBloat(behavioralProjects, lowWorthSessionIds),
() => detectSessionOutliers(behavioralProjects, outlierExclusions),
() => detectCapabilityReliability(behavioralProjects, provider),
() => detectLowWorthSessions(behavioralProjects, provider),
() => detectContextBloat(behavioralProjects, lowWorthSessionIds, provider),
() => detectSessionOutliers(behavioralProjects, outlierExclusions, provider),
claudeOnly(() => detectBloatedClaudeMd(projectCwds)),
claudeOnly(() => detectBashBloat()),
claudeOnly(() => detectRecurringContext(openers)),
@ -3624,7 +3707,7 @@ function wrap(text: string, width: number, indent: string): string {
/// destination. Issue #277: users were dropping one-time session openers
/// into CLAUDE.md as permanent rules because the prompts had no labeled
/// home in the output.
function renderActionHeader(action: WasteAction): string {
function renderActionHeader(action: WasteAction, copy: OptimizeRemediationCopy): string {
const headerWidth = PANEL_WIDTH - 4
const fillTo = (label: string): string => {
const inner = ` ${label} `
@ -3637,18 +3720,11 @@ function renderActionHeader(action: WasteAction): string {
case 'command':
return fillTo('Run this command')
case 'paste':
switch (action.destination) {
case 'claude-md': return fillTo('Suggested CLAUDE.md addition (permanent rule)')
case 'session-opener': return fillTo('One-time session opener (do NOT add to CLAUDE.md)')
case 'prompt': return fillTo('Ask Claude in the current session')
case 'shell-config': return fillTo('Add to your shell config')
case 'manual': return fillTo('Manual action')
default: return fillTo('Suggested action')
}
return fillTo(optimizePasteHeader(action.destination, copy))
}
}
function renderFinding(n: number, f: WasteFinding, costRate: number): string[] {
function renderFinding(n: number, f: WasteFinding, costRate: number, copy: OptimizeRemediationCopy): string[] {
const lines: string[] = []
const costSaved = f.tokensSaved * costRate
const impactLabel = f.impact.charAt(0).toUpperCase() + f.impact.slice(1)
@ -3674,7 +3750,7 @@ function renderFinding(n: number, f: WasteFinding, costRate: number): string[] {
// permanent rules and one-time prompts are no longer interchangeable in
// the output.
const a = f.fix
lines.push(chalk.hex(ORANGE)(` ${renderActionHeader(a)}`))
lines.push(chalk.hex(ORANGE)(` ${renderActionHeader(a, copy)}`))
lines.push(chalk.hex(DIM)(` ${a.label}`))
if (a.type === 'file-content') {
for (const line of a.content.split('\n')) lines.push(chalk.hex(CYAN)(` ${line}`))
@ -3743,7 +3819,9 @@ export function renderOptimize(
previouslyApplied?: Record<string, string>,
modelRecommendations?: ModelDefaultRecommendation[],
appliedFixes: AppliedFix[] = [],
provider?: string,
): string {
const copy = optimizeRemediationCopy(provider)
const lines: string[] = []
lines.push('')
lines.push(` ${chalk.bold.hex(ORANGE)('CodeBurn config health')}${chalk.dim(' ' + periodLabel)}`)
@ -3766,9 +3844,9 @@ export function renderOptimize(
if (findings.length === 0) {
lines.push(chalk.hex(GREEN)(' Nothing to fix. Your setup is lean.'))
lines.push('')
lines.push(chalk.dim(' CodeBurn optimize scans your Claude Code sessions and config for'))
lines.push(chalk.dim(' token waste: junk directory reads, duplicate file reads, unused'))
lines.push(chalk.dim(' agents/skills/MCP servers, bloated CLAUDE.md, and more.'))
for (const line of optimizeEmptyScanLines(provider)) {
lines.push(chalk.dim(` ${line}`))
}
lines.push('')
lines.push(...renderAppliedFixes(appliedFixes))
lines.push(...renderWorkflowSection(reworkedFiles, coachingNotes))
@ -3799,7 +3877,7 @@ export function renderOptimize(
for (const f of group) {
const appliedOn = previouslyApplied?.[f.id]
const shown = appliedOn ? { ...f, title: `${f.title} (previously applied ${appliedOn}, re-flagged)` } : f
lines.push(...renderFinding(++n, shown, costRate))
lines.push(...renderFinding(++n, shown, costRate, copy))
}
}
@ -3868,7 +3946,7 @@ export async function runOptimize(
}
const { topReworkedFiles, coachingNotes } = buildWorkflowReport(projects)
const output = renderOptimize(findings, costRate, periodLabel, periodCost, sessionCount, callCount, healthScore, healthGrade, topReworkedFiles, coachingNotes, opts.appliedHeader, opts.previouslyApplied, result.modelRecommendations, opts.appliedFixes)
const output = renderOptimize(findings, costRate, periodLabel, periodCost, sessionCount, callCount, healthScore, healthGrade, topReworkedFiles, coachingNotes, opts.appliedHeader, opts.previouslyApplied, result.modelRecommendations, opts.appliedFixes, opts.provider)
console.log(output)
}

View file

@ -431,7 +431,16 @@ function parseCodexLine(line: string | Buffer): CodexEntry | null {
? getRawDurationMs(getRawPayloadFieldWindow(line, 'duration') ?? '')
: undefined
const timingDuration = payloadDuration ?? getRawDurationMs(pHead) ?? getRawDurationMs(timingTail)
const compactModel = getRawJsonStringField(pHead, 'model')
// session_meta can embed same-name keys under base_instructions /
// dynamic_tools (including provenance.model). A depth-agnostic scan of the
// compact head steals the first nested hit and can overwrite turn_context.
// Restrict every session_meta string field to payload depth 1. Other event
// types keep the cheap first-match scan.
const payloadString = (field: string): string | undefined =>
type === 'session_meta'
? getRawJsonStringField(getRawPayloadFieldWindow(line, field) ?? '', field)
: getRawJsonStringField(pHead, field)
const compactModel = payloadString('model')
const compactModelName = getRawJsonStringField(pHead, 'model_name')
const compactLastUsage = getRawTokenUsage(pHead, 'last_token_usage')
const compactTotalUsage = getRawTokenUsage(pHead, 'total_token_usage')
@ -446,13 +455,13 @@ function parseCodexLine(line: string | Buffer): CodexEntry | null {
payload: {
type: payloadType,
role,
cwd: getRawJsonStringField(pHead, 'cwd'),
model_provider: getRawJsonStringField(pHead, 'model_provider'),
originator: getRawJsonStringField(pHead, 'originator'),
session_id: getRawJsonStringField(pHead, 'session_id'),
forked_from_id: getRawJsonStringField(pHead, 'forked_from_id'),
model: getRawJsonStringField(pHead, 'model'),
name: getRawJsonStringField(pHead, 'name'),
cwd: payloadString('cwd'),
model_provider: payloadString('model_provider'),
originator: payloadString('originator'),
session_id: payloadString('session_id'),
forked_from_id: payloadString('forked_from_id'),
model: compactModel,
name: payloadString('name'),
invocation,
call_id: getRawJsonStringField(pHead, 'call_id'),
turn_id: getRawJsonStringField(pHead, 'turn_id'),

View file

@ -199,6 +199,29 @@ const coreProviders: Provider[] = [claude, cline, clineCli, codewhale, codebuff,
// when an optional module fails to load. Must stay in sync with getAllProviders.
const lazyProviderNames = ['antigravity', 'forge', 'goose', 'cursor', 'opencode', 'cursor-agent', 'crush', 'warp', 'vercel-gateway', 'zcode', 'zed']
// Display names for lazy providers. Must match the `displayName` on the
// loaded Provider object; `providerDisplayName` + getAllProviders() test
// is the drift check.
const lazyProviderDisplayNames: Record<string, string> = {
antigravity: 'Antigravity',
forge: 'Forge',
goose: 'Goose',
cursor: 'Cursor',
opencode: 'OpenCode',
'cursor-agent': 'Cursor Agent',
crush: 'Crush',
warp: 'Warp',
'vercel-gateway': 'Vercel AI Gateway',
zcode: 'ZCode',
zed: 'Zed',
}
export function providerDisplayName(name: string): string {
const core = coreProviders.find(p => p.name === name)
if (core) return core.displayName
return lazyProviderDisplayNames[name] ?? name
}
// Canonical set of every provider name (core + lazy), used to validate the
// --provider CLI flag. Computed lazily so importing this module never depends on
// every provider object being defined at load time (e.g. under test mocks).

View file

@ -277,7 +277,11 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// rich-session-capture-v1: per-call LOC deltas + editFailed from
// patch_apply_end. (The codex-results.json CODEX_CACHE_VERSION is bumped in
// lockstep so the pre-session-cache layer re-parses too.)
codex: 'mcp-attribution-v5-est-cost-active-timing-mcp-wait-rich-capture-v1-cross-provider-pr-v1',
// session-meta-model-v1: parse large session_meta records structurally so a
// nested base_instructions provenance.model cannot overwrite turn_context.
// session-meta-fields-v1: the same depth-1 window for cwd/name/originator/
// session_id/forked_from_id/model_provider, not just model.
codex: 'mcp-attribution-v5-est-cost-active-timing-mcp-wait-rich-capture-v1-cross-provider-pr-v1-session-meta-model-v1-session-meta-fields-v1',
cursor: 'composer-anchored-crediting-v1-est-cost',
'cursor-agent': 'workspaceless-transcript-v1',
// source-provenance-v1 (#944): CLI sessions were misread as VS Code