fix(cli): judge a pattern against the day cache, and never on screen

Three defects in the unmatched-pattern warning, all reported against a
path that is in fact correct.

`report`, `overview` and `status` judged a pattern against the live parse
plus the day cache, while `sessions`, `models`, `audit`, `compare`,
`optimize`, `yield` and `spend` judged it against the live parse alone.
On a project whose transcripts have expired, `overview --project <path>`
bills it while `sessions --project <path>` called the path wrong. The
check now falls back to the day cache, and only for what the live parse
missed, so the normal path reads no cache at all.

The warning also reached two places that must never see it. An Ink screen
owns the terminal, so it now honours the same `setInteractiveScanUI`
latch the parser checks before printing scan progress: `report --project
/typo` no longer writes over the dashboard. And `serve` routes every
stderr write into the progress-frame emitter, so `runStdioServe` calls
`suppressProjectFilterWarnings()` at startup rather than the module
reading argv, which a leading `--verbose` would have shifted.

SERVE_OPTIONS gains --project/--exclude for the seven commands that just
declared them, as the comment above it requires. Without that a filtered
request falls back to a cold spawn instead of the resident.
This commit is contained in:
Mathieu Stanowski 2026-09-11 17:29:55 +02:00
parent 740ec551e3
commit d8dfd72832
11 changed files with 199 additions and 52 deletions

View file

@ -4,6 +4,7 @@ import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'fs/promise
import { join } from 'path'
import { getCodeburnCacheDir } from './cache-dir.js'
import type { ProjectFilterTarget } from './parser.js'
import type { DateRange, ProjectSummary } from './types.js'
// Bumped to 27: claude-haiku-4.5 copilot store rows now price correctly (alias added) — #1093.
@ -1460,3 +1461,25 @@ export async function ensureCacheHydrated(
return c
})
}
/// The projects the day cache still knows about over a range, whose sources may
/// be long expired. A --project/--exclude pattern is only reported as naming
/// nothing once it has missed here too: the cache is what the totals are built
/// from, so a path it carries is a path the report bills, whatever the live
/// parse can still see. Read all-provider on purpose, like the day split itself,
/// so a provider-scoped command does not call a path wrong because the spend
/// sits under another tool.
export function cachedProjectIdentities(cache: DailyCache, startStr: string, endStr: string): ProjectFilterTarget[] {
const identities: ProjectFilterTarget[] = []
for (const day of cache.days) {
if (day.date < startStr || day.date > endStr || !day.projects) continue
for (const [name, stats] of Object.entries(day.projects)) {
identities.push({ project: name, projectPath: stats.path ?? '' })
}
}
return identities
}
export async function cachedProjectIdentitiesForRange(range: DateRange): Promise<ProjectFilterTarget[]> {
return cachedProjectIdentities(await loadDailyCache(), toDateString(range.start), toDateString(range.end))
}

View file

