From d8dfd728323e5579ddcd31b9d75ca77323cfe36f Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Fri, 11 Sep 2026 17:29:55 +0200 Subject: [PATCH] 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 ` bills it while `sessions --project ` 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. --- src/daily-cache.ts | 23 +++++++ src/main.ts | 32 +++++---- src/project-filter-warnings.ts | 40 +++++++---- src/serve.ts | 11 +++ src/spend-flow.ts | 3 +- src/usage-aggregator.ts | 33 +++------ src/yield.ts | 3 +- tests/cli-project-filter-commands.test.ts | 83 ++++++++++++++++++++++- tests/serve-stdio.test.ts | 19 ++++++ tests/yield-overlap-attribution.test.ts | 2 + tests/yield-repo-grouping.test.ts | 2 + 11 files changed, 199 insertions(+), 52 deletions(-) diff --git a/src/daily-cache.ts b/src/daily-cache.ts index c2119a92..f2476cd0 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -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 { + return cachedProjectIdentities(await loadDailyCache(), toDateString(range.start), toDateString(range.end)) +} diff --git a/src/main.ts b/src/main.ts index 34f4951f..b31116a1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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 & { 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) diff --git a/src/project-filter-warnings.ts b/src/project-filter-warnings.ts index d76c4e07..2cb5b698 100644 --- a/src/project-filter-warnings.ts +++ b/src/project-filter-warnings.ts @@ -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() +/// 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, +): Promise { + 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`) } } diff --git a/src/serve.ts b/src/serve.ts index 8ea073ca..0c284fa2 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -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 { } export async function runStdioServe(buildProgram: () => Command): Promise { + // 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 diff --git a/src/spend-flow.ts b/src/spend-flow.ts index cd155943..4c533e49 100644 --- a/src/spend-flow.ts +++ b/src/spend-flow.ts @@ -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 { 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>() const projectTotals = new Map() diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index f8575f71..8bc03721 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -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 { 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[number] diff --git a/src/yield.ts b/src/yield.ts index a239ee29..32a1c303 100644 --- a/src/yield.ts +++ b/src/yield.ts @@ -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 { 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 = { diff --git a/tests/cli-project-filter-commands.test.ts b/tests/cli-project-filter-commands.test.ts index 7d8533e8..abf345c7 100644 --- a/tests/cli-project-filter-commands.test.ts +++ b/tests/cli-project-filter-commands.test.ts @@ -5,6 +5,8 @@ import { spawnSync } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' +import { DAILY_CACHE_VERSION, currentTzKey } from '../src/daily-cache.js' + // Each test spawns `tsx src/cli.ts`, which re-transpiles the CLI per spawn. vi.setConfig({ testTimeout: 30_000 }) @@ -49,10 +51,52 @@ async function seedHome(): Promise { return home } +/** A project whose only sessions are older than today, so a today-scoped pass misses it. */ +async function seedHomeWithOlderSessions(): Promise { + const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-')) + homes.push(home) + const dir = join(home, '.claude', 'projects', SIBLINGS[0]!.dir) + await mkdir(dir, { recursive: true }) + const fiveDaysAgo = Date.now() - 5 * 24 * 60 * 60 * 1000 + const lines = [1, 2].map(index => JSON.stringify({ + type: 'assistant', + timestamp: new Date(fiveDaysAgo + index * 60_000).toISOString(), + sessionId: 's-old', + cwd: SIBLINGS[0]!.cwd, + message: { + type: 'message', role: 'assistant', model: 'claude-3-5-sonnet-20241022', id: `old-m${index}`, + content: [], + usage: { input_tokens: 90000, output_tokens: 12000, cache_creation_input_tokens: 0, cache_read_input_tokens: 300000 }, + }, + })) + await writeFile(join(dir, 's-old.jsonl'), lines.join('\n') + '\n', 'utf-8') + return home +} + +/** A carried day the cache still bills, whose session files are long gone. */ +async function seedDayCacheOnly(): Promise { + const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-')) + homes.push(home) + await mkdir(join(home, '.claude', 'projects'), { recursive: true }) + await mkdir(join(home, 'cache'), { recursive: true }) + const date = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10) + const projects = { app: { cost: 30, calls: 10, savingsUSD: 0, sessions: 1, path: SIBLINGS[0]!.cwd } } + const day = { + date, cost: 30, savingsUSD: 0, calls: 10, sessions: 1, + inputTokens: 100, outputTokens: 50, cacheReadTokens: 0, cacheWriteTokens: 0, + editTurns: 1, oneShotTurns: 0, models: {}, categories: {}, providers: {}, projects, carried: true, + } + await writeFile(join(home, 'cache', `daily-cache.v${DAILY_CACHE_VERSION}.json`), JSON.stringify({ + version: DAILY_CACHE_VERSION, savingsConfigHash: '', tzKey: currentTzKey(), + lastComputedDate: date, days: [day], complete: true, + }), 'utf-8') + return home +} + function runCli(args: string[], home: string) { return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { cwd: process.cwd(), - env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), TZ: 'UTC' }, + env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEBURN_CACHE_DIR: join(home, 'cache'), TZ: 'UTC' }, encoding: 'utf-8', timeout: 30_000, }) @@ -126,6 +170,43 @@ describe('a rooted pattern that names nothing is reported', () => { expect(loose.stderr).not.toContain('no project in this period matches') }) + it('does not contradict a total the same command prints', async () => { + const home = await seedHomeWithOlderSessions() + // `status` builds today and then month. Judged on the today pass alone, the + // pattern looks unmatched while the month total beside it is that project's. + const result = runCli(['status', '--format', 'json', '--project', '/Users/gone/app'], home) + + expect(result.status).toBe(0) + expect(JSON.parse(result.stdout).month.cost).toBeGreaterThan(0) + expect(result.stderr).toBe('') + + const typo = runCli(['status', '--format', 'json', '--project', '/Users/gone/apps'], home) + expect(typo.stderr).toContain('no project in this period matches /Users/gone/apps') + }) + + it('stays quiet for a project only the day cache still bills', async () => { + const home = await seedDayCacheOnly() + // The sources expired, so the live parse cannot see this project; the cache + // can, and it is what the totals are built from. Every command has to agree. + const durable = runCli(['overview', '--period', '30days', '--project', SIBLINGS[0]!.cwd, '--no-color'], home) + expect(durable.stderr).toBe('') + expect(durable.stdout).toContain('30.00') + + const live = runCli(['sessions', '--format', 'json', '--period', '30days', '--project', SIBLINGS[0]!.cwd], home) + expect(live.status).toBe(0) + expect(live.stderr).toBe('') + + const typo = runCli(['sessions', '--format', 'json', '--period', '30days', '--project', `${SIBLINGS[0]!.cwd}s`], home) + expect(typo.stderr).toContain(`no project in this period matches ${SIBLINGS[0]!.cwd}s`) + }) + + 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. + const result = runCli(['sessions', '--format', 'json', '--period', '30days', '--project', '~/nowhere'], home) + expect(result.stderr).toContain('no project in this period matches ~/nowhere') + }) + it('judges each pattern on its own, against the list before any filtering', async () => { const home = await seedHome() diff --git a/tests/serve-stdio.test.ts b/tests/serve-stdio.test.ts index 4d7dfd05..1ea2d415 100644 --- a/tests/serve-stdio.test.ts +++ b/tests/serve-stdio.test.ts @@ -178,6 +178,25 @@ describe('codeburn serve --stdio', () => { } }, 60_000) + // SERVE_OPTIONS mirrors the Commander definitions: a command that declares + // --project/--exclude but is missing them here falls back to a cold spawn. + it('routes --project/--exclude for every command that declares them', async () => { + const commands: Array<[number, string[]]> = [ + [330, ['status', '--format', 'json', '--period', 'today', '--project', '/nope']], + [331, ['overview', '--period', 'today', '--no-color', '--exclude', '/nope']], + [332, ['models', '--format', 'json', '--period', 'today', '--project', '/nope']], + [333, ['sessions', '--format', 'json', '--period', 'today', '--exclude', '/nope']], + [334, ['compare', '--format', 'json', '--period', 'today', '--project', '/nope']], + [335, ['yield', '--format', 'json', '--period', 'today', '--exclude', '/nope']], + [336, ['spend', '--format', 'flow-json', '--period', 'today', '--project', '/nope']], + [337, ['optimize', '--format', 'json', '--period', 'today', '--exclude', '/nope']], + [338, ['audit', '--format', 'json', '--period', 'today', '--project', '/nope']], + ] + for (const [id, args] of commands) { + expect(await request(id, args)).toMatchObject({ ok: true }) + } + }, 60_000) + it('survives a malformed request line and keeps serving', async () => { sendRaw('this is not json') const res = await request(6, ['status', '--format', 'menubar-json', '--period', 'today']) diff --git a/tests/yield-overlap-attribution.test.ts b/tests/yield-overlap-attribution.test.ts index 484b6251..8f0506ba 100644 --- a/tests/yield-overlap-attribution.test.ts +++ b/tests/yield-overlap-attribution.test.ts @@ -15,6 +15,8 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({ vi.mock('../src/parser.js', () => ({ parseAllSessions: parseAllSessionsMock, filterProjectsByName: (projects: unknown[]) => projects, + unmatchedRootedPatterns: () => [], + isInteractiveScanUI: () => false, })) function git(cwd: string, args: string[], env: Record = {}): string { diff --git a/tests/yield-repo-grouping.test.ts b/tests/yield-repo-grouping.test.ts index 69b1b1c4..6cd21c45 100644 --- a/tests/yield-repo-grouping.test.ts +++ b/tests/yield-repo-grouping.test.ts @@ -16,6 +16,8 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({ vi.mock('../src/parser.js', () => ({ parseAllSessions: parseAllSessionsMock, filterProjectsByName: (projects: unknown[]) => projects, + unmatchedRootedPatterns: () => [], + isInteractiveScanUI: () => false, })) function git(cwd: string, args: string[], env: Record = {}): string {