Merge pull request #1285 from mathieustan/feat/cli-project-filter
Some checks are pending
CI / semgrep (push) Waiting to run
Tests / test (22) (push) Waiting to run
Tests / test (22.13.0) (push) Waiting to run
Tests / test-platforms (macos-latest) (push) Waiting to run
Tests / test-platforms (windows-latest) (push) Waiting to run
Tests / desktop (push) Waiting to run

fix(cli): honor --project/--exclude on every reporting command, and anchor absolute-path patterns
This commit is contained in:
ozymandiashh 2026-09-11 20:15:20 +03:00 • committed by GitHub
commit effa656ef2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 610 additions and 74 deletions

View file

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

View file

@ -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<void> {
export async function renderCompare(range: DateRange, provider: string, modelA?: string, modelB?: string, projectFilter?: string[], excludeFilter?: string[]): Promise<void> {
// 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

View file

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

View file

@ -3,6 +3,8 @@ 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'
import { getProvider } from './providers/index.js'
@ -492,6 +494,7 @@ async function runJsonReport(period: Period, provider: string, project: string[]
await loadPricing()
const { range, label } = getDateRange(period)
const durable = await buildDurablePeriod({ range, label }, { provider, project, exclude })
await reportUnmatchedProjectPatterns(durable.knownProjects, project, exclude)
const report: ReturnType<typeof buildJsonReport> & { plan?: JsonPlanSummary; plans?: JsonPlanSummaryMap } = await attachPlanSummaries(buildJsonReport(durable.liveProjects, label, period, durable))
console.log(JSON.stringify(report, null, 2))
}
@ -816,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)
@ -995,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)
@ -1274,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()
@ -1308,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 },
@ -1365,7 +1372,14 @@ program
assertProvider(opts.provider, 'export')
await loadPricing()
const pf = opts.provider
const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project, opts.exclude)
// 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[]) => {
widestParse ??= p
return filterProjectsByName(p, opts.project, opts.exclude)
}
let customRange: DateRange | null = null
try {
customRange = parseDateRangeFlags(opts.from, opts.to)
@ -1378,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) },
@ -2041,6 +2057,8 @@ program
.option('--dry-run', 'With --apply: print the plan and exit without changing anything')
.option('--only <ids>', '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 <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'optimize')
const format = opts.json ? 'json' : opts.format
@ -2063,7 +2081,9 @@ program
} else {
({ range, label } = getDateRange(opts.period))
}
const projects = await parseAllSessions(range, opts.provider)
const parsed = await parseAllSessions(range, opts.provider)
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')
await runOptimizeApply(projects, range, { yes: opts.yes, dryRun: opts.dryRun, only: opts.only, provider: opts.provider })
@ -2214,6 +2234,8 @@ program
.option('--format <format>', 'Output format: tui, json', 'tui')
.option('--model-a <model>', 'First model to compare')
.option('--model-b <model>', 'Second model to compare')
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'compare')
assertFormat(opts.format, ['tui', 'json'], 'compare')
@ -2221,7 +2243,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 = await parseAllSessions(range, opts.provider)
const parsed = await parseAllSessions(range, opts.provider)
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()
@ -2262,7 +2286,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 +2297,8 @@ program
.option('--to <date>', 'Custom range end (YYYY-MM-DD)')
.option('--provider <provider>', 'Filter by provider (e.g. claude, codex, cursor)', 'all')
.option('--format <format>', 'Output format: table, json', 'table')
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'audit')
const { aggregateAudit, renderAuditTable, renderAuditJson } = await import('./audit-report.js')
@ -2290,7 +2316,9 @@ program
range = getDateRange(opts.period).range
}
const projects = await parseAllSessions(range, opts.provider)
const parsed = await parseAllSessions(range, opts.provider)
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
const rows = await aggregateAudit(projects)
const fmt = (opts.format ?? 'table').toLowerCase()
@ -2320,6 +2348,8 @@ program
.option('--unpriced', 'Show only models with usage that currently price at $0')
.option('--no-totals', 'Suppress the footer totals row')
.option('--format <format>', 'Output format: table, markdown, json, csv', 'table')
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'models')
if (opts.byTask && opts.byAgent) {
@ -2341,7 +2371,9 @@ program
range = getDateRange(opts.period).range
}
const projects = await parseAllSessions(range, opts.provider)
const parsed = await parseAllSessions(range, opts.provider)
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, {
byTask: !!opts.byTask,
@ -2413,6 +2445,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 <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertProvider(opts.provider, 'sessions')
assertFormat(opts.format, ['table', 'json'], 'sessions')
@ -2433,7 +2467,9 @@ program
range = getDateRange(opts.period).range
}
const projects = await parseAllSessions(range, opts.provider)
const parsed = await parseAllSessions(range, opts.provider)
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)
if (opts.format === 'json') {
@ -2517,6 +2553,8 @@ program
.option('-p, --period <period>', 'Analysis period: today, week, 30days, month, all, lifetime', 'week')
.option('--provider <provider>', 'Filter by provider (e.g. claude, codex, cursor)', 'all')
.option('--format <format>', 'Output format: text, json', 'text')
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertFormat(opts.format, ['text', 'json'], 'yield')
assertProvider(opts.provider, 'yield')
@ -2526,7 +2564,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 +2580,8 @@ program
.option('--to <date>', 'Custom range end (YYYY-MM-DD)')
.option('--provider <provider>', 'Filter by provider (e.g. claude, codex, cursor)', 'all')
.option('--format <format>', 'Output format: flow-json', 'flow-json')
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
.action(async (opts) => {
assertFormat(opts.format, ['flow-json'], 'spend')
assertProvider(opts.provider, 'spend')
@ -2561,7 +2601,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

View file

@ -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
@ -4413,29 +4418,89 @@ 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('/') || 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
/// 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(expandTilde(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.
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 + '/'))
}
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 ?? [])
// 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 = 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
}
}
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
return !projects.some(entry => matchesProjectPattern(entry, pattern))
})
}
export function filterProjectsByName(
projects: ProjectSummary[],
include?: string[],
exclude?: string[],
): 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))
})
}
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))
})
}
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 {

View file

@ -0,0 +1,38 @@
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. Called once per command, by the command itself, over every
/// project identity that command could have matched.
///
/// 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 suppressProjectFilterWarnings(): void {
suppressed = true
}
export async function reportUnmatchedProjectPatterns(
projects: readonly ProjectFilterTarget[],
include?: readonly string[],
exclude?: readonly string[],
alsoKnown?: () => Promise<readonly ProjectFilterTarget[]>,
): Promise<void> {
if (suppressed || isInteractiveScanUI()) return
const patterns = [...(include ?? []), ...(exclude ?? [])]
if (patterns.length === 0) return
let unmatched = unmatchedRootedPatterns(projects, patterns)
// Only then, and only for what is still missing: a command whose population is
// the live parse alone would call a path wrong while the day cache bills it.
if (unmatched.length > 0 && alsoKnown) {
unmatched = unmatchedRootedPatterns(await alsoKnown(), unmatched)
}
for (const pattern of unmatched) {
process.stderr.write(`codeburn: no project in this period matches ${pattern} (an absolute path has to be a project's path, or a prefix of it on a segment boundary)\n`)
}
}

