From c03020c56386712b3846f1e5a6ffc6ae8ae6c369 Mon Sep 17 00:00:00 2001
From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com>
Date: Sat, 12 Sep 2026 04:28:58 +0300
Subject: [PATCH 1/4] Add cohort model comparison over an explicit observation
population
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
compare --format cohort-json answers a facet query (models, canonical
projects, activity categories) and, with --model-a/--model-b, a cohort
comparison whose observation is one edit turn driven by exactly one
behavioral model. Cost attributed to the owning model's own calls in the
turn; turns mixing models are excluded, counted, and shown with their
combined cost; $0 on a model without a free-rate rule is unknown cost,
not zero. Percentiles use linear interpolation at (N-1)*p — [1,2,4,8]
gives median 3 and P90 6.8, pinned in tests. The report carries the full
observation list, so every statistic is reproducible from the payload.
--from/--to and --category are additive on the compare command; the
classic json/tui contracts are unchanged.
---
docs/compare-cohorts.md | 86 ++++++
src/compare-cohorts.ts | 440 +++++++++++++++++++++++++++++++
src/main.ts | 56 +++-
tests/cli-compare-cohort.test.ts | 213 +++++++++++++++
tests/compare-cohorts.test.ts | 400 ++++++++++++++++++++++++++++
5 files changed, 1192 insertions(+), 3 deletions(-)
create mode 100644 docs/compare-cohorts.md
create mode 100644 src/compare-cohorts.ts
create mode 100644 tests/cli-compare-cohort.test.ts
create mode 100644 tests/compare-cohorts.test.ts
diff --git a/docs/compare-cohorts.md b/docs/compare-cohorts.md
new file mode 100644
index 00000000..cc9ba7dd
--- /dev/null
+++ b/docs/compare-cohorts.md
@@ -0,0 +1,86 @@
+# Cohort model comparison (Compare → Cohorts)
+
+The classic Compare view answers "how do these two models differ across my whole
+history?" by aggregating everything each model ever did. The **Cohorts** mode —
+new in this change — answers a narrower question: **how do the two models behave
+on the same kind of work, over a population you can inspect?**
+
+## What an observation is (V1 definition)
+
+* An observation is one **edit turn** (a turn that edited files) whose
+ **behavioral calls** carry **exactly one model**. That model owns the
+ observation. "Behavioral call" is CodeBurn's existing definition
+ (`src/behavioral-weight.ts`): real requests, excluding supplementary
+ accounting rows.
+* The **cost attributed to the model** is the recorded cost of *that model's own
+ calls inside the turn*. A session that used several models never transfers the
+ cost of one model to another, and no session total is attributed to a
+ "dominant" model.
+* Edit turns whose behavioral calls span **two or more models** are excluded
+ from both cohorts, counted, and shown with their combined cost.
+* An edit turn with no behavioral model call at all is excluded the same way.
+* A `$0` cost on a model the pricing rules do not declare free (local models,
+ subscription SKUs, explicit zero-rate overrides) is **unknown cost, not zero**:
+ such observations keep their retry/one-shot weight (which needs no pricing)
+ and are counted separately, but stay out of cost percentiles.
+
+The classic mode's formulas are untouched; both modes remain available.
+
+## What the mode shows
+
+In order, before any metric:
+
+1. **Population** — included observations per model, the distinct sessions they
+ come from, excluded turns that mix models (with their combined cost),
+ excluded turns without a behavioral model, and the unknown-cost count.
+2. **Inspect samples** — the declared population itself, one row per
+ observation (timestamp, project, session, category, cost, input / output /
+ context-proxy tokens, retries). Every number on the page is reproducible
+ from this list. Activating a row also hands the sample to the shared
+ navigation when one is registered (`app/renderer/lib/sampleNavigation.ts`);
+ the section is fully usable without it.
+3. **Cost per edit turn** — median, P90, mean over cost-known observations, the
+ one-shot rate and retry rate over the declared population (zero *observed*
+ retries never proves code correctness), and a compact cost histogram whose
+ top bucket is open-ended so outliers are never dropped.
+4. **Token volume** — median/P90 of output, input, and the **context proxy**
+ (input + cache-read tokens — a proxy, never presented as a measured context
+ window).
+
+## Selection and the volume band
+
+The selection covers model A, model B, the interval (a custom date range when
+one is active, otherwise the selected period), one project, and one activity
+category. On the CLI the same selection exists as:
+
+```bash
+codeburn compare --format cohort-json # facets: models, projects, categories
+codeburn compare --format cohort-json \
+ --model-a --model-b \
+ [--period 30days | --from 2026-08-01 --to 2026-08-31] \
+ [--project ]... [--exclude ]... \
+ [--category coding]
+```
+
+The **volume band** narrows the population to observations inside a token range
+(output, input, or the context proxy). A band explicitly excludes — and counts —
+observations that fall outside it **and** observations that carry no token
+measure at all (missing data is never read as "small"). Rates are recomputed
+over the remaining declared population.
+
+## Fixed conventions
+
+* Percentiles use **linear interpolation at position (N-1)·p** — for costs
+ [1, 2, 4, 8] the median is 3 and P90 is 6.8. Pinned by tests on both the core
+ (`tests/compare-cohorts.test.ts`) and the renderer mirror
+ (`app/renderer/lib/cohortStats.test.ts`).
+* No outlier removal, no sample equalizing, no automatic winner: the mode is a
+ descriptive comparison of your own history. N and variation are always shown.
+
+## Population-first contract
+
+The `cohort-json` payload embeds the full observation list per model, so any
+statistic is reproducible from the payload (and from the Inspect samples list)
+without re-running anything. Volume-band math runs in the renderer over that
+list (`app/renderer/lib/cohortStats.ts`, a mirror of the core math with the same
+pinned convention) so band changes are instant.
diff --git a/src/compare-cohorts.ts b/src/compare-cohorts.ts
new file mode 100644
index 00000000..c0a733ba
--- /dev/null
+++ b/src/compare-cohorts.ts
@@ -0,0 +1,440 @@
+// Cohort model comparison: compare two models over EXPLICIT groups of similar
+// work — an explicit, inspectable population of edit-turn observations the user
+// can reproduce, not the classic whole-history aggregate.
+//
+// V1 OBSERVATION DEFINITION (normative, mirrored in docs/compare-cohorts.md):
+// * An observation is one EDIT turn (`turn.hasEdits`) whose behavioral calls
+// (`isBehavioralCall`, src/behavioral-weight.ts) carry EXACTLY ONE distinct
+// model. That model owns the observation.
+// * The cost attributed to the model is the RECORDED cost of that model's own
+// calls inside the turn (`costUSD` summed over the turn's calls of that
+// model only). Costs of any other model in the turn are never transferred,
+// and the session's total cost is never attributed to a dominant model.
+// * Edit turns whose behavioral calls span 2+ distinct models are EXCLUDED
+// from both cohorts, counted, and shown with their combined cost.
+// * An edit turn with zero behavioral calls is excluded the same way (no
+// model can own it).
+// * `costUSD === 0` on a model the existing pricing rules do not declare free
+// (`isExpectedFreeModel`, src/models.ts) is UNKNOWN cost, not zero: such
+// observations keep their retry/one-shot weight (which needs no pricing)
+// and are counted separately, excluded only from cost statistics.
+// The classic compare formulas (src/compare-stats.ts) are untouched.
+
+import type { ClassifiedTurn, ProjectSummary, TaskCategory } from './types.js'
+import { CATEGORY_LABELS } from './types.js'
+import { isBehavioralCall } from './behavioral-weight.js'
+import { callBillableOutputTokens } from './session-output.js'
+import { getShortModelName, isExpectedFreeModel } from './models.js'
+import { aggregateModelStats, findModelStat, type ModelStats } from './compare-stats.js'
+
+// The CLI's cohort branch resolves these through this one dynamic import; both
+// are the classic module's own implementations (single identity source).
+export { aggregateModelStats, findModelStat }
+
+const SYNTHETIC = ''
+
+/// Cost per behavioral model id inside one turn. `` is filtered: it
+/// is accounting text, never a served model.
+function behavioralCostByModel(turn: ClassifiedTurn): Map {
+ const byModel = new Map()
+ for (const call of turn.assistantCalls) {
+ if (!isBehavioralCall(call)) continue
+ if (call.model === SYNTHETIC) continue
+ byModel.set(call.model, (byModel.get(call.model) ?? 0) + call.costUSD)
+ }
+ return byModel
+}
+
+export type CohortObservation = {
+ /** Owning session id. Not globally unique by itself: pair with `project` for
+ * identity, per the app's canonical-identity rules. */
+ sessionId: string
+ /** Project label exactly as reports print it (`ProjectSummary.project`). */
+ project: string
+ timestamp: string
+ category: TaskCategory
+ /** The single behavioral model of the turn (canonical id). */
+ model: string
+ /** Recorded cost of the owning model's calls in this turn. */
+ costUSD: number
+ /** False when costUSD is 0 on a model the pricing rules do not declare free
+ * — a pricing gap, never reported as a $0 observation. */
+ costKnown: boolean
+ retries: number
+ oneShot: boolean
+ /** Token volumes summed over the owning model's calls in the turn. */
+ inputTokens: number
+ outputTokens: number
+ cacheReadTokens: number
+ cacheWriteTokens: number
+ /** inputTokens + cacheReadTokens. An explicit PROXY for context size, not a
+ * measured context window; every UI label must say so. */
+ contextProxyTokens: number
+ /** False when the owning model's calls in the turn report no tokens at all.
+ * Volume bands must exclude and count these, never read them as small. */
+ tokensReported: boolean
+}
+
+export type ExcludedMultiModelTurn = {
+ sessionId: string
+ project: string
+ timestamp: string
+ category: TaskCategory
+ /** Canonical model ids of the turn's behavioral calls (2+). */
+ models: string[]
+ /** Combined recorded cost of all behavioral calls in the turn. Shown so the
+ * user can see what the V1 rule keeps out; attributed to NO cohort. */
+ costUSD: number
+}
+
+export type CohortExclusions = {
+ /** Edit turns in the selection with 2+ distinct behavioral models. */
+ multiModelTurns: ExcludedMultiModelTurn[]
+ /** Edit turns in the selection whose behavioral calls carry no model. */
+ noBehavioralModelTurns: number
+ combinedMultiModelCostUSD: number
+}
+
+export type CohortSelection = {
+ projects: ProjectSummary[]
+ /** Inclusive; undefined = every activity category. */
+ category?: TaskCategory
+}
+
+/**
+ * Walk the selection once and split every edit turn into cohort observations or
+ * exclusions. Both cohorts see the same turn stream, so a mixed session
+ * contributes observations to each of its models and its multi-model turns to
+ * nobody — only to the ONE shared exclusion ledger both reports attach.
+ */
+export function extractCohortObservations(
+ selection: CohortSelection,
+): { perModel: Map; exclusions: CohortExclusions } {
+ const perModel = new Map()
+ const exclusions: CohortExclusions = {
+ multiModelTurns: [],
+ noBehavioralModelTurns: 0,
+ combinedMultiModelCostUSD: 0,
+ }
+
+ const cohortFor = (model: string): CohortObservation[] => {
+ let obs = perModel.get(model)
+ if (!obs) {
+ obs = []
+ perModel.set(model, obs)
+ }
+ return obs
+ }
+
+ for (const project of selection.projects) {
+ for (const session of project.sessions) {
+ for (const turn of session.turns) {
+ if (!turn.hasEdits) continue
+ if (selection.category && turn.category !== selection.category) continue
+
+ const byModel = behavioralCostByModel(turn)
+
+ if (byModel.size === 0) {
+ // Shared ledger: no behavioral model owns this edit turn.
+ exclusions.noBehavioralModelTurns++
+ continue
+ }
+ if (byModel.size > 1) {
+ const models = [...byModel.keys()].sort()
+ const cost = [...byModel.values()].reduce((sum, c) => sum + c, 0)
+ exclusions.multiModelTurns.push({
+ sessionId: session.sessionId,
+ project: project.project,
+ timestamp: turn.timestamp,
+ category: turn.category,
+ models,
+ costUSD: cost,
+ })
+ exclusions.combinedMultiModelCostUSD += cost
+ continue
+ }
+
+ const model = byModel.keys().next().value as string
+ let cost = 0
+ let inputTokens = 0
+ let outputTokens = 0
+ let cacheReadTokens = 0
+ let cacheWriteTokens = 0
+ let tokensReported = false
+ for (const call of turn.assistantCalls) {
+ if (call.model !== model || !isBehavioralCall(call)) continue
+ cost += call.costUSD
+ const callInput = call.usage.inputTokens
+ const callOutput = call.usage.outputTokens
+ const callCacheRead = call.usage.cacheReadInputTokens
+ const callCacheWrite = call.usage.cacheCreationInputTokens
+ inputTokens += callInput
+ outputTokens += callBillableOutputTokens(call)
+ cacheReadTokens += callCacheRead
+ cacheWriteTokens += callCacheWrite
+ if (callInput > 0 || callOutput > 0 || callCacheRead > 0 || callCacheWrite > 0) tokensReported = true
+ }
+
+ // Unknown ≠ zero: reuse the app's own pricing-gap rules (models.ts).
+ const costKnown = cost > 0 || isExpectedFreeModel(model)
+
+ const acc = cohortFor(model)
+ acc.push({
+ sessionId: session.sessionId,
+ project: project.project,
+ timestamp: turn.timestamp,
+ category: turn.category,
+ model,
+ costUSD: cost,
+ costKnown,
+ retries: turn.retries,
+ oneShot: turn.retries === 0,
+ inputTokens,
+ outputTokens,
+ cacheReadTokens,
+ cacheWriteTokens,
+ contextProxyTokens: inputTokens + cacheReadTokens,
+ tokensReported,
+ })
+ }
+ }
+ }
+
+ return { perModel, exclusions }
+}
+
+/// Percentile convention FIXED for this feature (pinned in tests on both the
+/// core and the renderer mirror): sort ascending, position (N-1)*p, linear
+/// interpolation between neighbors. [1, 2, 4, 8] → median 3, P90 6.8.
+export function linearPercentile(sorted: readonly number[], p: number): number | null {
+ if (sorted.length === 0) return null
+ if (sorted.length === 1) return sorted[0] as number
+ const pos = (sorted.length - 1) * p
+ const lower = Math.floor(pos)
+ const upper = Math.ceil(pos)
+ if (lower === upper) return sorted[lower] as number
+ const fraction = pos - lower
+ return (sorted[lower] as number) * (1 - fraction) + (sorted[upper] as number) * fraction
+}
+
+export function medianOf(sorted: readonly number[]): number | null {
+ return linearPercentile(sorted, 0.5)
+}
+
+export type CostHistogram = {
+ /// Half-open buckets [edge[i], edge[i+1]) over the KNOWN costs. The LAST
+ /// bucket is open-ended: outliers are never dropped, they land there and stay
+ /// in every percentile. Empty edges means "everything is $0 (free models)".
+ edges: number[]
+ counts: number[]
+}
+
+const HISTOGRAM_BUCKETS = 8
+
+/** Deterministic linear edges from 0 to the 95th percentile of the known
+ * costs; the top bucket is open-ended so outliers stretch nothing. */
+export function costHistogram(costs: readonly number[]): CostHistogram {
+ if (costs.length === 0) return { edges: [], counts: [] }
+ const sorted = [...costs].sort((a, b) => a - b)
+ const p95 = linearPercentile(sorted, 0.95) ?? 0
+ const top = p95 > 0 ? p95 : 0
+ if (top <= 0) return { edges: [], counts: [costs.length] }
+ const edges: number[] = []
+ for (let i = 1; i < HISTOGRAM_BUCKETS; i++) edges.push((top * i) / HISTOGRAM_BUCKETS)
+ const counts = new Array(HISTOGRAM_BUCKETS).fill(0)
+ for (const cost of costs) {
+ let bucket = 0
+ while (bucket < edges.length && cost >= (edges[bucket] as number)) bucket++
+ counts[bucket]++
+ }
+ return { edges, counts }
+}
+
+export type CohortVolumeStats = {
+ outputMedian: number | null
+ outputP90: number | null
+ inputMedian: number | null
+ inputP90: number | null
+ contextProxyMedian: number | null
+ contextProxyP90: number | null
+ /** Observations with no token measure at all: visible, never read as small. */
+ missingMeasureCount: number
+}
+
+export type CohortStats = {
+ model: string
+ label: string
+ /** Declared population: observations after the selection filters (and after a
+ * volume band when one is active). Every rate below uses THIS denominator. */
+ observationCount: number
+ distinctSessionCount: number
+ /** Retry / one-shot over the declared population (classic meaning: observed
+ * retries only; zero observed retries never proves code correctness). */
+ retryCount: number
+ retryRate: number | null
+ oneShotCount: number
+ oneShotRate: number | null
+ /** Cost statistics over cost-KNOWN observations only. */
+ costKnownCount: number
+ unknownCostCount: number
+ costMedian: number | null
+ costP90: number | null
+ costMean: number | null
+ costHistogram: CostHistogram
+ volume: CohortVolumeStats
+}
+
+export function computeCohortStats(model: string, observations: readonly CohortObservation[]): CohortStats {
+ const knownCosts = observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
+ const knownCostSum = knownCosts.reduce((sum, c) => sum + c, 0)
+ const sessionKeys = new Set(observations.map(o => `${o.project}/${o.sessionId}`))
+ const byMeasure = (pick: (o: CohortObservation) => number) =>
+ observations.filter(o => o.tokensReported).map(pick).sort((a, b) => a - b)
+ const outputTokens = byMeasure(o => o.outputTokens)
+ const inputTokens = byMeasure(o => o.inputTokens)
+ const contextProxy = byMeasure(o => o.contextProxyTokens)
+
+ const retryCount = observations.reduce((sum, o) => sum + o.retries, 0)
+ const oneShotCount = observations.filter(o => o.oneShot).length
+ const n = observations.length
+
+ return {
+ model,
+ label: getShortModelName(model),
+ observationCount: n,
+ distinctSessionCount: sessionKeys.size,
+ retryCount,
+ retryRate: n > 0 ? retryCount / n : null,
+ oneShotCount,
+ oneShotRate: n > 0 ? (oneShotCount / n) * 100 : null,
+ costKnownCount: knownCosts.length,
+ unknownCostCount: n - knownCosts.length,
+ costMedian: medianOf(knownCosts),
+ costP90: linearPercentile(knownCosts, 0.9),
+ costMean: knownCosts.length > 0 ? knownCostSum / knownCosts.length : null,
+ costHistogram: costHistogram(knownCosts),
+ volume: {
+ outputMedian: medianOf(outputTokens),
+ outputP90: linearPercentile(outputTokens, 0.9),
+ inputMedian: medianOf(inputTokens),
+ inputP90: linearPercentile(inputTokens, 0.9),
+ contextProxyMedian: medianOf(contextProxy),
+ contextProxyP90: linearPercentile(contextProxy, 0.9),
+ missingMeasureCount: observations.filter(o => !o.tokensReported).length,
+ },
+ }
+}
+
+// ————— Report contracts (JSON over the IPC bridge) —————
+
+export type CohortModelReport = {
+ model: string
+ label: string
+ stats: CohortStats
+ /** The DECLARED population: every observation the stats above were computed
+ * from, so any number in the report is reproducible from this list. */
+ observations: CohortObservation[]
+ /** Exclusions as seen from this cohort (the same shared ledger on both). */
+ exclusions: {
+ multiModelTurnCount: number
+ combinedMultiModelCostUSD: number
+ noBehavioralModelTurns: number
+ }
+}
+
+export type CohortComparisonReport = {
+ kind: 'cohort-comparison'
+ period: { label: string; provider: string }
+ selection: { projects: string[]; category: string | null; from: string | null; to: string | null }
+ /** Conventions the UI must surface, not bury. */
+ conventions: {
+ percentile: string
+ contextProxy: string
+ attribution: string
+ }
+ modelA: CohortModelReport
+ modelB: CohortModelReport
+}
+
+export type CohortFacets = {
+ kind: 'cohort-facets'
+ /** Models with usage in the population (classic ModelStats shape): one
+ * canonical identity per row (aliases folded), the same list the classic
+ * picker shows, so both Compare modes agree on which models exist. */
+ models: ModelStats[]
+ /** Canonical project identities of the population. */
+ projects: Array<{ project: string; projectPath: string; sessions: number; costUSD: number }>
+ categories: Array<{ id: TaskCategory; label: string }>
+}
+
+export function cohortCategoryOptions(): Array<{ id: TaskCategory; label: string }> {
+ return Object.entries(CATEGORY_LABELS).map(([id, label]) => ({ id: id as TaskCategory, label }))
+}
+
+export function buildCohortComparison(
+ projects: ProjectSummary[],
+ modelA: string,
+ modelB: string,
+ label: string,
+ provider: string,
+ selection: { category?: TaskCategory; from?: string | null; to?: string | null } = {},
+): CohortComparisonReport {
+ const { perModel, exclusions } = extractCohortObservations({ projects, category: selection.category })
+ const sharedExclusions = {
+ multiModelTurnCount: exclusions.multiModelTurns.length,
+ combinedMultiModelCostUSD: exclusions.combinedMultiModelCostUSD,
+ noBehavioralModelTurns: exclusions.noBehavioralModelTurns,
+ }
+
+ const build = (model: string): CohortModelReport => {
+ const observations = perModel.get(model) ?? []
+ return {
+ model,
+ label: getShortModelName(model),
+ stats: computeCohortStats(model, observations),
+ observations,
+ exclusions: sharedExclusions,
+ }
+ }
+
+ return {
+ kind: 'cohort-comparison',
+ period: { label, provider },
+ selection: {
+ projects: [...new Set(projects.map(p => p.project))].sort(),
+ category: selection.category ?? null,
+ from: selection.from ?? null,
+ to: selection.to ?? null,
+ },
+ conventions: {
+ percentile: 'linear interpolation at position (N-1)*p',
+ contextProxy: 'input + cache-read tokens (proxy, not a measured context window)',
+ attribution: 'observation cost = recorded cost of the owning model\'s calls in the turn',
+ },
+ modelA: build(modelA),
+ modelB: build(modelB),
+ }
+}
+
+export function buildCohortFacets(projects: ProjectSummary[]): CohortFacets {
+ const projectMap = new Map()
+ for (const p of projects) {
+ const existing = projectMap.get(p.project)
+ if (existing) {
+ existing.sessions += p.sessions.length
+ existing.costUSD += p.totalCostUSD
+ } else {
+ projectMap.set(p.project, { project: p.project, projectPath: p.projectPath, sessions: p.sessions.length, costUSD: p.totalCostUSD })
+ }
+ }
+ return {
+ kind: 'cohort-facets',
+ models: aggregateModelStats(projects),
+ projects: [...projectMap.values()].sort((a, b) => b.costUSD - a.costUSD),
+ categories: cohortCategoryOptions(),
+ }
+}
+
+export function renderCohortJson(report: CohortComparisonReport | CohortFacets): string {
+ return JSON.stringify(report, null, 2)
+}
diff --git a/src/main.ts b/src/main.ts
index 79e57225..e2e57de6 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -451,6 +451,15 @@ function assertFormat(value: string, allowed: readonly string[], command: string
}
}
+/** Task-category ids (types.ts CATEGORY_LABELS keys), shared with `--task`. */
+function assertCategory(value: string): void {
+ if (value in CATEGORY_LABELS) return
+ process.stderr.write(
+ `codeburn: unknown category "${value}". Valid values: ${Object.keys(CATEGORY_LABELS).join(', ')}.\n`
+ )
+ process.exit(1)
+}
+
type AliasRow = { from: string; to: string }
function toAliasRows(aliases: Record): AliasRow[] {
@@ -2232,16 +2241,57 @@ program
.description('Compare two AI models side-by-side')
.option('-p, --period ', 'Analysis period: today, week, 30days, month, all, lifetime', 'all')
.option('--provider ', 'Filter by provider (e.g. claude, gemini, cursor, copilot)', 'all')
- .option('--format ', 'Output format: tui, json', 'tui')
+ .option('--format ', 'Output format: tui, json, cohort-json', 'tui')
.option('--model-a ', 'First model to compare')
.option('--model-b ', 'Second model to compare')
.option('--project ', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude ', 'Exclude projects matching name (repeatable)', collect, [])
+ .option('--from ', 'Custom range start (YYYY-MM-DD)')
+ .option('--to ', 'Custom range end (YYYY-MM-DD)')
+ .option('--category ', 'cohort-json only: keep edit-turn observations of one activity category')
.action(async (opts) => {
assertProvider(opts.provider, 'compare')
- assertFormat(opts.format, ['tui', 'json'], 'compare')
+ assertFormat(opts.format, ['tui', 'json', 'cohort-json'], 'compare')
await loadPricing()
- const { range, label } = getDateRange(opts.period)
+ const customRange = parseDateRangeFlags(opts.from, opts.to)
+ const { range, label } = customRange
+ ? { range: customRange, label: formatDateRangeLabel(opts.from, opts.to) }
+ : getDateRange(opts.period)
+ if (opts.format === 'cohort-json') {
+ if (opts.category !== undefined) assertCategory(opts.category)
+ const { aggregateModelStats, buildCohortComparison, buildCohortFacets, findModelStat, renderCohortJson } = await import('./compare-cohorts.js')
+ const parsed = await parseAllSessions(range, opts.provider)
+ await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
+ const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
+
+ // Without --model-a/--model-b the cohort format answers the FACET query:
+ // the models, canonical project identities, and activity categories the
+ // desktop cohort pickers are built from (one parse, one contract).
+ if (!opts.modelA && !opts.modelB) {
+ process.stdout.write(renderCohortJson(buildCohortFacets(projects)) + '\n')
+ return
+ }
+ if (!opts.modelA || !opts.modelB) {
+ process.stderr.write('codeburn compare: --model-a and --model-b must be provided together.\n')
+ process.exit(1)
+ }
+ const models = aggregateModelStats(projects)
+ const modelA = findModelStat(models, opts.modelA)
+ const modelB = findModelStat(models, opts.modelB)
+ if (!modelA) {
+ process.stderr.write(`codeburn compare: model not found: "${opts.modelA}".\n`)
+ process.exit(1)
+ }
+ if (!modelB) {
+ process.stderr.write(`codeburn compare: model not found: "${opts.modelB}".\n`)
+ process.exit(1)
+ }
+ process.stdout.write(renderCohortJson(buildCohortComparison(
+ projects, modelA.model, modelB.model, label, opts.provider,
+ { category: opts.category as TaskCategory | undefined, from: opts.from ?? null, to: opts.to ?? null },
+ )) + '\n')
+ return
+ }
if (opts.format === 'json') {
const { aggregateModelStats, buildCompareJson, findModelStat, projectSessionIds, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js')
const parsed = await parseAllSessions(range, opts.provider)
diff --git a/tests/cli-compare-cohort.test.ts b/tests/cli-compare-cohort.test.ts
new file mode 100644
index 00000000..c707802c
--- /dev/null
+++ b/tests/cli-compare-cohort.test.ts
@@ -0,0 +1,213 @@
+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 { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+
+// End-to-end over the real CLI: the cohort branch of `compare` must apply the
+// --project / --exclude / --category / --from--to selection BEFORE computing
+// anything, and the reported statistics must be reproducible from the sample
+// list the same payload carries. Unit tests pin the math; this one proves the
+// selection flags actually reach it.
+
+// Each test spawns `tsx src/cli.ts`, which re-transpiles the CLI per spawn.
+beforeAll(() => {
+ vi.setConfig({ testTimeout: 60_000 })
+})
+
+const SIBLINGS = [
+ { dir: '-Users-gone-alpha', cwd: '/Users/gone/alpha', session: 's-alpha' },
+ { dir: '-Users-gone-beta', cwd: '/Users/gone/beta', session: 's-beta' },
+]
+
+const OPUS = 'claude-opus-4-20250514'
+const SONNET = 'claude-3-5-sonnet-20241022'
+
+let homes: string[] = []
+
+afterEach(async () => {
+ while (homes.length > 0) {
+ const home = homes.pop()
+ if (home) await rm(home, { recursive: true, force: true })
+ }
+})
+
+function assistantLine(session: string, cwd: string, model: string, minutesAgo: number, costWeights: { input: number; output: number } = { input: 90_000, output: 12_000 }): string {
+ return JSON.stringify({
+ type: 'assistant',
+ timestamp: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
+ sessionId: session,
+ cwd,
+ message: {
+ type: 'message', role: 'assistant', model, id: `${session}-${model}-${minutesAgo}`,
+ content: [{ type: 'tool_use', id: `tu-${minutesAgo}`, name: 'Edit', input: {} }],
+ usage: {
+ input_tokens: costWeights.input,
+ output_tokens: costWeights.output,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 300_000,
+ },
+ },
+ })
+}
+
+function userLine(session: string, cwd: string, minutesAgo: number, text = 'please edit the file'): string {
+ return JSON.stringify({
+ type: 'user',
+ timestamp: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
+ sessionId: session,
+ cwd,
+ message: { role: 'user', content: text },
+ })
+}
+
+/**
+ * Two sibling projects:
+ * - alpha: 2 opus edit turns, 1 sonnet edit turn, 1 opus+sonnet MIXED turn
+ * - beta: 1 opus edit turn
+ */
+async function seedHome(): Promise {
+ const home = await mkdtemp(join(tmpdir(), 'codeburn-compare-cohort-'))
+ homes.push(home)
+ const minutes = (n: number) => 5 + n
+ const alphaLines = [
+ userLine('s-alpha', '/Users/gone/alpha', minutes(1)),
+ assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(2)),
+ userLine('s-alpha', '/Users/gone/alpha', minutes(3)),
+ assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(4)),
+ userLine('s-alpha', '/Users/gone/alpha', minutes(5)),
+ assistantLine('s-alpha', '/Users/gone/alpha', SONNET, minutes(6)),
+ // Mixed turn: two assistant lines of different models between user msgs.
+ userLine('s-alpha', '/Users/gone/alpha', minutes(7)),
+ assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(8)),
+ assistantLine('s-alpha', '/Users/gone/alpha', SONNET, minutes(9)),
+ ]
+ const betaLines = [
+ userLine('s-beta', '/Users/gone/beta', minutes(1)),
+ assistantLine('s-beta', '/Users/gone/beta', OPUS, minutes(2)),
+ ]
+ const alphaDir = join(home, '.claude', 'projects', SIBLINGS[0]!.dir)
+ const betaDir = join(home, '.claude', 'projects', SIBLINGS[1]!.dir)
+ await mkdir(alphaDir, { recursive: true })
+ await mkdir(betaDir, { recursive: true })
+ await writeFile(join(alphaDir, `${SIBLINGS[0]!.session}.jsonl`), alphaLines.join('\n') + '\n', 'utf-8')
+ await writeFile(join(betaDir, `${SIBLINGS[1]!.session}.jsonl`), betaLines.join('\n') + '\n', 'utf-8')
+ return home
+}
+
+function runCli(args: string[], home: string) {
+ return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
+ cwd: process.cwd(),
+ env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEBURN_CACHE_DIR: join(home, 'cache'), TZ: 'UTC' },
+ encoding: 'utf-8',
+ timeout: 60_000,
+ })
+}
+
+type CohortReport = {
+ kind: string
+ modelA: { model: string; stats: { observationCount: number; distinctSessionCount: number; costMedian: number | null; costP90: number | null; unknownCostCount: number }; observations: Array<{ costUSD: number; costKnown: boolean; sessionId: string; project: string; category: string }> }
+ modelB: { model: string; stats: { observationCount: number }; observations: unknown[] }
+ conventions: Record
+}
+
+describe('compare --format cohort-json', () => {
+ it('answers the facet query without models: models, canonical projects, categories', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days'], home)
+ expect(result.status).toBe(0)
+ // tsx emits a Node deprecation line on stderr; the meaningful assertion is
+ // that no codeburn-level warning (e.g. an unmatched project pattern) fired.
+ expect(result.stderr).not.toContain('codeburn')
+ const facets = JSON.parse(result.stdout)
+ expect(facets.kind).toBe('cohort-facets')
+ expect(facets.models.map((m: { model: string }) => m.model).sort()).toEqual([OPUS, SONNET].sort())
+ expect(facets.projects.map((p: { project: string }) => p.project).sort())
+ .toEqual(['-Users-gone-alpha', '-Users-gone-beta'])
+ expect(facets.categories.length).toBeGreaterThan(5)
+ })
+
+ it('attributes each single-model edit turn to its own model and reports the mixed turn as excluded', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET], home)
+ expect(result.status).toBe(0)
+ const report = JSON.parse(result.stdout) as CohortReport
+ expect(report.kind).toBe('cohort-comparison')
+ // alpha: 2 opus turns + beta: 1 opus turn = 3 observations; the mixed turn
+ // belongs to NOBODY. Sonnet: 1 single-model turn.
+ expect(report.modelA.stats.observationCount).toBe(3)
+ expect(report.modelB.stats.observationCount).toBe(1)
+ expect(report.modelA.observations).toHaveLength(3)
+ // Reproducibility: the median is recomputable from the sample list.
+ const costs = report.modelA.observations.map(o => o.costUSD).sort((a, b) => a - b)
+ const median = costs.length % 2 === 1
+ ? costs[(costs.length - 1) / 2]
+ : (costs[costs.length / 2 - 1]! + costs[costs.length / 2]!) / 2
+ expect(report.modelA.stats.costMedian).toBeCloseTo(median, 10)
+ expect(report.modelA.stats.distinctSessionCount).toBe(2)
+ // Conventions are part of the payload, not folklore.
+ expect(report.conventions.attribution).toContain('owning model')
+ })
+
+ it('lets a rooted --project exclude observations before any statistic is computed', async () => {
+ const home = await seedHome()
+ const filtered = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET, '--project', '/Users/gone/alpha'], home)
+ expect(filtered.status).toBe(0)
+ const report = JSON.parse(filtered.stdout) as CohortReport
+ expect(report.modelA.stats.observationCount).toBe(2)
+ expect(report.modelA.observations.every(o => o.project === '-Users-gone-alpha')).toBe(true)
+ // And the payload's selection records the restriction.
+ expect(JSON.parse(filtered.stdout).selection.projects).toEqual(['-Users-gone-alpha'])
+ })
+
+ it('reports zero-observation cohorts with null stats instead of zeros when a category keeps nothing', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET, '--category', 'testing'], home)
+ expect(result.status).toBe(0)
+ const report = JSON.parse(result.stdout) as CohortReport
+ expect(report.modelA.stats.observationCount).toBe(0)
+ expect(report.modelA.stats.costMedian).toBeNull()
+ expect(report.modelA.observations).toEqual([])
+ expect(report.modelB.stats.observationCount).toBe(0)
+ })
+
+ it('rejects an unknown category with a usable message', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--category', 'not-a-category'], home)
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('unknown category "not-a-category"')
+ })
+
+ it('rejects an unknown model like the classic format does', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', 'nope-1', '--model-b', OPUS], home)
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('model not found: "nope-1"')
+ })
+
+ it('accepts an explicit --from/--to interval', async () => {
+ const home = await seedHome()
+ const from = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
+ const to = new Date().toISOString().slice(0, 10)
+ const result = runCli(['compare', '--format', 'cohort-json', '--model-a', OPUS, '--model-b', SONNET, '--from', from, '--to', to], home)
+ expect(result.status).toBe(0)
+ const report = JSON.parse(result.stdout) as CohortReport & { selection: { from: string; to: string } }
+ expect(report.selection.from).toBe(from)
+ expect(report.selection.to).toBe(to)
+ expect(report.modelA.stats.observationCount).toBe(3)
+ })
+
+ it('leaves the classic json contract untouched (an array of ModelStats)', async () => {
+ const home = await seedHome()
+ const result = runCli(['compare', '--format', 'json', '--period', '30days'], home)
+ expect(result.status).toBe(0)
+ const classic = JSON.parse(result.stdout)
+ expect(Array.isArray(classic)).toBe(true)
+ expect(classic.map((m: { model: string }) => m.model).sort()).toEqual([OPUS, SONNET].sort())
+ // Classic rows carry the classic fields, untouched by the cohort work.
+ expect(classic[0]).toHaveProperty('editTurns')
+ expect(classic[0]).toHaveProperty('editCost')
+ expect(classic[0]).not.toHaveProperty('observations')
+ })
+})
diff --git a/tests/compare-cohorts.test.ts b/tests/compare-cohorts.test.ts
new file mode 100644
index 00000000..3fbbcf98
--- /dev/null
+++ b/tests/compare-cohorts.test.ts
@@ -0,0 +1,400 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ buildCohortComparison,
+ buildCohortFacets,
+ computeCohortStats,
+ costHistogram,
+ extractCohortObservations,
+ linearPercentile,
+ medianOf,
+ type CohortObservation,
+} from '../src/compare-cohorts.js'
+import { findModelStat } from '../src/compare-stats.js'
+import { getShortModelName } from '../src/models.js'
+import type { ClassifiedTurn, ProjectSummary, SessionSummary } from '../src/types.js'
+
+let keySeq = 0
+
+function makeTurn(model: string | string[], cost: number, opts: {
+ hasEdits?: boolean
+ retries?: number
+ category?: string
+ timestamp?: string
+ sessionId?: string
+ outputTokens?: number
+ inputTokens?: number
+ unpriced?: boolean
+ extraCalls?: Array<{ model: string; cost: number }>
+} = {}): ClassifiedTurn {
+ const models = Array.isArray(model) ? model : [model]
+ const calls = models.map((m, i) => ({
+ provider: 'claude',
+ model: m,
+ usage: {
+ inputTokens: opts.inputTokens ?? 1200,
+ outputTokens: opts.outputTokens ?? 300,
+ cacheCreationInputTokens: 400,
+ cacheReadInputTokens: 5000,
+ cachedInputTokens: 0,
+ reasoningTokens: 0,
+ webSearchRequests: 0,
+ },
+ costUSD: i === 0 ? cost : 0,
+ tools: opts.hasEdits === false ? ['Read'] : ['Edit'],
+ mcpTools: [],
+ skills: [],
+ subagentTypes: [],
+ hasAgentSpawn: false,
+ hasPlanMode: false,
+ speed: 'standard' as const,
+ timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
+ bashCommands: [],
+ deduplicationKey: `key-${keySeq++}`,
+ }))
+ for (const extra of opts.extraCalls ?? []) {
+ calls.push({
+ provider: 'claude',
+ model: extra.model,
+ usage: {
+ inputTokens: 1000,
+ outputTokens: 250,
+ cacheCreationInputTokens: 0,
+ cacheReadInputTokens: 4000,
+ cachedInputTokens: 0,
+ reasoningTokens: 0,
+ webSearchRequests: 0,
+ },
+ costUSD: extra.cost,
+ tools: ['Edit'],
+ mcpTools: [],
+ skills: [],
+ subagentTypes: [],
+ hasAgentSpawn: false,
+ hasPlanMode: false,
+ speed: 'standard' as const,
+ timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
+ bashCommands: [],
+ deduplicationKey: `key-${keySeq++}`,
+ })
+ }
+ return {
+ timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
+ category: (opts.category ?? 'coding') as ClassifiedTurn['category'],
+ retries: opts.retries ?? 0,
+ hasEdits: opts.hasEdits ?? true,
+ userMessage: '',
+ sessionId: opts.sessionId ?? 'sess-1',
+ assistantCalls: calls,
+ }
+}
+
+function makeSession(sessionId: string, turns: ClassifiedTurn[]): SessionSummary {
+ return {
+ sessionId,
+ project: 'proj-a',
+ firstTimestamp: turns[0]?.timestamp ?? '',
+ lastTimestamp: turns[turns.length - 1]?.timestamp ?? '',
+ totalCostUSD: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalCacheReadTokens: 0,
+ totalCacheWriteTokens: 0,
+ apiCalls: turns.reduce((s, t) => s + t.assistantCalls.length, 0),
+ turns,
+ modelBreakdown: {},
+ toolBreakdown: {},
+ mcpBreakdown: {},
+ bashBreakdown: {},
+ categoryBreakdown: {} as SessionSummary['categoryBreakdown'],
+ skillBreakdown: {} as SessionSummary['skillBreakdown'],
+ }
+}
+
+function makeProject(sessionId: string, turns: ClassifiedTurn[], project = 'proj-a'): ProjectSummary {
+ const session = makeSession(sessionId, turns)
+ session.project = project
+ return {
+ project,
+ projectPath: `/work/${project}`,
+ sessions: [session],
+ totalCostUSD: 0,
+ totalProxiedCostUSD: 0,
+ totalApiCalls: session.apiCalls,
+ }
+}
+
+// ————— The pinned percentile convention —————
+
+describe('percentile convention (pinned)', () => {
+ it('gives median 3 and P90 6.8 for [1, 2, 4, 8] with linear interpolation at (N-1)*p', () => {
+ const sorted = [1, 2, 4, 8]
+ expect(medianOf(sorted)).toBe(3)
+ expect(linearPercentile(sorted, 0.9)).toBeCloseTo(6.8, 10)
+ })
+
+ it('interpolates at exact positions without rounding', () => {
+ expect(linearPercentile([10, 20], 0.5)).toBe(15)
+ expect(linearPercentile([10], 0.9)).toBe(10)
+ expect(linearPercentile([], 0.9)).toBeNull()
+ })
+})
+
+// ————— Observation extraction —————
+
+describe('extractCohortObservations', () => {
+ it('owns an edit turn by its single behavioral model and attributes only that model\'s cost', () => {
+ // One turn: opus behavioral call ($0.10) + sonnet behavioral call ($0.05)
+ // would be MULTI-model; here instead: opus call costs 0.10, a second call
+ // of the SAME model adds 0.02 — both belong to the observation.
+ const project = makeProject('s1', [
+ makeTurn('opus-4-6', 0.10, { extraCalls: [{ model: 'opus-4-6', cost: 0.02 }] }),
+ ])
+ const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
+ const obs = perModel.get('opus-4-6')!
+ expect(obs).toHaveLength(1)
+ expect(obs[0]!.costUSD).toBeCloseTo(0.12)
+ expect(obs[0]!.model).toBe('opus-4-6')
+ // No other model gets an observation; nothing was excluded.
+ expect(perModel.size).toBe(1)
+ expect(exclusions.multiModelTurns).toHaveLength(0)
+ })
+
+ it('excludes multi-model edit turns and transfers no cost to either model', () => {
+ const project = makeProject('s1', [
+ makeTurn(['opus-4-6', 'sonnet-5'], 0.10, { extraCalls: [{ model: 'sonnet-5', cost: 0.05 }] }),
+ makeTurn('opus-4-6', 0.10),
+ ])
+ const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
+ // The mixed turn is counted once, shown with combined cost 0.15, and NO
+ // cohort receives any of it. opus keeps only its own single-model turn.
+ expect(exclusions.multiModelTurns).toHaveLength(1)
+ expect(exclusions.multiModelTurns[0]!.models).toEqual(['opus-4-6', 'sonnet-5'])
+ expect(exclusions.combinedMultiModelCostUSD).toBeCloseTo(0.15)
+ expect(perModel.get('opus-4-6')).toHaveLength(1)
+ expect(perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.10)
+ expect(perModel.has('sonnet-5')).toBe(false)
+ })
+
+ it('reports one shared exclusion ledger even when a cohort has zero observations', () => {
+ const project = makeProject('s1', [
+ makeTurn(['opus-4-6', 'mystery-pro-9'], 0.10, { extraCalls: [{ model: 'mystery-pro-9', cost: 0.05 }] }),
+ ])
+ const { exclusions } = extractCohortObservations({ projects: [project] })
+ expect(exclusions.multiModelTurns).toHaveLength(1)
+ })
+
+ it('counts edit turns with no behavioral model', () => {
+ const turn = makeTurn('opus-4-6', 0)
+ turn.assistantCalls[0]!.supplementaryAccounting = true
+ const project = makeProject('s1', [turn])
+ const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
+ expect(exclusions.noBehavioralModelTurns).toBe(1)
+ expect(perModel.size).toBe(0)
+ })
+
+ it('respects the category selection before anything is counted', () => {
+ const project = makeProject('s1', [
+ makeTurn('opus-4-6', 0.10, { category: 'coding' }),
+ makeTurn('opus-4-6', 0.20, { category: 'debugging' }),
+ ])
+ const coding = extractCohortObservations({ projects: [project], category: 'coding' })
+ expect(coding.perModel.get('opus-4-6')).toHaveLength(1)
+ expect(coding.perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.10)
+
+ const debugging = extractCohortObservations({ projects: [project], category: 'debugging' })
+ expect(debugging.perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.20)
+ })
+
+ it('skips non-edit turns entirely', () => {
+ const project = makeProject('s1', [makeTurn('opus-4-6', 0.10, { hasEdits: false })])
+ const { perModel } = extractCohortObservations({ projects: [project] })
+ expect(perModel.size).toBe(0)
+ })
+
+ it('pairs project and session for identity (a bare sessionId is not a global key)', () => {
+ const p1 = makeProject('same-id', [makeTurn('opus-4-6', 0.10)], 'proj-a')
+ const p2 = makeProject('same-id', [makeTurn('opus-4-6', 0.10)], 'proj-b')
+ const stats = computeCohortStats('opus-4-6', [
+ ...(extractCohortObservations({ projects: [p1] }).perModel.get('opus-4-6') ?? []),
+ ...(extractCohortObservations({ projects: [p2] }).perModel.get('opus-4-6') ?? []),
+ ])
+ // Two sessions share the literal id; distinct sessions must be 2.
+ expect(stats.distinctSessionCount).toBe(2)
+ expect(stats.observationCount).toBe(2)
+ })
+})
+
+// ————— Cost semantics: unknown ≠ zero —————
+
+describe('unknown cost handling', () => {
+ it('marks an unpriced model\'s $0 observations as unknown and keeps them out of cost stats but in retry stats', () => {
+ const project = makeProject('s1', [
+ makeTurn('mystery-pro-9', 0, { retries: 3 }),
+ makeTurn('mystery-pro-9', 0, { retries: 0 }),
+ ])
+ const { perModel } = extractCohortObservations({ projects: [project] })
+ const obs = perModel.get('mystery-pro-9')!
+ expect(obs.every(o => !o.costKnown)).toBe(true)
+ const stats = computeCohortStats('mystery-pro-9', obs)
+ expect(stats.observationCount).toBe(2)
+ expect(stats.unknownCostCount).toBe(2)
+ expect(stats.costKnownCount).toBe(0)
+ expect(stats.costMedian).toBeNull()
+ expect(stats.costP90).toBeNull()
+ // Retry statistics never need pricing: they still count.
+ expect(stats.retryCount).toBe(3)
+ expect(stats.oneShotCount).toBe(1)
+ expect(stats.retryRate).toBeCloseTo(1.5)
+ })
+
+ it('keeps legitimately free models (local / flat-rate) as known-zero cost', () => {
+ const project = makeProject('s1', [makeTurn('qwen3:35b', 0)])
+ const { perModel } = extractCohortObservations({ projects: [project] })
+ const obs = perModel.get('qwen3:35b')!
+ expect(obs[0]!.costKnown).toBe(true)
+ const stats = computeCohortStats('qwen3:35b', obs)
+ expect(stats.unknownCostCount).toBe(0)
+ expect(stats.costMedian).toBe(0)
+ })
+})
+
+// ————— Cohort statistics —————
+
+describe('computeCohortStats', () => {
+ function obs(cost: number, over: Partial = {}): CohortObservation {
+ return {
+ sessionId: 's1',
+ project: 'proj-a',
+ timestamp: '2026-08-15T10:00:00Z',
+ category: 'coding',
+ model: 'opus-4-6',
+ costUSD: cost,
+ costKnown: true,
+ retries: 0,
+ oneShot: true,
+ inputTokens: 1000,
+ outputTokens: 500,
+ cacheReadTokens: 2000,
+ cacheWriteTokens: 100,
+ contextProxyTokens: 3000,
+ tokensReported: true,
+ ...over,
+ }
+ }
+
+ it('produces the pinned [1,2,4,8] convention through the full stats path', () => {
+ const stats = computeCohortStats('opus-4-6', [obs(1), obs(2), obs(4), obs(8)])
+ expect(stats.costMedian).toBe(3)
+ expect(stats.costP90).toBeCloseTo(6.8, 10)
+ })
+
+ it('handles N=0 with nulls and no NaN anywhere', () => {
+ const stats = computeCohortStats('opus-4-6', [])
+ expect(stats.observationCount).toBe(0)
+ expect(stats.costMedian).toBeNull()
+ expect(stats.costP90).toBeNull()
+ expect(stats.retryRate).toBeNull()
+ expect(stats.oneShotRate).toBeNull()
+ expect(stats.costHistogram.counts).toEqual([])
+ expect(stats.volume.outputMedian).toBeNull()
+ expect(JSON.stringify(stats)).not.toContain('NaN')
+ })
+
+ it('handles N=1: median and P90 both equal the single value', () => {
+ const stats = computeCohortStats('opus-4-6', [obs(0.42)])
+ expect(stats.costMedian).toBeCloseTo(0.42)
+ expect(stats.costP90).toBeCloseTo(0.42)
+ expect(stats.oneShotRate).toBe(100)
+ })
+
+ it('keeps a huge outlier in every statistic and the histogram top bucket', () => {
+ const costs = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 5.0]
+ const stats = computeCohortStats('opus-4-6', costs.map(c => obs(c)))
+ // Outlier still in the population and the percentiles.
+ expect(stats.observationCount).toBe(10)
+ expect(stats.costP90).toBeGreaterThan(0.09)
+ expect(stats.costMedian).toBeCloseTo(0.055)
+ const hist = stats.costHistogram
+ expect(hist.counts.reduce((a, b) => a + b, 0)).toBe(10)
+ // The 95th-percentile edge pushes the outlier into the last bucket.
+ expect(hist.counts[hist.counts.length - 1]).toBeGreaterThanOrEqual(1)
+ })
+
+ it('handles very unequal groups by never inventing values for the small one', () => {
+ const big = Array.from({ length: 50 }, (_, i) => obs(0.01 * (i + 1)))
+ const stats = computeCohortStats('opus-4-6', big)
+ expect(stats.observationCount).toBe(50)
+ expect(stats.costMedian).toBeCloseTo(0.255)
+ const tiny = computeCohortStats('sonnet-5', [obs(0.9, { model: 'sonnet-5' })])
+ expect(tiny.observationCount).toBe(1)
+ })
+
+ it('computes volume percentiles only over observations that report tokens', () => {
+ const withTokens = obs(0.10)
+ const without = obs(0.10, { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, tokensReported: false })
+ const stats = computeCohortStats('opus-4-6', [withTokens, without])
+ expect(stats.volume.missingMeasureCount).toBe(1)
+ expect(stats.volume.outputMedian).toBe(500)
+ // Cost statistics still cover BOTH observations (cost is known for both).
+ expect(stats.costKnownCount).toBe(2)
+ })
+
+ it('is reproducible from the report\'s observation list', () => {
+ const project = makeProject('s1', [
+ makeTurn('opus-4-6', 0.10, { retries: 1 }),
+ makeTurn('opus-4-6', 0.30, { retries: 0 }),
+ makeTurn('sonnet-5', 0.05, { retries: 2 }),
+ ])
+ const report = buildCohortComparison([project], 'opus-4-6', 'sonnet-5', 'Test label', 'claude')
+ // Recompute the medians from the reported sample lists; they must match.
+ for (const side of [report.modelA, report.modelB]) {
+ const known = side.observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
+ const recomputed = medianOf(known)
+ expect(recomputed).toBeCloseTo(side.stats.costMedian ?? NaN)
+ expect(side.stats.observationCount).toBe(side.observations.length)
+ }
+ })
+})
+
+// ————— Histogram determinism —————
+
+describe('costHistogram', () => {
+ it('is deterministic and totals the population', () => {
+ const costs = [0.1, 0.2, 0.3, 0.4, 0.5]
+ const h1 = costHistogram(costs)
+ const h2 = costHistogram([...costs].reverse())
+ expect(h1).toEqual(h2)
+ expect(h1.counts.reduce((a, b) => a + b, 0)).toBe(costs.length)
+ })
+
+ it('collapses to a single bucket when every cost is zero', () => {
+ const h = costHistogram([0, 0, 0])
+ expect(h.edges).toEqual([])
+ expect(h.counts).toEqual([3])
+ })
+})
+
+// ————— Facets and alias resolution —————
+
+describe('facets and model identity', () => {
+ it('lists canonical project identities once with merged session counts', () => {
+ const p1 = makeProject('s1', [makeTurn('opus-4-6', 0.10)], 'proj-a')
+ const p2 = makeProject('s2', [makeTurn('opus-4-6', 0.10)], 'proj-a')
+ const facets = buildCohortFacets([p1, p2])
+ expect(facets.projects).toHaveLength(1)
+ expect(facets.projects[0]!.sessions).toBe(2)
+ expect(facets.categories.length).toBeGreaterThan(5)
+ })
+
+ it('resolves display-name aliases to the canonical id like the classic picker', () => {
+ const project = makeProject('s1', [makeTurn('claude-opus-4-6-20260610', 0.10)])
+ const facets = buildCohortFacets([project])
+ const canonical = facets.models[0]!.model
+ expect(canonical).toBe('claude-opus-4-6-20260610')
+ // findModelStat is the shared alias-aware lookup; a display name like
+ // "Opus 4.6" resolves to the same canonical row.
+ const byDisplay = findModelStat(facets.models, getShortModelName(canonical))
+ expect(byDisplay?.model).toBe(canonical)
+ })
+})
From 9a383dca30e7e9929f69770fad45d4731e9b7dcc Mon Sep 17 00:00:00 2001
From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com>
Date: Sat, 12 Sep 2026 04:29:14 +0300
Subject: [PATCH 2/4] Add Compare cohorts mode with population disclosure,
samples, and volume band
Desktop cohorts mode talks to the new cohort-json format through two
typed bridge channels (facets + report) with argv validation for models,
repeatable project patterns, and categories. The section keeps the
classic mode side by side; the cohorts view shows the population before
any metric (included observations, distinct sessions, excluded mixed-
model turns with their combined cost, unknown-cost count), an Inspect
samples list of the declared population through a minimal navigation
adapter (sampleNavigation.ts), cost median/P90/mean with a compact
histogram whose top bucket is open-ended, one-shot/retry rates over the
declared population, and token volume with input + cache-read labeled as
a context proxy. The volume band recomputes renderer-side over the
report's own observation list (cohortStats.ts mirrors the core
convention, pinned to the same test vector), excludes and counts
observations without a token measure, and never reads missing data as
small. CODEBURN_USER_DATA_DIR opts into an isolated Electron profile so
parallel dev runs get their own userData/serve.pid.
---
app/electron/main.test.ts | 8 +
app/electron/main.ts | 42 ++
app/electron/preload.ts | 3 +
app/renderer/lib/cohortStats.test.ts | 111 ++++++
app/renderer/lib/cohortStats.ts | 134 +++++++
app/renderer/lib/sampleNavigation.ts | 36 ++
app/renderer/lib/types.ts | 98 +++++
app/renderer/sections/Compare.test.tsx | 168 +++++++-
app/renderer/sections/Compare.tsx | 516 ++++++++++++++++++++++++-
app/renderer/styles/plain.css | 25 ++
10 files changed, 1137 insertions(+), 4 deletions(-)
create mode 100644 app/renderer/lib/cohortStats.test.ts
create mode 100644 app/renderer/lib/cohortStats.ts
create mode 100644 app/renderer/lib/sampleNavigation.ts
diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts
index 9a7111f1..f1dff516 100644
--- a/app/electron/main.test.ts
+++ b/app/electron/main.test.ts
@@ -47,6 +47,8 @@ const CHANNELS = [
'codeburn:getCompare',
'codeburn:getPeriodCompare',
'codeburn:getPeriodCompareSessions',
+ 'codeburn:getCompareCohortModels',
+ 'codeburn:getCompareCohort',
'codeburn:getYield',
'codeburn:getSpendFlow',
'codeburn:getBranchSpend',
@@ -114,6 +116,9 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> =
// Claude sanitizes project paths to dash-leading slugs; the key rides in the
// VALUE position of --key, so a dash-leading key must survive validation.
{ channel: 'codeburn:getPeriodCompareSessions', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all', 'project', '-work-pricing'], argv: ['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--dimension', 'project', '--key', '-work-pricing'] },
+ { channel: 'codeburn:getCompareCohortModels', args: ['month', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] },
+ { channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b'] },
+ { channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha', 'loose-word'], 'coding'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b', '--project', '/Users/gone/alpha', '--project', 'loose-word', '--category', 'coding'] },
{ channel: 'codeburn:getYield', args: ['today', 'all'], argv: ['yield', '--format', 'json', '--period', 'today'] },
{ channel: 'codeburn:getYield', args: ['today', 'claude'], argv: ['yield', '--format', 'json', '--period', 'today', '--provider', 'claude'] },
{ channel: 'codeburn:getSpendFlow', args: ['month', 'openai'], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--provider', 'openai'] },
@@ -261,6 +266,9 @@ describe('createBridgeHandlers (IPC input validation)', () => {
{ name: 'device name that looks like a flag', channel: 'codeburn:removeDevice', args: ['-rf'] },
{ name: 'relative export path', channel: 'codeburn:exportData', args: ['json', 'all', 'relative/out'] },
{ name: 'compare model that looks like a flag', channel: 'codeburn:getCompare', args: ['month', 'all', '-a', 'model-b'] },
+ { name: 'cohort model that looks like a flag', channel: 'codeburn:getCompareCohort', args: ['month', 'all', '-a', 'model-b'] },
+ { name: 'cohort project pattern that looks like a flag', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['-rf']] },
+ { name: 'unknown cohort category', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, undefined, 'not-a-category'] },
{ name: 'price override model that looks like a flag', channel: 'codeburn:setPriceOverride', args: ['-x', { input: 1, output: 2 }] },
{ name: 'non-positive price override rate', channel: 'codeburn:setPriceOverride', args: ['my-model', { input: 0, output: 2 }] },
{ name: 'non-finite price override rate', channel: 'codeburn:setPriceOverride', args: ['my-model', { input: 1, output: Number.POSITIVE_INFINITY }] },
diff --git a/app/electron/main.ts b/app/electron/main.ts
index b73a63bc..71ea8bdd 100644
--- a/app/electron/main.ts
+++ b/app/electron/main.ts
@@ -314,6 +314,29 @@ function vToken(value: string): string {
if (value.startsWith('-')) throw new CliError('bad-args', 'argument must not start with "-"')
return value
}
+// Project filter patterns reach the CLI as repeatable --project values. An
+// absolute path starts with "/", a loose word must not start with "-" (that
+// would read as a flag); anything else is refused before it becomes argv.
+function vProjectPatterns(projects: string[] | undefined): string[] {
+ if (!projects || projects.length === 0) return []
+ for (const pattern of projects) {
+ if (typeof pattern !== 'string' || pattern.length === 0 || pattern.startsWith('-')) {
+ throw new CliError('bad-args', 'invalid project pattern')
+ }
+ }
+ return projects.flatMap(pattern => ['--project', pattern])
+}
+// Activity categories for the cohort selection: the ids behind the CLI's
+// --category (src/types.ts CATEGORY_LABELS keys). Duplicated here because the
+// main process deliberately does not import core src/ modules.
+const COHORT_CATEGORIES = new Set([
+ 'coding', 'debugging', 'feature', 'refactoring', 'testing', 'exploration',
+ 'planning', 'delegation', 'git', 'build/deploy', 'conversation', 'brainstorming', 'general',
+])
+function vCategory(category: string): string {
+ if (!COHORT_CATEGORIES.has(category)) throw new CliError('bad-args', 'invalid category')
+ return category
+}
// Claude config source ids are `:` (src/providers/claude.ts) — the
// colon is part of the real value, so the token class allows it while anchoring
// the first char to alphanumeric so a leading "-" can never smuggle a flag.
@@ -600,6 +623,17 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
'--dimension', dimension, '--key', vContributionKey(key),
]
}),
+ // Cohort mode: the facet query (models/projects/categories) and the report
+ // for two models over an explicit selection. Same `compare` command, new
+ // cohort-json format; --project stays repeatable, category is one id.
+ 'codeburn:getCompareCohortModels': run((period: string, provider: string, range?: DateRange) => [
+ 'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)), ...rangeArgs(vRange(range)),
+ ], 3),
+ 'codeburn:getCompareCohort': run((period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string) => [
+ 'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
+ '--model-a', vToken(modelA), '--model-b', vToken(modelB), ...rangeArgs(vRange(range)),
+ ...(vProjectPatterns(projects)), ...(category ? ['--category', vCategory(category)] : []),
+ ], 7),
'codeburn:getYield': run((period: string, provider: string, range?: DateRange) => [
'yield', '--format', 'json', '--period', vPeriod(period),
...providerArgs(vProvider(provider)),
@@ -903,6 +937,14 @@ function bootstrap(): void {
console.error('Unhandled promise rejection in main process:', reason)
})
+ // Opt-in profile isolation for parallel dev/verification runs: a distinct
+ // userData dir also isolates serve.pid, the single-instance lock and telemetry
+ // state, so two checkouts can run Electron side by side. Unset by default —
+ // normal launches keep the OS default profile.
+ if (process.env.CODEBURN_USER_DATA_DIR) {
+ app.setPath('userData', process.env.CODEBURN_USER_DATA_DIR)
+ }
+
// Packaged builds ship their own version-matched CLI under resources/cli (the
// afterPack hook copies it in). Point the resolver at the launch shim before
// any handler spawns; cli.ts runs it with Electron-as-node. The shim, not
diff --git a/app/electron/preload.ts b/app/electron/preload.ts
index 32a4a927..8e0fd999 100644
--- a/app/electron/preload.ts
+++ b/app/electron/preload.ts
@@ -31,6 +31,9 @@ const bridge = {
getCompare: (period: string, provider: string, modelA: string, modelB: string) => invoke('codeburn:getCompare', period, provider, modelA, modelB),
getPeriodCompare: (rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean) => invoke('codeburn:getPeriodCompare', rangeA, rangeB, provider, background),
getPeriodCompareSessions: (rangeA: DateRange, rangeB: DateRange, provider: string, dimension: string, key: string) => invoke('codeburn:getPeriodCompareSessions', rangeA, rangeB, provider, dimension, key),
+ getCompareCohortModels: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getCompareCohortModels', period, provider, range, background),
+ getCompareCohort: (period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string, background?: boolean) =>
+ invoke('codeburn:getCompareCohort', period, provider, modelA, modelB, range, projects, category, background),
getYield: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getYield', period, provider, range, background),
getSpendFlow: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getSpendFlow', period, provider, range, background),
getBranchSpend: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getBranchSpend', period, provider, range, background),
diff --git a/app/renderer/lib/cohortStats.test.ts b/app/renderer/lib/cohortStats.test.ts
new file mode 100644
index 00000000..7b787b14
--- /dev/null
+++ b/app/renderer/lib/cohortStats.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ applyVolumeBand,
+ computeBandCohortStats,
+ costHistogram,
+ linearPercentile,
+ medianOf,
+} from './cohortStats'
+import type { CohortObservation } from './types'
+
+function obs(over: Partial = {}): CohortObservation {
+ return {
+ sessionId: 's1',
+ project: 'proj-a',
+ timestamp: '2026-08-15T10:00:00Z',
+ category: 'coding',
+ model: 'model-a',
+ costUSD: 0.1,
+ costKnown: true,
+ retries: 0,
+ oneShot: true,
+ inputTokens: 1000,
+ outputTokens: 500,
+ cacheReadTokens: 2000,
+ cacheWriteTokens: 100,
+ contextProxyTokens: 3000,
+ tokensReported: true,
+ ...over,
+ }
+}
+
+describe('renderer percentile mirror (pinned to the core convention)', () => {
+ it('gives median 3 and P90 6.8 for [1, 2, 4, 8] with linear interpolation at (N-1)*p', () => {
+ const sorted = [1, 2, 4, 8]
+ expect(medianOf(sorted)).toBe(3)
+ expect(linearPercentile(sorted, 0.9)).toBeCloseTo(6.8, 10)
+ })
+
+ it('degenerates safely: empty → null, single value → itself', () => {
+ expect(linearPercentile([], 0.9)).toBeNull()
+ expect(linearPercentile([7], 0.9)).toBe(7)
+ })
+})
+
+describe('applyVolumeBand', () => {
+ it('keeps the whole population when no band is set', () => {
+ const observations = [obs(), obs({ outputTokens: 999999 })]
+ const result = applyVolumeBand(observations, null)
+ expect(result.kept).toHaveLength(2)
+ expect(result.outsideBand).toBe(0)
+ expect(result.missingMeasure).toBe(0)
+ })
+
+ it('excludes observations outside the band and counts them', () => {
+ const observations = [obs({ outputTokens: 100 }), obs({ outputTokens: 5000 }), obs({ outputTokens: 900000 })]
+ const result = applyVolumeBand(observations, { measure: 'output', min: 1000, max: 10000 })
+ expect(result.kept.map(o => o.outputTokens)).toEqual([5000])
+ expect(result.outsideBand).toBe(2)
+ })
+
+ it('never treats observations without token data as small: they are excluded and counted', () => {
+ const observations = [obs({ tokensReported: false, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0 }), obs()]
+ const result = applyVolumeBand(observations, { measure: 'output', min: null, max: 1000000 })
+ expect(result.kept).toHaveLength(1)
+ expect(result.missingMeasure).toBe(1)
+ expect(result.outsideBand).toBe(0)
+ })
+
+ it('bands the context proxy measure on input + cache read', () => {
+ const low = obs({ inputTokens: 10, cacheReadTokens: 20, contextProxyTokens: 30 })
+ const high = obs({ inputTokens: 5000, cacheReadTokens: 50000, contextProxyTokens: 55000 })
+ const result = applyVolumeBand([low, high], { measure: 'contextProxy', min: 1000, max: null })
+ expect(result.kept).toEqual([high])
+ })
+})
+
+describe('computeBandCohortStats over the band-filtered population', () => {
+ it('divides rates by the declared (band-filtered) population', () => {
+ const kept = [
+ obs({ retries: 1, oneShot: false, costUSD: 1 }),
+ obs({ retries: 0, costUSD: 2 }),
+ obs({ retries: 2, oneShot: false, costUSD: 4 }),
+ obs({ retries: 0, costUSD: 8 }),
+ ]
+ const stats = computeBandCohortStats('model-a', kept)
+ expect(stats.observationCount).toBe(4)
+ // The exact pinned vector, through the full band-stats path.
+ expect(stats.costMedian).toBe(3)
+ expect(stats.costP90).toBeCloseTo(6.8, 10)
+ expect(stats.retryCount).toBe(3)
+ expect(stats.retryRate).toBeCloseTo(0.75)
+ expect(stats.oneShotRate).toBe(50)
+ })
+
+ it('counts unknown cost observations separately and keeps them out of cost percentiles', () => {
+ const kept = [obs({ costKnown: false, costUSD: 0 }), obs({ costUSD: 0.5 })]
+ const stats = computeBandCohortStats('model-a', kept)
+ expect(stats.unknownCostCount).toBe(1)
+ expect(stats.costKnownCount).toBe(1)
+ expect(stats.costMedian).toBe(0.5)
+ })
+
+ it('keeps histograms deterministic and totalling the population', () => {
+ const costs = [0.1, 0.2, 0.3, 0.4, 0.5]
+ const h1 = costHistogram(costs)
+ const h2 = costHistogram([...costs].reverse())
+ expect(h1).toEqual(h2)
+ expect(h1.counts.reduce((a, b) => a + b, 0)).toBe(5)
+ })
+})
diff --git a/app/renderer/lib/cohortStats.ts b/app/renderer/lib/cohortStats.ts
new file mode 100644
index 00000000..86027c95
--- /dev/null
+++ b/app/renderer/lib/cohortStats.ts
@@ -0,0 +1,134 @@
+import type { CohortObservation, CohortStats, CohortVolumeStats } from './types'
+
+/**
+ * Renderer-side cohort math over the DECLARED population a cohort-json report
+ * carries. The core implementation is src/compare-cohorts.ts; this mirror
+ * exists so volume-band changes recompute instantly from the report's own
+ * observation list instead of respawning the CLI, and both sides pin the same
+ * percentile convention in tests: sort ascending, position (N-1)*p, linear
+ * interpolation — [1, 2, 4, 8] → median 3, P90 6.8.
+ */
+
+/** Volume measure an observation carries. `contextProxy` is input + cache-read
+ * tokens — a proxy, not a measured context window; callers must label it so. */
+export type VolumeMeasure = 'output' | 'input' | 'contextProxy'
+
+export type VolumeBand = {
+ measure: VolumeMeasure
+ min: number | null
+ max: number | null
+}
+
+export function linearPercentile(sorted: readonly number[], p: number): number | null {
+ if (sorted.length === 0) return null
+ if (sorted.length === 1) return sorted[0] as number
+ const pos = (sorted.length - 1) * p
+ const lower = Math.floor(pos)
+ const upper = Math.ceil(pos)
+ if (lower === upper) return sorted[lower] as number
+ const fraction = pos - lower
+ return (sorted[lower] as number) * (1 - fraction) + (sorted[upper] as number) * fraction
+}
+
+export function medianOf(sorted: readonly number[]): number | null {
+ return linearPercentile(sorted, 0.5)
+}
+
+export function volumeOf(observation: CohortObservation, measure: VolumeMeasure): number {
+ if (measure === 'output') return observation.outputTokens
+ if (measure === 'input') return observation.inputTokens
+ return observation.contextProxyTokens
+}
+
+export type BandFilterResult = {
+ /** Observations inside the band — the new declared population. */
+ kept: CohortObservation[]
+ /** Observations dropped because they fall OUTSIDE the band edges. */
+ outsideBand: number
+ /** Observations dropped because they carry NO token measure at all. A band
+ * must never read these as small context — they are excluded and counted. */
+ missingMeasure: number
+}
+
+export function applyVolumeBand(observations: readonly CohortObservation[], band: VolumeBand | null): BandFilterResult {
+ if (!band || (band.min == null && band.max == null)) {
+ return { kept: [...observations], outsideBand: 0, missingMeasure: 0 }
+ }
+ const kept: CohortObservation[] = []
+ let outsideBand = 0
+ let missingMeasure = 0
+ for (const observation of observations) {
+ if (!observation.tokensReported) {
+ missingMeasure++
+ continue
+ }
+ const value = volumeOf(observation, band.measure)
+ if (band.min != null && value < band.min) { outsideBand++; continue }
+ if (band.max != null && value > band.max) { outsideBand++; continue }
+ kept.push(observation)
+ }
+ return { kept, outsideBand, missingMeasure }
+}
+
+const HISTOGRAM_BUCKETS = 8
+
+/** Same deterministic histogram as the core: linear edges 0 → P95 of known
+ * costs, top bucket open-ended so outliers stretch nothing. */
+export function costHistogram(costs: readonly number[]): { edges: number[]; counts: number[] } {
+ if (costs.length === 0) return { edges: [], counts: [] }
+ const sorted = [...costs].sort((a, b) => a - b)
+ const p95 = linearPercentile(sorted, 0.95) ?? 0
+ if (p95 <= 0) return { edges: [], counts: [costs.length] }
+ const edges: number[] = []
+ for (let i = 1; i < HISTOGRAM_BUCKETS; i++) edges.push((p95 * i) / HISTOGRAM_BUCKETS)
+ const counts = new Array(HISTOGRAM_BUCKETS).fill(0)
+ for (const cost of costs) {
+ let bucket = 0
+ while (bucket < edges.length && cost >= (edges[bucket] as number)) bucket++
+ counts[bucket]++
+ }
+ return { edges, counts }
+}
+
+export function computeBandCohortStats(model: string, observations: readonly CohortObservation[]): CohortStats {
+ const knownCosts = observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
+ const knownCostSum = knownCosts.reduce((sum, c) => sum + c, 0)
+ const sessionKeys = new Set(observations.map(o => `${o.project}/${o.sessionId}`))
+ const reported = observations.filter(o => o.tokensReported)
+ const byMeasure = (pick: (o: CohortObservation) => number) => reported.map(pick).sort((a, b) => a - b)
+ const outputTokens = byMeasure(o => o.outputTokens)
+ const inputTokens = byMeasure(o => o.inputTokens)
+ const contextProxy = byMeasure(o => o.contextProxyTokens)
+
+ const retryCount = observations.reduce((sum, o) => sum + o.retries, 0)
+ const oneShotCount = observations.filter(o => o.oneShot).length
+ const n = observations.length
+
+ const volume: CohortVolumeStats = {
+ outputMedian: medianOf(outputTokens),
+ outputP90: linearPercentile(outputTokens, 0.9),
+ inputMedian: medianOf(inputTokens),
+ inputP90: linearPercentile(inputTokens, 0.9),
+ contextProxyMedian: medianOf(contextProxy),
+ contextProxyP90: linearPercentile(contextProxy, 0.9),
+ missingMeasureCount: observations.filter(o => !o.tokensReported).length,
+ }
+
+ return {
+ model,
+ label: model,
+ observationCount: n,
+ distinctSessionCount: sessionKeys.size,
+ retryCount,
+ retryRate: n > 0 ? retryCount / n : null,
+ oneShotCount,
+ oneShotRate: n > 0 ? (oneShotCount / n) * 100 : null,
+ costKnownCount: knownCosts.length,
+ unknownCostCount: n - knownCosts.length,
+ costMedian: medianOf(knownCosts),
+ costP90: linearPercentile(knownCosts, 0.9),
+ costMean: knownCosts.length > 0 ? knownCostSum / knownCosts.length : null,
+ costHistogram: costHistogram(knownCosts),
+ volume,
+ }
+}
diff --git a/app/renderer/lib/sampleNavigation.ts b/app/renderer/lib/sampleNavigation.ts
new file mode 100644
index 00000000..6037403b
--- /dev/null
+++ b/app/renderer/lib/sampleNavigation.ts
@@ -0,0 +1,36 @@
+/**
+ * Minimal sample-navigation adapter (Goal 4, Inspect samples).
+ *
+ * CONTRACT (for the shared navigation integration): the cohort sample list
+ * calls `openSample(ref)` when the user activates a sample row. Whoever owns
+ * the common drill-through navigation registers itself once via
+ * `registerSampleOpener`. `openSample` returns false when no navigation is
+ * registered, and the Compare section keeps its self-contained inline sample
+ * rendering — the feature works standalone today and gains the shared
+ * navigation without code changes here.
+ *
+ * `SampleRef` carries the canonical identity pieces only (project + session id
+ * + timestamp). A bare sessionId is not globally unique, so consumers must
+ * pair it with the project label exactly as reports print it.
+ */
+export type SampleRef = {
+ sessionId: string
+ project: string
+ timestamp: string
+}
+
+export type SampleOpener = (ref: SampleRef) => void
+
+let opener: SampleOpener | null = null
+
+/** Install (or remove with null) the shared navigation's sample opener. */
+export function registerSampleOpener(next: SampleOpener | null): void {
+ opener = next
+}
+
+/** Hand a sample to the registered navigation; false when none is registered. */
+export function openSample(ref: SampleRef): boolean {
+ if (!opener) return false
+ opener(ref)
+ return true
+}
diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts
index 58f5411d..b0f410a2 100644
--- a/app/renderer/lib/types.ts
+++ b/app/renderer/lib/types.ts
@@ -723,6 +723,100 @@ export type CompareJsonReport = {
workingStyle: WorkingStyleRow[]
}
+// ————— src/compare-cohorts.ts (compare --format cohort-json) —————
+// Mirrors the core contracts 1:1. The renderer never imports the Node engine,
+// so these hand copies ARE the IPC types; tests on both sides pin the same
+// percentile convention ([1,2,4,8] → median 3, P90 6.8).
+
+/** One observation = one edit turn whose behavioral calls carry exactly one
+ * model. `costUSD` is that model's own recorded cost in the turn (never
+ * another model's, never the session total). */
+export type CohortObservation = {
+ sessionId: string
+ project: string
+ timestamp: string
+ category: string
+ model: string
+ costUSD: number
+ /** False when costUSD is 0 on a model the pricing rules do not declare free
+ * — a pricing gap, never displayed as a real $0 observation. */
+ costKnown: boolean
+ retries: number
+ oneShot: boolean
+ inputTokens: number
+ outputTokens: number
+ cacheReadTokens: number
+ cacheWriteTokens: number
+ /** input + cache-read tokens: an explicit PROXY for context size, never a
+ * measured context window. */
+ contextProxyTokens: number
+ /** False when the turn's calls report no tokens at all; volume bands must
+ * exclude and count these, never read them as small. */
+ tokensReported: boolean
+}
+
+export type CohortVolumeStats = {
+ outputMedian: number | null
+ outputP90: number | null
+ inputMedian: number | null
+ inputP90: number | null
+ contextProxyMedian: number | null
+ contextProxyP90: number | null
+ missingMeasureCount: number
+}
+
+export type CohortStats = {
+ model: string
+ label: string
+ /** Declared population the rates below divide by (selection filters, plus a
+ * volume band when one is active). */
+ observationCount: number
+ distinctSessionCount: number
+ retryCount: number
+ retryRate: number | null
+ oneShotCount: number
+ oneShotRate: number | null
+ costKnownCount: number
+ unknownCostCount: number
+ costMedian: number | null
+ costP90: number | null
+ costMean: number | null
+ costHistogram: { edges: number[]; counts: number[] }
+ volume: CohortVolumeStats
+}
+
+export type CohortModelReport = {
+ model: string
+ label: string
+ stats: CohortStats
+ /** The declared population itself: every statistic is reproducible from it. */
+ observations: CohortObservation[]
+ exclusions: {
+ multiModelTurnCount: number
+ combinedMultiModelCostUSD: number
+ noBehavioralModelTurns: number
+ }
+}
+
+export type CohortComparisonReport = {
+ kind: 'cohort-comparison'
+ period: { label: string; provider: string }
+ selection: { projects: string[]; category: string | null; from: string | null; to: string | null }
+ conventions: {
+ percentile: string
+ contextProxy: string
+ attribution: string
+ }
+ modelA: CohortModelReport
+ modelB: CohortModelReport
+}
+
+export type CohortFacets = {
+ kind: 'cohort-facets'
+ models: ModelStats[]
+ projects: Array<{ project: string; projectPath: string; sessions: number; costUSD: number }>
+ categories: Array<{ id: string; label: string }>
+}
// ---- Compare periods (period-diff; B minus A, A is the reference) ----
// Mirrors the JSON emitted by `codeburn compare-periods --format json`
// (src/period-diff.ts). Raw (unrounded) numbers; the UI formats.
@@ -983,6 +1077,10 @@ export interface CodeburnBridge {
getSessionsContributions(period: Period, provider: string, range?: DateRange, background?: boolean): Promise
getCompareModels(period: Period, provider: string, background?: boolean): Promise
getCompare(period: Period, provider: string, modelA: string, modelB: string): Promise
+ /** Cohort mode facets: models, canonical projects, activity categories. */
+ getCompareCohortModels(period: Period, provider: string, range?: DateRange, background?: boolean): Promise
+ /** Cohort mode report for two models over an explicit selection. */
+ getCompareCohort(period: Period, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string, background?: boolean): Promise
/** Compare periods (B minus A). Both ranges are required local YYYY-MM-DD keys. */
getPeriodCompare(rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean): Promise
/** Sessions behind one project/model contribution, joined across A and B. */
diff --git a/app/renderer/sections/Compare.test.tsx b/app/renderer/sections/Compare.test.tsx
index a0269269..0a1f6d2d 100644
--- a/app/renderer/sections/Compare.test.tsx
+++ b/app/renderer/sections/Compare.test.tsx
@@ -3,12 +3,14 @@ import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import type { CompareJsonReport, ModelStats } from '../lib/types'
+import type { CohortComparisonReport, CompareJsonReport, ModelStats } from '../lib/types'
import { Compare } from './Compare'
const mocks = vi.hoisted(() => ({
getCompareModels: vi.fn<(period: string, provider: string) => Promise>(),
getCompare: vi.fn<(period: string, provider: string, modelA: string, modelB: string) => Promise>(),
+ getCompareCohortModels: vi.fn<(period: string, provider: string) => Promise>(),
+ getCompareCohort: vi.fn<(period: string, provider: string, modelA: string, modelB: string, range?: unknown, projects?: string[], category?: string) => Promise>(),
telemetryTrack: vi.fn<(name: string, props?: Record) => Promise>(),
}))
vi.mock('../lib/ipc', async orig => {
@@ -48,6 +50,8 @@ describe('Compare', () => {
beforeEach(() => {
mocks.getCompareModels.mockReset()
mocks.getCompare.mockReset()
+ mocks.getCompareCohortModels.mockReset()
+ mocks.getCompareCohort.mockReset()
mocks.telemetryTrack.mockReset().mockResolvedValue(true)
})
@@ -128,3 +132,165 @@ describe('Compare', () => {
expect(mocks.getCompare).not.toHaveBeenCalled()
})
})
+
+// ————— Cohorts mode —————
+
+const cohortReport: CohortComparisonReport = {
+ kind: 'cohort-comparison',
+ period: { label: 'Last 30 days', provider: 'all' },
+ selection: { projects: [], category: null, from: null, to: null },
+ conventions: {
+ percentile: 'linear interpolation at position (N-1)*p',
+ contextProxy: 'input + cache-read tokens (proxy, not a measured context window)',
+ attribution: 'observation cost = recorded cost of the owning model\'s calls in the turn',
+ },
+ modelA: {
+ model: 'Opus 4.8',
+ label: 'Opus 4.8',
+ stats: {
+ model: 'Opus 4.8', label: 'Opus 4.8', observationCount: 4, distinctSessionCount: 2,
+ retryCount: 3, retryRate: 0.75, oneShotCount: 2, oneShotRate: 50,
+ costKnownCount: 4, unknownCostCount: 0,
+ costMedian: 3, costP90: 6.8, costMean: 3.75,
+ costHistogram: { edges: [1, 2, 3, 4, 5, 6, 7], counts: [1, 1, 0, 1, 0, 0, 0, 1] },
+ volume: { outputMedian: 500, outputP90: 900, inputMedian: 1000, inputP90: 2000, contextProxyMedian: 3000, contextProxyP90: 5000, missingMeasureCount: 0 },
+ },
+ observations: [
+ { sessionId: 's1', project: '/work/app', timestamp: '2026-08-14T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 1, costKnown: true, retries: 1, oneShot: false, inputTokens: 1000, outputTokens: 500, cacheReadTokens: 2000, cacheWriteTokens: 100, contextProxyTokens: 3000, tokensReported: true },
+ { sessionId: 's1', project: '/work/app', timestamp: '2026-08-14T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 2, costKnown: true, retries: 0, oneShot: true, inputTokens: 1200, outputTokens: 600, cacheReadTokens: 2200, cacheWriteTokens: 100, contextProxyTokens: 3400, tokensReported: true },
+ { sessionId: 's2', project: '/work/kit', timestamp: '2026-08-15T10:00:00Z', category: 'debugging', model: 'Opus 4.8', costUSD: 4, costKnown: true, retries: 2, oneShot: false, inputTokens: 1500, outputTokens: 800, cacheReadTokens: 3000, cacheWriteTokens: 100, contextProxyTokens: 4500, tokensReported: true },
+ { sessionId: 's2', project: '/work/kit', timestamp: '2026-08-15T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 8, costKnown: true, retries: 0, oneShot: true, inputTokens: 4000, outputTokens: 900, cacheReadTokens: 5000, cacheWriteTokens: 100, contextProxyTokens: 9000, tokensReported: true },
+ ],
+ exclusions: { multiModelTurnCount: 1, combinedMultiModelCostUSD: 0.15, noBehavioralModelTurns: 0 },
+ },
+ modelB: {
+ model: 'Sonnet 5',
+ label: 'Sonnet 5',
+ stats: {
+ model: 'Sonnet 5', label: 'Sonnet 5', observationCount: 0, distinctSessionCount: 0,
+ retryCount: 0, retryRate: null, oneShotCount: 0, oneShotRate: null,
+ costKnownCount: 0, unknownCostCount: 0,
+ costMedian: null, costP90: null, costMean: null,
+ costHistogram: { edges: [], counts: [] },
+ volume: { outputMedian: null, outputP90: null, inputMedian: null, inputP90: null, contextProxyMedian: null, contextProxyP90: null, missingMeasureCount: 0 },
+ },
+ observations: [],
+ exclusions: { multiModelTurnCount: 1, combinedMultiModelCostUSD: 0.15, noBehavioralModelTurns: 0 },
+ },
+}
+
+const facets = {
+ kind: 'cohort-facets' as const,
+ models: [modelA, modelB],
+ projects: [
+ { project: '/work/app', projectPath: '/work/app', sessions: 1, costUSD: 10 },
+ { project: '/work/kit', projectPath: '/work/kit', sessions: 1, costUSD: 5 },
+ ],
+ categories: [
+ { id: 'coding', label: 'Coding' },
+ { id: 'debugging', label: 'Debugging' },
+ ],
+}
+
+describe('Compare cohorts mode', () => {
+ beforeEach(() => {
+ mocks.getCompareModels.mockReset()
+ mocks.getCompare.mockReset()
+ mocks.getCompareCohortModels.mockReset()
+ mocks.getCompareCohort.mockReset()
+ mocks.telemetryTrack.mockReset().mockResolvedValue(true)
+ // The classic view mounts first (the mode switch lives inside it), so the
+ // classic mocks need implementations even in cohort-only tests.
+ mocks.getCompareModels.mockResolvedValue([modelA, modelB])
+ mocks.getCompare.mockResolvedValue(report)
+ mocks.getCompareCohortModels.mockResolvedValue(facets)
+ mocks.getCompareCohort.mockResolvedValue(cohortReport)
+ })
+
+ async function openCohorts() {
+ const user = userEvent.setup()
+ render( )
+ await user.click(await screen.findByRole('tab', { name: 'Cohorts' }))
+ await screen.findByLabelText('Cohort first model')
+ await screen.findByLabelText('Cohort second model')
+ await screen.findByText('Population')
+ return user
+ }
+
+ it('shows the population disclosure before the metrics and requests the cohort report', async () => {
+ await openCohorts()
+ expect(mocks.getCompareCohort).toHaveBeenCalledWith('30days', 'all', 'Opus 4.8', 'Sonnet 5', undefined, undefined, undefined)
+ // Exclusion ledger visible: mixed-model turns with their combined cost.
+ expect(screen.getAllByText(/Excluded turns mixing models/).length).toBeGreaterThan(0)
+ expect(screen.getAllByText('1 ($0.15)').length).toBe(2)
+ // Metrics cards render the pinned convention numbers.
+ expect(screen.getAllByText('$3.00').length).toBeGreaterThanOrEqual(1)
+ expect(screen.getAllByText('$6.80').length).toBeGreaterThanOrEqual(1)
+ })
+
+ it('renders a zero-observation cohort as explicit emptiness, not zeros', async () => {
+ const user = await openCohorts()
+ const second = screen.getByLabelText('Cohort second model')
+ // Keep Sonnet 5 selected: its cohort is empty → the sample card explains it.
+ expect(second).toBeInTheDocument()
+ expect(await screen.findByText(/No observations match the current selection/)).toBeInTheDocument()
+ expect(mocks.getCompareCohort).toHaveBeenCalled()
+ void user
+ })
+
+ it('passes a project selection through so out-of-selection observations are excluded before calculation', async () => {
+ const user = await openCohorts()
+ await user.click(screen.getByLabelText('Cohort project'))
+ await user.click(await screen.findByRole('option', { name: 'work/app' }))
+ await waitFor(() => expect(mocks.getCompareCohort).toHaveBeenCalledWith('30days', 'all', 'Opus 4.8', 'Sonnet 5', undefined, ['/work/app'], undefined))
+ })
+
+ it('applies a volume band from the declared population and shows what it excluded', async () => {
+ const user = await openCohorts()
+ // Band on output tokens [0, 700]: keeps 2 of the 4 Opus observations
+ // (output 500 and 600); the 800 and 900 ones are excluded and counted.
+ await user.type(screen.getByLabelText('Volume band minimum'), '0')
+ await user.type(screen.getByLabelText('Volume band maximum'), '700')
+ await waitFor(() => expect(screen.getByText(/Volume band excludes 2 observation/)).toBeInTheDocument())
+ // The recomputed median over the kept costs [1, 2] is 1.5.
+ expect(screen.getAllByText('$1.50').length).toBeGreaterThanOrEqual(1)
+ })
+
+ it('counts band exclusions of observations without token data, never reading them as small', async () => {
+ const user = await openCohorts()
+ // A report as the CLI would answer for the /work/app project: two
+ // token-bearing observations plus one with NO token measure at all.
+ const withMissing = {
+ ...cohortReport,
+ modelA: {
+ ...cohortReport.modelA,
+ observations: [
+ cohortReport.modelA.observations[0]!,
+ cohortReport.modelA.observations[1]!,
+ { sessionId: 's3', project: '/work/app', timestamp: '2026-08-16T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 0.5, costKnown: true, retries: 0, oneShot: true, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0, tokensReported: false },
+ ],
+ },
+ }
+ mocks.getCompareCohort.mockResolvedValue(withMissing)
+ // A new selection = a new memo key = a real re-fetch of the new payload.
+ await user.click(screen.getByLabelText('Cohort project'))
+ await user.click(await screen.findByRole('option', { name: 'work/app' }))
+ await user.type(screen.getByLabelText('Volume band minimum'), '0')
+ await user.type(screen.getByLabelText('Volume band maximum'), '700')
+ await waitFor(() => expect(screen.getByText(/without any token measure/)).toBeInTheDocument())
+ // The missing-measure observation is excluded from the banded stats
+ // (2 of the 4 observations in the spread mock survive the band; the mock
+ // carries the original stats object, hence 4). The first Inspect samples
+ // card is model A's.
+ expect(screen.getAllByText('Inspect samples')[0]!.closest('.cmp-card')).toHaveTextContent('2 of 4 in selection')
+ })
+
+ it('returns to the classic comparison unchanged', async () => {
+ const user = await openCohorts()
+ mocks.getCompareModels.mockResolvedValue([modelA, modelB])
+ mocks.getCompare.mockResolvedValue(report)
+ await user.click(screen.getByRole('tab', { name: 'Classic' }))
+ expect(await screen.findByLabelText('First model')).toBeInTheDocument()
+ expect(await screen.findByText('Performance')).toBeInTheDocument()
+ })
+})
diff --git a/app/renderer/sections/Compare.tsx b/app/renderer/sections/Compare.tsx
index d3ee60d1..0b436dc6 100644
--- a/app/renderer/sections/Compare.tsx
+++ b/app/renderer/sections/Compare.tsx
@@ -1,17 +1,35 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { CliErrorPanel } from '../components/CliErrorPanel'
import { Dropdown } from '../components/Dropdown'
import { EmptyNote } from '../components/EmptyState'
import { Panel } from '../components/Panel'
+import { SegTabs } from '../components/SegTabs'
import { SectionSkeleton } from '../components/Skeleton'
import { SwitchingBanner } from '../components/SwitchingBanner'
import { usePolled } from '../hooks/usePolled'
-import { formatCompact, formatUsd } from '../lib/format'
+import {
+ applyVolumeBand,
+ computeBandCohortStats,
+ type VolumeBand,
+ type VolumeMeasure,
+} from '../lib/cohortStats'
+import { formatCompact, formatUsd, shortenProjectPath } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { reportMemoKey } from '../lib/reportMemoKey'
+import { openSample } from '../lib/sampleNavigation'
import { trackEvent } from '../lib/track'
-import type { CompareJsonReport, ComparisonRow, DateRange, ModelStats, Period, WorkingStyleRow } from '../lib/types'
+import type {
+ CohortComparisonReport,
+ CohortModelReport,
+ CohortObservation,
+ CompareJsonReport,
+ ComparisonRow,
+ DateRange,
+ ModelStats,
+ Period,
+ WorkingStyleRow,
+} from '../lib/types'
function fmtMetric(v: number | null, fn: 'cost' | 'number' | 'percent' | 'decimal'): string {
if (v === null) return '—'
@@ -31,6 +49,8 @@ function RangeNote() {
)
}
+type CompareMode = 'classic' | 'cohorts'
+
export function Compare({
period,
provider,
@@ -43,6 +63,56 @@ export function Compare({
range?: DateRange | null
refreshToken?: number
ready?: boolean
+}) {
+ const [mode, setMode] = useState('classic')
+
+ if (mode === 'cohorts') {
+ return (
+
+
+ setMode(next as CompareMode)}
+ />
+
+
+
+ )
+ }
+
+ return (
+
+
+ setMode(next as CompareMode)}
+ />
+
+
+
+ )
+}
+
+function ClassicCompare({
+ period,
+ provider,
+ range,
+ refreshToken,
+ ready,
+}: {
+ period: Period
+ provider: string
+ range: DateRange | null
+ refreshToken: number
+ ready: boolean
}) {
const models = usePolled(
() => codeburn.getCompareModels(period, provider),
@@ -286,3 +356,443 @@ function ContextCard({ modelA, modelB }: { modelA: ModelStats; modelB: ModelStat
)
}
+
+// ————— Cohorts mode: model comparison over an explicit, inspectable population —————
+
+const SAMPLES_INITIAL_COUNT = 20
+
+type BandMeasureLabel = { value: VolumeMeasure; label: string }
+
+const BAND_MEASURES: BandMeasureLabel[] = [
+ { value: 'output', label: 'Output tokens' },
+ { value: 'input', label: 'Input tokens' },
+ { value: 'contextProxy', label: 'Context proxy (input + cache read)' },
+]
+
+function CohortCompare({
+ period,
+ provider,
+ range,
+ refreshToken,
+ ready,
+}: {
+ period: Period
+ provider: string
+ range: DateRange | null
+ refreshToken: number
+ ready: boolean
+}) {
+ const facets = usePolled(
+ () => codeburn.getCompareCohortModels(period, provider, range ?? undefined),
+ [period, provider, range?.from, range?.to, refreshToken],
+ { enabled: ready, memoKey: reportMemoKey('cohortmodels', period, provider, range) },
+ )
+
+ const [modelA, setModelA] = useState(null)
+ const [modelB, setModelB] = useState(null)
+ const [project, setProject] = useState('')
+ const [category, setCategory] = useState('')
+
+ useEffect(() => {
+ if (!facets.data) return
+ const available = new Set(facets.data.models.map(model => model.model))
+ setModelA(current => current && available.has(current) ? current : facets.data?.models[0]?.model ?? null)
+ setModelB(current => current && available.has(current) ? current : facets.data?.models[1]?.model ?? null)
+ // A project/category that vanished from the population must not keep
+ // filtering silently: fall back to "all".
+ setProject(current => {
+ if (!current) return ''
+ return facets.data?.projects.some(p => p.project === current) ? current : ''
+ })
+ }, [facets.data])
+
+ const report = usePolled(
+ () => codeburn.getCompareCohort(period, provider, modelA ?? '', modelB ?? '', range ?? undefined, project ? [project] : undefined, category || undefined),
+ [period, provider, modelA, modelB, range?.from, range?.to, project, category, refreshToken],
+ {
+ enabled: ready && !!modelA && !!modelB && modelA !== modelB,
+ memoKey: reportMemoKey('cohort', period, provider, range, `${modelA}|${modelB}|${project}|${category}`),
+ },
+ )
+
+ if (!facets.data) {
+ if (facets.error) return
+ return
+ }
+
+ if (facets.data.models.length < 2) {
+ return (
+
+ Need at least two models with usage in this range to compare.
+
+ )
+ }
+
+ const modelRows = facets.data.models
+ const nudgeDistinct = (chosen: string) => modelRows.find(model => model.model !== chosen)?.model ?? null
+ const intervalLabel = range ? `${range.from} → ${range.to}` : (report.data?.period.label ?? period)
+
+ return (
+ <>
+ {facets.switching && }
+
+ ({ value: model.model, label: `${model.model} · ${model.calls.toLocaleString()} calls` }))}
+ onChange={next => {
+ setModelA(next)
+ if (next === modelB) setModelB(nudgeDistinct(next))
+ }}
+ />
+ vs
+ ({ value: model.model, label: `${model.model} · ${model.calls.toLocaleString()} calls` }))}
+ onChange={next => {
+ setModelB(next)
+ if (next === modelA) setModelA(nudgeDistinct(next))
+ }}
+ />
+ ({ value: p.project, label: shortenProjectPath(p.project) }))]}
+ onChange={setProject}
+ />
+ ({ value: c.id, label: c.label }))]}
+ onChange={setCategory}
+ />
+
+
+ Cohort interval: {intervalLabel}. One observation = one edit turn driven by exactly one
+ behavioral model; turns mixing models are excluded and counted below.
+
+ {modelA && modelB && modelA !== modelB && (
+
+ )}
+ >
+ )
+}
+
+function CohortReport({ report }: { report: ReturnType> }) {
+ const [band, setBand] = useState(null)
+
+ if (!report.data) {
+ if (report.error) return
+ return
+ }
+
+ const data = report.data
+ // Volume bands recompute from the report's own declared population — instant,
+ // deterministic, and reproducible from the sample lists.
+ const sideA = cohortSide(data.modelA, band)
+ const sideB = cohortSide(data.modelB, band)
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+function cohortSide(model: CohortModelReport, band: VolumeBand | null) {
+ const filtered = applyVolumeBand(model.observations, band)
+ const stats = band ? computeBandCohortStats(model.model, filtered.kept) : model.stats
+ return {
+ model,
+ band,
+ kept: filtered.kept,
+ excludedOutsideBand: filtered.outsideBand,
+ excludedMissingMeasure: filtered.missingMeasure,
+ stats,
+ }
+}
+
+type CohortSide = ReturnType
+
+function PopulationCard({ data, sideA, sideB, band, onBandChange }: {
+ data: CohortComparisonReport
+ sideA: CohortSide
+ sideB: CohortSide
+ band: VolumeBand | null
+ onBandChange: (band: VolumeBand | null) => void
+}) {
+ const bandExcludedTotal = sideA.excludedOutsideBand + sideB.excludedOutsideBand
+ const missingMeasureTotal = sideA.excludedMissingMeasure + sideB.excludedMissingMeasure
+ return (
+
+
+
Population
+ Who is being compared, before any metric
+
+
+
Selection {data.modelA.label} {data.modelB.label}
+
+ Observations (edit turns, one model)
+ {sideA.stats.observationCount.toLocaleString()}
+ {sideB.stats.observationCount.toLocaleString()}
+
+
+ Distinct sessions they come from
+ {sideA.stats.distinctSessionCount.toLocaleString()}
+ {sideB.stats.distinctSessionCount.toLocaleString()}
+
+
+ Excluded turns mixing models
+ {data.modelA.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelA.exclusions.combinedMultiModelCostUSD)})
+ {data.modelB.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelB.exclusions.combinedMultiModelCostUSD)})
+
+
+ Excluded turns without a model
+ {data.modelA.exclusions.noBehavioralModelTurns.toLocaleString()}
+ {data.modelB.exclusions.noBehavioralModelTurns.toLocaleString()}
+
+
+ Unknown cost (not zero)
+ {sideA.stats.unknownCostCount.toLocaleString()}
+ {sideB.stats.unknownCostCount.toLocaleString()}
+
+
+ Projects / category in selection
+ {describeSelection(data)}
+
+
+
+ {(bandExcludedTotal > 0 || missingMeasureTotal > 0) && (
+
+ Volume band excludes {bandExcludedTotal.toLocaleString()} observation(s) outside the band
+ {missingMeasureTotal > 0 ? ` and ${missingMeasureTotal.toLocaleString()} without any token measure (never counted as small)` : ''}.
+ Rates below use the remaining declared population.
+
+ )}
+
+ Context proxy = input + cache-read tokens (a proxy, not a measured context window).
+ Percentiles use linear interpolation at position (N-1)·p. Outliers are never removed;
+ no winner is picked — this is a descriptive comparison.
+
+
+ )
+}
+
+function describeSelection(data: CohortComparisonReport): string {
+ const projects = data.selection.projects
+ const projectLabel = projects.length === 0
+ ? 'all'
+ : projects.length <= 2 ? projects.join(', ') : `${projects.length} projects`
+ const category = data.selection.category ?? 'all categories'
+ const interval = data.selection.from && data.selection.to ? `${data.selection.from} → ${data.selection.to}` : data.period.label
+ return `${projectLabel} · ${category} · ${interval}`
+}
+
+function VolumeBandFilter({ band, onChange }: { band: VolumeBand | null; onChange: (band: VolumeBand | null) => void }) {
+ const measure = band?.measure ?? 'output'
+ const min = band?.min?.toString() ?? ''
+ const max = band?.max?.toString() ?? ''
+
+ const push = (next: { measure?: VolumeMeasure; min?: string; max?: string }) => {
+ const nextMeasure = next.measure ?? measure
+ const minRaw = next.min ?? min
+ const maxRaw = next.max ?? max
+ const minNum = minRaw.trim() === '' ? null : Number(minRaw)
+ const maxNum = maxRaw.trim() === '' ? null : Number(maxRaw)
+ const validMin = minNum != null && Number.isFinite(minNum) ? minNum : null
+ const validMax = maxNum != null && Number.isFinite(maxNum) ? maxNum : null
+ if (validMin == null && validMax == null) {
+ onChange(null)
+ return
+ }
+ onChange({ measure: nextMeasure, min: validMin, max: validMax })
+ }
+
+ return (
+
+ Volume band
+ ({ value: m.value, label: m.label }))}
+ onChange={next => push({ measure: next as VolumeMeasure })}
+ />
+ push({ min: event.target.value })}
+ />
+ –
+ push({ max: event.target.value })}
+ />
+ {band && (
+ onChange(null)}>Clear band
+ )}
+
+ )
+}
+
+function CohortModelCard({ side }: { side: CohortSide }) {
+ const stats = side.stats
+ const histogram = stats.costHistogram
+ const maxCount = Math.max(1, ...histogram.counts)
+ return (
+
+
Cost per edit turn {side.model.label}
+
+
Median cost {fmtCost(stats.costMedian)}
+
P90 cost {fmtCost(stats.costP90)}
+
Mean cost {fmtCost(stats.costMean)}
+
One-shot rate {fmtMetric(stats.oneShotRate, 'percent')} ({stats.oneShotCount}/{stats.observationCount})
+
Retry rate {fmtMetric(stats.retryRate, 'decimal')} ({stats.retryCount})
+
Cost known for {stats.costKnownCount}/{stats.observationCount} observations
+
+
+ {histogram.edges.length === 0 && histogram.counts.length === 1 ? (
+
All known costs ≈ $0 (free models).
+ ) : (
+ histogram.counts.map((count, index) => (
+
+ {bucketLabel(histogram.edges, index)}
+
+ {count.toLocaleString()}
+
+ ))
+ )}
+
+
+ )
+}
+
+function fmtCost(value: number | null): string {
+ return value === null ? '—' : formatUsd(value)
+}
+
+function bucketLabel(edges: number[], index: number): string {
+ if (edges.length === 0) return '$0'
+ if (index === 0) return `< ${formatUsd(edges[0] as number)}`
+ if (index === edges.length) return `≥ ${formatUsd(edges[edges.length - 1] as number)}`
+ return `${formatUsd(edges[index - 1] as number)}–${formatUsd(edges[index] as number)}`
+}
+
+function VolumeCard({ title, side }: { title: string; side: CohortSide }) {
+ const volume = side.stats.volume
+ const rows = [
+ ['Output tokens', fmtVolume(volume.outputMedian), fmtVolume(volume.outputP90)],
+ ['Input tokens', fmtVolume(volume.inputMedian), fmtVolume(volume.inputP90)],
+ ['Context proxy (in + cache read)', fmtVolume(volume.contextProxyMedian), fmtVolume(volume.contextProxyP90)],
+ ]
+ return (
+
+
{title} {side.model.label}
+
+
Volume Median P90
+ {rows.map(([label, median, p90]) => (
+
+ {label}
+ {median}
+ {p90}
+
+ ))}
+
+ Observations without token data
+ {volume.missingMeasureCount.toLocaleString()}
+
+
+
+
+ )
+}
+
+function fmtVolume(value: number | null): string {
+ return value === null ? '—' : formatCompact(value)
+}
+
+/** Inspect samples: the declared population, inspectable row by row. Renders
+ * inline (self-contained); activating a row also hands it to the shared
+ * navigation adapter when one is registered (sampleNavigation.ts contract). */
+function SampleInspector({ side }: { side: CohortSide }) {
+ const [showAll, setShowAll] = useState(false)
+ const observations = useMemo(
+ () => [...side.kept].sort((a, b) => b.costUSD - a.costUSD || a.timestamp.localeCompare(b.timestamp)),
+ [side.kept],
+ )
+ const visible = showAll ? observations : observations.slice(0, SAMPLES_INITIAL_COUNT)
+
+ return (
+
+
+
Inspect samples
+ {side.model.label} · {side.stats.observationCount.toLocaleString()} of {side.model.stats.observationCount.toLocaleString()} in selection
+
+ {observations.length === 0 ? (
+
+ No observations match the current selection{side.band ? ' and volume band' : ''}. Nothing is compared.
+
+ ) : (
+
+ {visible.map((observation, index) => (
+
+ ))}
+ {observations.length > SAMPLES_INITIAL_COUNT && (
+ setShowAll(current => !current)}>
+ {showAll ? 'Show fewer' : `Show all ${observations.length.toLocaleString()} observations`}
+
+ )}
+
+ )}
+
+ )
+}
+
+function SampleRow({ observation }: { observation: CohortObservation }) {
+ const activate = () => {
+ openSample({ sessionId: observation.sessionId, project: observation.project, timestamp: observation.timestamp })
+ }
+ return (
+
+ {observation.timestamp.slice(0, 16).replace('T', ' ')}
+ {shortenProjectPath(observation.project)}
+ {observation.sessionId.slice(0, 10)}
+ {observation.category}
+
+ {observation.costKnown ? formatUsd(observation.costUSD) : 'unknown'}
+
+
+ {observation.tokensReported ? `${formatCompact(observation.inputTokens)} / ${formatCompact(observation.outputTokens)} / ${formatCompact(observation.contextProxyTokens)}` : 'no token data'}
+
+ {observation.oneShot ? 'one-shot' : `${observation.retries} retry`}
+
+ )
+}
diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css
index 09cf367e..ea04a734 100644
--- a/app/renderer/styles/plain.css
+++ b/app/renderer/styles/plain.css
@@ -907,6 +907,28 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
.cmp-bar-value { color: var(--mut); font-family: var(--mono); font-size: 10.5px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.cmp-turns { color: var(--mut2); }
+/* Compare · Cohorts mode */
+.cmp-value-wide { overflow: hidden; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
+.cmp-band { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 14px; border-top: 1px solid var(--line2); }
+.cmp-band-label { color: var(--mut); font-size: 11px; font-weight: 600; }
+.cmp-band .dropdown { max-width: 250px; }
+.cmp-band .dropdown-trigger { min-height: 27px; padding: 4px 9px; font-size: 11px; }
+.cmp-band-input { width: 90px; min-height: 27px; padding: 4px 8px; border: 1px solid var(--line2); border-radius: 6px; background: var(--fill); color: var(--ink); font-family: var(--mono); font-size: 11px; font-variant-numeric: tabular-nums; }
+.cmp-band-sep { color: var(--mut2); }
+.cmp-band-clear { border: 0; background: none; color: var(--accent); font-size: 11px; cursor: pointer; padding: 2px 4px; }
+.cmp-histogram { display: flex; flex-direction: column; gap: 4px; padding: 10px 14px 12px; border-top: 1px solid var(--line2); }
+.cmp-hist-row { display: grid; grid-template-columns: 110px minmax(0, 1fr) 44px; align-items: center; gap: 8px; }
+.cmp-hist-label { overflow: hidden; color: var(--mut2); font-family: var(--mono); font-size: 9.5px; font-variant-numeric: tabular-nums; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
+.cmp-hist-count { color: var(--mut); font-family: var(--mono); font-size: 10px; font-variant-numeric: tabular-nums; text-align: right; }
+.cmp-hist-note { color: var(--mut2); font-size: 10.5px; }
+.cmp-samples { display: flex; flex-direction: column; max-height: 320px; overflow-y: auto; }
+.cmp-sample { display: grid; grid-template-columns: 104px minmax(70px, 1fr) 84px 74px 70px minmax(120px, 1.3fr) 70px; align-items: center; column-gap: 8px; width: 100%; padding: 6px 14px; border: 0; border-bottom: 1px solid var(--line2); background: none; color: var(--mut); font-family: var(--mono); font-size: 10px; font-variant-numeric: tabular-nums; text-align: left; cursor: pointer; }
+.cmp-sample:hover { background: var(--fill); }
+.cmp-sample-project, .cmp-sample-session, .cmp-sample-cat { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.cmp-sample-cost, .cmp-sample-tokens, .cmp-sample-retries { text-align: right; white-space: nowrap; }
+.cmp-sample-time { color: var(--mut2); }
+.cmp-samples-more { border: 0; background: none; color: var(--accent); font-size: 11px; cursor: pointer; padding: 8px 14px; text-align: left; }
+
@media (max-width: 860px) {
.spend-top-row { grid-template-columns: 1fr; }
.spend-breakdowns { grid-template-columns: 1fr; }
@@ -918,8 +940,11 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
.sessions-toolbar, .sessions-search { width: 100%; }
.sessions-search { min-width: 0; }
.cmp-picker { gap: 5px; }
+ .cmp-picker .dropdown { max-width: 46vw; }
.cmp-category { grid-template-columns: 70px minmax(0, 1fr); }
.cmp-bar-row { grid-template-columns: minmax(0, 1fr) 76px; }
+ .cmp-sample { grid-template-columns: 90px minmax(60px, 1fr) 70px 60px minmax(100px, 1fr) 60px; }
+ .cmp-sample-cat { display: none; }
}
@media (max-width: 720px) {
From e78f4b9e7064594574af390a2b6cadaeb2509c64 Mon Sep 17 00:00:00 2001
From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com>
Date: Sat, 12 Sep 2026 13:21:58 +0300
Subject: [PATCH 3/4] Fix cohort accounting and exact project selection
---
app/electron/main.test.ts | 5 +++--
app/electron/main.ts | 18 ++++++++--------
app/renderer/lib/types.ts | 4 ++--
app/renderer/sections/Compare.test.tsx | 5 +++--
app/renderer/sections/Compare.tsx | 8 +++----
docs/compare-cohorts.md | 7 +++++++
src/compare-cohorts.ts | 22 ++++++++++++++-----
src/main.ts | 13 +++++++++---
tests/cli-compare-cohort.test.ts | 25 ++++++++++++++++++++++
tests/compare-cohorts.test.ts | 29 ++++++++++++++++++++++++++
10 files changed, 109 insertions(+), 27 deletions(-)
diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts
index f1dff516..08b5978a 100644
--- a/app/electron/main.test.ts
+++ b/app/electron/main.test.ts
@@ -118,7 +118,7 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> =
{ channel: 'codeburn:getPeriodCompareSessions', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all', 'project', '-work-pricing'], argv: ['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--dimension', 'project', '--key', '-work-pricing'] },
{ channel: 'codeburn:getCompareCohortModels', args: ['month', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] },
{ channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b'] },
- { channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha', 'loose-word'], 'coding'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b', '--project', '/Users/gone/alpha', '--project', 'loose-word', '--category', 'coding'] },
+ { channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha', '-Users-gone-alpha'], 'coding'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b', '--project-id=/Users/gone/alpha', '--project-id=-Users-gone-alpha', '--category', 'coding'] },
{ channel: 'codeburn:getYield', args: ['today', 'all'], argv: ['yield', '--format', 'json', '--period', 'today'] },
{ channel: 'codeburn:getYield', args: ['today', 'claude'], argv: ['yield', '--format', 'json', '--period', 'today', '--provider', 'claude'] },
{ channel: 'codeburn:getSpendFlow', args: ['month', 'openai'], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--provider', 'openai'] },
@@ -267,7 +267,8 @@ describe('createBridgeHandlers (IPC input validation)', () => {
{ name: 'relative export path', channel: 'codeburn:exportData', args: ['json', 'all', 'relative/out'] },
{ name: 'compare model that looks like a flag', channel: 'codeburn:getCompare', args: ['month', 'all', '-a', 'model-b'] },
{ name: 'cohort model that looks like a flag', channel: 'codeburn:getCompareCohort', args: ['month', 'all', '-a', 'model-b'] },
- { name: 'cohort project pattern that looks like a flag', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['-rf']] },
+ { name: 'cohort project identity containing NUL', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['bad\0id']] },
+ { name: 'empty cohort project identity', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['']] },
{ name: 'unknown cohort category', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, undefined, 'not-a-category'] },
{ name: 'price override model that looks like a flag', channel: 'codeburn:setPriceOverride', args: ['-x', { input: 1, output: 2 }] },
{ name: 'non-positive price override rate', channel: 'codeburn:setPriceOverride', args: ['my-model', { input: 0, output: 2 }] },
diff --git a/app/electron/main.ts b/app/electron/main.ts
index 71ea8bdd..4a55fd3d 100644
--- a/app/electron/main.ts
+++ b/app/electron/main.ts
@@ -314,17 +314,17 @@ function vToken(value: string): string {
if (value.startsWith('-')) throw new CliError('bad-args', 'argument must not start with "-"')
return value
}
-// Project filter patterns reach the CLI as repeatable --project values. An
-// absolute path starts with "/", a loose word must not start with "-" (that
-// would read as a flag); anything else is refused before it becomes argv.
-function vProjectPatterns(projects: string[] | undefined): string[] {
+// Exact identities from the cohort facet report, not loose CLI patterns.
+// Keep the value attached to its flag so label-only ids starting with "-"
+// remain data; NUL is invalid in process argv.
+function vProjectIds(projects: string[] | undefined): string[] {
if (!projects || projects.length === 0) return []
for (const pattern of projects) {
- if (typeof pattern !== 'string' || pattern.length === 0 || pattern.startsWith('-')) {
- throw new CliError('bad-args', 'invalid project pattern')
+ if (typeof pattern !== 'string' || pattern.length === 0 || pattern.includes('\0')) {
+ throw new CliError('bad-args', 'invalid project identity')
}
}
- return projects.flatMap(pattern => ['--project', pattern])
+ return projects.map(id => `--project-id=${id}`)
}
// Activity categories for the cohort selection: the ids behind the CLI's
// --category (src/types.ts CATEGORY_LABELS keys). Duplicated here because the
@@ -625,14 +625,14 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
}),
// Cohort mode: the facet query (models/projects/categories) and the report
// for two models over an explicit selection. Same `compare` command, new
- // cohort-json format; --project stays repeatable, category is one id.
+ // cohort-json format; project identities are exact, category is one id.
'codeburn:getCompareCohortModels': run((period: string, provider: string, range?: DateRange) => [
'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)), ...rangeArgs(vRange(range)),
], 3),
'codeburn:getCompareCohort': run((period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string) => [
'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
'--model-a', vToken(modelA), '--model-b', vToken(modelB), ...rangeArgs(vRange(range)),
- ...(vProjectPatterns(projects)), ...(category ? ['--category', vCategory(category)] : []),
+ ...(vProjectIds(projects)), ...(category ? ['--category', vCategory(category)] : []),
], 7),
'codeburn:getYield': run((period: string, provider: string, range?: DateRange) => [
'yield', '--format', 'json', '--period', vPeriod(period),
diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts
index b0f410a2..da32e673 100644
--- a/app/renderer/lib/types.ts
+++ b/app/renderer/lib/types.ts
@@ -814,7 +814,7 @@ export type CohortComparisonReport = {
export type CohortFacets = {
kind: 'cohort-facets'
models: ModelStats[]
- projects: Array<{ project: string; projectPath: string; sessions: number; costUSD: number }>
+ projects: Array<{ id: string; project: string; projectPath: string; sessions: number; costUSD: number }>
categories: Array<{ id: string; label: string }>
}
// ---- Compare periods (period-diff; B minus A, A is the reference) ----
@@ -1079,7 +1079,7 @@ export interface CodeburnBridge {
getCompare(period: Period, provider: string, modelA: string, modelB: string): Promise
/** Cohort mode facets: models, canonical projects, activity categories. */
getCompareCohortModels(period: Period, provider: string, range?: DateRange, background?: boolean): Promise
- /** Cohort mode report for two models over an explicit selection. */
+ /** Cohort mode report; projects contains exact ids from CohortFacets. */
getCompareCohort(period: Period, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string, background?: boolean): Promise
/** Compare periods (B minus A). Both ranges are required local YYYY-MM-DD keys. */
getPeriodCompare(rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean): Promise
diff --git a/app/renderer/sections/Compare.test.tsx b/app/renderer/sections/Compare.test.tsx
index 0a1f6d2d..cdaf697c 100644
--- a/app/renderer/sections/Compare.test.tsx
+++ b/app/renderer/sections/Compare.test.tsx
@@ -183,8 +183,9 @@ const facets = {
kind: 'cohort-facets' as const,
models: [modelA, modelB],
projects: [
- { project: '/work/app', projectPath: '/work/app', sessions: 1, costUSD: 10 },
- { project: '/work/kit', projectPath: '/work/kit', sessions: 1, costUSD: 5 },
+ { id: '/work/app', project: '-work-app', projectPath: '/work/app', sessions: 1, costUSD: 10 },
+ { id: '/work/app-backend', project: '-work-app-backend', projectPath: '/work/app-backend', sessions: 1, costUSD: 5 },
+ { id: '/work/kit', project: '-work-kit', projectPath: '/work/kit', sessions: 1, costUSD: 5 },
],
categories: [
{ id: 'coding', label: 'Coding' },
diff --git a/app/renderer/sections/Compare.tsx b/app/renderer/sections/Compare.tsx
index 0b436dc6..772e8dba 100644
--- a/app/renderer/sections/Compare.tsx
+++ b/app/renderer/sections/Compare.tsx
@@ -385,7 +385,7 @@ function CohortCompare({
const facets = usePolled(
() => codeburn.getCompareCohortModels(period, provider, range ?? undefined),
[period, provider, range?.from, range?.to, refreshToken],
- { enabled: ready, memoKey: reportMemoKey('cohortmodels', period, provider, range) },
+ { enabled: ready, memoKey: reportMemoKey('cohortmodels-v2', period, provider, range) },
)
const [modelA, setModelA] = useState(null)
@@ -402,7 +402,7 @@ function CohortCompare({
// filtering silently: fall back to "all".
setProject(current => {
if (!current) return ''
- return facets.data?.projects.some(p => p.project === current) ? current : ''
+ return facets.data?.projects.some(p => p.id === current) ? current : ''
})
}, [facets.data])
@@ -411,7 +411,7 @@ function CohortCompare({
[period, provider, modelA, modelB, range?.from, range?.to, project, category, refreshToken],
{
enabled: ready && !!modelA && !!modelB && modelA !== modelB,
- memoKey: reportMemoKey('cohort', period, provider, range, `${modelA}|${modelB}|${project}|${category}`),
+ memoKey: reportMemoKey('cohort-v2', period, provider, range, JSON.stringify([modelA, modelB, project, category])),
},
)
@@ -461,7 +461,7 @@ function CohortCompare({
id="cohort-project"
ariaLabel="Cohort project"
value={project}
- options={[{ value: '', label: 'All projects' }, ...facets.data.projects.map(p => ({ value: p.project, label: shortenProjectPath(p.project) }))]}
+ options={[{ value: '', label: 'All projects' }, ...facets.data.projects.map(p => ({ value: p.id, label: shortenProjectPath(p.id) }))]}
onChange={setProject}
/>
` (repeatable, `cohort-json` only). This selects exactly one
+identity, so selecting `/work/app` cannot also include `/work/app-backend`.
+The CLI's existing `--project` option continues to accept loose name patterns.
+
The **volume band** narrows the population to observations inside a token range
(output, input, or the context proxy). A band explicitly excludes — and counts —
observations that fall outside it **and** observations that carry no token
diff --git a/src/compare-cohorts.ts b/src/compare-cohorts.ts
index c0a733ba..2580c864 100644
--- a/src/compare-cohorts.ts
+++ b/src/compare-cohorts.ts
@@ -26,6 +26,7 @@ import { isBehavioralCall } from './behavioral-weight.js'
import { callBillableOutputTokens } from './session-output.js'
import { getShortModelName, isExpectedFreeModel } from './models.js'
import { aggregateModelStats, findModelStat, type ModelStats } from './compare-stats.js'
+import { spendProjectIdentity } from './spend-flow.js'
// The CLI's cohort branch resolves these through this one dynamic import; both
// are the classic module's own implementations (single identity source).
@@ -162,7 +163,9 @@ export function extractCohortObservations(
let cacheWriteTokens = 0
let tokensReported = false
for (const call of turn.assistantCalls) {
- if (call.model !== model || !isBehavioralCall(call)) continue
+ // Supplementary accounting is weightless for requests, but retains
+ // real cost and tokens attributable to this observation's model.
+ if (call.model !== model) continue
cost += call.costUSD
const callInput = call.usage.inputTokens
const callOutput = call.usage.outputTokens
@@ -363,7 +366,7 @@ export type CohortFacets = {
* picker shows, so both Compare modes agree on which models exist. */
models: ModelStats[]
/** Canonical project identities of the population. */
- projects: Array<{ project: string; projectPath: string; sessions: number; costUSD: number }>
+ projects: Array<{ id: string; project: string; projectPath: string; sessions: number; costUSD: number }>
categories: Array<{ id: TaskCategory; label: string }>
}
@@ -417,14 +420,15 @@ export function buildCohortComparison(
}
export function buildCohortFacets(projects: ProjectSummary[]): CohortFacets {
- const projectMap = new Map()
+ const projectMap = new Map()
for (const p of projects) {
- const existing = projectMap.get(p.project)
+ const { id } = spendProjectIdentity(p)
+ const existing = projectMap.get(id)
if (existing) {
existing.sessions += p.sessions.length
existing.costUSD += p.totalCostUSD
} else {
- projectMap.set(p.project, { project: p.project, projectPath: p.projectPath, sessions: p.sessions.length, costUSD: p.totalCostUSD })
+ projectMap.set(id, { id, project: p.project, projectPath: p.projectPath, sessions: p.sessions.length, costUSD: p.totalCostUSD })
}
}
return {
@@ -435,6 +439,14 @@ export function buildCohortFacets(projects: ProjectSummary[]): CohortFacets {
}
}
+/** Desktop selections name exact project identities. Keep the public CLI's
+ * loose --project patterns independent of this explicit selection. */
+export function selectCohortProjects(projects: ProjectSummary[], ids: readonly string[] = []): ProjectSummary[] {
+ if (ids.length === 0) return projects
+ const selected = new Set(ids)
+ return projects.filter(project => selected.has(spendProjectIdentity(project).id))
+}
+
export function renderCohortJson(report: CohortComparisonReport | CohortFacets): string {
return JSON.stringify(report, null, 2)
}
diff --git a/src/main.ts b/src/main.ts
index e2e57de6..31eec544 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -2249,9 +2249,14 @@ program
.option('--from ', 'Custom range start (YYYY-MM-DD)')
.option('--to ', 'Custom range end (YYYY-MM-DD)')
.option('--category ', 'cohort-json only: keep edit-turn observations of one activity category')
+ .option('--project-id ', 'cohort-json only: exact canonical project identity (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'compare')
assertFormat(opts.format, ['tui', 'json', 'cohort-json'], 'compare')
+ if (opts.projectId.length > 0 && opts.format !== 'cohort-json') {
+ process.stderr.write('codeburn compare: --project-id requires --format cohort-json.\n')
+ process.exit(1)
+ }
await loadPricing()
const customRange = parseDateRangeFlags(opts.from, opts.to)
const { range, label } = customRange
@@ -2259,10 +2264,10 @@ program
: getDateRange(opts.period)
if (opts.format === 'cohort-json') {
if (opts.category !== undefined) assertCategory(opts.category)
- const { aggregateModelStats, buildCohortComparison, buildCohortFacets, findModelStat, renderCohortJson } = await import('./compare-cohorts.js')
+ const { aggregateModelStats, buildCohortComparison, buildCohortFacets, findModelStat, renderCohortJson, selectCohortProjects } = await import('./compare-cohorts.js')
const parsed = await parseAllSessions(range, opts.provider)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
- const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
+ const projects = selectCohortProjects(filterProjectsByName(parsed, opts.project, opts.exclude), opts.projectId)
// Without --model-a/--model-b the cohort format answers the FACET query:
// the models, canonical project identities, and activity categories the
@@ -2275,7 +2280,9 @@ program
process.stderr.write('codeburn compare: --model-a and --model-b must be provided together.\n')
process.exit(1)
}
- const models = aggregateModelStats(projects)
+ // Resolve against the same period/provider population as the desktop
+ // model picker. A selected project may have zero work for either model.
+ const models = aggregateModelStats(parsed)
const modelA = findModelStat(models, opts.modelA)
const modelB = findModelStat(models, opts.modelB)
if (!modelA) {
diff --git a/tests/cli-compare-cohort.test.ts b/tests/cli-compare-cohort.test.ts
index c707802c..09154d52 100644
--- a/tests/cli-compare-cohort.test.ts
+++ b/tests/cli-compare-cohort.test.ts
@@ -172,6 +172,31 @@ describe('compare --format cohort-json', () => {
expect(report.modelB.stats.observationCount).toBe(0)
})
+ it('selects an exact project id while preserving loose --project matching', async () => {
+ const home = await seedHome()
+ const siblingPath = '/Users/gone/alpha-backend'
+ const siblingDir = join(home, '.claude', 'projects', '-Users-gone-alpha-backend')
+ await mkdir(siblingDir, { recursive: true })
+ await writeFile(join(siblingDir, 's-sibling.jsonl'), [
+ userLine('s-sibling', siblingPath, 10),
+ assistantLine('s-sibling', siblingPath, OPUS, 9),
+ ].join('\n') + '\n')
+ const args = ['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET]
+ const exact = runCli([...args, '--project-id=/Users/gone/alpha'], home)
+ expect(exact.status).toBe(0)
+ const report = JSON.parse(exact.stdout) as CohortReport
+ expect(report.modelA.stats.observationCount).toBe(2)
+ expect(report.modelA.observations.every(o => o.project === '-Users-gone-alpha')).toBe(true)
+ const loose = runCli([...args, '--project', 'alpha'], home)
+ expect(loose.status).toBe(0)
+ expect(JSON.parse(loose.stdout).modelA.stats.observationCount).toBe(3)
+ const oneModel = runCli([...args, '--project-id=/Users/gone/alpha-backend'], home)
+ expect(oneModel.status).toBe(0)
+ const oneModelReport = JSON.parse(oneModel.stdout) as CohortReport
+ expect(oneModelReport.modelA.stats.observationCount).toBe(1)
+ expect(oneModelReport.modelB.stats.observationCount).toBe(0)
+ })
+
it('rejects an unknown category with a usable message', async () => {
const home = await seedHome()
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--category', 'not-a-category'], home)
diff --git a/tests/compare-cohorts.test.ts b/tests/compare-cohorts.test.ts
index 3fbbcf98..c8e95db7 100644
--- a/tests/compare-cohorts.test.ts
+++ b/tests/compare-cohorts.test.ts
@@ -8,6 +8,7 @@ import {
extractCohortObservations,
linearPercentile,
medianOf,
+ selectCohortProjects,
type CohortObservation,
} from '../src/compare-cohorts.js'
import { findModelStat } from '../src/compare-stats.js'
@@ -143,6 +144,21 @@ describe('percentile convention (pinned)', () => {
// ————— Observation extraction —————
describe('extractCohortObservations', () => {
+ it('retains supplementary spend and tokens without giving it behavioral ownership', () => {
+ const turn = makeTurn('opus-4-6', 1, { inputTokens: 100 })
+ turn.assistantCalls.push({
+ ...turn.assistantCalls[0]!, costUSD: 9, supplementaryAccounting: true,
+ usage: { ...turn.assistantCalls[0]!.usage, inputTokens: 900 },
+ }, {
+ ...turn.assistantCalls[0]!, model: 'sonnet-5', costUSD: 7, supplementaryAccounting: true,
+ })
+ const { perModel, exclusions } = extractCohortObservations({ projects: [makeProject('s1', [turn])] })
+ expect(perModel.get('opus-4-6')).toHaveLength(1)
+ expect(perModel.get('opus-4-6')![0]).toMatchObject({ costUSD: 10, inputTokens: 1000 })
+ expect(perModel.has('sonnet-5')).toBe(false)
+ expect(exclusions.multiModelTurns).toEqual([])
+ })
+
it('owns an edit turn by its single behavioral model and attributes only that model\'s cost', () => {
// One turn: opus behavioral call ($0.10) + sonnet behavioral call ($0.05)
// would be MULTI-model; here instead: opus call costs 0.10, a second call
@@ -227,6 +243,19 @@ describe('extractCohortObservations', () => {
// ————— Cost semantics: unknown ≠ zero —————
+describe('canonical cohort project selection', () => {
+ it('keeps same-label projects distinct and selects exact identities without prefix matching', () => {
+ const projects = ['/work/app', '/work/app-backend', '/other/app'].map((projectPath, i) => ({
+ ...makeProject(`s${i}`, [makeTurn('opus-4-6', i + 1)], 'app'), projectPath,
+ }))
+ const facets = buildCohortFacets(projects)
+ expect(facets.projects.map(p => p.id).sort()).toEqual(projects.map(p => p.projectPath).sort())
+ expect(selectCohortProjects(projects, ['/work/app'])).toEqual([projects[0]])
+ expect(selectCohortProjects(projects, ['/work/app', '/other/app'])).toEqual([projects[0], projects[2]])
+ expect(selectCohortProjects(projects, ['app'])).toEqual([])
+ })
+})
+
describe('unknown cost handling', () => {
it('marks an unpriced model\'s $0 observations as unknown and keeps them out of cost stats but in retry stats', () => {
const project = makeProject('s1', [
From 029843c13d5eb1a51447152d60c746bd3c07a6ba Mon Sep 17 00:00:00 2001
From: iamtoruk
Date: Sat, 12 Sep 2026 13:56:31 -0700
Subject: [PATCH 4/4] Wire cohort samples to the real drill-through, scope and
serve the new flags
Rebased on main, which since gained #1307, #1316 and #1319.
- Delete app/renderer/lib/sampleNavigation.ts. It was a placeholder for a
registry that never landed: #1316 ships drill-through as an onInvestigate
callback prop plus NavState. The sample rows now call it, threaded from
App.tsx through Compare, and open the owning session for real.
- Give a CohortObservation the provider/project/session triple the sessions
report keys rows by (inferSessionProvider, session.project || project.project),
so a sample resolves to exactly one session row. Without it a cohort sample
could not build sessionRowKey at all.
- Carry projectArgs() on both cohort spawns, per #1307. The saved project
filter now scopes the facet query and the report; --project-id still narrows
within it. Extended the scopes-every-fetch test to cover both.
- Allow --from, --to, --category and --project-id on compare in SERVE_OPTIONS.
Verified over stdio: before, every cohort request but the bare facet query
came back "command not served" and fell back to a spawn.
- Catch the invalid-date throw on compare like report does, instead of an
unhandled UsageQueryError stack trace.
- Drop the unrelated CODEBURN_USER_DATA_DIR hunk in bootstrap().
---
app/electron/main.test.ts | 8 +++++
app/electron/main.ts | 14 +++-----
app/renderer/App.tsx | 2 +-
app/renderer/lib/cohortStats.test.ts | 1 +
app/renderer/lib/sampleNavigation.ts | 36 --------------------
app/renderer/lib/types.ts | 1 +
app/renderer/sections/Compare.test.tsx | 24 ++++++++++----
app/renderer/sections/Compare.tsx | 46 ++++++++++++++++++--------
docs/compare-cohorts.md | 12 ++++---
src/compare-cohorts.ts | 15 +++++----
src/main.ts | 8 ++++-
src/serve.ts | 4 ++-
tests/compare-cohorts.test.ts | 9 +++++
13 files changed, 101 insertions(+), 79 deletions(-)
delete mode 100644 app/renderer/lib/sampleNavigation.ts
diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts
index 08b5978a..e4cc9aac 100644
--- a/app/electron/main.test.ts
+++ b/app/electron/main.test.ts
@@ -860,6 +860,14 @@ describe('project filter', () => {
// contribution row either.
await handlers['codeburn:getPeriodCompareSessions']!(rangeA, rangeB, 'all', 'model', 'sonnet')
expect(calls[4]).toEqual(['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch', '--dimension', 'model', '--key', 'sonnet'])
+ await handlers['codeburn:getCompareCohortModels']!('week', 'all')
+ expect(calls[5]).toEqual(['compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch'])
+ // --project-id narrows WITHIN the saved filter; it never replaces it.
+ await handlers['codeburn:getCompareCohort']!('week', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha'])
+ expect(calls[6]).toEqual([
+ 'compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch',
+ '--model-a', 'model-a', '--model-b', 'model-b', '--project-id=/Users/gone/alpha',
+ ])
})
})
diff --git a/app/electron/main.ts b/app/electron/main.ts
index 4a55fd3d..2c09a905 100644
--- a/app/electron/main.ts
+++ b/app/electron/main.ts
@@ -627,10 +627,14 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
// for two models over an explicit selection. Same `compare` command, new
// cohort-json format; project identities are exact, category is one id.
'codeburn:getCompareCohortModels': run((period: string, provider: string, range?: DateRange) => [
- 'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)), ...rangeArgs(vRange(range)),
+ 'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
+ ...projectArgs(), ...rangeArgs(vRange(range)),
], 3),
+ // The saved project filter still scopes the population; --project-id then
+ // narrows it further to one identity the facet report offered.
'codeburn:getCompareCohort': run((period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string) => [
'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
+ ...projectArgs(),
'--model-a', vToken(modelA), '--model-b', vToken(modelB), ...rangeArgs(vRange(range)),
...(vProjectIds(projects)), ...(category ? ['--category', vCategory(category)] : []),
], 7),
@@ -937,14 +941,6 @@ function bootstrap(): void {
console.error('Unhandled promise rejection in main process:', reason)
})
- // Opt-in profile isolation for parallel dev/verification runs: a distinct
- // userData dir also isolates serve.pid, the single-instance lock and telemetry
- // state, so two checkouts can run Electron side by side. Unset by default —
- // normal launches keep the OS default profile.
- if (process.env.CODEBURN_USER_DATA_DIR) {
- app.setPath('userData', process.env.CODEBURN_USER_DATA_DIR)
- }
-
// Packaged builds ship their own version-matched CLI under resources/cli (the
// afterPack hook copies it in). Point the resolver at the launch shim before
// any handler spawns; cli.ts runs it with Electron-as-node. The shim, not
diff --git a/app/renderer/App.tsx b/app/renderer/App.tsx
index c58a4ecf..c5a5326b 100644
--- a/app/renderer/App.tsx
+++ b/app/renderer/App.tsx
@@ -943,7 +943,7 @@ function AppMain() {
) : section === 'models' ? (
) : section === 'compare' ? (
-
+
) : section === 'periods' ? (
) : (
diff --git a/app/renderer/lib/cohortStats.test.ts b/app/renderer/lib/cohortStats.test.ts
index 7b787b14..b5523ba8 100644
--- a/app/renderer/lib/cohortStats.test.ts
+++ b/app/renderer/lib/cohortStats.test.ts
@@ -12,6 +12,7 @@ import type { CohortObservation } from './types'
function obs(over: Partial = {}): CohortObservation {
return {
sessionId: 's1',
+ provider: 'claude',
project: 'proj-a',
timestamp: '2026-08-15T10:00:00Z',
category: 'coding',
diff --git a/app/renderer/lib/sampleNavigation.ts b/app/renderer/lib/sampleNavigation.ts
deleted file mode 100644
index 6037403b..00000000
--- a/app/renderer/lib/sampleNavigation.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Minimal sample-navigation adapter (Goal 4, Inspect samples).
- *
- * CONTRACT (for the shared navigation integration): the cohort sample list
- * calls `openSample(ref)` when the user activates a sample row. Whoever owns
- * the common drill-through navigation registers itself once via
- * `registerSampleOpener`. `openSample` returns false when no navigation is
- * registered, and the Compare section keeps its self-contained inline sample
- * rendering — the feature works standalone today and gains the shared
- * navigation without code changes here.
- *
- * `SampleRef` carries the canonical identity pieces only (project + session id
- * + timestamp). A bare sessionId is not globally unique, so consumers must
- * pair it with the project label exactly as reports print it.
- */
-export type SampleRef = {
- sessionId: string
- project: string
- timestamp: string
-}
-
-export type SampleOpener = (ref: SampleRef) => void
-
-let opener: SampleOpener | null = null
-
-/** Install (or remove with null) the shared navigation's sample opener. */
-export function registerSampleOpener(next: SampleOpener | null): void {
- opener = next
-}
-
-/** Hand a sample to the registered navigation; false when none is registered. */
-export function openSample(ref: SampleRef): boolean {
- if (!opener) return false
- opener(ref)
- return true
-}
diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts
index da32e673..b1f2b5b0 100644
--- a/app/renderer/lib/types.ts
+++ b/app/renderer/lib/types.ts
@@ -733,6 +733,7 @@ export type CompareJsonReport = {
* another model's, never the session total). */
export type CohortObservation = {
sessionId: string
+ provider: string
project: string
timestamp: string
category: string
diff --git a/app/renderer/sections/Compare.test.tsx b/app/renderer/sections/Compare.test.tsx
index cdaf697c..02414c7b 100644
--- a/app/renderer/sections/Compare.test.tsx
+++ b/app/renderer/sections/Compare.test.tsx
@@ -156,10 +156,10 @@ const cohortReport: CohortComparisonReport = {
volume: { outputMedian: 500, outputP90: 900, inputMedian: 1000, inputP90: 2000, contextProxyMedian: 3000, contextProxyP90: 5000, missingMeasureCount: 0 },
},
observations: [
- { sessionId: 's1', project: '/work/app', timestamp: '2026-08-14T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 1, costKnown: true, retries: 1, oneShot: false, inputTokens: 1000, outputTokens: 500, cacheReadTokens: 2000, cacheWriteTokens: 100, contextProxyTokens: 3000, tokensReported: true },
- { sessionId: 's1', project: '/work/app', timestamp: '2026-08-14T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 2, costKnown: true, retries: 0, oneShot: true, inputTokens: 1200, outputTokens: 600, cacheReadTokens: 2200, cacheWriteTokens: 100, contextProxyTokens: 3400, tokensReported: true },
- { sessionId: 's2', project: '/work/kit', timestamp: '2026-08-15T10:00:00Z', category: 'debugging', model: 'Opus 4.8', costUSD: 4, costKnown: true, retries: 2, oneShot: false, inputTokens: 1500, outputTokens: 800, cacheReadTokens: 3000, cacheWriteTokens: 100, contextProxyTokens: 4500, tokensReported: true },
- { sessionId: 's2', project: '/work/kit', timestamp: '2026-08-15T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 8, costKnown: true, retries: 0, oneShot: true, inputTokens: 4000, outputTokens: 900, cacheReadTokens: 5000, cacheWriteTokens: 100, contextProxyTokens: 9000, tokensReported: true },
+ { sessionId: 's1', provider: 'claude', project: '/work/app', timestamp: '2026-08-14T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 1, costKnown: true, retries: 1, oneShot: false, inputTokens: 1000, outputTokens: 500, cacheReadTokens: 2000, cacheWriteTokens: 100, contextProxyTokens: 3000, tokensReported: true },
+ { sessionId: 's1', provider: 'claude', project: '/work/app', timestamp: '2026-08-14T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 2, costKnown: true, retries: 0, oneShot: true, inputTokens: 1200, outputTokens: 600, cacheReadTokens: 2200, cacheWriteTokens: 100, contextProxyTokens: 3400, tokensReported: true },
+ { sessionId: 's2', provider: 'claude', project: '/work/kit', timestamp: '2026-08-15T10:00:00Z', category: 'debugging', model: 'Opus 4.8', costUSD: 4, costKnown: true, retries: 2, oneShot: false, inputTokens: 1500, outputTokens: 800, cacheReadTokens: 3000, cacheWriteTokens: 100, contextProxyTokens: 4500, tokensReported: true },
+ { sessionId: 's2', provider: 'claude', project: '/work/kit', timestamp: '2026-08-15T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 8, costKnown: true, retries: 0, oneShot: true, inputTokens: 4000, outputTokens: 900, cacheReadTokens: 5000, cacheWriteTokens: 100, contextProxyTokens: 9000, tokensReported: true },
],
exclusions: { multiModelTurnCount: 1, combinedMultiModelCostUSD: 0.15, noBehavioralModelTurns: 0 },
},
@@ -208,9 +208,9 @@ describe('Compare cohorts mode', () => {
mocks.getCompareCohort.mockResolvedValue(cohortReport)
})
- async function openCohorts() {
+ async function openCohorts(onInvestigate?: (request: unknown) => void) {
const user = userEvent.setup()
- render( )
+ render( )
await user.click(await screen.findByRole('tab', { name: 'Cohorts' }))
await screen.findByLabelText('Cohort first model')
await screen.findByLabelText('Cohort second model')
@@ -268,7 +268,7 @@ describe('Compare cohorts mode', () => {
observations: [
cohortReport.modelA.observations[0]!,
cohortReport.modelA.observations[1]!,
- { sessionId: 's3', project: '/work/app', timestamp: '2026-08-16T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 0.5, costKnown: true, retries: 0, oneShot: true, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0, tokensReported: false },
+ { sessionId: 's3', provider: 'claude', project: '/work/app', timestamp: '2026-08-16T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 0.5, costKnown: true, retries: 0, oneShot: true, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0, tokensReported: false },
],
},
}
@@ -286,6 +286,16 @@ describe('Compare cohorts mode', () => {
expect(screen.getAllByText('Inspect samples')[0]!.closest('.cmp-card')).toHaveTextContent('2 of 4 in selection')
})
+ it('drills a sample through to its session with the shared investigation key', async () => {
+ const onInvestigate = vi.fn()
+ const user = await openCohorts(onInvestigate)
+ await user.click(screen.getAllByTitle(/^Open session: /)[0]!)
+ expect(onInvestigate).toHaveBeenCalledWith({
+ filters: expect.objectContaining({ sessions: [{ provider: 'claude', sessionId: 's2' }] }),
+ sessionId: 'claude\u0000/work/kit\u0000s2',
+ })
+ })
+
it('returns to the classic comparison unchanged', async () => {
const user = await openCohorts()
mocks.getCompareModels.mockResolvedValue([modelA, modelB])
diff --git a/app/renderer/sections/Compare.tsx b/app/renderer/sections/Compare.tsx
index 772e8dba..ef449b10 100644
--- a/app/renderer/sections/Compare.tsx
+++ b/app/renderer/sections/Compare.tsx
@@ -17,8 +17,10 @@ import {
import { formatCompact, formatUsd, shortenProjectPath } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { reportMemoKey } from '../lib/reportMemoKey'
-import { openSample } from '../lib/sampleNavigation'
+import { sessionFilters } from '../lib/investigation'
import { trackEvent } from '../lib/track'
+import type { InvestigateRequest } from './Overview'
+import { sessionRowKey } from './Sessions'
import type {
CohortComparisonReport,
CohortModelReport,
@@ -57,12 +59,14 @@ export function Compare({
range = null,
refreshToken = 0,
ready = true,
+ onInvestigate,
}: {
period: Period
provider: string
range?: DateRange | null
refreshToken?: number
ready?: boolean
+ onInvestigate?: (request: InvestigateRequest) => void
}) {
const [mode, setMode] = useState('classic')
@@ -79,7 +83,7 @@ export function Compare({
onChange={next => setMode(next as CompareMode)}
/>
-
+
)
}
@@ -375,12 +379,14 @@ function CohortCompare({
range,
refreshToken,
ready,
+ onInvestigate,
}: {
period: Period
provider: string
range: DateRange | null
refreshToken: number
ready: boolean
+ onInvestigate?: (request: InvestigateRequest) => void
}) {
const facets = usePolled(
() => codeburn.getCompareCohortModels(period, provider, range ?? undefined),
@@ -477,13 +483,16 @@ function CohortCompare({
behavioral model; turns mixing models are excluded and counted below.
{modelA && modelB && modelA !== modelB && (
-
+
)}
>
)
}
-function CohortReport({ report }: { report: ReturnType> }) {
+function CohortReport({ report, onInvestigate }: {
+ report: ReturnType>
+ onInvestigate?: (request: InvestigateRequest) => void
+}) {
const [band, setBand] = useState(null)
if (!report.data) {
@@ -509,8 +518,8 @@ function CohortReport({ report }: { report: ReturnType
-
-
+
+
)
@@ -737,10 +746,13 @@ function fmtVolume(value: number | null): string {
return value === null ? '—' : formatCompact(value)
}
-/** Inspect samples: the declared population, inspectable row by row. Renders
- * inline (self-contained); activating a row also hands it to the shared
- * navigation adapter when one is registered (sampleNavigation.ts contract). */
-function SampleInspector({ side }: { side: CohortSide }) {
+/** Inspect samples: the declared population, inspectable row by row. Activating
+ * a row drills through to the owning session with the shared investigation
+ * navigation, keyed by the same provider/project/session triple Sessions uses. */
+function SampleInspector({ side, onInvestigate }: {
+ side: CohortSide
+ onInvestigate?: (request: InvestigateRequest) => void
+}) {
const [showAll, setShowAll] = useState(false)
const observations = useMemo(
() => [...side.kept].sort((a, b) => b.costUSD - a.costUSD || a.timestamp.localeCompare(b.timestamp)),
@@ -761,7 +773,7 @@ function SampleInspector({ side }: { side: CohortSide }) {
) : (
{visible.map((observation, index) => (
-
+
))}
{observations.length > SAMPLES_INITIAL_COUNT && (
setShowAll(current => !current)}>
@@ -774,13 +786,19 @@ function SampleInspector({ side }: { side: CohortSide }) {
)
}
-function SampleRow({ observation }: { observation: CohortObservation }) {
+function SampleRow({ observation, onInvestigate }: {
+ observation: CohortObservation
+ onInvestigate?: (request: InvestigateRequest) => void
+}) {
const activate = () => {
- openSample({ sessionId: observation.sessionId, project: observation.project, timestamp: observation.timestamp })
+ onInvestigate?.({
+ filters: sessionFilters({ provider: observation.provider, sessionId: observation.sessionId }),
+ sessionId: sessionRowKey(observation),
+ })
}
return (
{observation.timestamp.slice(0, 16).replace('T', ' ')}
{shortenProjectPath(observation.project)}
diff --git a/docs/compare-cohorts.md b/docs/compare-cohorts.md
index 7eea7693..5b54fa5a 100644
--- a/docs/compare-cohorts.md
+++ b/docs/compare-cohorts.md
@@ -19,7 +19,11 @@ on the same kind of work, over a population you can inspect?**
Supplementary accounting for that model remains part of its cost and token
totals, without adding observations or changing behavioral ownership.
* Edit turns whose behavioral calls span **two or more models** are excluded
- from both cohorts, counted, and shown with their combined cost.
+ from both cohorts, counted, and shown with their combined cost. This is the
+ one place cohort counts diverge from `compare --format json`, which owns a
+ turn by its *first* behavioral call (`primaryTurnModel`, `src/compare-stats.ts`)
+ and so still counts a mixed turn for that first model. Cohort observations
+ therefore equal a model's `editTurns` except for mixed turns it led.
* An edit turn with no behavioral model call at all is excluded the same way.
* A `$0` cost on a model the pricing rules do not declare free (local models,
subscription SKUs, explicit zero-rate overrides) is **unknown cost, not zero**:
@@ -38,9 +42,9 @@ In order, before any metric:
2. **Inspect samples** — the declared population itself, one row per
observation (timestamp, project, session, category, cost, input / output /
context-proxy tokens, retries). Every number on the page is reproducible
- from this list. Activating a row also hands the sample to the shared
- navigation when one is registered (`app/renderer/lib/sampleNavigation.ts`);
- the section is fully usable without it.
+ from this list. Activating a row drills through to the owning session with
+ the shared investigation navigation, keyed by the same provider/project/
+ session triple the sessions report uses.
3. **Cost per edit turn** — median, P90, mean over cost-known observations, the
one-shot rate and retry rate over the declared population (zero *observed*
retries never proves code correctness), and a compact cost histogram whose
diff --git a/src/compare-cohorts.ts b/src/compare-cohorts.ts
index 2580c864..3849612b 100644
--- a/src/compare-cohorts.ts
+++ b/src/compare-cohorts.ts
@@ -23,7 +23,7 @@
import type { ClassifiedTurn, ProjectSummary, TaskCategory } from './types.js'
import { CATEGORY_LABELS } from './types.js'
import { isBehavioralCall } from './behavioral-weight.js'
-import { callBillableOutputTokens } from './session-output.js'
+import { callBillableOutputTokens, inferSessionProvider } from './session-output.js'
import { getShortModelName, isExpectedFreeModel } from './models.js'
import { aggregateModelStats, findModelStat, type ModelStats } from './compare-stats.js'
import { spendProjectIdentity } from './spend-flow.js'
@@ -47,10 +47,12 @@ function behavioralCostByModel(turn: ClassifiedTurn): Map {
}
export type CohortObservation = {
- /** Owning session id. Not globally unique by itself: pair with `project` for
- * identity, per the app's canonical-identity rules. */
+ /** Owning session id. Not globally unique by itself: pair with `provider` and
+ * `project` for identity, per the app's canonical-identity rules. */
sessionId: string
- /** Project label exactly as reports print it (`ProjectSummary.project`). */
+ /** Same provider/project/session triple the sessions report keys rows by, so
+ * drill-through resolves an observation to exactly one session row. */
+ provider: string
project: string
timestamp: string
category: TaskCategory
@@ -145,7 +147,7 @@ export function extractCohortObservations(
const cost = [...byModel.values()].reduce((sum, c) => sum + c, 0)
exclusions.multiModelTurns.push({
sessionId: session.sessionId,
- project: project.project,
+ project: session.project || project.project,
timestamp: turn.timestamp,
category: turn.category,
models,
@@ -184,7 +186,8 @@ export function extractCohortObservations(
const acc = cohortFor(model)
acc.push({
sessionId: session.sessionId,
- project: project.project,
+ provider: inferSessionProvider(session),
+ project: session.project || project.project,
timestamp: turn.timestamp,
category: turn.category,
model,
diff --git a/src/main.ts b/src/main.ts
index 31eec544..38fcaf49 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -2258,7 +2258,13 @@ program
process.exit(1)
}
await loadPricing()
- const customRange = parseDateRangeFlags(opts.from, opts.to)
+ let customRange: DateRange | null = null
+ try {
+ customRange = parseDateRangeFlags(opts.from, opts.to)
+ } catch (err) {
+ console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`)
+ process.exit(1)
+ }
const { range, label } = customRange
? { range: customRange, label: formatDateRangeLabel(opts.from, opts.to) }
: getDateRange(opts.period)
diff --git a/src/serve.ts b/src/serve.ts
index 66ecfb28..18a254d6 100644
--- a/src/serve.ts
+++ b/src/serve.ts
@@ -107,9 +107,11 @@ const SERVE_OPTIONS: Readonly {
expect(stats.distinctSessionCount).toBe(2)
expect(stats.observationCount).toBe(2)
})
+
+ it('carries the same provider/project/session triple the sessions report keys rows by', () => {
+ const project = makeProject('s1', [makeTurn('opus-4-6', 0.10)], 'proj-a')
+ const [observation] = extractCohortObservations({ projects: [project] }).perModel.get('opus-4-6') ?? []
+ const [row] = aggregateSessions([project])
+ expect([observation?.provider, observation?.project, observation?.sessionId])
+ .toEqual([row?.provider, row?.project, row?.sessionId])
+ })
})
// ————— Cost semantics: unknown ≠ zero —————