From 1be0875fce8cbd94669223c9117c261b4ce76eeb Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sat, 22 Aug 2026 23:55:27 +0530 Subject: [PATCH 01/19] fix(doctor): treat Buzz as a launcher, not a second Codex tree A ~/.buzz/.codex nest is skipped when a distinct primary Codex home exists. doctor lists Buzz (and Grok Bot) as launchers with no session count so the billed seat is not double-counted. --- src/doctor.ts | 15 +++++++ src/launcher-homes.ts | 56 +++++++++++++++++++++++ src/providers/codex.ts | 11 ++++- tests/launcher-homes.test.ts | 86 ++++++++++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 src/launcher-homes.ts create mode 100644 tests/launcher-homes.test.ts diff --git a/src/doctor.ts b/src/doctor.ts index 95a3d44d..b6ad3cc1 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -14,6 +14,7 @@ import { type SessionCache, } from './session-cache.js' import { renderTable } from './text-table.js' +import { collectLauncherNotes, type LauncherNote } from './launcher-homes.js' // ── Types ────────────────────────────────────────────────────────────── @@ -71,6 +72,8 @@ export type ClaudeRetentionNote = { export type DoctorReport = { generatedAt: string providers: DoctorProviderReport[] + /** Nests that drive another billed store. Never given a session count. */ + launchers?: LauncherNote[] /// Present when the Claude provider is in the report and a config dir was /// found. Surfaced because deleted transcripts are unrecoverable: daily /// totals survive in CodeBurn's cache, but per-session detail does not. @@ -84,6 +87,8 @@ export type CollectDoctorOptions = { cache?: SessionCache /** Max discovered sources to parse-sample per provider. */ sampleLimit?: number + /** Injectable launcher notes (defaults to scanning the real home). */ + launchers?: LauncherNote[] } // Bound the parse sample: at most this many discovered sources per provider, @@ -330,6 +335,8 @@ export async function collectDoctorReport( providers.sort((a, b) => (a.displayName < b.displayName ? -1 : a.displayName > b.displayName ? 1 : 0)) const report: DoctorReport = { generatedAt: new Date().toISOString(), providers } + const launchers = opts.launchers ?? collectLauncherNotes() + if (launchers.length > 0) report.launchers = launchers if (providers.some(p => p.provider === 'claude')) { const retention = await collectClaudeRetention() if (retention) report.claudeRetention = retention @@ -445,6 +452,14 @@ export function renderDoctorTable( } } + if (report.launchers && report.launchers.length > 0) { + out.push('') + out.push(c.bold('Launchers')) + for (const launcher of report.launchers) { + out.push(` ${launcher.name} ${c.dim(launcher.path)} ${launcher.verdict}`) + } + } + if (report.claudeRetention) { const r = report.claudeRetention const source = r.configured ? 'cleanupPeriodDays' : 'cleanupPeriodDays not set; Claude Code default' diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts new file mode 100644 index 00000000..97b103d6 --- /dev/null +++ b/src/launcher-homes.ts @@ -0,0 +1,56 @@ +import { existsSync } from 'fs' +import { homedir } from 'os' +import { join, resolve, sep } from 'path' + +export type LauncherNote = { + name: string + path: string + billedVia: string + verdict: string +} + +/** True when `dir` is a Codex home nested under a launcher nest, and a distinct + * primary Codex home exists. Scanning it would double-count the billed seat. */ +export function isNestedLauncherCodexHome( + dir: string, + opts: { primaryDir: string; launcherRoots: string[] }, +): boolean { + const resolved = resolve(dir) + const primary = resolve(opts.primaryDir) + if (resolved === primary) return false + const underLauncher = opts.launcherRoots.some(root => { + const r = resolve(root) + return resolved === r || resolved.startsWith(r + sep) + }) + if (!underLauncher) return false + return existsSync(primary) +} + +export function defaultLauncherRoots(): string[] { + return [join(homedir(), '.buzz')] +} + +/** Surfaces that drive another billed store. Not providers. No session count. */ +export function collectLauncherNotes(home = homedir()): LauncherNote[] { + const notes: LauncherNote[] = [] + const buzz = join(home, '.buzz') + if (existsSync(buzz)) { + notes.push({ + name: 'buzz', + path: buzz, + billedVia: 'codex', + verdict: 'LAUNCHER (no usage store; billed via Codex)', + }) + } + const grokStore = join(home, '.grok') + const grokBot = join(home, 'Library', 'Application Support', 'Grok Bot') + if (existsSync(grokBot) && existsSync(grokStore)) { + notes.push({ + name: 'grok-bot', + path: grokBot, + billedVia: 'grok', + verdict: 'LAUNCHER (Electron cache; billed via ~/.grok)', + }) + } + return notes +} diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 0ff061c3..b72a2497 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -12,6 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import { defaultLauncherRoots, isNestedLauncherCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -1329,8 +1330,15 @@ export async function parseCodexFileFull(source: SessionSource, seenKeys: Set { + if (skipNested) return [] return discoverSessionsInDir(dir) }, diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts new file mode 100644 index 00000000..d5238634 --- /dev/null +++ b/tests/launcher-homes.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises' +import { join } from 'path' +import { tmpdir } from 'os' + +import { collectLauncherNotes, isNestedLauncherCodexHome } from '../src/launcher-homes.js' +import { collectDoctorReport, renderDoctorTable } from '../src/doctor.js' +import { createCodexProvider } from '../src/providers/codex.js' +import { emptyCache } from '../src/session-cache.js' + +function sessionMeta(): string { + return JSON.stringify({ + type: 'session_meta', + timestamp: '2026-04-14T10:00:00Z', + payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: 'sess-001', model: 'gpt-5.3-codex' }, + }) +} + +async function writeCodexSession(codexDir: string, name = 'rollout-sess-001.jsonl'): Promise { + const dayDir = join(codexDir, 'sessions', '2026', '04', '14') + await mkdir(dayDir, { recursive: true }) + await writeFile(join(dayDir, name), `${sessionMeta()}\n`) +} + +describe('isNestedLauncherCodexHome', () => { + it('skips a Codex home under .buzz when a distinct primary home exists', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const primary = join(root, 'real-codex') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(primary, { recursive: true }) + await mkdir(nested, { recursive: true }) + expect(isNestedLauncherCodexHome(nested, { primaryDir: primary, launcherRoots: [buzz] })).toBe(true) + await rm(root, { recursive: true, force: true }) + }) + + it('does not skip the sole Codex home even if it sits under .buzz', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(nested, { recursive: true }) + expect(isNestedLauncherCodexHome(nested, { primaryDir: nested, launcherRoots: [buzz] })).toBe(false) + await rm(root, { recursive: true, force: true }) + }) +}) + +describe('Codex discover skips nested Buzz home', () => { + let root: string + beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'codex-buzz-')) }) + afterEach(async () => { await rm(root, { recursive: true, force: true }) }) + + it('counts only the primary tree when a Buzz nest also has rollouts', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl') + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const real = createCodexProvider(primary, { primaryDir: primary, launcherRoots: [buzz] }) + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect((await real.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) + expect(await nest.discoverSessions()).toEqual([]) + }) +}) + +describe('doctor launchers', () => { + it('lists Buzz as a launcher with no session count', async () => { + const home = await mkdtemp(join(tmpdir(), 'home-')) + await mkdir(join(home, '.buzz'), { recursive: true }) + const notes = collectLauncherNotes(home) + expect(notes).toEqual([expect.objectContaining({ name: 'buzz', billedVia: 'codex' })]) + expect(notes[0]!.verdict).toMatch(/LAUNCHER/) + expect(notes[0]!.verdict).not.toMatch(/\\d+ session/) + + const report = await collectDoctorReport('all', { + providers: [createCodexProvider(join(home, 'empty-codex'))], + cache: emptyCache(), + launchers: notes, + }) + expect(report.launchers).toEqual(notes) + const table = renderDoctorTable(report, { color: false }) + expect(table).toContain('Launchers') + expect(table).toContain('buzz') + expect(table).toContain('billed via Codex') + await rm(home, { recursive: true, force: true }) + }) +}) From f31d84aad37dcfc143d5d4fd07001263204695aa Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 00:08:14 +0530 Subject: [PATCH 02/19] fix(doctor): do not treat a Buzz CODEX_HOME as the primary home When CODEX_HOME points at ~/.buzz/.codex and ~/.codex exists, walk the billed home. An explicit nested factory still returns no sessions. --- src/launcher-homes.ts | 4 ++++ src/providers/codex.ts | 12 ++++++++--- tests/launcher-homes.test.ts | 42 +++++++++++++++++++++++++++++++++++- 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index 97b103d6..34f15543 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -26,6 +26,10 @@ export function isNestedLauncherCodexHome( return existsSync(primary) } +export function defaultBilledCodexHome(): string { + return join(homedir(), '.codex') +} + export function defaultLauncherRoots(): string[] { return [join(homedir(), '.buzz')] } diff --git a/src/providers/codex.ts b/src/providers/codex.ts index b72a2497..b4a3e810 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -12,7 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' -import { defaultLauncherRoots, isNestedLauncherCodexHome } from '../launcher-homes.js' +import { defaultBilledCodexHome, defaultLauncherRoots, isNestedLauncherCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -1335,8 +1335,9 @@ export function createCodexProvider( opts?: { primaryDir?: string; launcherRoots?: string[] }, ): Provider { const dir = getCodexDir(codexDir) + const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome() const skipNested = isNestedLauncherCodexHome(dir, { - primaryDir: opts?.primaryDir ?? getCodexDir(), + primaryDir, launcherRoots: opts?.launcherRoots ?? defaultLauncherRoots(), }) @@ -1365,7 +1366,12 @@ export function createCodexProvider( }, async discoverSessions(): Promise { - if (skipNested) return [] + if (skipNested) { + // CODEX_HOME pointed at a launcher nest: walk the billed ~/.codex home + // instead. An explicit nested factory (tests / second tree) stays empty. + if (codexDir === undefined) return discoverSessionsInDir(primaryDir) + return [] + } return discoverSessionsInDir(dir) }, diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index d5238634..e4c9e429 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -60,6 +60,46 @@ describe('Codex discover skips nested Buzz home', () => { expect((await real.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) expect(await nest.discoverSessions()).toEqual([]) }) + + it('default factory with CODEX_HOME in .buzz walks ~/.codex, not the nest', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl') + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + try { + const provider = createCodexProvider() + expect((await provider.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('keeps a sole CODEX_HOME nest when ~/.codex does not exist', async () => { + const home = root + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + try { + const provider = createCodexProvider() + expect((await provider.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-buzz.jsonl']) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) }) describe('doctor launchers', () => { @@ -69,7 +109,7 @@ describe('doctor launchers', () => { const notes = collectLauncherNotes(home) expect(notes).toEqual([expect.objectContaining({ name: 'buzz', billedVia: 'codex' })]) expect(notes[0]!.verdict).toMatch(/LAUNCHER/) - expect(notes[0]!.verdict).not.toMatch(/\\d+ session/) + expect(notes[0]!.verdict).not.toMatch(/\d+\s+session/) const report = await collectDoctorReport('all', { providers: [createCodexProvider(join(home, 'empty-codex'))], From 4296db737b8ceb522f1e47854c022c62a375722d Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 00:13:46 +0530 Subject: [PATCH 03/19] fix(doctor): keep Codex probeRoots on the tree actually scanned A Buzz CODEX_HOME now redirects discovery and probeRoots to ~/.codex together. An explicit nest factory still has no sessions and no roots. --- src/providers/codex.ts | 17 ++++++++--------- tests/launcher-homes.test.ts | 5 +++++ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/providers/codex.ts b/src/providers/codex.ts index b4a3e810..e3c68afb 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -1340,6 +1340,9 @@ export function createCodexProvider( primaryDir, launcherRoots: opts?.launcherRoots ?? defaultLauncherRoots(), }) + // One tree for discovery and probeRoots. A nest CODEX_HOME with a distinct + // billed home redirects the default factory; an explicit nest factory is empty. + const scannedDir = skipNested ? (codexDir === undefined ? primaryDir : null) : dir return { name: 'codex', @@ -1359,20 +1362,16 @@ export function createCodexProvider( // Same `dir` discoverSessionsInDir walks: /sessions (dated // rollout files) and /archived_sessions. Honors CODEX_HOME. async probeRoots(): Promise { + if (!scannedDir) return [] return [ - { path: join(dir, 'sessions'), label: 'sessions' }, - { path: join(dir, 'archived_sessions'), label: 'archived' }, + { path: join(scannedDir, 'sessions'), label: 'sessions' }, + { path: join(scannedDir, 'archived_sessions'), label: 'archived' }, ] }, async discoverSessions(): Promise { - if (skipNested) { - // CODEX_HOME pointed at a launcher nest: walk the billed ~/.codex home - // instead. An explicit nested factory (tests / second tree) stays empty. - if (codexDir === undefined) return discoverSessionsInDir(primaryDir) - return [] - } - return discoverSessionsInDir(dir) + if (!scannedDir) return [] + return discoverSessionsInDir(scannedDir) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index e4c9e429..fc2541e0 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -74,6 +74,11 @@ describe('Codex discover skips nested Buzz home', () => { try { const provider = createCodexProvider() expect((await provider.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) + const roots = await provider.probeRoots!() + expect(roots.map(r => r.path)).toEqual([ + join(primary, 'sessions'), + join(primary, 'archived_sessions'), + ]) } finally { if (prevHome === undefined) delete process.env.HOME else process.env.HOME = prevHome From 17bb4bfdda8d5cf79630db5987e3b8a6d16e00e9 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:13:07 +0530 Subject: [PATCH 04/19] fix(codex): drop only overlapping nest rollouts A second createCodexProvider(nest, {primaryDir, launcherRoots}) filters shared rollout-*.jsonl basenames. The production singleton honors CODEX_HOME and never hides unique nest sessions because ~/.codex exists. --- src/launcher-homes.ts | 50 +++++++++++++++++-- src/providers/codex.ts | 34 ++++++++----- tests/launcher-homes.test.ts | 97 +++++++++++++++++++++++++----------- 3 files changed, 135 insertions(+), 46 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index 34f15543..9945e384 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -1,4 +1,4 @@ -import { existsSync } from 'fs' +import { existsSync, readdirSync, realpathSync } from 'fs' import { homedir } from 'os' import { join, resolve, sep } from 'path' @@ -9,23 +9,63 @@ export type LauncherNote = { verdict: string } +function resolveHome(dir: string): string { + try { + return realpathSync(dir) + } catch { + return resolve(dir) + } +} + /** True when `dir` is a Codex home nested under a launcher nest, and a distinct - * primary Codex home exists. Scanning it would double-count the billed seat. */ + * primary Codex home exists. Gate for overlap-only filtering on a *second* + * provider instance — it does not by itself drop sessions. */ export function isNestedLauncherCodexHome( dir: string, opts: { primaryDir: string; launcherRoots: string[] }, ): boolean { - const resolved = resolve(dir) - const primary = resolve(opts.primaryDir) + const resolved = resolveHome(dir) + const primary = resolveHome(opts.primaryDir) if (resolved === primary) return false const underLauncher = opts.launcherRoots.some(root => { - const r = resolve(root) + const r = resolveHome(root) return resolved === r || resolved.startsWith(r + sep) }) if (!underLauncher) return false return existsSync(primary) } +/** Rollout basenames under a Codex home (sessions/YYYY/MM/DD + archived). */ +export function listRolloutBasenames(codexDir: string): Set { + const names = new Set() + const take = (file: string) => { + if (file.startsWith('rollout-') && file.endsWith('.jsonl')) names.add(file) + } + const sessionsDir = join(codexDir, 'sessions') + try { + for (const year of readdirSync(sessionsDir)) { + if (!/^\d{4}$/.test(year)) continue + const yearDir = join(sessionsDir, year) + for (const month of readdirSync(yearDir)) { + if (!/^\d{2}$/.test(month)) continue + const monthDir = join(yearDir, month) + for (const day of readdirSync(monthDir)) { + if (!/^\d{2}$/.test(day)) continue + for (const file of readdirSync(join(monthDir, day))) take(file) + } + } + } + } catch { + // missing tree + } + try { + for (const file of readdirSync(join(codexDir, 'archived_sessions'))) take(file) + } catch { + // missing archive + } + return names +} + export function defaultBilledCodexHome(): string { return join(homedir(), '.codex') } diff --git a/src/providers/codex.ts b/src/providers/codex.ts index e3c68afb..6f2dd9a9 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -12,7 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' -import { defaultBilledCodexHome, defaultLauncherRoots, isNestedLauncherCodexHome } from '../launcher-homes.js' +import { defaultBilledCodexHome, isNestedLauncherCodexHome, listRolloutBasenames } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -1336,13 +1336,20 @@ export function createCodexProvider( ): Provider { const dir = getCodexDir(codexDir) const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome() - const skipNested = isNestedLauncherCodexHome(dir, { - primaryDir, - launcherRoots: opts?.launcherRoots ?? defaultLauncherRoots(), - }) - // One tree for discovery and probeRoots. A nest CODEX_HOME with a distinct - // billed home redirects the default factory; an explicit nest factory is empty. - const scannedDir = skipNested ? (codexDir === undefined ? primaryDir : null) : dir + // Production singleton (no args) honors CODEX_HOME / override as the one + // root. Unique nest sessions must never be dropped because ~/.codex exists. + // Only a second factory — createCodexProvider(nestPath, {primaryDir, + // launcherRoots}) — may drop overlapping rollout-*.jsonl basenames. + const secondPrimary = opts?.primaryDir + const secondRoots = opts?.launcherRoots + const filterOverlap = + codexDir !== undefined && + secondPrimary !== undefined && + secondRoots !== undefined && + isNestedLauncherCodexHome(dir, { + primaryDir: secondPrimary, + launcherRoots: secondRoots, + }) return { name: 'codex', @@ -1362,16 +1369,17 @@ export function createCodexProvider( // Same `dir` discoverSessionsInDir walks: /sessions (dated // rollout files) and /archived_sessions. Honors CODEX_HOME. async probeRoots(): Promise { - if (!scannedDir) return [] return [ - { path: join(scannedDir, 'sessions'), label: 'sessions' }, - { path: join(scannedDir, 'archived_sessions'), label: 'archived' }, + { path: join(dir, 'sessions'), label: 'sessions' }, + { path: join(dir, 'archived_sessions'), label: 'archived' }, ] }, async discoverSessions(): Promise { - if (!scannedDir) return [] - return discoverSessionsInDir(scannedDir) + const sources = await discoverSessionsInDir(dir) + if (!filterOverlap) return sources + const primaryNames = listRolloutBasenames(primaryDir) + return sources.filter(source => !primaryNames.has(basename(source.path))) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index fc2541e0..ea168f73 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' -import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises' +import { mkdtemp, mkdir, writeFile, rm, symlink } from 'fs/promises' import { join } from 'path' import { tmpdir } from 'os' @@ -22,6 +22,10 @@ async function writeCodexSession(codexDir: string, name = 'rollout-sess-001.json await writeFile(join(dayDir, name), `${sessionMeta()}\n`) } +function names(sources: { path: string }[]): string[] { + return sources.map(s => s.path.split('/').pop()!) +} + describe('isNestedLauncherCodexHome', () => { it('skips a Codex home under .buzz when a distinct primary home exists', async () => { const root = await mkdtemp(join(tmpdir(), 'launch-')) @@ -42,14 +46,26 @@ describe('isNestedLauncherCodexHome', () => { expect(isNestedLauncherCodexHome(nested, { primaryDir: nested, launcherRoots: [buzz] })).toBe(false) await rm(root, { recursive: true, force: true }) }) + + it('treats a realpath-equivalent nest as the same home', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const primary = join(root, 'real-codex') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(primary, { recursive: true }) + await mkdir(buzz, { recursive: true }) + await symlink(primary, nested) + expect(isNestedLauncherCodexHome(nested, { primaryDir: primary, launcherRoots: [buzz] })).toBe(false) + await rm(root, { recursive: true, force: true }) + }) }) -describe('Codex discover skips nested Buzz home', () => { +describe('Codex discover overlap-only nest filter', () => { let root: string beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'codex-buzz-')) }) afterEach(async () => { await rm(root, { recursive: true, force: true }) }) - it('counts only the primary tree when a Buzz nest also has rollouts', async () => { + it('keeps a distinct nest rollout on the second factory', async () => { const primary = join(root, 'primary') const buzz = join(root, '.buzz') const nested = join(buzz, '.codex') @@ -57,11 +73,48 @@ describe('Codex discover skips nested Buzz home', () => { await writeCodexSession(nested, 'rollout-buzz.jsonl') const real = createCodexProvider(primary, { primaryDir: primary, launcherRoots: [buzz] }) const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) - expect((await real.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) - expect(await nest.discoverSessions()).toEqual([]) + expect(names(await real.discoverSessions())).toEqual(['rollout-primary.jsonl']) + expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz.jsonl']) }) - it('default factory with CODEX_HOME in .buzz walks ~/.codex, not the nest', async () => { + it('filters only a nest rollout whose basename overlaps the primary tree', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-shared.jsonl') + await writeCodexSession(nested, 'rollout-shared.jsonl') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl') + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz-only.jsonl']) + }) + + it('default factory with CODEX_HOME=nest and a stub ~/.codex still discovers the nest', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await mkdir(primary, { recursive: true }) + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + try { + const provider = createCodexProvider() + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + const roots = await provider.probeRoots!() + expect(roots.map(r => r.path)).toEqual([ + join(nested, 'sessions'), + join(nested, 'archived_sessions'), + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('default factory with CODEX_HOME=nest does not drop unique nest rollouts when ~/.codex has its own', async () => { const home = root const primary = join(home, '.codex') const nested = join(home, '.buzz', '.codex') @@ -73,12 +126,7 @@ describe('Codex discover skips nested Buzz home', () => { process.env.CODEX_HOME = nested try { const provider = createCodexProvider() - expect((await provider.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-primary.jsonl']) - const roots = await provider.probeRoots!() - expect(roots.map(r => r.path)).toEqual([ - join(primary, 'sessions'), - join(primary, 'archived_sessions'), - ]) + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) } finally { if (prevHome === undefined) delete process.env.HOME else process.env.HOME = prevHome @@ -87,23 +135,13 @@ describe('Codex discover skips nested Buzz home', () => { } }) - it('keeps a sole CODEX_HOME nest when ~/.codex does not exist', async () => { - const home = root - const nested = join(home, '.buzz', '.codex') + it('explicit nest path without second-factory opts is not silently emptied', async () => { + const primary = join(root, 'primary') + const nested = join(root, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl') await writeCodexSession(nested, 'rollout-buzz.jsonl') - const prevHome = process.env.HOME - const prevCodex = process.env.CODEX_HOME - process.env.HOME = home - process.env.CODEX_HOME = nested - try { - const provider = createCodexProvider() - expect((await provider.discoverSessions()).map(s => s.path.split('/').pop())).toEqual(['rollout-buzz.jsonl']) - } finally { - if (prevHome === undefined) delete process.env.HOME - else process.env.HOME = prevHome - if (prevCodex === undefined) delete process.env.CODEX_HOME - else process.env.CODEX_HOME = prevCodex - } + const provider = createCodexProvider(nested) + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) }) }) @@ -126,6 +164,9 @@ describe('doctor launchers', () => { expect(table).toContain('Launchers') expect(table).toContain('buzz') expect(table).toContain('billed via Codex') + const buzzLine = table.split('\n').find(line => /^\s*buzz\s/.test(line)) + expect(buzzLine).toBeDefined() + expect(buzzLine).not.toMatch(/\d+\s+session/) await rm(home, { recursive: true, force: true }) }) }) From e8ab5086fef61854d32b4ed7f668a0b644470691 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:30:11 +0530 Subject: [PATCH 05/19] fix(codex): empty a realpath-alias nest factory A second factory whose path is a distinct alias of the primary home is complete overlap, not a distinct nest. The primary factory itself still discovers. --- src/launcher-homes.ts | 5 +++++ src/providers/codex.ts | 13 +++++++++++-- tests/launcher-homes.test.ts | 13 +++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index 9945e384..bb7f69f5 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -17,6 +17,11 @@ function resolveHome(dir: string): string { } } +/** True when two Codex homes are the same physical tree. */ +export function sameCodexHome(a: string, b: string): boolean { + return resolveHome(a) === resolveHome(b) +} + /** True when `dir` is a Codex home nested under a launcher nest, and a distinct * primary Codex home exists. Gate for overlap-only filtering on a *second* * provider instance — it does not by itself drop sessions. */ diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 6f2dd9a9..2d2d6a0c 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -1,7 +1,7 @@ import { readdir, stat } from 'fs/promises' import { createReadStream } from 'fs' import { createInterface } from 'readline' -import { basename, join } from 'path' +import { basename, join, resolve } from 'path' import { homedir } from 'os' import { readSessionLines } from '../fs-utils.js' @@ -12,7 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' -import { defaultBilledCodexHome, isNestedLauncherCodexHome, listRolloutBasenames } from '../launcher-homes.js' +import { defaultBilledCodexHome, isNestedLauncherCodexHome, listRolloutBasenames, sameCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -1342,6 +1342,12 @@ export function createCodexProvider( // launcherRoots}) — may drop overlapping rollout-*.jsonl basenames. const secondPrimary = opts?.primaryDir const secondRoots = opts?.launcherRoots + const duplicateHome = + codexDir !== undefined && + secondPrimary !== undefined && + secondRoots !== undefined && + sameCodexHome(dir, secondPrimary) && + resolve(dir) !== resolve(secondPrimary) const filterOverlap = codexDir !== undefined && secondPrimary !== undefined && @@ -1376,6 +1382,9 @@ export function createCodexProvider( }, async discoverSessions(): Promise { + // Same physical tree via two factories is complete overlap, not a + // distinct nest. isNestedLauncherCodexHome is false in that case. + if (duplicateHome) return [] const sources = await discoverSessionsInDir(dir) if (!filterOverlap) return sources const primaryNames = listRolloutBasenames(primaryDir) diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index ea168f73..59a3dae5 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -135,6 +135,19 @@ describe('Codex discover overlap-only nest filter', () => { } }) + it('second factory on a realpath-equivalent nest emits no duplicate sources', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-same-physical-tree.jsonl') + await mkdir(buzz, { recursive: true }) + await symlink(primary, nested) + const real = createCodexProvider(primary, { primaryDir: primary, launcherRoots: [buzz] }) + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await real.discoverSessions())).toEqual(['rollout-same-physical-tree.jsonl']) + expect(await nest.discoverSessions()).toEqual([]) + }) + it('explicit nest path without second-factory opts is not silently emptied', async () => { const primary = join(root, 'primary') const nested = join(root, '.buzz', '.codex') From 5b25641440b03063278b380b29b045daa4e9109f Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:42:38 +0530 Subject: [PATCH 06/19] Price and label OrcaRouter gateway model ids as the model they route to Add orcarouter/ as a routing wrapper like cmd/ and antigravity/, alias the smart and fusion routes to their current upstream rows, and give each route a branded display name. Unknown vendors nested inside the route still fail closed. --- CHANGELOG.md | 5 ++++- README.md | 2 +- src/models.ts | 28 +++++++++++++++++++++++++++- tests/models.test.ts | 42 +++++++++++++++++++++++++++++++++++++++++- 4 files changed, 73 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e21dddda..d3853f33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ - **`CODEBURN_CACHE_SCOPE=all` forces a full session-cache read.** A ranged query reads only the month shards that can contribute a turn to it, which is a real behaviour change on a warm cache; this is the escape hatch for the case where a number looks wrong and you want to know whether the scoped read is why. Set it and every load ignores its scope and reads every shard, one-shot runs and the resident `codeburn serve` alike. It is a read policy, not an input to any cache fingerprint: setting or unsetting it re-parses nothing and invalidates nothing. +### Added (OrcaRouter) +- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; the smart route `orcarouter/auto` aliases to a fast Sonnet rate and the fusion routes alias to their current `openai/gpt-oss-120b` target, each keeping a branded route label (like the other `*-auto` presets); and an unknown vendor nested inside the route still fails closed. + ### Added (Windows) - **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls. - **A menubar app for Windows.** `windows/` is a Tauri 2 tray app — Rust binary, React popover — that puts today's spend in the notification area and mirrors the macOS menubar screen for screen: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, CSV/JSON export, launch at login, currency, and theme. Windows has no menubar title, so the number lives in a second tray icon rendered from the system font at the panel's native icon size (Settings can turn it off; the tooltip always carries it). It reads everything through the CLI like the macOS and GNOME clients do, and gates on **codeburn 0.9.9 or newer** — the first release accepting `status --format menubar-json --no-optimize` — showing a setup screen with the install command until it finds one. Refresh follows popover visibility the way the macOS app does: 60 s with optimize findings while open, 2 minutes for today's total while closed, and immediately on open when what you are looking at has gone stale. The Claude quota view never spends Claude's single-use refresh token; on a 401 it re-reads Claude Code's own credential file for a token it has already rotated, matching the macOS client. Ships as an unsigned `.msi` from the `windows-v*` tag, which `codeburn menubar` now installs for you. The same crate still builds and runs a tray on Linux, but that stays experimental and unreleased — `gnome/` is the supported Linux surface. @@ -21,7 +24,7 @@ ### Changed - **The discovery sweep issues its metadata syscalls concurrently.** Every dated command re-walks and re-stats every provider tree before it can decide what is already cached, and that sweep was strictly serial: one `readdir`, one `stat`, one `state.json` read at a time, per provider, one provider after another. On a 21k-file / 9-provider corpus it owned most of a warm run's wall clock while the machine sat idle waiting on the kernel. Provider discovery now runs across providers at once, and the four walks that dominate it (claude, codex, kimicode, grok) plus the Claude project-dir walk and both fingerprint passes fan out through a shared bounded-concurrency helper. Order is unchanged everywhere — each level is re-concatenated in registry/`readdir` order before anything reconciles against the cache — so what is discovered, in what sequence, is byte-identical to the serial walk. Two smaller cuts ride along: the Claude walk reads directory entries with their types so a plain file no longer costs a wasted `subagents/` probe, and the Codex result cache (a single file that can reach hundreds of MB) now shares one in-flight load between concurrent readers instead of letting each one re-read and re-parse it. Warm `codeburn today` on that corpus: 5.30s to 2.99s; a cold parse 34.7s to 31.1s. (#1104) - **A kill mid-way through a non-Claude provider phase no longer restarts that whole phase.** `scanProjectDirs` (Claude) has long taken a throttled `saveProgress` callback so a killed cold parse resumes from a warm cache; `parseProviderSources` (every other provider — codex, cursor, gemini, and the rest) did not, and only persisted at the whole-provider boundary. On a large single-provider corpus (a multi-GB codex history is the common case) an app-timeout SIGKILL, crash, or force-quit during that phase discarded everything parsed since the last provider finished, forcing the entire phase to re-parse from zero on the next run. `parseProviderSources` now takes the same callback, invoked once per source right after that source's cache entry lands (mirroring `scanProjectDirs`' placement, outside the per-file try/catch), on the same file-count/wall-clock throttle. A file only ever gets a fingerprint once it has fully parsed, so a mid-file kill can never leave a half-parsed file's entry looking complete on resume. -- **Routed model ids price as the model they wrap, and an unknown vendor prefix no longer prices by blind stripping.** Token-plan and gateway spellings of the same model (`omniroute:`, `cp/`, `cline-pass/`, `cline-free/`, `cmd/`, `antigravity/`) are peeled and the remaining id is priced, so a Cline Pass or OmniRoute session shows a `~` estimate instead of $0. In exchange, `provider/model` is no longer treated as authority on its own: the leading segment is stripped only when it is a namespace the bundled pricing catalog itself uses (`anthropic/`, `openai/`, `google/`, `x-ai/`, `qwen/`, `moonshotai/`, `nousresearch/`, `xiaomi/`, `z-ai/`, and every other vendor prefix in the LiteLLM snapshot), one of the routing wrappers above, or one of the client-side spellings `kimi/`, `mimo/`, `zhipu/`, `litellm_proxy/` and `openai_like/`. Anything else stays unpriced and is reported as unpriced rather than inheriting the price of a same-named cloud row, and local-runner prefixes (`ollama/`, `lmstudio/`, `hosted_vllm/`, `local/`) are excluded on purpose so an unlisted local tag can never invent cloud spend. A user price override for the bare id wins over the catalog row a routed spelling would otherwise hit. +- **Routed model ids price as the model they wrap, and an unknown vendor prefix no longer prices by blind stripping.** Token-plan and gateway spellings of the same model (`omniroute:`, `cp/`, `cline-pass/`, `cline-free/`, `cmd/`, `antigravity/`, `orcarouter/`) are peeled and the remaining id is priced, so a Cline Pass or OmniRoute session shows a `~` estimate instead of $0. In exchange, `provider/model` is no longer treated as authority on its own: the leading segment is stripped only when it is a namespace the bundled pricing catalog itself uses (`anthropic/`, `openai/`, `google/`, `x-ai/`, `qwen/`, `moonshotai/`, `nousresearch/`, `xiaomi/`, `z-ai/`, and every other vendor prefix in the LiteLLM snapshot), one of the routing wrappers above, or one of the client-side spellings `kimi/`, `mimo/`, `zhipu/`, `litellm_proxy/` and `openai_like/`. Anything else stays unpriced and is reported as unpriced rather than inheriting the price of a same-named cloud row, and local-runner prefixes (`ollama/`, `lmstudio/`, `hosted_vllm/`, `local/`) are excluded on purpose so an unlisted local tag can never invent cloud spend. A user price override for the bare id wins over the catalog row a routed spelling would otherwise hit. - **SQLite providers now survive read-only database parents.** A read-only SQLite open is not read-only on disk: on a WAL database SQLite must create `-shm` and `-wal` in the database's own directory, so a source on read-only media, under restrictive permissions, or inside a Flatpak/snap confinement failed with `attempt to write a readonly database` (or `unable to open database file` when a `-wal` was present without its `-shm`), and both discovery sites swallowed it — the provider read as "not installed" rather than as an error. That covers cursor, cursor-agent, opencode, goose, warp, kilo-code, zerostack and the copilot agent-traces database. The direct open stays the fast path and is byte-identical when it succeeds. When it fails for want of sidecars: a database with no WAL frames to lose is opened in place with `immutable=1`, which costs nothing and cannot go stale; a database with a non-empty `-wal` is copied with its `-wal` into the CodeBurn cache and read there, so its un-checkpointed rows are never silently dropped. The copy costs one database's worth of disk and is taken once per change — it is keyed by the main-plus-WAL fingerprint, published under a fingerprint-stamped name so a refresh never overwrites a copy another process is reading, and superseded copies are evicted once a day has passed without a read, keeping at most one predecessor. If the cache itself cannot be written, the database is skipped with a notice naming it and the reason rather than in silence. The original provider database is never opened writable or modified. - **Grok Build now reads the CLI's own completed-turn usage instead of estimating it.** Usage comes from the `turn_completed.usage` records Grok CLI already writes into `updates.jsonl` (`inputTokens`, `outputTokens`, `cachedReadTokens`, `cacheCreationTokens`, `reasoningTokens`), deduplicated by `prompt_id` and emitted as one session-level call from the top-level totals. The previous parser reconstructed an estimate from the running `_meta.totalTokens` context counter, so **existing Grok totals will change materially on upgrade** - on one real 568-session corpus cache-read went from 150K to 96.3M tokens, total tokens from 20.0M to 113.9M, and cost from $36.98 to $56.79. Cache read and cache creation are subsets of input and reasoning is a subset of output, so reasoning is clamped to the record's reported output and split back out to match this repo's exclusive-reasoning contract. `modelUsage` only selects a priced attribution id; multi-model rate attribution stays out of scope, so one session is priced at one model's rate. `costUsdTicks` is ignored because its scale is undocumented. Sessions with no usable record - older CLI versions - keep the old context-curve heuristic and stay flagged estimated. **In a session that has at least one `turn_completed` record, turns without one are not counted at all** (their tokens are dropped rather than estimated), and the session is marked estimated instead of claiming full provider coverage. Cached Grok sessions re-parse once. The daily cache re-derives once on first run after upgrade: this is a global re-derivation of every day and every provider, since the daily cache has no per-provider invalidation, but it reads the warm session cache rather than re-parsing transcripts, so it costs seconds (~3s on the corpus above), and the superseded cache file is retained on disk as the baseline for days no source can still re-derive. (#998) - **Codex rollouts parse across worker threads too, and the workload gate now takes bytes or files.** Codex is the bigger half of a real cold parse — a 4 GB rollout corpus against 1.8 GB of Claude sessions — and it was still decoding one file at a time. A whole-file rollout decode now runs on the same pool, against an empty dedup set, and comes back with the calls, the dedup keys it claimed, and the codex-cache entry it would have written; the parent installs all three in the serial loop's order, so `codex-results.json` and every payload come out byte-identical to a serial run. Cross-file state stays where it was: a forked rollout replaying its parent's token_count history collides on the parent's keys and is re-parsed in-process, and no worker ever touches the cache module's per-directory state. Files the Codex cache can serve exactly or resume into from a byte offset never reach a worker — they read a few KB and the resume state belongs to the parent. The workload gate is now pending BYTES alone (200 MB), not file count: 250 pending files holding under a megabyte between them spawned threads that made the run ~5% slower, while a few hundred huge rollouts were being turned away. The count takes `max(pendingFiles / 50, pendingBytes / 200 MB)`, and the per-thread memory budget is derived per parse as `clamp(256 MB, 2 × average pending file + 128 MB, 1 GB)` rather than a flat 256 MB — a 260 MB rollout peaks near 430 MB in its worker and scales linearly with the pool, so the flat figure over-subscribed exactly the workload this adds. The decision is per provider, and at most one pool is alive at a time. diff --git a/README.md b/README.md index 78ac72f1..0ca4aed6 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ Left/right arrow keys switch between Today, 7 Days, 30 Days, Month, 6 Months, an ### Pricing -Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. +Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. Routing-gateway model ids are priced as the model they wrap: [OrcaRouter](https://www.orcarouter.ai) route ids (`orcarouter/auto`, `orcarouter/fusion`, …) peel to the model the gateway routes to, and a nested upstream spelling (`orcarouter/deepseek/deepseek-v4-pro`) prices at that exact row, so a gateway-routed session reports real spend instead of $0. ### Task Categories diff --git a/src/models.ts b/src/models.ts index 652a1924..6923f94c 100644 --- a/src/models.ts +++ b/src/models.ts @@ -344,6 +344,17 @@ const BUILTIN_ALIASES: Record = { 'claude-4-7-opus-xhigh': 'claude-opus-4-7', 'claude-4-7-opus-xhigh-fast': 'claude-opus-4-7', 'qwen-auto': 'claude-sonnet-4-5', + // OrcaRouter's smart route. The route picks a model per request; at the time + // of writing it lands on a Qwen/Llama flash model, so a fast Sonnet rate is + // the honest estimate until the route's target stabilizes (mirrors the + // `*-auto` presets above). + 'orcarouter/auto': 'claude-sonnet-4-5', + // OrcaRouter's fusion routes currently serve openai/gpt-oss-120b (verified + // live 2026-08). If the gateway re-routes them, these drift like any other + // preset estimate; they keep a priced row instead of reporting $0. + 'orcarouter/fusion': 'openai/gpt-oss-120b', + 'orcarouter/fusion-flash': 'openai/gpt-oss-120b', + 'orcarouter/fusion-mini': 'openai/gpt-oss-120b', 'kimi-auto': 'kimi-k2-thinking', 'kimi-code': 'kimi-k2-thinking', 'kimi-for-coding': 'kimi-k2-thinking', @@ -801,7 +812,7 @@ export function resolveCanonicalModelId(model: string): string { // `nousresearch/`, …) is never dropped by a stale list. const EXTRA_NAMESPACES = [ // Routing wrappers (see ROUTER_PREFIXES); no catalog lists them. - 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', + 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter', // LiteLLM route prefixes that never appear as a key prefix. 'litellm_proxy', 'openai_like', // Vendor spellings the catalog indexes under another name: `zhipu` is `z-ai`, @@ -840,6 +851,12 @@ function stripKnownFirstNamespace(model: string): string { // Routing wrappers (OmniRoute, Cline Pass, cmd/, …) are not model ids. // Peel them so any plan/gateway spelling of the same model shares one price. +// OrcaRouter is a gateway that routes to many vendors. Its catalog exposes +// route ids (`orcarouter/auto`, `orcarouter/fusion`, …) and plain vendor ids +// (`deepseek/deepseek-v4-pro`); a route id can also spell a nested upstream +// (`orcarouter/deepseek/deepseek-v4-pro`), and the completion response's +// `model` field reports the upstream id that actually ran. Peeling the prefix +// lets every routed spelling price at the upstream row. const ROUTER_PREFIXES = [ /^omniroute:/i, /^cp\//i, @@ -847,6 +864,7 @@ const ROUTER_PREFIXES = [ /^cline-free\//i, /^cmd\//i, /^antigravity\//i, + /^orcarouter\//i, // `xiaomi/` is NOT peeled: it is the vendor namespace LiteLLM prices under, // and BUILTIN_ALIASES maps the bare MiMo ids INTO it. Peeling would pull the // opposite way. It stays a known namespace via the catalog-derived set. @@ -1149,6 +1167,14 @@ const autoModelNames: Record = { 'openclaw-auto': 'OpenClaw (auto)', 'qwen-auto': 'Qwen (auto)', 'kimi-auto': 'Kimi (auto)', + // OrcaRouter route ids. The smart route routes per request and the fusion + // routes resolve to a gateway-picked upstream, so each keeps its branded + // route label rather than the current upstream's display name. Prices are + // aliased in BUILTIN_ALIASES to the route's current target. + 'orcarouter/auto': 'OrcaRouter (auto)', + 'orcarouter/fusion': 'OrcaRouter Fusion', + 'orcarouter/fusion-flash': 'OrcaRouter Fusion Flash', + 'orcarouter/fusion-mini': 'OrcaRouter Fusion Mini', 'codex-auto-review': 'Codex Auto Review', } diff --git a/tests/models.test.ts b/tests/models.test.ts index 5580ea0a..3652d16b 100644 --- a/tests/models.test.ts +++ b/tests/models.test.ts @@ -138,7 +138,7 @@ describe('getModelCosts', () => { const known = ['anthropic', 'x-ai', 'xai', 'qwen', 'moonshotai', 'nousresearch', 'kimi', 'litellm_proxy', 'openai_like', 'zhipu', 'mimo', 'xiaomi', - 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity'] + 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter'] for (const ns of known) { expect(getModelCosts(`${ns}/zzz-namespace-probe`), ns).not.toBeNull() } @@ -159,10 +159,13 @@ describe('getModelCosts', () => { 'omniroute:cline-free/zzz-router-probe', 'omniroute:antigravity/zzz-router-probe', 'omniroute:cmd/zzz-router-probe', + 'omniroute:orcarouter/zzz-router-probe', ] for (const id of routed) expect(getModelCosts(id), id).not.toBeNull() expect(getModelCosts('omniroute:nosuchvendor/zzz-router-probe')).toBeNull() + // A nested unknown vendor inside a known routing wrapper must fail closed. + expect(getModelCosts('omniroute:orcarouter/nosuchvendor/zzz-router-probe')).toBeNull() }) it('lets a user price override for a bare id win over the routed catalog row', () => { @@ -170,6 +173,36 @@ describe('getModelCosts', () => { expect(getModelCosts('cp/cline-pass/glm-5.3')!.inputCostPerToken).toBe(99 / 1_000_000) expect(getModelCosts('omniroute:cp/cline-pass/glm-5.3')!.outputCostPerToken).toBe(99 / 1_000_000) }) + + it('prices OrcaRouter route ids at their upstream row and the smart route via alias', () => { + // `orcarouter/auto` is a smart route; the alias maps it to a Sonnet flash + // rate rather than leaving it unpriced at $0 (the CLI warns on $0 models). + expect(getModelCosts('orcarouter/auto')!.inputCostPerToken).toBe( + getModelCosts('claude-sonnet-4-5')!.inputCostPerToken, + ) + + // The fusion routes currently resolve to openai/gpt-oss-120b (verified live). + expect(getModelCosts('orcarouter/fusion')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/fusion-flash')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/fusion-mini')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + + // Fully-qualified upstream ids peel to the exact LiteLLM row. + expect(getModelCosts('orcarouter/deepseek/deepseek-v4-pro')!.inputCostPerToken).toBe( + getModelCosts('deepseek/deepseek-v4-pro')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/deepseek/deepseek-v4-flash')!.outputCostPerToken).toBe( + getModelCosts('deepseek/deepseek-v4-flash')!.outputCostPerToken, + ) + + // A route id for an unknown upstream stays unpriced (fail closed). + expect(getModelCosts('orcarouter/nosuchvendor/zzz-router-probe')).toBeNull() + }) }) describe('resolveCanonicalModelId', () => { @@ -247,6 +280,13 @@ describe('getShortModelName', () => { expect(getShortModelName('z-ai/glm-5.3')).toBe('GLM-5.3') expect(getShortModelName('xiaomi/glm-5.3')).toBe('GLM-5.3') expect(getShortModelName('cp/cline-pass/glm-5.3')).toBe('GLM-5.3') + // OrcaRouter route ids peel to the upstream id, which keeps the upstream label. + expect(getShortModelName('orcarouter/deepseek/deepseek-v4-pro')).toBe('DeepSeek v4 Pro') + // The route ids keep their branded labels (like the other `*-auto` presets). + expect(getShortModelName('orcarouter/auto')).toBe('OrcaRouter (auto)') + expect(getShortModelName('orcarouter/fusion')).toBe('OrcaRouter Fusion') + expect(getShortModelName('orcarouter/fusion-flash')).toBe('OrcaRouter Fusion Flash') + expect(getShortModelName('orcarouter/fusion-mini')).toBe('OrcaRouter Fusion Mini') // Grok Build prices via the grok-build-0.1 sibling. expect(getShortModelName('grok-build')).toBe('Grok Build') expect(getShortModelName('grok-build-0.1')).toBe('Grok Build') From dcab9a451cc79fa9497326b550fd4248f7854654 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:59:27 +0530 Subject: [PATCH 07/19] Identify OrcaRouter route ids as the routed model, not a branded label --- CHANGELOG.md | 2 +- src/models.ts | 39 +++++++++++++++++++++------------------ tests/models.test.ts | 17 ++++++++++++----- 3 files changed, 34 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3853f33..d2190248 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ - **`CODEBURN_CACHE_SCOPE=all` forces a full session-cache read.** A ranged query reads only the month shards that can contribute a turn to it, which is a real behaviour change on a warm cache; this is the escape hatch for the case where a number looks wrong and you want to know whether the scoped read is why. Set it and every load ignores its scope and reads every shard, one-shot runs and the resident `codeburn serve` alike. It is a read policy, not an input to any cache fingerprint: setting or unsetting it re-parses nothing and invalidates nothing. ### Added (OrcaRouter) -- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; the smart route `orcarouter/auto` aliases to a fast Sonnet rate and the fusion routes alias to their current `openai/gpt-oss-120b` target, each keeping a branded route label (like the other `*-auto` presets); and an unknown vendor nested inside the route still fails closed. +- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; the smart route `orcarouter/auto` aliases to a fast Sonnet rate and the fusion routes alias to their current `openai/gpt-oss-120b` target, so display and report identity match those routed models; and an unknown vendor nested inside the route still fails closed. ### Added (Windows) - **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls. diff --git a/src/models.ts b/src/models.ts index 6923f94c..c9196aff 100644 --- a/src/models.ts +++ b/src/models.ts @@ -290,8 +290,9 @@ export async function loadPricing(): Promise { // Known model name variants that providers emit but LiteLLM/fallback don't index under. // OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last). -// getCanonicalName strips a KNOWN vendor/router prefix first, so only the -// post-strip forms need to be listed here. +// getCanonicalName strips a KNOWN vendor/router prefix first unless the +// full cleaned id itself is an alias (orcarouter/auto). Post-strip forms +// still cover every other entry here. const BUILTIN_ALIASES: Record = { 'anthropic--claude-4.6-opus': 'claude-opus-4-6', 'anthropic--claude-4.6-sonnet': 'claude-sonnet-4-6', @@ -347,11 +348,12 @@ const BUILTIN_ALIASES: Record = { // OrcaRouter's smart route. The route picks a model per request; at the time // of writing it lands on a Qwen/Llama flash model, so a fast Sonnet rate is // the honest estimate until the route's target stabilizes (mirrors the - // `*-auto` presets above). + // `*-auto` presets above). Display and report identity follow this target. 'orcarouter/auto': 'claude-sonnet-4-5', // OrcaRouter's fusion routes currently serve openai/gpt-oss-120b (verified // live 2026-08). If the gateway re-routes them, these drift like any other - // preset estimate; they keep a priced row instead of reporting $0. + // preset estimate; they keep a priced row instead of reporting $0. Display + // and report identity follow this target, not a branded route label. 'orcarouter/fusion': 'openai/gpt-oss-120b', 'orcarouter/fusion-flash': 'openai/gpt-oss-120b', 'orcarouter/fusion-mini': 'openai/gpt-oss-120b', @@ -785,12 +787,21 @@ function resolveAlias(model: string): string { return model } function getCanonicalName(model: string): string { - return stripKnownFirstNamespace( - model - .replace(/@.*$/, '') - .replace(/-\d{8}$/, '') - .replace(/\[[^\]]*\]$/, ''), - ) + const cleaned = model + .replace(/@.*$/, '') + .replace(/-\d{8}$/, '') + .replace(/\[[^\]]*\]$/, '') + // Full-id aliases (orcarouter/auto) must stay visible so resolveAlias can + // see them. Stripping first would leave a leaf (`auto`) with no mapping. + // Nested wrappers without an alias still peel as before. + if (Object.hasOwn(userAliases, cleaned) || Object.hasOwn(BUILTIN_ALIASES, cleaned)) { + return cleaned + } + const lowercase = cleaned.toLowerCase() + if (lowercase !== cleaned && Object.hasOwn(BUILTIN_ALIASES, lowercase)) { + return cleaned + } + return stripKnownFirstNamespace(cleaned) } /// Alias-resolved identity for report merge. Display names stay cosmetic — @@ -1167,14 +1178,6 @@ const autoModelNames: Record = { 'openclaw-auto': 'OpenClaw (auto)', 'qwen-auto': 'Qwen (auto)', 'kimi-auto': 'Kimi (auto)', - // OrcaRouter route ids. The smart route routes per request and the fusion - // routes resolve to a gateway-picked upstream, so each keeps its branded - // route label rather than the current upstream's display name. Prices are - // aliased in BUILTIN_ALIASES to the route's current target. - 'orcarouter/auto': 'OrcaRouter (auto)', - 'orcarouter/fusion': 'OrcaRouter Fusion', - 'orcarouter/fusion-flash': 'OrcaRouter Fusion Flash', - 'orcarouter/fusion-mini': 'OrcaRouter Fusion Mini', 'codex-auto-review': 'Codex Auto Review', } diff --git a/tests/models.test.ts b/tests/models.test.ts index 3652d16b..b5bc2db0 100644 --- a/tests/models.test.ts +++ b/tests/models.test.ts @@ -218,6 +218,13 @@ describe('resolveCanonicalModelId', () => { expect(resolveCanonicalModelId('claude-opus-4.6')).toBe('claude-opus-4-6') expect(resolveCanonicalModelId('kimi-code')).toBe('kimi-k2-thinking') expect(resolveCanonicalModelId('cline-pass/kimi-k3')).toBe('kimi-k3') + expect(resolveCanonicalModelId('orcarouter/auto')).toBe(resolveCanonicalModelId('claude-sonnet-4-5')) + expect(resolveCanonicalModelId('orcarouter/fusion')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/fusion-flash')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/fusion-mini')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/deepseek/deepseek-v4-pro')).toBe( + resolveCanonicalModelId('deepseek/deepseek-v4-pro'), + ) }) }) @@ -282,11 +289,11 @@ describe('getShortModelName', () => { expect(getShortModelName('cp/cline-pass/glm-5.3')).toBe('GLM-5.3') // OrcaRouter route ids peel to the upstream id, which keeps the upstream label. expect(getShortModelName('orcarouter/deepseek/deepseek-v4-pro')).toBe('DeepSeek v4 Pro') - // The route ids keep their branded labels (like the other `*-auto` presets). - expect(getShortModelName('orcarouter/auto')).toBe('OrcaRouter (auto)') - expect(getShortModelName('orcarouter/fusion')).toBe('OrcaRouter Fusion') - expect(getShortModelName('orcarouter/fusion-flash')).toBe('OrcaRouter Fusion Flash') - expect(getShortModelName('orcarouter/fusion-mini')).toBe('OrcaRouter Fusion Mini') + // Route ids display as the model they route to, not a branded gateway label. + expect(getShortModelName('orcarouter/auto')).toBe(getShortModelName('claude-sonnet-4-5')) + expect(getShortModelName('orcarouter/fusion')).toBe(getShortModelName('openai/gpt-oss-120b')) + expect(getShortModelName('orcarouter/fusion-flash')).toBe(getShortModelName('openai/gpt-oss-120b')) + expect(getShortModelName('orcarouter/fusion-mini')).toBe(getShortModelName('openai/gpt-oss-120b')) // Grok Build prices via the grok-build-0.1 sibling. expect(getShortModelName('grok-build')).toBe('Grok Build') expect(getShortModelName('grok-build-0.1')).toBe('Grok Build') From 0c7d92a312260135de064b05480ec23b4e0eb0d3 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 19:12:04 +0530 Subject: [PATCH 08/19] feat: Copilot AI Credit plan math from total_nano_aiu Spent credits are finite nanoAiu / 1e9. Token-priced costUSD does not fill the Copilot bar. Thread nanoAiu through cachedCallToApiCall with no cache-version bump. --- CHANGELOG.md | 1 + README.md | 4 +- docs/providers/copilot.md | 5 +- src/config.ts | 7 +- src/copilot-aiu.ts | 19 ++++ src/dashboard.tsx | 11 ++ src/main.ts | 73 +++++++++++-- src/parser.ts | 3 + src/plan-usage.ts | 79 ++++++++++++-- src/plans.ts | 43 +++++++- src/providers/types.ts | 9 +- src/session-cache.ts | 6 +- src/types.ts | 4 + tests/cli-plan.test.ts | 51 +++++++++ tests/copilot-aiu-serve.test.ts | 93 ++++++++++++++++ tests/copilot-aiu.test.ts | 20 ++++ tests/plan-budget-copy.test.ts | 24 +++++ tests/plan-usage.test.ts | 184 ++++++++++++++++++++++++++++++++ tests/plans.test.ts | 5 + 19 files changed, 609 insertions(+), 32 deletions(-) create mode 100644 src/copilot-aiu.ts create mode 100644 tests/copilot-aiu-serve.test.ts create mode 100644 tests/copilot-aiu.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e21dddda..441bb549 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Copilot AI Credit plans.** `codeburn plan set copilot-pro` (1,500 credits / $15 equivalent, not the $10 sticker), `copilot-pro-plus` (7,000), `copilot-max` (20,000), and `custom --credits N --provider copilot`. Spend is `sum(finite nanoAiu) / 1e9`. Token-priced `costUSD` does not fill the credits bar. Claude / cursor / grok / custom-USD plans stay on `costUSD`. (#943) - **`codeburn models --unpriced`.** The dashboard warns about models that price at $0 and points at `codeburn model-alias`, but the list itself was hard to get out of the TUI. This filters the plain-stdout `models` report to exactly those rows, reusing `findUnpricedModels` so local, free, aliased and price-overridden models are treated the same way the warning treats them, and defaulting that mode's min-cost to 0 so $0 rows are not pre-filtered away. Thanks @kocaemre. (#969) - **`optimize` spots the same long block pasted at the start of many sessions.** The new `recurring-context` detector groups sessions by their opening block — normalized for whitespace and ANSI, hashed over the first 2 KB — and reports a block of at least 1.5 KB that opens 5 or more sessions, with the top three by tokens, their session counts and the project each is confined to. It is a habit, not an apply-able fix: CodeBurn will not move your own text into `CLAUDE.md` for you, so the finding asks Claude to give the block a permanent home (a `CLAUDE.md` rule, or a file read on demand) and hand back a one-line pointer to open sessions with instead. Savings count the repeats only, never the first paste, and are marked `estimated`: provider usage is counted per API call, where the pasted block is mixed in with the system prompt, tool schemas and `CLAUDE.md`, so the block is sized from its own bytes. Injected system reminders and slash-command wrappers are not pastes and are skipped, and neither is a prompt a program wrote — an SDK session or a subagent task — read from the entry's flags, which survive the parser's large-line path. The opening block comes from the session scan that already runs, so nothing extra is read from disk. - **Applied fixes get re-measured on every `optimize` run, and told plainly whether they worked.** After `codeburn optimize --apply`, every still-applied fix comes back in an `Applied fixes` section on subsequent `codeburn optimize` runs, carrying the verdict `act report` already computes from the same reconciliation: `worked` (at least 70% of its window-scaled estimate realized), `partial` (something, but under that), `no-effect` (no measured reduction, printed with the exact `codeburn act undo ` that puts it back), or `measuring` for anything younger than the 3-day measurement window. The numbers are measured — provider-counted usage over the post-apply window — not re-estimated. `--apply` now says when the re-measure will happen, `--format json` gains `appliedFixes[]` (add-only), and the same section appears in the dashboard TUI and the desktop app. New `codeburn optimize --auto-revert` undoes the fixes that measured no reduction at all through the same code path as `codeburn act undo`; it never touches `partial` or still-measuring fixes, and never auto-reverts a `CLAUDE.md` rule (it prints the undo command instead), matching the `--yes` guardrail. diff --git a/README.md b/README.md index 78ac72f1..bf1f903a 100644 --- a/README.md +++ b/README.md @@ -568,14 +568,16 @@ For categories that involve code edits, CodeBurn tracks file-aware retry cycles. codeburn plan set claude-max # $200/month codeburn plan set claude-pro # $20/month codeburn plan set cursor-pro # $20/month +codeburn plan set copilot-pro # 1500 AI Credits ($15 equivalent) codeburn plan set custom --monthly-usd 200 --provider codex # ChatGPT Pro-style custom plan +codeburn plan set custom --credits 20000 --provider copilot # org Copilot allotment codeburn plan reset --provider codex # remove one provider plan codeburn plan set none # disable plan view codeburn plan # show configured plans codeburn plan reset # remove plan config ``` -Subscription tracking for Claude Pro, Claude Max, Cursor Pro, and custom provider plans. Plans are stored per provider, so you can track Claude and Codex/Cursor subscriptions at the same time; the dashboard shows one overage line per active provider plan. A legacy/custom `all` plan remains a single aggregate plan and is replaced when you add a provider-specific plan, avoiding double-counted overage rows. Existing single-plan config is still read as a fallback. Presets use publicly stated plan prices (as of April 2026); they do not model exact token allowances, because vendors do not publish precise consumer-plan limits. +Subscription tracking for Claude Pro, Claude Max, Cursor Pro, Copilot (AI credits), and custom provider plans. Plans are stored per provider, so you can track Claude and Codex/Cursor subscriptions at the same time; the dashboard shows one overage line per active provider plan. A legacy/custom `all` plan remains a single aggregate plan and is replaced when you add a provider-specific plan, avoiding double-counted overage rows. Existing single-plan config is still read as a fallback. USD presets use publicly stated plan prices (as of April 2026). Copilot presets use official individual AI-credit allotments (Pro 1,500 / Pro+ 7,000 / Max 20,000; fetched 2026-08-23) — not the $10 / $39 / $100 sticker prices — and spend is `total_nano_aiu / 1e9`, never token-priced USD. ### Currency diff --git a/docs/providers/copilot.md b/docs/providers/copilot.md index 62926388..45fbdeab 100644 --- a/docs/providers/copilot.md +++ b/docs/providers/copilot.md @@ -140,8 +140,9 @@ see the #927 ruling in `src/session-cache.ts`). still re-derive its pruned rows. - **Billing metadata.** Each row's `total_nano_aiu` and `request_multiplier` are captured onto the cached call when the store's schema has them (older - stores parse identically without). Nothing prices or displays them yet — - billing-grade cost is upstream #890. + stores parse identically without). Plan math sums finite `nanoAiu` into + Copilot AI credits (`codeburn plan set copilot-pro`). Billing-grade cost + rewrite of every report is still upstream #890. - **Sync.** `codeburn sync push` holds a copilot session until it has been quiet for 24 hours. The reconciliation output is mutable (a residual shrinks as rows land, a rollup is dropped once rows cover its leg, a row's pairing diff --git a/src/config.ts b/src/config.ts index 742a7d65..d96c0442 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,12 +4,15 @@ import { homedir } from 'os' import { randomBytes } from 'crypto' import { PLAN_PROVIDERS } from './plans.js' -export type PlanId = 'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'custom' | 'none' -export type PlanProvider = 'claude' | 'codex' | 'cursor' | 'grok' | 'all' +export type PlanId = 'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'copilot-pro' | 'copilot-pro-plus' | 'copilot-max' | 'custom' | 'none' +export type PlanProvider = 'claude' | 'codex' | 'cursor' | 'grok' | 'copilot' | 'all' export type Plan = { id: PlanId monthlyUsd: number + // Copilot plans budget in AI credits. monthlyUsd stays as credits × $0.01 so + // isActivePlan and add-only JSON keep working. Absent on USD plans. + monthlyCredits?: number provider: PlanProvider resetDay?: number setAt: string diff --git a/src/copilot-aiu.ts b/src/copilot-aiu.ts new file mode 100644 index 00000000..115da442 --- /dev/null +++ b/src/copilot-aiu.ts @@ -0,0 +1,19 @@ +// Copilot AI credits. Official rate from GitHub Docs, *Usage-based billing +// for individuals*, fetched 2026-08-23: +// https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals +// 1e9 nano-AIU = 1 credit = $0.01. No per-model rate table in this slice. + +export const NANO_AIU_PER_CREDIT = 1e9 +export const AI_CREDIT_USD = 0.01 + +export function isFiniteNanoAiu(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) +} + +export function nanoAiuToCredits(nanoAiu: number): number { + return nanoAiu / NANO_AIU_PER_CREDIT +} + +export function creditsToUsd(credits: number): number { + return credits * AI_CREDIT_USD +} diff --git a/src/dashboard.tsx b/src/dashboard.tsx index b67f3b97..f902727f 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -488,9 +488,20 @@ function planColor(planUsage: PlanUsage): string { // end-first, so the headline stays short enough to keep the percentage visible // at 80 columns and the status leads with the disclaimer, not the arithmetic. export function planBudgetHeadline(planUsage: PlanUsage): string { + if (planUsage.plan.provider === 'copilot') { + const spent = planUsage.spentCredits ?? 0 + const budget = planUsage.budgetCredits ?? planUsage.plan.monthlyCredits ?? 0 + return `${planLabel(planUsage)}: ${formatCredits(spent)} / ${formatCredits(budget)} AI Credits` + } return `${planLabel(planUsage)}: ${formatCost(planUsage.spentApiEquivalentUsd)} API-equivalent / ${formatCost(planUsage.budgetUsd)} budget` } +function formatCredits(n: number): string { + if (Number.isInteger(n)) return String(n) + const rounded = Math.round(n * 1e6) / 1e6 + return String(rounded) +} + export function planStatusText(planUsage: PlanUsage): string { // The period is anniversary-based (plan.resetDay, 1-28, settable per plan via // `codeburn plan set --reset-day`), so this is a monthly budget window, not a diff --git a/src/main.ts b/src/main.ts index 61efb9ba..85015206 100644 --- a/src/main.ts +++ b/src/main.ts @@ -144,10 +144,16 @@ type JsonPlanSummary = { daysUntilReset: number periodStart: string periodEnd: string + monthlyCredits?: number + spentCredits?: number + budgetCredits?: number + creditsIncomplete?: boolean + monthlyUsd?: number + spentApiEquivalentUsd?: number } function toJsonPlanSummary(planUsage: PlanUsage): JsonPlanSummary { - return { + const summary: JsonPlanSummary = { id: planUsage.plan.id, provider: planUsage.plan.provider, budget: convertCost(planUsage.budgetUsd), @@ -159,6 +165,15 @@ function toJsonPlanSummary(planUsage: PlanUsage): JsonPlanSummary { periodStart: planUsage.periodStart.toISOString(), periodEnd: planUsage.periodEnd.toISOString(), } + if (planUsage.plan.provider === 'copilot') { + summary.monthlyCredits = planUsage.plan.monthlyCredits + summary.spentCredits = planUsage.spentCredits + summary.budgetCredits = planUsage.budgetCredits + summary.creditsIncomplete = planUsage.creditsIncomplete + summary.monthlyUsd = planUsage.plan.monthlyUsd + summary.spentApiEquivalentUsd = planUsage.spentApiEquivalentUsd + } + return summary } type JsonPlanSummaryMap = Partial> @@ -383,6 +398,7 @@ function toPlanDisplay(plan: Plan) { return { id: plan.id, monthlyUsd: plan.monthlyUsd, + ...(plan.monthlyCredits != null ? { monthlyCredits: plan.monthlyCredits } : {}), provider: plan.provider, resetDay: clampResetDay(plan.resetDay), setAt: plan.setAt || null, @@ -1695,14 +1711,15 @@ program .description('Show or configure a subscription plan for overage tracking') .option('--format ', 'Output format: text or json', 'text') .option('--monthly-usd ', 'Monthly plan price in USD (for custom)', parseNumber) - .option('--provider ', 'Provider scope: all, claude, codex, cursor') + .option('--credits ', 'Monthly AI credits (copilot custom plans)', parseNumber) + .option('--provider ', `Provider scope: ${PLAN_PROVIDERS.join(', ')}`) .option('--reset-day ', 'Day of month plan resets (1-28)', parseInteger, 1) - .action(async (action?: string, id?: string, opts?: { format?: string; monthlyUsd?: number; provider?: string; resetDay?: number }) => { + .action(async (action?: string, id?: string, opts?: { format?: string; monthlyUsd?: number; credits?: number; provider?: string; resetDay?: number }) => { assertFormat(opts?.format ?? 'text', ['text', 'json'], 'plan') const mode = action ?? 'show' const providerOption = opts?.provider if (providerOption !== undefined && !isPlanProvider(providerOption)) { - console.error(`\n --provider must be one of: all, claude, codex, cursor; got "${providerOption}".\n`) + console.error(`\n --provider must be one of: ${PLAN_PROVIDERS.join(', ')}; got "${providerOption}".\n`) process.exitCode = 1 return } @@ -1731,7 +1748,7 @@ program console.log(`\n Plans: ${plans.length}`) for (const plan of plans) { console.log(` ${plan.provider}: ${planLabel(plan)} (${plan.id})`) - console.log(` Budget: $${plan.monthlyUsd}/month`) + console.log(` Budget: ${plan.provider === 'copilot' && plan.monthlyCredits != null ? `${plan.monthlyCredits} AI Credits` : `$${plan.monthlyUsd}/month`}`) console.log(` Reset day: ${clampResetDay(plan.resetDay)}`) if (plan.setAt) console.log(` Set at: ${plan.setAt}`) } @@ -1779,18 +1796,56 @@ program } if (id === 'custom') { - if (opts?.monthlyUsd === undefined) { + const credits = opts?.credits + const monthlyUsdOpt = opts?.monthlyUsd + const provider = providerOption ?? 'all' + + if (credits !== undefined && provider !== 'copilot') { + console.error('\n --credits is only valid with --provider copilot.\n') + process.exitCode = 1 + return + } + + if (provider === 'copilot') { + if (monthlyUsdOpt !== undefined) { + console.error('\n Copilot custom plans take --credits, not --monthly-usd (units mixed).\n') + process.exitCode = 1 + return + } + if (credits === undefined) { + console.error('\n Custom copilot plans require --credits .\n') + process.exitCode = 1 + return + } + if (!Number.isFinite(credits) || credits <= 0) { + console.error(`\n --credits must be a positive finite number; got ${credits}.\n`) + process.exitCode = 1 + return + } + await savePlan({ + id: 'custom', + monthlyCredits: credits, + monthlyUsd: credits * 0.01, + provider: 'copilot', + resetDay, + setAt: new Date().toISOString(), + }) + console.log(`\n Plan set to custom (${credits} AI Credits, copilot, reset day ${resetDay}).`) + console.log(` Config saved to ${getConfigFilePath()}\n`) + return + } + + if (monthlyUsdOpt === undefined) { console.error('\n Custom plans require --monthly-usd .\n') process.exitCode = 1 return } - const monthlyUsd = opts.monthlyUsd + const monthlyUsd = monthlyUsdOpt if (!Number.isFinite(monthlyUsd) || monthlyUsd <= 0) { - console.error(`\n --monthly-usd must be a positive number; got ${opts.monthlyUsd}.\n`) + console.error(`\n --monthly-usd must be a positive number; got ${monthlyUsdOpt}.\n`) process.exitCode = 1 return } - const provider = providerOption ?? 'all' await savePlan({ id: 'custom', monthlyUsd, diff --git a/src/parser.ts b/src/parser.ts index 1ee1cb15..35542b23 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -2493,6 +2493,7 @@ function providerCallToTurn(call: ParsedProviderCall): ParsedTurn { bashCommands: call.bashCommands, deduplicationKey: call.deduplicationKey, isEstimated: call.costIsEstimated, + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), }) const prRefs = extractPrUrlsFromText(call.userMessage) @@ -2580,6 +2581,7 @@ function apiCallToCachedCall(call: ParsedApiCall): CachedCall { ...(call.interrupted ? { interrupted: true } : {}), ...(call.userModified ? { userModified: true } : {}), ...(call.toolErrors ? { toolErrors: call.toolErrors } : {}), + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, @@ -2700,6 +2702,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall { activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), }) } diff --git a/src/plan-usage.ts b/src/plan-usage.ts index 85444124..19243fd3 100644 --- a/src/plan-usage.ts +++ b/src/plan-usage.ts @@ -1,8 +1,9 @@ import { behavioralCallCount } from './behavioral-weight.js' import { readPlans, type Plan, type PlanMap } from './config.js' +import { creditsToUsd, isFiniteNanoAiu, nanoAiuToCredits } from './copilot-aiu.js' import { parseAllSessions } from './parser.js' import { PLAN_PROVIDERS } from './plans.js' -import type { DateRange, ProjectSummary } from './types.js' +import type { DateRange, ParsedApiCall, ProjectSummary } from './types.js' const MS_PER_DAY = 24 * 60 * 60 * 1000 const PLAN_NEAR_THRESHOLD_PCT = 80 @@ -19,6 +20,10 @@ export type PlanUsage = { status: PlanStatus projectedMonthUsd: number daysUntilReset: number + // Copilot credit-plan fields. Absent on Claude / cursor / grok / custom-USD. + spentCredits?: number + budgetCredits?: number + creditsIncomplete?: boolean } export function clampResetDay(resetDay: number | undefined): number { @@ -69,12 +74,46 @@ function diffCalendarDays(from: Date, to: Date): number { return toDayIndex(to) - toDayIndex(from) } +export function isCopilotCreditsPlan(plan: Plan): boolean { + return plan.provider === 'copilot' +} + +function planCallSpend(plan: Plan, call: { costUSD: number; nanoAiu?: number }): number { + if (!isCopilotCreditsPlan(plan)) return call.costUSD + return isFiniteNanoAiu(call.nanoAiu) ? creditsToUsd(nanoAiuToCredits(call.nanoAiu)) : 0 +} + +function forEachPlanCall(projects: ProjectSummary[], visit: (call: ParsedApiCall) => void): void { + for (const project of projects) { + for (const session of project.sessions ?? []) { + for (const turn of session.turns ?? []) { + for (const call of turn.assistantCalls ?? []) visit(call) + } + } + } +} + +export function copilotCreditSpend(projects: ProjectSummary[]): { spentCredits: number; creditsIncomplete: boolean } { + let nanoSum = 0 + let creditsIncomplete = false + forEachPlanCall(projects, call => { + if (call.provider !== 'copilot') return + if (isFiniteNanoAiu(call.nanoAiu)) { + nanoSum += call.nanoAiu + return + } + creditsIncomplete = true + }) + return { spentCredits: nanoAiuToCredits(nanoSum), creditsIncomplete } +} + export function projectMonthEnd( projects: ProjectSummary[], periodStart: Date, periodEnd: Date, today: Date, spent: number, + spendOf: (call: { costUSD: number; nanoAiu?: number }) => number = (call) => call.costUSD, ): number { const dayCosts = new Map() @@ -88,7 +127,7 @@ export function projectMonthEnd( if (Number.isNaN(ts.getTime())) continue if (ts < periodStart || ts > today) continue const dayKey = toLocalDateKey(ts) - dayCosts.set(dayKey, (dayCosts.get(dayKey) ?? 0) + call.costUSD) + dayCosts.set(dayKey, (dayCosts.get(dayKey) ?? 0) + spendOf(call)) } } } @@ -110,12 +149,36 @@ export function projectMonthEnd( export function getPlanUsageFromProjects(plan: Plan, projects: ProjectSummary[], today = new Date()): PlanUsage { const { periodStart, periodEnd } = computePeriodFromResetDay(plan.resetDay, today) - const spent = projects.reduce((sum, p) => sum + p.totalCostUSD, 0) const budgetUsd = plan.monthlyUsd + const daysUntilReset = Math.max(0, diffCalendarDays(today, periodEnd)) + + if (isCopilotCreditsPlan(plan)) { + const { spentCredits, creditsIncomplete } = copilotCreditSpend(projects) + const budgetCredits = plan.monthlyCredits ?? 0 + const percentUsed = budgetCredits > 0 ? (spentCredits / budgetCredits) * 100 : 0 + const spent = creditsToUsd(spentCredits) + const status: PlanStatus = percentUsed > 100 ? 'over' : percentUsed >= PLAN_NEAR_THRESHOLD_PCT ? 'near' : 'under' + const projectedMonthUsd = projectMonthEnd(projects, periodStart, periodEnd, today, spent, call => planCallSpend(plan, call)) + return { + plan, + periodStart, + periodEnd, + spentApiEquivalentUsd: spent, + budgetUsd, + percentUsed, + status, + projectedMonthUsd, + daysUntilReset, + spentCredits, + budgetCredits, + creditsIncomplete, + } + } + + const spent = projects.reduce((sum, p) => sum + p.totalCostUSD, 0) const percentUsed = budgetUsd > 0 ? (spent / budgetUsd) * 100 : 0 const status: PlanStatus = percentUsed > 100 ? 'over' : percentUsed >= PLAN_NEAR_THRESHOLD_PCT ? 'near' : 'under' const projectedMonthUsd = projectMonthEnd(projects, periodStart, periodEnd, today, spent) - const daysUntilReset = Math.max(0, diffCalendarDays(today, periodEnd)) return { plan, @@ -157,17 +220,19 @@ export function getPlanScopedProjects(plan: Plan, projects: ProjectSummary[], to (sum, turn) => sum + turn.assistantCalls.reduce((turnSum, call) => turnSum + call.costUSD, 0), 0, ) + const hasNanoAiu = turns.some(turn => turn.assistantCalls.some(call => isFiniteNanoAiu(call.nanoAiu))) const apiCalls = turns.reduce((sum, turn) => sum + behavioralCallCount(turn.assistantCalls), 0) // Keep on cost as well as calls: a copilot rollup-only session has // zero behavioral calls but real spend, and dropping it would erase - // that spend from the plan window. - return apiCalls > 0 || totalCostUSD > 0 ? { ...session, turns, totalCostUSD, apiCalls } : null + // that spend from the plan window. A store-row with nanoAiu and $0 + // token cost still has to reach credit math. + return apiCalls > 0 || totalCostUSD > 0 || hasNanoAiu ? { ...session, turns, totalCostUSD, apiCalls } : null }) .filter((session): session is NonNullable => session !== null) const totalCostUSD = sessions.reduce((sum, session) => sum + session.totalCostUSD, 0) const totalApiCalls = sessions.reduce((sum, session) => sum + session.apiCalls, 0) - return totalApiCalls > 0 || totalCostUSD > 0 ? { ...project, sessions, totalCostUSD, totalApiCalls } : null + return sessions.length > 0 ? { ...project, sessions, totalCostUSD, totalApiCalls } : null }) .filter((project): project is NonNullable => project !== null) } diff --git a/src/plans.ts b/src/plans.ts index e384e75c..7488c3a1 100644 --- a/src/plans.ts +++ b/src/plans.ts @@ -1,9 +1,19 @@ import type { Plan, PlanId, PlanProvider } from './config.js' +import { AI_CREDIT_USD } from './copilot-aiu.js' -export const PLAN_PROVIDERS: PlanProvider[] = ['all', 'claude', 'codex', 'cursor', 'grok'] -export const PLAN_IDS: PlanId[] = ['claude-pro', 'claude-max', 'claude-max-5x', 'cursor-pro', 'supergrok', 'supergrok-heavy', 'custom', 'none'] +export const PLAN_PROVIDERS: PlanProvider[] = ['all', 'claude', 'codex', 'cursor', 'grok', 'copilot'] +export const PLAN_IDS: PlanId[] = ['claude-pro', 'claude-max', 'claude-max-5x', 'cursor-pro', 'supergrok', 'supergrok-heavy', 'copilot-pro', 'copilot-pro-plus', 'copilot-max', 'custom', 'none'] -export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy', Omit> = { +// Official Copilot individual allotments from GitHub Docs, *Usage-based +// billing for individuals*, fetched 2026-08-23. Flex is documented as +// variable — pin this table, do not invent a later flex number. +// https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals +// monthlyUsd is credits × $0.01 (the budget equivalent), not the sticker price. +const COPILOT_PRO_CREDITS = 1500 +const COPILOT_PRO_PLUS_CREDITS = 7000 +const COPILOT_MAX_CREDITS = 20000 + +export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'copilot-pro' | 'copilot-pro-plus' | 'copilot-max', Omit> = { 'claude-pro': { id: 'claude-pro', monthlyUsd: 20, @@ -40,6 +50,27 @@ export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' provider: 'grok', resetDay: 1, }, + 'copilot-pro': { + id: 'copilot-pro', + monthlyCredits: COPILOT_PRO_CREDITS, + monthlyUsd: COPILOT_PRO_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, + 'copilot-pro-plus': { + id: 'copilot-pro-plus', + monthlyCredits: COPILOT_PRO_PLUS_CREDITS, + monthlyUsd: COPILOT_PRO_PLUS_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, + 'copilot-max': { + id: 'copilot-max', + monthlyCredits: COPILOT_MAX_CREDITS, + monthlyUsd: COPILOT_MAX_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, } export function isPlanProvider(value: string): value is PlanProvider { @@ -71,6 +102,12 @@ export function planDisplayName(id: PlanId): string { return 'SuperGrok' case 'supergrok-heavy': return 'SuperGrok Heavy' + case 'copilot-pro': + return 'Copilot Pro' + case 'copilot-pro-plus': + return 'Copilot Pro+' + case 'copilot-max': + return 'Copilot Max' case 'custom': return 'Custom' case 'none': diff --git a/src/providers/types.ts b/src/providers/types.ts index b9671d9d..357d5eef 100644 --- a/src/providers/types.ts +++ b/src/providers/types.ts @@ -67,11 +67,10 @@ export type ParsedProviderCall = { // starts the leg's store-row subtraction interval here instead of at the // previous leg. Omitted when the leg contains no compaction. compactedAt?: string - // Copilot session-store billing metadata, captured only — no report consumes - // these yet (pricing/display design is upstream #890). total_nano_aiu is the - // request's charged AI-credit amount in nano-AIU (1e9 nano-AIU = 1 credit = - // $0.01); request_multiplier is the model's plan multiplier. Captured now so - // a future consumer needs no re-parse of rows the CLI may prune meanwhile. + // Copilot session-store billing metadata. total_nano_aiu is the request's + // charged AI-credit amount in nano-AIU (1e9 nano-AIU = 1 credit = $0.01); + // plan math sums finite nanoAiu. request_multiplier stays capture-only + // (billing-grade cost rewrite is upstream #890). nanoAiu?: number requestMultiplier?: number turnId?: string diff --git a/src/session-cache.ts b/src/session-cache.ts index 30047f2e..3d76c90f 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -54,9 +54,9 @@ export type CachedCall = { activeDurationMs?: number activeGeneratedTokens?: number toolWaitMs?: number - // Copilot session-store billing metadata (capture-only; no report consumes - // these yet — see ParsedProviderCall). Omitted when the store's schema - // predates the columns. + // Copilot session-store billing metadata. Plan math reads nanoAiu (1e9 = 1 + // credit). requestMultiplier stays capture-only. Omitted when the store's + // schema predates the columns. nanoAiu?: number requestMultiplier?: number // Copilot shutdown rollups only: stamp of the last successful in-session diff --git a/src/types.ts b/src/types.ts index 34451ac1..81dd6f86 100644 --- a/src/types.ts +++ b/src/types.ts @@ -162,6 +162,10 @@ export type ParsedApiCall = { /// tokens/cost but skip it in apiCalls / model-call / turn counts. Transient: /// assigned at serve time, never cached. supplementaryAccounting?: boolean + /// Copilot session-store `total_nano_aiu`. 1e9 nano-AIU = 1 credit = $0.01. + /// Threaded from CachedCall / ParsedProviderCall so plan math can sum credits. + /// Absent on older stores and on JSONL / shutdown-rollup siblings. + nanoAiu?: number } export type ToolCall = { diff --git a/tests/cli-plan.test.ts b/tests/cli-plan.test.ts index 14e2b121..cae7d051 100644 --- a/tests/cli-plan.test.ts +++ b/tests/cli-plan.test.ts @@ -147,4 +147,55 @@ describe('codeburn plan command', () => { await rm(home, { recursive: true, force: true }) } }, CLI_PLAN_TIMEOUT_MS) + + it('sets copilot-pro as 1500 credits / $15 equivalent', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-plan-')) + + try { + const result = runCli(['plan', 'set', 'copilot-pro'], home) + expect(result.status).toBe(0) + + const configPath = join(home, '.config', 'codeburn', 'config.json') + const config = JSON.parse(await readFile(configPath, 'utf-8')) as { + plans?: { copilot?: { id?: string; monthlyCredits?: number; monthlyUsd?: number; provider?: string; resetDay?: number } } + } + expect(config.plans?.copilot).toMatchObject({ + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + }) + } finally { + await rm(home, { recursive: true, force: true }) + } + }, CLI_PLAN_TIMEOUT_MS) + + it('writes custom copilot credits and rejects mixed units', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-plan-')) + + try { + const ok = runCli(['plan', 'set', 'custom', '--credits', '20000', '--provider', 'copilot'], home) + expect(ok.status).toBe(0) + const configPath = join(home, '.config', 'codeburn', 'config.json') + const config = JSON.parse(await readFile(configPath, 'utf-8')) as { + plans?: { copilot?: { monthlyCredits?: number; monthlyUsd?: number; provider?: string } } + } + expect(config.plans?.copilot).toMatchObject({ + monthlyCredits: 20000, + monthlyUsd: 200, + provider: 'copilot', + }) + + const mixed = runCli(['plan', 'set', 'custom', '--monthly-usd', '200', '--provider', 'copilot'], home) + expect(mixed.status).not.toBe(0) + expect(mixed.stderr).toContain('units mixed') + + const wrongProvider = runCli(['plan', 'set', 'custom', '--credits', '20000', '--provider', 'claude'], home) + expect(wrongProvider.status).not.toBe(0) + expect(wrongProvider.stderr).toContain('--credits is only valid with --provider copilot') + } finally { + await rm(home, { recursive: true, force: true }) + } + }, CLI_PLAN_TIMEOUT_MS) }) diff --git a/tests/copilot-aiu-serve.test.ts b/tests/copilot-aiu-serve.test.ts new file mode 100644 index 00000000..5d502a3f --- /dev/null +++ b/tests/copilot-aiu-serve.test.ts @@ -0,0 +1,93 @@ +// Serve-hole proof for #943: CachedCall.nanoAiu already survives disk. +// cachedCallToApiCall must thread it onto ParsedApiCall with no CACHE_VERSION bump. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mkdtemp, rm } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { createRequire } from 'node:module' + +import { isSqliteAvailable } from '../src/sqlite.js' +import { CACHE_VERSION, clearLoadCacheMemo } from '../src/session-cache.js' +import { clearSessionCache, parseAllSessions } from '../src/parser.js' + +const requireForTest = createRequire(import.meta.url) +type TestDb = { + exec(sql: string): void + prepare(sql: string): { run(...p: unknown[]): void } + close(): void +} + +function collectNanoAiu(projects: Awaited>): number[] { + return projects + .flatMap(p => p.sessions) + .flatMap(s => s.turns) + .flatMap(t => t.assistantCalls) + .map(c => c.nanoAiu) + .filter((n): n is number => typeof n === 'number') +} + +describe.skipIf(!isSqliteAvailable())('cachedCallToApiCall threads nanoAiu', () => { + let tmpHome: string + let tmpCache: string + let dbPath: string + + beforeEach(async () => { + tmpHome = await mkdtemp(join(tmpdir(), 'cb-aiu-serve-home-')) + tmpCache = await mkdtemp(join(tmpdir(), 'cb-aiu-serve-cache-')) + dbPath = join(tmpHome, 'session-store.db') + + process.env['HOME'] = tmpHome + process.env['USERPROFILE'] = tmpHome + process.env['CODEBURN_CACHE_DIR'] = tmpCache + process.env['CODEBURN_COPILOT_SESSION_STORE_DB'] = dbPath + process.env['CODEBURN_COPILOT_DISABLE_OTEL'] = '1' + process.env['CODEBURN_COPILOT_SESSION_STATE_DIR'] = join(tmpHome, 'no-jsonl') + process.env['CODEBURN_COPILOT_WS_STORAGE_DIR'] = join(tmpHome, 'no-ws') + process.env['CODEBURN_COPILOT_GLOBAL_STORAGE_DIR'] = join(tmpHome, 'no-global') + process.env['CODEBURN_COPILOT_JETBRAINS_DIR'] = join(tmpHome, 'no-jb') + + const { DatabaseSync } = requireForTest('node:sqlite') as { DatabaseSync: new (path: string) => TestDb } + const db = new DatabaseSync(dbPath) + db.exec(` + CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, repository TEXT, branch TEXT, created_at TEXT DEFAULT (datetime('now'))); + CREATE TABLE assistant_usage_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL REFERENCES sessions(id), + model TEXT NOT NULL, + input_tokens INTEGER, output_tokens INTEGER, + cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER, + total_nano_aiu INTEGER, request_multiplier REAL, + created_at TEXT DEFAULT (datetime('now')) + ); + `) + db.prepare(`INSERT INTO sessions (id, cwd) VALUES ('sess-aiu', '/tmp/codeburn')`).run() + db.prepare( + `INSERT INTO assistant_usage_events + (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, total_nano_aiu, request_multiplier, created_at) + VALUES ('sess-aiu', 'claude-sonnet-4-5', 1000, 20, 600, 300, 0, 1500000000, 1.0, '2026-08-05T12:00:00.000Z')`, + ).run() + db.close() + }) + + afterEach(async () => { + clearSessionCache() + clearLoadCacheMemo() + await rm(tmpHome, { recursive: true, force: true }) + await rm(tmpCache, { recursive: true, force: true }) + }) + + it('serves nanoAiu on a cold parse and a warm cache read without a CACHE_VERSION bump', async () => { + expect(CACHE_VERSION).toBe(9) + + clearSessionCache() + const cold = await parseAllSessions(undefined, 'copilot') + expect(collectNanoAiu(cold)).toEqual([1_500_000_000]) + + // Drop the in-memory memo only. Disk cache now serves via cachedCallToApiCall. + clearSessionCache() + const warm = await parseAllSessions(undefined, 'copilot') + expect(collectNanoAiu(warm)).toEqual([1_500_000_000]) + expect(CACHE_VERSION).toBe(9) + }) +}) diff --git a/tests/copilot-aiu.test.ts b/tests/copilot-aiu.test.ts new file mode 100644 index 00000000..88d9f9b9 --- /dev/null +++ b/tests/copilot-aiu.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest' + +import { AI_CREDIT_USD, creditsToUsd, isFiniteNanoAiu, nanoAiuToCredits } from '../src/copilot-aiu.js' + +describe('copilot AIU helpers', () => { + it('converts 1.5e9 nano-AIU to 1.5 credits and $0.015', () => { + expect(nanoAiuToCredits(1_500_000_000)).toBe(1.5) + expect(creditsToUsd(1.5)).toBeCloseTo(0.015, 12) + expect(1.5 / 1500 * 100).toBeCloseTo(0.1, 12) + expect(1.5 * AI_CREDIT_USD).toBeCloseTo(0.015, 12) + }) + + it('accepts only finite nanoAiu', () => { + expect(isFiniteNanoAiu(1_500_000_000)).toBe(true) + expect(isFiniteNanoAiu(0)).toBe(true) + expect(isFiniteNanoAiu(undefined)).toBe(false) + expect(isFiniteNanoAiu(Number.NaN)).toBe(false) + expect(isFiniteNanoAiu(Number.POSITIVE_INFINITY)).toBe(false) + }) +}) diff --git a/tests/plan-budget-copy.test.ts b/tests/plan-budget-copy.test.ts index 787df94f..c6bc8793 100644 --- a/tests/plan-budget-copy.test.ts +++ b/tests/plan-budget-copy.test.ts @@ -55,6 +55,30 @@ describe('plan budget copy', () => { expect(planStatusText(cursor)).toContain('Approaching budget') }) + it('labels Copilot as AI Credits, not API-equivalent USD', () => { + const copilot = usage({ + plan: { + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, + budgetUsd: 15, + spentApiEquivalentUsd: 0.015, + spentCredits: 1.5, + budgetCredits: 1500, + percentUsed: 0.1, + creditsIncomplete: false, + }) + expect(planBudgetHeadline(copilot)).toBe('Copilot Pro: 1.5 / 1500 AI Credits') + const status = planStatusText(copilot) + expect(status).toContain('Not a live provider window.') + expect(status).not.toMatch(/GitHub|UTC|copilot_internal/i) + expect(status).not.toMatch(/calendar/i) + }) + // computePeriodFromResetDay builds an anniversary window from plan.resetDay // (1-28, settable with `codeburn plan set --reset-day`), so a plan that resets // on the 15th is NOT on a calendar month and must never be called one. diff --git a/tests/plan-usage.test.ts b/tests/plan-usage.test.ts index 94cc7521..dffa5ce2 100644 --- a/tests/plan-usage.test.ts +++ b/tests/plan-usage.test.ts @@ -410,3 +410,187 @@ describe('getPlanUsage', () => { } }) }) + +function usageCall(overrides: { + provider: string + costUSD: number + timestamp: string + nanoAiu?: number + supplementaryAccounting?: boolean +}) { + return { + provider: overrides.provider, + model: 'claude-sonnet-4-5', + usage: { + inputTokens: 100, + outputTokens: 20, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, + }, + costUSD: overrides.costUSD, + tools: [], + mcpTools: [], + skills: [], + subagentTypes: [], + hasAgentSpawn: false, + hasPlanMode: false, + speed: 'standard' as const, + timestamp: overrides.timestamp, + bashCommands: [], + deduplicationKey: `${overrides.provider}-${overrides.timestamp}-${overrides.nanoAiu ?? 'none'}`, + ...(overrides.nanoAiu != null ? { nanoAiu: overrides.nanoAiu } : {}), + ...(overrides.supplementaryAccounting ? { supplementaryAccounting: true } : {}), + } +} + +function usageProject(calls: ReturnType[]): ProjectSummary { + return { + project: 'codeburn', + projectPath: '/tmp/codeburn', + totalCostUSD: calls.reduce((sum, call) => sum + call.costUSD, 0), + totalApiCalls: calls.length, + sessions: [{ + turns: [{ + timestamp: calls[0]!.timestamp, + assistantCalls: calls, + }], + }], + } as ProjectSummary +} + +describe('copilot AI credit plan math', () => { + const today = new Date('2026-08-10T12:00:00.000Z') + const copilotPro: Plan = { + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + const claudePro: Plan = { + id: 'claude-pro', + monthlyUsd: 20, + provider: 'claude', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + + it('turns 1.5e9 nanoAiu into 1.5 / 1500 credits (0.1%)', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.budgetCredits).toBe(1500) + expect(usage.percentUsed).toBeCloseTo(0.1, 10) + expect(usage.spentApiEquivalentUsd).toBeCloseTo(0.015, 10) + expect(usage.creditsIncomplete).toBe(false) + expect(usage.status).toBe('under') + }) + + it('does not fill the credits bar from token costUSD when nanoAiu is missing', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(0) + expect(usage.creditsIncomplete).toBe(true) + expect(usage.percentUsed).toBe(0) + expect(usage.spentApiEquivalentUsd).toBe(0) + }) + + it('counts a paired store-row once and ignores JSONL / rollup siblings', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:01.000Z', + }), + usageCall({ + provider: 'copilot', + costUSD: 0.25, + timestamp: '2026-08-06T12:00:00.000Z', + supplementaryAccounting: true, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.percentUsed).toBeCloseTo(0.1, 10) + expect(usage.creditsIncomplete).toBe(true) + }) + + it('keeps Claude plans on costUSD against the same mixed fixture', () => { + const projects = [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + }), + usageCall({ + provider: 'claude', + costUSD: 5, + timestamp: '2026-08-05T12:00:00.000Z', + }), + ]), + ] + const scopedClaude = getPlanScopedProjects(claudePro, projects, today) + const claudeUsage = getPlanUsageFromProjects(claudePro, scopedClaude, today) + const copilotUsage = getPlanUsageFromProjects(copilotPro, getPlanScopedProjects(copilotPro, projects, today), today) + + expect(claudeUsage.spentApiEquivalentUsd).toBe(5) + expect(claudeUsage.spentCredits).toBeUndefined() + expect(claudeUsage.percentUsed).toBe(25) + expect(copilotUsage.spentCredits).toBe(1.5) + expect(copilotUsage.percentUsed).toBeCloseTo(0.1, 10) + }) + + it('leaves cursor and grok USD siblings at 25%', () => { + const cursor = getPlanUsageFromProjects({ + id: 'cursor-pro', + monthlyUsd: 20, + provider: 'cursor', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, [usageProject([usageCall({ provider: 'cursor', costUSD: 5, timestamp: '2026-08-05T12:00:00.000Z' })])], today) + const grok = getPlanUsageFromProjects({ + id: 'supergrok', + monthlyUsd: 30, + provider: 'grok', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, [usageProject([usageCall({ provider: 'grok', costUSD: 7.5, timestamp: '2026-08-05T12:00:00.000Z' })])], today) + + expect(cursor.percentUsed).toBe(25) + expect(grok.percentUsed).toBe(25) + expect(cursor.spentCredits).toBeUndefined() + expect(grok.spentCredits).toBeUndefined() + }) +}) diff --git a/tests/plans.test.ts b/tests/plans.test.ts index ca4553b3..2a4c7e49 100644 --- a/tests/plans.test.ts +++ b/tests/plans.test.ts @@ -12,6 +12,9 @@ describe('plan presets', () => { expect(getPresetPlan('claude-pro')).toMatchObject({ id: 'claude-pro', monthlyUsd: 20, provider: 'claude' }) expect(getPresetPlan('claude-max')).toMatchObject({ id: 'claude-max', monthlyUsd: 200, provider: 'claude' }) expect(getPresetPlan('cursor-pro')).toMatchObject({ id: 'cursor-pro', monthlyUsd: 20, provider: 'cursor' }) + expect(getPresetPlan('copilot-pro')).toMatchObject({ id: 'copilot-pro', monthlyCredits: 1500, monthlyUsd: 15, provider: 'copilot' }) + expect(getPresetPlan('copilot-pro-plus')).toMatchObject({ id: 'copilot-pro-plus', monthlyCredits: 7000, monthlyUsd: 70, provider: 'copilot' }) + expect(getPresetPlan('copilot-max')).toMatchObject({ id: 'copilot-max', monthlyCredits: 20000, monthlyUsd: 200, provider: 'copilot' }) expect(getPresetPlan('custom')).toBeNull() }) @@ -22,7 +25,9 @@ describe('plan presets', () => { expect(isPlanProvider('all')).toBe(true) expect(isPlanProvider('claude')).toBe(true) + expect(isPlanProvider('copilot')).toBe(true) expect(isPlanProvider('invalid')).toBe(false) + expect(isPlanId('copilot-pro')).toBe(true) }) }) From aa1e38016fd4881e2ff63eb6540ded528c3f55df Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 20:54:21 +0530 Subject: [PATCH 09/19] fix(models): leave orcarouter/auto unpriced and bump daily cache to v28 Sonnet was a guess against a Qwen/Llama flash route. Fusion aliases keep the 2026-08 live completion-model provenance. Warm days re-derive. --- CHANGELOG.md | 2 +- README.md | 2 +- scripts/upgrade-path/run.mjs | 2 +- src/daily-cache.ts | 3 ++- src/models.ts | 20 ++++++++------------ tests/models.test.ts | 16 +++++++--------- 6 files changed, 20 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2190248..37c084b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ - **`CODEBURN_CACHE_SCOPE=all` forces a full session-cache read.** A ranged query reads only the month shards that can contribute a turn to it, which is a real behaviour change on a warm cache; this is the escape hatch for the case where a number looks wrong and you want to know whether the scoped read is why. Set it and every load ignores its scope and reads every shard, one-shot runs and the resident `codeburn serve` alike. It is a read policy, not an input to any cache fingerprint: setting or unsetting it re-parses nothing and invalidates nothing. ### Added (OrcaRouter) -- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; the smart route `orcarouter/auto` aliases to a fast Sonnet rate and the fusion routes alias to their current `openai/gpt-oss-120b` target, so display and report identity match those routed models; and an unknown vendor nested inside the route still fails closed. +- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; `orcarouter/auto` stays unpriced (the smart route lands on a Qwen/Llama flash model — a Sonnet alias would overprice it) and the fusion routes alias to their current `openai/gpt-oss-120b` target (live completion `model` field, 2026-08); and an unknown vendor nested inside the route still fails closed. Daily cache v28 so warm days re-derive the new prices. ### Added (Windows) - **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls. diff --git a/README.md b/README.md index 0ca4aed6..31df76cf 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ Left/right arrow keys switch between Today, 7 Days, 30 Days, Month, 6 Months, an ### Pricing -Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. Routing-gateway model ids are priced as the model they wrap: [OrcaRouter](https://www.orcarouter.ai) route ids (`orcarouter/auto`, `orcarouter/fusion`, …) peel to the model the gateway routes to, and a nested upstream spelling (`orcarouter/deepseek/deepseek-v4-pro`) prices at that exact row, so a gateway-routed session reports real spend instead of $0. +Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. Routing-gateway model ids are priced as the model they wrap: [OrcaRouter](https://www.orcarouter.ai) fusion route ids peel to their current upstream (`openai/gpt-oss-120b`), `orcarouter/auto` stays unpriced until a live probe pins the rotating target, and a nested upstream spelling (`orcarouter/deepseek/deepseek-v4-pro`) prices at that exact row, so a gateway-routed session reports real spend instead of $0. ### Task Categories diff --git a/scripts/upgrade-path/run.mjs b/scripts/upgrade-path/run.mjs index ac848043..c7af2816 100644 --- a/scripts/upgrade-path/run.mjs +++ b/scripts/upgrade-path/run.mjs @@ -33,7 +33,7 @@ const WORK = process.env['UPGRADE_PATH_WORK'] || join(tmpdir(), 'codeburn upgrad const OLD_SESSION_CACHE = 'session-cache.v7.json' const OLD_DAILY_CACHE = 'daily-cache.v17.json' const NEW_SESSION_CACHE_DIR = 'session-cache.v9' -const NEW_DAILY_CACHE = 'daily-cache.v27.json' +const NEW_DAILY_CACHE = 'daily-cache.v28.json' const HOME = join(WORK, 'user home') const PAYLOADS = join(WORK, 'payloads') diff --git a/src/daily-cache.ts b/src/daily-cache.ts index b59561cc..7c42ceac 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -168,7 +168,8 @@ import type { DateRange, ProjectSummary } from './types.js' // v25: #1047 activity-id pricing. v24 on main already shipped #1090. // v26: #946 copilot session-store accounting (see the top of this ladder). // v27: #1093 claude-haiku-4.5 alias (see top). -export const DAILY_CACHE_VERSION = 27 +// v28: #1118 OrcaRouter route pricing (fusion aliases + peel; auto stays unpriced). +export const DAILY_CACHE_VERSION = 28 const MIN_SUPPORTED_VERSION = 27 /// Providers whose per-day CALL COUNT means something different at diff --git a/src/models.ts b/src/models.ts index c9196aff..775d680e 100644 --- a/src/models.ts +++ b/src/models.ts @@ -291,7 +291,7 @@ export async function loadPricing(): Promise { // Known model name variants that providers emit but LiteLLM/fallback don't index under. // OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last). // getCanonicalName strips a KNOWN vendor/router prefix first unless the -// full cleaned id itself is an alias (orcarouter/auto). Post-strip forms +// full cleaned id itself is an alias (orcarouter/fusion). Post-strip forms // still cover every other entry here. const BUILTIN_ALIASES: Record = { 'anthropic--claude-4.6-opus': 'claude-opus-4-6', @@ -345,15 +345,11 @@ const BUILTIN_ALIASES: Record = { 'claude-4-7-opus-xhigh': 'claude-opus-4-7', 'claude-4-7-opus-xhigh-fast': 'claude-opus-4-7', 'qwen-auto': 'claude-sonnet-4-5', - // OrcaRouter's smart route. The route picks a model per request; at the time - // of writing it lands on a Qwen/Llama flash model, so a fast Sonnet rate is - // the honest estimate until the route's target stabilizes (mirrors the - // `*-auto` presets above). Display and report identity follow this target. - 'orcarouter/auto': 'claude-sonnet-4-5', - // OrcaRouter's fusion routes currently serve openai/gpt-oss-120b (verified - // live 2026-08). If the gateway re-routes them, these drift like any other - // preset estimate; they keep a priced row instead of reporting $0. Display - // and report identity follow this target, not a branded route label. + // OrcaRouter fusion routes. Provenance: live OrcaRouter completion `model` + // field, 2026-08 (community #1058 / house #1118). Re-verify if the gateway + // rotates targets. `orcarouter/auto` is intentionally unaliased: the smart + // route currently lands on a Qwen/Llama flash model, so a Sonnet alias + // would overprice ~3–30×. Fail closed until a live probe pins that target. 'orcarouter/fusion': 'openai/gpt-oss-120b', 'orcarouter/fusion-flash': 'openai/gpt-oss-120b', 'orcarouter/fusion-mini': 'openai/gpt-oss-120b', @@ -791,8 +787,8 @@ function getCanonicalName(model: string): string { .replace(/@.*$/, '') .replace(/-\d{8}$/, '') .replace(/\[[^\]]*\]$/, '') - // Full-id aliases (orcarouter/auto) must stay visible so resolveAlias can - // see them. Stripping first would leave a leaf (`auto`) with no mapping. + // Full-id aliases (orcarouter/fusion) must stay visible so resolveAlias can + // see them. Stripping first would leave a leaf (`fusion`) with no mapping. // Nested wrappers without an alias still peel as before. if (Object.hasOwn(userAliases, cleaned) || Object.hasOwn(BUILTIN_ALIASES, cleaned)) { return cleaned diff --git a/tests/models.test.ts b/tests/models.test.ts index b5bc2db0..d1bef7e8 100644 --- a/tests/models.test.ts +++ b/tests/models.test.ts @@ -174,14 +174,12 @@ describe('getModelCosts', () => { expect(getModelCosts('omniroute:cp/cline-pass/glm-5.3')!.outputCostPerToken).toBe(99 / 1_000_000) }) - it('prices OrcaRouter route ids at their upstream row and the smart route via alias', () => { - // `orcarouter/auto` is a smart route; the alias maps it to a Sonnet flash - // rate rather than leaving it unpriced at $0 (the CLI warns on $0 models). - expect(getModelCosts('orcarouter/auto')!.inputCostPerToken).toBe( - getModelCosts('claude-sonnet-4-5')!.inputCostPerToken, - ) + it('prices OrcaRouter fusion and nested upstreams; auto stays fail-closed', () => { + // `orcarouter/auto` rotates onto a Qwen/Llama flash model. No live probe + // pins a rate, so it stays unpriced rather than inheriting Sonnet. + expect(getModelCosts('orcarouter/auto')).toBeNull() - // The fusion routes currently resolve to openai/gpt-oss-120b (verified live). + // The fusion routes currently resolve to openai/gpt-oss-120b (live 2026-08). expect(getModelCosts('orcarouter/fusion')!.inputCostPerToken).toBe( getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, ) @@ -218,7 +216,7 @@ describe('resolveCanonicalModelId', () => { expect(resolveCanonicalModelId('claude-opus-4.6')).toBe('claude-opus-4-6') expect(resolveCanonicalModelId('kimi-code')).toBe('kimi-k2-thinking') expect(resolveCanonicalModelId('cline-pass/kimi-k3')).toBe('kimi-k3') - expect(resolveCanonicalModelId('orcarouter/auto')).toBe(resolveCanonicalModelId('claude-sonnet-4-5')) + expect(resolveCanonicalModelId('orcarouter/auto')).not.toBe(resolveCanonicalModelId('claude-sonnet-4-5')) expect(resolveCanonicalModelId('orcarouter/fusion')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) expect(resolveCanonicalModelId('orcarouter/fusion-flash')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) expect(resolveCanonicalModelId('orcarouter/fusion-mini')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) @@ -290,7 +288,7 @@ describe('getShortModelName', () => { // OrcaRouter route ids peel to the upstream id, which keeps the upstream label. expect(getShortModelName('orcarouter/deepseek/deepseek-v4-pro')).toBe('DeepSeek v4 Pro') // Route ids display as the model they route to, not a branded gateway label. - expect(getShortModelName('orcarouter/auto')).toBe(getShortModelName('claude-sonnet-4-5')) + expect(getShortModelName('orcarouter/auto')).not.toBe(getShortModelName('claude-sonnet-4-5')) expect(getShortModelName('orcarouter/fusion')).toBe(getShortModelName('openai/gpt-oss-120b')) expect(getShortModelName('orcarouter/fusion-flash')).toBe(getShortModelName('openai/gpt-oss-120b')) expect(getShortModelName('orcarouter/fusion-mini')).toBe(getShortModelName('openai/gpt-oss-120b')) From 55155c10ed3062153d9e8b5dfab3d4408fc46533 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 20:54:21 +0530 Subject: [PATCH 10/19] fix(plan): do not double Copilot credits when both twins have nanoAiu Store-row nanoAiu is still the bill when the JSONL twin has none. USD plans keep the cost-or-calls retain predicate. --- src/plan-usage.ts | 30 +++++++++++++++---------- tests/plan-usage.test.ts | 47 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/src/plan-usage.ts b/src/plan-usage.ts index 19243fd3..72e39bd6 100644 --- a/src/plan-usage.ts +++ b/src/plan-usage.ts @@ -83,11 +83,11 @@ function planCallSpend(plan: Plan, call: { costUSD: number; nanoAiu?: number }): return isFiniteNanoAiu(call.nanoAiu) ? creditsToUsd(nanoAiuToCredits(call.nanoAiu)) : 0 } -function forEachPlanCall(projects: ProjectSummary[], visit: (call: ParsedApiCall) => void): void { +function forEachPlanTurn(projects: ProjectSummary[], visit: (calls: ParsedApiCall[]) => void): void { for (const project of projects) { for (const session of project.sessions ?? []) { for (const turn of session.turns ?? []) { - for (const call of turn.assistantCalls ?? []) visit(call) + visit(turn.assistantCalls ?? []) } } } @@ -96,13 +96,17 @@ function forEachPlanCall(projects: ProjectSummary[], visit: (call: ParsedApiCall export function copilotCreditSpend(projects: ProjectSummary[]): { spentCredits: number; creditsIncomplete: boolean } { let nanoSum = 0 let creditsIncomplete = false - forEachPlanCall(projects, call => { - if (call.provider !== 'copilot') return - if (isFiniteNanoAiu(call.nanoAiu)) { - nanoSum += call.nanoAiu - return - } - creditsIncomplete = true + forEachPlanTurn(projects, calls => { + const copilot = calls.filter(call => call.provider === 'copilot') + if (copilot.length === 0) return + const primaryNano = copilot.filter(call => !call.supplementaryAccounting && isFiniteNanoAiu(call.nanoAiu)) + const suppNano = copilot.filter(call => call.supplementaryAccounting && isFiniteNanoAiu(call.nanoAiu)) + // Store rows are supplementary and are the bill when the JSONL twin has + // no nanoAiu. If both sides carry nanoAiu, count the behavioral row only + // so a paired rollup cannot double the credits. + const counted = primaryNano.length > 0 && suppNano.length > 0 ? primaryNano : [...primaryNano, ...suppNano] + for (const call of counted) nanoSum += call.nanoAiu! + if (copilot.some(call => !isFiniteNanoAiu(call.nanoAiu))) creditsIncomplete = true }) return { spentCredits: nanoAiuToCredits(nanoSum), creditsIncomplete } } @@ -225,8 +229,12 @@ export function getPlanScopedProjects(plan: Plan, projects: ProjectSummary[], to // Keep on cost as well as calls: a copilot rollup-only session has // zero behavioral calls but real spend, and dropping it would erase // that spend from the plan window. A store-row with nanoAiu and $0 - // token cost still has to reach credit math. - return apiCalls > 0 || totalCostUSD > 0 || hasNanoAiu ? { ...session, turns, totalCostUSD, apiCalls } : null + // token cost still has to reach credit math — but only on a copilot + // credit plan. Claude/cursor/grok USD plans keep the old + // cost-or-calls predicate so a $0 nanoAiu-only session is not an + // unannounced retain on providers this PR is not about. + const keepForCredits = isCopilotCreditsPlan(plan) && hasNanoAiu + return apiCalls > 0 || totalCostUSD > 0 || keepForCredits ? { ...session, turns, totalCostUSD, apiCalls } : null }) .filter((session): session is NonNullable => session !== null) diff --git a/tests/plan-usage.test.ts b/tests/plan-usage.test.ts index dffa5ce2..7882c030 100644 --- a/tests/plan-usage.test.ts +++ b/tests/plan-usage.test.ts @@ -545,6 +545,53 @@ describe('copilot AI credit plan math', () => { expect(usage.creditsIncomplete).toBe(true) }) + it('does not double credits when a paired rollup also carries nanoAiu', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:01.000Z', + nanoAiu: 1_500_000_000, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.creditsIncomplete).toBe(false) + }) + + it('keeps a $0 nanoAiu-only session on copilot plans and drops it on USD plans', () => { + const projects = [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + ]), + ] + const allUsd: Plan = { + id: 'custom', + monthlyUsd: 100, + provider: 'all', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + expect(getPlanScopedProjects(copilotPro, projects, today)).toHaveLength(1) + expect(getPlanScopedProjects(allUsd, projects, today)).toHaveLength(0) + expect(getPlanScopedProjects(claudePro, projects, today)).toHaveLength(0) + }) + it('keeps Claude plans on costUSD against the same mixed fixture', () => { const projects = [ usageProject([ From 7042048608d32124829c7022283ff66bb563ab9f Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Sun, 23 Aug 2026 20:54:21 +0530 Subject: [PATCH 11/19] fix(codex): dedup nest rollouts by session id on the default factory Wire defaultLauncherRoots into createCodexProvider(nest) so overlap filtering is not opts-only. Compare payload.session_id, not basename. --- src/launcher-homes.ts | 59 +++++++++++++++++++++++++++++------- src/providers/codex.ts | 33 +++++++++----------- tests/launcher-homes.test.ts | 50 +++++++++++++++++++++--------- 3 files changed, 97 insertions(+), 45 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index bb7f69f5..bf603b72 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -1,4 +1,4 @@ -import { existsSync, readdirSync, realpathSync } from 'fs' +import { closeSync, existsSync, openSync, readdirSync, readSync, realpathSync } from 'fs' import { homedir } from 'os' import { join, resolve, sep } from 'path' @@ -40,11 +40,32 @@ export function isNestedLauncherCodexHome( return existsSync(primary) } -/** Rollout basenames under a Codex home (sessions/YYYY/MM/DD + archived). */ -export function listRolloutBasenames(codexDir: string): Set { - const names = new Set() - const take = (file: string) => { - if (file.startsWith('rollout-') && file.endsWith('.jsonl')) names.add(file) +/** Session id from the first `session_meta` line of a Codex rollout file. + * Missing / unreadable files return undefined — callers must not drop those. */ +export function rolloutFileSessionId(filePath: string): string | undefined { + try { + const fd = openSync(filePath, 'r') + try { + const buf = Buffer.alloc(8192) + const n = readSync(fd, buf, 0, buf.length, 0) + const line = buf.subarray(0, n).toString('utf8').split('\n', 1)[0] ?? '' + if (!line) return undefined + const parsed: unknown = JSON.parse(line) + if (!parsed || typeof parsed !== 'object') return undefined + const payload = (parsed as { payload?: { session_id?: unknown } }).payload + const id = payload?.session_id + return typeof id === 'string' && id.length > 0 ? id : undefined + } finally { + closeSync(fd) + } + } catch { + return undefined + } +} + +function walkRolloutFiles(codexDir: string, visit: (filePath: string) => void): void { + const take = (dir: string, file: string) => { + if (file.startsWith('rollout-') && file.endsWith('.jsonl')) visit(join(dir, file)) } const sessionsDir = join(codexDir, 'sessions') try { @@ -56,19 +77,33 @@ export function listRolloutBasenames(codexDir: string): Set { const monthDir = join(yearDir, month) for (const day of readdirSync(monthDir)) { if (!/^\d{2}$/.test(day)) continue - for (const file of readdirSync(join(monthDir, day))) take(file) + const dayDir = join(monthDir, day) + for (const file of readdirSync(dayDir)) take(dayDir, file) } } } } catch { // missing tree } + const archivedDir = join(codexDir, 'archived_sessions') try { - for (const file of readdirSync(join(codexDir, 'archived_sessions'))) take(file) + for (const file of readdirSync(archivedDir)) take(archivedDir, file) } catch { // missing archive } - return names +} + +/** Session ids under a Codex home (sessions/YYYY/MM/DD + archived). + * Identity is the rollout's `payload.session_id`, not the filename: Codex + * names embed a timestamp+uuid so basename collisions are rare, but a + * dollar-protecting dedup cannot treat 'unlikely' as identity. */ +export function listRolloutSessionIds(codexDir: string): Set { + const ids = new Set() + walkRolloutFiles(codexDir, filePath => { + const id = rolloutFileSessionId(filePath) + if (id) ids.add(id) + }) + return ids } export function defaultBilledCodexHome(): string { @@ -79,7 +114,9 @@ export function defaultLauncherRoots(): string[] { return [join(homedir(), '.buzz')] } -/** Surfaces that drive another billed store. Not providers. No session count. */ +/** Surfaces that drive another billed store. Not providers. No session count. + * Presence of `~/.buzz` is the heuristic — we do not inspect a nested Codex + * tree here (that store is billed via the Codex provider). */ export function collectLauncherNotes(home = homedir()): LauncherNote[] { const notes: LauncherNote[] = [] const buzz = join(home, '.buzz') @@ -88,7 +125,7 @@ export function collectLauncherNotes(home = homedir()): LauncherNote[] { name: 'buzz', path: buzz, billedVia: 'codex', - verdict: 'LAUNCHER (no usage store; billed via Codex)', + verdict: 'LAUNCHER (billed via Codex)', }) } const grokStore = join(home, '.grok') diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 2d2d6a0c..ca3089ce 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -12,7 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' -import { defaultBilledCodexHome, isNestedLauncherCodexHome, listRolloutBasenames, sameCodexHome } from '../launcher-homes.js' +import { defaultBilledCodexHome, defaultLauncherRoots, isNestedLauncherCodexHome, listRolloutSessionIds, rolloutFileSessionId, sameCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -1335,27 +1335,19 @@ export function createCodexProvider( opts?: { primaryDir?: string; launcherRoots?: string[] }, ): Provider { const dir = getCodexDir(codexDir) + // Production singleton (no args) still honors CODEX_HOME / override as the + // one root. An explicit nest path — even without second-factory opts — + // overlap-filters against the default billed home using defaultLauncherRoots + // so a future createCodexProvider(nest) cannot double-count session ids. const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome() - // Production singleton (no args) honors CODEX_HOME / override as the one - // root. Unique nest sessions must never be dropped because ~/.codex exists. - // Only a second factory — createCodexProvider(nestPath, {primaryDir, - // launcherRoots}) — may drop overlapping rollout-*.jsonl basenames. - const secondPrimary = opts?.primaryDir - const secondRoots = opts?.launcherRoots + const launcherRoots = opts?.launcherRoots ?? defaultLauncherRoots() const duplicateHome = codexDir !== undefined && - secondPrimary !== undefined && - secondRoots !== undefined && - sameCodexHome(dir, secondPrimary) && - resolve(dir) !== resolve(secondPrimary) + sameCodexHome(dir, primaryDir) && + resolve(dir) !== resolve(primaryDir) const filterOverlap = codexDir !== undefined && - secondPrimary !== undefined && - secondRoots !== undefined && - isNestedLauncherCodexHome(dir, { - primaryDir: secondPrimary, - launcherRoots: secondRoots, - }) + isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots }) return { name: 'codex', @@ -1387,8 +1379,11 @@ export function createCodexProvider( if (duplicateHome) return [] const sources = await discoverSessionsInDir(dir) if (!filterOverlap) return sources - const primaryNames = listRolloutBasenames(primaryDir) - return sources.filter(source => !primaryNames.has(basename(source.path))) + const primaryIds = listRolloutSessionIds(primaryDir) + return sources.filter(source => { + const id = rolloutFileSessionId(source.path) + return !(id && primaryIds.has(id)) + }) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index 59a3dae5..69ebe3fd 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -8,18 +8,19 @@ import { collectDoctorReport, renderDoctorTable } from '../src/doctor.js' import { createCodexProvider } from '../src/providers/codex.js' import { emptyCache } from '../src/session-cache.js' -function sessionMeta(): string { +function sessionMeta(sessionId: string): string { return JSON.stringify({ type: 'session_meta', timestamp: '2026-04-14T10:00:00Z', - payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: 'sess-001', model: 'gpt-5.3-codex' }, + payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: sessionId, model: 'gpt-5.3-codex' }, }) } -async function writeCodexSession(codexDir: string, name = 'rollout-sess-001.jsonl'): Promise { +async function writeCodexSession(codexDir: string, name: string, sessionId?: string): Promise { + const id = sessionId ?? name.replace(/^rollout-/, '').replace(/\.jsonl$/, '') const dayDir = join(codexDir, 'sessions', '2026', '04', '14') await mkdir(dayDir, { recursive: true }) - await writeFile(join(dayDir, name), `${sessionMeta()}\n`) + await writeFile(join(dayDir, name), `${sessionMeta(id)}\n`) } function names(sources: { path: string }[]): string[] { @@ -77,17 +78,27 @@ describe('Codex discover overlap-only nest filter', () => { expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz.jsonl']) }) - it('filters only a nest rollout whose basename overlaps the primary tree', async () => { + it('filters only a nest rollout whose session id overlaps the primary tree', async () => { const primary = join(root, 'primary') const buzz = join(root, '.buzz') const nested = join(buzz, '.codex') - await writeCodexSession(primary, 'rollout-shared.jsonl') - await writeCodexSession(nested, 'rollout-shared.jsonl') - await writeCodexSession(nested, 'rollout-buzz-only.jsonl') + await writeCodexSession(primary, 'rollout-shared.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz-only.jsonl']) }) + it('keeps a nest rollout whose basename collides but session id is unique', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-shared.jsonl', 'sess-primary') + await writeCodexSession(nested, 'rollout-shared.jsonl', 'sess-nest') + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await nest.discoverSessions())).toEqual(['rollout-shared.jsonl']) + }) + it('default factory with CODEX_HOME=nest and a stub ~/.codex still discovers the nest', async () => { const home = root const primary = join(home, '.codex') @@ -148,13 +159,22 @@ describe('Codex discover overlap-only nest filter', () => { expect(await nest.discoverSessions()).toEqual([]) }) - it('explicit nest path without second-factory opts is not silently emptied', async () => { - const primary = join(root, 'primary') - const nested = join(root, '.buzz', '.codex') - await writeCodexSession(primary, 'rollout-primary.jsonl') - await writeCodexSession(nested, 'rollout-buzz.jsonl') - const provider = createCodexProvider(nested) - expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + it('explicit nest path without second-factory opts uses default launcher roots', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz.jsonl', 'sess-buzz') + const prevHome = process.env.HOME + process.env.HOME = home + try { + const provider = createCodexProvider(nested) + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + } }) }) From 053fa1cd9a42da35b48e815a285ce5c7b611c133 Mon Sep 17 00:00:00 2001 From: Sean Erswell-liljefelt Date: Mon, 24 Aug 2026 09:21:22 +0200 Subject: [PATCH 12/19] docs: add Omarchy plugin installation --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 78ac72f1..955407a6 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,14 @@ gnome-extensions enable codeburn@codeburn.dev See [gnome/README.md](gnome/README.md) for settings and development notes. The Tauri tray app in `windows/` also builds and runs on Linux, but it is experimental and unreleased there — the GNOME extension is the supported Linux surface. +### Omarchy + +Install the [CodeBurn Omarchy plugin](https://omarchyplugins.com/plugin.html?id=codeburn) to add CodeBurn to Omarchy: + +```bash +omarchy plugin add https://github.com/erzz/omarchy-codeburn.git --enable +``` + ## CodeBurn in your agent (MCP) ```bash From fcbc28540f094ee8a7dd80877313613769e5a43b Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 24 Aug 2026 02:19:34 -0700 Subject: [PATCH 13/19] fix(sync): never put a filesystem path on the wire as ai.project MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several providers key a project by its sanitized absolute path ("-Users-me-Projects-app"), and sync shipped that verbatim as ai.project on usage and attribution spans — contradicting docs/sync/README.md's promise that file paths stay local. Confirmed on real exports. One choke point after parseAllSessions maps project to the leaf directory name before either wire path reads it; codeburn yield's local output is untouched. Never-lose: usage span ids and commit attribution keys carry no project (unchanged, no re-send); session attribution keys hash the record, so each already-synced session re-emits once and the receiver upserts by (org, trace) — replaced, not duplicated. Two directories with the same leaf name now collapse to one wire project identity; that is the documented contract, and git.repo still disambiguates. --- src/sync/cli.ts | 5 +++-- src/sync/otlp.ts | 10 ++++++++++ tests/sync-attribution-cli.test.ts | 22 +++++++++++++++++++++- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/sync/cli.ts b/src/sync/cli.ts index 1c40ec1d..509a112f 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -23,7 +23,7 @@ import { import { createCredentialStore } from './credentials.js' import { readSyncConfig, writeSyncConfig, deleteSyncConfig, updateLastSync } from './config.js' import { collectUnsentCalls, collectUnsentAttribution, sendBatches, sendAttributionBatches, batchCalls, MAX_PER_PUSH, MAX_ATTRIBUTION_PER_PUSH, type PushResult } from './push.js' -import { batchAttributionItems } from './otlp.js' +import { batchAttributionItems, wireProjectName } from './otlp.js' export function registerSyncCommands(program: Command): void { const sync = program @@ -274,7 +274,8 @@ export function registerSyncCommands(program: Command): void { process.exit(1) } const { range } = getDateRange(period) - const projects = await parseAllSessions(range) + const projects = (await parseAllSessions(range)) + .map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) })) // Flatten + filter against sent-ledger const { allCalls, unsent, held, frozen } = collectUnsentCalls(projects) diff --git a/src/sync/otlp.ts b/src/sync/otlp.ts index 03c7f11c..2395a2ea 100644 --- a/src/sync/otlp.ts +++ b/src/sync/otlp.ts @@ -65,6 +65,16 @@ export function deriveTraceId(sessionId: string): string { return createHash('sha256').update(sessionId).digest('hex').slice(0, 32) } +/** + * Wire-safe project identity: the leaf directory name. Several providers key a + * project by its sanitized absolute path ("-Users-me-Projects-app"), and + * docs/sync/README.md promises file paths stay local. + */ +export function wireProjectName(projectPath: string, fallback: string): string { + const normalized = projectPath.trim().replace(/\\/g, '/').replace(/\/+$/, '') + return normalized.split('/').filter(Boolean).pop() ?? fallback +} + // --- Timestamp conversion --- function toUnixNano(isoTimestamp: string): string { diff --git a/tests/sync-attribution-cli.test.ts b/tests/sync-attribution-cli.test.ts index 295350fc..65048453 100644 --- a/tests/sync-attribution-cli.test.ts +++ b/tests/sync-attribution-cli.test.ts @@ -10,7 +10,7 @@ import { execFileSync } from 'node:child_process' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest' import { Command } from 'commander' @@ -154,4 +154,24 @@ describe('sync push --attribution (CLI level)', () => { const wire = JSON.stringify(idp.tracesRequests) expect(wire).toContain('github.com/acme/cli-widget') }) + + it('never puts a filesystem path on the wire as ai.project', async () => { + const now = Date.now() + const first = new Date(now - 90 * 60 * 1000).toISOString() + const last = new Date(now - 30 * 60 * 1000).toISOString() + const session = makeSession('cli-sess-1', first, last, [makeCall(`call-${now}`, first)]) + parseAllSessionsMock.mockResolvedValue([ + { project: `-${repoDir.replace(/^\//, '').replace(/\//g, '-')}`, projectPath: repoDir, sessions: [session] } as ProjectSummary, + ]) + await runPush(['--attribution']) + const wire = JSON.stringify(idp.tracesRequests) + expect(wire).not.toContain(repoDir) // no absolute path + expect(wire).not.toContain(repoDir.replace(/\//g, '-')) // no slugified path + const projects = idp.tracesRequests.flatMap(r => (r.body as any).resourceSpans + .flatMap((rs: any) => rs.scopeSpans.flatMap((ss: any) => ss.spans)) + .flatMap((s: any) => s.attributes.filter((a: any) => a.key === 'ai.project') + .map((a: any) => a.value.stringValue))) + expect(projects.length).toBeGreaterThanOrEqual(2) // usage + attribution spans + expect(new Set(projects)).toEqual(new Set([basename(repoDir)])) + }) }) From 619c17ec2e1992938633c0df61a794f4da9c82ae Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 24 Aug 2026 02:25:38 -0700 Subject: [PATCH 14/19] fix(sync): export billable output tokens, not raw output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Providers that bill reasoning separately from output (the exclusive set) were under-reported on the wire by exactly their reasoning volume — measured on a real pilot push: opencode short by 37,848 tokens, the summed reasoningTokens of the window. Cost was already correct (priced locally before export). Route ai.output_tokens through billableOutputTokens, the same correction the display layer took in PR #1115. Inclusive providers (claude, codex, copilot) are byte-identical. Span ids derive from dedup keys that carry no token counts, so nothing re-sends and nothing duplicates. --- src/sync/otlp.ts | 6 +++++- tests/sync-ledger-otlp.test.ts | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/sync/otlp.ts b/src/sync/otlp.ts index 2395a2ea..aa305ffd 100644 --- a/src/sync/otlp.ts +++ b/src/sync/otlp.ts @@ -8,6 +8,7 @@ import { createHash } from 'crypto' import { hostname, userInfo } from 'os' import type { ParsedApiCall } from '../types.js' +import { billableOutputTokens } from '../models.js' import type { SessionAttributionRecord } from '../yield.js' export interface OtlpSpan { @@ -103,7 +104,10 @@ export function buildOtlpPayload(calls: CallWithSession[]): OtlpPayload { { key: 'ai.provider', value: { stringValue: call.provider } }, { key: 'ai.model', value: { stringValue: call.model } }, { key: 'ai.input_tokens', value: { intValue: String(call.usage.inputTokens) } }, - { key: 'ai.output_tokens', value: { intValue: String(call.usage.outputTokens) } }, + // Billable output, not raw: for providers that bill reasoning separately + // the raw output under-reports by the reasoning volume. Same routing the + // display layer adopted in #1115/#1116. + { key: 'ai.output_tokens', value: { intValue: String(billableOutputTokens(call.provider, call.usage.outputTokens, call.usage.reasoningTokens)) } }, { key: 'ai.cost_usd', value: { doubleValue: call.costUSD } }, { key: 'ai.project', value: { stringValue: project } }, { key: 'ai.speed', value: { stringValue: call.speed } }, diff --git a/tests/sync-ledger-otlp.test.ts b/tests/sync-ledger-otlp.test.ts index 53fa9656..1b08c57c 100644 --- a/tests/sync-ledger-otlp.test.ts +++ b/tests/sync-ledger-otlp.test.ts @@ -159,6 +159,44 @@ describe('buildOtlpPayload', () => { expect(attrMap['ai.session_id']).toBeUndefined() }) + it('bills reasoning into ai.output_tokens for exclusive providers (opencode)', () => { + const payload = buildOtlpPayload([makeCallWithSession({ + provider: 'opencode', + usage: { + inputTokens: 1000, + outputTokens: 500, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 250, + webSearchRequests: 0, + }, + })]) + const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes + const attrMap = Object.fromEntries(attrs.map(a => [a.key, a.value])) + + expect(attrMap['ai.output_tokens']).toEqual({ intValue: '750' }) + }) + + it('keeps ai.output_tokens raw for inclusive providers (claude)', () => { + const payload = buildOtlpPayload([makeCallWithSession({ + provider: 'claude', + usage: { + inputTokens: 1000, + outputTokens: 500, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 250, + webSearchRequests: 0, + }, + })]) + const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes + const attrMap = Object.fromEntries(attrs.map(a => [a.key, a.value])) + + expect(attrMap['ai.output_tokens']).toEqual({ intValue: '500' }) + }) + it('includes tools as array attribute', () => { const payload = buildOtlpPayload([makeCallWithSession()]) const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes From 2c87ee3eaa3badacacb8f800e0be30eebe69ef95 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Mon, 24 Aug 2026 18:15:34 +0530 Subject: [PATCH 15/19] fix(codex): walk billed+nest trees on the no-arg singleton filterOverlap required an explicit nest path, so export const codex = createCodexProvider() never deduped. When the resolved dir is a launcher nest and ~/.codex is a distinct existing tree, discover both and drop nest sources whose session id is already billed. Unique nest and billed sessions stay. Soften the Buzz doctor note to a presence heuristic. --- src/launcher-homes.ts | 7 +++-- src/providers/codex.ts | 53 +++++++++++++++++++++++------------- tests/launcher-homes.test.ts | 44 ++++++++++++++++++++++++++---- 3 files changed, 77 insertions(+), 27 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index bf603b72..1c5446f0 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -23,8 +23,9 @@ export function sameCodexHome(a: string, b: string): boolean { } /** True when `dir` is a Codex home nested under a launcher nest, and a distinct - * primary Codex home exists. Gate for overlap-only filtering on a *second* - * provider instance — it does not by itself drop sessions. */ + * primary Codex home exists. Gate for overlap-only filtering — it does not by + * itself drop sessions. The production no-arg factory uses this to walk both + * trees; an explicit nest factory uses it to drop overlapping nest ids. */ export function isNestedLauncherCodexHome( dir: string, opts: { primaryDir: string; launcherRoots: string[] }, @@ -125,7 +126,7 @@ export function collectLauncherNotes(home = homedir()): LauncherNote[] { name: 'buzz', path: buzz, billedVia: 'codex', - verdict: 'LAUNCHER (billed via Codex)', + verdict: 'LAUNCHER (heuristic; billed via Codex)', }) } const grokStore = join(home, '.grok') diff --git a/src/providers/codex.ts b/src/providers/codex.ts index ca3089ce..d036c4e6 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -1330,24 +1330,40 @@ export async function parseCodexFileFull(source: SessionSource, seenKeys: Set { + const id = rolloutFileSessionId(source.path) + return !(id && billedIds.has(id)) + }) +} + export function createCodexProvider( codexDir?: string, opts?: { primaryDir?: string; launcherRoots?: string[] }, ): Provider { const dir = getCodexDir(codexDir) - // Production singleton (no args) still honors CODEX_HOME / override as the - // one root. An explicit nest path — even without second-factory opts — - // overlap-filters against the default billed home using defaultLauncherRoots - // so a future createCodexProvider(nest) cannot double-count session ids. const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome() const launcherRoots = opts?.launcherRoots ?? defaultLauncherRoots() + // Explicit nest factory whose path is a realpath alias of the billed home: + // empty so a second factory cannot double-count the same tree. The no-arg + // singleton must not take this branch — CODEX_HOME may be that alias. const duplicateHome = codexDir !== undefined && sameCodexHome(dir, primaryDir) && resolve(dir) !== resolve(primaryDir) - const filterOverlap = - codexDir !== undefined && - isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots }) + const nestHome = isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots }) + // Production `codex` singleton is createCodexProvider() with no args. When + // the resolved dir is a launcher nest and ~/.codex is a distinct existing + // tree, walk BOTH and drop nest sources whose session id is already billed. + const scanBoth = nestHome && codexDir === undefined return { name: 'codex', @@ -1364,13 +1380,12 @@ export function createCodexProvider( return toolNameMap[rawTool] ?? rawTool }, - // Same `dir` discoverSessionsInDir walks: /sessions (dated - // rollout files) and /archived_sessions. Honors CODEX_HOME. + // Trees discoverSessions actually walks. Honors CODEX_HOME; when the + // production singleton scans nest + billed home, both appear here. async probeRoots(): Promise { - return [ - { path: join(dir, 'sessions'), label: 'sessions' }, - { path: join(dir, 'archived_sessions'), label: 'archived' }, - ] + if (duplicateHome) return [] + if (scanBoth) return [...rootsFor(primaryDir), ...rootsFor(dir)] + return rootsFor(dir) }, async discoverSessions(): Promise { @@ -1378,12 +1393,12 @@ export function createCodexProvider( // distinct nest. isNestedLauncherCodexHome is false in that case. if (duplicateHome) return [] const sources = await discoverSessionsInDir(dir) - if (!filterOverlap) return sources - const primaryIds = listRolloutSessionIds(primaryDir) - return sources.filter(source => { - const id = rolloutFileSessionId(source.path) - return !(id && primaryIds.has(id)) - }) + if (scanBoth) { + const billed = await discoverSessionsInDir(primaryDir) + return [...billed, ...dropOverlappingNestSources(sources, primaryDir)] + } + if (!nestHome) return sources + return dropOverlappingNestSources(sources, primaryDir) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index 69ebe3fd..465f670d 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { mkdtemp, mkdir, writeFile, rm, symlink } from 'fs/promises' import { join } from 'path' import { tmpdir } from 'os' @@ -114,6 +114,8 @@ describe('Codex discover overlap-only nest filter', () => { expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) const roots = await provider.probeRoots!() expect(roots.map(r => r.path)).toEqual([ + join(primary, 'sessions'), + join(primary, 'archived_sessions'), join(nested, 'sessions'), join(nested, 'archived_sessions'), ]) @@ -125,19 +127,51 @@ describe('Codex discover overlap-only nest filter', () => { } }) - it('default factory with CODEX_HOME=nest does not drop unique nest rollouts when ~/.codex has its own', async () => { + it('no-arg factory discovers billed + unique nest and drops overlapping nest ids', async () => { const home = root const primary = join(home, '.codex') const nested = join(home, '.buzz', '.codex') - await writeCodexSession(primary, 'rollout-primary.jsonl') - await writeCodexSession(nested, 'rollout-buzz.jsonl') + await writeCodexSession(primary, 'rollout-billed.jsonl', 'sess-shared') + await writeCodexSession(primary, 'rollout-billed-only.jsonl', 'sess-billed') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') const prevHome = process.env.HOME const prevCodex = process.env.CODEX_HOME process.env.HOME = home process.env.CODEX_HOME = nested try { const provider = createCodexProvider() - expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + expect(names(await provider.discoverSessions()).sort()).toEqual([ + 'rollout-billed-only.jsonl', + 'rollout-billed.jsonl', + 'rollout-buzz-only.jsonl', + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('exported codex singleton dedups nest ids against billed home', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-billed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + vi.resetModules() + try { + const { codex } = await import('../src/providers/codex.js') + expect(names(await codex.discoverSessions()).sort()).toEqual([ + 'rollout-billed.jsonl', + 'rollout-buzz-only.jsonl', + ]) } finally { if (prevHome === undefined) delete process.env.HOME else process.env.HOME = prevHome From 57e897c74a6c10e8f1ad441e7e2be5bcb815ac0a Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Mon, 24 Aug 2026 18:35:59 +0530 Subject: [PATCH 16/19] fix(plan): close Copilot nanoAiu twins once per session foldCopilotSupplementaryTurns will not fold a supplementary twin across a local-day boundary, so the pair can occupy separate turns. Credit spend now groups at session scope. --- src/plan-usage.ts | 11 +++++++--- tests/plan-usage.test.ts | 45 ++++++++++++++++++++++++++++++++++------ 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/src/plan-usage.ts b/src/plan-usage.ts index 72e39bd6..50a14211 100644 --- a/src/plan-usage.ts +++ b/src/plan-usage.ts @@ -83,12 +83,14 @@ function planCallSpend(plan: Plan, call: { costUSD: number; nanoAiu?: number }): return isFiniteNanoAiu(call.nanoAiu) ? creditsToUsd(nanoAiuToCredits(call.nanoAiu)) : 0 } -function forEachPlanTurn(projects: ProjectSummary[], visit: (calls: ParsedApiCall[]) => void): void { +function forEachPlanSession(projects: ProjectSummary[], visit: (calls: ParsedApiCall[]) => void): void { for (const project of projects) { for (const session of project.sessions ?? []) { + const calls: ParsedApiCall[] = [] for (const turn of session.turns ?? []) { - visit(turn.assistantCalls ?? []) + calls.push(...(turn.assistantCalls ?? [])) } + visit(calls) } } } @@ -96,7 +98,10 @@ function forEachPlanTurn(projects: ProjectSummary[], visit: (calls: ParsedApiCal export function copilotCreditSpend(projects: ProjectSummary[]): { spentCredits: number; creditsIncomplete: boolean } { let nanoSum = 0 let creditsIncomplete = false - forEachPlanTurn(projects, calls => { + // Pairing is session-wide. foldCopilotSupplementaryTurns will not fold a + // supplementary twin across a local-day boundary, so both nanoAiu rows can + // occupy separate turns of the same session. Close the twin once here. + forEachPlanSession(projects, calls => { const copilot = calls.filter(call => call.provider === 'copilot') if (copilot.length === 0) return const primaryNano = copilot.filter(call => !call.supplementaryAccounting && isFiniteNanoAiu(call.nanoAiu)) diff --git a/tests/plan-usage.test.ts b/tests/plan-usage.test.ts index 7882c030..91b85ee3 100644 --- a/tests/plan-usage.test.ts +++ b/tests/plan-usage.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { describe, it, expect, vi, beforeEach } from 'vitest' import { savePlan, type Plan } from '../src/config.js' -import { activePlansFromMap, computePeriodFromResetDay, getPlanScopedProjects, getPlanUsage, getPlanUsageFromProjects, getPlanUsages } from '../src/plan-usage.js' +import { activePlansFromMap, computePeriodFromResetDay, copilotCreditSpend, getPlanScopedProjects, getPlanUsage, getPlanUsageFromProjects, getPlanUsages } from '../src/plan-usage.js' import type { ProjectSummary } from '../src/types.js' const { parseAllSessionsMock } = vi.hoisted(() => ({ @@ -446,21 +446,26 @@ function usageCall(overrides: { } } -function usageProject(calls: ReturnType[]): ProjectSummary { +function usageProjectFromTurns(turns: ReturnType[][]): ProjectSummary { + const calls = turns.flat() return { project: 'codeburn', projectPath: '/tmp/codeburn', totalCostUSD: calls.reduce((sum, call) => sum + call.costUSD, 0), totalApiCalls: calls.length, sessions: [{ - turns: [{ - timestamp: calls[0]!.timestamp, - assistantCalls: calls, - }], + turns: turns.map(assistantCalls => ({ + timestamp: assistantCalls[0]!.timestamp, + assistantCalls, + })), }], } as ProjectSummary } +function usageProject(calls: ReturnType[]): ProjectSummary { + return usageProjectFromTurns([calls]) +} + describe('copilot AI credit plan math', () => { const today = new Date('2026-08-10T12:00:00.000Z') const copilotPro: Plan = { @@ -568,6 +573,34 @@ describe('copilot AI credit plan math', () => { expect(usage.creditsIncomplete).toBe(false) }) + it('does not double credits when nanoAiu twins sit in separate session turns', () => { + // foldCopilotSupplementaryTurns refuses a local-day-boundary pair, so the + // supplementary twin stays on its own turn. Credit math must still close + // once at session scope. + const projects = [ + usageProjectFromTurns([ + [usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T18:25:00.000Z', + nanoAiu: 1_500_000_000, + })], + [usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T18:35:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + })], + ]), + ] + + expect(copilotCreditSpend(projects).spentCredits).toBe(1.5) + const usage = getPlanUsageFromProjects(copilotPro, projects, today) + expect(usage.spentCredits).toBe(1.5) + expect(usage.creditsIncomplete).toBe(false) + }) + it('keeps a $0 nanoAiu-only session on copilot plans and drops it on USD plans', () => { const projects = [ usageProject([ From ada8ce2ac4b0757846c8c5631b76cdd73b20be29 Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Mon, 24 Aug 2026 18:36:25 +0530 Subject: [PATCH 17/19] fix(codex): read a complete session_meta first line rolloutFileSessionId sliced 8192 bytes then JSON.parse. Production session_meta first lines are 22-27 KB, so both trees returned undefined ids and the overlapping nest source was kept. Read up to the existing 1 MiB first-line cap and parse payload.session_id from the complete line. Pin billed-A / nest-A / nest-B at 30 KB on the exported no-arg singleton. --- src/launcher-homes.ts | 13 ++++++++-- src/providers/codex.ts | 4 +-- tests/launcher-homes.test.ts | 49 +++++++++++++++++++++++++++++++++--- 3 files changed, 58 insertions(+), 8 deletions(-) diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts index 1c5446f0..191afb34 100644 --- a/src/launcher-homes.ts +++ b/src/launcher-homes.ts @@ -41,15 +41,24 @@ export function isNestedLauncherCodexHome( return existsSync(primary) } +// Same bound as `readFirstLine` in providers/codex.ts. Real Codex +// session_meta first lines are ~22–27 KB; 8 KiB truncates them mid-JSON. +export const FIRST_LINE_READ_CAP = 1024 * 1024 + /** Session id from the first `session_meta` line of a Codex rollout file. * Missing / unreadable files return undefined — callers must not drop those. */ export function rolloutFileSessionId(filePath: string): string | undefined { try { const fd = openSync(filePath, 'r') try { - const buf = Buffer.alloc(8192) + const buf = Buffer.alloc(FIRST_LINE_READ_CAP) const n = readSync(fd, buf, 0, buf.length, 0) - const line = buf.subarray(0, n).toString('utf8').split('\n', 1)[0] ?? '' + if (n === 0) return undefined + const slice = buf.subarray(0, n) + const nl = slice.indexOf(0x0a) + // Hit the 1 MiB cap without a newline: incomplete, not a parseable id. + if (nl === -1 && n === FIRST_LINE_READ_CAP) return undefined + const line = (nl === -1 ? slice : slice.subarray(0, nl)).toString('utf8') if (!line) return undefined const parsed: unknown = JSON.parse(line) if (!parsed || typeof parsed !== 'object') return undefined diff --git a/src/providers/codex.ts b/src/providers/codex.ts index d036c4e6..81bbba8f 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -12,7 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' -import { defaultBilledCodexHome, defaultLauncherRoots, isNestedLauncherCodexHome, listRolloutSessionIds, rolloutFileSessionId, sameCodexHome } from '../launcher-homes.js' +import { defaultBilledCodexHome, defaultLauncherRoots, FIRST_LINE_READ_CAP, isNestedLauncherCodexHome, listRolloutSessionIds, rolloutFileSessionId, sameCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -178,7 +178,7 @@ function sanitizeProject(cwd: string): string { // Cap how many bytes we'll read while looking for the first newline. Real // Codex session_meta lines are ~22-27 KB; this leaves plenty of headroom while // keeping memory bounded if a corrupt file has no newline at all. -const FIRST_LINE_READ_CAP = 1024 * 1024 +// FIRST_LINE_READ_CAP is shared with rolloutFileSessionId. async function readFirstLine(filePath: string): Promise { // Codex CLI 0.128+ writes a session_meta line that can exceed 20 KB because diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts index 465f670d..0bc39449 100644 --- a/tests/launcher-homes.test.ts +++ b/tests/launcher-homes.test.ts @@ -8,19 +8,24 @@ import { collectDoctorReport, renderDoctorTable } from '../src/doctor.js' import { createCodexProvider } from '../src/providers/codex.js' import { emptyCache } from '../src/session-cache.js' -function sessionMeta(sessionId: string): string { +function sessionMeta(sessionId: string, extra: Record = {}): string { return JSON.stringify({ type: 'session_meta', timestamp: '2026-04-14T10:00:00Z', - payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: sessionId, model: 'gpt-5.3-codex' }, + payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: sessionId, model: 'gpt-5.3-codex', ...extra }, }) } -async function writeCodexSession(codexDir: string, name: string, sessionId?: string): Promise { +/** Production Codex session_meta first lines are ~22–27 KB. */ +function longSessionMeta(sessionId: string): string { + return sessionMeta(sessionId, { base_instructions: 'x'.repeat(30 * 1024) }) +} + +async function writeCodexSession(codexDir: string, name: string, sessionId?: string, meta?: string): Promise { const id = sessionId ?? name.replace(/^rollout-/, '').replace(/\.jsonl$/, '') const dayDir = join(codexDir, 'sessions', '2026', '04', '14') await mkdir(dayDir, { recursive: true }) - await writeFile(join(dayDir, name), `${sessionMeta(id)}\n`) + await writeFile(join(dayDir, name), `${meta ?? sessionMeta(id)}\n`) } function names(sources: { path: string }[]): string[] { @@ -180,6 +185,42 @@ describe('Codex discover overlap-only nest filter', () => { } }) + it('exported no-arg singleton dedups production-size session_meta first lines', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + const billedA = longSessionMeta('sess-A') + const nestA = longSessionMeta('sess-A') + const nestB = longSessionMeta('sess-B') + expect(Buffer.byteLength(billedA, 'utf8')).toBeGreaterThan(8 * 1024) + expect(Buffer.byteLength(nestA, 'utf8')).toBeGreaterThan(8 * 1024) + expect(Buffer.byteLength(nestB, 'utf8')).toBeGreaterThan(8 * 1024) + await writeCodexSession(primary, 'rollout-billed-A-long.jsonl', 'sess-A', billedA) + await writeCodexSession(nested, 'rollout-nest-A-long.jsonl', 'sess-A', nestA) + await writeCodexSession(nested, 'rollout-nest-B-long.jsonl', 'sess-B', nestB) + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + vi.resetModules() + try { + const { createCodexProvider: noArgFactory, codex } = await import('../src/providers/codex.js') + expect(names(await noArgFactory().discoverSessions()).sort()).toEqual([ + 'rollout-billed-A-long.jsonl', + 'rollout-nest-B-long.jsonl', + ]) + expect(names(await codex.discoverSessions()).sort()).toEqual([ + 'rollout-billed-A-long.jsonl', + 'rollout-nest-B-long.jsonl', + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + it('second factory on a realpath-equivalent nest emits no duplicate sources', async () => { const primary = join(root, 'primary') const buzz = join(root, '.buzz') From b0a42172fbfff681845d0b756d1883b21b058ece Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 24 Aug 2026 06:41:47 -0700 Subject: [PATCH 18/19] fix(daily-cache): never-lose guards for degraded parses and residue-only days MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diagnosed via #1127. Three guards: - The gap-fill path no longer overwrites cached days wholesale: a complete parse wins per (date, provider) through the same guarded merge the re-derive path uses; a partial parse only fills days and slices the baseline lacks. Previously a parse degraded by the refresh lock (menubar running) could replace a good day with its undercount permanently. The gap path also stops dropping pendingRederive. - A day whose only content is turn-anchored residue (a midnight- straddling turn's category counts with zero cost/calls/tokens) is never sealed: the watermark pulls back so the next launch re-derives it — self-healing for every broken cache in the wild, no version bump. Bounded to the settle window and never for the oldest cached day. - codeburn doctor gains a read-only Cache health section listing residue-only dates and failed/empty session-cache entries, so the next report like #1127 is diagnosable in one command. Tests: residue-shape pin (day-aggregator), partial-gap cannot shrink a populated day (fails on the old code), complete-gap parity, watermark pull-back re-derive. --- src/daily-cache.ts | 51 ++++++++++- src/doctor.ts | 81 +++++++++++++++++ .../daily-cache-degraded-completeness.test.ts | 90 +++++++++++++++++++ tests/day-aggregator.test.ts | 60 +++++++++++++ 4 files changed, 280 insertions(+), 2 deletions(-) diff --git a/src/daily-cache.ts b/src/daily-cache.ts index 400806bc..5111e6b1 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -1179,6 +1179,15 @@ export function toDateString(date: Date): string { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` } +/// A day whose ONLY content is turn-anchored residue (one straddling turn's +/// category/edit counts, no calls) is not a derived day — it is a day the parse +/// under-read. Re-derive it instead of serving it. +export function isTurnResidueOnly(day: DailyEntry): boolean { + if (day.cost > 0 || day.calls > 0 || day.sessions > 0) return false + if (day.inputTokens + day.outputTokens + day.cacheReadTokens + day.cacheWriteTokens > 0) return false + return Object.values(day.categories).some(c => c.turns > 0) +} + export async function ensureCacheHydrated( parseSessions: (range: DateRange) => Promise, aggregateDays: (projects: ProjectSummary[]) => DailyEntry[], @@ -1241,6 +1250,34 @@ export async function ensureCacheHydrated( c = { ...c, lastComputedDate: newestCachedDate } } + // Never seal a residue-only day (issue #1127): a day whose only content is + // turn-anchored residue was under-read by the parse that produced it, so + // trust the DATA over the marker again — pull the watermark back to just + // before the oldest such day and let the ordinary gap parse re-derive it. + // This is what heals every already-broken cache on the next launch, with + // no version bump. + // + // Caveat: a day that GENUINELY held only one straddling turn and no other + // activity re-derives to the same residue shape and would be re-parsed on + // every launch. Bound that cost: skip the pull-back when the residue day + // is the oldest day in the cache, and only pull back inside the settle + // window — outside it the source files are gone and re-deriving cannot + // recover the day anyway. + const oldestCachedDate = c.days.reduce((min, d) => (min === null || d.date < min ? d.date : min), null) + const residueSettleCutoff = settleCutoffDate(now) + const oldestResidueDate = c.days.reduce( + (min, d) => (d.date >= residueSettleCutoff && d.date !== oldestCachedDate && isTurnResidueOnly(d) && (min === null || d.date < min) ? d.date : min), + null, + ) + if (oldestResidueDate !== null && c.lastComputedDate !== null && c.lastComputedDate >= oldestResidueDate) { + const pulledBack = new Date( + parseInt(oldestResidueDate.slice(0, 4)), + parseInt(oldestResidueDate.slice(5, 7)) - 1, + parseInt(oldestResidueDate.slice(8, 10)) - 1 + ) + c = { ...c, lastComputedDate: toDateString(pulledBack) } + } + // Three reasons to re-derive the whole retention window: // 1. Savings config changed — cached `savingsUSD` totals are stale. // 2. The cache was never finalized against a COMPLETE session parse (an old @@ -1354,7 +1391,17 @@ export async function ensureCacheHydrated( const gapDays = aggregateDays(gapProjects) const parseWasComplete = sessionComplete() const priorWatermark = c.lastComputedDate - c = addNewDays(c, gapDays, yesterdayStr) + // Gate the merge on parse completeness (issue #1127): replacing cached + // days wholesale with the gap parse's days let a PARTIAL parse overwrite + // a populated baseline day with its under-read version — and if the + // day's sources die before the next complete parse, the undercount is + // what survives. A complete parse still wins per (date, provider) + // exactly as the re-derive path does (partial-survival guarded); a + // partial one only fills days and slices the baseline lacks, so the gap + // merge is strictly additive and no cached data can shrink. + const merged = parseWasComplete + ? mergeDayEntries(gapDays, c.days, false, undefined, true) + : mergeDayEntries(c.days, gapDays, false) // Finalize as complete ONLY when the session parse that produced these days // was itself complete. If it was partial, leave `complete: false` so the // next launch (once the session cache is whole) re-backfills instead of @@ -1362,7 +1409,7 @@ export async function ensureCacheHydrated( // the same reason as the re-derive path above: a partial parse cannot // vouch for the days it never read, and gapStart is the only thing that // will ever bring them back. - c = { ...c, lastComputedDate: parseWasComplete ? c.lastComputedDate : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } + c = { ...c, days: applyRetention(merged, yesterdayStr), lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } await saveDailyCache(c) } else if (c.complete !== true && sessionComplete()) { // No gap to fill (already current through yesterday) but not yet marked — diff --git a/src/doctor.ts b/src/doctor.ts index 95a3d44d..0f13a949 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -7,6 +7,7 @@ import { Chalk } from 'chalk' import { getClaudeConfigDirs } from './providers/claude.js' import { getAllProviders } from './providers/index.js' import type { Provider } from './providers/types.js' +import { dailyCachePath, isTurnResidueOnly, type DailyEntry } from './daily-cache.js' import { PROVIDER_ENV_VARS, PROVIDER_PARSE_VERSIONS, @@ -68,6 +69,24 @@ export type ClaudeRetentionNote = { settingsPath: string } +export type DoctorSessionCacheIssue = { + provider: string + /// Session-cache file key (the source path, including any virtual suffix). + path: string + reason: 'failed' | 'no-turns' +} + +export type DoctorCacheHealth = { + /// Daily-cache dates whose only content is turn-anchored residue — a day the + /// parse under-read (isTurnResidueOnly, issue #1127). ensureCacheHydrated + /// re-derives them on the next launch; they are listed here so the state is + /// visible without an archaeology dig. + residueOnlyDays: string[] + /// Session-cache entries flagged as parse failures or cached with zero + /// turns — the under-read entries residue days come from. + sessionCacheIssues: DoctorSessionCacheIssue[] +} + export type DoctorReport = { generatedAt: string providers: DoctorProviderReport[] @@ -75,6 +94,8 @@ export type DoctorReport = { /// found. Surfaced because deleted transcripts are unrecoverable: daily /// totals survive in CodeBurn's cache, but per-session detail does not. claudeRetention?: ClaudeRetentionNote + /// Present only when there is something to list. + cacheHealth?: DoctorCacheHealth } export type CollectDoctorOptions = { @@ -82,6 +103,8 @@ export type CollectDoctorOptions = { providers?: Provider[] /** Injectable cache snapshot (defaults to reading session-cache.json). */ cache?: SessionCache + /** Injectable daily-cache days (defaults to reading the daily cache file). */ + dailyCacheDays?: DailyEntry[] /** Max discovered sources to parse-sample per provider. */ sampleLimit?: number } @@ -334,6 +357,11 @@ export async function collectDoctorReport( const retention = await collectClaudeRetention() if (retention) report.claudeRetention = retention } + const residueOnlyDays = collectResidueOnlyDays(opts.dailyCacheDays ?? await readDailyCacheDays()) + const sessionCacheIssues = collectSessionCacheIssues(cache) + if (residueOnlyDays.length > 0 || sessionCacheIssues.length > 0) { + report.cacheHealth = { residueOnlyDays, sessionCacheIssues } + } return report } finally { if (prevSuppress === undefined) delete process.env['CODEBURN_SUPPRESS_CACHE_WRITES'] @@ -347,6 +375,45 @@ const CLAUDE_DEFAULT_CLEANUP_DAYS = 30 // the doctor line turns into a warning. const CLAUDE_RETENTION_WARN_DAYS = 365 +/// Read-only peek at the daily cache's days: loadDailyCache can WRITE +/// (adoption / migration), which doctor's read-only promise forbids, so the +/// file is read and parsed directly. Anything unreadable or foreign simply +/// yields no days — doctor must never crash on a corrupt cache. +async function readDailyCacheDays(): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(dailyCachePath(), 'utf-8')) + const days = (parsed as { days?: unknown } | null)?.days + if (!Array.isArray(days)) return [] + return days.filter((d): d is DailyEntry => !!d && typeof d === 'object' && typeof (d as DailyEntry).date === 'string') + } catch { + return [] + } +} + +function collectResidueOnlyDays(days: DailyEntry[]): string[] { + const out: string[] = [] + for (const d of days) { + try { + if (isTurnResidueOnly(d)) out.push(d.date) + } catch { + // Foreign junk in a hand-edited cache: skip the day, keep diagnosing. + } + } + return out.sort() +} + +function collectSessionCacheIssues(cache: SessionCache): DoctorSessionCacheIssue[] { + const out: DoctorSessionCacheIssue[] = [] + for (const [provider, section] of Object.entries(cache.providers)) { + for (const [path, f] of Object.entries(section.files)) { + // A failed entry carries no turns by construction; report it once, as failed. + if (f.failed) out.push({ provider, path, reason: 'failed' }) + else if (Array.isArray(f.turns) && f.turns.length === 0) out.push({ provider, path, reason: 'no-turns' }) + } + } + return out +} + async function collectClaudeRetention(): Promise { for (const dir of await getClaudeConfigDirs()) { const settingsPath = join(dir, 'settings.json') @@ -445,6 +512,20 @@ export function renderDoctorTable( } } + if (report.cacheHealth) { + out.push('') + out.push(c.bold('Cache health') + c.dim(' (issue #1127 diagnostics — under-read cache entries)')) + for (const date of report.cacheHealth.residueOnlyDays) { + out.push(' ' + c.yellow(date) + c.dim(' residue-only day (turn counts but no calls/cost); re-derived on next launch')) + } + for (const issue of report.cacheHealth.sessionCacheIssues) { + out.push( + ' ' + c.dim(`${issue.provider} `) + issue.path + + c.dim(issue.reason === 'failed' ? ' (cached parse failure)' : ' (cached with 0 turns)'), + ) + } + } + if (report.claudeRetention) { const r = report.claudeRetention const source = r.configured ? 'cleanupPeriodDays' : 'cleanupPeriodDays not set; Claude Code default' diff --git a/tests/daily-cache-degraded-completeness.test.ts b/tests/daily-cache-degraded-completeness.test.ts index d3df6cce..af7f2573 100644 --- a/tests/daily-cache-degraded-completeness.test.ts +++ b/tests/daily-cache-degraded-completeness.test.ts @@ -14,6 +14,7 @@ import { currentTzKey, ensureCacheHydrated, saveDailyCache, + toDateString, } from '../src/daily-cache.js' const TMP_CACHE_ROOT = join(tmpdir(), `codeburn-degraded-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`) @@ -185,3 +186,92 @@ describe('daily cache: a complete cache that outruns its own data is not trusted expect(out.complete).toBe(true) }) }) + +/// A day whose only content is turn-anchored residue: one straddling turn's +/// category counts, zero cost/calls/sessions/tokens (isTurnResidueOnly). +function residueDay(date: string): DailyEntry { + return day(date, {}, { + categories: { conversation: { turns: 1, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 } }, + }) +} + +describe('daily cache: the gap path never shrinks a populated baseline day', () => { + // A populated baseline day inside the gap window (carried there by an older + // cache generation while the watermark sat behind it). The gap parse + // under-reads it: 5 calls / $5 where the baseline holds 500 / $50. + async function seedGapDay(): Promise { + await seed({ + days: [ + VANISHED, + day(daysAgoStr(4), { claude: slice(120, 900) }), + day(daysAgoStr(2), { claude: slice(50, 500), grok: slice(9, 60) }), + ], + }) + } + + it('a partial gap parse only fills what the baseline lacks', async () => { + await seedGapDay() + const underRead = [day(daysAgoStr(2), { claude: slice(5, 10) })] + const out = await ensureCacheHydrated(noSessions, () => underRead, 'cfg-A', () => false) + const kept = out.days.find(d => d.date === daysAgoStr(2))! + // Baseline wins wholesale: the partial parse's undercount must not replace it. + expect(kept.cost).toBe(59) + expect(kept.calls).toBe(560) + expect(kept.providers['claude']).toMatchObject({ cost: 50, calls: 500 }) + expect(kept.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + // Watermark held and not finalized, so a later complete parse re-covers the gap. + expect(out.lastComputedDate).toBe(daysAgoStr(4)) + expect(out.complete).toBe(false) + expectPreserved(out) + }) + + it('a complete gap parse still wins per (date, provider)', async () => { + await seedGapDay() + const fresh = [day(daysAgoStr(2), { claude: slice(75, 620) })] + const out = await ensureCacheHydrated(noSessions, () => fresh, 'cfg-A', () => true) + const rederived = out.days.find(d => d.date === daysAgoStr(2))! + // The fresh claude slice replaces the baseline one; the grok slice the + // parse did not produce is carried, not wiped. + expect(rederived.providers['claude']).toMatchObject({ cost: 75, calls: 620 }) + expect(rederived.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + expect(rederived.cost).toBe(84) + expect(rederived.calls).toBe(680) + expect(out.days.map(d => d.date)).toEqual([daysAgoStr(40), daysAgoStr(4), daysAgoStr(2)]) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + expectPreserved(out) + }) +}) + +describe('daily cache: a residue-only day is re-derived, not served', () => { + it('pulls the watermark back to just before the residue day so the gap parse re-derives it', async () => { + // The broken-cache shape issue #1127 leaves behind: complete and stamped, + // watermark at yesterday, and a residue-only day sealed behind it. The + // oldest-day exemption does not apply (an older populated day exists) and + // the residue day is inside the settle window. + await seed({ + lastComputedDate: daysAgoStr(1), + watermarkTrusted: true, + days: [day(daysAgoStr(10), { claude: slice(80, 700) }), residueDay(daysAgoStr(3))], + }) + const ranges: DateRange[] = [] + const rederived = [day(daysAgoStr(3), { claude: slice(33, 210) })] + const out = await ensureCacheHydrated( + async (range) => { ranges.push(range); return [] }, + () => rederived, + 'cfg-A', + () => true, + ) + // The watermark moved back to daysAgoStr(4), so the gap parse started on + // the residue day itself instead of skipping it forever. + expect(ranges).toHaveLength(1) + expect(toDateString(ranges[0]!.start)).toBe(daysAgoStr(3)) + const healed = out.days.find(d => d.date === daysAgoStr(3))! + expect(healed.providers['claude']).toMatchObject({ cost: 33, calls: 210 }) + expect(healed.cost).toBe(33) + expect(healed.calls).toBe(210) + expect(out.days.find(d => d.date === daysAgoStr(10))).toMatchObject({ cost: 80, calls: 700 }) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + }) +}) diff --git a/tests/day-aggregator.test.ts b/tests/day-aggregator.test.ts index f561a877..874dee97 100644 --- a/tests/day-aggregator.test.ts +++ b/tests/day-aggregator.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { aggregateProjectsIntoDays, buildPeriodDataFromDays, dateKey } from '../src/day-aggregator.js' +import { isTurnResidueOnly } from '../src/daily-cache.js' import type { ProjectSummary } from '../src/types.js' function makeProject(overrides: Partial & { sessions: ProjectSummary['sessions'] }): ProjectSummary { @@ -220,6 +221,65 @@ describe('aggregateProjectsIntoDays', () => { expect(days[0]!.providers).toEqual({}) }) + it("pins the residue shape: a sliced straddling turn leaves turn counts but zero cost/calls on the anchor day", () => { + // The contract isTurnResidueOnly keys off (issue #1127). A history parse + // that ends at midnight slices a straddling turn to its in-range calls; + // when the surviving half carries the turn-level judgments (category, + // editTurns) onto day A but every call landed on day B, day A is left + // holding ONLY residue: categories.conversation.turns === 1 with + // cost/calls/sessions all 0. Construct in LOCAL time so the turn + // genuinely straddles local midnight on any machine TZ. + const iso = (y: number, mo: number, d: number, h: number, mi: number) => + new Date(y, mo, d, h, mi, 0).toISOString() + const turnTs = iso(2026, 3, 16, 23, 58) // day A, just before midnight + const callTs = iso(2026, 3, 17, 0, 5) // day B: every call past midnight + const dayA = dateKey(turnTs) + const dayB = dateKey(callTs) + expect(dayA).not.toBe(dayB) // sanity: the fixture really straddles local midnight + + const projects: ProjectSummary[] = [ + makeProject({ + sessions: [{ + sessionId: 's1', + project: 'p', + firstTimestamp: callTs, + lastTimestamp: callTs, + totalCostUSD: 6, + totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, + apiCalls: 1, + turns: [ + { + userMessage: 'one more thing before bed', timestamp: turnTs, sessionId: 's1', + category: 'conversation', retries: 0, hasEdits: false, + assistantCalls: [makeCall(callTs, 6)], + }, + ], + modelBreakdown: {}, toolBreakdown: {}, mcpBreakdown: {}, bashBreakdown: {}, + categoryBreakdown: {} as never, + skillBreakdown: {} as never, + }], + }), + ] + + const days = aggregateProjectsIntoDays(projects) + const anchor = days.find(d => d.date === dayA)! + const next = days.find(d => d.date === dayB)! + + // Anchor day: ONLY turn-anchored residue — no cost, calls, sessions, or tokens. + expect(anchor.cost).toBe(0) + expect(anchor.calls).toBe(0) + expect(anchor.sessions).toBe(0) + expect(anchor.inputTokens + anchor.outputTokens + anchor.cacheReadTokens + anchor.cacheWriteTokens).toBe(0) + expect(anchor.categories['conversation']!.turns).toBe(1) + expect(isTurnResidueOnly(anchor)).toBe(true) + + // Next day: the full cost/calls of the same turn. + expect(next.cost).toBe(6) + expect(next.calls).toBe(1) + expect(next.sessions).toBe(1) + expect(isTurnResidueOnly(next)).toBe(false) + }) + it('counts a session under its firstTimestamp date', () => { const projects: ProjectSummary[] = [ makeProject({ From fe89385af8f9db541ceadf8701c8b6db6346d91f Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 24 Aug 2026 07:16:06 -0700 Subject: [PATCH 19/19] docs: mark the Omarchy plugin community-maintained (#1125 follow-up) --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 51c90484..c1ca15c2 100644 --- a/README.md +++ b/README.md @@ -369,6 +369,8 @@ See [gnome/README.md](gnome/README.md) for settings and development notes. The T Install the [CodeBurn Omarchy plugin](https://omarchyplugins.com/plugin.html?id=codeburn) to add CodeBurn to Omarchy: +Community-maintained by [@erzz](https://github.com/erzz) — issues and feature requests go to [erzz/omarchy-codeburn](https://github.com/erzz/omarchy-codeburn). + ```bash omarchy plugin add https://github.com/erzz/omarchy-codeburn.git --enable ```