From f7a66e51f5a4c7ebd2b1fa47bb60d05bc40751ff Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 04:57:27 +0300 Subject: [PATCH 1/6] feat(cli): compare-periods command with a deterministic B-minus-A diff engine Add src/period-diff.ts: pure period-vs-period difference engine. Totals come from the shared buildPeriodData rules; contributions per project and per model carry status new/gone/up/down/flat with pct=null at A=0 (labeled New, never an infinite percentage); normalized views per day and per 100 calls print their denominators; day arithmetic walks local midnights so DST and month boundaries count calendar days. historyBasis cross-checks the durable daily cache and reports aggregate-only carried days separately instead of force-reconciling them into the totals. diffSessions joins the drill-down on the canonical session identity (provider + project path + sessionId), attributing the model's own slice for the model lens. New command: compare-periods --format json|sessions with explicit --from-a/--to-a/--from-b/--to-b (local YYYY-MM-DD, validated loudly) defaulting to the last seven complete days vs the seven before, plus --provider and the existing --project/--exclude filtering. Range slicing reuses parseAllSessions' call-granularity behavior, so a session straddling the boundary contributes to each side by its own calls. Tests: engine fixtures including the X/Y/Z acceptance reconciliation, A=0/B=0, unequal lengths, DST and month walks, carried history, a real-parse boundary session split by call and joined back into one drill-down row, and CLI runs on a temp HOME fixture. --- scripts/perf/goal1-demo-fixture.mjs | 89 ++++ src/main.ts | 120 ++++- src/period-diff.ts | 546 +++++++++++++++++++++++ tests/compare-periods-cli.test.ts | 167 +++++++ tests/period-diff-boundary-parse.test.ts | 106 +++++ tests/period-diff.test.ts | 378 ++++++++++++++++ 6 files changed, 1405 insertions(+), 1 deletion(-) create mode 100644 scripts/perf/goal1-demo-fixture.mjs create mode 100644 src/period-diff.ts create mode 100644 tests/compare-periods-cli.test.ts create mode 100644 tests/period-diff-boundary-parse.test.ts create mode 100644 tests/period-diff.test.ts 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
Pick two ranges and see exactly what drove the change — projects, models, and the sessions behind them.
+ A spans {daysA} {daysA === 1 ? 'day' : 'days'} · B spans {daysB} {daysB === 1 ? 'day' : 'days'} + {delta !== 0 && <> · duration differs by {delta > 0 ? '+' : ''}{delta} {Math.abs(delta) === 1 ? 'day' : 'days'}>} + {overlap > 0 && <> · the ranges overlap on {overlap} {overlap === 1 ? 'day' : 'days'} — overlapping days count in BOTH sides>} + · all differences are B − A +
+ ) +} + +function TotalsCard({ report }: { report: PeriodDiffReport }) { + const rows: Array<{ label: string; get: (t: PeriodDiffReport['totals']['A']) => number }> = [ + { label: 'API-equivalent cost', get: t => t.cost }, + { label: 'API calls', get: t => t.calls }, + { label: 'Sessions', get: t => t.sessions }, + { label: 'Input tokens', get: t => t.inputTokens }, + { label: 'Output tokens', get: t => t.outputTokens }, + { label: 'Cache read tokens', get: t => t.cacheReadTokens }, + { label: 'Cache write tokens', get: t => t.cacheWriteTokens }, + { label: 'Local-model savings', get: t => t.savingsUSD }, + { label: 'Estimated-price cost', get: t => t.estimatedCostUSD }, + ] + const fmt = (label: string, value: number): string => { + if (label.includes('cost') || label.includes('savings')) return formatUsd(value) + if (label.includes('tokens')) return formatCompact(value) + return value.toLocaleString('en-US') + } + return ( ++ Denominators: {report.normalized.denominators.perDay}; {report.normalized.denominators.per100Calls}. +
+Each side's cost divided by its own calendar days (A: {report.rangeA.days}, B: {report.rangeB.days}) — percentages are unchanged by the scale.
+ )} + {view === 'per100Calls' && ( +Each side's cost per 100 of its OWN API calls — efficiency, not scale. A side with zero calls has no cost per call: shown as —.
+ )} +Different range lengths — per-day rows compare daily averages, not totals.
+ )} + {drill && ( +Click a row to inspect the sessions behind it. The project and model lenses describe the SAME global difference from two perspectives — never add them together.
+A session active on both sides of the boundary appears once with its in-range cost on each side — attribution follows each call's own timestamp.
+Each side's cost divided by its own calendar days (A: {report.rangeA.days}, B: {report.rangeB.days}) — percentages are unchanged by the scale.
+Each side's cost divided by its own calendar days (A: {report.rangeA.days}, B: {report.rangeB.days}) — differences and percentages compare these daily averages.
)} {view === 'per100Calls' && (Each side's cost per 100 of its OWN API calls — efficiency, not scale. A side with zero calls has no cost per call: shown as —.
@@ -480,7 +475,7 @@ function LensCard({ {row.key} {norm.a === null ? '—' : formatUsd(norm.a)} {norm.b === null ? '—' : formatUsd(norm.b)} - {norm.diff === null ? '—' : signedUsd(norm.diff)} + {norm.diff === null ? '—' : signedUsd(norm.diff)} {norm.status === 'new' && New} {norm.status === 'gone' && <>Gone {signedPct(norm.pct)}>} @@ -538,7 +533,7 @@ function DrillPanel({ drillKey, ), [rangeA.from, rangeA.to, rangeB.from, rangeB.to, provider, dimension, drillKey, refreshToken], - { memoKey: reportMemoKey('periodcomparesessions', 'week', provider, { from: rangeA.from, to: rangeA.to }, `${dimension}:${drillKey}`) }, + { memoKey: reportMemoKey('periodcomparesessions-v2', 'week', provider, { from: rangeA.from, to: rangeA.to }, JSON.stringify([rangeB.from, rangeB.to, dimension, drillKey])) }, ) if (!report.data) { if (report.error) return+ Session detail only. A further {formatUsd(carriedA)} (A) and {formatUsd(carriedB)} (B) of daily history + has no session detail behind it and is NOT in these totals — see Coverage & basis. +
+ )}