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

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