View file

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

View file

@ -1,4 +1,6 @@
import { foldIdentifiedWindowsPath, parseAllSessions } from './parser.js'
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'
import type { DateRange } from './types.js'
@ -87,8 +89,10 @@ function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map<s
}
}
export async function computeSpendFlow(range: DateRange, provider: string): Promise<SpendFlow> {
const projects = await parseAllSessions(range, provider)
export async function computeSpendFlow(range: DateRange, provider: string, projectFilter?: string[], excludeFilter?: string[]): Promise<SpendFlow> {
const parsed = await parseAllSessions(range, provider)
await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, projectFilter, excludeFilter)
const matrix = new Map<string, Map<string, number>>()
const projectTotals = new Map<string, number>()
const modelTotals = new Map<string, number>()

View file

@ -3,7 +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 { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, sessionHydrationSnapshot } from './parser.js'
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'
@ -18,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'
@ -376,33 +378,16 @@ 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
/// 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))
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<string, ProjectDayStats>,
include: string[],
exclude: string[],
matches: ProjectFilter,
): { cost: number; calls: number; savingsUSD: number; sessions: number; projects: Record<string, ProjectDayStats>; matched: number } {
const out = { cost: 0, calls: 0, savingsUSD: 0, sessions: 0, projects: {} as Record<string, ProjectDayStats>, 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 +417,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 +425,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 +435,7 @@ function sliceDayToProject(day: DailyEntry, include: string[], exclude: string[]
const providers: Record<string, ProviderDaySlice> = {}
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 +517,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 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 +527,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))
@ -619,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
@ -642,7 +632,11 @@ export type DurablePeriod = {
export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: AggregateOpts = {}): Promise<DurablePeriod> {
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 +698,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 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 +715,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,7 +771,8 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
}
const carriedCostUSD = days.reduce((s, d) => s + (d.carried ? d.cost : 0), 0)
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, cache, todayAllDays, scanRange }
const knownProjects = [...seenProjects, ...cachedProjectIdentities(cache, rangeStartStr, rangeEndStr)]
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, knownProjects, cache, todayAllDays, scanRange }
}
type PayloadProject = NonNullable<PeriodData['projects']>[number]

View file

