fix(usage): preserve project identity and qualify incomplete session counts

This commit is contained in:
Aditya Vikram Singh 2026-09-07 22:02:54 +05:30
parent 0b1cf56fd9
commit f5fd47e83d
57 changed files with 4770 additions and 201 deletions

View file

@ -5,6 +5,7 @@ import React, { Fragment, useState, useCallback, useEffect, useLayoutEffect, use
import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement, type Instance, type RenderOptions } from 'ink'
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
import { formatCost, formatTokens, markEstimated, carriedCostNote } from './format.js'
import { formatSessionCount } from './session-count-label.js'
import { aggregateModelEfficiency } from './model-efficiency.js'
import { parseAllSessions, filterProjectsByDateRange, filterProjectsByName, setInteractiveScanUI, withSinglePassParse, withColdFirstPaintFloor, filesParsedFromSourceCount, isCompleteSessionSnapshotAvailable } from './parser.js'
import { findUnpricedModels, isExpectedFreeModel, loadPricing } from './models.js'
@ -361,7 +362,8 @@ export type DurableOverview = {
savingsUSD: number
calls: number
sessions: number
inputTokens: number
sessionCountBasis?: 'identity' | 'partial'
inputTokens: number,
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
@ -394,6 +396,7 @@ async function computeDurableOverview(
savingsUSD: data.savingsUSD,
calls: data.calls,
sessions: data.sessions,
sessionCountBasis: data.sessionCountBasis,
inputTokens: data.inputTokens,
outputTokens: data.outputTokens,
cacheReadTokens: data.cacheReadTokens,
@ -617,8 +620,8 @@ function Overview({ projects, label, width, planUsages, durable }: { projects: P
<Text dimColor> cost </Text>
<Text bold>{totalCalls.toLocaleString()}</Text>
<Text dimColor> calls </Text>
<Text bold>{String(totalSessions)}</Text>
<Text dimColor> sessions </Text>
<Text bold>{durable ? formatSessionCount(totalSessions, durable.sessionCountBasis) : `${totalSessions.toLocaleString()} sessions`}</Text>
<Text dimColor> </Text>
<Text bold>{cacheHit.toFixed(1)}%</Text>
<Text dimColor> cache hit</Text>
</Text>

View file

@ -999,6 +999,7 @@ program
savingsUSD: durable.data.savingsUSD,
calls: durable.data.calls,
sessions: durable.data.sessions,
sessionCountBasis: durable.data.sessionCountBasis,
inputTokens: durable.data.inputTokens,
outputTokens: durable.data.outputTokens,
cacheReadTokens: durable.data.cacheReadTokens,

View file

@ -42,6 +42,7 @@ export function redactProjectNames(payload: MenubarPayload, includeNames: boolea
topProjects: payload.current.topProjects.map(p => ({
...p,
name: pseudonym(p.name),
...(p.id ? { id: pseudonym(p.id) } : {}),
sessionDetails: p.sessionDetails ? redactSessionDetails(p.sessionDetails) : [],
})),
topSessions: payload.current.topSessions.map(s => ({ ...s, project: pseudonym(s.project) })),

View file

@ -1,6 +1,7 @@
import { formatCost, formatTokens, markEstimated } from '../format.js'
import type { MenubarPayload } from '../menubar-json.js'
import { unpricedModelHint } from '../models.js'
import { formatSessionCount } from '../session-count-label.js'
const ESTIMATED_LEGEND = '_~ estimated cost (priced from estimated tokens)_'
const isEstimated = (m: { estimatedCostUSD?: number }) => (m.estimatedCostUSD ?? 0) > 0
@ -21,7 +22,7 @@ export function renderSummaryTable(p: MenubarPayload): string {
const c = p.current
const unpriced = c.unpricedModels ?? []
return [
`**${c.label}** — ${formatCost(c.cost)} · ${c.calls} calls · ${c.sessions} sessions`,
`**${c.label}** — ${formatCost(c.cost)} · ${c.calls} calls · ${formatSessionCount(c.sessions, c.sessionCountBasis)}`,
`cache hit ${pct(c.cacheHitPercent)} · one-shot ${oneShot(c.oneShotRate)} · in ${formatTokens(c.inputTokens)} / out ${formatTokens(c.outputTokens)}`,
...(unpriced.length > 0
? [`⚠ ${unpriced.length} model${unpriced.length === 1 ? '' : 's'} unpriced, counted at $0: ${unpriced.map(u => `${u.model} (${u.calls} calls)`).join(', ')}. ${unpricedModelHint()}`]
@ -32,7 +33,7 @@ export function renderSummaryTable(p: MenubarPayload): string {
...(c.topModels.slice(0, 5).some(isEstimated) ? [ESTIMATED_LEGEND] : []),
'',
'_Top projects_',
mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, 5).map(x => [x.name, formatCost(x.cost), String(x.sessions)])),
mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, 5).map(x => [x.name, formatCost(x.cost), formatSessionCount(x.sessions, x.sessionCountBasis)])),
].join('\n')
}
@ -43,7 +44,7 @@ export function renderBreakdownTable(p: MenubarPayload, by: BreakdownBy, limit:
const table = mdTable(['Model', 'Cost', 'Calls'], rows.map(m => [m.name, markEstimated(formatCost(m.cost), isEstimated(m)), String(m.calls)]))
return rows.some(isEstimated) ? `${table}\n\n${ESTIMATED_LEGEND}` : table
}
if (by === 'project') return mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, limit).map(x => [x.name, formatCost(x.cost), String(x.sessions)]))
if (by === 'project') return mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, limit).map(x => [x.name, formatCost(x.cost), formatSessionCount(x.sessions, x.sessionCountBasis)]))
if (by === 'task') return mdTable(['Task', 'Cost', 'Turns', 'One-shot'], c.topActivities.slice(0, limit).map(a => [a.name, formatCost(a.cost), String(a.turns), oneShot(a.oneShotRate)]))
return mdTable(['Provider', 'Cost'], Object.entries(c.providers).sort(([, a], [, b]) => b - a).slice(0, limit).map(([name, cost]) => [name, formatCost(cost)]))
}

View file

