chompyy 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6955 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,1342 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFileSync, statSync } from 'fs';
3
+ import { behavioralCallCount, behavioralTurnCount } from './behavioral-weight.js';
4
+ import { flatString } from './content-utils.js';
5
+ import { ESTIMATED_COST_LEGEND, isEstimatedCost, markEstimated } from './format.js';
6
+ import { modelRowKey } from './models.js';
7
+ import { maxOf } from './math-utils.js';
8
+ import { callCommands, createHead, ghPrCommands, isCommit, namedPr, namedPrNumber, prNumbersIn, pushes, readPrNumbers, readsCode, reviewVerdict, roundStarts } from './pr-signals.js';
9
+ import { costBasisShares, inferSessionProvider, sessionBillableOutputTokens } from './session-output.js';
10
+ import { CATEGORY_LABELS } from './types.js';
11
+ import { resolveWorkUnits, workUnitSessionKey } from './work-units.js';
12
+ function sessionCostLabel(cost) {
13
+ return `$${cost.toFixed(2)}`;
14
+ }
15
+ export function sessionCacheHitPercent(input, reads, writes) {
16
+ return reads + writes === 0 ? null : reads / (input + reads + writes) * 100;
17
+ }
18
+ export function cacheHitLabel(percent) {
19
+ return percent === null ? '\u2014' : `${Math.round(percent)}%`;
20
+ }
21
+ function durationMs(startedAt, endedAt) {
22
+ const duration = new Date(endedAt).getTime() - new Date(startedAt).getTime();
23
+ return Number.isFinite(duration) ? duration : 0;
24
+ }
25
+ export function aggregateSessions(projects) {
26
+ return projects.flatMap(project => project.sessions.map(session => ({
27
+ sessionId: session.sessionId,
28
+ title: session.title ?? '',
29
+ project: session.project || project.project,
30
+ provider: inferSessionProvider(session),
31
+ models: Object.keys(session.modelBreakdown),
32
+ cost: session.totalCostUSD,
33
+ savingsUSD: session.totalSavingsUSD,
34
+ calls: session.apiCalls,
35
+ turns: behavioralTurnCount(session.turns),
36
+ inputTokens: session.totalInputTokens,
37
+ outputTokens: sessionBillableOutputTokens(session),
38
+ cacheReadTokens: session.totalCacheReadTokens,
39
+ cacheWriteTokens: session.totalCacheWriteTokens,
40
+ cacheHitPercent: sessionCacheHitPercent(session.totalInputTokens, session.totalCacheReadTokens, session.totalCacheWriteTokens),
41
+ startedAt: session.firstTimestamp,
42
+ endedAt: session.lastTimestamp,
43
+ durationMs: durationMs(session.firstTimestamp, session.lastTimestamp),
44
+ estimatedCost: session.totalEstimatedCostUSD ?? 0,
45
+ isEstimated: isEstimatedCost(session.totalCostUSD, session.totalEstimatedCostUSD, sessionCostLabel(session.totalCostUSD)),
46
+ costBasis: costBasisShares(session.turns.flatMap(turn => turn.assistantCalls)),
47
+ ...(session.retained ? { retained: session.retained } : {}),
48
+ ...(session.identity ? { identity: session.identity } : {}),
49
+ })));
50
+ }
51
+ export function renderJson(rows) {
52
+ return JSON.stringify(rows, null, 2);
53
+ }
54
+ function defaultTerminalWidth() {
55
+ const cols = process.stdout.columns;
56
+ if (typeof cols === 'number' && cols > 0)
57
+ return cols;
58
+ const env = process.env['COLUMNS'] ? Number.parseInt(process.env['COLUMNS'], 10) : NaN;
59
+ return Number.isFinite(env) && env > 0 ? env : 120;
60
+ }
61
+ function frameWidth(columns) {
62
+ // Outer borders + one space either side of each cell + inner separators.
63
+ return 2 + columns.reduce((sum, col) => sum + col.width + 2, 0) + Math.max(0, columns.length - 1);
64
+ }
65
+ function fitColumns(columns, available, dropOrder) {
66
+ const fitted = columns.map(col => ({ ...col }));
67
+ // Remove low-value columns before squeezing names into unreadable slivers.
68
+ for (const key of dropOrder ?? ['turns', 'saved', 'provider', 'calls', 'cache']) {
69
+ if (frameWidth(fitted) <= available)
70
+ break;
71
+ const index = fitted.findIndex(col => col.key === key && col.optional);
72
+ if (index >= 0)
73
+ fitted.splice(index, 1);
74
+ }
75
+ while (frameWidth(fitted) > available) {
76
+ const shrinkable = fitted
77
+ .filter(col => col.width > col.minWidth)
78
+ .sort((a, b) => (b.flex ?? 0) - (a.flex ?? 0) || b.width - a.width);
79
+ const col = shrinkable[0];
80
+ if (!col)
81
+ break;
82
+ col.width--;
83
+ }
84
+ return fitted;
85
+ }
86
+ function truncate(value, width) {
87
+ if (value.length <= width)
88
+ return value;
89
+ if (width <= 1)
90
+ return value.slice(0, width);
91
+ return value.slice(0, width - 1) + '\u2026';
92
+ }
93
+ export function cleanSessionProjectLabel(raw) {
94
+ const normalized = raw.trim().replace(/\\/g, '/').replace(/\/+$/, '');
95
+ if (!normalized)
96
+ return 'Unknown';
97
+ if (normalized.startsWith('/')) {
98
+ const parts = normalized.split('/').filter(Boolean);
99
+ if (normalized === '/private/tmp' || normalized === '/tmp')
100
+ return 'Temporary';
101
+ return parts.at(-1) || 'Unknown';
102
+ }
103
+ // Claude stores a cwd such as /Users/alex/Projects/acme/app as the lossy
104
+ // directory slug -Users-alex-Projects-acme-app. Strip the private home
105
+ // prefix and known workspace container without ever exposing the username.
106
+ let label = normalized.replace(/^-?Users-[^-]+-/, '');
107
+ label = label.replace(/^(Projects|Developer|Documents|Desktop|Downloads)-/, '');
108
+ if (label === 'private-tmp' || label === '-private-tmp')
109
+ return 'Temporary';
110
+ const worktreeMarker = label.match(/(?:--|-\.claude-|-)(?:claude-)?worktrees-/);
111
+ if (worktreeMarker?.index !== undefined) {
112
+ const base = label.slice(0, worktreeMarker.index);
113
+ let branch = label.slice(worktreeMarker.index + worktreeMarker[0].length);
114
+ const baseParts = base.split('-').filter(Boolean);
115
+ const repo = baseParts.at(-1) || base;
116
+ if (branch.startsWith('agent-'))
117
+ branch = `agent ${branch.slice(6, 14)}`;
118
+ return branch ? `${repo} · ${branch}` : repo;
119
+ }
120
+ // Repeated repository leaves are common after canonical worktree folding
121
+ // (Projects/eywa/eywa). Collapse that noisy shape.
122
+ const parts = label.split('-').filter(Boolean);
123
+ if (parts.length >= 2 && parts.at(-1) === parts.at(-2))
124
+ return parts.at(-1);
125
+ return label || 'Unknown';
126
+ }
127
+ export function shortSessionId(value) {
128
+ const id = value.trim();
129
+ if (id.startsWith('agent-'))
130
+ return `Agent ${id.slice(6, 14)}`;
131
+ if (id.startsWith('rollout-')) {
132
+ const tail = id.match(/([0-9a-f]{8})-[0-9a-f-]{27,}$/i)?.[1];
133
+ return `Codex ${tail ?? id.slice(-8)}`;
134
+ }
135
+ if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(id))
136
+ return `${id.slice(0, 8)}\u2026${id.slice(-4)}`;
137
+ return id.length > 24 ? `${id.slice(0, 12)}\u2026${id.slice(-6)}` : id || 'Unknown session';
138
+ }
139
+ export function sessionDisplayName(row) {
140
+ return row.title.trim() || shortSessionId(row.sessionId);
141
+ }
142
+ export function sessionModelLabel(models) {
143
+ const visible = models.filter(model => model !== '<synthetic>');
144
+ return (visible.length > 0 ? visible : models).map(m => modelRowKey(m)).join(', ') || 'Unknown';
145
+ }
146
+ function cellValue(row, key) {
147
+ switch (key) {
148
+ case 'started': return (row.startedAt ? row.startedAt.replace('T', ' ').slice(0, 16) : '-') + (row.retained ? RETAINED_MARK : '');
149
+ case 'session': return sessionDisplayName(row);
150
+ // Only the work-unit view carries a Children column, and it renders
151
+ // through workUnitCell; a bare SessionRow has no child count.
152
+ case 'children': return '';
153
+ case 'project': return cleanSessionProjectLabel(row.project);
154
+ case 'provider': return row.provider;
155
+ case 'models': return sessionModelLabel(row.models);
156
+ case 'cost': return markEstimated(sessionCostLabel(row.cost), row.isEstimated);
157
+ case 'cache': return cacheHitLabel(row.cacheHitPercent);
158
+ case 'saved': return `$${row.savingsUSD.toFixed(2)}`;
159
+ case 'calls': return row.calls.toLocaleString('en-US');
160
+ case 'turns': return row.turns.toLocaleString('en-US');
161
+ }
162
+ }
163
+ /// Shared bordered-grid renderer. `cell` produces the raw string for one item
164
+ /// and column; fitting, width expansion, and borders are identical for every
165
+ /// table this module emits, so the default sessions table stays byte-identical.
166
+ function renderSessionGrid(columns, items, cell, footer, available, dropOrder) {
167
+ const fitted = fitColumns(columns, available, dropOrder);
168
+ const values = items.map(item => fitted.map(col => cell(item, col.key)));
169
+ // Content can use spare room, but never grow beyond the terminal frame.
170
+ for (let i = 0; i < fitted.length; i++) {
171
+ const col = fitted[i];
172
+ const longest = maxOf(values.map(row => row[i]?.length ?? 0), col.header.length);
173
+ const spare = available - frameWidth(fitted);
174
+ const wanted = Math.max(0, Math.min(longest - col.width, spare));
175
+ col.width += wanted;
176
+ }
177
+ const border = (left, middle, right) => left + fitted.map(col => '\u2500'.repeat(col.width + 2)).join(middle) + right;
178
+ const line = (cells) => '\u2502' + fitted.map((col, i) => {
179
+ const value = truncate(cells[i] ?? '', col.width);
180
+ const padding = ' '.repeat(Math.max(0, col.width - value.length));
181
+ return ` ${col.right ? padding + value : value + padding} `;
182
+ }).join('\u2502') + '\u2502';
183
+ return [
184
+ border('\u250c', '\u252c', '\u2510'),
185
+ line(fitted.map(col => col.header)),
186
+ border('\u251c', '\u253c', '\u2524'),
187
+ ...values.map(line),
188
+ border('\u2514', '\u2534', '\u2518'),
189
+ footer,
190
+ ].join('\n');
191
+ }
192
+ function sessionColumns(hasSavings, childrenColumn) {
193
+ return [
194
+ { key: 'started', header: 'Started', width: 16, minWidth: 10 },
195
+ { key: 'session', header: 'Session', width: 30, minWidth: 12, flex: 3 },
196
+ ...(childrenColumn ? [{ key: 'children', header: 'Children', width: 8, minWidth: 5, right: true, optional: true }] : []),
197
+ { key: 'project', header: 'Project', width: 24, minWidth: 10, flex: 2 },
198
+ { key: 'provider', header: 'Provider', width: 9, minWidth: 8, optional: true },
199
+ { key: 'models', header: 'Models', width: 22, minWidth: 10, flex: 2 },
200
+ { key: 'cost', header: 'Cost', width: 9, minWidth: 7, right: true },
201
+ { key: 'cache', header: 'Cache', width: 6, minWidth: 6, right: true, optional: true },
202
+ ...(hasSavings ? [{ key: 'saved', header: 'Saved', width: 9, minWidth: 7, right: true, optional: true }] : []),
203
+ { key: 'calls', header: 'Calls', width: 7, minWidth: 5, right: true, optional: true },
204
+ { key: 'turns', header: 'Turns', width: 7, minWidth: 5, right: true, optional: true },
205
+ ];
206
+ }
207
+ const RETAINED_MARK = '*';
208
+ function estimatedLegend(rows) {
209
+ return (rows.some(row => row.isEstimated) ? `\n${ESTIMATED_COST_LEGEND}` : '')
210
+ + (rows.some(row => row.retained) ? `\n${RETAINED_MARK} kept from the cache after the tool removed its transcript` : '');
211
+ }
212
+ export function renderTable(rows, opts = {}) {
213
+ const sorted = [...rows].sort((a, b) => b.startedAt.localeCompare(a.startedAt));
214
+ const hasSavings = sorted.some(row => row.savingsUSD > 0);
215
+ const available = Math.max(60, opts.terminalWidth ?? defaultTerminalWidth());
216
+ const totalCost = sorted.reduce((sum, row) => sum + row.cost, 0);
217
+ const footer = `${sorted.length.toLocaleString('en-US')} sessions \u2022 $${totalCost.toFixed(2)} total \u2022 newest first${estimatedLegend(sorted)}`;
218
+ return renderSessionGrid(sessionColumns(hasSavings, false), sorted, cellValue, footer, available);
219
+ }
220
+ function workUnitCell(display, key) {
221
+ if (key === 'children')
222
+ return display.childCount > 0 ? String(display.childCount) : '';
223
+ if (key === 'session') {
224
+ const name = sessionDisplayName(display.row);
225
+ return display.depth === 1 ? ` \u21b3 ${name}` : name;
226
+ }
227
+ return cellValue(display.row, key);
228
+ }
229
+ function groupWorkUnitRows(rows, resolution) {
230
+ const unitById = new Map(resolution.units.map(unit => [unit.workUnitId, unit]));
231
+ const unitOf = (row) => {
232
+ const unitId = resolution.bySession.get(workUnitSessionKey(row.provider, row.sessionId));
233
+ const unit = unitId !== undefined ? unitById.get(unitId) : undefined;
234
+ return unit && unit.childSessionIds.length > 0 ? unit : undefined;
235
+ };
236
+ const membersByUnit = new Map();
237
+ for (const row of rows) {
238
+ const unit = unitOf(row);
239
+ if (!unit)
240
+ continue;
241
+ const list = membersByUnit.get(unit);
242
+ if (list)
243
+ list.push(row);
244
+ else
245
+ membersByUnit.set(unit, [row]);
246
+ }
247
+ const rootByUnit = new Map();
248
+ for (const [unit, members] of membersByUnit) {
249
+ const root = members.find(row => row.sessionId === unit.rootSessionId);
250
+ if (root && members.length >= 2)
251
+ rootByUnit.set(unit, root);
252
+ }
253
+ const entries = [];
254
+ for (const row of rows) {
255
+ const unit = unitOf(row);
256
+ const root = unit ? rootByUnit.get(unit) : undefined;
257
+ if (!unit || !root) {
258
+ entries.push({ row, root: row, children: [] });
259
+ continue;
260
+ }
261
+ if (row !== root)
262
+ continue;
263
+ const members = membersByUnit.get(unit);
264
+ const children = members
265
+ .filter(member => member !== root)
266
+ .sort((a, b) => b.startedAt.localeCompare(a.startedAt) || a.sessionId.localeCompare(b.sessionId));
267
+ const sum = (pick) => members.reduce((total, member) => total + pick(member), 0);
268
+ const startedAt = members.reduce((min, member) => (member.startedAt < min ? member.startedAt : min), root.startedAt);
269
+ const endedAt = members.reduce((max, member) => (member.endedAt > max ? member.endedAt : max), root.endedAt);
270
+ const models = [];
271
+ for (const member of [root, ...children]) {
272
+ for (const model of member.models)
273
+ if (!models.includes(model))
274
+ models.push(model);
275
+ }
276
+ const cost = sum(member => member.cost);
277
+ const estimatedCost = sum(member => member.estimatedCost);
278
+ const inputTokens = sum(member => member.inputTokens);
279
+ const cacheReadTokens = sum(member => member.cacheReadTokens);
280
+ const cacheWriteTokens = sum(member => member.cacheWriteTokens);
281
+ entries.push({
282
+ row: {
283
+ ...root,
284
+ models,
285
+ cost,
286
+ estimatedCost,
287
+ isEstimated: isEstimatedCost(cost, estimatedCost, sessionCostLabel(cost)),
288
+ costBasis: costBasisShares(members.flatMap(member => Object.entries(member.costBasis ?? {})
289
+ .map(([basis, share]) => ({ costBasis: basis, costUSD: share * member.cost })))),
290
+ savingsUSD: sum(member => member.savingsUSD),
291
+ calls: sum(member => member.calls),
292
+ turns: sum(member => member.turns),
293
+ inputTokens,
294
+ outputTokens: sum(member => member.outputTokens),
295
+ cacheReadTokens,
296
+ cacheWriteTokens,
297
+ cacheHitPercent: sessionCacheHitPercent(inputTokens, cacheReadTokens, cacheWriteTokens),
298
+ startedAt,
299
+ endedAt,
300
+ durationMs: durationMs(startedAt, endedAt),
301
+ },
302
+ root,
303
+ children,
304
+ });
305
+ }
306
+ return entries;
307
+ }
308
+ /// The default sessions list: one row per parent session with its
309
+ /// provider-recorded subagent sessions (work-unit children) folded in, so the
310
+ /// parent's cost/calls/tokens include them and `subagents` lists them. Only
311
+ /// grouping changes: the rows still sum to exactly the ungrouped total.
312
+ export function foldSubagentRows(rows, resolution) {
313
+ return groupWorkUnitRows(rows, resolution).map(({ row, children }) => (children.length ? { ...row, subagents: children } : row));
314
+ }
315
+ /// Every session in `projects` with its subagents folded in as in the default
316
+ /// sessions list, each row tagged with the project summary it came from. Ranked
317
+ /// lists (top sessions) use this so a parent's cost includes its subagents and
318
+ /// a folded subagent never shows as its own row.
319
+ export function foldedSessionRows(projects) {
320
+ const resolution = resolveWorkUnits(projects.flatMap(summary => summary.sessions.map(session => ({
321
+ sessionId: session.sessionId,
322
+ provider: inferSessionProvider(session),
323
+ lineage: session.lineage,
324
+ }))));
325
+ return foldSubagentRows(projects.flatMap(summary => aggregateSessions([summary]).map(row => ({ ...row, summary }))), resolution);
326
+ }
327
+ /// The `sessions --by-work-unit` table: one row per multi-session work unit
328
+ /// (root's title/project, cost/calls/savings/turns summed over root+children,
329
+ /// child count in the Children column), its children indented beneath, and
330
+ /// every standalone session exactly as in the default table. Entries sort
331
+ /// newest-first by each unit's latest member activity. The footer total sums
332
+ /// top-level entries only, so the grouped view reconciles exactly with the
333
+ /// ungrouped table (no double count, no dropped spend).
334
+ export function renderWorkUnitTable(rows, resolution, opts = {}) {
335
+ const entries = groupWorkUnitRows(rows, resolution).map(({ row, root, children }) => ({
336
+ display: { row, depth: 0, childCount: children.length },
337
+ children: children.map(child => ({ row: child, depth: 1, childCount: 0 })),
338
+ sortKey: children.reduce((max, child) => (child.startedAt > max ? child.startedAt : max), root.startedAt),
339
+ }));
340
+ entries.sort((a, b) => b.sortKey.localeCompare(a.sortKey));
341
+ const displays = entries.flatMap(entry => [entry.display, ...entry.children]);
342
+ const hasSavings = rows.some(row => row.savingsUSD > 0);
343
+ const available = Math.max(60, opts.terminalWidth ?? defaultTerminalWidth());
344
+ // Money invariant: the footer sums TOP-LEVEL entries (unit aggregates plus
345
+ // standalone rows), never the indented child detail, so grouped and
346
+ // ungrouped views total the same spend.
347
+ const totalCost = entries.reduce((total, entry) => total + entry.display.row.cost, 0);
348
+ const unitCount = entries.filter(entry => entry.display.childCount > 0).length;
349
+ const footer = `${rows.length.toLocaleString('en-US')} sessions \u2022 ${unitCount.toLocaleString('en-US')} work unit${unitCount === 1 ? '' : 's'} \u2022 $${totalCost.toFixed(2)} total \u2022 newest first${estimatedLegend(displays.map(d => d.row))}`;
350
+ return renderSessionGrid(sessionColumns(hasSavings, true), displays, workUnitCell, footer, available, ['children', 'turns', 'saved', 'provider', 'calls', 'cache']);
351
+ }
352
+ /// `sessions --by-work-unit --format json`: an add-only envelope. `sessions`
353
+ /// is the flat per-session row array (subagents not folded); `workUnits` is
354
+ /// the resolver's full partition (standalone sessions included, so consumers
355
+ /// can reconcile counts and totals).
356
+ export function renderWorkUnitJson(rows, resolution) {
357
+ return JSON.stringify({ sessions: rows, workUnits: resolution.units }, null, 2);
358
+ }
359
+ const GITHUB_PR_RE = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/;
360
+ export function shortenPrUrl(url) {
361
+ const m = GITHUB_PR_RE.exec(url);
362
+ return m ? `${m[1]}/${m[2]}#${m[3]}` : url;
363
+ }
364
+ function addToMap(m, key, value) {
365
+ m.set(key, (m.get(key) ?? 0) + value);
366
+ }
367
+ function ensureContribution(map, url) {
368
+ let e = map.get(url);
369
+ if (!e) {
370
+ e = { cost: 0, calls: 0, savingsUSD: 0, approx: false, models: new Map(), categories: new Map(), firstTs: '', lastTs: '' };
371
+ map.set(url, e);
372
+ }
373
+ return e;
374
+ }
375
+ // Split an integer `total` across `n` buckets as evenly as possible, giving the
376
+ // first `total % n` buckets the extra unit (largest-remainder, deterministic by
377
+ // bucket order). Keeps per-PR call counts integral so aggregated rows never
378
+ // over- or under-count from independent per-row rounding (a 1-call, 2-PR turn
379
+ // allocates [1, 0], not [0.5, 0.5] that would each round up to 1).
380
+ export function allocateEven(total, n) {
381
+ const base = Math.floor(total / n);
382
+ const extra = total - base * n;
383
+ return Array.from({ length: n }, (_, i) => base + (i < extra ? 1 : 0));
384
+ }
385
+ function parseMs(ts) {
386
+ return ts ? Date.parse(ts) : NaN;
387
+ }
388
+ // A child "self-links" when it referenced its own PR: it then attributes
389
+ // standalone (its own turn-level attribution is more precise) and is NEVER folded
390
+ // into a parent, so its spend is counted exactly once. A child with no links is
391
+ // folded only. This mutual exclusion is what prevents a double-charge.
392
+ function selfLinks(session) {
393
+ return !!session.prLinks?.length;
394
+ }
395
+ // A session id alone is NOT globally unique: imported or duplicated transcripts,
396
+ // or two providers, can reuse one id, letting two parents claim one child and
397
+ // corrupting the attribution map. Key parents (and a child's parent reference) by
398
+ // provider + id so linkage stays one-to-one; the ambiguity skip in
399
+ // resolveSubagentAttribution handles a genuine same-provider id collision.
400
+ // Subagent linkage (parentSessionId / agentSpawnLinks / spawnPrSets) is Claude
401
+ // only, and a fold ANCHOR has no in-range turns to infer a provider from, so a
402
+ // linkage-bearing session is always attributed to 'claude'; this keeps a parent
403
+ // and its child on the same key.
404
+ // NUL delimiter for composite keys: it cannot appear in a provider name, project
405
+ // name, or session id, so keys never collide (a plain space collides for a name
406
+ // or id that contains a space).
407
+ const KEY_SEP = String.fromCharCode(0);
408
+ function linkageProvider(session) {
409
+ if (session.parentSessionId || session.agentSpawnLinks || session.spawnPrSets)
410
+ return 'claude';
411
+ return inferSessionProvider(session);
412
+ }
413
+ function providerSessionKey(session) {
414
+ return `${linkageProvider(session)}${KEY_SEP}${session.sessionId}`;
415
+ }
416
+ function providerParentKey(session) {
417
+ return `${linkageProvider(session)}${KEY_SEP}${session.parentSessionId ?? ''}`;
418
+ }
419
+ // Row-level distinct-session key: provider + project + sessionId, NUL-delimited so a
420
+ // project name or session id containing a space never collides (undercounting
421
+ // distinct sessions in a PR row).
422
+ function rowSessionKey(session) {
423
+ return `${linkageProvider(session)}${KEY_SEP}${session.project}${KEY_SEP}${session.sessionId}`;
424
+ }
425
+ // Recursive canonical normalizer: sorts every OBJECT's keys so serialization is
426
+ // order-independent, and preserves ARRAY order (the caller pre-sorts arrays whose
427
+ // semantics are set-like). Emitting the normalized structure through JSON.stringify
428
+ // (rather than delimiter concatenation) means no separator can collide across
429
+ // distinct inputs.
430
+ function canonicalize(value) {
431
+ if (Array.isArray(value))
432
+ return value.map(canonicalize);
433
+ if (value && typeof value === 'object') {
434
+ const out = {};
435
+ for (const k of Object.keys(value).sort()) {
436
+ out[k] = canonicalize(value[k]);
437
+ }
438
+ return out;
439
+ }
440
+ return value;
441
+ }
442
+ const sortedCopy = (a) => [...(a ?? [])].sort();
443
+ // A record whose value arrays are SET-semantic (sorted), for spawnPrSets.
444
+ function sortedRecord(rec) {
445
+ const out = {};
446
+ for (const k of Object.keys(rec ?? {}))
447
+ out[k] = sortedCopy(rec[k]);
448
+ return out;
449
+ }
450
+ // Distinguishes two DIFFERENT records that happen to share a session id (duplicate
451
+ // or imported data): identical copies produce the same fingerprint and fold once,
452
+ // any difference marks the key ambiguous so it folds into NEITHER parent/subtree.
453
+ // The fingerprint serializes the COMPLETE fold-determining state, canonically:
454
+ // session-level linkage AND the per-turn sequence (timestamp, prRefs, cost, calls,
455
+ // savings, per-model cost). Set-semantic fields (PR-ref lists, ambiguous ids,
456
+ // spawnPrSets values) are sorted; the turn list keeps its order (sequence-semantic).
457
+ function sessionFingerprint(s) {
458
+ return JSON.stringify(canonicalize({
459
+ cost: s.totalCostUSD,
460
+ calls: s.apiCalls,
461
+ first: s.firstTimestamp,
462
+ last: s.lastTimestamp,
463
+ parent: s.parentSessionId ?? '',
464
+ agent: s.agentId ?? '',
465
+ prLinks: sortedCopy(s.prLinks),
466
+ rangeStart: sortedCopy(s.prRefsAtRangeStart),
467
+ ambiguous: sortedCopy(s.ambiguousSpawnAgentIds),
468
+ spawnLinks: s.agentSpawnLinks ?? {},
469
+ spawnPrSets: sortedRecord(s.spawnPrSets),
470
+ turns: s.turns.map(t => {
471
+ const modelCost = {};
472
+ for (const c of t.assistantCalls)
473
+ if (c.model)
474
+ modelCost[c.model] = (modelCost[c.model] ?? 0) + c.costUSD;
475
+ return {
476
+ ts: t.assistantCalls[0]?.timestamp ?? t.timestamp ?? '',
477
+ prRefs: sortedCopy(t.prRefs),
478
+ cost: t.assistantCalls.reduce((n, c) => n + c.costUSD, 0),
479
+ calls: behavioralCallCount(t.assistantCalls),
480
+ savings: t.assistantCalls.reduce((n, c) => n + (c.savingsUSD ?? 0), 0),
481
+ models: modelCost,
482
+ };
483
+ }),
484
+ }));
485
+ }
486
+ /// Provider-aware, fingerprint-qualified identity of a session: two sessions share
487
+ /// it ONLY when they are the same provider+id AND a proven-identical record. Used to
488
+ /// dedupe a fold anchor against a genuinely-identical surviving session without
489
+ /// dropping a different-provider or different-record session that shares a raw id.
490
+ export function sessionIdentity(session) {
491
+ return `${providerSessionKey(session)}${KEY_SEP}${sessionFingerprint(session)}`;
492
+ }
493
+ /// Index every sidechain (subagent) session by the parent that spawned it, keyed
494
+ /// by provider + `parentSessionId`. A child whose parent is absent from the scan
495
+ /// is never looked up, so it stays a standalone orphan.
496
+ export function buildSubagentIndex(projects) {
497
+ const index = new Map();
498
+ for (const project of projects)
499
+ for (const session of project.sessions) {
500
+ if (!session.parentSessionId)
501
+ continue;
502
+ const key = providerParentKey(session);
503
+ const list = index.get(key);
504
+ if (list)
505
+ list.push(session);
506
+ else
507
+ index.set(key, [session]);
508
+ }
509
+ return index;
510
+ }
511
+ // Read on demand rather than at parse: only folded runs and runs that push need
512
+ // it. Keyed by mtime so a long-lived `serve` re-reads only a changed sidecar.
513
+ const agentDescriptions = new Map();
514
+ function agentDescriptionOf(session) {
515
+ const path = session.agentMetaPath;
516
+ if (!path)
517
+ return '';
518
+ try {
519
+ const { mtimeMs } = statSync(path);
520
+ const hit = agentDescriptions.get(path);
521
+ if (hit?.mtimeMs === mtimeMs)
522
+ return hit.description;
523
+ const d = JSON.parse(readFileSync(path, 'utf8')).description;
524
+ const description = typeof d === 'string' && d.trim() ? flatString(d.trim().slice(0, 200)) : '';
525
+ agentDescriptions.set(path, { mtimeMs, description });
526
+ return description;
527
+ }
528
+ catch {
529
+ return '';
530
+ }
531
+ }
532
+ // Aggregate a child session and its non-self-linking descendants, depth-first.
533
+ // `claimed` is ONE set per parent resolution (shared across all direct children),
534
+ // so a descendant reachable through two paths (duplicate/diamond ids) folds
535
+ // exactly once and a parent-link cycle terminates. A self-linking descendant is
536
+ // skipped: it attributes standalone. `spawnAtMs` stays the TOP child's, since the
537
+ // whole subtree resolves against the top parent.
538
+ function buildChildFold(child, index, claimed, ambiguous, scanCommands) {
539
+ claimed.add(child.sessionId);
540
+ const models = new Map();
541
+ const categories = new Map();
542
+ let pushed = false;
543
+ let committed = false;
544
+ let reads = false;
545
+ const readPrs = new Set();
546
+ const prNumbers = new Set();
547
+ const branches = new Set();
548
+ let upstream;
549
+ for (const turn of child.turns) {
550
+ let turnCost = 0;
551
+ for (const call of turn.assistantCalls) {
552
+ turnCost += call.costUSD;
553
+ if (call.model)
554
+ addToMap(models, call.model, call.costUSD);
555
+ if (scanCommands)
556
+ for (const cmd of callCommands(call)) {
557
+ for (const named of pushes(cmd)) {
558
+ pushed = true;
559
+ if (named.length)
560
+ upstream = named.at(-1);
561
+ for (const b of named.length ? named : upstream ? [upstream] : [])
562
+ branches.add(b);
563
+ }
564
+ if (isCommit(cmd))
565
+ committed = true;
566
+ if (readsCode(cmd))
567
+ reads = true;
568
+ for (const n of readPrNumbers(cmd))
569
+ readPrs.add(n);
570
+ for (const n of prNumbersIn(cmd))
571
+ prNumbers.add(n);
572
+ }
573
+ }
574
+ if (turn.category)
575
+ addToMap(categories, turn.category, turnCost);
576
+ }
577
+ const description = agentDescriptionOf(child);
578
+ const fold = {
579
+ agentId: child.agentId ?? child.sessionId,
580
+ cost: child.totalCostUSD, calls: child.apiCalls, savingsUSD: child.totalSavingsUSD,
581
+ spawnAtMs: parseMs(child.firstTimestamp),
582
+ firstTs: child.firstTimestamp, lastTs: child.lastTimestamp,
583
+ models, categories, foldedSessions: 1,
584
+ named: namedPr(description),
585
+ ...(child.agentType ? { agentType: child.agentType } : {}),
586
+ mentioned: namedPrNumber(description),
587
+ pushed, committed, readsCode: reads, readPrs, prNumbers, branches, description,
588
+ };
589
+ for (const gc of index.get(providerSessionKey(child)) ?? []) {
590
+ // Skip a descendant whose id is ambiguous (two conflicting records share it):
591
+ // fold neither, consistent with the parent-level rule.
592
+ if (claimed.has(gc.sessionId) || selfLinks(gc) || ambiguous.has(providerSessionKey(gc)))
593
+ continue;
594
+ const gcf = buildChildFold(gc, index, claimed, ambiguous, scanCommands);
595
+ fold.cost += gcf.cost;
596
+ fold.calls += gcf.calls;
597
+ fold.savingsUSD += gcf.savingsUSD;
598
+ fold.foldedSessions += gcf.foldedSessions;
599
+ fold.pushed ||= gcf.pushed;
600
+ fold.committed ||= gcf.committed;
601
+ fold.readsCode ||= gcf.readsCode;
602
+ for (const n of gcf.readPrs)
603
+ fold.readPrs.add(n);
604
+ for (const n of gcf.prNumbers)
605
+ fold.prNumbers.add(n);
606
+ for (const b of gcf.branches)
607
+ fold.branches.add(b);
608
+ for (const [m, c] of gcf.models)
609
+ addToMap(fold.models, m, c);
610
+ for (const [cat, c] of gcf.categories)
611
+ addToMap(fold.categories, cat, c);
612
+ if (gcf.firstTs && (!fold.firstTs || gcf.firstTs < fold.firstTs))
613
+ fold.firstTs = gcf.firstTs;
614
+ if (gcf.lastTs > fold.lastTs)
615
+ fold.lastTs = gcf.lastTs;
616
+ }
617
+ return fold;
618
+ }
619
+ function turnStartTs(turn) {
620
+ return turn.assistantCalls[0]?.timestamp || turn.timestamp || '';
621
+ }
622
+ // Grace window for a child whose spawn pairing was AMBIGUOUS (the parent recorded
623
+ // its agentId, so we KNOW it spawned this child, but the exact launching turn could
624
+ // not be pinned) and whose first activity lands just after the parent's last turn.
625
+ // The repo has no session-idle gap constant to reuse, so 30 minutes is used as a
626
+ // conservative window: within it the child folds to the parent's last turn rather
627
+ // than vanish; beyond it, it stays unlinked.
628
+ const AMBIGUOUS_SPAWN_GRACE_MS = 30 * 60 * 1000;
629
+ /// Resolve a fold to the PR its launching parent turn was working on, using the
630
+ /// parent's UNFILTERED turn data so a date range cannot misattribute:
631
+ /// 1. spawn `tool_use` id to `parent.spawnPrSets` (built at assembly from the
632
+ /// FULL turn list), so a spawn in a pre-range turn still yields the right PR;
633
+ /// an empty set there means the spawn had no active PR, so unattributed.
634
+ /// 2. else the child's first-activity epoch bucketed into the parent's turn PR
635
+ /// carry (seeded from `prRefsAtRangeStart`). Timestamps compare as epoch ms
636
+ /// (mixed UTC offsets order correctly). Activity strictly AFTER the parent's
637
+ /// last timestamp is unlinked (contributes nothing); before the first turn it
638
+ /// carries the pre-range set (or unattributed).
639
+ function resolveChild(parent, fold) {
640
+ const spawnId = parent.agentSpawnLinks?.[fold.agentId];
641
+ if (spawnId !== undefined && parent.spawnPrSets && Object.prototype.hasOwnProperty.call(parent.spawnPrSets, spawnId)) {
642
+ const prs = parent.spawnPrSets[spawnId];
643
+ return { fold, prSet: prs.length ? namedPrSet(prs, fold.named) : null, unlinked: false };
644
+ }
645
+ const ms = fold.spawnAtMs;
646
+ if (Number.isNaN(ms))
647
+ return { fold, prSet: null, unlinked: true };
648
+ const lastMs = parseMs(parent.lastTimestamp);
649
+ if (!Number.isNaN(lastMs) && ms > lastMs) {
650
+ // After the parent's last turn: normally unlinked. But if the spawn pairing was
651
+ // AMBIGUOUS (we know it was spawned here, just not which turn) and the child
652
+ // started within the grace window, extend the fallback to the parent's LAST
653
+ // turn rather than lose it. A truly-absent pairing (no agentId at all) does not
654
+ // qualify: we cannot confirm this parent spawned it.
655
+ const ambiguousPairing = !!parent.ambiguousSpawnAgentIds?.includes(fold.agentId);
656
+ if (!(ambiguousPairing && ms - lastMs <= AMBIGUOUS_SPAWN_GRACE_MS)) {
657
+ return { fold, prSet: null, unlinked: true };
658
+ }
659
+ // Fall through: every turn has start <= lastMs <= ms, so the walk below carries
660
+ // `current` to the last turn's PR set.
661
+ }
662
+ let current = parent.prRefsAtRangeStart?.length ? parent.prRefsAtRangeStart : null;
663
+ for (const turn of parent.turns) {
664
+ const tMs = parseMs(turnStartTs(turn));
665
+ if (Number.isNaN(tMs))
666
+ continue;
667
+ if (tMs <= ms) {
668
+ if (turn.prRefs?.length)
669
+ current = turn.prRefs;
670
+ }
671
+ else
672
+ break;
673
+ }
674
+ return { fold, prSet: current ? namedPrSet(current, fold.named) : null, unlinked: false };
675
+ }
676
+ // A run whose prompt names one PR belongs to that PR, not to whatever PR the
677
+ // parent's last pr-link happened to carry (a review of #1729 spawned while the
678
+ // parent carried a stale #24). Only re-points spend that already had a PR, and
679
+ // only within the carried PR's repo (or the exact URL the prompt gave), so
680
+ // attributed totals never change.
681
+ function namedPrSet(carried, named) {
682
+ if (!named || named === 'multi')
683
+ return carried;
684
+ const repos = new Set(carried.map(url => {
685
+ const m = GITHUB_PR_RE.exec(url);
686
+ return m ? `${m[1]}/${m[2]}` : '';
687
+ }));
688
+ const repo = named.repo ?? (repos.size === 1 ? [...repos][0] : '');
689
+ if (!repo)
690
+ return carried;
691
+ return [`https://github.com/${repo}/pull/${named.number}`];
692
+ }
693
+ /// `scanCommands: false` skips the per-call PR signals (pushed, readPrs, ...) for
694
+ /// callers that only need each child's PR set.
695
+ export function resolveSubagentAttribution(projects, scanCommands = true) {
696
+ const index = buildSubagentIndex(projects);
697
+ // A provider+sessionId key is AMBIGUOUS when it is carried by more than one
698
+ // DISTINCT record (different fingerprint) across ALL candidate sessions and
699
+ // anchors, regardless of whether each has prLinks: a child pointing at that id
700
+ // cannot tell which record spawned it. Such a key folds into NEITHER parent and
701
+ // its subtree is skipped (correctness over coverage). Identical duplicates share
702
+ // a fingerprint, so they are not ambiguous and fold once.
703
+ const fpByKey = new Map();
704
+ const note = (s) => {
705
+ const k = providerSessionKey(s);
706
+ const set = fpByKey.get(k);
707
+ if (set)
708
+ set.add(sessionFingerprint(s));
709
+ else
710
+ fpByKey.set(k, new Set([sessionFingerprint(s)]));
711
+ };
712
+ for (const project of projects) {
713
+ for (const s of project.sessions)
714
+ note(s);
715
+ for (const a of project.subagentAnchors ?? [])
716
+ note(a);
717
+ }
718
+ const ambiguous = new Set();
719
+ for (const [k, fps] of fpByKey)
720
+ if (fps.size > 1)
721
+ ambiguous.add(k);
722
+ const out = new Map();
723
+ const resolveParent = (parent) => {
724
+ if (!parent.prLinks?.length)
725
+ return;
726
+ const k = providerSessionKey(parent);
727
+ if (out.has(k))
728
+ return; // already resolved for this key
729
+ if (ambiguous.has(k)) {
730
+ out.set(k, []);
731
+ return;
732
+ } // ambiguous parent id: fold nothing
733
+ const direct = index.get(k);
734
+ if (!direct?.length)
735
+ return;
736
+ const claimed = new Set(); // one claimed set across all direct children
737
+ const resolved = [];
738
+ for (const child of direct) {
739
+ if (claimed.has(child.sessionId) || selfLinks(child) || ambiguous.has(providerSessionKey(child)))
740
+ continue;
741
+ resolved.push(resolveChild(parent, buildChildFold(child, index, claimed, ambiguous, scanCommands)));
742
+ }
743
+ if (resolved.length)
744
+ out.set(k, resolved);
745
+ };
746
+ for (const project of projects) {
747
+ for (const parent of project.sessions)
748
+ resolveParent(parent);
749
+ for (const anchor of project.subagentAnchors ?? [])
750
+ resolveParent(anchor);
751
+ }
752
+ return out;
753
+ }
754
+ /// Attribute a session's spend to the PRs it referenced, at TURN granularity.
755
+ ///
756
+ /// Walk the turns in order carrying `current` = the PR set of the most recent
757
+ /// turn that referenced any PR (seeded from `prRefsAtRangeStart` so a reference
758
+ /// made before the report window still owns its in-range follow-up turns). Each
759
+ /// turn's cost/savings are split evenly across a multi-PR set (a merge-sweep turn
760
+ /// touching several PRs); calls are split by largest-remainder so they stay whole.
761
+ /// Each contribution also records the models of its calls and the turn's task
762
+ /// category, both weighted by the same split share. Turns before the first
763
+ /// reference land in `unattributed` (genuine session overhead). `repoint` may
764
+ /// swap one attributed turn's set (push evidence) without changing the carry.
765
+ ///
766
+ /// Legacy fallback: a session whose transcript already expired keeps its
767
+ /// session-level `prLinks` but has NO per-turn `prRefs`. With no turn boundaries
768
+ /// to attribute by, split the whole session evenly across its prLinks, mark every
769
+ /// portion `approx`, and carry the session's model union (its calls still name
770
+ /// their models) but NO category breakdown, since none can be honestly assigned.
771
+ export function attributeSessionPrSpend(session, repoint) {
772
+ const perUrl = new Map();
773
+ const unattributed = { cost: 0, calls: 0, savingsUSD: 0 };
774
+ const hasTurnRefs = session.turns.some(t => t.prRefs?.length) || !!session.prRefsAtRangeStart?.length;
775
+ if (!hasTurnRefs) {
776
+ const links = session.prLinks;
777
+ if (links?.length) {
778
+ const legacyModels = new Map();
779
+ for (const turn of session.turns) {
780
+ for (const call of turn.assistantCalls) {
781
+ if (call.model)
782
+ addToMap(legacyModels, call.model, call.costUSD);
783
+ }
784
+ }
785
+ const share = 1 / links.length;
786
+ const callAlloc = allocateEven(session.apiCalls, links.length);
787
+ links.forEach((url, i) => {
788
+ const e = ensureContribution(perUrl, url);
789
+ e.cost += session.totalCostUSD * share;
790
+ e.calls += callAlloc[i];
791
+ e.savingsUSD += session.totalSavingsUSD * share;
792
+ e.approx = true;
793
+ for (const [m, mc] of legacyModels)
794
+ addToMap(e.models, m, mc * share);
795
+ });
796
+ }
797
+ return { perUrl, unattributed, turnPrs: [] };
798
+ }
799
+ let current = session.prRefsAtRangeStart?.length ? session.prRefsAtRangeStart : null;
800
+ const turnPrs = [];
801
+ for (const [i, turn] of session.turns.entries()) {
802
+ if (turn.prRefs?.length)
803
+ current = turn.prRefs;
804
+ const prs = current && repoint ? repoint(i, current) : current;
805
+ turnPrs.push(prs);
806
+ const cost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0);
807
+ const calls = behavioralCallCount(turn.assistantCalls);
808
+ const savings = turn.assistantCalls.reduce((s, c) => s + (c.savingsUSD ?? 0), 0);
809
+ // Cost/savings keep every call, so a supplementary-only turn (calls === 0)
810
+ // still attributes its spend here — only a genuinely empty turn is skipped.
811
+ if (cost === 0 && calls === 0 && savings === 0)
812
+ continue;
813
+ if (prs === null) {
814
+ unattributed.cost += cost;
815
+ unattributed.calls += calls;
816
+ unattributed.savingsUSD += savings;
817
+ continue;
818
+ }
819
+ const modelCostInTurn = new Map();
820
+ for (const call of turn.assistantCalls) {
821
+ if (call.model)
822
+ addToMap(modelCostInTurn, call.model, call.costUSD);
823
+ }
824
+ const share = 1 / prs.length;
825
+ const callAlloc = allocateEven(calls, prs.length);
826
+ const startTs = turnStartTs(turn);
827
+ const endTs = turn.assistantCalls.at(-1)?.timestamp || startTs;
828
+ prs.forEach((url, i) => {
829
+ const e = ensureContribution(perUrl, url);
830
+ if (startTs && (!e.firstTs || startTs < e.firstTs))
831
+ e.firstTs = startTs;
832
+ if (endTs > e.lastTs)
833
+ e.lastTs = endTs;
834
+ e.cost += cost * share;
835
+ e.calls += callAlloc[i];
836
+ e.savingsUSD += savings * share;
837
+ if (turn.category)
838
+ addToMap(e.categories, turn.category, cost * share);
839
+ for (const [m, mc] of modelCostInTurn)
840
+ addToMap(e.models, m, mc * share);
841
+ });
842
+ }
843
+ return { perUrl, unattributed, turnPrs };
844
+ }
845
+ /// Spend by pull request, at turn granularity, with subagent runs folded into the
846
+ /// PR each was working on. Computed in ONE pass so `aggregateByPr` (rows) and
847
+ /// `prLinkedTotals` (totals) never disagree; the payload builder should call this
848
+ /// once and read both. Rows carry ATTRIBUTED cost/calls and ARE summable; `approx`
849
+ /// marks legacy even-split rows; `models`/`categories` are the attributed
850
+ /// breakdowns. Sorted by cost, descending.
851
+ export function buildPrAttribution(projects) {
852
+ const byUrl = new Map();
853
+ const attribution = resolveSubagentAttribution(projects);
854
+ const signals = new Map();
855
+ const sig = (url) => {
856
+ let s = signals.get(url);
857
+ if (!s)
858
+ signals.set(url, s = { spend: [], openedMs: NaN, explicit: false, reviews: [] });
859
+ return s;
860
+ };
861
+ // Opens first: a run can push branch B before B's PR is opened, possibly by
862
+ // another session, so every head must be known before attributing.
863
+ const linked = projects.flatMap(p => p.sessions.filter(s => s.prLinks?.length));
864
+ const turnCmds = new Map();
865
+ for (const session of linked) {
866
+ const tc = turnCommands(session);
867
+ turnCmds.set(session, tc);
868
+ matchSessionCreates(session, tc, sig);
869
+ }
870
+ // ponytail: a head branch reused by two PRs maps to neither.
871
+ const heads = new Map();
872
+ for (const [url, s] of signals)
873
+ if (s.head)
874
+ heads.set(s.head, heads.has(s.head) && heads.get(s.head) !== url ? null : url);
875
+ // Push evidence: the PRs (in the carried set's repo) whose head these branches are.
876
+ const headPrs = (branches, carried) => {
877
+ if (!heads.size)
878
+ return null;
879
+ const repos = new Set(carried.map(u => prParts(u)?.repo));
880
+ const out = new Set();
881
+ for (const b of branches) {
882
+ const u = heads.get(b);
883
+ if (u && repos.has(prParts(u)?.repo))
884
+ out.add(u);
885
+ }
886
+ return out.size ? [...out] : null;
887
+ };
888
+ let attributedCost = 0;
889
+ let unattributedCost = 0;
890
+ let sessions = 0;
891
+ let subagentSessions = 0;
892
+ // Add one contribution (a parent turn's share, or a folded child's share) to a
893
+ // PR row. `sessionKey` is the contributing PARENT's identity, so a folded child
894
+ // does not inflate the row's distinct-session count beyond its parent. Empty
895
+ // timestamps (a 0-turn anchor) never widen the span; folded children pass their
896
+ // OWN activity span, which is what dates an anchor-only row.
897
+ const addTo = (url, sessionKey, firstTs, lastTs, cost, savings, calls, approx, models, categories, foldedRuns = 0) => {
898
+ if (cost === 0 && calls === 0 && savings === 0)
899
+ return;
900
+ const row = byUrl.get(url) ?? {
901
+ cost: 0, savingsUSD: 0, calls: 0, approx: false, legacyCost: 0,
902
+ sessions: new Set(), ownSessions: new Set(), foldedRuns: 0, firstStarted: firstTs, lastEnded: lastTs,
903
+ models: new Map(), categories: new Map(),
904
+ };
905
+ row.cost += cost;
906
+ row.savingsUSD += savings;
907
+ row.calls += calls;
908
+ row.sessions.add(sessionKey);
909
+ if (foldedRuns)
910
+ row.foldedRuns += foldedRuns;
911
+ else
912
+ row.ownSessions.add(sessionKey);
913
+ if (approx) {
914
+ row.approx = true;
915
+ row.legacyCost += cost;
916
+ }
917
+ for (const [m, mc] of models)
918
+ addToMap(row.models, m, mc);
919
+ for (const [cat, cc] of categories)
920
+ addToMap(row.categories, cat, cc);
921
+ if (firstTs && (!row.firstStarted || firstTs < row.firstStarted))
922
+ row.firstStarted = firstTs;
923
+ if (lastTs && lastTs > row.lastEnded)
924
+ row.lastEnded = lastTs;
925
+ byUrl.set(url, row);
926
+ };
927
+ // Fold one parent's resolved children into rows + totals, ONCE per parent key: two
928
+ // duplicate parent sessions share a provider+sessionId key and the SAME resolved
929
+ // children, so folding for each would double-count. An unlinked child contributes
930
+ // nothing; a child with no active PR goes to unattributed (no row).
931
+ const foldedKeys = new Set();
932
+ const foldChildren = (parent) => {
933
+ const key = providerSessionKey(parent);
934
+ if (foldedKeys.has(key))
935
+ return;
936
+ foldedKeys.add(key);
937
+ const sessionKey = rowSessionKey(parent);
938
+ for (const rc of attribution.get(key) ?? []) {
939
+ if (rc.unlinked)
940
+ continue;
941
+ subagentSessions += rc.fold.foldedSessions;
942
+ if (!rc.prSet?.length) {
943
+ unattributedCost += rc.fold.cost;
944
+ continue;
945
+ }
946
+ attributedCost += rc.fold.cost;
947
+ const namedOne = rc.fold.named !== null && rc.fold.named !== 'multi';
948
+ const prs = (!namedOne && headPrs(rc.fold.branches, rc.prSet)) || rc.prSet;
949
+ const share = 1 / prs.length;
950
+ const callAlloc = allocateEven(rc.fold.calls, prs.length);
951
+ prs.forEach((url, i) => {
952
+ const models = new Map();
953
+ for (const [m, mc] of rc.fold.models)
954
+ models.set(m, mc * share);
955
+ const categories = new Map();
956
+ for (const [cat, cc] of rc.fold.categories)
957
+ categories.set(cat, cc * share);
958
+ addTo(url, sessionKey, rc.fold.firstTs, rc.fold.lastTs, rc.fold.cost * share, rc.fold.savingsUSD * share, callAlloc[i], false, models, categories, rc.fold.foldedSessions);
959
+ foldSignals(sig(url), url, rc.fold, share, prs.length === 1);
960
+ });
961
+ }
962
+ };
963
+ for (const project of projects) {
964
+ for (const session of project.sessions) {
965
+ if (!session.prLinks?.length)
966
+ continue;
967
+ sessions += 1;
968
+ const sessionKey = rowSessionKey(session);
969
+ const tc = turnCmds.get(session);
970
+ const { perUrl, unattributed, turnPrs } = attributeSessionPrSpend(session, (i, carried) => (tc[i].pushed.length && headPrs(tc[i].pushed, carried)) || carried);
971
+ for (const [url, c] of perUrl) {
972
+ attributedCost += c.cost;
973
+ addTo(url, sessionKey, c.firstTs || session.firstTimestamp, c.lastTs || session.lastTimestamp, c.cost, c.savingsUSD, c.calls, c.approx, c.models, c.categories);
974
+ if (c.approx)
975
+ sig(url).spend.push({ ms: parseMs(session.firstTimestamp), cost: c.cost, review: false, legacy: true, run: { kind: 'session', key: sessionKey, description: null, models: c.models, at: session.firstTimestamp, link: 'carried' } });
976
+ }
977
+ turnSignals(session, sessionKey, tc, turnPrs, sig);
978
+ unattributedCost += unattributed.cost;
979
+ foldChildren(session);
980
+ }
981
+ // Anchor parents: fold their children only. NOT counted in `sessions`, and no
982
+ // own spend (they have no in-range turns).
983
+ for (const anchor of project.subagentAnchors ?? []) {
984
+ if (!anchor.prLinks?.length)
985
+ continue;
986
+ foldChildren(anchor);
987
+ }
988
+ }
989
+ const scan = scanPrCommands(projects);
990
+ const byNumber = new Map();
991
+ for (const url of byUrl.keys()) {
992
+ const pr = prParts(url);
993
+ if (pr)
994
+ byNumber.set(pr.number, [...(byNumber.get(pr.number) ?? []), url]);
995
+ }
996
+ const rows = [...byUrl.entries()]
997
+ .map(([url, r]) => {
998
+ // Collapse raw model names to short display names, summing costs that map
999
+ // to the same short name, then order by attributed cost (name asc breaks
1000
+ // ties for a stable order). Keep every real model: `<synthetic>` is an
1001
+ // internal accounting bucket, not a model a person chose or can act on.
1002
+ // The desktop renders the rest as wrapping chips, so an opaque "+N" never
1003
+ // hides which model did the work.
1004
+ const shortCosts = new Map();
1005
+ for (const [raw, mc] of r.models) {
1006
+ if (raw === '<synthetic>')
1007
+ continue;
1008
+ addToMap(shortCosts, modelRowKey(raw), mc);
1009
+ }
1010
+ const models = [...shortCosts.entries()]
1011
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
1012
+ .map(([name]) => name);
1013
+ const categories = [...r.categories.entries()]
1014
+ .map(([cat, cost]) => ({ name: CATEGORY_LABELS[cat] ?? cat, cost }));
1015
+ // Mixed row: live per-turn categories exist AND part of the row came from a
1016
+ // legacy even-split (no turn data). Add a synthetic line for the legacy
1017
+ // share so the expansion reconciles with the row cost instead of silently
1018
+ // dropping it. A legacy-only row keeps no categories (it surfaces as "no
1019
+ // per-turn detail"), so there is nothing to reconcile there.
1020
+ if (categories.length > 0 && r.legacyCost > 0) {
1021
+ categories.push({ name: 'Legacy estimate (no per-turn detail)', cost: r.legacyCost });
1022
+ }
1023
+ categories.sort((a, b) => b.cost - a.cost || a.name.localeCompare(b.name));
1024
+ return {
1025
+ url, label: shortenPrUrl(url),
1026
+ cost: r.cost, savingsUSD: r.savingsUSD,
1027
+ sessions: r.sessions.size, calls: r.calls,
1028
+ firstStarted: r.firstStarted, lastEnded: r.lastEnded,
1029
+ runs: r.ownSessions.size + r.foldedRuns,
1030
+ approx: r.approx,
1031
+ models,
1032
+ ...(categories.length ? { categories } : {}),
1033
+ ...rowSignals(url, signals.get(url), r.cost, scan, byNumber),
1034
+ };
1035
+ })
1036
+ .sort((a, b) => b.cost - a.cost);
1037
+ return { rows, totals: { cost: attributedCost + unattributedCost, sessions, subagentSessions, attributedCost, unattributedCost } };
1038
+ }
1039
+ function prParts(url) {
1040
+ const m = GITHUB_PR_RE.exec(url);
1041
+ return m ? { repo: `${m[1]}/${m[2]}`, number: Number(m[3]) } : null;
1042
+ }
1043
+ function mentionsUrl(text, url) {
1044
+ for (let i = text.indexOf(url); i >= 0; i = text.indexOf(url, i + 1))
1045
+ if (!/\d/.test(text[i + url.length] ?? ''))
1046
+ return true;
1047
+ return false;
1048
+ }
1049
+ function topModel(models) {
1050
+ let best = null;
1051
+ for (const [m, c] of models)
1052
+ if (m !== '<synthetic>' && (!best || c > best[1]))
1053
+ best = [m, c];
1054
+ return best ? modelRowKey(best[0]) : null;
1055
+ }
1056
+ // A folded run reviewed this PR when it read it (by number, or read code under
1057
+ // a description naming it) and neither committed nor pushed. A run split
1058
+ // across PRs, or whose description names several, reviews none of them.
1059
+ function foldSignals(s, url, fold, share, single) {
1060
+ const cost = fold.cost * share;
1061
+ if (cost === 0 && fold.calls === 0)
1062
+ return;
1063
+ const pr = prParts(url);
1064
+ const readThis = !!pr && single && fold.named !== 'multi' && (fold.readPrs.has(pr.number) || (fold.mentioned === pr.number && fold.readsCode));
1065
+ const review = readThis && !fold.committed && !fold.pushed;
1066
+ const link = pr && fold.mentioned === pr.number ? 'named'
1067
+ : s.head && fold.branches.has(s.head) ? 'pushed-head'
1068
+ : pr && fold.prNumbers.has(pr.number) ? 'gh-pr'
1069
+ : 'carried';
1070
+ s.spend.push({ ms: parseMs(fold.firstTs), cost, review, run: { kind: 'subagent', key: fold.agentId, description: fold.description || null, models: fold.models, at: fold.firstTs, link } });
1071
+ if (review)
1072
+ s.reviews.push({ kind: 'agent', label: fold.agentType ?? 'subagent', model: topModel(fold.models), costUSD: cost, at: fold.firstTs, evidence: 'reads-pr' });
1073
+ if (pr && (fold.prNumbers.has(pr.number) || fold.mentioned === pr.number))
1074
+ s.explicit = true;
1075
+ }
1076
+ // Pair each `gh pr create` in a turn with a PR first referenced in that turn
1077
+ // (its pr-link lands there): per repo, creates in call order against the new PR
1078
+ // numbers ascending, since GitHub numbers grow. A retried create for the same
1079
+ // head keeps only the last one. One call opening several PRs gets a pr-link for
1080
+ // the last one only.
1081
+ function matchCreates(cmds, fresh, sig) {
1082
+ const creates = new Map();
1083
+ cmds.forEach(c => ghPrCommands(c.cmd).forEach((g, j) => {
1084
+ if (g.verb !== 'create')
1085
+ return;
1086
+ const head = createHead(g.args);
1087
+ creates.set(head ?? `${c.ms}:${j}`, { ms: c.ms, ...(g.repo ? { repo: g.repo } : {}), ...(head ? { head } : {}), draft: /(?:^|\s)(?:--draft|-d)(?=\s|$)/.test(g.args) });
1088
+ }));
1089
+ if (!creates.size)
1090
+ return;
1091
+ const byRepo = new Map();
1092
+ for (const c of creates.values())
1093
+ byRepo.set(c.repo ?? '', [...(byRepo.get(c.repo ?? '') ?? []), c]);
1094
+ let unclaimed = [...fresh].sort((a, b) => (prParts(a)?.number ?? 0) - (prParts(b)?.number ?? 0));
1095
+ for (const repo of [...byRepo.keys()].sort().reverse()) {
1096
+ const cs = byRepo.get(repo).sort((a, b) => a.ms - b.ms);
1097
+ const us = unclaimed.filter(u => !repo || prParts(u)?.repo === repo);
1098
+ const paired = us.length === cs.length ? cs : us.length === 1 ? cs.slice(-1) : null;
1099
+ if (!paired)
1100
+ continue;
1101
+ paired.forEach((c, k) => {
1102
+ const s = sig(us[k]);
1103
+ if (Number.isNaN(s.openedMs) || c.ms < s.openedMs) {
1104
+ s.openedMs = c.ms;
1105
+ s.head = c.head;
1106
+ s.draft = c.draft;
1107
+ }
1108
+ s.explicit = true;
1109
+ });
1110
+ unclaimed = unclaimed.filter(u => !us.includes(u));
1111
+ }
1112
+ }
1113
+ // Each turn's commands, and the branches it pushed by name (a top-level session
1114
+ // moves between checkouts too freely to resolve a bare push).
1115
+ function turnCommands(session) {
1116
+ return session.turns.map(turn => {
1117
+ const cmds = turn.assistantCalls.flatMap(call => {
1118
+ const list = callCommands(call);
1119
+ if (!list.length)
1120
+ return [];
1121
+ const ms = parseMs(call.timestamp);
1122
+ return list.map(cmd => ({ cmd, ms }));
1123
+ });
1124
+ return { cmds, pushed: cmds.flatMap(c => pushes(c.cmd).flat()) };
1125
+ });
1126
+ }
1127
+ function matchSessionCreates(session, tc, sig) {
1128
+ const seen = new Set(session.prRefsAtRangeStart ?? []);
1129
+ session.turns.forEach((turn, i) => {
1130
+ const fresh = (turn.prRefs ?? []).filter(u => !seen.has(u));
1131
+ for (const u of fresh)
1132
+ seen.add(u);
1133
+ if (fresh.length)
1134
+ matchCreates(tc[i].cmds, fresh, sig);
1135
+ });
1136
+ }
1137
+ // Walk a parent's turns with the PR set each was attributed to: the share of
1138
+ // spend each PR carried, why it counts there, and `gh pr review <n>` posted for it.
1139
+ function turnSignals(session, sessionKey, tc, turnPrs, sig) {
1140
+ session.turns.forEach((turn, i) => {
1141
+ const prs = turnPrs[i];
1142
+ if (!prs)
1143
+ return;
1144
+ const cost = turn.assistantCalls.reduce((n, c) => n + c.costUSD, 0);
1145
+ if (cost === 0 && behavioralCallCount(turn.assistantCalls) === 0)
1146
+ return;
1147
+ const share = cost / prs.length;
1148
+ const at = turnStartTs(turn);
1149
+ const { cmds, pushed } = tc[i];
1150
+ const gh = cmds.flatMap(c => ghPrCommands(c.cmd));
1151
+ const named = new Set(cmds.flatMap(c => [...prNumbersIn(c.cmd)]));
1152
+ const models = new Map();
1153
+ for (const c of turn.assistantCalls)
1154
+ if (c.model)
1155
+ addToMap(models, c.model, c.costUSD);
1156
+ for (const url of prs) {
1157
+ const s = sig(url);
1158
+ const pr = prParts(url);
1159
+ const posted = pr ? gh.find(g => g.verb === 'review' && g.number === pr.number && (!g.repo || g.repo === pr.repo)) : undefined;
1160
+ const mentioned = mentionsUrl(turn.userMessage, url);
1161
+ const namesPr = !!pr && named.has(pr.number);
1162
+ const link = cmds.some(c => c.ms === s.openedMs) ? 'opened'
1163
+ : namesPr || posted ? 'gh-pr'
1164
+ : s.head && pushed.includes(s.head) ? 'pushed-head'
1165
+ : mentioned ? 'named'
1166
+ : 'carried';
1167
+ s.spend.push({ ms: parseMs(at), cost: share, review: !!posted, run: { kind: 'session', key: sessionKey, description: null, models, at, link } });
1168
+ if (posted)
1169
+ s.reviews.push({ kind: 'you', label: reviewVerdict(posted.args), model: topModel(models), costUSD: share, at, evidence: 'gh-pr-review' });
1170
+ if (namesPr || mentioned)
1171
+ s.explicit = true;
1172
+ }
1173
+ });
1174
+ }
1175
+ const STATE_EVENTS = new Set(['merge', 'close', 'ready', 'reopen']);
1176
+ // Every push and state change (merge, close, ready, reopen) in range, from every
1177
+ // session. A bare `git push` in a subagent run pushes the branch it last pushed
1178
+ // by name; a top-level session moves between checkouts too freely to assume that.
1179
+ function scanPrCommands(projects) {
1180
+ const out = { pushes: [], events: [] };
1181
+ for (const project of projects)
1182
+ for (const session of project.sessions) {
1183
+ const side = !!session.isSidechain;
1184
+ let mentioned;
1185
+ let upstream;
1186
+ for (const turn of session.turns)
1187
+ for (const call of turn.assistantCalls) {
1188
+ const cmds = callCommands(call);
1189
+ if (!cmds.length)
1190
+ continue;
1191
+ const ms = parseMs(call.timestamp);
1192
+ if (Number.isNaN(ms))
1193
+ continue;
1194
+ for (const cmd of cmds) {
1195
+ for (const branches of pushes(cmd)) {
1196
+ if (side && mentioned === undefined)
1197
+ mentioned = namedPrNumber(agentDescriptionOf(session));
1198
+ if (side && branches.length)
1199
+ upstream = branches.at(-1);
1200
+ out.pushes.push({ ms, branches: branches.length ? branches : upstream ? [upstream] : [], mentioned: mentioned ?? null });
1201
+ }
1202
+ for (const g of ghPrCommands(cmd)) {
1203
+ if (STATE_EVENTS.has(g.verb) && g.number !== undefined)
1204
+ out.events.push({ ms, number: g.number, ...(g.repo ? { repo: g.repo } : {}), verb: g.verb });
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ return out;
1210
+ }
1211
+ // One runList entry per folded run, and per session and link reason.
1212
+ function runList(spend) {
1213
+ const out = [];
1214
+ const bySession = new Map();
1215
+ for (const x of spend) {
1216
+ const { key, models, ...run } = x.run;
1217
+ const k = `${key}${KEY_SEP}${run.link}`;
1218
+ const hit = run.kind === 'session' ? bySession.get(k) : undefined;
1219
+ if (hit) {
1220
+ hit.costUSD += x.cost;
1221
+ if (run.at && (!hit.at || run.at < hit.at))
1222
+ hit.at = run.at;
1223
+ for (const [m, c] of models)
1224
+ addToMap(hit.models, m, c);
1225
+ continue;
1226
+ }
1227
+ const entry = { ...run, model: null, costUSD: x.cost, models: new Map(models) };
1228
+ if (run.kind === 'session')
1229
+ bySession.set(k, entry);
1230
+ out.push(entry);
1231
+ }
1232
+ return out
1233
+ .sort((a, b) => a.at.localeCompare(b.at))
1234
+ .map(({ models, ...run }) => ({ ...run, model: topModel(models) }));
1235
+ }
1236
+ // ponytail: a bare PR number (a merge, or a run's description) is matched
1237
+ // against this report's rows only; two rows with that number in different repos
1238
+ // leave it unmatched.
1239
+ function rowSignals(url, s, cost, scan, byNumber) {
1240
+ const pr = prParts(url);
1241
+ const isRow = (number, repo) => {
1242
+ const hits = (byNumber.get(number) ?? []).filter(u => !repo || prParts(u).repo === repo);
1243
+ return hits.length === 1 && hits[0] === url;
1244
+ };
1245
+ const opened = s && !Number.isNaN(s.openedMs) ? s.openedMs : null;
1246
+ // Without the head branch (`--head "$br"`) the open's own pushes cannot be
1247
+ // told apart, so it reads like a PR opened elsewhere: follow-ups only.
1248
+ const tracked = opened !== null && !!s?.head;
1249
+ const pushMs = scan.pushes
1250
+ .filter(p => (s?.head && p.branches.includes(s.head)) || (pr && p.mentioned === pr.number && isRow(pr.number)))
1251
+ .map(p => p.ms)
1252
+ .filter(ms => opened === null || ms > opened);
1253
+ const starts = tracked || pushMs.length ? roundStarts(pushMs) : null;
1254
+ const followUpRounds = starts ? starts.length : null;
1255
+ const events = scan.events.filter(e => isRow(e.number, e.repo) && (opened === null || e.ms >= opened));
1256
+ const merged = Math.min(Infinity, ...events.filter(e => e.verb === 'merge').map(e => e.ms));
1257
+ const mergedMs = Number.isFinite(merged) ? merged : null;
1258
+ // A plain open says nothing about now (a merge by script is not seen), so
1259
+ // only a draft open counts; a reopened draft stays a draft until `gh pr ready`.
1260
+ let draft = opened !== null && !!s?.draft;
1261
+ let state = draft ? 'draft' : null;
1262
+ for (const e of [...events].sort((a, b) => a.ms - b.ms)) {
1263
+ if (e.verb === 'ready')
1264
+ draft = false;
1265
+ state = e.verb === 'merge' ? 'merged' : e.verb === 'close' ? 'closed' : draft ? 'draft' : 'open';
1266
+ }
1267
+ const spend = s?.spend ?? [];
1268
+ const reviewSpend = spend.filter(x => x.review);
1269
+ const firstReview = Math.min(...reviewSpend.map(x => x.ms));
1270
+ const reviewUSD = reviewSpend.reduce((n, x) => n + x.cost, 0);
1271
+ const fixesUSD = spend.filter(x => !x.review && !x.legacy && x.ms >= firstReview).reduce((n, x) => n + x.cost, 0);
1272
+ return {
1273
+ linkEvidence: !spend.some(x => !x.legacy) ? null : s.explicit || mergedMs !== null ? 'explicit' : 'pr-link-only',
1274
+ openedAt: opened === null ? null : new Date(opened).toISOString(),
1275
+ followUpRounds,
1276
+ followUpPushes: pushMs.length,
1277
+ oneShot: tracked ? followUpRounds === 0 : null,
1278
+ reviewRuns: [...(s?.reviews ?? [])].sort((a, b) => a.at.localeCompare(b.at)),
1279
+ reviewCostUSD: reviewUSD,
1280
+ mergedAt: mergedMs === null ? null : new Date(mergedMs).toISOString(),
1281
+ timeToMergeMs: opened !== null && mergedMs !== null && mergedMs > opened ? mergedMs - opened : null,
1282
+ costSplit: { buildUSD: cost - reviewUSD - fixesUSD, reviewUSD, fixesUSD },
1283
+ carriedUSD: spend.filter(x => x.run.link === 'carried').reduce((n, x) => n + x.cost, 0),
1284
+ runList: runList(spend),
1285
+ state,
1286
+ followUpAt: (starts ?? []).map(ms => new Date(ms).toISOString()),
1287
+ };
1288
+ }
1289
+ /// Spend attributed to each pull request (thin wrapper over buildPrAttribution).
1290
+ export function aggregateByPr(projects) {
1291
+ return buildPrAttribution(projects).rows;
1292
+ }
1293
+ /// Totals across every PR-linked session (thin wrapper over buildPrAttribution).
1294
+ export function prLinkedTotals(projects) {
1295
+ return buildPrAttribution(projects).totals;
1296
+ }
1297
+ /// Per-branch spend, carrying each session's last-seen git branch forward across
1298
+ /// its turns. The cache stores a turn's branch only when it CHANGES, so a report
1299
+ /// must reconstruct each turn's branch from the last stored value — this walks a
1300
+ /// session's turns in order and does exactly that.
1301
+ ///
1302
+ /// Only sessions that EVER observed a branch participate: a provider that never
1303
+ /// captures branch data (only Claude does today) would otherwise pile all of its
1304
+ /// spend into one `null` bucket that dwarfs every real branch. Within a
1305
+ /// participating session, turns before the first observed branch are attributed
1306
+ /// to a single explicit `null` row the caller can label honestly.
1307
+ ///
1308
+ /// A session that switches branches counts toward EACH branch it touched (like
1309
+ /// the by-PR by-reference attribution), so rows must never be summed into a grand
1310
+ /// total. Sorted by cost, descending.
1311
+ export function aggregateByBranch(projects) {
1312
+ const byBranch = new Map();
1313
+ for (const project of projects) {
1314
+ for (const session of project.sessions) {
1315
+ // Participate when the session observed a branch anywhere in its full
1316
+ // transcript (`everHadBranch`, set pre-date-filter) — falling back to the
1317
+ // turns in hand for producers/fixtures that don't set the flag. A session
1318
+ // that never observed a branch (every non-Claude provider) is skipped so
1319
+ // it can't pile into the null bucket.
1320
+ if (!session.everHadBranch && !session.turns.some(turn => turn.gitBranch))
1321
+ continue;
1322
+ let current = null;
1323
+ for (const turn of session.turns) {
1324
+ if (turn.gitBranch)
1325
+ current = turn.gitBranch;
1326
+ // Raw gate: a supplementary-only turn still carries cost to attribute,
1327
+ // even though it adds no behavioral calls.
1328
+ if (turn.assistantCalls.length === 0)
1329
+ continue;
1330
+ const turnCost = turn.assistantCalls.reduce((sum, call) => sum + call.costUSD, 0);
1331
+ const row = byBranch.get(current) ?? { cost: 0, calls: 0, sessions: new Set() };
1332
+ row.cost += turnCost;
1333
+ row.calls += behavioralCallCount(turn.assistantCalls);
1334
+ row.sessions.add(session.sessionId);
1335
+ byBranch.set(current, row);
1336
+ }
1337
+ }
1338
+ }
1339
+ return [...byBranch.entries()]
1340
+ .map(([branch, d]) => ({ branch, cost: d.cost, calls: d.calls, sessions: d.sessions.size }))
1341
+ .sort((a, b) => b.cost - a.cost);
1342
+ }