From 29fcb38976bac4aab516d21a084b88616877ae47 Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Wed, 9 Sep 2026 17:02:50 +0200 Subject: [PATCH 1/5] feat(cli): honor --project/--exclude on the remaining reporting commands The README says these flags work on every command. They did not: only report, overview, web, status, today, month and export declared them, so sessions, models, compare, audit, optimize, yield and spend either rejected the flag outright or silently reported the whole corpus. Each command already funnels through parseAllSessions, so the filter is applied at that single point with the shared filterProjectsByName. yield and spend parse inside computeYield / computeSpendFlow, which now take the patterns as optional arguments and default to filtering nothing. README now states the matching rule instead of claiming "all commands". --- README.md | 2 +- src/compare.tsx | 6 ++--- src/main.ts | 30 ++++++++++++++++++------- src/spend-flow.ts | 6 ++--- src/yield.ts | 6 ++--- tests/yield-overlap-attribution.test.ts | 1 + tests/yield-repo-grouping.test.ts | 1 + 7 files changed, 34 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 5f36e218..a49cff4c 100644 --- a/README.md +++ b/README.md @@ -653,7 +653,7 @@ codeburn month --project api --project web # include multiple projects codeburn export --project inventory # export only "inventory" project data ``` -Filter by provider, project name (case-insensitive substring), or exact date range. The `--project` and `--exclude` flags work on all commands and can be combined with `--provider`. +Filter by provider, project, or exact date range. The `--project` and `--exclude` flags work on every reporting command and can be combined with `--provider`. A plain word matches a project's name or path as a case-insensitive substring, so `--project my-company` also covers `my-company-kit` and its worktrees. An absolute path selects that one project and anything inside it, so `--exclude /Users/me/work/my-company` leaves the sibling `/Users/me/work/my-company-kit` alone. A leading `~` is the shell's to expand, so quote it and it is read as a plain word, not a path. ```bash codeburn report --from 2026-04-01 --to 2026-04-10 # explicit window diff --git a/src/compare.tsx b/src/compare.tsx index c090b641..6bc2bf26 100644 --- a/src/compare.tsx +++ b/src/compare.tsx @@ -4,7 +4,7 @@ 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 { formatCost } from './format.js' -import { parseAllSessions, setInteractiveScanUI } from './parser.js' +import { filterProjectsByName, parseAllSessions, setInteractiveScanUI } from './parser.js' import { getAllProviders } from './providers/index.js' import type { ProjectSummary, DateRange } from './types.js' import { patchStdoutForWindows } from './ink-win.js' @@ -509,7 +509,7 @@ export function CompareView({ projects, onBack, presetModels }: CompareViewProps ) } -export async function renderCompare(range: DateRange, provider: string, modelA?: string, modelB?: string): Promise { +export async function renderCompare(range: DateRange, provider: string, modelA?: string, modelB?: string, projectFilter?: string[], excludeFilter?: string[]): Promise { // Interactive Ink UI: suppress the CLI scan-progress line for the whole // lifetime so it can't print over the rendered comparison. Plain CLI // commands still show progress. @@ -521,7 +521,7 @@ export async function renderCompare(range: DateRange, provider: string, modelA?: } patchStdoutForWindows() - const projects = await parseAllSessions(range, provider) + const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) // --model-a/--model-b: resolve up front (by canonical id or display name, // same lookup the JSON path uses) so the TUI jumps straight to results diff --git a/src/main.ts b/src/main.ts index 7398914f..1f3131db 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2041,6 +2041,8 @@ program .option('--dry-run', 'With --apply: print the plan and exit without changing anything') .option('--only ', 'With --apply: restrict to a comma-separated list of finding ids') .option('--auto-revert', 'Undo applied fixes that measured no reduction (never CLAUDE.md rules)') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertProvider(opts.provider, 'optimize') const format = opts.json ? 'json' : opts.format @@ -2063,7 +2065,7 @@ program } else { ({ range, label } = getDateRange(opts.period)) } - const projects = await parseAllSessions(range, opts.provider) + const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) if (opts.apply) { const { runOptimizeApply } = await import('./act/optimize-apply.js') await runOptimizeApply(projects, range, { yes: opts.yes, dryRun: opts.dryRun, only: opts.only, provider: opts.provider }) @@ -2214,6 +2216,8 @@ program .option('--format ', 'Output format: tui, json', 'tui') .option('--model-a ', 'First model to compare') .option('--model-b ', 'Second model to compare') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertProvider(opts.provider, 'compare') assertFormat(opts.format, ['tui', 'json'], 'compare') @@ -2221,7 +2225,7 @@ program const { range, label } = getDateRange(opts.period) if (opts.format === 'json') { const { aggregateModelStats, buildCompareJson, findModelStat, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js') - const projects = await parseAllSessions(range, opts.provider) + const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) const models = aggregateModelStats(projects) const providers = await getAllProviders() @@ -2262,7 +2266,7 @@ program process.exit(1) } } - await renderCompare(range, opts.provider, opts.modelA, opts.modelB) + await renderCompare(range, opts.provider, opts.modelA, opts.modelB, opts.project, opts.exclude) }) program @@ -2273,6 +2277,8 @@ program .option('--to ', 'Custom range end (YYYY-MM-DD)') .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') .option('--format ', 'Output format: table, json', 'table') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertProvider(opts.provider, 'audit') const { aggregateAudit, renderAuditTable, renderAuditJson } = await import('./audit-report.js') @@ -2290,7 +2296,7 @@ program range = getDateRange(opts.period).range } - const projects = await parseAllSessions(range, opts.provider) + const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) const rows = await aggregateAudit(projects) const fmt = (opts.format ?? 'table').toLowerCase() @@ -2320,6 +2326,8 @@ program .option('--unpriced', 'Show only models with usage that currently price at $0') .option('--no-totals', 'Suppress the footer totals row') .option('--format ', 'Output format: table, markdown, json, csv', 'table') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertProvider(opts.provider, 'models') if (opts.byTask && opts.byAgent) { @@ -2341,7 +2349,7 @@ program range = getDateRange(opts.period).range } - const projects = await parseAllSessions(range, opts.provider) + const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) const topN = typeof opts.top === 'number' && Number.isFinite(opts.top) ? opts.top : undefined let rows = await aggregateModels(projects, { byTask: !!opts.byTask, @@ -2413,6 +2421,8 @@ program .option('--by-pr', 'Group spend by the pull requests each session referenced') .option('--by-work-unit', 'Group sessions into provider-recorded work units: one row per orchestration root with its delegated children folded beneath') .option('--no-pager', 'Print the complete table directly instead of opening the interactive browser') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertProvider(opts.provider, 'sessions') assertFormat(opts.format, ['table', 'json'], 'sessions') @@ -2433,7 +2443,7 @@ program range = getDateRange(opts.period).range } - const projects = await parseAllSessions(range, opts.provider) + const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) if (opts.byPr) { const { rows: prRows, totals } = buildPrAttribution(projects) if (opts.format === 'json') { @@ -2517,6 +2527,8 @@ program .option('-p, --period ', 'Analysis period: today, week, 30days, month, all, lifetime', 'week') .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') .option('--format ', 'Output format: text, json', 'text') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertFormat(opts.format, ['text', 'json'], 'yield') assertProvider(opts.provider, 'yield') @@ -2526,7 +2538,7 @@ program if (opts.format !== 'json') { console.log(`\n Analyzing yield for ${label}...\n`) } - const summary = await computeYield(range, process.cwd(), opts.provider) + const summary = await computeYield(range, process.cwd(), opts.provider, opts.project, opts.exclude) if (opts.format === 'json') { console.log(JSON.stringify(buildYieldJsonReport(summary, label, range), null, 2)) return @@ -2542,6 +2554,8 @@ program .option('--to ', 'Custom range end (YYYY-MM-DD)') .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') .option('--format ', 'Output format: flow-json', 'flow-json') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) .action(async (opts) => { assertFormat(opts.format, ['flow-json'], 'spend') assertProvider(opts.provider, 'spend') @@ -2561,7 +2575,7 @@ program range = getDateRange(opts.period).range } - console.log(JSON.stringify(await computeSpendFlow(range, opts.provider))) + console.log(JSON.stringify(await computeSpendFlow(range, opts.provider, opts.project, opts.exclude))) }) program diff --git a/src/spend-flow.ts b/src/spend-flow.ts index 7728a866..1cf7bc6d 100644 --- a/src/spend-flow.ts +++ b/src/spend-flow.ts @@ -1,4 +1,4 @@ -import { foldIdentifiedWindowsPath, parseAllSessions } from './parser.js' +import { filterProjectsByName, foldIdentifiedWindowsPath, parseAllSessions } from './parser.js' import { toDateString } from './daily-cache.js' import type { DateRange } from './types.js' @@ -87,8 +87,8 @@ function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map { - const projects = await parseAllSessions(range, provider) +export async function computeSpendFlow(range: DateRange, provider: string, projectFilter?: string[], excludeFilter?: string[]): Promise { + const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) const matrix = new Map>() const projectTotals = new Map() const modelTotals = new Map() diff --git a/src/yield.ts b/src/yield.ts index fb284442..1b7a51d2 100644 --- a/src/yield.ts +++ b/src/yield.ts @@ -1,7 +1,7 @@ import { execFileSync } from 'child_process' import { realpathSync } from 'fs' import { resolve } from 'path' -import { parseAllSessions } from './parser.js' +import { filterProjectsByName, parseAllSessions } from './parser.js' import { isTrustedAbsoluteWorkingDirectory } from './path-privacy.js' import type { DateRange, ProjectSummary, SessionSummary } from './types.js' @@ -460,8 +460,8 @@ function buildRepoGroups( return repoGroups } -export async function computeYield(range: DateRange, cwd: string, provider: string = 'all'): Promise { - const projects = await parseAllSessions(range, provider) +export async function computeYield(range: DateRange, cwd: string, provider: string = 'all', projectFilter?: string[], excludeFilter?: string[]): Promise { + const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) const summary: YieldSummary = { productive: { cost: 0, sessions: 0 }, diff --git a/tests/yield-overlap-attribution.test.ts b/tests/yield-overlap-attribution.test.ts index f1dc37df..484b6251 100644 --- a/tests/yield-overlap-attribution.test.ts +++ b/tests/yield-overlap-attribution.test.ts @@ -14,6 +14,7 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({ vi.mock('../src/parser.js', () => ({ parseAllSessions: parseAllSessionsMock, + filterProjectsByName: (projects: unknown[]) => projects, })) 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 e55f1f8c..69b1b1c4 100644 --- a/tests/yield-repo-grouping.test.ts +++ b/tests/yield-repo-grouping.test.ts @@ -15,6 +15,7 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({ vi.mock('../src/parser.js', () => ({ parseAllSessions: parseAllSessionsMock, + filterProjectsByName: (projects: unknown[]) => projects, })) function git(cwd: string, args: string[], env: Record = {}): string { From 172b8f4df69c7dfd87c4cc181c89e80a3fc4e1bc Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Wed, 9 Sep 2026 17:02:57 +0200 Subject: [PATCH 2/5] fix(cli): anchor an absolute-path project pattern to a segment boundary filterProjectsByName matched every pattern as a raw substring, so --exclude /a/my-company also removed the sibling /a/my-company-kit, and no pattern the caller could type expressed "this project and not its neighbours". A rooted pattern (POSIX, Windows drive, UNC) now keys through normalizeAbsProjectPathKey, the helper #1271 added for project identity, and matches the way isProxiedPath matches proxyPaths: equal to the project path, or a prefix of it on a path-segment boundary. Going through that helper keeps one identity rule in the parser: identified Windows paths casefold, POSIX case stays identity, and a Codex-style stripped absolute path ("root/vault") keys the same as the pattern "/root/vault" the user types. A pattern that is not rooted stays the loose substring people type on the command line, so --project my-company keeps covering my-company-kit and worktrees. The rule lives in one closure (makeProjectFilter) applied to the live parse and to the carry-forward day cache alike. The cache path had its own copy, lowercasing and substring-matching, so a filtered headline anchored today's live days while matching every cached day loosely: on a carried day split across /Users/gone/app ($30) and /Users/gone/app-kit ($70), --exclude /Users/gone/app returned 0 instead of 70, and --exclude /users/gone/app excluded both instead of neither. Both shapes are in tests/project-filter-durable-totals.test.ts, the suite that exists to pin that a filter selects the same projects whether it is resolved against a fresh parse or against the cache. The README gains the rules that were not written down: an absolute POSIX path is case-sensitive while a Windows drive or UNC path folds case, and a leading ~ is the shell's to expand. --- src/parser.ts | 34 +++++++++----- src/usage-aggregator.ts | 26 +++++------ tests/parser-filter.test.ts | 52 +++++++++++++++++++++ tests/project-filter-durable-totals.test.ts | 41 ++++++++++++++++ 4 files changed, 128 insertions(+), 25 deletions(-) diff --git a/src/parser.ts b/src/parser.ts index fc5471a0..27521e21 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -4413,6 +4413,26 @@ export function setCachePutMeta(meta: { startMs: number; endMs: number; sig: str putMeta = meta } +export function isRootedProjectPattern(pattern: string): boolean { + const raw = pattern.trim().replace(/\\/g, '/') + return raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) +} + +/// An absolute path names ONE project, so it anchors on a segment boundary (the +/// isProxiedPath rule): "/a/proj" takes "/a/proj/sub" but not "/a/proj-ui-kit". +/// Both sides key through normalizeAbsProjectPathKey (Windows casefolds, POSIX +/// does not, #1260), and rootedness alone picks the branch, so "/" names none. +export function matchesProjectPattern(project: { project: string; projectPath?: string }, pattern: string): boolean { + const projectPath = project.projectPath ?? '' + if (isRootedProjectPattern(pattern)) { + const anchor = normalizeAbsProjectPathKey(pattern) + const target = normalizeAbsProjectPathKey(projectPath) + return anchor !== null && target !== null && (target === anchor || target.startsWith(anchor + '/')) + } + const needle = pattern.toLowerCase() + return project.project.toLowerCase().includes(needle) || projectPath.toLowerCase().includes(needle) +} + export function filterProjectsByName( projects: ProjectSummary[], include?: string[], @@ -4420,20 +4440,10 @@ export function filterProjectsByName( ): ProjectSummary[] { let result = projects if (include && include.length > 0) { - const patterns = include.map(s => s.toLowerCase()) - result = result.filter(p => { - const name = p.project.toLowerCase() - const path = p.projectPath.toLowerCase() - return patterns.some(pat => name.includes(pat) || path.includes(pat)) - }) + result = result.filter(p => include.some(pattern => matchesProjectPattern(p, pattern))) } if (exclude && exclude.length > 0) { - const patterns = exclude.map(s => s.toLowerCase()) - result = result.filter(p => { - const name = p.project.toLowerCase() - const path = p.projectPath.toLowerCase() - return !patterns.some(pat => name.includes(pat) || path.includes(pat)) - }) + result = result.filter(p => !exclude.some(pattern => matchesProjectPattern(p, pattern))) } return result } diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index c3e80d69..68c93470 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -3,7 +3,7 @@ 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 { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, sessionHydrationSnapshot } from './parser.js' +import { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, matchesProjectPattern, sessionHydrationSnapshot } from './parser.js' import { findUnpricedModels, getFlatRateModelsConfigHash, getLocalModelSavingsConfigHash, getPriceOverridesConfigHash, getShortModelName, isExpectedFreeModel } from './models.js' import { getAllProviders, safeDiscoverSessions } from './providers/index.js' import { loadPlugins, pluginPayloadSections } from './plugins/loader.js' @@ -376,17 +376,17 @@ export function overlayProviderDaySlices( return mergeDayEntries(freshSliced, sliced, false, undefined, true) } -/// Does a cached day's project entry pass the active name filters? Mirrors -/// parser.filterProjectsByName exactly — case-insensitive substring match -/// against the project name OR its filesystem path, include first then exclude — -/// so a filter selects the same projects whether it is resolved against a fresh -/// parse or against the day cache. Patterns arrive pre-lowercased. `path` is +/// Does a cached day's project entry pass the active name filters? Delegates to +/// the one rule filterProjectsByName applies, so a filter selects the same +/// projects whether it is resolved against a fresh parse or against the day +/// cache — a second copy here put anchored live days and substring-matched +/// cached days inside one headline. Patterns arrive raw: the rule casefolds +/// identified Windows paths itself and keeps POSIX case as identity. `path` is /// absent on entries whose sessions were gone before it could be recorded; the /// name is then all there is to match on, as it is for the display layers. function dayProjectMatches(name: string, path: string | undefined, include: string[], exclude: string[]): boolean { - const n = name.toLowerCase() - const p = (path ?? '').toLowerCase() - const hit = (pattern: string): boolean => n.includes(pattern) || (p !== '' && p.includes(pattern)) + const entry = { project: name, projectPath: path ?? '' } + const hit = (pattern: string): boolean => matchesProjectPattern(entry, pattern) if (include.length > 0 && !include.some(hit)) return false if (exclude.length > 0 && exclude.some(hit)) return false return true @@ -532,8 +532,8 @@ export function buildDurableOverviewFromNormalizedIndex( opts: AggregateOpts = {}, ): IndexedDurableOverview { const pf = opts.provider ?? 'all' - const include = (opts.project ?? []).map(value => value.toLowerCase()) - const exclude = (opts.exclude ?? []).map(value => value.toLowerCase()) + const include = opts.project ?? [] + const exclude = opts.exclude ?? [] const hasProjectFilter = include.length > 0 || exclude.length > 0 const filteredProjects = filterProjectsByName(normalizedProjects, opts.project ?? [], opts.exclude ?? []) const scanProjects = filterProjectsByDateRange(filteredProjects, periodInfo.range) @@ -704,8 +704,8 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate // name-filtered above (`fp`), but the historical remainder comes straight out // of the day cache, so without this slice a --project/--exclude headline // counted every expired-source day whole while the detail panels did not. - const projectInclude = (opts.project ?? []).map(s => s.toLowerCase()) - const projectExclude = (opts.exclude ?? []).map(s => s.toLowerCase()) + const projectInclude = opts.project ?? [] + const projectExclude = opts.exclude ?? [] const hasProjectFilter = projectInclude.length > 0 || projectExclude.length > 0 // What a filtered total cannot claim, and therefore has to leave out: a cached // day with no project split at all, or — with a provider filter also active, diff --git a/tests/parser-filter.test.ts b/tests/parser-filter.test.ts index 4c347220..829522d4 100644 --- a/tests/parser-filter.test.ts +++ b/tests/parser-filter.test.ts @@ -52,6 +52,58 @@ describe('filterProjectsByName', () => { expect(result.map(p => p.project).sort()).toEqual(['AgentSeal', 'dashboard']) }) + it('an absolute-path pattern does not swallow a sibling sharing its prefix', () => { + const siblings = [ + makeProject('my-company', '/Users/alice/work/my-company'), + makeProject('my-company-kit', '/Users/alice/work/my-company-kit'), + makeProject('client', '/Users/alice/work/my-company/packages/client'), + ] + const result = filterProjectsByName(siblings, undefined, ['/Users/alice/work/my-company']) + expect(result.map(p => p.project)).toEqual(['my-company-kit']) + }) + + it('anchors an absolute-path include the same way', () => { + const siblings = [ + makeProject('my-company', '/Users/alice/work/my-company'), + makeProject('my-company-kit', '/Users/alice/work/my-company-kit'), + ] + expect(filterProjectsByName(siblings, ['/Users/alice/work/my-company']).map(p => p.project)).toEqual(['my-company']) + }) + + it('keeps a plain word loose, so it still spans siblings and worktrees', () => { + const siblings = [ + makeProject('my-company', '/Users/alice/work/my-company'), + makeProject('my-company-kit', '/Users/alice/work/my-company-kit'), + makeProject('other', '/Users/alice/work/other'), + ] + expect(filterProjectsByName(siblings, ['my-company']).map(p => p.project)).toEqual(['my-company', 'my-company-kit']) + }) + + it('is trailing-slash and backslash tolerant on an absolute pattern', () => { + const win = [makeProject('app', 'C:\\Users\\alice\\app'), makeProject('app-two', 'C:\\Users\\alice\\app-two')] + expect(filterProjectsByName(win, undefined, ['C:/Users/alice/app/']).map(p => p.project)).toEqual(['app-two']) + }) + + it('folds case on an identified Windows pattern and keeps POSIX case identity', () => { + const posix = [makeProject('Vault', '/a/Vault'), makeProject('vault', '/a/vault')] + expect(filterProjectsByName(posix, ['/a/Vault']).map(p => p.project)).toEqual(['Vault']) + const win = [makeProject('vault', 'C:\\Work\\Vault')] + expect(filterProjectsByName(win, ['c:/work/vault']).map(p => p.project)).toEqual(['vault']) + const unc = [makeProject('vault', '\\\\Server\\Share\\Vault')] + expect(filterProjectsByName(unc, ['//server/share']).map(p => p.project)).toEqual(['vault']) + }) + + it('anchors a POSIX pattern against a Codex-style stripped absolute path', () => { + const codex = [makeProject('vault', 'root/vault'), makeProject('vault-ui', 'root/vault-ui')] + expect(filterProjectsByName(codex, undefined, ['/root/vault']).map(p => p.project)).toEqual(['vault-ui']) + }) + + it('names no project for a rooted pattern that keys to nothing', () => { + expect(filterProjectsByName(projects, ['/'])).toEqual([]) + expect(filterProjectsByName(projects, undefined, ['/'])).toEqual(projects) + expect(filterProjectsByName(projects, undefined, ['//'])).toEqual(projects) + }) + it('exclude matches path substring', () => { const result = filterProjectsByName(projects, undefined, ['/tmp']) expect(result.map(p => p.project)).not.toContain('sandbox') diff --git a/tests/project-filter-durable-totals.test.ts b/tests/project-filter-durable-totals.test.ts index 9d8cffdb..f405afdd 100644 --- a/tests/project-filter-durable-totals.test.ts +++ b/tests/project-filter-durable-totals.test.ts @@ -112,6 +112,18 @@ function carriedDayTwoProviders(date: string): DailyEntry { return day } +/** The same carried day, with the two projects as path siblings sharing a prefix. */ +function carriedDaySiblingProjects(date: string): DailyEntry { + const day = carriedDayWithProjects(date) + const projects = { + app: { cost: KEEP.cost, calls: KEEP.calls, savingsUSD: 0, sessions: KEEP.sessions, path: '/Users/gone/app' }, + 'app-kit': { cost: DROP.cost, calls: DROP.calls, savingsUSD: 0, sessions: DROP.sessions, path: '/Users/gone/app-kit' }, + } + day.projects = projects + day.providers['claude']!.projects = projects + return day +} + async function seedCache(...days: DailyEntry[]): Promise { const cache: DailyCache = { version: DAILY_CACHE_VERSION, @@ -235,6 +247,35 @@ describe('durable headline honours --project / --exclude on carried days', () => expect(durable.data.cost).toBeCloseTo(live.cost + KEEP.cost, 6) }) + // A cached day and a live day must answer the same pattern the same way. The + // two below are the shapes where a substring copy of the rule diverges from + // the anchored one, inside a single headline total. + it('anchors an absolute pattern on a carried day, so the sibling survives', async () => { + await seedCache(carriedDaySiblingProjects(daysAgoStr(10))) + await seedLiveTodaySession() + const range = coveringRange() + + const live = await liveOnly(range, [], ['/Users/gone/app']) + clearSessionCache() + const durable = await buildDurablePeriod({ range, label: 'p' }, { provider: 'all', exclude: ['/Users/gone/app'] }) + + expect(durable.data.cost).toBeCloseTo(live.cost + DROP.cost, 6) + expect(durable.data.calls).toBe(live.calls + DROP.calls) + }) + + it('keeps POSIX case identity on a carried day, so a wrong-case path selects nothing', async () => { + await seedCache(carriedDaySiblingProjects(daysAgoStr(10))) + await seedLiveTodaySession() + const range = coveringRange() + + const live = await liveOnly(range, [], ['/users/gone/app']) + clearSessionCache() + const durable = await buildDurablePeriod({ range, label: 'p' }, { provider: 'all', exclude: ['/users/gone/app'] }) + + expect(durable.data.cost).toBeCloseTo(live.cost + DAY_COST, 6) + expect(durable.data.calls).toBe(live.calls + DAY_CALLS) + }) + it('keeps a project whose name is a prototype member (constructor) in the sliced total', async () => { // A project directory can legitimately be named "constructor"/"valueOf"/etc. // The day cache must carry it as an own key: if the load path drops it, the From 648fa40ebd33d18a7bd281514fd6185ba051e814 Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Fri, 11 Sep 2026 16:05:08 +0200 Subject: [PATCH 3/5] feat(cli): warn when a rooted --project/--exclude names no project A rooted pattern selects one project or nothing, so a typo does not fail: it reports a total over a set nobody asked for, which reads exactly like a correct answer. The run now says so on stderr, and the exit status is untouched. unmatchedRootedPatterns() tries each pattern on its own against the UNFILTERED project list, which is what keeps it honest. Judged inside filterProjectsByName instead, an earlier --project would mask a later one selecting the same project, and an --exclude would be tested against what --project had already removed. The message is period-scoped, since a range-scoped parse is what was checked, and the durable path passes the carried days' project identities alongside the live parse, so a pattern naming only an expired-source project stays silent. Nothing is reported under `serve`. That path routes process.stderr.write into the progress-frame emitter (runCaptured), so a warning would reach the desktop app as a scan-progress line. The tests spawn the real CLI over a seeded corpus of two path siblings: sessions for the commands that filter at the call site, spend and yield for the two that take the patterns as arguments and filter inside, so dropping the argument anywhere fails the suite. They also pin the shapes that must stay silent: a pattern that selects something, a loose word, a second --project overlapping the first, and an --exclude naming a project --project had already removed. --- README.md | 2 +- src/main.ts | 32 ++++- src/parser.ts | 70 +++++++--- src/project-filter-warnings.ts | 26 ++++ src/spend-flow.ts | 5 +- src/usage-aggregator.ts | 75 ++++++----- src/yield.ts | 5 +- tests/cli-project-filter-commands.test.ts | 148 ++++++++++++++++++++++ 8 files changed, 303 insertions(+), 60 deletions(-) create mode 100644 src/project-filter-warnings.ts create mode 100644 tests/cli-project-filter-commands.test.ts diff --git a/README.md b/README.md index a49cff4c..fded41d4 100644 --- a/README.md +++ b/README.md @@ -653,7 +653,7 @@ codeburn month --project api --project web # include multiple projects codeburn export --project inventory # export only "inventory" project data ``` -Filter by provider, project, or exact date range. The `--project` and `--exclude` flags work on every reporting command and can be combined with `--provider`. A plain word matches a project's name or path as a case-insensitive substring, so `--project my-company` also covers `my-company-kit` and its worktrees. An absolute path selects that one project and anything inside it, so `--exclude /Users/me/work/my-company` leaves the sibling `/Users/me/work/my-company-kit` alone. A leading `~` is the shell's to expand, so quote it and it is read as a plain word, not a path. +Filter by provider, project, or exact date range. The `--project` and `--exclude` flags work on every reporting command and can be combined with `--provider`. A plain word matches a project's name or path as a case-insensitive substring, so `--project my-company` also covers `my-company-kit` and its worktrees. An absolute path selects that one project and anything inside it, so `--exclude /Users/me/work/my-company` leaves the sibling `/Users/me/work/my-company-kit` alone. A leading `~` is the shell's to expand, so quote it and it is read as a plain word, not a path. An absolute POSIX path is case-sensitive, the same rule that decides project identity everywhere else (`/Users/me/Vault` and `/Users/me/vault` are two projects); a Windows drive or UNC path folds case. An absolute path that matches no project in the period you asked for is reported on stderr, since it would otherwise leave a total that looks right. ```bash codeburn report --from 2026-04-01 --to 2026-04-10 # explicit window diff --git a/src/main.ts b/src/main.ts index 1f3131db..34f4951f 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 { reportUnmatchedProjectPatterns } from './project-filter-warnings.js' import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI, computeCorpusFingerprint, isSessionHydrationComplete } from './parser.js' import { allProviderNames, getAllProviders } from './providers/index.js' import { getProvider } from './providers/index.js' @@ -1365,7 +1366,16 @@ program assertProvider(opts.provider, 'export') await loadPricing() const pf = opts.provider - const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project, opts.exclude) + let patternsChecked = false + 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) + } + return filterProjectsByName(p, opts.project, opts.exclude) + } let customRange: DateRange | null = null try { customRange = parseDateRangeFlags(opts.from, opts.to) @@ -2065,7 +2075,9 @@ program } else { ({ range, label } = getDateRange(opts.period)) } - const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) + const parsed = await parseAllSessions(range, opts.provider) + reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude) + const projects = filterProjectsByName(parsed, opts.project, opts.exclude) if (opts.apply) { const { runOptimizeApply } = await import('./act/optimize-apply.js') await runOptimizeApply(projects, range, { yes: opts.yes, dryRun: opts.dryRun, only: opts.only, provider: opts.provider }) @@ -2225,7 +2237,9 @@ program const { range, label } = getDateRange(opts.period) if (opts.format === 'json') { const { aggregateModelStats, buildCompareJson, findModelStat, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js') - const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) + const parsed = await parseAllSessions(range, opts.provider) + reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude) + const projects = filterProjectsByName(parsed, opts.project, opts.exclude) const models = aggregateModelStats(projects) const providers = await getAllProviders() @@ -2296,7 +2310,9 @@ program range = getDateRange(opts.period).range } - const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) + const parsed = await parseAllSessions(range, opts.provider) + reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude) + const projects = filterProjectsByName(parsed, opts.project, opts.exclude) const rows = await aggregateAudit(projects) const fmt = (opts.format ?? 'table').toLowerCase() @@ -2349,7 +2365,9 @@ program range = getDateRange(opts.period).range } - const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) + const parsed = await parseAllSessions(range, opts.provider) + reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude) + 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, { byTask: !!opts.byTask, @@ -2443,7 +2461,9 @@ program range = getDateRange(opts.period).range } - const projects = filterProjectsByName(await parseAllSessions(range, opts.provider), opts.project, opts.exclude) + const parsed = await parseAllSessions(range, opts.provider) + reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude) + const projects = filterProjectsByName(parsed, opts.project, opts.exclude) if (opts.byPr) { const { rows: prRows, totals } = buildPrAttribution(projects) if (opts.format === 'json') { diff --git a/src/parser.ts b/src/parser.ts index 27521e21..b19b8ed1 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -4418,19 +4418,62 @@ export function isRootedProjectPattern(pattern: string): boolean { return raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) } +/// A pattern is normalized once and matched many times: the day cache runs the +/// filter for every project of every day, and again per provider slice. +type CompiledPattern = { rooted: true; anchor: string | null } | { rooted: false; needle: string } + +export type ProjectFilterTarget = { project: string; projectPath?: string } + +function compile(patterns: readonly string[]): CompiledPattern[] { + return patterns.map(pattern => isRootedProjectPattern(pattern) + ? { rooted: true as const, anchor: normalizeAbsProjectPathKey(pattern) } + : { rooted: false as const, needle: pattern.toLowerCase() }) +} + /// An absolute path names ONE project, so it anchors on a segment boundary (the /// isProxiedPath rule): "/a/proj" takes "/a/proj/sub" but not "/a/proj-ui-kit". /// Both sides key through normalizeAbsProjectPathKey (Windows casefolds, POSIX /// does not, #1260), and rootedness alone picks the branch, so "/" names none. -export function matchesProjectPattern(project: { project: string; projectPath?: string }, pattern: string): boolean { - const projectPath = project.projectPath ?? '' - if (isRootedProjectPattern(pattern)) { - const anchor = normalizeAbsProjectPathKey(pattern) - const target = normalizeAbsProjectPathKey(projectPath) - return anchor !== null && target !== null && (target === anchor || target.startsWith(anchor + '/')) +function hit(entry: ProjectFilterTarget, pattern: CompiledPattern, key: string | null): boolean { + if (pattern.rooted) { + const anchor = pattern.anchor + return anchor !== null && key !== null && (key === anchor || key.startsWith(anchor + '/')) } - const needle = pattern.toLowerCase() - return project.project.toLowerCase().includes(needle) || projectPath.toLowerCase().includes(needle) + return entry.project.toLowerCase().includes(pattern.needle) + || (entry.projectPath ?? '').toLowerCase().includes(pattern.needle) +} + +/// The filter as one closure: patterns are compiled here, so the caller can +/// hold it across a loop, and include-then-exclude is composed in one place for +/// the live parse and the day cache alike. +export function makeProjectFilter( + include?: readonly string[], + exclude?: readonly string[], +): (entry: ProjectFilterTarget) => boolean { + const inc = compile(include ?? []) + const exc = compile(exclude ?? []) + return entry => { + const key = normalizeAbsProjectPathKey(entry.projectPath ?? '') + if (inc.length > 0 && !inc.some(pattern => hit(entry, pattern, key))) return false + if (exc.length > 0 && exc.some(pattern => hit(entry, pattern, key))) return false + return true + } +} + +export function matchesProjectPattern(project: ProjectFilterTarget, pattern: string): boolean { + return makeProjectFilter([pattern])(project) +} + +/// Which rooted patterns name no project here? Each is tried on its own against +/// the UNFILTERED list: judged inside filterProjectsByName instead, an earlier +/// --project would mask a later one that selects the same project, and an +/// --exclude would be tested against what --project had already removed. +export function unmatchedRootedPatterns(projects: readonly ProjectFilterTarget[], patterns: readonly string[]): string[] { + return patterns.filter(pattern => { + if (!isRootedProjectPattern(pattern)) return false + const matches = makeProjectFilter([pattern]) + return !projects.some(entry => matches(entry)) + }) } export function filterProjectsByName( @@ -4438,14 +4481,9 @@ export function filterProjectsByName( include?: string[], exclude?: string[], ): ProjectSummary[] { - let result = projects - if (include && include.length > 0) { - result = result.filter(p => include.some(pattern => matchesProjectPattern(p, pattern))) - } - if (exclude && exclude.length > 0) { - result = result.filter(p => !exclude.some(pattern => matchesProjectPattern(p, pattern))) - } - return result + if ((include?.length ?? 0) === 0 && (exclude?.length ?? 0) === 0) return projects + const matches = makeProjectFilter(include, exclude) + return projects.filter(matches) } function turnDayString(turn: ClassifiedTurn): string | null { diff --git a/src/project-filter-warnings.ts b/src/project-filter-warnings.ts new file mode 100644 index 00000000..d76c4e07 --- /dev/null +++ b/src/project-filter-warnings.ts @@ -0,0 +1,26 @@ +import { 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. +/// +/// 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() + +export 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)) + if (patterns.length === 0) return + for (const pattern of unmatchedRootedPatterns(projects, patterns)) { + reported.add(pattern) + 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/spend-flow.ts b/src/spend-flow.ts index 1cf7bc6d..cd155943 100644 --- a/src/spend-flow.ts +++ b/src/spend-flow.ts @@ -1,3 +1,4 @@ +import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js' import { filterProjectsByName, foldIdentifiedWindowsPath, parseAllSessions } from './parser.js' import { toDateString } from './daily-cache.js' import type { DateRange } from './types.js' @@ -88,7 +89,9 @@ function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map { - const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) + const parsed = await parseAllSessions(range, provider) + reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter) + const projects = filterProjectsByName(parsed, projectFilter, excludeFilter) const matrix = new Map>() const projectTotals = new Map() const modelTotals = new Map() diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index 68c93470..f8575f71 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -3,7 +3,10 @@ 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 { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, matchesProjectPattern, sessionHydrationSnapshot } from './parser.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' import { findUnpricedModels, getFlatRateModelsConfigHash, getLocalModelSavingsConfigHash, getPriceOverridesConfigHash, getShortModelName, isExpectedFreeModel } from './models.js' import { getAllProviders, safeDiscoverSessions } from './providers/index.js' import { loadPlugins, pluginPayloadSections } from './plugins/loader.js' @@ -376,33 +379,16 @@ export function overlayProviderDaySlices( return mergeDayEntries(freshSliced, sliced, false, undefined, true) } -/// Does a cached day's project entry pass the active name filters? Delegates to -/// the one rule filterProjectsByName applies, so a filter selects the same -/// projects whether it is resolved against a fresh parse or against the day -/// cache — a second copy here put anchored live days and substring-matched -/// cached days inside one headline. Patterns arrive raw: the rule casefolds -/// identified Windows paths itself and keeps POSIX case as identity. `path` is -/// absent on entries whose sessions were gone before it could be recorded; the -/// name is then all there is to match on, as it is for the display layers. -function dayProjectMatches(name: string, path: string | undefined, include: string[], exclude: string[]): boolean { - const entry = { project: name, projectPath: path ?? '' } - const hit = (pattern: string): boolean => matchesProjectPattern(entry, pattern) - if (include.length > 0 && !include.some(hit)) return false - if (exclude.length > 0 && exclude.some(hit)) return false - return true -} - -/// Sum the per-project day stats that pass the filters. `defineProperty` so a -/// project directory named "__proto__" stays an own key instead of mutating the -/// prototype link (same reason day-aggregator does it when writing them). +/// `path` is absent on entries whose sessions were gone before it could be +/// recorded; the name is then all there is to match on, as it is for the +/// display layers. function sumMatchingProjects( projects: Record, - include: string[], - exclude: string[], + matches: ProjectFilter, ): { cost: number; calls: number; savingsUSD: number; sessions: number; projects: Record; matched: number } { const out = { cost: 0, calls: 0, savingsUSD: 0, sessions: 0, projects: {} as Record, matched: 0 } for (const [name, p] of Object.entries(projects)) { - if (!dayProjectMatches(name, p.path, include, exclude)) continue + if (!matches({ project: name, projectPath: p.path ?? '' })) continue out.cost += p.cost out.calls += p.calls out.savingsUSD += p.savingsUSD ?? 0 @@ -432,7 +418,7 @@ function sumMatchingProjects( /// any project, so it contributes nothing to a project-filtered total and its /// cost is surfaced as `unattributedCostUSD` instead of being silently folded in /// (understating with a stated figure beats overstating with excluded spend). -function sliceDayToProject(day: DailyEntry, include: string[], exclude: string[]): DailyEntry { +function sliceDayToProject(day: DailyEntry, matches: ProjectFilter): DailyEntry { const zeroDay = (): DailyEntry => ({ date: day.date, cost: 0, savingsUSD: 0, calls: 0, sessions: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, @@ -440,7 +426,7 @@ function sliceDayToProject(day: DailyEntry, include: string[], exclude: string[] ...(day.carried ? { carried: true as const } : {}), }) if (!day.projects) return zeroDay() - const totals = sumMatchingProjects(day.projects, include, exclude) + const totals = sumMatchingProjects(day.projects, matches) if (totals.matched === 0) return zeroDay() // Provider slices carry their own per-project split, so `--provider X` on top @@ -450,7 +436,7 @@ function sliceDayToProject(day: DailyEntry, include: string[], exclude: string[] const providers: Record = {} for (const [name, slice] of Object.entries(day.providers)) { if (!slice.projects) continue - const sliced = sumMatchingProjects(slice.projects, include, exclude) + const sliced = sumMatchingProjects(slice.projects, matches) if (sliced.matched === 0) continue Object.defineProperty(providers, name, { value: { cost: sliced.cost, calls: sliced.calls, savingsUSD: sliced.savingsUSD, sessions: sliced.sessions, projects: sliced.projects }, @@ -532,9 +518,8 @@ export function buildDurableOverviewFromNormalizedIndex( opts: AggregateOpts = {}, ): IndexedDurableOverview { const pf = opts.provider ?? 'all' - const include = opts.project ?? [] - const exclude = opts.exclude ?? [] - const hasProjectFilter = include.length > 0 || exclude.length > 0 + const hasProjectFilter = (opts.project?.length ?? 0) > 0 || (opts.exclude?.length ?? 0) > 0 + const matchesFilter = makeProjectFilter(opts.project, opts.exclude) const filteredProjects = filterProjectsByName(normalizedProjects, opts.project ?? [], opts.exclude ?? []) const scanProjects = filterProjectsByDateRange(filteredProjects, periodInfo.range) const now = new Date() @@ -543,7 +528,7 @@ export function buildDurableOverviewFromNormalizedIndex( const todayDays = normalizedDays .filter(day => day.date === todayStr) const historicalSlice = hasProjectFilter - ? (day: DailyEntry): DailyEntry => sliceDayToProject(day, include, exclude) + ? (day: DailyEntry): DailyEntry => sliceDayToProject(day, matchesFilter) : undefined const cachedAllDays = unionDaysForPeriod(cache, todayDays, periodInfo, null, historicalSlice) const cachedDates = new Set(cache.days.map(day => day.date)) @@ -639,10 +624,25 @@ 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 - const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project ?? [], opts.exclude ?? []) + const seenProjects: ProjectFilterTarget[] = [] + const fp = (p: ProjectSummary[]) => { + seenProjects.push(...p) + return filterProjectsByName(p, opts.project ?? [], opts.exclude ?? []) + } const now = new Date() const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()) @@ -704,9 +704,8 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate // name-filtered above (`fp`), but the historical remainder comes straight out // of the day cache, so without this slice a --project/--exclude headline // counted every expired-source day whole while the detail panels did not. - const projectInclude = opts.project ?? [] - const projectExclude = opts.exclude ?? [] - const hasProjectFilter = projectInclude.length > 0 || projectExclude.length > 0 + const hasProjectFilter = (opts.project?.length ?? 0) > 0 || (opts.exclude?.length ?? 0) > 0 + const matchesFilter = makeProjectFilter(opts.project, opts.exclude) // What a filtered total cannot claim, and therefore has to leave out: a cached // day with no project split at all, or — with a provider filter also active, // since the headline then reads that provider's slice — a slice carried from a @@ -722,7 +721,7 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate const sliceHistorical = hasProjectFilter ? (day: DailyEntry): DailyEntry => { unattributedCostUSD += unattributableCost(day) - return sliceDayToProject(day, projectInclude, projectExclude) + return sliceDayToProject(day, matchesFilter) } : undefined @@ -778,6 +777,12 @@ 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 } } diff --git a/src/yield.ts b/src/yield.ts index 1b7a51d2..a239ee29 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 { reportUnmatchedProjectPatterns } from './project-filter-warnings.js' import { filterProjectsByName, parseAllSessions } from './parser.js' import { isTrustedAbsoluteWorkingDirectory } from './path-privacy.js' import type { DateRange, ProjectSummary, SessionSummary } from './types.js' @@ -461,7 +462,9 @@ function buildRepoGroups( } export async function computeYield(range: DateRange, cwd: string, provider: string = 'all', projectFilter?: string[], excludeFilter?: string[]): Promise { - const projects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter) + const parsed = await parseAllSessions(range, provider) + reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter) + const projects = filterProjectsByName(parsed, projectFilter, excludeFilter) const summary: YieldSummary = { productive: { cost: 0, sessions: 0 }, diff --git a/tests/cli-project-filter-commands.test.ts b/tests/cli-project-filter-commands.test.ts new file mode 100644 index 00000000..7d8533e8 --- /dev/null +++ b/tests/cli-project-filter-commands.test.ts @@ -0,0 +1,148 @@ +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 { afterEach, describe, expect, it, vi } from 'vitest' + +// Each test spawns `tsx src/cli.ts`, which re-transpiles the CLI per spawn. +vi.setConfig({ testTimeout: 30_000 }) + +// Unit tests of filterProjectsByName cannot tell whether a command passes its +// patterns down. These run the real binary over two path siblings, so dropping +// the argument anywhere here fails the suite. +const SIBLINGS = [ + { dir: '-Users-gone-app', cwd: '/Users/gone/app', session: 's-app' }, + { dir: '-Users-gone-app-kit', cwd: '/Users/gone/app-kit', session: 's-kit' }, +] + +let homes: string[] = [] + +afterEach(async () => { + while (homes.length > 0) { + const home = homes.pop() + if (home) await rm(home, { recursive: true, force: true }) + } +}) + +async function seedHome(): Promise { + const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-')) + homes.push(home) + const now = Date.now() + const line = (session: string, cwd: string, index: number): string => JSON.stringify({ + type: 'assistant', + timestamp: new Date(now - (30 - index) * 60_000).toISOString(), + sessionId: session, + cwd, + message: { + type: 'message', role: 'assistant', model: 'claude-3-5-sonnet-20241022', id: `${session}-m${index}`, + content: [], + usage: { input_tokens: 90000, output_tokens: 12000, cache_creation_input_tokens: 0, cache_read_input_tokens: 300000 }, + }, + }) + for (const project of SIBLINGS) { + const dir = join(home, '.claude', 'projects', project.dir) + await mkdir(dir, { recursive: true }) + const lines = [1, 2].map(index => line(project.session, project.cwd, index)) + 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(), + env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), TZ: 'UTC' }, + encoding: 'utf-8', + timeout: 30_000, + }) +} + +describe('--project / --exclude reach the reporting commands', () => { + it('sessions keeps the sibling an absolute --exclude does not name', async () => { + const home = await seedHome() + + const all = runCli(['sessions', '--format', 'json', '--period', '30days'], home) + expect(all.stderr).toBe('') + expect(JSON.parse(all.stdout).map((s: { project: string }) => s.project).sort()) + .toEqual(['-Users-gone-app', '-Users-gone-app-kit']) + + const filtered = runCli(['sessions', '--format', 'json', '--period', '30days', '--exclude', '/Users/gone/app'], home) + expect(filtered.status).toBe(0) + expect(JSON.parse(filtered.stdout).map((s: { project: string }) => s.project)) + .toEqual(['-Users-gone-app-kit']) + }) + + it('spend carries the patterns into computeSpendFlow', async () => { + const home = await seedHome() + + const all = runCli(['spend', '--format', 'flow-json', '--period', '30days'], home) + expect(all.status).toBe(0) + expect(JSON.parse(all.stdout).projects).toHaveLength(2) + + const filtered = runCli(['spend', '--format', 'flow-json', '--period', '30days', '--exclude', '/Users/gone/app'], home) + expect(filtered.status).toBe(0) + const projects = JSON.parse(filtered.stdout).projects as Array<{ label: string }> + expect(projects.map(p => p.label)).toEqual(['app-kit']) + }) + + it('yield carries the patterns into computeYield', async () => { + const home = await seedHome() + + const all = runCli(['yield', '--format', 'json', '--period', '30days'], home) + expect(all.status).toBe(0) + expect(JSON.parse(all.stdout).details).toHaveLength(2) + + const filtered = runCli(['yield', '--format', 'json', '--period', '30days', '--exclude', '/Users/gone/app'], home) + expect(filtered.status).toBe(0) + const report = JSON.parse(filtered.stdout) + expect(report.details.map((d: { project: string }) => d.project)).toEqual(['-Users-gone-app-kit']) + type YieldDetail = { project: string; costUSD: number } + const kept = (JSON.parse(all.stdout).details as YieldDetail[]).find(d => d.project === '-Users-gone-app-kit')! + const total = (report.details as YieldDetail[]).reduce((sum, d) => sum + d.costUSD, 0) + expect(total).toBeCloseTo(kept.costUSD, 6) + }) +}) + +describe('a rooted pattern that names nothing is reported', () => { + it('warns on stderr rather than reporting a total over a set nobody asked for', async () => { + const home = await seedHome() + const result = runCli(['sessions', '--format', 'json', '--period', '30days', '--exclude', '/Users/gone/apps'], home) + + expect(result.stderr).toContain('no project in this period matches /Users/gone/apps') + // The run still reports: the warning is advisory, not a failure. + expect(result.status).toBe(0) + expect(JSON.parse(result.stdout)).toHaveLength(2) + }) + + it('stays quiet when the pattern selects something, and for a loose word', async () => { + const home = await seedHome() + + const rooted = runCli(['sessions', '--format', 'json', '--period', '30days', '--exclude', '/Users/gone/app'], home) + expect(rooted.stderr).not.toContain('no project in this period matches') + + // A plain word is a substring by design, so it is never a typo signal. + const loose = runCli(['sessions', '--format', 'json', '--period', '30days', '--exclude', 'nothing-like-this'], home) + expect(loose.stderr).not.toContain('no project in this period matches') + }) + + it('judges each pattern on its own, against the list before any filtering', async () => { + const home = await seedHome() + + // The second --project selects a project the first one also covers. Judged + // inside the filter, `some()` would stop at the first and call it unmatched. + const overlapping = runCli([ + 'sessions', '--format', 'json', '--period', '30days', + '--project', '/Users/gone/app', '--project', '/Users/gone/app/sub', + ], home) + expect(overlapping.stderr).toContain('/Users/gone/app/sub') + expect(overlapping.stderr).not.toContain('matches /Users/gone/app (') + + // And an --exclude must not be judged against what --project already removed. + const both = runCli([ + 'sessions', '--format', 'json', '--period', '30days', + '--project', '/Users/gone/app', '--exclude', '/Users/gone/app-kit', + ], home) + expect(both.stderr).toBe('') + }) +}) From 740ec551e3a0c3e7ecd91c8a438dcd777cb3e8d8 Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Fri, 11 Sep 2026 17:29:55 +0200 Subject: [PATCH 4/5] fix(cli): expand a leading ~ in a project pattern A quoted '~/work/app' reaches the CLI unexpanded, and a pattern typed into a field has no shell behind it at all. It was neither rooted nor a substring of any stored path, so it selected nothing and said nothing. The README made it worse by telling people to quote it. A leading ~ is now expanded against the home directory and anchored like any absolute path, so the quoted form selects the same project as the one the shell would have expanded, and a wrong one is reported. Two more from reading the hot path: the compiled filter only pays for the project path key when some pattern is rooted and can read it, which the day cache runs per project, per day, per provider slice; and unmatchedRootedPatterns now calls matchesProjectPattern instead of open-coding it. --- README.md | 2 +- src/parser.ts | 27 ++++++++++++++++++++++----- tests/parser-filter.test.ts | 10 ++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fded41d4..b0625931 100644 --- a/README.md +++ b/README.md @@ -653,7 +653,7 @@ codeburn month --project api --project web # include multiple projects codeburn export --project inventory # export only "inventory" project data ``` -Filter by provider, project, or exact date range. The `--project` and `--exclude` flags work on every reporting command and can be combined with `--provider`. A plain word matches a project's name or path as a case-insensitive substring, so `--project my-company` also covers `my-company-kit` and its worktrees. An absolute path selects that one project and anything inside it, so `--exclude /Users/me/work/my-company` leaves the sibling `/Users/me/work/my-company-kit` alone. A leading `~` is the shell's to expand, so quote it and it is read as a plain word, not a path. An absolute POSIX path is case-sensitive, the same rule that decides project identity everywhere else (`/Users/me/Vault` and `/Users/me/vault` are two projects); a Windows drive or UNC path folds case. An absolute path that matches no project in the period you asked for is reported on stderr, since it would otherwise leave a total that looks right. +Filter by provider, project, or exact date range. The `--project` and `--exclude` flags work on every reporting command and can be combined with `--provider`. A plain word matches a project's name or path as a case-insensitive substring, so `--project my-company` also covers `my-company-kit` and its worktrees. An absolute path selects that one project and anything inside it, so `--exclude /Users/me/work/my-company` leaves the sibling `/Users/me/work/my-company-kit` alone. A leading `~` is expanded against your home directory, so a quoted `'~/work/my-company'` selects the same project as the path the shell would have expanded. An absolute POSIX path is case-sensitive, the same rule that decides project identity everywhere else (`/Users/me/Vault` and `/Users/me/vault` are two projects); a Windows drive or UNC path folds case. An absolute path that matches no project in the period you asked for is reported on stderr, since it would otherwise leave a total that looks right. ```bash codeburn report --from 2026-04-01 --to 2026-04-10 # explicit window diff --git a/src/parser.ts b/src/parser.ts index b19b8ed1..1869765c 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1,3 +1,4 @@ +import { homedir } from 'node:os' import { existsSync } from 'fs' import { lstat, readFile, readdir, stat } from 'fs/promises' import { createHash } from 'crypto' @@ -3170,6 +3171,10 @@ export function setInteractiveScanUI(active = true): void { interactiveScanUI = active } +export function isInteractiveScanUI(): boolean { + return interactiveScanUI +} + // Machine-readable scan progress for the desktop app's first-run splash. Plain // CLI/terminal usage is untouched: emission is gated on CODEBURN_PROGRESS=1, // which only the app's cold-start warmup spawn sets. Each event is one @@ -4415,7 +4420,16 @@ export function setCachePutMeta(meta: { startMs: number; endMs: number; sig: str export function isRootedProjectPattern(pattern: string): boolean { const raw = pattern.trim().replace(/\\/g, '/') - return raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) + return raw.startsWith('/') || raw === '~' || raw.startsWith('~/') || /^[a-zA-Z]:\//.test(raw) +} + +/// A quoted "~/proj" reaches us unexpanded, and so does one typed into a field +/// with no shell behind it. Left as a loose word it would match nothing and say +/// nothing, since no stored path contains a tilde. +function expandTilde(pattern: string): string { + const raw = pattern.trim().replace(/\\/g, '/') + if (raw !== '~' && !raw.startsWith('~/')) return raw + return homedir().replace(/\\/g, '/') + raw.slice(1) } /// A pattern is normalized once and matched many times: the day cache runs the @@ -4426,7 +4440,7 @@ export type ProjectFilterTarget = { project: string; projectPath?: string } function compile(patterns: readonly string[]): CompiledPattern[] { return patterns.map(pattern => isRootedProjectPattern(pattern) - ? { rooted: true as const, anchor: normalizeAbsProjectPathKey(pattern) } + ? { rooted: true as const, anchor: normalizeAbsProjectPathKey(expandTilde(pattern)) } : { rooted: false as const, needle: pattern.toLowerCase() }) } @@ -4452,8 +4466,12 @@ export function makeProjectFilter( ): (entry: ProjectFilterTarget) => boolean { const inc = compile(include ?? []) const exc = compile(exclude ?? []) + // The key costs a trim, a global replace and three regex passes. The day cache + // runs this per project, per day, per provider slice, so it is only paid when + // some pattern is rooted and can actually read it. + const needsKey = inc.some(p => p.rooted) || exc.some(p => p.rooted) return entry => { - const key = normalizeAbsProjectPathKey(entry.projectPath ?? '') + const key = needsKey ? normalizeAbsProjectPathKey(entry.projectPath ?? '') : null if (inc.length > 0 && !inc.some(pattern => hit(entry, pattern, key))) return false if (exc.length > 0 && exc.some(pattern => hit(entry, pattern, key))) return false return true @@ -4471,8 +4489,7 @@ export function matchesProjectPattern(project: ProjectFilterTarget, pattern: str export function unmatchedRootedPatterns(projects: readonly ProjectFilterTarget[], patterns: readonly string[]): string[] { return patterns.filter(pattern => { if (!isRootedProjectPattern(pattern)) return false - const matches = makeProjectFilter([pattern]) - return !projects.some(entry => matches(entry)) + return !projects.some(entry => matchesProjectPattern(entry, pattern)) }) } diff --git a/tests/parser-filter.test.ts b/tests/parser-filter.test.ts index 829522d4..49c5a742 100644 --- a/tests/parser-filter.test.ts +++ b/tests/parser-filter.test.ts @@ -1,3 +1,5 @@ +import { homedir } from 'node:os' + import { describe, it, expect } from 'vitest' import { filterProjectsByName } from '../src/parser.js' @@ -104,6 +106,14 @@ describe('filterProjectsByName', () => { expect(filterProjectsByName(projects, undefined, ['//'])).toEqual(projects) }) + it('expands a leading ~ the shell did not, and anchors it', () => { + const home = homedir().replace(/\\/g, '/') + const mine = [makeProject('app', `${home}/work/app`), makeProject('app-kit', `${home}/work/app-kit`)] + expect(filterProjectsByName(mine, ['~/work/app']).map(p => p.project)).toEqual(['app']) + expect(filterProjectsByName(mine, undefined, ['~/work/app']).map(p => p.project)).toEqual(['app-kit']) + expect(filterProjectsByName(mine, ['~/nowhere'])).toEqual([]) + }) + it('exclude matches path substring', () => { const result = filterProjectsByName(projects, undefined, ['/tmp']) expect(result.map(p => p.project)).not.toContain('sandbox') From d8dfd728323e5579ddcd31b9d75ca77323cfe36f Mon Sep 17 00:00:00 2001 From: Mathieu Stanowski Date: Fri, 11 Sep 2026 17:29:55 +0200 Subject: [PATCH 5/5] 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 {