fix(cli): scope compare self-corrections to filtered projects, warn on web

compare --project filtered the model rows but scanned every session on the
machine for self-corrections. Scope the scan to the filtered projects'
sessions, and call reportUnmatchedProjectPatterns from web.
This commit is contained in:
iamtoruk 2026-09-12 03:49:43 -07:00
parent 7d0083961d
commit 6ee71e91c6
5 changed files with 101 additions and 11 deletions

View file

@ -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<string[]> {
return files
}
export async function scanSelfCorrections(projectDirs: string[]): Promise<Map<string, number>> {
/// 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<string> {
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<string>): Promise<Map<string, number>> {
const counts = new Map<string, number>()
const seen = new Set<string>()
@ -407,6 +416,7 @@ export async function scanSelfCorrections(projectDirs: string[]): Promise<Map<st
}
for (const file of allFiles) {
if (sessionIds && !sessionIds.has(basename(file, '.jsonl'))) continue
let raw: string
try {
raw = await readFile(file, 'utf8')

View file

@ -2,7 +2,7 @@ import React, { useState, useEffect, useRef } from 'react'
import { render, Box, Text, useInput, useApp, useStdout } from 'ink'
import type { ModelStats, ComparisonRow, CategoryComparison, WorkingStyleRow } from './compare-stats.js'
import { aggregateModelStats, computeComparison, computeCategoryComparison, computeWorkingStyle, findModelStat, scanSelfCorrections } from './compare-stats.js'
import { aggregateModelStats, computeComparison, computeCategoryComparison, computeWorkingStyle, findModelStat, projectSessionIds, scanSelfCorrections } from './compare-stats.js'
import { formatCost } from './format.js'
import { filterProjectsByName, parseAllSessions, setInteractiveScanUI } from './parser.js'
import { getAllProviders } from './providers/index.js'
@ -338,9 +338,12 @@ type CompareViewProps = {
// validated to exist in `projects`' aggregated stats by the caller). When
// set, comparison results load immediately instead of showing the picker.
presetModels?: [string, string]
// `projects` is already project-filtered: scope the self-correction scan to
// its sessions instead of every session on the machine.
scopeToProjects?: boolean
}
export function CompareView({ projects, onBack, presetModels }: CompareViewProps) {
export function CompareView({ projects, onBack, presetModels, scopeToProjects }: CompareViewProps) {
const { exit } = useApp()
const [phase, setPhase] = useState<'select' | 'loading' | 'results'>('select')
const [models, setModels] = useState<ModelStats[]>(() => 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(
<CompareView projects={projects} onBack={() => process.exit(0)} presetModels={presetModels} />
<CompareView projects={projects} onBack={() => process.exit(0)} presetModels={presetModels} scopeToProjects={hasProjectFilter} />
)
await waitUntilExit()
} finally {

View file

@ -2112,7 +2112,7 @@ export function InteractiveDashboard({ initialProjects, initialDailyHistoryProje
{isCustomRange && <CustomRangeBanner label={headerLabel} width={dashWidth} />}
{indexing && <IndexingBanner width={dashWidth} done={indexedFiles} total={indexPendingFiles} cold={indexCold} phase={indexPhase} visiblePeriod={period} />}
{view === 'compare'
? <CompareView projects={projects} onBack={() => setView('dashboard')} />
? <CompareView projects={projects} onBack={() => setView('dashboard')} scopeToProjects={(projectFilter?.length ?? 0) > 0 || (excludeFilter?.length ?? 0) > 0} />
: view === 'optimize' && optimizeResult
? <OptimizeView findings={optimizeResult.findings} costRate={optimizeResult.costRate} projects={projects} label={headerLabel} width={dashWidth} healthScore={optimizeResult.healthScore} healthGrade={optimizeResult.healthGrade} cursor={findingsCursor} appliedFixes={appliedFixes} />
: <DashboardContent projects={projects} period={period} columns={columns} maxContentWidth={maxContentWidth} activeProvider={activeProvider} budgets={projectBudgets} planUsages={planUsages} label={headerLabel} dayMode={isDayMode} dailyHistoryProjects={dailyHistoryProjects} dailyHistoryPageSize={dailyHistoryPageSize} scrollableDailyHistory={scrollableDailyHistory} dailyHistoryCursor={Math.min(dailyHistoryCursor, dailyHistoryMaxCursor)} durable={durable} />}

View file

@ -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
}