diff --git a/src/compare-stats.ts b/src/compare-stats.ts index 2b4b9931..1cad5350 100644 --- a/src/compare-stats.ts +++ b/src/compare-stats.ts @@ -1,5 +1,5 @@ import { readdir, readFile } from 'fs/promises' -import { join } from 'path' +import { basename, join } from 'path' import type { ClassifiedTurn, ProjectSummary } from './types.js' import { isBehavioralCall } from './behavioral-weight.js' @@ -379,7 +379,16 @@ async function collectJsonlFiles(sessionDir: string): Promise { return files } -export async function scanSelfCorrections(projectDirs: string[]): Promise> { +/// Session ids of every session in `projects`. For Claude transcripts the id IS +/// the `.jsonl` stem, which is what lets a project-filtered compare scope the +/// self-correction scan to the sessions it actually reported on. +export function projectSessionIds(projects: readonly ProjectSummary[]): Set { + return new Set(projects.flatMap(p => p.sessions.map(s => s.sessionId))) +} + +/// `sessionIds`, when given, restricts the scan to transcripts whose file stem +/// is one of them; omitted, every file under `projectDirs` is read as before. +export async function scanSelfCorrections(projectDirs: string[], sessionIds?: ReadonlySet): Promise> { const counts = new Map() const seen = new Set() @@ -407,6 +416,7 @@ export async function scanSelfCorrections(projectDirs: string[]): Promise('select') const [models, setModels] = useState(() => aggregateModelStats(projects)) @@ -426,7 +429,7 @@ export function CompareView({ projects, onBack, presetModels }: CompareViewProps const sessions = await p.discoverSessions() for (const s of sessions) dirs.push(s.path) } - const corrections = await scanSelfCorrections(dirs) + const corrections = await scanSelfCorrections(dirs, scopeToProjects ? projectSessionIds(projectsRef.current) : undefined) if (cancelled) return const currentProjects = projectsRef.current @@ -521,6 +524,7 @@ export async function renderCompare(range: DateRange, provider: string, modelA?: } patchStdoutForWindows() + const hasProjectFilter = (projectFilter?.length ?? 0) > 0 || (excludeFilter?.length ?? 0) > 0 const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) // --model-a/--model-b: resolve up front (by canonical id or display name, @@ -545,7 +549,7 @@ export async function renderCompare(range: DateRange, provider: string, modelA?: const stopUserTimingGuard = startUserTimingGuard() try { const { waitUntilExit } = render( - process.exit(0)} presetModels={presetModels} /> + process.exit(0)} presetModels={presetModels} scopeToProjects={hasProjectFilter} /> ) await waitUntilExit() } finally { diff --git a/src/dashboard.tsx b/src/dashboard.tsx index dcc34092..5eb9d562 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -2112,7 +2112,7 @@ export function InteractiveDashboard({ initialProjects, initialDailyHistoryProje {isCustomRange && } {indexing && } {view === 'compare' - ? setView('dashboard')} /> + ? setView('dashboard')} scopeToProjects={(projectFilter?.length ?? 0) > 0 || (excludeFilter?.length ?? 0) > 0} /> : view === 'optimize' && optimizeResult ? : } diff --git a/src/main.ts b/src/main.ts index b31116a1..1274e77d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -33,7 +33,7 @@ import { pairingCode } from './sharing/pairing.js' import { ShareController } from './sharing/share-controller.js' import { getSharingDir, loadRemotes, saveRemotes } from './sharing/store.js' import type { UsageQuery } from './sharing/share-server.js' -import { formatDateRangeLabel, parseDateRangeFlags, parseDayFlag, parseDaysFlag, getDateRange, toPeriod, type Period } from './cli-date.js' +import { formatDateRangeLabel, parseDateRangeFlags, parseDayFlag, parseDaysFlag, getDateRange, periodInfoFromQuery, toPeriod, type Period } from './cli-date.js' import { runOptimize } from './optimize.js' import { registerActCommands } from './act/cli.js' import { registerGuardCommands } from './guard/cli.js' @@ -1077,6 +1077,11 @@ program .option('--no-open', 'Do not open the browser automatically') .action(async (opts) => { assertProvider(opts.provider, 'web') + if (opts.project.length > 0 || opts.exclude.length > 0) { + const { range } = periodInfoFromQuery({ period: opts.period, from: opts.from, to: opts.to }, 'today') + const parsed = await parseAllSessions(range, opts.provider) + await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range)) + } await runWebDashboard({ period: opts.period, provider: opts.provider, @@ -2242,7 +2247,7 @@ program await loadPricing() const { range, label } = getDateRange(opts.period) if (opts.format === 'json') { - const { aggregateModelStats, buildCompareJson, findModelStat, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js') + const { aggregateModelStats, buildCompareJson, findModelStat, projectSessionIds, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js') const parsed = await parseAllSessions(range, opts.provider) await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range)) const projects = filterProjectsByName(parsed, opts.project, opts.exclude) @@ -2254,7 +2259,8 @@ program const sessions = await provider.discoverSessions() for (const session of sessions) dirs.push(session.path) } - const corrections = await scanSelfCorrections(dirs) + const scope = opts.project.length > 0 || opts.exclude.length > 0 ? projectSessionIds(projects) : undefined + const corrections = await scanSelfCorrections(dirs, scope) for (const model of models) { model.selfCorrections = corrections.get(model.model) ?? 0 } diff --git a/tests/cli-project-filter-commands.test.ts b/tests/cli-project-filter-commands.test.ts index 6f9df662..5cbde8ee 100644 --- a/tests/cli-project-filter-commands.test.ts +++ b/tests/cli-project-filter-commands.test.ts @@ -1,7 +1,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { spawnSync } from 'node:child_process' +import { spawn, spawnSync } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -93,6 +93,32 @@ async function seedDayCacheOnly(): Promise { return home } +/** A project pair whose assistant turns all read as self-corrections. */ +async function seedHomeWithApologies(): Promise { + const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-')) + homes.push(home) + const now = Date.now() + for (const [offset, project] of SIBLINGS.entries()) { + const dir = join(home, '.claude', 'projects', project.dir) + await mkdir(dir, { recursive: true }) + // scanSelfCorrections dedupes on model+timestamp, so the siblings must not + // share one. + const lines = [1, 2].map(index => JSON.stringify({ + type: 'assistant', + timestamp: new Date(now - (30 - index - offset * 5) * 60_000).toISOString(), + sessionId: project.session, + cwd: project.cwd, + message: { + type: 'message', role: 'assistant', model: 'claude-3-5-sonnet-20241022', id: `${project.session}-m${index}`, + content: [{ type: 'text', text: 'I apologize for the confusion.' }], + usage: { input_tokens: 90000, output_tokens: 12000, cache_creation_input_tokens: 0, cache_read_input_tokens: 300000 }, + }, + })) + await writeFile(join(dir, `${project.session}.jsonl`), lines.join('\n') + '\n', 'utf-8') + } + return home +} + function runCli(args: string[], home: string) { return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { cwd: process.cwd(), @@ -102,7 +128,41 @@ function runCli(args: string[], home: string) { }) } +/** `web` never exits on its own: run it until the server announces itself. */ +function runServerCli(args: string[], home: string): Promise { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { + cwd: process.cwd(), + env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEBURN_CACHE_DIR: join(home, 'cache'), TZ: 'UTC' }, + }) + let stderr = '' + let stdout = '' + const stop = () => { child.kill('SIGKILL'); resolve(stderr) } + child.stderr.setEncoding('utf-8') + child.stdout.setEncoding('utf-8') + child.stderr.on('data', chunk => { stderr += chunk }) + child.stdout.on('data', chunk => { stdout += chunk; if (stdout.includes('Press Ctrl+C to stop')) stop() }) + child.on('error', reject) + child.on('close', () => resolve(stderr)) + }) +} + describe('--project / --exclude reach the reporting commands', () => { + it('compare scopes self-corrections to the filtered projects', async () => { + const home = await seedHomeWithApologies() + + const all = runCli(['compare', '--format', 'json', '--period', '30days'], home) + expect(all.status).toBe(0) + const allStats = JSON.parse(all.stdout) as Array<{ selfCorrections: number }> + expect(allStats).toHaveLength(1) + expect(allStats[0]!.selfCorrections).toBe(4) + + const filtered = runCli(['compare', '--format', 'json', '--period', '30days', '--project', '/Users/gone/app-kit'], home) + expect(filtered.status).toBe(0) + const filteredStats = JSON.parse(filtered.stdout) as Array<{ selfCorrections: number }> + expect(filteredStats[0]!.selfCorrections).toBe(2) + }) + it('sessions keeps the sibling an absolute --exclude does not name', async () => { const home = await seedHome() @@ -200,6 +260,16 @@ describe('a rooted pattern that names nothing is reported', () => { expect(typo.stderr).toContain(`no project in this period matches ${SIBLINGS[0]!.cwd}s`) }) + it('reports from web too, before the server starts', async () => { + const home = await seedHome() + + const typo = await runServerCli(['web', '--no-open', '--port', '0', '--period', '30days', '--project', '/Users/gone/apps'], home) + expect(typo).toContain('no project in this period matches /Users/gone/apps') + + const named = await runServerCli(['web', '--no-open', '--port', '0', '--period', '30days', '--project', '/Users/gone/app'], home) + expect(named).not.toContain('no project in this period matches') + }) + it('reports a quoted ~ pattern the shell never expanded', async () => { const home = await seedHome() // The README tells people to quote it, and a pattern field has no shell.