@ -3,6 +3,7 @@ import { Command, Option } from 'commander'
import { installMenubarApp } from './menubar-installer.js'
import { exportCsv, exportJson, type PeriodExport } from './export.js'
import { findUnpricedModels, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setFlatRateModels, setFlatRateRemoved, setProxyPaths, normalizeProxyPath, unpricedModelHint, isBuiltInFlatRateModel, isSameFlatRateModel, getProxyPathsConfigHash, getModelAliasesConfigHash, getPriceOverridesConfigHash, getLocalModelSavingsConfigHash, getFlatRateModelsConfigHash, getPricingGenerationKey } from './models.js'
import { cachedProjectIdentitiesForRange } from './daily-cache.js'
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI, computeCorpusFingerprint, isSessionHydrationComplete } from './parser.js'
import { allProviderNames, getAllProviders } from './providers/index.js'
@ -493,6 +494,7 @@ async function runJsonReport(period: Period, provider: string, project: string[]
await loadPricing()
const { range, label } = getDateRange(period)
const durable = await buildDurablePeriod({ range, label }, { provider, project, exclude })
await reportUnmatchedProjectPatterns(durable.knownProjects, project, exclude)
const report: ReturnType<typeof buildJsonReport> & { plan?: JsonPlanSummary; plans?: JsonPlanSummaryMap } = await attachPlanSummaries(buildJsonReport(durable.liveProjects, label, period, durable))
console.log(JSON.stringify(report, null, 2))
}
@ -817,6 +819,7 @@ program
const label = daySelection?.label ?? formatDateRangeLabel(opts.from, opts.to)
const periodKey = daySelection ? 'day' : 'custom'
const durable = await buildDurablePeriod({ range, label }, { provider: opts.provider, project: opts.project, exclude: opts.exclude })
await reportUnmatchedProjectPatterns(durable.knownProjects, opts.project, opts.exclude)
console.log(JSON.stringify(await attachPlanSummaries(buildJsonReport(durable.liveProjects, label, periodKey, durable)), null, 2))
} else {
await runJsonReport(period, opts.provider, opts.project, opts.exclude)
@ -996,6 +999,7 @@ program
? { range: customRange, label: formatDateRangeLabel(opts.from, opts.to) }
: getDateRange(period!)
const durable = await buildDurablePeriod({ range, label }, { provider: opts.provider, project: opts.project, exclude: opts.exclude })
await reportUnmatchedProjectPatterns(durable.knownProjects, opts.project, opts.exclude)
const projects = durable.liveProjects
const config = await readConfig()
const budget = isOverviewBudgetFilterActive(opts)
@ -1275,6 +1279,7 @@ program
const todayData = todayDurable.data
const todayProjects = todayDurable.liveProjects
const monthDurable = await buildDurablePeriod(getDateRange('month'), { provider: pf, project: opts.project, exclude: opts.exclude })
await reportUnmatchedProjectPatterns([...todayDurable.knownProjects, ...monthDurable.knownProjects], opts.project, opts.exclude)
const monthData = monthDurable.data
const monthProjects = monthDurable.liveProjects
const { code, rate } = getCurrency()
@ -1309,6 +1314,7 @@ program
const todayDurable = await buildDurablePeriod(getDateRange('today'), { provider: pf, project: opts.project, exclude: opts.exclude })
const monthDurable = await buildDurablePeriod(getDateRange('month'), { provider: pf, project: opts.project, exclude: opts.exclude })
await reportUnmatchedProjectPatterns([...todayDurable.knownProjects, ...monthDurable.knownProjects], opts.project, opts.exclude)
console.log(renderStatusBar([], {
today: { cost: todayDurable.data.cost, calls: todayDurable.data.calls },
month: { cost: monthDurable.data.cost, calls: monthDurable.data.calls },
@ -1366,14 +1372,12 @@ program
assertProvider(opts.provider, 'export')
await loadPricing()
const pf = opts.provider
let patternsChecked = false
// Both callers below pass a whole-period parse, so the first one is the
// widest list this command sees. The closure cannot await, so it only
// records; the report happens once the covered range is known.
let widestParse: ProjectSummary[] | null = null
const fp = (p: ProjectSummary[]) => {
// Both callers below pass a whole-period parse, so the first one is the
// widest list this command ever sees.
if (!patternsChecked) {
patternsChecked = true
reportUnmatchedProjectPatterns(p, opts.project, opts.exclude)
}
widestParse ??= p
return filterProjectsByName(p, opts.project, opts.exclude)
}
let customRange: DateRange | null = null
@ -1388,9 +1392,11 @@ program
let periods: PeriodExport[]
if (customRange) {
periods = [{ label: formatDateRangeLabel(opts.from, opts.to), projects: fp(await parseAllSessions(customRange, pf)) }]
await reportUnmatchedProjectPatterns(widestParse ?? [], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(customRange!))
clearSessionCache()
} else {
const thirtyDayProjects = fp(await parseAllSessions(getDateRange('30days').range, pf))
await reportUnmatchedProjectPatterns(widestParse ?? [], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(getDateRange('30days').range))
clearSessionCache()
periods = [
{ label: 'Today', projects: filterProjectsByDateRange(thirtyDayProjects, getDateRange('today').range) },
@ -2076,7 +2082,7 @@ program
({ range, label } = getDateRange(opts.period))
}
const parsed = await parseAllSessions(range, opts.provider)
reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
if (opts.apply) {
const { runOptimizeApply } = await import('./act/optimize-apply.js')
@ -2238,8 +2244,8 @@ program
if (opts.format === 'json') {
const { aggregateModelStats, buildCompareJson, findModelStat, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js')
const parsed = await parseAllSessions(range, opts.provider)
reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude)
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
const models = aggregateModelStats(projects)
const providers = await getAllProviders()
@ -2311,7 +2317,7 @@ program
}
const parsed = await parseAllSessions(range, opts.provider)
reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
const rows = await aggregateAudit(projects)
@ -2366,7 +2372,7 @@ program
}
const parsed = await parseAllSessions(range, opts.provider)
reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
const topN = typeof opts.top === 'number' && Number.isFinite(opts.top) ? opts.top : undefined
let rows = await aggregateModels(projects, {
@ -2462,7 +2468,7 @@ program
}
const parsed = await parseAllSessions(range, opts.provider)
reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
if (opts.byPr) {
const { rows: prRows, totals } = buildPrAttribution(projects)

View file

@ -1,26 +1,38 @@
import { type ProjectFilterTarget, unmatchedRootedPatterns } from './parser.js'
import { isInteractiveScanUI, type ProjectFilterTarget, unmatchedRootedPatterns } from './parser.js'
/// A rooted --project/--exclude selects one project or nothing, so a typo does
/// not fail: it reports a total over a set nobody asked for, which reads like a
/// correct answer. Judged against what the command parsed, before filtering.
/// correct answer. Called once per command, by the command itself, over every
/// project identity that command could have matched.
///
/// Never under `serve`: that path routes process.stderr.write into the
/// progress-frame emitter (runCaptured), so a warning would reach the desktop
/// app as scan progress, and `reported` would outlive the request that filled it.
const reported = new Set<string>()
/// Two callers must never see it. An Ink screen owns the terminal, so the same
/// `setInteractiveScanUI` latch the parser checks before printing scan progress
/// gates this too. And `serve` routes process.stderr.write into the progress-
/// frame emitter (runCaptured), so a warning would reach the desktop app as scan
/// progress: runStdioServe calls suppressProjectFilterWarnings() rather than
/// this module reading argv, which `codeburn --verbose serve` would shift.
let suppressed = false
export function reportUnmatchedProjectPatterns(
export function suppressProjectFilterWarnings(): void {
suppressed = true
}
export async function reportUnmatchedProjectPatterns(
projects: readonly ProjectFilterTarget[],
include?: readonly string[],
exclude?: readonly string[],
): void {
if (process.argv[2] === 'serve') return
// One command can filter several parses (export builds three periods out of
// one), and a missing path is one piece of news.
const patterns =[...(include ?? []), ...(exclude ?? [])].filter(pattern => !reported.has(pattern))
alsoKnown?: () => Promise<readonly ProjectFilterTarget[]>,
): Promise<void> {
if (suppressed || isInteractiveScanUI()) return
const patterns = [...(include ?? []), ...(exclude ?? [])]
if (patterns.length === 0) return
for (const pattern of unmatchedRootedPatterns(projects, patterns)) {
reported.add(pattern)
let unmatched = unmatchedRootedPatterns(projects, patterns)
// Only then, and only for what is still missing: a command whose population is
// the live parse alone would call a path wrong while the day cache bills it.
if (unmatched.length > 0 && alsoKnown) {
unmatched = unmatchedRootedPatterns(await alsoKnown(), unmatched)
}
for (const pattern of unmatched) {
process.stderr.write(`codeburn: no project in this period matches ${pattern} (an absolute path has to be a project's path, or a prefix of it on a segment boundary)\n`)
}
}

View file

@ -8,6 +8,7 @@ import { getDateRange } from './cli-date.js'
import { getConfigFilePath } from './config.js'
import type { ParseReuseValidation } from './parser.js'
import { SERVE_HYDRATION_ENV } from './usage-aggregator.js'
import { suppressProjectFilterWarnings } from './project-filter-warnings.js'
// ---------------------------------------------------------------------------
// codeburn serve --stdio: a resident query server for the desktop app.
@ -91,29 +92,36 @@ const SERVE_OPTIONS: Readonly<Record<string, Readonly<Record<string, ServeOption
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--task': 'value', '--by-task': 'flag', '--by-agent': 'flag',
'--top': 'value', '--min-cost': 'value', '--no-totals': 'flag', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
sessions: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value', '--by-pr': 'flag', '--no-pager': 'flag',
'--project': 'value', '--exclude': 'value',
},
compare: {
'-p': 'value', '--period': 'value', '--provider': 'value', '--format': 'value',
'--model-a': 'value', '--model-b': 'value',
'--project': 'value', '--exclude': 'value',
},
yield: {
'-p': 'value', '--period': 'value', '--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
spend: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
optimize: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value', '--json': 'flag',
'--project': 'value', '--exclude': 'value',
},
audit: {
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
'--provider': 'value', '--format': 'value',
'--project': 'value', '--exclude': 'value',
},
}
@ -382,6 +390,9 @@ async function startRootWatchers(): Promise<RootWatcherState | null> {
}
export async function runStdioServe(buildProgram: () => Command): Promise<void> {
// Every stderr write becomes a progress frame below, so the project-filter
// warning has to stay quiet for the life of this process.
suppressProjectFilterWarnings()
// Panel bursts (the app fetching every panel for one period) reuse a parse
// whose through-now range end differs by less than this window, instead of
// re-running the discovery sweep per panel. Serve-only: one-shot CLI runs

View file

@ -1,3 +1,4 @@
import { cachedProjectIdentitiesForRange } from './daily-cache.js'
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
import { filterProjectsByName, foldIdentifiedWindowsPath, parseAllSessions } from './parser.js'
import { toDateString } from './daily-cache.js'
@ -90,7 +91,7 @@ function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map<s
export async function computeSpendFlow(range: DateRange, provider: string, projectFilter?: string[], excludeFilter?: string[]): Promise<SpendFlow> {
const parsed = await parseAllSessions(range, provider)
reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter)
await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, projectFilter, excludeFilter)
const matrix = new Map<string, Map<string, number>>()
const projectTotals = new Map<string, number>()

View file

@ -3,10 +3,9 @@ import { CATEGORY_LABELS, type ProjectSummary, type SessionSummary, type TaskCat
import { isBehavioralCall } from './behavioral-weight.js'
import { type PeriodData, type ProviderCost, type BreakdownArrays, type MenubarPayload, type ClaudeConfigSelector, type HydrationState, buildMenubarPayload } from './menubar-json.js'
import { type SessionCountBasis } from './session-count-label.js'
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
type ProjectFilter = (entry: ProjectFilterTarget) => boolean
import { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, makeProjectFilter, type ProjectFilterTarget, sessionHydrationSnapshot } from './parser.js'
type ProjectFilter = (entry: ProjectFilterTarget) => boolean
import { findUnpricedModels, getFlatRateModelsConfigHash, getLocalModelSavingsConfigHash, getPriceOverridesConfigHash, getShortModelName, isExpectedFreeModel } from './models.js'
import { getAllProviders, safeDiscoverSessions } from './providers/index.js'
import { loadPlugins, pluginPayloadSections } from './plugins/loader.js'
@ -21,7 +20,7 @@ import { scanUserCorrections, medianTimeToFirstEditMs, aggregateFileChurn, compu
import { buildPrAttribution, aggregateByBranch } from './sessions-report.js'
import { scanAndDetect } from './optimize.js'
import { callBillableOutputTokens, sessionBillableOutputTokens, inferSessionProvider } from './session-output.js'
import { getDaysInRange, ensureCacheHydrated, loadDailyCache, emptyCache, mergeDayEntries, BACKFILL_DAYS, toDateString, type DailyCache, type DailyEntry, type ProjectDayStats, type ProviderDaySlice } from './daily-cache.js'
import { getDaysInRange, ensureCacheHydrated, loadDailyCache, cachedProjectIdentities, emptyCache, mergeDayEntries, BACKFILL_DAYS, toDateString, type DailyCache, type DailyEntry, type ProjectDayStats, type ProviderDaySlice } from './daily-cache.js'
import { buildGranularHistory } from './granular-history.js'
import { spendProjectIdentity } from './spend-flow.js'
@ -604,6 +603,12 @@ export type DurablePeriod = {
/// The exact provider-sliced, day-filtered day set behind `data`. Daily rows
/// rendered by report/overview come from here so they reconcile to `data`.
days: DailyEntry[]
/// Every project identity this period could have matched, filter not applied:
/// the live parse plus the carried days, whose sources are long gone. The
/// command layer resolves --project/--exclude against it, once, after the last
/// period it builds. Reporting from here instead judged `status` on its narrow
/// `today` pass and contradicted its own monthly total.
knownProjects: ProjectFilterTarget[]
/// Sum of `cost` on `carried` days included in the period (footnote source).
carriedCostUSD: number
/// Cost the active --project/--exclude filter had to set aside: cached days
@ -624,17 +629,6 @@ export type DurablePeriod = {
scanRange: DateRange
}
function cachedProjectIdentities(cache: DailyCache, startStr: string, endStr: string): ProjectFilterTarget[] {
const identities: ProjectFilterTarget[] = []
for (const day of cache.days) {
if (day.date < startStr || day.date > endStr || !day.projects) continue
for (const [name, stats] of Object.entries(day.projects)) {
identities.push({ project: name, projectPath: stats.path ?? '' })
}
}
return identities
}
export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: AggregateOpts = {}): Promise<DurablePeriod> {
const pf = opts.provider ?? 'all'
const daysSelection = opts.daysSelection ?? null
@ -777,13 +771,8 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
}
const carriedCostUSD = days.reduce((s, d) => s + (d.carried ? d.cost : 0), 0)
// Judged against everything this period could have matched, which on the
// durable path includes carried days whose sources are long gone.
reportUnmatchedProjectPatterns(
[...seenProjects, ...cachedProjectIdentities(cache, rangeStartStr, rangeEndStr)],
opts.project, opts.exclude,
)
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, cache, todayAllDays, scanRange }
const knownProjects = [...seenProjects, ...cachedProjectIdentities(cache, rangeStartStr, rangeEndStr)]
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, knownProjects, cache, todayAllDays, scanRange }
}
type PayloadProject = NonNullable<PeriodData['projects']>[number]

View file

@ -1,6 +1,7 @@
import { execFileSync } from 'child_process'
import { realpathSync } from 'fs'
import { resolve } from 'path'
import { cachedProjectIdentitiesForRange } from './daily-cache.js'
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
import { filterProjectsByName, parseAllSessions } from './parser.js'
import { isTrustedAbsoluteWorkingDirectory } from './path-privacy.js'
@ -463,7 +464,7 @@ function buildRepoGroups(
export async function computeYield(range: DateRange, cwd: string, provider: string = 'all', projectFilter?: string[], excludeFilter?: string[]): Promise<YieldSummary> {
const parsed = await parseAllSessions(range, provider)
reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter)
await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, projectFilter, excludeFilter)
const summary: YieldSummary = {