diff --git a/scripts/perf/goal1-demo-fixture.mjs b/scripts/perf/goal1-demo-fixture.mjs new file mode 100644 index 00000000..ed7e2b0a --- /dev/null +++ b/scripts/perf/goal1-demo-fixture.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +// Goal-1 demo fixture: an isolated Claude config dir + cache dir with usage in +// the two default compare windows (A = Aug 29 - Sep 4, B = Sep 5 - Sep 11, +// relative to today 2026-09-12 local) so the desktop Compare periods screen +// has a known story to show. Read-only fixture; nothing touches real logs. +import { mkdir, writeFile, rm } from 'node:fs/promises' +import { join } from 'node:path' + +const root = process.argv[2] +if (!root) { console.error('usage: node gen-fixture.mjs '); process.exit(1) } +await rm(root, { recursive: true, force: true }) + +const day = (month, date, hour, minute = 0) => new Date(2026, month - 1, date, hour, minute, 0).toISOString() + +function assistant(sessionId, ts, model, input, output, msgId) { + return JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: ts, + message: { + id: msgId, + type: 'message', + role: 'assistant', + model, + content: [{ type: 'text', text: 'ok' }], + usage: { input_tokens: input, output_tokens: output }, + }, + }) +} +function user(sessionId, ts) { + return JSON.stringify({ type: 'user', sessionId, timestamp: ts, message: { role: 'user', content: 'work on the feature' } }) +} + +const MODEL = 'claude-sonnet-4-5' +const MYSTERY = 'mystery-model-9' // no pricing anywhere: coverage must flag it + +const sessions = { + // /work/pricing: active in both windows, MUCH heavier in B (Up), plus a + // session straddling the A/B boundary (Sep 4 22:00 + Sep 5 08:00). + 'pricing-a1': [ + ['u', day(8, 30, 9)], ['a', day(8, 30, 9, 1), MODEL, 2000, 300], + ['u', day(9, 2, 10)], ['a', day(9, 2, 10, 1), MODEL, 2500, 400], + ], + 'pricing-straddle': [ + ['u', day(9, 4, 22)], ['a', day(9, 4, 22, 1), MODEL, 3000, 300], + ['u', day(9, 5, 8)], ['a', day(9, 5, 8, 1), MODEL, 4000, 400], + ], + 'pricing-b1': [ + ['u', day(9, 9, 11)], ['a', day(9, 9, 11, 1), MODEL, 12000, 900], + ['u', day(9, 10, 15)], ['a', day(9, 10, 15, 1), MODEL, 9000, 700], + ], + // /work/website: only in A (Gone). + 'website-a1': [ + ['u', day(8, 31, 14)], ['a', day(8, 31, 14, 1), MODEL, 4000, 500], + ], + // /work/mobile: only in B (New) — one priced call plus one call on the + // unpriced model (coverage must flag the unpriced one as unknown, not zero). + 'mobile-b1': [ + ['u', day(9, 8, 9)], ['a', day(9, 8, 9, 1), MYSTERY, 6000, 800], + ], + 'mobile-b2': [ + ['u', day(9, 7, 16)], ['a', day(9, 7, 16, 1), MODEL, 2000, 300], + ], +} + +const projects = { + 'pricing': 'pricing-a1', + 'pricing2': 'pricing-straddle', + 'pricing3': 'pricing-b1', + 'website': 'website-a1', + 'mobile': 'mobile-b1', +} + +const slug = name => name.replaceAll('/', '-') +for (const [dir, prefix] of Object.entries({ '-work-pricing': ['pricing-a1', 'pricing-straddle', 'pricing-b1'], '-work-website': ['website-a1'], '-work-mobile': ['mobile-b1', 'mobile-b2'] })) { + const dirPath = join(root, 'claude', 'projects', dir) + await mkdir(dirPath, { recursive: true }) + let seq = 0 + for (const sessionId of prefix) { + const lines = sessions[sessionId].map(spec => { + const [kind, ts, model, input, output] = spec + if (kind === 'u') return user(sessionId, ts) + seq += 1 + return assistant(sessionId, ts, model, input, output, `msg-${sessionId}-${seq}`) + }) + await writeFile(join(dirPath, `${sessionId}.jsonl`), lines.join('\n') + '\n', 'utf-8') + } +} +console.log(`fixture written under ${root}`) diff --git a/src/main.ts b/src/main.ts index 431d31da..5cb652c9 100644 --- a/src/main.ts +++ b/src/main.ts @@ -19,7 +19,9 @@ import { isBehavioralCall } from './behavioral-weight.js' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import type { AppliedFix } from './act/types.js' import { aggregateModelEfficiency } from './model-efficiency.js' -import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, type DurablePeriod } from './usage-aggregator.js' +import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, getDailyCacheConfigHash, type DurablePeriod } from './usage-aggregator.js' +import { aggregateProjectsIntoDays } from './day-aggregator.js' +import { buildPeriodDiffReport, defaultSevenDayRanges, diffSessions, dayKeyToRange, historyBasis, localRangeInfo } from './period-diff.js' import { loadStatusSnapshot, saveStatusSnapshot } from './session-cache.js' import { renderDashboard } from './dashboard.js' import { renderOverview } from './overview.js' @@ -2289,6 +2291,122 @@ program await renderCompare(range, opts.provider, opts.modelA, opts.modelB, opts.project, opts.exclude) }) +program + .command('compare-periods') + .description('Compare usage and cost between two periods (B minus A: B is analyzed, A is the reference)') + .option('--from-a ', 'Reference period A start (YYYY-MM-DD)') + .option('--to-a ', 'Reference period A end (YYYY-MM-DD)') + .option('--from-b ', 'Analyzed period B start (YYYY-MM-DD)') + .option('--to-b ', 'Analyzed period B end (YYYY-MM-DD)') + .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') + .option('--format ', 'Output format: json, sessions', 'json') + .option('--dimension ', 'Drill-down dimension for --format sessions: project, model') + .option('--key ', 'Canonical contribution key for --format sessions (project path or model id from the report)') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) + .option('--no-with-history', 'Skip the durable daily-history cross-check (aggregate-only carried days)') + .action(async (opts) => { + assertProvider(opts.provider, 'compare-periods') + assertFormat(opts.format, ['json', 'sessions'], 'compare-periods') + + // Explicit ranges must come as two complete pairs; otherwise the default + // horizon is the last seven complete local days (B) vs the seven before + // (A). Same local-date conventions as --from/--to everywhere else. + const flagsGiven = [opts.fromA, opts.toA, opts.fromB, opts.toB].filter(v => v !== undefined) + let keyRangeA: DateRange + let keyRangeB: DateRange + if (flagsGiven.length > 0) { + if (flagsGiven.length !== 4) { + process.stderr.write('codeburn compare-periods: --from-a/--to-a/--from-b/--to-b must be provided together.\n') + process.exit(1) + } + const a = parseDateRangeFlags(opts.fromA, opts.toA) + const b = parseDateRangeFlags(opts.fromB, opts.toB) + if (!a || !b) { + process.stderr.write('codeburn compare-periods: --from-a/--to-a/--from-b/--to-b must be valid YYYY-MM-DD dates.\n') + process.exit(1) + } + keyRangeA = a + keyRangeB = b + } else { + const defaults = defaultSevenDayRanges() + keyRangeA = dayKeyToRange(defaults.A.from, defaults.A.to) + keyRangeB = dayKeyToRange(defaults.B.from, defaults.B.to) + } + + if (opts.format === 'sessions') { + const dimension = opts.dimension + if (dimension !== 'project' && dimension !== 'model') { + process.stderr.write('codeburn compare-periods: --dimension must be "project" or "model" for --format sessions.\n') + process.exit(1) + } + if (!opts.key) { + process.stderr.write('codeburn compare-periods: --key is required for --format sessions.\n') + process.exit(1) + } + await loadPricing() + const [projectsA, projectsB] = await Promise.all([ + parseAllSessions(keyRangeA, opts.provider), + parseAllSessions(keyRangeB, opts.provider), + ]) + process.stdout.write(JSON.stringify({ + dimension, + key: opts.key, + provider: opts.provider, + rangeA: localRangeInfo(keyRangeA), + rangeB: localRangeInfo(keyRangeB), + sessions: diffSessions(projectsA, projectsB, dimension, opts.key), + }, null, 2) + '\n') + return + } + + await loadPricing() + const [parsedA, parsedB] = await Promise.all([ + parseAllSessions(keyRangeA, opts.provider), + parseAllSessions(keyRangeB, opts.provider), + ]) + await reportUnmatchedProjectPatterns([...parsedA, ...parsedB], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(keyRangeB)) + const projectsA = filterProjectsByName(parsedA, opts.project, opts.exclude) + const projectsB = filterProjectsByName(parsedB, opts.project, opts.exclude) + + // Cross-check the durable daily history so usage whose sources aged off + // disk (aggregate-only carried days) is visible instead of silently + // missing from a transcript-based report. Best-effort: an unavailable + // daily cache degrades to the report's explicit "detail only" basis note. + let history + if (opts.withHistory) { + try { + const { ensureCacheHydrated } = await import('./daily-cache.js') + const cache = await ensureCacheHydrated( + range => parseAllSessions(range, 'all'), + aggregateProjectsIntoDays, + getDailyCacheConfigHash(), + isSessionHydrationComplete, + ) + history = historyBasis( + cache, + localRangeInfo(keyRangeA), + localRangeInfo(keyRangeB), + opts.provider, + aggregateProjectsIntoDays(projectsA), + aggregateProjectsIntoDays(projectsB), + ) + } catch (err) { + process.stderr.write(`codeburn compare-periods: daily history check skipped (${err instanceof Error ? err.message : String(err)}).\n`) + } + } + + const report = buildPeriodDiffReport({ + provider: opts.provider, + rangeA: localRangeInfo(keyRangeA), + rangeB: localRangeInfo(keyRangeB), + projectsA, + projectsB, + history, + }) + process.stdout.write(JSON.stringify(report, null, 2) + '\n') + }) + program .command('audit') .description("Token audit: raw provider token fields vs codeburn's displayed totals and cost derivation") diff --git a/src/period-diff.ts b/src/period-diff.ts new file mode 100644 index 00000000..56b9ac76 --- /dev/null +++ b/src/period-diff.ts @@ -0,0 +1,546 @@ +import { getDaysInRange, type DailyCache, type DailyEntry } from './daily-cache.js' +import type { DateRange, ProjectSummary } from './types.js' +import { buildPeriodData, canonicalSessionCountKey } from './usage-aggregator.js' +import { inferSessionProvider } from './session-output.js' + +/// Period-vs-period difference engine (Compare periods). Pure functions only: +/// no clock reads, no filesystem, no parsing. The caller parses each range with +/// `parseAllSessions(range, provider)` — which slices at CALL granularity +/// (src/parser.ts `callsInRange`, issue #852) — and hands the sliced +/// ProjectSummary[] trees in. A session that straddles the A/B boundary is +/// therefore split across both ranges at the same granularity every other +/// CodeBurn report uses; nothing here re-derives attribution from session start +/// dates. All differences are B − A. A is the reference period, B the analyzed +/// one. + +export type PeriodRangeKey = { from: string; to: string } + +export type PeriodRangeInfo = { + from: string + to: string + /// Inclusive count of local calendar days, counted by walking local + /// midnights (never millisecond division, which DST breaks). + days: number +} + +export type ContributionStatus = 'new' | 'gone' | 'up' | 'down' | 'flat' + +export type Contribution = { + /// Canonical project path or canonical model id (the keys every other + /// report uses — never a display title or short name). + key: string + costA: number + costB: number + diff: number + /// diff / |costA| × 100. Null when costA is exactly 0 — the row is labeled + /// `new` instead of inventing an infinite percentage. + pct: number | null + status: ContributionStatus + callsA: number + callsB: number +} + +export type PeriodTotals = { + cost: number + calls: number + sessions: number + inputTokens: number + outputTokens: number + cacheReadTokens: number + cacheWriteTokens: number + savingsUSD: number + estimatedCostUSD: number +} + +export type TotalsDiff = { + A: PeriodTotals + B: PeriodTotals + /// B − A for every component, unrounded. + diff: PeriodTotals + /// Per-component B−A percent, null where the A component is 0. + pct: Record, number | null> & { sessions: number | null } +} + +export type NormalizedMetric = { + a: number | null + b: number | null + diff: number | null + pct: number | null +} + +export type NormalizedView = { + /// Cost per calendar day of each range. + perDay: NormalizedMetric + /// Cost per 100 (behavioral) API calls of each range. + per100Calls: NormalizedMetric + /// What each denominator counts, so a normalized number can always be + /// checked against the raw totals on screen. + denominators: { + perDay: string + per100Calls: string + } +} + +export type CoverageBlock = { + /// Models with calls but no price data — "unknown", never zero — per range, + /// straight from the shared buildPeriodData rules. + unpricedModelsA: Array<{ model: string; calls: number }> + unpricedModelsB: Array<{ model: string; calls: number }> + pricingCoverageA: number | null + pricingCoverageB: number | null +} + +export type AggregateDayRow = { + date: string + /// Cost the durable daily history holds for that day (all providers, or the + /// selected provider's slice when a provider filter is active). + historyCost: number + /// Cost the session-detail basis explains for that day. + detailCost: number + /// historyCost − detailCost when the durable history holds more than the + /// session detail can explain: usage whose sources aged off disk and survives + /// only as the aggregate carried history. Shown separately, never folded into + /// the totals or the contribution lenses. + aggregateOnly: number +} + +export type HistoryBasis = { + historyCost: { A: number; B: number } + detailCost: { A: number; B: number } + /// Days in each range whose durable history exceeds what the session detail + /// explains, sorted by date. Empty arrays when everything reconciles. + days: { A: AggregateDayRow[]; B: AggregateDayRow[] } + aggregateOnly: { A: number; B: number } + /// One-line explanation of the basis, rendered verbatim in the UI/report. + basis: string +} + +export type PeriodDiffReport = { + schema: 1 + provider: string + rangeA: PeriodRangeInfo + rangeB: PeriodRangeInfo + /// Inclusive local-day overlap of A and B, 0 when disjoint. + overlapDays: number + /// days(B) − days(A); 0 when the ranges are equally long. + durationDeltaDays: number + totals: TotalsDiff + /// Same global difference seen per project. Lenses are never summed together: + /// each one alone reconciles the global diff (before display rounding). + projects: Contribution[] + /// Separate lens: the same global difference seen per model. + models: Contribution[] + normalized: NormalizedView + coverage: CoverageBlock + history?: HistoryBasis +} + +export type SessionDiffRow = { + /// `provider\0projectPath\0sessionId` — the canonical session identity. A + /// bare sessionId is not globally unique and is never used as the key. + identity: string + provider: string + sessionId: string + project: string + title?: string + costA: number + costB: number + diff: number + callsA: number + callsB: number +} + +const EPSILON = 1e-9 + +function localDateKey(date: Date): string { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` +} + +function localDayStart(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()) +} + +/// Count inclusive local calendar days from `from` to `to` by walking local +/// midnights. Millisecond division would miscount across a DST transition; a +/// calendar walk does not, in any timezone. +export function countLocalDays(from: string, to: string): number { + const [fy, fm, fd] = from.split('-').map(Number) as [number, number, number] + const [ty, tm, td] = to.split('-').map(Number) as [number, number, number] + const cursor = localDayStart(new Date(fy, fm - 1, fd)) + const end = localDayStart(new Date(ty, tm - 1, td)) + if (cursor > end) return 0 + let days = 0 + while (cursor <= end) { + days++ + cursor.setDate(cursor.getDate() + 1) + } + return days +} + +export function rangeInfo(range: PeriodRangeKey): PeriodRangeInfo { + return { ...range, days: countLocalDays(range.from, range.to) } +} + +/// Key a parser DateRange (local start/end Dates, end inclusive at 23:59:59.999) +/// into from/to strings plus its inclusive local-day count. +export function localRangeInfo(range: DateRange): PeriodRangeInfo { + return rangeInfo({ from: localDateKey(range.start), to: localDateKey(range.end) }) +} + +/// Local 'YYYY-MM-DD' day keys (inclusive) back into the parser DateRange +/// shape: [from 00:00:00.000, to 23:59:59.999] in LOCAL time — the same +/// convention `--from/--to` uses everywhere else in the CLI. +export function dayKeyToRange(from: string, to: string): DateRange { + const [fy, fm, fd] = from.split('-').map(Number) as [number, number, number] + const [ty, tm, td] = to.split('-').map(Number) as [number, number, number] + return { start: new Date(fy, fm - 1, fd), end: new Date(ty, tm - 1, td, 23, 59, 59, 999) } +} + +/// The default horizon: B = the last seven COMPLETE local calendar days +/// (today is never complete), A = the seven before that. All local time — +/// never UTC. +export function defaultSevenDayRanges(now = new Date()): { A: PeriodRangeKey; B: PeriodRangeKey } { + const day = (offset: number): string => { + const d = localDayStart(now) + d.setDate(d.getDate() + offset) + return localDateKey(d) + } + return { + A: { from: day(-14), to: day(-8) }, + B: { from: day(-7), to: day(-1) }, + } +} + +/// Inclusive local-day overlap between two [from..to] key ranges. +export function overlapDays(a: PeriodRangeKey, b: PeriodRangeKey): number { + const start = a.from > b.from ? a.from : b.from + const end = a.to < b.to ? a.to : b.to + if (start > end) return 0 + return countLocalDays(start, end) +} + +function pct(diff: number, base: number): number | null { + if (Math.abs(base) < EPSILON) return null + return (diff / Math.abs(base)) * 100 +} + +function statusOf(costA: number, costB: number): ContributionStatus { + if (Math.abs(costA) < EPSILON && Math.abs(costB) >= EPSILON) return 'new' + if (Math.abs(costB) < EPSILON && Math.abs(costA) >= EPSILON) return 'gone' + if (costB > costA) return 'up' + if (costB < costA) return 'down' + return 'flat' +} + +/// Deterministic order: largest absolute movement first, then B size, then key. +function byMovement(a: Contribution, b: Contribution): number { + const delta = Math.abs(b.diff) - Math.abs(a.diff) + if (delta !== 0) return delta + if (b.costB !== a.costB) return b.costB - a.costB + return a.key.localeCompare(b.key) +} + +function contribution(key: string, costA: number, costB: number, callsA: number, callsB: number): Contribution { + const diff = costB - costA + return { key, costA, costB, diff, pct: pct(diff, costA), status: statusOf(costA, costB), callsA, callsB } +} + +function totalsOf(projects: ProjectSummary[], label: string): { totals: PeriodTotals; unpriced: Array<{ model: string; calls: number }>; pricingCoverage: number | null } { + const data = buildPeriodData(label, projects) + return { + totals: { + cost: data.cost, + calls: data.calls, + sessions: data.sessions, + inputTokens: data.inputTokens, + outputTokens: data.outputTokens, + cacheReadTokens: data.cacheReadTokens, + cacheWriteTokens: data.cacheWriteTokens, + savingsUSD: data.savingsUSD, + estimatedCostUSD: data.estimatedCostUSD ?? 0, + }, + unpriced: (data.unpricedModels ?? []).map(m => ({ model: m.model, calls: m.calls })), + pricingCoverage: data.pricingCoverage ?? null, + } +} + +function diffTotals(a: PeriodTotals, b: PeriodTotals): TotalsDiff { + const diff: PeriodTotals = { + cost: b.cost - a.cost, + calls: b.calls - a.calls, + sessions: b.sessions - a.sessions, + inputTokens: b.inputTokens - a.inputTokens, + outputTokens: b.outputTokens - a.outputTokens, + cacheReadTokens: b.cacheReadTokens - a.cacheReadTokens, + cacheWriteTokens: b.cacheWriteTokens - a.cacheWriteTokens, + savingsUSD: b.savingsUSD - a.savingsUSD, + estimatedCostUSD: b.estimatedCostUSD - a.estimatedCostUSD, + } + const pctRow = (fn: (t: PeriodTotals) => number): number | null => { + const va = fn(a) + return pct(fn(diff), va) + } + return { + A: a, + B: b, + diff, + pct: { + cost: pctRow(t => t.cost), + calls: pctRow(t => t.calls), + sessions: pctRow(t => t.sessions), + inputTokens: pctRow(t => t.inputTokens), + outputTokens: pctRow(t => t.outputTokens), + cacheReadTokens: pctRow(t => t.cacheReadTokens), + cacheWriteTokens: pctRow(t => t.cacheWriteTokens), + savingsUSD: pctRow(t => t.savingsUSD), + estimatedCostUSD: pctRow(t => t.estimatedCostUSD), + }, + } +} + +function normalize(numeratorA: number, numeratorB: number, denominatorA: number, denominatorB: number): NormalizedMetric { + // Denominator 0 or unknown → unavailable (null), never an invented value. + const a = denominatorA > 0 ? numeratorA / denominatorA : null + const b = denominatorB > 0 ? numeratorB / denominatorB : null + if (a === null || b === null) return { a, b, diff: null, pct: null } + const delta = b - a + return { a, b, diff: delta, pct: pct(delta, a) } +} + +function normalizedView(totalsA: PeriodTotals, totalsB: PeriodTotals, rangeA: PeriodRangeInfo, rangeB: PeriodRangeInfo): NormalizedView { + return { + perDay: normalize(totalsA.cost, totalsB.cost, rangeA.days, rangeB.days), + per100Calls: normalize(totalsA.cost * 100, totalsB.cost * 100, totalsA.calls, totalsB.calls), + denominators: { + perDay: `calendar days in the range (A: ${rangeA.days}, B: ${rangeB.days})`, + per100Calls: `API calls × 100 (A: ${totalsA.calls.toLocaleString('en-US')}, B: ${totalsB.calls.toLocaleString('en-US')})`, + }, + } +} + +function projectContributions(projectsA: ProjectSummary[], projectsB: ProjectSummary[]): Contribution[] { + const costsA = new Map() + const costsB = new Map() + for (const p of projectsA) costsA.set(p.project, { cost: p.totalCostUSD, calls: p.totalApiCalls }) + for (const p of projectsB) costsB.set(p.project, { cost: p.totalCostUSD, calls: p.totalApiCalls }) + const keys = new Set([...costsA.keys(), ...costsB.keys()]) + const rows: Contribution[] = [] + for (const key of keys) { + const a = costsA.get(key) + const b = costsB.get(key) + const costA = a?.cost ?? 0 + const costB = b?.cost ?? 0 + if (Math.abs(costA) < EPSILON && Math.abs(costB) < EPSILON) continue + rows.push(contribution(key, costA, costB, a?.calls ?? 0, b?.calls ?? 0)) + } + return rows.sort(byMovement) +} + +function modelContributions(projectsA: ProjectSummary[], projectsB: ProjectSummary[]): Contribution[] { + const fold = (projects: ProjectSummary[]): Map => { + const map = new Map() + for (const p of projects) { + for (const sess of p.sessions) { + for (const [model, d] of Object.entries(sess.modelBreakdown)) { + const acc = map.get(model) ?? { cost: 0, calls: 0 } + acc.cost += d.costUSD + acc.calls += d.calls + map.set(model, acc) + } + } + } + return map + } + const costsA = fold(projectsA) + const costsB = fold(projectsB) + const keys = new Set([...costsA.keys(), ...costsB.keys()]) + const rows: Contribution[] = [] + for (const key of keys) { + const a = costsA.get(key) + const b = costsB.get(key) + const costA = a?.cost ?? 0 + const costB = b?.cost ?? 0 + if (Math.abs(costA) < EPSILON && Math.abs(costB) < EPSILON) continue + rows.push(contribution(key, costA, costB, a?.calls ?? 0, b?.calls ?? 0)) + } + return rows.sort(byMovement) +} + +/// Cross-check the session-detail totals against the durable daily history +/// (the ONLY record of days whose sources aged off disk, flagged `carried`). +/// Days where the history holds more than the detail explains are listed with +/// their aggregate-only amount so a reader can always see how much of the +/// picture has no session detail behind it. The aggregate-only amount is +/// reported separately and is NEVER folded into totals or lenses. +export function historyBasis( + cache: DailyCache, + rangeA: PeriodRangeKey, + rangeB: PeriodRangeKey, + provider: string, + freshDaysA: DailyEntry[], + freshDaysB: DailyEntry[], +): HistoryBasis { + const dayCost = (entry: DailyEntry): number => { + if (provider === 'all' || provider === '') return entry.cost + return entry.providers[provider]?.cost ?? 0 + } + const detailByDay = (days: DailyEntry[]): Map => + new Map(days.map(day => [day.date, day.cost])) + + const build = (range: PeriodRangeKey, fresh: DailyEntry[]) => { + const detail = detailByDay(fresh) + const rows: AggregateDayRow[] = [] + let historyCost = 0 + let detailCost = 0 + let aggregateOnly = 0 + for (const entry of getDaysInRange(cache, range.from, range.to)) { + const history = dayCost(entry) + const explained = detail.get(entry.date) ?? 0 + historyCost += history + detailCost += explained + // Only a POSITIVE unexplained remainder is aggregate history. A negative + // one (detail exceeds history) means the durable cache is simply behind, + // not that detail is wrong — never clamp it into a fake carried number. + if (history > explained + EPSILON) { + const unexplained = history - explained + aggregateOnly += unexplained + rows.push({ date: entry.date, historyCost: history, detailCost: explained, aggregateOnly: unexplained }) + } + } + return { rows, historyCost, detailCost, aggregateOnly } + } + + const a = build(rangeA, freshDaysA) + const b = build(rangeB, freshDaysB) + return { + historyCost: { A: a.historyCost, B: b.historyCost }, + detailCost: { A: a.detailCost, B: b.detailCost }, + days: { A: a.rows, B: b.rows }, + aggregateOnly: { A: a.aggregateOnly, B: b.aggregateOnly }, + basis: 'Totals come from parsed session transcripts. Days whose sources no longer exist survive only as aggregate daily history; their unexplained cost is listed here, not folded into the totals.', + } +} + +// getDaysInRange is imported at the top of this module. +function emptyHistoryBasis(): HistoryBasis { + return { + historyCost: { A: 0, B: 0 }, + detailCost: { A: 0, B: 0 }, + days: { A: [], B: [] }, + aggregateOnly: { A: 0, B: 0 }, + basis: 'Daily history unavailable in this run; totals reflect parsed session detail only.', + } +} + +export function buildPeriodDiffReport(args: { + provider: string + rangeA: PeriodRangeKey + rangeB: PeriodRangeKey + projectsA: ProjectSummary[] + projectsB: ProjectSummary[] + history?: HistoryBasis +}): PeriodDiffReport { + const infoA = rangeInfo(args.rangeA) + const infoB = rangeInfo(args.rangeB) + const labelA = `${infoA.from} to ${infoA.to}` + const labelB = `${infoB.from} to ${infoB.to}` + const sideA = totalsOf(args.projectsA, labelA) + const sideB = totalsOf(args.projectsB, labelB) + const totalsA = sideA.totals + const totalsB = sideB.totals + return { + schema: 1, + provider: args.provider, + rangeA: infoA, + rangeB: infoB, + overlapDays: overlapDays(args.rangeA, args.rangeB), + durationDeltaDays: infoB.days - infoA.days, + totals: diffTotals(totalsA, totalsB), + projects: projectContributions(args.projectsA, args.projectsB), + models: modelContributions(args.projectsA, args.projectsB), + normalized: normalizedView(totalsA, totalsB, infoA, infoB), + coverage: { + unpricedModelsA: sideA.unpriced, + unpricedModelsB: sideB.unpriced, + pricingCoverageA: sideA.pricingCoverage, + pricingCoverageB: sideB.pricingCoverage, + }, + history: args.history ?? emptyHistoryBasis(), + } +} + +/// Sessions behind one contribution, joined across A and B on the canonical +/// session identity (provider + project path + sessionId). Costs are each +/// range's post-slice session totals, so a session with activity on both sides +/// of the boundary appears once with a cost in each column. +export function diffSessions( + projectsA: ProjectSummary[], + projectsB: ProjectSummary[], + dimension: 'project' | 'model', + key: string, +): SessionDiffRow[] { + type Acc = { provider: string; sessionId: string; project: string; title?: string; costA: number; costB: number; callsA: number; callsB: number } + const accs = new Map() + + const fold = (projects: ProjectSummary[], side: 'A' | 'B') => { + for (const project of projects) { + for (const session of project.sessions) { + // Model lens: attribute the MODEL's slice of the session (its + // modelBreakdown entry), never the whole session cost — a session can + // use several models and its total belongs to no single one of them. + const modelEntry = dimension === 'model' ? session.modelBreakdown[key] : undefined + if (dimension === 'model' && !modelEntry) continue + if (dimension === 'project' && project.project !== key) continue + const cost = dimension === 'model' ? modelEntry!.costUSD : session.totalCostUSD + const calls = dimension === 'model' ? modelEntry!.calls : session.apiCalls + const identity = canonicalSessionCountKey(session, project.projectPath) + const acc = accs.get(identity) ?? { + provider: inferSessionProvider(session), + sessionId: session.sessionId, + project: project.project, + title: session.title, + costA: 0, + costB: 0, + callsA: 0, + callsB: 0, + } + if (side === 'A') { + acc.costA += cost + acc.callsA += calls + } else { + acc.costB += cost + acc.callsB += calls + } + if (!acc.title && session.title) acc.title = session.title + accs.set(identity, acc) + } + } + } + fold(projectsA, 'A') + fold(projectsB, 'B') + + const rows: SessionDiffRow[] = [] + for (const [identity, acc] of accs) { + if (Math.abs(acc.costA) < EPSILON && Math.abs(acc.costB) < EPSILON) continue + rows.push({ + identity, + provider: acc.provider, + sessionId: acc.sessionId, + project: acc.project, + ...(acc.title ? { title: acc.title } : {}), + costA: acc.costA, + costB: acc.costB, + diff: acc.costB - acc.costA, + callsA: acc.callsA, + callsB: acc.callsB, + }) + } + return rows.sort(byMovementLikeSessions) +} + +function byMovementLikeSessions(a: SessionDiffRow, b: SessionDiffRow): number { + const delta = Math.abs(b.diff) - Math.abs(a.diff) + if (delta !== 0) return delta + if (b.costB !== a.costB) return b.costB - a.costB + return a.identity.localeCompare(b.identity) +} diff --git a/tests/compare-periods-cli.test.ts b/tests/compare-periods-cli.test.ts new file mode 100644 index 00000000..a61d618d --- /dev/null +++ b/tests/compare-periods-cli.test.ts @@ -0,0 +1,167 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' + +import { describe, expect, it } from 'vitest' + +function runCli(args: string[], home: string) { + return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { + cwd: process.cwd(), + env: { + ...process.env, + CLAUDE_CONFIG_DIR: join(home, '.claude'), + CODEBURN_CACHE_DIR: join(home, '.cache', 'codeburn'), + HOME: home, USERPROFILE: home, + TZ: 'UTC', + }, + encoding: 'utf-8', + }) +} + +function userLine(sessionId: string, timestamp: string): string { + return JSON.stringify({ + type: 'user', + sessionId, + timestamp, + message: { role: 'user', content: 'add feature' }, + }) +} + +function assistantLine(sessionId: string, timestamp: string, messageId: string, inputTokens: number): string { + return JSON.stringify({ + type: 'assistant', + sessionId, + timestamp, + message: { + id: messageId, + type: 'message', + role: 'assistant', + model: 'claude-sonnet-4-5', + content: [{ type: 'text', text: 'done' }], + usage: { input_tokens: inputTokens, output_tokens: 100 }, + }, + }) +} + +// Two sessions on two consecutive local days (UTC runner): 'a-side' on +// 2026-04-16, 'b-side' on 2026-04-17. Session 'straddle' has one call on +// EACH day, proving the drill-down joins its two sliced halves. +async function writeFixture(home: string): Promise { + const projectDir = join(home, '.claude', 'projects', 'work') + await mkdir(projectDir, { recursive: true }) + await writeFile( + join(projectDir, 'a-side.jsonl'), + [ + userLine('a-side', '2026-04-16T10:00:00Z'), + assistantLine('a-side', '2026-04-16T10:01:00Z', 'msg-a', 1000), + ].join('\n'), + ) + await writeFile( + join(projectDir, 'b-side.jsonl'), + [ + userLine('b-side', '2026-04-17T10:00:00Z'), + assistantLine('b-side', '2026-04-17T10:01:00Z', 'msg-b', 3000), + ].join('\n'), + ) + await writeFile( + join(projectDir, 'straddle.jsonl'), + [ + userLine('straddle', '2026-04-16T20:00:00Z'), + assistantLine('straddle', '2026-04-16T20:01:00Z', 'msg-s1', 1000), + userLine('straddle', '2026-04-17T09:00:00Z'), + assistantLine('straddle', '2026-04-17T09:01:00Z', 'msg-s2', 2000), + ].join('\n'), + ) +} + +const ARGS_A = ['--from-a', '2026-04-16', '--to-a', '2026-04-16', '--from-b', '2026-04-17', '--to-b', '2026-04-17'] + +describe('codeburn compare-periods (CLI)', () => { + it('reports the B − A difference with reconciling lenses on a real fixture', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--format', 'json', ...ARGS_A], home) + expect(run.status).toBe(0) + const report = JSON.parse(run.stdout) + + expect(report.schema).toBe(1) + expect(report.rangeA).toMatchObject({ from: '2026-04-16', to: '2026-04-16', days: 1 }) + expect(report.rangeB).toMatchObject({ from: '2026-04-17', to: '2026-04-17', days: 1 }) + + const totalA = report.totals.A.cost + const totalB = report.totals.B.cost + expect(totalA).toBeGreaterThan(0) + expect(totalB).toBeGreaterThan(totalA) + expect(report.totals.diff.cost).toBeCloseTo(totalB - totalA, 10) + + const lensSum = (rows: Array<{ diff: number }>) => rows.reduce((s, r) => s + r.diff, 0) + expect(report.projects).toHaveLength(1) + expect(report.projects[0].key.endsWith('work') || report.projects[0].key.includes('work')).toBe(true) + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + expect(lensSum(report.models)).toBeCloseTo(report.totals.diff.cost, 10) + + // The boundary-straddling session must be visible in the drill-down + // with a cost on BOTH sides, joined into one canonical row. + const drill = runCli( + ['compare-periods', '--format', 'sessions', '--dimension', 'project', '--key', report.projects[0].key, ...ARGS_A], + home, + ) + expect(drill.status).toBe(0) + const sessions = JSON.parse(drill.stdout) + const straddle = sessions.sessions.find((s: { sessionId: string }) => s.sessionId === 'straddle') + expect(straddle).toBeDefined() + expect(straddle.costA).toBeGreaterThan(0) + expect(straddle.costB).toBeGreaterThan(0) + // Same-session drill rows must not duplicate the straddler. + expect(sessions.sessions.filter((s: { sessionId: string }) => s.sessionId === 'straddle')).toHaveLength(1) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('defaults to the last seven complete days vs the seven before', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-default-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--format', 'json'], home) + expect(run.status).toBe(0) + const report = JSON.parse(run.stdout) + expect(report.rangeB.days).toBe(7) + expect(report.rangeA.days).toBe(7) + // Today (Apr 18 in the fixture's world, but really the runner's today) + // must not be inside either range: both are complete days only. + const today = new Date() + const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}` + expect(report.rangeB.to).not.toBe(todayKey) + expect(report.rangeB.to < todayKey).toBe(true) + expect(report.rangeA.to < report.rangeB.from).toBe(true) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('rejects partial explicit ranges loudly', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-bad-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--from-a', '2026-04-16'], home) + expect(run.status).not.toBe(0) + expect(run.stderr).toContain('must be provided together') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('rejects an impossible date instead of rolling it forward', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-bad2-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--from-a', '2026-02-31', '--to-a', '2026-03-05', '--from-b', '2026-04-16', '--to-b', '2026-04-17'], home) + expect(run.status).not.toBe(0) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/period-diff-boundary-parse.test.ts b/tests/period-diff-boundary-parse.test.ts new file mode 100644 index 00000000..e724f617 --- /dev/null +++ b/tests/period-diff-boundary-parse.test.ts @@ -0,0 +1,106 @@ +import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { loadPricing } from '../src/models.js' +import { parseAllSessions, clearSessionCache } from '../src/parser.js' +import { buildPeriodDiffReport, diffSessions } from '../src/period-diff.js' +import type { DateRange } from '../src/types.js' + +// End-to-end proof that a session with activity on BOTH sides of the A/B +// boundary is attributed at the parser's real granularity (per call, issue +// #852), and that the period-diff engine joins the two halves into one row. + +let base: string + +beforeEach(async () => { + base = await mkdtemp(join(tmpdir(), 'codeburn-period-diff-')) + process.env['CLAUDE_CONFIG_DIR'] = base + await loadPricing() +}) + +afterEach(async () => { + delete process.env['CLAUDE_CONFIG_DIR'] + clearSessionCache() + await rm(base, { recursive: true, force: true }) +}) + +function line(timestamp: string, messageId: string, inputTokens: number): string { + return JSON.stringify({ + type: 'assistant', + sessionId: 'straddle', + timestamp, + message: { + id: messageId, + type: 'message', + role: 'assistant', + model: 'claude-sonnet-4-5', + content: [{ type: 'text', text: 'ok' }], + usage: { input_tokens: inputTokens, output_tokens: 100 }, + }, + }) +} + +// One session, two turns: local Apr 16 10:00 (side A) and Apr 17 10:00 (side B). +async function writeStraddlingSession(): Promise { + const projectDir = join(base, 'projects', 'work') + await mkdir(projectDir, { recursive: true }) + const tsA = new Date(2026, 3, 16, 10, 0, 0).toISOString() + const tsB = new Date(2026, 3, 17, 10, 0, 0).toISOString() + await writeFile( + join(projectDir, 'straddle.jsonl'), + [line(tsA, 'msg-a', 1000), line(tsB, 'msg-b', 3000)].join('\n') + '\n', + 'utf-8', + ) +} + +function dayRange(y: number, m: number, d: number): DateRange { + return { start: new Date(y, m, d), end: new Date(y, m, d, 23, 59, 59, 999) } +} + +describe('period diff over a real parse', () => { + it('splits a boundary-straddling session by call and reconciles the diff', async () => { + await writeStraddlingSession() + const rangeA = dayRange(2026, 3, 16) + const rangeB = dayRange(2026, 3, 17) + + const projectsA = await parseAllSessions(rangeA, 'all') + const projectsB = await parseAllSessions(rangeB, 'all') + + // Each range holds the SAME session with only ITS calls (post-slice). + const sessionA = projectsA[0]!.sessions[0]! + const sessionB = projectsB[0]!.sessions[0]! + expect(sessionA.sessionId).toBe('straddle') + expect(sessionB.sessionId).toBe('straddle') + const costA = sessionA.totalCostUSD + const costB = sessionB.totalCostUSD + expect(costA).toBeGreaterThan(0) + expect(costB).toBeGreaterThan(costA) // Apr 17's call carries more input tokens. + + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-04-16', to: '2026-04-16' }, + rangeB: { from: '2026-04-17', to: '2026-04-17' }, + projectsA, + projectsB, + }) + // Same canonical project on both sides → one contribution row, diff = B − A. + expect(report.projects).toHaveLength(1) + expect(report.projects[0]!.costA).toBeCloseTo(costA, 10) + expect(report.projects[0]!.costB).toBeCloseTo(costB, 10) + expect(report.totals.diff.cost).toBeCloseTo(costB - costA, 10) + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + + // Drill-down: ONE row for the straddling session, cost on both sides. + const rows = diffSessions(projectsA, projectsB, 'project', projectsA[0]!.project) + expect(rows).toHaveLength(1) + expect(rows[0]!.sessionId).toBe('straddle') + expect(rows[0]!.costA).toBeCloseTo(costA, 10) + expect(rows[0]!.costB).toBeCloseTo(costB, 10) + }) +}) + +function lensSum(rows: Array<{ diff: number }>): number { + return rows.reduce((s, row) => s + row.diff, 0) +} diff --git a/tests/period-diff.test.ts b/tests/period-diff.test.ts new file mode 100644 index 00000000..0a4cd480 --- /dev/null +++ b/tests/period-diff.test.ts @@ -0,0 +1,378 @@ +import { describe, expect, it } from 'vitest' + +import { + buildPeriodDiffReport, + countLocalDays, + defaultSevenDayRanges, + diffSessions, + historyBasis, + localRangeInfo, + overlapDays, + rangeInfo, +} from '../src/period-diff.js' +import type { DailyCache, DailyEntry } from '../src/daily-cache.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' + +// Minimal but arithmetically consistent session/project fixtures: the same +// fields buildPeriodData, the session-count key, and the model lens read. + +type SessionSpec = { + sessionId: string + provider?: string + model?: string + modelCosts?: Record + costUSD: number + calls: number + inputTokens?: number + outputTokens?: number + cacheReadTokens?: number + cacheWriteTokens?: number + title?: string + firstTimestamp?: string +} + +function makeSession(spec: SessionSpec): SessionSummary { + const modelBreakdown: SessionSummary['modelBreakdown'] = {} + const models = spec.modelCosts ?? { [spec.model ?? 'test-model']: { costUSD: spec.costUSD, calls: spec.calls } } + let totalCost = 0 + let totalCalls = 0 + for (const [model, d] of Object.entries(models)) { + modelBreakdown[model] = { + calls: d.calls, + costUSD: d.costUSD, + savingsUSD: 0, + tokens: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0 }, + } + totalCost += d.costUSD + totalCalls += d.calls + } + const costUSD = spec.modelCosts ? totalCost : spec.costUSD + const calls = spec.modelCosts ? totalCalls : spec.calls + return { + sessionId: spec.sessionId, + project: 'proj', + firstTimestamp: spec.firstTimestamp ?? '2026-03-10T10:00:00.000Z', + lastTimestamp: spec.firstTimestamp ?? '2026-03-10T11:00:00.000Z', + totalCostUSD: costUSD, + totalSavingsUSD: 0, + totalInputTokens: spec.inputTokens ?? 0, + totalOutputTokens: spec.outputTokens ?? 0, + totalReasoningTokens: 0, + totalCacheReadTokens: spec.cacheReadTokens ?? 0, + totalCacheWriteTokens: spec.cacheWriteTokens ?? 0, + apiCalls: calls, + turns: [], + modelBreakdown, + toolBreakdown: {}, + mcpBreakdown: {}, + bashBreakdown: {}, + categoryBreakdown: {} as SessionSummary['categoryBreakdown'], + skillBreakdown: {}, + subagentBreakdown: {}, + } as SessionSummary +} + +function makeProject(project: string, sessions: SessionSummary[]): ProjectSummary { + const totalCostUSD = sessions.reduce((s, sess) => s + sess.totalCostUSD, 0) + return { + project, + projectPath: project, + sessions, + totalCostUSD, + totalSavingsUSD: 0, + totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0), + totalProxiedCostUSD: 0, + } +} + +const RANGE_A = { from: '2026-03-02', to: '2026-03-08' } +const RANGE_B = { from: '2026-03-09', to: '2026-03-15' } + +// The acceptance fixture: A: X=70, Y=30 → 100. B: X=90, Z=70 → 160. +// Differences X=+20, Y=−30, Z=+70, total=+60. Every complete lens must +// reconcile the global difference before display rounding. +function acceptanceFixture(): { projectsA: ProjectSummary[]; projectsB: ProjectSummary[] } { + return { + projectsA: [ + makeProject('/work/x', [makeSession({ sessionId: 'x1', model: 'model-x', costUSD: 70, calls: 7 })]), + makeProject('/work/y', [makeSession({ sessionId: 'y1', model: 'model-y', costUSD: 30, calls: 3 })]), + ], + projectsB: [ + makeProject('/work/x', [makeSession({ sessionId: 'x1', model: 'model-x', costUSD: 90, calls: 9 })]), + makeProject('/work/z', [makeSession({ sessionId: 'z1', model: 'model-z', costUSD: 70, calls: 7 })]), + ], + } +} + +function lensSum(rows: Array<{ diff: number }>): number { + return rows.reduce((s, row) => s + row.diff, 0) +} + +describe('buildPeriodDiffReport — acceptance fixture', () => { + const { projectsA, projectsB } = acceptanceFixture() + const report = buildPeriodDiffReport({ provider: 'all', rangeA: RANGE_A, rangeB: RANGE_B, projectsA, projectsB }) + + it('reports the global difference B − A', () => { + expect(report.totals.A.cost).toBe(100) + expect(report.totals.B.cost).toBe(160) + expect(report.totals.diff.cost).toBe(60) + expect(report.totals.pct.cost).toBeCloseTo(60, 10) + }) + + it('reconciles the project lens with the global difference', () => { + const x = report.projects.find(row => row.key === '/work/x') + const y = report.projects.find(row => row.key === '/work/y') + const z = report.projects.find(row => row.key === '/work/z') + expect(x).toMatchObject({ costA: 70, costB: 90, diff: 20, status: 'up' }) + expect(y).toMatchObject({ costA: 30, costB: 0, diff: -30, status: 'gone' }) + expect(z).toMatchObject({ costA: 0, costB: 70, diff: 70, status: 'new' }) + expect(y!.pct).toBeCloseTo(-100, 10) + expect(z!.pct).toBeNull() // New: no infinite percentage. + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + }) + + it('reconciles the separate model lens with the same global difference', () => { + const byKey = new Map(report.models.map(row => [row.key, row])) + expect(byKey.get('model-x')!.diff).toBe(20) + expect(byKey.get('model-y')!.diff).toBe(-30) + expect(byKey.get('model-z')!.diff).toBe(70) + expect(lensSum(report.models)).toBeCloseTo(report.totals.diff.cost, 10) + // Lenses are perspectives, not partitions to be summed together — the + // report carries them separately and nothing adds projects + models. + }) + + it('shows both ranges, their duration, and disjointness', () => { + expect(report.rangeA).toMatchObject({ from: '2026-03-02', to: '2026-03-08', days: 7 }) + expect(report.rangeB).toMatchObject({ from: '2026-03-09', to: '2026-03-15', days: 7 }) + expect(report.durationDeltaDays).toBe(0) + expect(report.overlapDays).toBe(0) + }) + + it('normalizes per day and per 100 calls with explicit denominators', () => { + // A: $100 over 10 calls → $10/call → $1000 per 100 calls; B: $160/16 calls. + expect(report.normalized.perDay).toMatchObject({ a: 100 / 7, b: 160 / 7 }) + expect(report.normalized.per100Calls).toMatchObject({ a: 1000, b: 1000, diff: 0 }) + expect(report.normalized.denominators.perDay).toContain('A: 7') + expect(report.normalized.denominators.per100Calls).toContain('calls × 100') + }) +}) + +describe('edge cases', () => { + it('A = 0: every row is New, no percentage is invented, per-100-calls is unavailable', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [], + projectsB: [makeProject('/work/z', [makeSession({ sessionId: 'z1', model: 'model-z', costUSD: 70, calls: 7 })])], + }) + expect(report.totals.A.cost).toBe(0) + expect(report.totals.diff.cost).toBe(70) + expect(report.projects).toHaveLength(1) + expect(report.projects[0]).toMatchObject({ status: 'new', pct: null, diff: 70 }) + expect(report.models[0]).toMatchObject({ status: 'new', pct: null }) + // No calls in A → cost per 100 calls is unavailable, not zero and not ∞. + expect(report.normalized.per100Calls.a).toBeNull() + expect(report.normalized.per100Calls.diff).toBeNull() + // Per-day still works: 0 days with data is a zero denominator too. + expect(report.normalized.perDay.a).toBe(0) + }) + + it('B = 0: every row is Gone, the difference is −A', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/work/y', [makeSession({ sessionId: 'y1', model: 'model-y', costUSD: 30, calls: 3 })])], + projectsB: [], + }) + expect(report.totals.diff.cost).toBe(-30) + expect(report.projects[0]).toMatchObject({ status: 'gone', diff: -30 }) + expect(report.projects[0]!.pct).toBeCloseTo(-100, 10) + expect(report.normalized.per100Calls.b).toBeNull() + }) + + it('ranges of different lengths normalize honestly and report the duration delta', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-03-02', to: '2026-03-08' }, // 7 days + rangeB: { from: '2026-03-09', to: '2026-03-22' }, // 14 days + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', costUSD: 70, calls: 7 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', costUSD: 140, calls: 14 })])], + }) + expect(report.durationDeltaDays).toBe(7) + expect(report.normalized.perDay).toMatchObject({ a: 10, b: 10, diff: 0 }) + // Raw totals doubled, normalized per day did not — the view must show both. + expect(report.totals.diff.cost).toBe(70) + }) + + it('overlapping ranges report their overlap in days', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-03-05', to: '2026-03-11' }, + rangeB: { from: '2026-03-09', to: '2026-03-15' }, + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', costUSD: 1, calls: 1 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', costUSD: 2, calls: 1 })])], + }) + expect(report.overlapDays).toBe(3) // Mar 9, 10, 11. + }) + + it('unpriced models and estimated cost are surfaced as coverage, not hidden', () => { + // 'mystery-model' has calls but no price → cost 0 and it lands in + // unpricedModels via the shared buildPeriodData rules. + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', model: 'mystery-model', costUSD: 0, calls: 4 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', model: 'claude-sonnet-4-5', costUSD: 5, calls: 4 })])], + }) + expect(report.coverage.unpricedModelsA.map(m => m.model)).toContain('mystery-model') + expect(report.coverage.pricingCoverageA).toBeLessThan(1) + }) +}) + +describe('calendar arithmetic', () => { + it('counts days across a month boundary by walking local midnights', () => { + expect(countLocalDays('2026-02-27', '2026-03-03')).toBe(5) + expect(countLocalDays('2026-01-31', '2026-02-01')).toBe(2) + }) + + it('counts days across DST transitions without millisecond math', () => { + // US DST starts 2026-03-08; EU DST starts 2026-10-25 and ends 2026-03-29. + // Whatever the runner's timezone, a calendar walk counts calendar days. + expect(countLocalDays('2026-03-07', '2026-03-09')).toBe(3) + expect(countLocalDays('2026-10-24', '2026-10-26')).toBe(3) + expect(countLocalDays('2026-03-28', '2026-03-30')).toBe(3) + }) + + it('defaults to the last seven complete days vs the seven before', () => { + const ranges = defaultSevenDayRanges(new Date(2026, 2, 15, 12, 0, 0)) // Mar 15 2026, noon local + expect(ranges.B).toEqual({ from: '2026-03-08', to: '2026-03-14' }) + expect(ranges.A).toEqual({ from: '2026-03-01', to: '2026-03-07' }) + expect(rangeInfo(ranges.A).days).toBe(7) + expect(rangeInfo(ranges.B).days).toBe(7) + // Today (Mar 15) is deliberately outside both ranges: it is not complete. + }) + + it('rejects inverted ranges as zero days', () => { + expect(countLocalDays('2026-03-10', '2026-03-01')).toBe(0) + }) + + it('round-trips a DateRange through localRangeInfo', () => { + const info = localRangeInfo({ start: new Date(2026, 2, 9), end: new Date(2026, 2, 15, 23, 59, 59, 999) }) + expect(info).toEqual({ from: '2026-03-09', to: '2026-03-15', days: 7 }) + }) +}) + +describe('sessions spanning the A/B boundary', () => { + // The parser hands each range a post-slice tree: the same session carries + // only its in-range calls on each side. The drill-down must join the two + // halves into ONE row keyed by the canonical identity — never two sessions. + it('joins both halves of a boundary-straddling session', () => { + const session = (cost: number, calls: number): SessionSummary => + makeSession({ sessionId: 'straddle-1', model: 'model-x', costUSD: cost, calls, title: 'long run' }) + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/work/x', [session(30, 3)])], + projectsB: [makeProject('/work/x', [session(40, 4)])], + }) + expect(report.projects).toHaveLength(1) + expect(report.projects[0]).toMatchObject({ costA: 30, costB: 40, diff: 10 }) + + const rows = diffSessions( + [makeProject('/work/x', [session(30, 3)])], + [makeProject('/work/x', [session(40, 4)])], + 'project', + '/work/x', + ) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ sessionId: 'straddle-1', costA: 30, costB: 40, diff: 10, callsA: 3, callsB: 4 }) + expect(rows[0]!.identity).toContain('straddle-1') + }) + + it('drills by model across projects and by project across models', () => { + const a = [makeProject('/w1', [makeSession({ sessionId: 's1', modelCosts: { 'm-a': { costUSD: 10, calls: 1 }, 'm-b': { costUSD: 5, calls: 1 } } })])] + const b = [makeProject('/w2', [makeSession({ sessionId: 's2', modelCosts: { 'm-a': { costUSD: 25, calls: 2 } } })])] + // Two DIFFERENT sessions (a bare sessionId is not globally unique — the + // identity includes the project path), so the model lens yields two rows. + const byModel = diffSessions(a, b, 'model', 'm-a') + expect(byModel).toHaveLength(2) + const pairA = byModel.find(row => row.costA === 10) + const pairB = byModel.find(row => row.costB === 25) + expect(pairA).toMatchObject({ costB: 0, diff: -10 }) + expect(pairB).toMatchObject({ costA: 0, diff: 25 }) + expect(lensSum(byModel)).toBe(15) + // m-b exists only in A → its own row, status via negative diff. + const goneModel = diffSessions(a, b, 'model', 'm-b') + expect(goneModel).toHaveLength(1) + expect(goneModel[0]).toMatchObject({ costA: 5, costB: 0, diff: -5 }) + const byProject = diffSessions(a, b, 'project', '/w2') + expect(byProject).toHaveLength(1) + expect(byProject[0]).toMatchObject({ costA: 0, costB: 25 }) + }) +}) + +function day(date: string, cost: number, carried?: true): DailyEntry { + return { + date, + cost, + savingsUSD: 0, + calls: 1, + sessions: 1, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: {}, + ...(carried ? { carried: true as const } : {}), + } +} + +describe('history basis (aggregate-only carried history)', () => { + const cache: DailyCache = { + version: 21, + savingsConfigHash: '', + lastComputedDate: '2026-03-15', + days: [ + day('2026-03-03', 10), // fully explained by detail + day('2026-03-05', 12, true), // sources gone: 12 in history, 0 in detail + day('2026-03-11', 4), // explained + day('2026-03-13', 9, true), // sources gone on the B side + ], + } + + it('lists only the days history holds that session detail cannot explain', () => { + const freshA = [day('2026-03-03', 10)] + const freshB = [day('2026-03-11', 4)] + const basis = historyBasis(cache, RANGE_A, RANGE_B, 'all', freshA, freshB) + expect(basis.aggregateOnly.A).toBeCloseTo(12, 10) + expect(basis.aggregateOnly.B).toBeCloseTo(9, 10) + expect(basis.days.A.map(row => row.date)).toEqual(['2026-03-05']) + expect(basis.days.B.map(row => row.date)).toEqual(['2026-03-13']) + // The totals NEVER include the aggregate-only amount: the detail basis + // stays reconciled with its own lenses. + expect(basis.detailCost.A).toBe(10) + expect(basis.historyCost.A).toBe(22) + }) + + it('never reports a negative unexplained remainder when detail leads history', () => { + const plainCache: DailyCache = { ...cache, days: [day('2026-03-03', 10)] } + const basis = historyBasis(plainCache, RANGE_A, RANGE_B, 'all', [day('2026-03-03', 15)], []) + expect(basis.aggregateOnly.A).toBe(0) + expect(basis.days.A).toHaveLength(0) + }) +}) + +describe('overlap helper', () => { + it('handles disjoint and identical ranges', () => { + expect(overlapDays({ from: '2026-03-01', to: '2026-03-07' }, { from: '2026-03-09', to: '2026-03-15' })).toBe(0) + expect(overlapDays(RANGE_A, RANGE_A)).toBe(7) + }) +})