@ -1,7 +1,9 @@
import { execFileSync } from 'child_process'
import { realpathSync } from 'fs'
import { resolve } from 'path'
import { parseAllSessions } from './parser.js'
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'
import type { DateRange, ProjectSummary, SessionSummary } from './types.js'
@ -460,8 +462,10 @@ function buildRepoGroups(
return repoGroups
}
export async function computeYield(range: DateRange, cwd: string, provider: string = 'all'): Promise<YieldSummary> {
const projects = await parseAllSessions(range, provider)
export async function computeYield(range: DateRange, cwd: string, provider: string = 'all', projectFilter?: string[], excludeFilter?: string[]): Promise<YieldSummary> {
const parsed = await parseAllSessions(range, provider)
await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range))
const projects = filterProjectsByName(parsed, projectFilter, excludeFilter)
const summary: YieldSummary = {
productive: { cost: 0, sessions: 0 },

View file

@ -0,0 +1,229 @@
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'
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 })
// 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<string> {
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
}
/** A project whose only sessions are older than today, so a today-scoped pass misses it. */
async function seedHomeWithOlderSessions(): Promise<string> {
const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-'))
homes.push(home)
const dir = join(home, '.claude', 'projects', SIBLINGS[0]!.dir)
await mkdir(dir, { recursive: true })
const fiveDaysAgo = Date.now() - 5 * 24 * 60 * 60 * 1000
const lines = [1, 2].map(index => JSON.stringify({
type: 'assistant',
timestamp: new Date(fiveDaysAgo + index * 60_000).toISOString(),
sessionId: 's-old',
cwd: SIBLINGS[0]!.cwd,
message: {
type: 'message', role: 'assistant', model: 'claude-3-5-sonnet-20241022', id: `old-m${index}`,
content: [],
usage: { input_tokens: 90000, output_tokens: 12000, cache_creation_input_tokens: 0, cache_read_input_tokens: 300000 },
},
}))
await writeFile(join(dir, 's-old.jsonl'), lines.join('\n') + '\n', 'utf-8')
return home
}
/** A carried day the cache still bills, whose session files are long gone. */
async function seedDayCacheOnly(): Promise<string> {
const home = await mkdtemp(join(tmpdir(), 'codeburn-project-filter-cli-'))
homes.push(home)
await mkdir(join(home, '.claude', 'projects'), { recursive: true })
await mkdir(join(home, 'cache'), { recursive: true })
const date = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
const projects = { app: { cost: 30, calls: 10, savingsUSD: 0, sessions: 1, path: SIBLINGS[0]!.cwd } }
const day = {
date, cost: 30, savingsUSD: 0, calls: 10, sessions: 1,
inputTokens: 100, outputTokens: 50, cacheReadTokens: 0, cacheWriteTokens: 0,
editTurns: 1, oneShotTurns: 0, models: {}, categories: {}, providers: {}, projects, carried: true,
}
await writeFile(join(home, 'cache', `daily-cache.v${DAILY_CACHE_VERSION}.json`), JSON.stringify({
version: DAILY_CACHE_VERSION, savingsConfigHash: '', tzKey: currentTzKey(),
lastComputedDate: date, days: [day], complete: true,
}), 'utf-8')
return home
}
function runCli(args: string[], home: string) {
return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
cwd: process.cwd(),
env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEBURN_CACHE_DIR: join(home, 'cache'), 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('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()
// 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('')
})
})

View file

@ -1,3 +1,5 @@
import { homedir } from 'node:os'
import { describe, it, expect } from 'vitest'
import { filterProjectsByName } from '../src/parser.js'
@ -52,6 +54,66 @@ 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('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')

View file

@ -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<void> {
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

View file

@ -178,6 +178,25 @@ describe('codeburn serve --stdio', () => {
}
}, 60_000)
// SERVE_OPTIONS mirrors the Commander definitions: a command that declares
// --project/--exclude but is missing them here falls back to a cold spawn.
it('routes --project/--exclude for every command that declares them', async () => {
const commands: Array<[number, string[]]> = [
[330, ['status', '--format', 'json', '--period', 'today', '--project', '/nope']],
[331, ['overview', '--period', 'today', '--no-color', '--exclude', '/nope']],
[332, ['models', '--format', 'json', '--period', 'today', '--project', '/nope']],
[333, ['sessions', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
[334, ['compare', '--format', 'json', '--period', 'today', '--project', '/nope']],
[335, ['yield', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
[336, ['spend', '--format', 'flow-json', '--period', 'today', '--project', '/nope']],
[337, ['optimize', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
[338, ['audit', '--format', 'json', '--period', 'today', '--project', '/nope']],
]
for (const [id, args] of commands) {
expect(await request(id, args)).toMatchObject({ ok: true })
}
}, 60_000)
it('survives a malformed request line and keeps serving', async () => {
sendRaw('this is not json')
const res = await request(6, ['status', '--format', 'menubar-json', '--period', 'today'])

View file

@ -14,6 +14,9 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({
vi.mock('../src/parser.js', () => ({
parseAllSessions: parseAllSessionsMock,
filterProjectsByName: (projects: unknown[]) => projects,
unmatchedRootedPatterns: () => [],
isInteractiveScanUI: () => false,
}))
function git(cwd: string, args: string[], env: Record<string, string> = {}): string {

View file

@ -15,6 +15,9 @@ const { parseAllSessionsMock } = vi.hoisted(() => ({
vi.mock('../src/parser.js', () => ({
parseAllSessions: parseAllSessionsMock,
filterProjectsByName: (projects: unknown[]) => projects,
unmatchedRootedPatterns: () => [],
isInteractiveScanUI: () => false,
}))
function git(cwd: string, args: string[], env: Record<string, string> = {}): string {