@ -16,6 +16,10 @@ export type PeriodData = {
estimatedCostUSD?: number
calls: number
sessions: number
/// How `sessions` was derived. `identity` is exact unique source ids with no
/// unknown-cache contribution; `partial` is a lower bound. Omitted on older
/// PeriodData producers.
sessionCountBasis?: SessionCountBasis
inputTokens: number
outputTokens: number
cacheReadTokens: number
@ -29,7 +33,7 @@ export type PeriodData = {
/// current tables (#638): their calls contribute $0 to `cost`. Optional so
/// PeriodData producers that predate the field keep compiling.
unpricedModels?: Array<{ model: string; calls: number; tokens: number }>
projects?: Array<{ name: string; cost: number; savingsUSD: number; sessions: number; sessionDetails?: Array<{ cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number; savingsUSD: number }> }> }>
projects?: Array<{ id?: string; name: string; cost: number; savingsUSD: number; sessions: number; sessionCountBasis?: SessionCountBasis; sessionDetails?: Array<{ cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number; savingsUSD: number }> }> }>
modelEfficiency?: Array<{ name: string; costPerEdit: number | null; oneShotRate: number | null }>
topSessions?: Array<{ project: string; cost: number; savingsUSD: number; calls: number; date: string }>
/// Workflow-intelligence rollups (issue: workflow intelligence). Optional so
@ -91,6 +95,7 @@ export type ProviderCost = {
outputTokens?: number
/** Provider-scoped session count for the period, absent under the same rule. */
sessions?: number
sessionCountBasis?: SessionCountBasis
}
import type { OptimizeResult } from './optimize.js'
import { getCurrency } from './currency.js'
@ -100,6 +105,7 @@ import type { ReworkedFile } from './workflow-insights.js'
import type { PrRow, BranchRow } from './sessions-report.js'
import type { LiveSessionsBlock } from './live-sessions.js'
import { buildTelemetrySnapshot, type TelemetrySnapshot, type TelemetrySnapshotInput } from './telemetry-snapshot.js'
import { sessionCountIsExact, type SessionCountBasis } from './session-count-label.js'
const TOP_ACTIVITIES_LIMIT = 20
const TOP_MODELS_LIMIT = 20
@ -235,6 +241,8 @@ export type MenubarPayload = {
cost: number
calls: number
sessions: number
/// How `sessions` was derived. Omitted on older producers.
sessionCountBasis?: SessionCountBasis
oneShotRate: number | null
inputTokens: number
outputTokens: number
@ -296,13 +304,22 @@ export type MenubarPayload = {
inputTokens?: number
outputTokens?: number
sessions?: number
sessionCountBasis?: SessionCountBasis
}>
topProjects: Array<{
/// Stable identity (abs cwd when known). Optional so older PeriodData
/// producers keep compiling; renderer expand keys on `id ?? name`.
id?: string
name: string
cost: number
savingsUSD: number
sessions: number
avgCostPerSession: number
/// Present only when `sessionCountBasis` is `identity` and sessions > 0.
/// Omitted for lower-bound counts so clients cannot treat cost/count as exact.
avgCostPerSession?: number
/// How `sessions` was derived. Omitted on older producers. `identity` is
/// an exact unique count from surviving source files; `partial` is a lower bound.
sessionCountBasis?: SessionCountBasis
sessionDetails: Array<{
cost: number
savingsUSD: number
@ -513,6 +530,7 @@ function buildProviderDetails(providers: ProviderCost[]): MenubarPayload['curren
...(p.inputTokens === undefined ? {} : { inputTokens: p.inputTokens }),
...(p.outputTokens === undefined ? {} : { outputTokens: p.outputTokens }),
...(p.sessions === undefined ? {} : { sessions: p.sessions }),
...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}),
}))
}
@ -529,11 +547,15 @@ function buildTopProjects(projects: PeriodData['projects']): MenubarPayload['cur
.sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD))
.slice(0, TOP_PROJECTS_LIMIT)
.map(p => ({
...(p.id ? { id: p.id } : {}),
name: p.name,
cost: p.cost,
savingsUSD: p.savingsUSD,
sessions: p.sessions,
avgCostPerSession: p.sessions > 0 ? p.cost / p.sessions : 0,
...(sessionCountIsExact(p.sessionCountBasis) && p.sessions > 0
? { avgCostPerSession: p.cost / p.sessions }
: {}),
...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}),
sessionDetails: (p.sessionDetails ?? []).map(s => ({
cost: s.cost,
savingsUSD: s.savingsUSD,
@ -614,6 +636,7 @@ export function buildMenubarPayload(
cost: current.cost,
calls: current.calls,
sessions: current.sessions,
...(current.sessionCountBasis ? { sessionCountBasis: current.sessionCountBasis } : {}),
oneShotRate: aggregateOneShotRate(current.categories),
inputTokens: current.inputTokens,
outputTokens: current.outputTokens,

View file

@ -7,6 +7,7 @@ import { formatCost as baseCost, getCurrency } from './currency.js'
import { findUnpricedModels, getShortModelName, unpricedModelHint } from './models.js'
import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js'
import { markEstimated } from './format.js'
import { formatSessionCount, SESSION_COUNT_HELP, type SessionCountBasis } from './session-count-label.js'
import { dateKey } from './day-aggregator.js'
import type { DailyEntry } from './daily-cache.js'
import type { BudgetStatus, BudgetTier } from './budget.js'
@ -45,6 +46,28 @@ function projectName(p: ProjectSummary): string {
return p.project.split('-').filter(Boolean).pop() || p.project
}
/** #1260: aggregate by abs path identity so /a/vault != /b/vault. */
function projectAggKey(p: ProjectSummary): string {
const path = (p.projectPath ?? '').trim().replace(/\\/g, '/')
if (path && isAbsoluteProjectPath(path)) return path.replace(/\/+$/, '').toLowerCase()
// Codex-style stripped abs ("root/vault") still has a slash and no leading dash.
if (path.includes('/') && !path.startsWith('-')) return path.replace(/\/+$/, '').toLowerCase()
return `label:${projectName(p).toLowerCase()}`
}
function disambiguatedProjectLabel(key: string, sample: ProjectSummary, basenameCounts: Map<string, number>): string {
const base = projectName(sample)
if ((basenameCounts.get(base) ?? 0) <= 1) return base
const path = (sample.projectPath ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '')
if (path && isAbsoluteProjectPath(path)) {
const parts = path.split('/').filter(Boolean)
if (parts.length >= 2) return parts.slice(-2).join('/')
return path
}
return sample.project || base || key
}
type Col = { header: string; right?: boolean }
type OverviewBudget = {
tier: BudgetTier
@ -92,6 +115,7 @@ export type OverviewDurable = {
savingsUSD: number
calls: number
sessions: number
sessionCountBasis?: SessionCountBasis
inputTokens: number
outputTokens: number
cacheReadTokens: number
@ -127,18 +151,18 @@ export function renderOverview(
const byCat = new Map<string, { cost: number; turns: number }>()
const byTool = new Map<string, number>()
const byDay = new Map<string, { cost: number; tokens: number; providers: Set<string> }>()
const byProject = new Map<string, { cost: number; sessions: number }>()
const byProject = new Map<string, { cost: number; sessions: number; sample: ProjectSummary }>()
for (const p of projects) {
cost += p.totalCostUSD
savings += p.totalSavingsUSD
calls += p.totalApiCalls
sessions += p.sessions.length
const pname = projectName(p)
const pe = byProject.get(pname) ?? { cost: 0, sessions: 0 }
const pkey = projectAggKey(p)
const pe = byProject.get(pkey) ?? { cost: 0, sessions: 0, sample: p }
pe.cost += p.totalCostUSD
pe.sessions += p.sessions.length
byProject.set(pname, pe)
byProject.set(pkey, pe)
for (const s of p.sessions) {
inTok += s.totalInputTokens
outTok += sessionBillableOutputTokens(s)
@ -222,7 +246,10 @@ export function renderOverview(
const kv = (k: string, v: string): string => ' ' + c.dim(k.padEnd(11)) + v
out.push(kv('Cost', c.bold(formatCost(cost))))
out.push(kv('Tokens', formatTokens(totalTokens) + c.dim(' (breakdown below)')))
out.push(kv('Calls', formatCount(calls) + c.dim(' sessions ') + formatCount(sessions)))
out.push(kv('Calls', formatCount(calls) + c.dim(' ') + formatSessionCount(sessions, durable ? durable.sessionCountBasis : 'identity')))
if (durable && durable.sessionCountBasis !== 'identity' && sessions > 0) {
out.push(kv('', c.dim(SESSION_COUNT_HELP)))
}
out.push(kv('Cache hit', `${cacheHit.toFixed(1)}%`))
if (savings > 0) out.push(kv('Savings', formatCost(savings) + c.dim(' (local models)')))
const unpriced = findUnpricedModels(
@ -307,13 +334,18 @@ export function renderOverview(
out.push('')
}
// Top projects
// Top projects (#1260: labels disambiguate when basename collides across abs paths)
const projRows = [...byProject.entries()].sort((a, b) => b[1].cost - a[1].cost).slice(0, 10)
if (projRows.length) {
const basenameCounts = new Map<string, number>()
for (const [, v] of projRows) {
const b = projectName(v.sample)
basenameCounts.set(b, (basenameCounts.get(b) ?? 0) + 1)
}
out.push(heading('Top projects'))
out.push(renderTable(c,
[{ header: 'Project' }, { header: 'Cost', right: true }, { header: 'Sessions', right: true }],
projRows.map(([name, v]) => [name, formatCost(v.cost), formatCount(v.sessions)]),
projRows.map(([key, v]) => [disambiguatedProjectLabel(key, v.sample, basenameCounts), formatCost(v.cost), formatCount(v.sessions)]),
))
out.push('')
}

View file

@ -77,9 +77,22 @@ function claudeSlugFallbackPath(dirName: string): string {
return dirName
}
function normalizeProjectPathKey(projectPath: string): string {
/// Drive-letter and UNC (`//server/share` after slash-normalize) are Windows
/// identity: directory case folds. A single leading slash is POSIX and does not.
function isWindowsAbsPath(slashNormalized: string): boolean {
return /^[a-zA-Z]:(\/|$)/.test(slashNormalized) || slashNormalized.startsWith('//')
}
function foldIdentifiedWindowsPath(slashNormalized: string): string {
return isWindowsAbsPath(slashNormalized) ? slashNormalized.toLowerCase() : slashNormalized
}
/// Cache/live grouping key for a stored cwd. Separators always normalize.
/// Identified Windows paths casefold; POSIX case is identity.
export function normalizeProjectPathKey(projectPath: string): string {
const normalized = projectPath.trim().replace(/\\/g, '/')
return (normalized.replace(/\/+$/, '') || normalized).toLowerCase()
const trimmed = normalized.replace(/\/+$/, '') || normalized
return foldIdentifiedWindowsPath(trimmed)
}
function projectNameFromPath(projectPath: string, fallback: string): string {
@ -4221,7 +4234,12 @@ export async function parseProviderSources(
}
}
const projectMap = new Map<string, { projectPath?: string; sessions: SessionSummary[] }>()
// #1260 REVISE3: group by absolute projectPath / workingDirectory when
// available — never by display basename alone. Two Pi roots with cwd=/a/vault
// and /b/vault both display as "vault"; keying on the leaf collapsed them
// (first projectPath wins) before mergeProjectsByCrossProviderKey could see
// distinct abs identities.
const projectMap = new Map<string, { project: string; projectPath?: string; sessions: SessionSummary[] }>()
for (const [key, { project, projectPath, workingDirectory, turns, prLinks, title, lineage, agentName, agentStartedAt }] of sessionMap) {
const sessionId = key.split(':')[1] ?? key
const assembledTurns = providerName === 'copilot'
@ -4242,19 +4260,28 @@ export async function parseProviderSources(
// Supplementary-only sessions (e.g. a rollup with no per-turn calls) have
// apiCalls 0 by design but their tokens/cost are real and must serve.
if (session.apiCalls > 0 || session.totalCostUSD > 0 || session.totalInputTokens + session.totalOutputTokens + session.totalCacheReadTokens + session.totalCacheWriteTokens + session.totalReasoningTokens > 0) {
const existing = projectMap.get(project)
const absFromPath = projectPath ? normalizeAbsProjectPathKey(projectPath) : null
const absFromWd = workingDirectory ? normalizeAbsProjectPathKey(workingDirectory) : null
const absKey = absFromPath ?? absFromWd
const groupKey = absKey ? `path:${absKey}` : `label:${project}`
const resolvedPath = absFromPath ? projectPath : (absFromWd ? workingDirectory : projectPath)
const existing = projectMap.get(groupKey)
if (existing) {
existing.sessions.push(session)
if (!existing.projectPath && projectPath) existing.projectPath = projectPath
if (absFromPath && !normalizeAbsProjectPathKey(existing.projectPath ?? '')) {
existing.projectPath = projectPath
} else if (!existing.projectPath && resolvedPath) {
existing.projectPath = resolvedPath
}
} else {
projectMap.set(project, { projectPath, sessions: [session] })
projectMap.set(groupKey, { project, projectPath: resolvedPath, sessions: [session] })
}
}
}
const projects: ProjectSummary[] = []
for (const [dirName, { projectPath, sessions }] of projectMap) {
projects.push(summarizeProject(dirName, projectPath ?? unsanitizePath(dirName), sessions))
for (const { project, projectPath, sessions } of projectMap.values()) {
projects.push(summarizeProject(project, projectPath ?? unsanitizePath(project), sessions))
}
return projects
@ -4573,31 +4600,152 @@ export function filterProjectsByDays(projects: ProjectSummary[], days: Set<strin
// same repo used with Claude Code + Codex, say). An additive total summed at
// the session level but forgotten here silently under-reports for exactly the
// multi-provider users (this bit totalEstimatedCostUSD once, caught in #639
// verification). Known gaps, deliberate: totalSavingsUSD is still not summed
// (pre-existing, tracked separately) and totalProxiedCostUSD is re-derived
// after the merge rather than summed here.
export function mergeProjectsByCrossProviderKey(projects: ProjectSummary[]): Map<string, ProjectSummary> {
const crossProviderKey = (p: ProjectSummary): string => {
const path = p.projectPath.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase()
return path.includes('/') ? path : p.project.toLowerCase()
// verification). totalSavingsUSD is summed with cost/calls. totalProxiedCostUSD
// is re-derived after the merge rather than summed here.
//
// #1260: providers sanitize the same absolute cwd differently (-root-vault /
// root-vault / vault). Prefer absolute projectPath (or session.workingDirectory)
// as the merge key; attach slug/basename-only rows only when they uniquely match
// one absolute path. Ambiguous basenames across distinct parents stay separate.
// POSIX path case is identity: /a/Vault and /a/vault are two keys. Identified
// Windows drive/UNC paths still casefold (C:\\Work\\Vault ≡ c:/work/vault).
// Lowercased labels are matching hints only — two path keys sharing a hint
// stay unattached.
export function normalizeAbsProjectPathKey(projectPath: string): string | null {
const raw = projectPath.trim().replace(/\\/g, '/')
if (!raw) return null
// Absolute POSIX, Windows drive, or Codex-style stripped abs ("root/vault").
const looksAbs = raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) || (raw.includes('/') && !raw.startsWith('-'))
if (!looksAbs) return null
const folded = foldIdentifiedWindowsPath(raw)
const stripped = folded.replace(/^\/+/, '').replace(/\/+$/, '')
return stripped || null
}
function sanitizePathAsLabel(absKey: string): string {
return absKey.replace(/\//g, '-')
}
function labelAliases(project: string): string[] {
const raw = project.trim().replace(/\\/g, '/').toLowerCase()
if (!raw) return []
const noLeadDash = raw.replace(/^-+/, '')
return [...new Set([raw, noLeadDash].filter(Boolean))]
}
function foldInto(existing: ProjectSummary, p: ProjectSummary): void {
existing.sessions.push(...p.sessions)
if (p.subagentAnchors?.length) existing.subagentAnchors = [...(existing.subagentAnchors ?? []), ...p.subagentAnchors]
existing.totalCostUSD += p.totalCostUSD
existing.totalSavingsUSD = (existing.totalSavingsUSD ?? 0) + (p.totalSavingsUSD ?? 0)
existing.totalEstimatedCostUSD = (existing.totalEstimatedCostUSD ?? 0) + (p.totalEstimatedCostUSD ?? 0)
existing.totalApiCalls += p.totalApiCalls
}
export function crossProviderProjectKey(p: ProjectSummary): string {
const fromPath = normalizeAbsProjectPathKey(p.projectPath)
if (fromPath) return `path:${fromPath}`
const wd = p.sessions.map(s => s.workingDirectory).find(w => typeof w === 'string' && w.trim())
if (wd) {
const fromWd = normalizeAbsProjectPathKey(wd)
if (fromWd) return `path:${fromWd}`
}
const mergedMap = new Map<string, ProjectSummary>()
const aliases = labelAliases(p.project)
return `label:${aliases[0] ?? p.project.toLowerCase()}`
}
const SANITIZED_COLLISION = '__collision__'
function registerSanitizedLabel(
pathBySanitized: Map<string, string>,
sanitizedMembers: Map<string, Set<string>>,
label: string,
key: string,
): void {
const members = sanitizedMembers.get(label) ?? new Set<string>()
members.add(key)
sanitizedMembers.set(label, members)
const prev = pathBySanitized.get(label)
if (prev === undefined) {
pathBySanitized.set(label, key)
return
}
if (prev !== key) pathBySanitized.set(label, SANITIZED_COLLISION)
}
export function mergeProjectsByCrossProviderKey(projects: ProjectSummary[]): Map<string, ProjectSummary> {
const pathProjects = new Map<string, ProjectSummary>()
const pathBySanitized = new Map<string, string>()
const sanitizedMembers = new Map<string, Set<string>>()
const pathByBasename = new Map<string, string[]>()
const deferred: ProjectSummary[] = []
for (const p of projects) {
const key = crossProviderKey(p)
const existing = mergedMap.get(key)
const key = crossProviderProjectKey(p)
if (!key.startsWith('path:')) {
deferred.push(p)
continue
}
const abs = key.slice('path:'.length)
const existing = pathProjects.get(key)
if (existing) {
existing.sessions.push(...p.sessions)
if (p.subagentAnchors?.length) existing.subagentAnchors = [...(existing.subagentAnchors ?? []), ...p.subagentAnchors]
existing.totalCostUSD += p.totalCostUSD
existing.totalEstimatedCostUSD = (existing.totalEstimatedCostUSD ?? 0) + (p.totalEstimatedCostUSD ?? 0)
existing.totalApiCalls += p.totalApiCalls
foldInto(existing, p)
if (normalizeAbsProjectPathKey(p.projectPath) && !normalizeAbsProjectPathKey(existing.projectPath)) {
existing.projectPath = p.projectPath
existing.project = p.project
}
} else {
mergedMap.set(key, { ...p })
pathProjects.set(key, { ...p })
const sanitized = sanitizePathAsLabel(abs).toLowerCase()
registerSanitizedLabel(pathBySanitized, sanitizedMembers, sanitized, key)
registerSanitizedLabel(pathBySanitized, sanitizedMembers, `-${sanitized}`, key)
const base = abs.split('/').filter(Boolean).pop()
if (base) {
const hint = base.toLowerCase()
const bucket = pathByBasename.get(hint) ?? []
bucket.push(key)
pathByBasename.set(hint, bucket)
}
}
}
const labelOnly = new Map<string, ProjectSummary>()
for (const p of deferred) {
// Collect ALL candidates from sanitized + basename maps across aliases.
// On sanitized COLLISION, retain the full member set (do not ignore collision
// so a weaker basename unique-hit can still attach). Attach only when exactly
// one path key remains; otherwise stay label-only.
const candidates = new Set<string>()
for (const alias of labelAliases(p.project)) {
const viaSanitized = pathBySanitized.get(alias)
if (viaSanitized === SANITIZED_COLLISION) {
const members = sanitizedMembers.get(alias)
if (members) for (const m of members) candidates.add(m)
} else if (viaSanitized) {
candidates.add(viaSanitized)
}
const bases = pathByBasename.get(alias)
if (bases) for (const b of bases) candidates.add(b)
}
if (candidates.size === 1) {
const attach = [...candidates][0]!
foldInto(pathProjects.get(attach)!, p)
continue
}
// size === 0: no match; size > 1: ambiguous (sanitized collision, multi-parent, …)
const labelKey = `label:${labelAliases(p.project)[0] ?? p.project.toLowerCase()}`
const existing = labelOnly.get(labelKey)
if (existing) foldInto(existing, p)
else labelOnly.set(labelKey, { ...p })
}
const mergedMap = new Map<string, ProjectSummary>()
for (const [k, v] of pathProjects) mergedMap.set(k, v)
for (const [k, v] of labelOnly) mergedMap.set(k, v)
return mergedMap
}
function summaryProvider(session: SessionSummary): string {
return session.turns.flatMap(t => t.assistantCalls)[0]?.provider ?? 'unknown'
}

View file

@ -107,6 +107,12 @@ function getOmpSessionsDir(override?: string): string {
// pathological run of blank/junk lines).
const MAX_HEADER_LINES_SCANNED = 20
function looksAbsolutePath(value: string): boolean {
const trimmed = value.trim()
if (!trimmed) return false
return trimmed.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(trimmed)
}
async function readSessionEntry(filePath: string): Promise<PiEntry | null> {
let linesScanned = 0
for await (const line of readSessionLines(filePath)) {
@ -149,11 +155,17 @@ async function discoverSessionsInDir(sessionsDir: string, providerName: string):
const addSession = async (filePath: string, agentName?: string): Promise<void> => {
const entry = await readSessionEntry(filePath)
if (!entry) return
const cwd = entry.cwd ?? dirName
// Prefer the session header cwd when present. Keep basename(project) for
// display, but retain the absolute cwd on sourcePath so parse/grouping
// never have to infer identity from the sole observed leaf name (#1260).
const rawCwd = typeof entry.cwd === 'string' ? entry.cwd.trim() : ''
const cwd = rawCwd || dirName
const absCwd = looksAbsolutePath(cwd) ? cwd : undefined
sources.push({
path: filePath,
project: basename(cwd),
project: basename(cwd) || cwd,
provider: providerName,
...(absCwd ? { sourcePath: absCwd } : {}),
...(agentName ? {
agentName,
...(typeof entry.timestamp === 'string' ? { agentStartedAt: entry.timestamp } : {}),
@ -204,6 +216,12 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
let pendingUserMessage = ''
let sessionTimestamp = ''
let pendingUserTimestamp = ''
// Absolute session cwd from the header (or discovery sourcePath). Must
// survive into projectPath/workingDirectory so cross-provider merge can
// key by real path instead of basename-only (#1260 Codex REVISE2).
let sessionCwd = typeof source.sourcePath === 'string' && looksAbsolutePath(source.sourcePath)
? source.sourcePath.trim()
: ''
for (const [lineIdx, line] of lines.entries()) {
let entry: PiEntry
@ -216,6 +234,10 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
if (entry.type === 'session') {
sessionId = entry.id ?? sessionId
if (typeof entry.timestamp === 'string' && entry.timestamp) sessionTimestamp = entry.timestamp
if (typeof entry.cwd === 'string' && entry.cwd.trim()) {
const headerCwd = entry.cwd.trim()
if (looksAbsolutePath(headerCwd)) sessionCwd = headerCwd
}
continue
}
if (entry.type === 'model_change') {
@ -318,6 +340,11 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
deduplicationKey: dedupKey,
userMessage: pendingUserMessage,
sessionId,
project: source.project,
...(sessionCwd ? {
projectPath: sessionCwd,
workingDirectory: sessionCwd,
} : {}),
}
pendingUserMessage = ''

View file

@ -389,7 +389,13 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// nested-agent-v1: OMP writes crewmate transcripts one directory below each
// parent session. reported-cost-v2 persists those measured costs through the
// cache, including the explicit zero on xai-oauth turns.
omp: 'nested-agent-v1-reported-cost-v2',
// cwd-project-path-v1 (#1260): retain absolute session header cwd on
// projectPath/workingDirectory instead of basename-only identity.
// project-group-by-abs-v1 (#1260 REVISE3): parseProviderSources groups by
// abs projectPath/workingDirectory so same-basename distinct roots stay apart.
pi: 'cwd-project-path-v1-project-group-by-abs-v1',
// project-group-by-abs-v1: shared Pi/OMP serve grouping uses abs identity.
omp: 'nested-agent-v1-reported-cost-v2-cwd-project-path-v1-project-group-by-abs-v1',
opencode: 'session-model-v1',
quickdesk: 'emf-sqlite-v2-est-cost',
// session-lineage-capture-v1: SessionLineage (CB-1, slice 1) is now carried

View file

@ -0,0 +1,38 @@
/// Shared session-count phrasing for CLI, MCP, and tests.
/// Exact unique counts come only from surviving source identities with no
/// unknown cache contribution. Everything else is a lower bound.
export type SessionCountBasis = 'identity' | 'partial'
export const SESSION_COUNT_HELP = 'Older session logs may be unavailable.'
/// Combined-scope counts are a sum of per-device numbers with no shared identity
/// contract. Do not show that sum as unique or as a lower bound.
export const COMBINED_SESSION_COUNT_HELP = 'Session identities are unavailable across devices.'
export const COMBINED_SESSION_COUNT_LABEL = 'Session count unavailable'
export function sessionCountIsExact(basis: SessionCountBasis | undefined): boolean {
return basis === 'identity'
}
export function formatSessionCount(
sessions: number,
basis: SessionCountBasis | undefined,
): string {
if (!sessionCountIsExact(basis)) {
if (sessions <= 0) return 'Session count unavailable'
return sessions === 1 ? 'At least 1 session' : `At least ${sessions.toLocaleString('en-US')} sessions`
}
if (sessions === 1) return '1 session'
return `${sessions.toLocaleString('en-US')} sessions`
}
/// Compact average for surfaces that show one. Never invent $0 or cost/count
/// when the count is a bound.
export function formatSessionAveragePlaceholder(): string {
return '—'
}
/// Combined-scope display only. Ignores the numeric wire sum; do not pass 0 to
/// `formatSessionCount` to obtain this string.
export function formatCombinedSessionCount(): string {
return COMBINED_SESSION_COUNT_LABEL
}

View file

@ -96,6 +96,9 @@ export function summarizeDeviceUsage(results: DeviceUsage[], window?: SummaryWin
return {
cost: a.cost + d.cost,
calls: a.calls + d.calls,
// Numeric wire sum only. Combined-scope UI must not present this as a
// unique or lower-bound session count until a cross-device identity
// contract exists.
sessions: a.sessions + d.sessions,
inputTokens: a.inputTokens + d.inputTokens,
outputTokens: a.outputTokens + d.outputTokens,

View file

@ -22,6 +22,18 @@ function addToMap<K>(map: Map<K, number>, key: K, cost: number): void {
map.set(key, (map.get(key) ?? 0) + cost)
}
/** #1260: identity for spend nodes — abs projectPath when present, else display label. */
export function spendProjectIdentity(project: { project: string; projectPath?: string }): { id: string; label: string } {
const raw = (project.projectPath ?? '').trim().replace(/\\/g, '/')
const looksAbs = raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) || (raw.includes('/') && !raw.startsWith('-'))
if (looksAbs && raw) {
const id = raw.replace(/\/+$/, '')
const base = id.split('/').filter(Boolean).pop() || project.project
return { id, label: base }
}
return { id: project.project, label: project.project }
}
function sortedEntries(totals: Map<string, number>): Array<[string, number]> {
return [...totals.entries()].sort(([aName, aCost], [bName, bCost]) => {
const byCost = bCost - aCost
@ -40,24 +52,62 @@ function buildNodes(totals: Map<string, number>): { nodes: SpendFlowNode[]; keep
return { nodes, keep }
}
function looksAbsId(id: string): boolean {
return id.startsWith('/') || /^[a-zA-Z]:\//.test(id)
}
function pathParts(id: string): string[] {
return id.replace(/\\/g, '/').replace(/\/+$/, '').split('/').filter(Boolean)
}
/// Visible chart labels keep the literal basename (hyphens stay hyphens).
/// Same-basename abs cwds pick up enough parent segments to distinguish.
/// Legacy slug ids and Other are left as-is.
function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map<string, string>): void {
const visible = nodes.filter(node => node.id !== OTHER_ID)
for (const node of visible) {
if (!looksAbsId(node.id)) {
node.label = labels.get(node.id) ?? node.id
continue
}
const parts = pathParts(node.id)
const base = parts.at(-1) || labels.get(node.id) || node.id
const collisions = visible.filter(other => other.id !== node.id && looksAbsId(other.id) && pathParts(other.id).at(-1) === base)
if (collisions.length === 0) {
node.label = base
continue
}
let label = base
for (let n = 2; n <= parts.length; n++) {
label = parts.slice(-n).join('/')
const clash = collisions.some(other => pathParts(other.id).slice(-n).join('/') === label)
if (!clash) break
}
node.label = label
}
}
export async function computeSpendFlow(range: DateRange, provider: string): Promise<SpendFlow> {
const projects = await parseAllSessions(range, provider)
const matrix = new Map<string, Map<string, number>>()
const projectTotals = new Map<string, number>()
const modelTotals = new Map<string, number>()
const projectLabels = new Map<string, string>()
for (const project of projects) {
const { id: projectId, label: projectLabel } = spendProjectIdentity(project)
if (!projectLabels.has(projectId)) projectLabels.set(projectId, projectLabel)
for (const session of project.sessions) {
for (const [model, breakdown] of Object.entries(session.modelBreakdown)) {
const cost = breakdown.costUSD
if (cost <= 0) continue
let modelCosts = matrix.get(project.project)
let modelCosts = matrix.get(projectId)
if (!modelCosts) {
modelCosts = new Map<string, number>()
matrix.set(project.project, modelCosts)
matrix.set(projectId, modelCosts)
}
addToMap(modelCosts, model, cost)
addToMap(projectTotals, project.project, cost)
addToMap(projectTotals, projectId, cost)
addToMap(modelTotals, model, cost)
}
}
@ -65,6 +115,7 @@ export async function computeSpendFlow(range: DateRange, provider: string): Prom
const { nodes: models, keep: keptModels } = buildNodes(modelTotals)
const { nodes: projectsNodes, keep: keptProjects } = buildNodes(projectTotals)
assignDistinguishingProjectLabels(projectsNodes, projectLabels)
const rolledLinks = new Map<string, SpendFlowLink>()
for (const [project, modelCosts] of matrix.entries()) {

View file

@ -1,7 +1,8 @@
import { homedir } from 'node:os'
import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory, type DateRange } from './types.js'
import { CATEGORY_LABELS, type ProjectSummary, type SessionSummary, type TaskCategory, type DateRange } from './types.js'
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 { findUnpricedModels, getFlatRateModelsConfigHash, getLocalModelSavingsConfigHash, getPriceOverridesConfigHash, getShortModelName, isExpectedFreeModel } from './models.js'
import { getAllProviders, safeDiscoverSessions } from './providers/index.js'
@ -16,9 +17,10 @@ import { aggregateModelTaskTurns, sessionDurationMinutes } from './telemetry-sna
import { scanUserCorrections, medianTimeToFirstEditMs, aggregateFileChurn, computePricingCoverage } from './workflow-insights.js'
import { buildPrAttribution, aggregateByBranch } from './sessions-report.js'
import { scanAndDetect } from './optimize.js'
import { callBillableOutputTokens, sessionBillableOutputTokens } from './session-output.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 { buildGranularHistory } from './granular-history.js'
import { spendProjectIdentity } from './spend-flow.js'
// Row caps for the by-PR / by-branch payload aggregations, ranked by cost.
const TOP_BRANCHES = 15
@ -31,6 +33,7 @@ export type ProviderSliceTotal = {
inputTokens?: number
outputTokens?: number
sessions?: number
sessionCountBasis?: SessionCountBasis
}
/// Folds one day's provider slice into the period total. Tokens and sessions are
@ -44,7 +47,9 @@ export function addProviderSlice(totals: Record<string, ProviderSliceTotal>, nam
total.hasUsage ||= providerSliceHasUsage(slice)
if (slice.inputTokens !== undefined) total.inputTokens = (total.inputTokens ?? 0) + slice.inputTokens
if (slice.outputTokens !== undefined) total.outputTokens = (total.outputTokens ?? 0) + slice.outputTokens
if (slice.sessions !== undefined) total.sessions = (total.sessions ?? 0) + slice.sessions
// Per-day session ticks are not distinct identities. Keep the max day as a
// lower bound; never sum occupancy across dates.
if (slice.sessions !== undefined) total.sessions = Math.max(total.sessions ?? 0, slice.sessions)
totals[name] = total
}
@ -102,7 +107,8 @@ export function buildPeriodData(label: string, projects: ProjectSummary[]): Peri
savingsUSD: projects.reduce((s, p) => s + p.totalSavingsUSD, 0),
estimatedCostUSD: projects.reduce((s, p) => s + (p.totalEstimatedCostUSD ?? 0), 0),
calls: projects.reduce((s, p) => s + p.totalApiCalls, 0),
sessions: projects.reduce((s, p) => s + p.sessions.length, 0),
sessions: uniqueCanonicalSessionCountFromProjects(projects),
sessionCountBasis: 'identity',
inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens,
categories: Object.entries(catTotals)
.sort(([, a], [, b]) => b.cost - a.cost)
@ -504,6 +510,7 @@ export type IndexedDurableOverview = {
savingsUSD: number
calls: number
sessions: number
sessionCountBasis?: SessionCountBasis
inputTokens: number
outputTokens: number
cacheReadTokens: number
@ -574,7 +581,9 @@ export function buildDurableOverviewFromNormalizedIndex(
// Fields whose durable day rows cannot project under a project filter come
// from the same normalized period slice that feeds the visible detail panels.
const scan = buildPeriodData(periodInfo.label, scanProjects)
data.sessions = Math.max(data.sessions, scan.sessions)
const sessionCount = uniquePeriodSessionCount(scanProjects, days)
data.sessions = sessionCount.sessions
data.sessionCountBasis = sessionCount.basis
if (hasProjectFilter) {
data.inputTokens = scan.inputTokens
data.outputTokens = scan.outputTokens
@ -587,6 +596,7 @@ export function buildDurableOverviewFromNormalizedIndex(
savingsUSD: data.savingsUSD,
calls: data.calls,
sessions: data.sessions,
sessionCountBasis: data.sessionCountBasis,
inputTokens: data.inputTokens,
outputTokens: data.outputTokens,
cacheReadTokens: data.cacheReadTokens,
@ -737,9 +747,12 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
data.workflow = scanData.workflow
data.topReworkedFiles = scanData.topReworkedFiles
data.pricingCoverage = scanData.pricingCoverage
// Cache buckets a session on its START day, the scan on any ACTIVE day; both
// are lower bounds of distinct sessions, so max is the tightest safe bound.
data.sessions = Math.max(data.sessions, scanData.sessions)
// Daily occupancy ticks are not unique across a period (one session file
// active on two days is two ticks). Prefer canonical provider+sessionId
// from the live parse; occupancy remains only for source-dead days.
const sessionCount = uniquePeriodSessionCount(liveProjects, days)
data.sessions = sessionCount.sessions
data.sessionCountBasis = sessionCount.basis
// Tokens/models/categories have no per-project split in the day cache, so
// sliceDayToProject drops them (see there). Under a project filter they come
// from the live parse instead: exact for the filtered projects, bounded by
@ -768,6 +781,472 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, cache, todayAllDays, scanRange }
}
type PayloadProject = NonNullable<PeriodData['projects']>[number]
type PayloadSessionDetail = NonNullable<PayloadProject['sessionDetails']>[number]
/// Period unique-count key: provider + cwd/project + canonical sessionId.
/// Filename-colliding `sess.jsonl` in two folders stay distinct. Same file
/// spanning days stays one. Not fingerprint/cost/calls.
export function canonicalSessionCountKey(session: SessionSummary, projectPath?: string): string {
const loc = projectPath || session.workingDirectory || session.project
return `${inferSessionProvider(session)}\0${loc}\0${session.sessionId}`
}
export function uniqueCanonicalSessionCount(
sessions: Iterable<SessionSummary>,
projectPath?: string,
): number {
const ids = new Set<string>()
let anonymous = 0
for (const session of sessions) {
if (session.sessionId) ids.add(canonicalSessionCountKey(session, projectPath))
else anonymous += 1
}
return ids.size + anonymous
}
export function uniqueCanonicalSessionCountFromProjects(projects: Iterable<ProjectSummary>): number {
const ids = new Set<string>()
let anonymous = 0
for (const project of projects) {
for (const session of project.sessions) {
if (session.sessionId) ids.add(canonicalSessionCountKey(session, project.projectPath))
else anonymous += 1
}
}
return ids.size + anonymous
}
export function uniqueCanonicalSessionCountForProvider(
projects: Iterable<ProjectSummary>,
provider: string,
): number {
const ids = new Set<string>()
let anonymous = 0
for (const project of projects) {
for (const session of project.sessions) {
if (inferSessionProvider(session) !== provider) continue
if (session.sessionId) ids.add(canonicalSessionCountKey(session, project.projectPath))
else anonymous += 1
}
}
return ids.size + anonymous
}
/// Live unique IDs are a lower bound. Per-day cache ticks are another.
/// Never sum those bounds; never sum ticks across dates; never treat matching
/// counts as identity. Exact only when accounting did not use cache rows that
/// lack identities (including empty source-only data → 0).
export function boundSessionCount(
liveUnique: number,
cacheDayBound: number,
unknownCache: boolean,
): { sessions: number, basis: SessionCountBasis } {
if (!unknownCache) return { sessions: liveUnique, basis: 'identity' }
return { sessions: Math.max(liveUnique, cacheDayBound), basis: 'partial' }
}
export function maxDaySessionBound(days: Array<{ sessions?: number }>): number {
let max = 0
for (const day of days) {
const n = day.sessions ?? 0
if (n > max) max = n
}
return max
}
function hasUnknownCacheAccounting(entry: {
cost?: number
calls?: number
savingsUSD?: number
sessions?: number
inputTokens?: number
outputTokens?: number
cacheReadTokens?: number
cacheWriteTokens?: number
}): boolean {
return (entry.cost ?? 0) > 0
|| (entry.calls ?? 0) > 0
|| (entry.savingsUSD ?? 0) > 0
|| (entry.sessions ?? 0) > 0
|| (entry.inputTokens ?? 0) > 0
|| (entry.outputTokens ?? 0) > 0
|| (entry.cacheReadTokens ?? 0) > 0
|| (entry.cacheWriteTokens ?? 0) > 0
}
/// Cache rows have no session identities. Any retained accounting on a row
/// (cost, calls, tokens, savings, or a positive session tick) is unknown
/// provenance — including sessions 0 / absent. A truly empty row is not.
function dayLacksSessionIdentities(day: DailyEntry): boolean {
if (day.carried) return true
if (hasUnknownCacheAccounting(day)) return true
for (const project of Object.values(day.projects ?? {})) {
if (hasUnknownCacheAccounting(project)) return true
}
for (const slice of Object.values(day.providers ?? {})) {
if (hasUnknownCacheAccounting(slice)) return true
}
return false
}
export function uniquePeriodSessionCount(
liveProjects: ProjectSummary[],
days: DailyEntry[],
): { sessions: number, basis: SessionCountBasis } {
const liveUnique = uniqueCanonicalSessionCountFromProjects(liveProjects)
const unknownCache = days.some(dayLacksSessionIdentities)
return boundSessionCount(liveUnique, maxDaySessionBound(days), unknownCache)
}
function applyProviderSessionCounts(
providers: ProviderCost[],
liveProjects: ProjectSummary[],
unknownCache: boolean,
): void {
for (const provider of providers) {
const liveUnique = uniqueCanonicalSessionCountForProvider(liveProjects, provider.name)
if (!unknownCache) {
if (liveUnique > 0 || provider.sessions !== undefined) {
provider.sessions = liveUnique
provider.sessionCountBasis = 'identity'
}
continue
}
const cacheBound = provider.sessions ?? 0
const counted = boundSessionCount(liveUnique, cacheBound, true)
if (counted.sessions === 0 && provider.sessions === undefined && liveUnique === 0) {
if ((provider.cost ?? 0) > 0) {
provider.sessions = 0
provider.sessionCountBasis = 'partial'
}
continue
}
provider.sessions = counted.sessions
provider.sessionCountBasis = counted.basis
}
}
function sessionDetailsOf(sessions: SessionSummary[]): PayloadSessionDetail[] {
return [...sessions]
.sort((a, b) => b.totalCostUSD - a.totalCostUSD)
.slice(0, 10)
.map(s => ({
cost: s.totalCostUSD,
savingsUSD: s.totalSavingsUSD,
calls: s.apiCalls,
inputTokens: s.totalInputTokens,
outputTokens: sessionBillableOutputTokens(s),
date: s.firstTimestamp?.split('T')[0] ?? '',
models: Object.entries(s.modelBreakdown)
.map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD }))
.sort((a, b) => b.cost - a.cost)
.slice(0, 3),
}))
}
function displayBasename(path: string | undefined, fallback: string, home: string): string {
if (!path) return fallback
if (path === home || path === home + '/') return 'Home'
return path.replace(/\\/g, '/').split('/').filter(Boolean).pop() || fallback
}
function disambiguatedProjectName(
path: string | undefined,
basename: string,
fallback: string,
basenameCounts: Map<string, number>,
): string {
if (basename === 'Home') return 'Home'
if ((basenameCounts.get(basename) ?? 0) <= 1) return basename
const normalized = (path ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '')
const parts = normalized.split('/').filter(Boolean)
if (parts.length >= 2) return parts.slice(-2).join('/')
return normalized || fallback || basename
}
/// Join cache project slugs with live parse rows by abs-cwd identity (#1260).
/// Canonical identity is case-preserving: POSIX `/tmp/Case/Vault` and
/// `/tmp/case/vault` are distinct. Same cwd across providers coalesces once;
/// distinct cwd with the same basename stays distinct.
///
/// Explicit known cache paths are identities of their own — a later day of the
/// same slug at a different path does not fold into the first path. Pathless
/// cache days attach only when cache+live agree on exactly one known identity.
/// Otherwise the pathless total stays at the legacy slug (unallocated) and is
/// cache-authoritative for matching live rows of that slug: do not add those
/// live costs again. A truly different live-only slug at a cwd still counts.
///
/// Cost/savings stay per-contributor (cache ?? live) except for the
/// unallocated matching-slug case above. Session *counts* are live unique IDs
/// when accounting is source-only; any cache row without identities is a
/// lower bound (max of live unique and the max per-day tick, never a sum).
/// Session details follow the same allocation: only matching sessions, never
/// the whole grouped project, and an unresolved legacy row does not inherit a
/// live folder path or name.
export function buildPayloadProjects(
scanProjects: ProjectSummary[],
cacheDays: DailyEntry[] | null,
home: string,
): PayloadProject[] {
type Contrib = {
cacheCost: number
cacheSavings: number
cacheSessions: number
cacheSessionDays: number
cacheMaxDaySessions: number
cacheCalls: number
hasCache: boolean
liveCost: number
liveSavings: number
liveSessions: number
}
type Acc = {
id: string
path?: string
fallbackName: string
contribs: Map<string, Contrib>
sessions: SessionSummary[]
}
const byKey = new Map<string, Acc>()
const take = (project: string, projectPath: string | undefined, fallbackName: string): Acc => {
const ident = spendProjectIdentity({ project, projectPath })
const key = ident.id
let acc = byKey.get(key)
if (!acc) {
acc = {
id: ident.id,
path: projectPath,
fallbackName,
contribs: new Map(),
sessions: [],
}
byKey.set(key, acc)
} else if (projectPath && !acc.path) {
acc.path = projectPath
acc.id = ident.id
}
return acc
}
const contribOf = (acc: Acc, slug: string): Contrib => {
let c = acc.contribs.get(slug)
if (!c) {
c = {
cacheCost: 0,
cacheSavings: 0,
cacheSessions: 0,
cacheSessionDays: 0,
cacheMaxDaySessions: 0,
cacheCalls: 0,
hasCache: false,
liveCost: 0,
liveSavings: 0,
liveSessions: 0,
}
acc.contribs.set(slug, c)
}
return c
}
const addSessionOnce = (acc: Acc, s: SessionSummary): void => {
if (!acc.sessions.includes(s)) acc.sessions.push(s)
}
const placeCache = (
slug: string,
path: string | undefined,
cost: number,
savingsUSD: number,
occupancy: { sessions: number, sessionDays: number, maxDaySessions: number, calls: number },
): Acc => {
const acc = take(slug, path, slug)
const c = contribOf(acc, slug)
c.hasCache = true
c.cacheCost += cost
c.cacheSavings += savingsUSD
c.cacheCalls += occupancy.calls
c.cacheSessions += occupancy.sessions
c.cacheSessionDays += occupancy.sessionDays
if (occupancy.maxDaySessions > c.cacheMaxDaySessions) c.cacheMaxDaySessions = occupancy.maxDaySessions
return acc
}
const livePathsBySlug = new Map<string, Set<string>>()
const rememberLiveSlug = (slug: string, projectPath: string | undefined): void => {
if (!projectPath) return
const id = spendProjectIdentity({ project: slug, projectPath }).id
let paths = livePathsBySlug.get(slug)
if (!paths) {
paths = new Set()
livePathsBySlug.set(slug, paths)
}
paths.add(id)
}
for (const p of scanProjects) {
rememberLiveSlug(p.project, p.projectPath)
for (const s of p.sessions) rememberLiveSlug(s.project, p.projectPath)
}
type Totals = { cost: number; savingsUSD: number; sessions: number; sessionDays: number; maxDaySessions: number; calls: number }
const knownBySlug = new Map<string, Map<string, Totals>>()
const pathlessBySlug = new Map<string, Totals>()
const emptyTotals = (): Totals => ({ cost: 0, savingsUSD: 0, sessions: 0, sessionDays: 0, maxDaySessions: 0, calls: 0 })
const addTotals = (into: Totals, cost: number, savingsUSD: number, sessions: number, calls: number): void => {
into.cost += cost
into.savingsUSD += savingsUSD
into.calls += calls
into.sessions += sessions
if (sessions > 0) {
into.sessionDays += 1
if (sessions > into.maxDaySessions) into.maxDaySessions = sessions
}
}
if (cacheDays) {
for (const d of cacheDays) {
for (const [name, p] of Object.entries(d.projects ?? {})) {
if (p.path) {
const id = spendProjectIdentity({ project: name, projectPath: p.path }).id
let byId = knownBySlug.get(name)
if (!byId) {
byId = new Map()
knownBySlug.set(name, byId)
}
const acc = byId.get(id) ?? emptyTotals()
addTotals(acc, p.cost, p.savingsUSD, p.sessions, p.calls)
byId.set(id, acc)
} else {
const acc = pathlessBySlug.get(name) ?? emptyTotals()
addTotals(acc, p.cost, p.savingsUSD, p.sessions, p.calls)
pathlessBySlug.set(name, acc)
}
}
}
}
const cacheIdentities = new Map<string, Set<string>>()
const unallocatedSlugs = new Set<string>()
const rememberCacheIdentity = (slug: string, id: string): void => {
let ids = cacheIdentities.get(slug)
if (!ids) {
ids = new Set()
cacheIdentities.set(slug, ids)
}
ids.add(id)
}
for (const [slug, byId] of knownBySlug) {
for (const [id, totals] of byId) {
placeCache(slug, id, totals.cost, totals.savingsUSD, totals)
rememberCacheIdentity(slug, id)
}
}
for (const [slug, totals] of pathlessBySlug) {
const known = new Set(cacheIdentities.get(slug) ?? [])
for (const id of livePathsBySlug.get(slug) ?? []) known.add(id)
if (known.size === 1) {
const id = [...known][0]!
placeCache(slug, id, totals.cost, totals.savingsUSD, totals)
rememberCacheIdentity(slug, id)
} else {
const acc = placeCache(slug, undefined, totals.cost, totals.savingsUSD, totals)
unallocatedSlugs.add(slug)
rememberCacheIdentity(slug, acc.id)
}
}
const policyFor = (slug: string, liveId: string): 'use-cache' | 'use-live' | 'suppress' => {
if (cacheIdentities.get(slug)?.has(liveId)) return 'use-cache'
if (unallocatedSlugs.has(slug)) return 'suppress'
return 'use-live'
}
for (const p of scanProjects) {
const liveId = spendProjectIdentity({ project: p.project, projectPath: p.projectPath }).id
if (p.sessions.length === 0) {
const policy = policyFor(p.project, liveId)
if (policy === 'suppress') continue
const acc = take(p.project, p.projectPath, p.project)
if (policy === 'use-live') {
const c = contribOf(acc, p.project)
c.liveCost += p.totalCostUSD
c.liveSavings += p.totalSavingsUSD
}
continue
}
for (const s of p.sessions) {
const policy = policyFor(s.project, liveId)
if (policy === 'suppress') {
const cacheAcc = byKey.get(s.project)
if (cacheAcc) addSessionOnce(cacheAcc, s)
continue
}
const acc = take(p.project, p.projectPath, p.project)
addSessionOnce(acc, s)
const c = contribOf(acc, s.project)
if (policy === 'use-live') {
c.liveCost += s.totalCostUSD
c.liveSavings += s.totalSavingsUSD
c.liveSessions += 1
} else {
c.liveSessions += 1
}
}
}
const rows = [...byKey.values()].map(acc => {
const path = acc.path
let cost = 0
let savingsUSD = 0
for (const c of acc.contribs.values()) {
cost += c.hasCache ? c.cacheCost : c.liveCost
savingsUSD += c.hasCache ? c.cacheSavings : c.liveSavings
}
const liveUnique = uniqueCanonicalSessionCount(acc.sessions, acc.path)
let cacheDayBound = 0
let unknownCache = false
for (const c of acc.contribs.values()) {
if (!c.hasCache) continue
if (
c.cacheCost > 0
|| c.cacheSavings > 0
|| c.cacheCalls > 0
|| c.cacheSessions > 0
|| c.cacheMaxDaySessions > 0
) {
unknownCache = true
}
if (c.cacheMaxDaySessions > cacheDayBound) cacheDayBound = c.cacheMaxDaySessions
}
const counted = boundSessionCount(liveUnique, cacheDayBound, unknownCache)
const sessions = counted.sessions
const sessionCountBasis = counted.basis
return {
acc,
path,
basename: displayBasename(path, acc.fallbackName, home),
cost,
savingsUSD,
sessions,
sessionCountBasis,
}
})
const basenameCounts = new Map<string, number>()
for (const row of rows) basenameCounts.set(row.basename, (basenameCounts.get(row.basename) ?? 0) + 1)
return rows
.map(({ acc, path, basename, cost, savingsUSD, sessions, sessionCountBasis }) => {
const details = sessionDetailsOf(acc.sessions)
return {
id: acc.id,
name: disambiguatedProjectName(path, basename, acc.fallbackName, basenameCounts),
cost,
savingsUSD,
sessions,
sessionCountBasis,
...(details.length ? { sessionDetails: details } : {}),
}
})
.sort((a, b) => b.cost - a.cost)
}
/**
* Resolved-range aggregation shared by `status --format menubar-json` and the MCP server.
* Pricing must already be loaded (callers run loadPricing first). When opts.optimize is
@ -931,6 +1410,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
inputTokens: currentData.inputTokens,
outputTokens: currentData.outputTokens,
sessions: currentData.sessions,
sessionCountBasis: currentData.sessionCountBasis,
hasUsage: currentData.cost > 0
|| currentData.savingsUSD > 0
|| currentData.calls > 0
@ -942,6 +1422,15 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
})
}
if (isAllProviders || (isClaudeConfigScoped && effectivelyScoped)) {
applyProviderSessionCounts(
providers,
scanProjects,
!(isClaudeConfigScoped && effectivelyScoped)
&& (cacheDaysForPeriod ?? []).some(dayLacksSessionIdentities),
)
}
// DAILY HISTORY (last 365 days)
// Cache stores per-provider cost+calls per day in DailyEntry.providers, so we can derive
// a provider-filtered history without re-parsing. Tokens aren't broken down per provider
@ -977,65 +1466,18 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
return path.split('/').filter(Boolean).pop() || fallback
}
const friendlyProject = (p: ProjectSummary) => friendlyFromPath(p.projectPath || p.project, p.project)
const sessionDetailsOf = (p: ProjectSummary) => [...p.sessions]
.sort((a, b) => b.totalCostUSD - a.totalCostUSD)
.slice(0, 10)
.map(s => ({
cost: s.totalCostUSD,
savingsUSD: s.totalSavingsUSD,
calls: s.apiCalls,
inputTokens: s.totalInputTokens,
outputTokens: sessionBillableOutputTokens(s),
date: s.firstTimestamp?.split('T')[0] ?? '',
models: Object.entries(s.modelBreakdown)
.map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD }))
.sort((a, b) => b.cost - a.cost)
.slice(0, 3),
}))
if (cacheDaysForPeriod !== null) {
// Project totals come from the SAME day set as the headline, so carried
// days count here too. The surviving-session parse contributes only what
// day entries cannot: the per-session drill-down and a fresher project
// path. Days recorded before the projects rollup existed have totals but
// no project split, so this list can sum to less than the headline — an
// honest gap, not a bug.
type CachedProjectTotal = { cost: number; savingsUSD: number; sessions: number; path?: string }
const cachedTotals = new Map<string, CachedProjectTotal>()
for (const d of cacheDaysForPeriod) {
for (const [name, p] of Object.entries(d.projects ?? {})) {
const acc = cachedTotals.get(name) ?? { cost: 0, savingsUSD: 0, sessions: 0 }
acc.cost += p.cost
acc.savingsUSD += p.savingsUSD
acc.sessions += p.sessions
if (!acc.path && p.path) acc.path = p.path
cachedTotals.set(name, acc)
}
}
const liveByName = new Map(scanProjects.map(p => [p.project, p]))
const names = new Set([...cachedTotals.keys(), ...liveByName.keys()])
currentData.projects = [...names].map(name => {
const cached = cachedTotals.get(name)
const live = liveByName.get(name)
return {
name: live ? friendlyProject(live) : friendlyFromPath(cached?.path, name),
cost: cached?.cost ?? live!.totalCostUSD,
savingsUSD: cached?.savingsUSD ?? live!.totalSavingsUSD,
// max for the same reason as the headline: start-day bucketing vs
// active-day counting, both lower bounds of distinct sessions.
sessions: Math.max(cached?.sessions ?? 0, live?.sessions.length ?? 0),
...(live ? { sessionDetails: sessionDetailsOf(live) } : {}),
}
}).sort((a, b) => b.cost - a.cost)
} else {
currentData.projects = scanProjects.map(p => ({
name: friendlyProject(p),
cost: p.totalCostUSD,
savingsUSD: p.totalSavingsUSD,
sessions: p.sessions.length,
sessionDetails: sessionDetailsOf(p),
}))
}
// Project totals come from the SAME day set as the headline when a cache
// day set exists, so carried days count here too. Join is by case-preserving
// abs-cwd identity, not provider slug: same cwd coalesces once; distinct cwd
// with the same basename stays distinct. Explicit known cache paths never
// fold into each other; pathless cache attaches only when cache+live agree
// on one identity. Ambiguous pathless cache stays at the legacy slug and is
// authoritative for matching live rows of that slug. Cost is per-contributor
// (cache ?? live) otherwise. Days recorded before the projects rollup existed
// have totals but no project split, so this list can sum to less than the
// headline — an honest gap.
currentData.projects = buildPayloadProjects(scanProjects, cacheDaysForPeriod, home)
const effMap = aggregateModelEfficiency(scanProjects)
currentData.modelEfficiency = [...effMap.entries()].map(([name, eff]) => ({