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

@ -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<string> {
return home
}
/** A project whose only sessions are older than today, so a today-scoped pass misses it. */
async function seedHomeWithOlderSessions(): Promise<string> {
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<string> {
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()

View file

@ -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'])

View file

@ -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, string> = {}): string {

View file

@ -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, string> = {}): string {