unbound-cli 1.23.0 → 1.24.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.
package/README.md CHANGED
@@ -330,6 +330,32 @@ unbound trace 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c --json
330
330
 
331
331
  Terminal `mark-fp` records the same feedback as rejecting a risk score in the dashboard. It does not hide the run. Data security `mark-fp` moves the detection to `--findings false-positive`, and the gateway then skips that value for the organization. The CLI never shows a detected value or the prompt it was found in; see them in the console.
332
332
 
333
+ ### Delivery
334
+
335
+ Needs Admin or Analytics Viewer over the whole organization (a token needs `analytics=view` and org scope). Read-only.
336
+
337
+ | Command | Description |
338
+ |---------|-------------|
339
+ | `unbound delivery summary` | AI branches, PRs opened and merged, merge rate, AI spend, cost per PR and time to first PR |
340
+ | `unbound delivery branches` | AI branches with their PR, ticket, work group, users and cost (`--outcome`, `--ticket-status`, `--work-group`, `--search`, `--sort first_seen\|cost`) |
341
+ | `unbound delivery branch <id>` | One branch with its PR and ticket links, timeline and sessions |
342
+ | `unbound delivery users` | AI spend, PRs raised and merged per person (`--sort ai_spend`, `merge_rate_pct`, ...) |
343
+ | `unbound delivery teams` | The same per department, with active AI users and share of branches with a ticket |
344
+ | `unbound delivery spend --by outcome\|work-group` | AI spend by PR outcome, or by work group (`--pr-state all\|merged\|open\|no_pr`) |
345
+ | `unbound delivery repos` | Repositories with AI work in the window, the values `--repo` takes |
346
+
347
+ Every command except `branch` takes `--time-window ONE_DAY|THREE_DAYS|SEVEN_DAYS|FOURTEEN_DAYS|THIRTY_DAYS` (default `THIRTY_DAYS`) or `--start/--end YYYY-MM-DD` (max 31 days, within the last 31 days). `summary`, `branches`, `users`, `teams` and `spend` also filter by `--user` (user IDs, not emails), `--team`, `--manager`, `--tool` and `--repo`. `--json` prints the raw response.
348
+
349
+ ```bash
350
+ unbound delivery summary --time-window SEVEN_DAYS
351
+ unbound delivery branches --outcome merged --json | jq '.results[] | {name, pr: .pr.number, cost}'
352
+ unbound delivery branch 4821
353
+ unbound delivery users --sort merge_rate_pct --team Platform
354
+ unbound delivery spend --by work-group --pr-state merged
355
+ ```
356
+
357
+ A PR appears only when an agent's own tool call created it. Merge counts and cost per merged PR need GitHub connected.
358
+
333
359
  ## Configuration
334
360
 
335
361
  Config is stored in `~/.unbound/config.json`. For tenant deployments, point the CLI at your own hosts in one command (recommended for new installs):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unbound-cli",
3
- "version": "1.23.0",
3
+ "version": "1.24.0",
4
4
  "description": "CLI tool for Unbound - AI Gateway management",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -0,0 +1,567 @@
1
+ const api = require('../api');
2
+ const config = require('../config');
3
+ const output = require('../output');
4
+ const { sanitizeForTerminal } = require('../chartRender');
5
+ const { buildQueryString, parseList, resolveWindow, TIME_WINDOWS, DEFAULT_TIME_WINDOW } = require('../lib/analytics-query');
6
+
7
+ const BASE_PATH = '/api/v1/analytics/delivery';
8
+
9
+ // Delivery covers at most a month, so the 90-day preset is left out.
10
+ const DELIVERY_TIME_WINDOWS = TIME_WINDOWS.filter((window) => window !== 'THREE_MONTHS');
11
+ const OUTCOMES = ['merged', 'in_review', 'closed', 'no_pr', 'pr_raised'];
12
+ const TICKET_STATUSES = ['done', 'in_progress', 'todo', 'canceled', 'unsynced', 'untracked'];
13
+ const WORK_GROUPS = ['build', 'fix', 'improve', 'infra_ops', 'unknown'];
14
+ const BRANCH_SORTS = ['first_seen', 'cost'];
15
+ // The server sorts only by a column it shows, so each table offers its own columns.
16
+ const USER_SORTS = [
17
+ 'prs_raised', 'prs_merged', 'merge_rate_pct', 'ai_spend', 'cost_per_merged_pr', 'cost_per_pr', 'last_active',
18
+ ];
19
+ const TEAM_SORTS = [
20
+ 'active_ai_users', 'ai_branches', 'prs_raised', 'prs_merged', 'merge_rate_pct', 'ai_spend', 'cost_per_merged_pr',
21
+ 'cost_per_pr', 'with_ticket_pct',
22
+ ];
23
+ const PEOPLE_SORTS = { users: USER_SORTS, teams: TEAM_SORTS };
24
+ const SORT_ORDERS = ['desc', 'asc'];
25
+ const SPEND_BY = ['outcome', 'work_group'];
26
+ const PR_STATES = ['all', 'merged', 'open', 'no_pr'];
27
+ const MAX_PAGE_SIZE = 100;
28
+ const MAX_CUSTOM_RANGE_DAYS = 31;
29
+ const MAX_DETAIL_SESSIONS = 100;
30
+ const DAY_MS = 24 * 60 * 60 * 1000;
31
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32
+
33
+ const OUTCOME_LABELS = { merged: 'Merged', in_review: 'In review', closed: 'Closed', no_pr: 'No PR' };
34
+ const WORK_GROUP_LABELS = { build: 'Build', fix: 'Fix', improve: 'Improve', infra_ops: 'Infra / ops', unknown: 'Unknown' };
35
+
36
+ const FORBIDDEN_MESSAGE = 'Delivery analytics needs Admin or Analytics Viewer over the whole organization '
37
+ + '(a token needs analytics=view and org scope).';
38
+ const NOT_SERVED_MESSAGE = 'This Unbound backend does not serve Delivery analytics yet.';
39
+
40
+ const WINDOW_HELP = `
41
+ TIME RANGE
42
+ --time-window <w> ${DELIVERY_TIME_WINDOWS.join(' | ')}
43
+ Default ${DEFAULT_TIME_WINDOW}.
44
+ --start, --end Custom range as YYYY-MM-DD. Max 31 days, within the last 31 days.
45
+ Not with --time-window.
46
+ `;
47
+
48
+ const FILTER_HELP = `
49
+ FILTERS (comma-separated)
50
+ --user User IDs --team Department names
51
+ --manager Manager names --tool AI tool types, e.g. CLAUDE_CODE,CURSOR
52
+ --repo Repositories as owner/repo (see \`unbound delivery repos\`)
53
+ An unknown --tool type is ignored by the server, so check the spelling.
54
+ `;
55
+
56
+ const PEOPLE_HELP = `
57
+ Columns depend on whether GitHub is connected: merges and cost per merged PR need it.
58
+ `;
59
+
60
+ function requireLogin() {
61
+ if (!config.isLoggedIn()) {
62
+ throw new Error('Not logged in. Run `unbound login` first.');
63
+ }
64
+ }
65
+
66
+ function describeError(err, branchId) {
67
+ if (!(err instanceof api.ApiError)) return err.message;
68
+ if (err.statusCode === 403) return FORBIDDEN_MESSAGE;
69
+ const serverError = typeof err.body?.error === 'string' ? err.body.error : null;
70
+ if (err.statusCode === 404 && !serverError) return NOT_SERVED_MESSAGE;
71
+ if (err.statusCode === 404 && branchId !== undefined && serverError === 'Branch not found') {
72
+ return `Branch ${branchId} not found in your organization.`;
73
+ }
74
+ return sanitizeForTerminal(err.message);
75
+ }
76
+
77
+ async function run(fn, branchId) {
78
+ try {
79
+ requireLogin();
80
+ await fn();
81
+ } catch (err) {
82
+ output.error(describeError(err, branchId));
83
+ process.exitCode = 1;
84
+ }
85
+ }
86
+
87
+ function normalizeChoice(value) {
88
+ return String(value).trim().toLowerCase().replace(/-/g, '_');
89
+ }
90
+
91
+ function parseChoice(flag, value, choices) {
92
+ if (value === undefined) return undefined;
93
+ const choice = normalizeChoice(value);
94
+ if (!choices.includes(choice)) {
95
+ throw new Error(`Invalid ${flag} "${value}". Must be one of: ${choices.join(', ')}.`);
96
+ }
97
+ return choice;
98
+ }
99
+
100
+ function parseChoices(flag, value, choices) {
101
+ return parseList(value).map((item) => parseChoice(flag, item, choices));
102
+ }
103
+
104
+ function parsePositiveInt(flag, value) {
105
+ const number = Number(value);
106
+ if (!Number.isInteger(number) || number < 1) {
107
+ throw new Error(`Invalid ${flag} "${value}". Must be a positive integer.`);
108
+ }
109
+ return number;
110
+ }
111
+
112
+ function resolveDeliveryWindow(opts) {
113
+ if (opts.timeWindow && !opts.start && !opts.end) {
114
+ const timeWindow = opts.timeWindow.toUpperCase().replace(/-/g, '_');
115
+ if (!DELIVERY_TIME_WINDOWS.includes(timeWindow)) {
116
+ throw new Error(`Invalid --time-window "${opts.timeWindow}". Must be one of: ${DELIVERY_TIME_WINDOWS.join(', ')}.`);
117
+ }
118
+ }
119
+ // Checked first so ranges over 90 days get the 31-day message, not resolveWindow's 90-day one.
120
+ if (opts.start && opts.end && !Number.isNaN(Date.parse(opts.start)) && !Number.isNaN(Date.parse(opts.end))) {
121
+ checkCustomRange({ start_date: opts.start, end_date: opts.end });
122
+ }
123
+ return resolveWindow(opts);
124
+ }
125
+
126
+ // Counts both ends, like the server's (end - start).days + 1.
127
+ function checkCustomRange(window) {
128
+ const days = (Date.parse(window.end_date) - Date.parse(window.start_date)) / DAY_MS + 1;
129
+ if (days > MAX_CUSTOM_RANGE_DAYS) {
130
+ throw new Error(`Custom range cannot exceed ${MAX_CUSTOM_RANGE_DAYS} days (requested ${days} days).`);
131
+ }
132
+ }
133
+
134
+ // The server silently drops anything but numeric IDs and UUIDs, so an email would return an empty result.
135
+ function parseUserIds(value) {
136
+ const userIds = parseList(value);
137
+ const invalid = userIds.find((userId) => !/^\d+$/.test(userId) && !UUID_PATTERN.test(userId));
138
+ if (invalid) {
139
+ throw new Error(`Invalid --user "${invalid}". Use user IDs (see \`unbound delivery users --json\`), not emails.`);
140
+ }
141
+ return userIds;
142
+ }
143
+
144
+ function filterQuery(opts) {
145
+ return {
146
+ ...resolveDeliveryWindow(opts),
147
+ user_ids: parseUserIds(opts.user),
148
+ department_names: parseList(opts.team),
149
+ manager_names: parseList(opts.manager),
150
+ tool_types: parseList(opts.tool).map((tool) => tool.toUpperCase().replace(/-/g, '_')),
151
+ git_repos: parseList(opts.repo),
152
+ };
153
+ }
154
+
155
+ function pageQuery(opts, sortChoices) {
156
+ const query = {
157
+ page: opts.page === undefined ? 1 : parsePositiveInt('--page', opts.page),
158
+ search: opts.search,
159
+ sort_by: parseChoice('--sort', opts.sort, sortChoices),
160
+ sort_order: parseChoice('--order', opts.order, SORT_ORDERS),
161
+ };
162
+ if (opts.pageSize !== undefined) {
163
+ query.page_size = parsePositiveInt('--page-size', opts.pageSize);
164
+ if (query.page_size > MAX_PAGE_SIZE) throw new Error(`--page-size cannot exceed ${MAX_PAGE_SIZE}.`);
165
+ }
166
+ return query;
167
+ }
168
+
169
+ function ticketAndGroupQuery(opts) {
170
+ return {
171
+ status: parseChoices('--ticket-status', opts.ticketStatus, TICKET_STATUSES),
172
+ work_group: parseChoices('--work-group', opts.workGroup, WORK_GROUPS),
173
+ };
174
+ }
175
+
176
+ function fetchDelivery(path, query) {
177
+ const queryString = buildQueryString(query);
178
+ return api.get(`${BASE_PATH}/${path}/${queryString ? `?${queryString}` : ''}`);
179
+ }
180
+
181
+ function money(value) {
182
+ return value === null || value === undefined ? '-' : `$${Number(value).toFixed(2)}`;
183
+ }
184
+
185
+ function percent(value) {
186
+ return value === null || value === undefined ? '-' : `${value}%`;
187
+ }
188
+
189
+ function hours(value) {
190
+ return value === null || value === undefined ? '-' : `${value}h`;
191
+ }
192
+
193
+ function dateTime(value) {
194
+ const date = new Date(value);
195
+ return value && !Number.isNaN(date.getTime()) ? date.toISOString().slice(0, 16).replace('T', ' ') : '-';
196
+ }
197
+
198
+ function tokenCount(value) {
199
+ return value === null || value === undefined ? '-' : Number(value).toLocaleString();
200
+ }
201
+
202
+ function orDash(value) {
203
+ return value === null || value === undefined ? '-' : value;
204
+ }
205
+
206
+ function safe(value) {
207
+ return value === null || value === undefined || value === '' ? '-' : sanitizeForTerminal(String(value));
208
+ }
209
+
210
+ // Every value is sanitized: server strings must not reach the terminal raw.
211
+ function printKeyValue(pairs) {
212
+ output.keyValue(pairs.map(([key, value]) => [key, safe(value)]));
213
+ }
214
+
215
+ function totalPages(data) {
216
+ return Math.max(Math.ceil(Number(data.count || 0) / Number(data.page_size || 1)), 1);
217
+ }
218
+
219
+ function pageFooter(data, noun) {
220
+ const page = Number(data.page);
221
+ console.log('');
222
+ output.info(`Page ${page} of ${totalPages(data)} (${Number(data.count || 0).toLocaleString()} ${noun}).`);
223
+ if (page < totalPages(data)) output.info(`Next page: --page ${page + 1}`);
224
+ }
225
+
226
+ function printPastLastPage(data, noun) {
227
+ output.info(`Page ${Number(data.page)} is past the last page `
228
+ + `(${totalPages(data)} pages, ${Number(data.count).toLocaleString()} ${noun}).`);
229
+ }
230
+
231
+ async function showSummary(opts) {
232
+ const data = await fetchDelivery('summary', filterQuery(opts));
233
+ if (opts.json) {
234
+ output.json(data);
235
+ return;
236
+ }
237
+ const { connections, kpis } = data;
238
+ const github = Boolean(connections.github);
239
+ if (!github) {
240
+ output.warn('GitHub is not connected, so merges and cost per merged PR are unavailable.');
241
+ }
242
+ printKeyValue([
243
+ ['GitHub connected', github ? 'yes' : 'no'],
244
+ ['Ticket tracker', connections.ticket_tracker || 'none'],
245
+ ['AI branches', `${orDash(kpis.ai_branches.value)} (previous ${orDash(kpis.ai_branches.previous)})`],
246
+ ['PRs opened', `${orDash(kpis.prs_opened.value)} (previous ${orDash(kpis.prs_opened.previous)})`],
247
+ ['PRs merged', github
248
+ ? `${orDash(kpis.prs_merged.value)} (merge rate ${percent(kpis.prs_merged.merge_rate_pct)})`
249
+ : 'needs GitHub'],
250
+ ['AI spend', money(kpis.ai_spend)],
251
+ ['Cost per PR', money(kpis.cost_per_pr.value)],
252
+ ['Cost per merged PR', github ? money(kpis.cost_per_merged_pr.value) : 'needs GitHub'],
253
+ ['Time to first PR', `median ${hours(kpis.time_to_first_pr.median_hours)}, p90 ${hours(kpis.time_to_first_pr.p90_hours)}`],
254
+ ]);
255
+ }
256
+
257
+ function prLabel(pr) {
258
+ return `#${pr.number} ${pr.status}`;
259
+ }
260
+
261
+ function ticketLabel(ticket) {
262
+ return `${ticket.key} ${ticket.status || ticket.category}`;
263
+ }
264
+
265
+ function workGroupLabel(branch) {
266
+ const group = branch.work_group?.group;
267
+ if (group) return WORK_GROUP_LABELS[group] || group;
268
+ return branch.category_pending ? 'pending' : null;
269
+ }
270
+
271
+ function branchRow(branch) {
272
+ const { pr, ticket } = branch;
273
+ return [
274
+ String(branch.id),
275
+ branch.name,
276
+ branch.repository,
277
+ pr ? prLabel(pr) : '-',
278
+ ticket ? ticketLabel(ticket) : '-',
279
+ workGroupLabel(branch) || '-',
280
+ branch.users.map((user) => user.email || user.name).join(', ') || '-',
281
+ money(branch.cost),
282
+ String(branch.sessions),
283
+ dateTime(branch.first_seen),
284
+ ];
285
+ }
286
+
287
+ async function listBranches(opts) {
288
+ const query = {
289
+ ...filterQuery(opts),
290
+ ...pageQuery(opts, BRANCH_SORTS),
291
+ ...ticketAndGroupQuery(opts),
292
+ outcome: parseChoice('--outcome', opts.outcome, OUTCOMES),
293
+ };
294
+ const data = await fetchDelivery('branches', query);
295
+ if (opts.json) {
296
+ output.json(data);
297
+ return;
298
+ }
299
+ if (data.results.length === 0) {
300
+ if (data.count > 0) printPastLastPage(data, 'branches');
301
+ else output.info('No AI branches for this window and filter set.');
302
+ return;
303
+ }
304
+ const headers = ['ID', 'Branch', 'Repository', 'PR', 'Ticket', 'Work group', 'Users', 'Cost', 'Sessions', 'First seen'];
305
+ output.logTable(headers, data.results.map(branchRow), { wide: Boolean(opts.wide) });
306
+ pageFooter(data, 'branches');
307
+ output.info('Details: unbound delivery branch <ID>');
308
+ }
309
+
310
+ function linked(label, url) {
311
+ return url ? `${label} ${url}` : label;
312
+ }
313
+
314
+ async function showBranch(id, opts) {
315
+ const branchId = parsePositiveInt('branch ID', id);
316
+ const branch = await api.get(`${BASE_PATH}/branches/${branchId}/`);
317
+ if (opts.json) {
318
+ output.json(branch);
319
+ return;
320
+ }
321
+ const { pr, ticket, timeline } = branch;
322
+ printKeyValue([
323
+ ['Branch', branch.name],
324
+ ['Repository', branch.repository],
325
+ ['Pull request', pr ? linked(prLabel(pr), pr.url) : 'none'],
326
+ ['Ticket', ticket ? linked(ticketLabel(ticket), ticket.url) : 'none'],
327
+ ['Work group', workGroupLabel(branch)],
328
+ ['Cost', money(branch.cost)],
329
+ ['Tokens', tokenCount(branch.tokens)],
330
+ ['AI hours', hours(branch.ai_hours)],
331
+ ['First session', dateTime(timeline?.first_session_at)],
332
+ ['PR created', dateTime(timeline?.pr_created_at)],
333
+ ['Status seen', dateTime(timeline?.status_seen_at)],
334
+ ]);
335
+ console.log('');
336
+ if (branch.sessions.length === 0) {
337
+ output.info('No sessions on this branch.');
338
+ return;
339
+ }
340
+ const rows = branch.sessions.map((session) => [
341
+ String(session.task_id),
342
+ session.app_label || '-',
343
+ session.user ? session.user.email : '-',
344
+ dateTime(session.started_at),
345
+ String(session.duration_minutes),
346
+ money(session.cost),
347
+ tokenCount(session.tokens),
348
+ ]);
349
+ output.logTable(['Task ID', 'Tool', 'User', 'Started', 'Minutes', 'Cost', 'Tokens'], rows, { wide: Boolean(opts.wide) });
350
+ if (rows.length === MAX_DETAIL_SESSIONS) output.info(`Showing the newest ${MAX_DETAIL_SESSIONS} sessions.`);
351
+ }
352
+
353
+ function teamName(team) {
354
+ if (team && typeof team === 'object') {
355
+ const name = team.name || 'No team';
356
+ return team.manager ? `${name} (${team.manager})` : name;
357
+ }
358
+ return team || '-';
359
+ }
360
+
361
+ const PEOPLE_COLUMNS = {
362
+ user: { header: 'User', cell: (row) => row.user.email || row.user.name },
363
+ team: { header: 'Team', cell: (row) => teamName(row.team) },
364
+ active_ai_users: { header: 'Active AI users', cell: (row) => String(row.active_ai_users) },
365
+ ai_branches: { header: 'AI branches', cell: (row) => String(row.ai_branches) },
366
+ prs_raised: { header: 'PRs raised', cell: (row) => String(row.prs_raised) },
367
+ prs_merged: { header: 'PRs merged', cell: (row) => String(row.prs_merged) },
368
+ merge_rate_pct: { header: 'Merge rate', cell: (row) => percent(row.merge_rate_pct) },
369
+ ai_spend: { header: 'AI spend', cell: (row) => money(row.ai_spend) },
370
+ cost_per_merged_pr: { header: 'Cost per merged PR', cell: (row) => money(row.cost_per_merged_pr) },
371
+ cost_per_pr: { header: 'Cost per PR', cell: (row) => money(row.cost_per_pr) },
372
+ with_ticket_pct: { header: 'With ticket', cell: (row) => percent(row.with_ticket_pct) },
373
+ last_active: { header: 'Last active', cell: (row) => dateTime(row.last_active) },
374
+ };
375
+
376
+ function peopleColumn(key) {
377
+ return PEOPLE_COLUMNS[key] || { header: key, cell: (row) => String(row[key] ?? '-') };
378
+ }
379
+
380
+ function warnSortFallback(data, requestedSort) {
381
+ if (!requestedSort || !data.sort_by || data.sort_by === requestedSort) return;
382
+ const reason = data.github ? 'is shown only when GitHub is not connected' : 'needs GitHub connected';
383
+ output.warn(`Sorted by ${safe(data.sort_by)}: ${requestedSort} ${reason}.`);
384
+ }
385
+
386
+ async function listPeople(noun, opts) {
387
+ const query = { ...filterQuery(opts), ...pageQuery(opts, PEOPLE_SORTS[noun]), ...ticketAndGroupQuery(opts) };
388
+ const data = await fetchDelivery(noun, query);
389
+ warnSortFallback(data, query.sort_by);
390
+ if (opts.json) {
391
+ output.json(data);
392
+ return;
393
+ }
394
+ if (data.results.length === 0) {
395
+ if (data.count > 0) printPastLastPage(data, noun);
396
+ else output.info(`No ${noun} with AI branches or PRs for this window and filter set.`);
397
+ return;
398
+ }
399
+ const columns = data.columns.map(peopleColumn);
400
+ const rows = data.results.map((row) => columns.map((column) => column.cell(row)));
401
+ output.logTable(columns.map((column) => column.header), rows, { wide: Boolean(opts.wide) });
402
+ pageFooter(data, noun);
403
+ }
404
+
405
+ function printSpendByOutcome(data) {
406
+ const rows = data.outcomes.map((outcome) => [
407
+ OUTCOME_LABELS[outcome.key] || outcome.key,
408
+ String(outcome.count),
409
+ money(outcome.cost),
410
+ ]);
411
+ output.logTable(['Outcome', 'Branches', 'Spend'], rows);
412
+ console.log('');
413
+ output.info(`Total spend ${money(data.total_cost)} (${money(data.pr_raised_cost)} on branches with a PR).`);
414
+ }
415
+
416
+ function printSpendByWorkGroup(data) {
417
+ const rows = Object.entries(data.totals).map(([group, total]) => [
418
+ WORK_GROUP_LABELS[group] || group,
419
+ String(total.pull_requests),
420
+ money(total.cost),
421
+ ]);
422
+ output.logTable(['Work group', 'PRs', 'Spend'], rows);
423
+ console.log('');
424
+ output.info(`PR state: ${safe(data.pr_state)}. Closed PRs never count.`);
425
+ }
426
+
427
+ async function showSpend(opts) {
428
+ const by = parseChoice('--by', opts.by || 'outcome', SPEND_BY);
429
+ const prState = parseChoice('--pr-state', opts.prState, PR_STATES);
430
+ if (prState && by !== 'work_group') throw new Error('--pr-state applies only to --by work-group.');
431
+ const path = by === 'outcome' ? 'spend-by-outcome' : 'spend-by-work-group';
432
+ const data = await fetchDelivery(path, { ...filterQuery(opts), pr_state: prState });
433
+ if (opts.json) {
434
+ output.json(data);
435
+ return;
436
+ }
437
+ if (by === 'outcome') printSpendByOutcome(data);
438
+ else printSpendByWorkGroup(data);
439
+ }
440
+
441
+ async function listRepos(opts) {
442
+ const data = await fetchDelivery('filters', resolveDeliveryWindow(opts));
443
+ if (opts.json) {
444
+ output.json(data);
445
+ return;
446
+ }
447
+ if (data.repositories.length === 0) {
448
+ output.info('No repositories with AI branches in this window.');
449
+ return;
450
+ }
451
+ for (const repository of data.repositories) console.log(safe(repository));
452
+ console.log('');
453
+ output.info('Filter by one with --repo <owner/repo>.');
454
+ }
455
+
456
+ function addWindowOptions(command) {
457
+ return command
458
+ .option('--time-window <window>', `Preset window (default ${DEFAULT_TIME_WINDOW})`)
459
+ .option('--start <date>', 'Custom range start, YYYY-MM-DD (use with --end)')
460
+ .option('--end <date>', 'Custom range end, YYYY-MM-DD (use with --start)');
461
+ }
462
+
463
+ function addFilterOptions(command) {
464
+ return addWindowOptions(command)
465
+ .option('--user <users>', 'User IDs (number or UUID), comma-separated')
466
+ .option('--team <teams>', 'Department names, comma-separated')
467
+ .option('--manager <managers>', 'Manager names, comma-separated')
468
+ .option('--tool <types>', 'AI tool types, comma-separated, e.g. CLAUDE_CODE,CURSOR')
469
+ .option('--repo <repos>', 'Repositories as owner/repo, comma-separated');
470
+ }
471
+
472
+ function addTableOptions(command, sortChoices, defaultSort) {
473
+ return command
474
+ .option('--ticket-status <statuses>', `Ticket status, comma-separated: ${TICKET_STATUSES.join(', ')}`)
475
+ .option('--work-group <groups>', `Work group, comma-separated: ${WORK_GROUPS.join(', ')}`)
476
+ .option('--search <text>', 'Search text')
477
+ .option('--sort <column>', `${sortChoices.join(' | ')} (default ${defaultSort})`)
478
+ .option('--order <order>', 'desc | asc (default desc)')
479
+ .option('--page <n>', 'Page number')
480
+ .option('--page-size <n>', `Rows per page, up to ${MAX_PAGE_SIZE} (default 10)`)
481
+ .option('--json', 'Output the raw JSON response')
482
+ .option('--wide', 'Print full values instead of clipping to terminal width');
483
+ }
484
+
485
+ function register(program) {
486
+ const delivery = program
487
+ .command('delivery')
488
+ .description('Delivery analytics: AI branches, pull requests and what they cost (Analytics > Delivery).')
489
+ .addHelpText('after', `
490
+ Examples:
491
+ $ unbound delivery summary --time-window SEVEN_DAYS
492
+ $ unbound delivery branches --outcome merged --sort cost
493
+ $ unbound delivery branches --outcome merged --json | jq '.results[] | {name, pr: .pr.number, cost}'
494
+ $ unbound delivery branch 4821
495
+ $ unbound delivery users --sort merge_rate_pct --team Platform
496
+ $ unbound delivery spend --by work-group --pr-state merged
497
+
498
+ A PR appears only when an agent's own tool call created it.
499
+ Every command takes --json and prints the raw response.
500
+
501
+ Admin or Analytics Viewer (whole organization).
502
+ `);
503
+
504
+ addFilterOptions(delivery
505
+ .command('summary')
506
+ .description('Show the headline delivery numbers for the window.')
507
+ .option('--json', 'Output the raw JSON response'))
508
+ .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}`)
509
+ .action((opts) => run(() => showSummary(opts)));
510
+
511
+ addTableOptions(addFilterOptions(delivery
512
+ .command('branches')
513
+ .description('List AI branches created in the window.')
514
+ .option('--outcome <outcome>', `PR outcome: ${OUTCOMES.join(', ')}`)), BRANCH_SORTS, 'first_seen')
515
+ .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}
516
+ Examples:
517
+ $ unbound delivery branches --outcome no_pr --sort cost
518
+ $ unbound delivery branches --ticket-status done --work-group fix
519
+ $ unbound delivery branches --repo acme/web --page 2 --json
520
+
521
+ With --work-group, branches are windowed by PR time (merged, else opened) instead of first seen.
522
+ `)
523
+ .action((opts) => run(() => listBranches(opts)));
524
+
525
+ delivery
526
+ .command('branch <id>')
527
+ .description('Show one branch: PR, ticket, cost, timeline and sessions.')
528
+ .option('--json', 'Output the raw JSON response')
529
+ .option('--wide', 'Print full values instead of clipping to terminal width')
530
+ .action((id, opts) => run(() => showBranch(id, opts), id));
531
+
532
+ addTableOptions(addFilterOptions(delivery
533
+ .command('users')
534
+ .description('List people with AI branches or PRs in the window.')), PEOPLE_SORTS.users, 'ai_spend')
535
+ .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}${PEOPLE_HELP}`)
536
+ .action((opts) => run(() => listPeople('users', opts)));
537
+
538
+ addTableOptions(addFilterOptions(delivery
539
+ .command('teams')
540
+ .description('List departments with AI branches or PRs in the window.')), PEOPLE_SORTS.teams, 'ai_spend')
541
+ .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}${PEOPLE_HELP}`)
542
+ .action((opts) => run(() => listPeople('teams', opts)));
543
+
544
+ addFilterOptions(delivery
545
+ .command('spend')
546
+ .description('Show AI spend by PR outcome or by work group.')
547
+ .option('--by <dimension>', 'outcome | work-group (default outcome)')
548
+ .option('--pr-state <state>', `With --by work-group: ${PR_STATES.join(', ')} (default all)`)
549
+ .option('--json', 'Output the raw JSON response'))
550
+ .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}
551
+ Examples:
552
+ $ unbound delivery spend
553
+ $ unbound delivery spend --by work-group --pr-state merged
554
+ `)
555
+ .action((opts) => run(() => showSpend(opts)));
556
+
557
+ addWindowOptions(delivery
558
+ .command('repos')
559
+ .description('List repositories with AI branches or charted PRs in the window.')
560
+ .option('--json', 'Output the raw JSON response'))
561
+ .addHelpText('after', WINDOW_HELP)
562
+ .action((opts) => run(() => listRepos(opts)));
563
+
564
+ return delivery;
565
+ }
566
+
567
+ module.exports = { register };
package/src/index.js CHANGED
@@ -183,6 +183,15 @@ FLAGS AND FALSE POSITIVES (Admin/Analytics Viewer/Manager; mark-fp is Admin only
183
183
  Mark a detection as a false positive
184
184
  $ unbound trace <trace-id> Log, terminal runs and data security for one trace ID
185
185
 
186
+ DELIVERY (Admin/Analytics Viewer, whole organization)
187
+ $ unbound delivery summary Branches, PRs opened and merged, spend, cost per PR
188
+ $ unbound delivery branches AI branches with PR, ticket, work group and cost
189
+ $ unbound delivery branch <id> One branch with its timeline and sessions
190
+ $ unbound delivery users | teams Spend, PRs and merges per person or department
191
+ $ unbound delivery spend --by outcome|work-group
192
+ AI spend by PR outcome or work group
193
+ $ unbound delivery repos Repositories to pass to --repo
194
+
186
195
  FALSE POSITIVES ON YOUR OWN REQUESTS (any user)
187
196
  $ unbound false-positive list <trace-id> Your findings on a blocked request
188
197
  $ unbound false-positive mark <trace-id> Mark one as a false positive
@@ -232,6 +241,7 @@ require('./commands/user-groups').register(program);
232
241
  require('./commands/tools').register(program);
233
242
  require('./commands/analytics').register(program);
234
243
  require('./commands/flags').register(program);
244
+ require('./commands/delivery').register(program);
235
245
  require('./commands/trace').register(program);
236
246
  require('./commands/false-positive').register(program);
237
247
  require('./commands/download').register(program);
@@ -0,0 +1,591 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const http = require('http');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawn } = require('child_process');
8
+
9
+ const BASE = '/api/v1/analytics/delivery';
10
+
11
+ const SUMMARY = {
12
+ connections: { github: true, ticket_tracker: 'LINEAR' },
13
+ kpis: {
14
+ ai_branches: { value: 42, previous: 30 },
15
+ prs_opened: { value: 20, previous: 15 },
16
+ prs_merged: { value: 12, merge_rate_pct: 60, closed: 2 },
17
+ ai_spend: 321.5,
18
+ cost_per_pr: { value: 16.08 },
19
+ cost_per_merged_pr: { value: 26.79 },
20
+ time_to_first_pr: { median_hours: 3.5, p90_hours: 11.2 },
21
+ },
22
+ throughput_unit: 'week',
23
+ throughput: [],
24
+ };
25
+
26
+ const BRANCH = {
27
+ id: 4821,
28
+ name: 'feat/login',
29
+ repository: 'acme/web',
30
+ users: [{ id: 1, name: 'Ada', email: 'ada@example.com' }],
31
+ tools: ['claude-code'],
32
+ ticket: { key: 'WEB-12', status: 'Done', category: 'done', url: 'https://linear.app/acme/issue/WEB-12' },
33
+ pr: { number: 123, status: 'merged', url: 'https://github.com/acme/web/pull/123' },
34
+ work_group: { group: 'build' },
35
+ category_pending: false,
36
+ sessions: 3,
37
+ ai_hours: 1.5,
38
+ cost: 12.345,
39
+ tokens: 98765,
40
+ first_seen: '2026-11-20T10:15:00Z',
41
+ };
42
+
43
+ const BRANCHES = { count: 25, page: 1, page_size: 10, results: [BRANCH], category_counts: { all: 25 } };
44
+
45
+ const BRANCH_DETAIL = {
46
+ ...BRANCH,
47
+ timeline: { first_session_at: '2026-11-20T10:15:00Z', pr_created_at: '2026-11-21T09:00:00Z', status_seen_at: null },
48
+ sessions: [{
49
+ task_id: 777, app_label: 'claude-code', user: { id: 1, email: 'ada@example.com' },
50
+ started_at: '2026-11-20T10:15:00Z', duration_minutes: 42, cost: 4.5, tokens: 1200,
51
+ }],
52
+ };
53
+
54
+ const USERS = {
55
+ github: true,
56
+ columns: ['user', 'team', 'prs_raised', 'prs_merged', 'merge_rate_pct', 'ai_spend', 'cost_per_merged_pr', 'last_active'],
57
+ sort_by: 'ai_spend',
58
+ count: 1,
59
+ page: 1,
60
+ page_size: 10,
61
+ results: [{
62
+ user: { id: 1, name: 'Ada', email: 'ada@example.com' }, team: 'Platform', prs_raised: 9, prs_merged: 7,
63
+ merge_rate_pct: 78, ai_spend: 88.1, cost_per_merged_pr: 12.59, last_active: '2026-11-26T08:00:00Z', low_sample: false,
64
+ }],
65
+ };
66
+
67
+ const TEAMS = {
68
+ github: false,
69
+ columns: ['team', 'active_ai_users', 'ai_branches', 'prs_raised', 'ai_spend', 'cost_per_pr', 'with_ticket_pct'],
70
+ sort_by: 'ai_spend',
71
+ count: 1,
72
+ page: 1,
73
+ page_size: 10,
74
+ results: [{
75
+ team: { name: 'Platform', manager: 'Grace' }, active_ai_users: 4, ai_branches: 11, prs_raised: 6,
76
+ ai_spend: 140.25, cost_per_pr: 23.38, with_ticket_pct: 82, low_sample: false,
77
+ }],
78
+ };
79
+
80
+ const SPEND_OUTCOME = {
81
+ total_cost: 200,
82
+ pr_raised_cost: 150,
83
+ outcomes: [
84
+ { key: 'merged', cost: 120, count: 8 },
85
+ { key: 'in_review', cost: 30, count: 3 },
86
+ { key: 'closed', cost: 0, count: 0 },
87
+ { key: 'no_pr', cost: 50, count: 6 },
88
+ ],
89
+ };
90
+
91
+ const SPEND_WORK_GROUP = {
92
+ unit: 'week',
93
+ pr_state: 'merged',
94
+ buckets: [],
95
+ totals: {
96
+ build: { cost: 90, pull_requests: 5 },
97
+ fix: { cost: 40, pull_requests: 4 },
98
+ improve: { cost: 0, pull_requests: 0 },
99
+ infra_ops: { cost: 10, pull_requests: 1 },
100
+ unknown: { cost: 0, pull_requests: 0 },
101
+ },
102
+ };
103
+
104
+ const REPOS = { repositories: ['acme/api', 'acme/web'] };
105
+
106
+ // An OSC 8 hyperlink and a red CSI colour, the two ways a server string could hijack the terminal.
107
+ const ESC = '\x1b';
108
+ const EVIL = `${ESC}]8;;https://evil.example${ESC}\\${ESC}[31m`;
109
+
110
+ function assertNoEscapes(text) {
111
+ assert.ok(!text.includes(ESC), `escape sequence reached the terminal:\n${JSON.stringify(text)}`);
112
+ }
113
+
114
+ const ROUTES = {
115
+ [`${BASE}/summary/`]: SUMMARY,
116
+ [`${BASE}/branches/`]: BRANCHES,
117
+ [`${BASE}/branches/4821/`]: BRANCH_DETAIL,
118
+ [`${BASE}/users/`]: USERS,
119
+ [`${BASE}/teams/`]: TEAMS,
120
+ [`${BASE}/spend-by-outcome/`]: SPEND_OUTCOME,
121
+ [`${BASE}/spend-by-work-group/`]: SPEND_WORK_GROUP,
122
+ [`${BASE}/filters/`]: REPOS,
123
+ };
124
+
125
+ const allRequests = [];
126
+
127
+ function startServer(routes) {
128
+ const seen = [];
129
+ const server = http.createServer((req, res) => {
130
+ req.resume();
131
+ req.on('end', () => {
132
+ const url = new URL(req.url, 'http://x');
133
+ const request = { method: req.method, path: url.pathname, query: url.searchParams };
134
+ seen.push(request);
135
+ allRequests.push(request);
136
+ const [status, payload] = routes(req.method, url) || [404, { error: 'no route' }];
137
+ res.writeHead(status, { 'Content-Type': 'application/json' });
138
+ res.end(JSON.stringify(payload));
139
+ });
140
+ });
141
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ server, seen, port: server.address().port })));
142
+ }
143
+
144
+ function mockBackend() {
145
+ return startServer((method, url) => (ROUTES[url.pathname] ? [200, ROUTES[url.pathname]] : null));
146
+ }
147
+
148
+ function runCli(port, args) {
149
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'delivery-test-'));
150
+ fs.mkdirSync(path.join(home, '.unbound'));
151
+ fs.writeFileSync(path.join(home, '.unbound', 'config.json'),
152
+ JSON.stringify({ api_key: 'test-key', base_url: `http://127.0.0.1:${port}` }));
153
+ return new Promise((resolve) => {
154
+ const child = spawn('node', [path.join(__dirname, '..', 'src', 'index.js'), ...args], {
155
+ env: {
156
+ ...process.env, HOME: home, UNBOUND_TOKEN: 'test-key', UNBOUND_API_URL: '', UNBOUND_TELEMETRY: '0',
157
+ UNBOUND_NO_UPDATE_CHECK: '1', COLUMNS: '400',
158
+ },
159
+ });
160
+ let stdout = '';
161
+ let stderr = '';
162
+ child.stdout.on('data', (d) => { stdout += d; });
163
+ child.stderr.on('data', (d) => { stderr += d; });
164
+ child.on('close', (code) => {
165
+ fs.rmSync(home, { recursive: true, force: true });
166
+ resolve({ code, stdout, stderr });
167
+ });
168
+ });
169
+ }
170
+
171
+ async function withBackend(fn, backend = mockBackend) {
172
+ const { server, seen, port } = await backend();
173
+ try {
174
+ await fn({ seen, run: (args) => runCli(port, args) });
175
+ } finally {
176
+ server.close();
177
+ }
178
+ }
179
+
180
+ test('summary prints the KPIs with the default 30-day window, and --json prints the raw body', async () => {
181
+ await withBackend(async ({ seen, run }) => {
182
+ const table = await run(['delivery', 'summary']);
183
+ assert.equal(table.code, 0, table.stderr);
184
+ assert.equal(seen[0].path, `${BASE}/summary/`);
185
+ assert.equal(seen[0].query.get('time_window'), 'THIRTY_DAYS');
186
+ for (const text of ['GitHub connected', 'yes', 'LINEAR', '42 (previous 30)', 'merge rate 60%', '$321.50',
187
+ 'Cost per merged PR', '$26.79', 'median 3.5h, p90 11.2h']) {
188
+ assert.ok(table.stdout.includes(text), `${text} missing from:\n${table.stdout}`);
189
+ }
190
+ const json = await run(['delivery', 'summary', '--json']);
191
+ assert.deepEqual(JSON.parse(json.stdout), SUMMARY);
192
+ });
193
+ });
194
+
195
+ test('summary without GitHub warns and marks merges and cost per merged PR as needing GitHub', async () => {
196
+ const noGithub = { ...SUMMARY, connections: { github: false, ticket_tracker: null } };
197
+ await withBackend(async ({ run }) => {
198
+ const r = await run(['delivery', 'summary']);
199
+ assert.equal(r.code, 0, r.stderr);
200
+ assert.match(r.stderr, /GitHub is not connected, so merges and cost per merged PR are unavailable\./);
201
+ assert.ok(r.stdout.includes('none'), r.stdout);
202
+ assert.match(r.stdout, /PRs merged\s+needs GitHub/);
203
+ assert.match(r.stdout, /Cost per merged PR\s+needs GitHub/);
204
+ assert.ok(!r.stdout.includes('$26.79'), r.stdout);
205
+ }, () => startServer(() => [200, noGithub]));
206
+ });
207
+
208
+ test('summary prints - for null KPIs and strips escapes from the ticket tracker', async () => {
209
+ const nullKpis = {
210
+ connections: { github: true, ticket_tracker: `${EVIL}JIRA` },
211
+ kpis: {
212
+ ai_branches: { value: null, previous: null },
213
+ prs_opened: { value: null, previous: null },
214
+ prs_merged: { value: null, merge_rate_pct: null },
215
+ ai_spend: null,
216
+ cost_per_pr: { value: null },
217
+ cost_per_merged_pr: { value: null },
218
+ time_to_first_pr: { median_hours: null, p90_hours: null },
219
+ },
220
+ };
221
+ await withBackend(async ({ run }) => {
222
+ const r = await run(['delivery', 'summary']);
223
+ assert.equal(r.code, 0, r.stderr);
224
+ assertNoEscapes(r.stdout);
225
+ assert.ok(r.stdout.includes('JIRA'), r.stdout);
226
+ assert.match(r.stdout, /AI branches\s+- \(previous -\)/);
227
+ assert.match(r.stdout, /PRs merged\s+- \(merge rate -\)/);
228
+ assert.match(r.stdout, /AI spend\s+-\n/);
229
+ assert.match(r.stdout, /Cost per merged PR\s+-\n/);
230
+ assert.match(r.stdout, /Time to first PR\s+median -, p90 -/);
231
+ assert.ok(!r.stdout.includes('null') && !r.stdout.includes('undefined'), r.stdout);
232
+ }, () => startServer(() => [200, nullKpis]));
233
+ });
234
+
235
+ test('summary sends the window and every people, tool and repo filter', async () => {
236
+ await withBackend(async ({ seen, run }) => {
237
+ const r = await run(['delivery', 'summary', '--start', '2026-11-01', '--end', '2026-11-20',
238
+ '--user', '7,3f2b8c1e-9a4d-4e2f-8b6a-1c2d3e4f5a6b', '--team', 'Platform', '--manager', 'Grace',
239
+ '--tool', 'claude-code,cursor', '--repo', 'acme/web,acme/api']);
240
+ assert.equal(r.code, 0, r.stderr);
241
+ const { query } = seen[0];
242
+ assert.equal(query.get('start_date'), '2026-11-01');
243
+ assert.equal(query.get('end_date'), '2026-11-20');
244
+ assert.equal(query.get('time_window'), null);
245
+ assert.deepEqual(query.getAll('user_ids'), ['7', '3f2b8c1e-9a4d-4e2f-8b6a-1c2d3e4f5a6b']);
246
+ assert.deepEqual(query.getAll('department_names'), ['Platform']);
247
+ assert.deepEqual(query.getAll('manager_names'), ['Grace']);
248
+ assert.deepEqual(query.getAll('tool_types'), ['CLAUDE_CODE', 'CURSOR']);
249
+ assert.deepEqual(query.getAll('git_repos'), ['acme/web', 'acme/api']);
250
+ });
251
+ });
252
+
253
+ test('branches sends its filters as repeated keys and prints rows with a page footer', async () => {
254
+ await withBackend(async ({ seen, run }) => {
255
+ const r = await run(['delivery', 'branches', '--outcome', 'merged', '--ticket-status', 'done,in-progress',
256
+ '--work-group', 'build,infra_ops', '--search', 'login', '--sort', 'cost', '--order', 'asc',
257
+ '--page-size', '10', '--time-window', 'seven_days']);
258
+ assert.equal(r.code, 0, r.stderr);
259
+ const { path: requestPath, query } = seen[0];
260
+ assert.equal(requestPath, `${BASE}/branches/`);
261
+ assert.equal(query.get('outcome'), 'merged');
262
+ assert.deepEqual(query.getAll('status'), ['done', 'in_progress']);
263
+ assert.deepEqual(query.getAll('work_group'), ['build', 'infra_ops']);
264
+ assert.equal(query.get('search'), 'login');
265
+ assert.equal(query.get('sort_by'), 'cost');
266
+ assert.equal(query.get('sort_order'), 'asc');
267
+ assert.equal(query.get('page'), '1');
268
+ assert.equal(query.get('page_size'), '10');
269
+ assert.equal(query.get('time_window'), 'SEVEN_DAYS');
270
+ assert.equal(query.get('pr_state'), null);
271
+ for (const text of ['4821', 'feat/login', 'acme/web', '#123 merged', 'WEB-12 Done', 'Build', 'ada@example.com',
272
+ '$12.35', '2026-11-20 10:15']) {
273
+ assert.ok(r.stdout.includes(text), `${text} missing from:\n${r.stdout}`);
274
+ }
275
+ assert.match(r.stderr, /Page 1 of 3 \(25 branches\)/);
276
+ assert.match(r.stderr, /Next page: --page 2/);
277
+ assert.match(r.stderr, /unbound delivery branch <ID>/);
278
+ const json = await run(['delivery', 'branches', '--json']);
279
+ assert.deepEqual(JSON.parse(json.stdout), BRANCHES);
280
+ assert.equal(seen[1].query.get('page'), '1');
281
+ assert.equal(seen[1].query.get('time_window'), 'THIRTY_DAYS');
282
+ });
283
+ });
284
+
285
+ test('branches shows a message when nothing matches', async () => {
286
+ await withBackend(async ({ run }) => {
287
+ const r = await run(['delivery', 'branches']);
288
+ assert.equal(r.code, 0, r.stderr);
289
+ assert.match(r.stderr, /No AI branches/);
290
+ }, () => startServer(() => [200, { count: 0, page: 1, page_size: 10, results: [] }]));
291
+ });
292
+
293
+ test('branches prints - for a branch with no PR, ticket, users or work group, and pending while categorizing', async () => {
294
+ const bare = { ...BRANCH, pr: null, ticket: null, work_group: { group: null }, category_pending: true, users: [] };
295
+ await withBackend(async ({ run }) => {
296
+ const r = await run(['delivery', 'branches']);
297
+ assert.equal(r.code, 0, r.stderr);
298
+ const row = r.stdout.split('\n').find((line) => line.includes('feat/login'));
299
+ assert.ok(row, r.stdout);
300
+ assert.match(row, /4821\s+feat\/login\s+acme\/web\s+-\s+-\s+pending\s+-\s+\$12\.35/);
301
+ }, () => startServer(() => [200, { ...BRANCHES, results: [bare] }]));
302
+ });
303
+
304
+ test('branches strips terminal escapes from server strings', async () => {
305
+ const evil = { ...BRANCH, name: `${EVIL}feat/evil`, first_seen: `${EVIL}2026-11-20T10:15:00Z` };
306
+ await withBackend(async ({ run }) => {
307
+ const r = await run(['delivery', 'branches']);
308
+ assert.equal(r.code, 0, r.stderr);
309
+ assertNoEscapes(r.stdout);
310
+ assert.ok(r.stdout.includes('feat/evil'), r.stdout);
311
+ }, () => startServer(() => [200, { ...BRANCHES, results: [evil] }]));
312
+ });
313
+
314
+ test('a page past the last one says so instead of reporting no data', async () => {
315
+ const pastEnd = { count: 25, page: 9, page_size: 10, results: [] };
316
+ await withBackend(async ({ run }) => {
317
+ const branches = await run(['delivery', 'branches', '--page', '9']);
318
+ assert.equal(branches.code, 0, branches.stderr);
319
+ assert.match(branches.stderr, /Page 9 is past the last page \(3 pages, 25 branches\)\./);
320
+ assert.doesNotMatch(branches.stderr, /No AI branches/);
321
+ const users = await run(['delivery', 'users', '--page', '9']);
322
+ assert.equal(users.code, 0, users.stderr);
323
+ assert.match(users.stderr, /Page 9 is past the last page \(3 pages, 25 users\)\./);
324
+ const teams = await run(['delivery', 'teams', '--page', '9']);
325
+ assert.match(teams.stderr, /Page 9 is past the last page \(3 pages, 25 teams\)\./);
326
+ }, () => startServer(() => [200, { ...pastEnd, columns: ['user'] }]));
327
+ });
328
+
329
+ test('branch shows the detail and its sessions, and --json prints the raw body', async () => {
330
+ await withBackend(async ({ seen, run }) => {
331
+ const r = await run(['delivery', 'branch', '4821']);
332
+ assert.equal(r.code, 0, r.stderr);
333
+ assert.equal(seen[0].path, `${BASE}/branches/4821/`);
334
+ for (const text of ['feat/login', '#123 merged https://github.com/acme/web/pull/123',
335
+ 'WEB-12 Done https://linear.app/acme/issue/WEB-12', '98,765', '1.5h', '777', 'claude-code', '42', '$4.50']) {
336
+ assert.ok(r.stdout.includes(text), `${text} missing from:\n${r.stdout}`);
337
+ }
338
+ assert.match(r.stdout, /Work group\s+Build/);
339
+ assert.doesNotMatch(r.stderr, /Showing the newest/);
340
+ const json = await run(['delivery', 'branch', '4821', '--json']);
341
+ assert.deepEqual(JSON.parse(json.stdout), BRANCH_DETAIL);
342
+ });
343
+ });
344
+
345
+ test('branch detail strips terminal escapes from names, links and times', async () => {
346
+ const evil = {
347
+ ...BRANCH_DETAIL,
348
+ name: `${EVIL}feat/evil`,
349
+ repository: `${EVIL}acme/web`,
350
+ ticket: { ...BRANCH.ticket, url: `${EVIL}https://linear.app/x` },
351
+ timeline: { first_session_at: `${EVIL}2026-11-20`, pr_created_at: null, status_seen_at: null },
352
+ };
353
+ await withBackend(async ({ run }) => {
354
+ const r = await run(['delivery', 'branch', '4821']);
355
+ assert.equal(r.code, 0, r.stderr);
356
+ assertNoEscapes(r.stdout);
357
+ assert.ok(r.stdout.includes('feat/evil') && r.stdout.includes('https://linear.app/x'), r.stdout);
358
+ assert.match(r.stdout, /First session\s+-/);
359
+ }, () => startServer(() => [200, evil]));
360
+ });
361
+
362
+ test('branch detail with no sessions, null tokens and an empty ticket URL', async () => {
363
+ const empty = { ...BRANCH_DETAIL, sessions: [], tokens: null, ticket: { ...BRANCH.ticket, url: '' } };
364
+ await withBackend(async ({ run }) => {
365
+ const r = await run(['delivery', 'branch', '4821']);
366
+ assert.equal(r.code, 0, r.stderr);
367
+ assert.match(r.stdout, /Ticket\s+WEB-12 Done\n/);
368
+ assert.match(r.stdout, /Tokens\s+-\n/);
369
+ assert.match(r.stderr, /No sessions on this branch/);
370
+ }, () => startServer(() => [200, empty]));
371
+ });
372
+
373
+ test('branch detail says when only the newest 100 sessions are shown', async () => {
374
+ const sessions = Array.from({ length: 100 }, (_, index) => ({ ...BRANCH_DETAIL.sessions[0], task_id: index + 1 }));
375
+ await withBackend(async ({ run }) => {
376
+ const r = await run(['delivery', 'branch', '4821']);
377
+ assert.equal(r.code, 0, r.stderr);
378
+ assert.match(r.stderr, /Showing the newest 100 sessions\./);
379
+ }, () => startServer(() => [200, { ...BRANCH_DETAIL, sessions }]));
380
+ });
381
+
382
+ test('users and teams send sort, page and ticket filters and print the columns the server lists', async () => {
383
+ await withBackend(async ({ seen, run }) => {
384
+ const users = await run(['delivery', 'users', '--sort', 'merge_rate_pct', '--page', '2', '--ticket-status', 'todo',
385
+ '--work-group', 'fix', '--team', 'Platform']);
386
+ assert.equal(users.code, 0, users.stderr);
387
+ assert.equal(seen[0].path, `${BASE}/users/`);
388
+ assert.equal(seen[0].query.get('sort_by'), 'merge_rate_pct');
389
+ assert.equal(seen[0].query.get('page'), '2');
390
+ assert.deepEqual(seen[0].query.getAll('status'), ['todo']);
391
+ assert.deepEqual(seen[0].query.getAll('work_group'), ['fix']);
392
+ assert.deepEqual(seen[0].query.getAll('department_names'), ['Platform']);
393
+ for (const text of ['User', 'Merge rate', 'Cost per merged PR', 'ada@example.com', 'Platform', '78%', '$88.10']) {
394
+ assert.ok(users.stdout.includes(text), `${text} missing from:\n${users.stdout}`);
395
+ }
396
+ assert.match(users.stderr, /Page 1 of 1 \(1 users\)/);
397
+
398
+ const teams = await run(['delivery', 'teams']);
399
+ assert.equal(teams.code, 0, teams.stderr);
400
+ assert.equal(seen[1].path, `${BASE}/teams/`);
401
+ assert.equal(seen[1].query.get('page'), '1');
402
+ for (const text of ['Active AI users', 'With ticket', 'Platform (Grace)', '$140.25', '82%', 'Cost per PR']) {
403
+ assert.ok(teams.stdout.includes(text), `${text} missing from:\n${teams.stdout}`);
404
+ }
405
+ assert.ok(!teams.stdout.includes('Cost per merged PR'), 'teams without GitHub show no merge columns');
406
+
407
+ assert.deepEqual(JSON.parse((await run(['delivery', 'users', '--json'])).stdout), USERS);
408
+ assert.deepEqual(JSON.parse((await run(['delivery', 'teams', '--json'])).stdout), TEAMS);
409
+ });
410
+ });
411
+
412
+ test('users without GitHub print the cost per PR column and no merge columns', async () => {
413
+ const noGithub = {
414
+ ...USERS,
415
+ github: false,
416
+ columns: ['user', 'team', 'prs_raised', 'ai_spend', 'cost_per_pr', 'last_active'],
417
+ results: [{
418
+ user: { id: 1, name: 'Ada', email: 'ada@example.com' }, team: 'Platform', prs_raised: 9, ai_spend: 88.1,
419
+ cost_per_pr: 9.79, last_active: '2026-11-26T08:00:00Z', low_sample: false,
420
+ }],
421
+ };
422
+ await withBackend(async ({ run }) => {
423
+ const r = await run(['delivery', 'users']);
424
+ assert.equal(r.code, 0, r.stderr);
425
+ for (const text of ['Cost per PR', '$9.79', 'PRs raised', '2026-11-26 08:00']) {
426
+ assert.ok(r.stdout.includes(text), `${text} missing from:\n${r.stdout}`);
427
+ }
428
+ assert.ok(!r.stdout.includes('Merge rate') && !r.stdout.includes('Cost per merged PR'), r.stdout);
429
+ }, () => startServer(() => [200, noGithub]));
430
+ });
431
+
432
+ test('users and teams warn when the server sorted by another column', async () => {
433
+ const fellBack = { ...TEAMS, sort_by: 'ai_spend' };
434
+ await withBackend(async ({ run }) => {
435
+ const r = await run(['delivery', 'teams', '--sort', 'merge_rate_pct']);
436
+ assert.equal(r.code, 0, r.stderr);
437
+ assert.match(r.stderr, /Sorted by ai_spend: merge_rate_pct needs GitHub connected\./);
438
+ const asked = await run(['delivery', 'teams', '--sort', 'ai_spend']);
439
+ assert.doesNotMatch(asked.stderr, /Sorted by/);
440
+ const unsorted = await run(['delivery', 'teams']);
441
+ assert.doesNotMatch(unsorted.stderr, /Sorted by/);
442
+ }, () => startServer(() => [200, fellBack]));
443
+ });
444
+
445
+ test('teams strips terminal escapes from team names', async () => {
446
+ const evil = { ...TEAMS, results: [{ ...TEAMS.results[0], team: { name: `${EVIL}Platform`, manager: null } }] };
447
+ await withBackend(async ({ run }) => {
448
+ const r = await run(['delivery', 'teams']);
449
+ assert.equal(r.code, 0, r.stderr);
450
+ assertNoEscapes(r.stdout);
451
+ assert.ok(r.stdout.includes('Platform'), r.stdout);
452
+ }, () => startServer(() => [200, evil]));
453
+ });
454
+
455
+ test('spend defaults to outcome and switches to work group with a PR state', async () => {
456
+ await withBackend(async ({ seen, run }) => {
457
+ const outcome = await run(['delivery', 'spend', '--repo', 'acme/web']);
458
+ assert.equal(outcome.code, 0, outcome.stderr);
459
+ assert.equal(seen[0].path, `${BASE}/spend-by-outcome/`);
460
+ assert.equal(seen[0].query.get('pr_state'), null);
461
+ assert.deepEqual(seen[0].query.getAll('git_repos'), ['acme/web']);
462
+ for (const text of ['Merged', 'In review', 'No PR', '$120.00', '$50.00']) {
463
+ assert.ok(outcome.stdout.includes(text), `${text} missing from:\n${outcome.stdout}`);
464
+ }
465
+ assert.match(outcome.stderr, /Total spend \$200\.00 \(\$150\.00 on branches with a PR\)/);
466
+
467
+ const workGroup = await run(['delivery', 'spend', '--by', 'work-group', '--pr-state', 'merged']);
468
+ assert.equal(workGroup.code, 0, workGroup.stderr);
469
+ assert.equal(seen[1].path, `${BASE}/spend-by-work-group/`);
470
+ assert.equal(seen[1].query.get('pr_state'), 'merged');
471
+ for (const text of ['Build', 'Fix', 'Infra / ops', '$90.00']) {
472
+ assert.ok(workGroup.stdout.includes(text), `${text} missing from:\n${workGroup.stdout}`);
473
+ }
474
+
475
+ assert.deepEqual(JSON.parse((await run(['delivery', 'spend', '--json'])).stdout), SPEND_OUTCOME);
476
+ assert.deepEqual(JSON.parse((await run(['delivery', 'spend', '--by', 'work_group', '--json'])).stdout),
477
+ SPEND_WORK_GROUP);
478
+ });
479
+ });
480
+
481
+ test('repos lists the window\'s repositories and sends only the window', async () => {
482
+ await withBackend(async ({ seen, run }) => {
483
+ const r = await run(['delivery', 'repos', '--time-window', 'FOURTEEN_DAYS']);
484
+ assert.equal(r.code, 0, r.stderr);
485
+ assert.equal(seen[0].path, `${BASE}/filters/`);
486
+ assert.deepEqual([...seen[0].query.keys()], ['time_window']);
487
+ assert.equal(seen[0].query.get('time_window'), 'FOURTEEN_DAYS');
488
+ assert.ok(r.stdout.includes('acme/api') && r.stdout.includes('acme/web'), r.stdout);
489
+ assert.deepEqual(JSON.parse((await run(['delivery', 'repos', '--json'])).stdout), REPOS);
490
+ });
491
+ });
492
+
493
+ test('repos strips terminal escapes from repository names', async () => {
494
+ await withBackend(async ({ run }) => {
495
+ const r = await run(['delivery', 'repos']);
496
+ assert.equal(r.code, 0, r.stderr);
497
+ assertNoEscapes(r.stdout);
498
+ assert.ok(r.stdout.includes('acme/evil'), r.stdout);
499
+ }, () => startServer(() => [200, { repositories: [`${EVIL}acme/evil`] }]));
500
+ });
501
+
502
+ test('bad input fails before any request is sent', async () => {
503
+ const cases = [
504
+ [['delivery', 'branches', '--outcome', 'shipped'], /Invalid --outcome "shipped"/],
505
+ [['delivery', 'branches', '--page-size', '101'], /--page-size cannot exceed 100/],
506
+ [['delivery', 'summary', '--user', 'priya@acme.dev'], /Invalid --user "priya@acme.dev"/],
507
+ [['delivery', 'branches', '--page', '0'], /Invalid --page "0"/],
508
+ [['delivery', 'branches', '--ticket-status', 'blocked'], /Invalid --ticket-status "blocked"/],
509
+ [['delivery', 'users', '--work-group', 'docs'], /Invalid --work-group "docs"/],
510
+ [['delivery', 'users', '--sort', 'name'], /Invalid --sort "name"/],
511
+ [['delivery', 'users', '--sort', 'active_ai_users'], /Invalid --sort "active_ai_users"/],
512
+ [['delivery', 'teams', '--sort', 'last_active'], /Invalid --sort "last_active"/],
513
+ [['delivery', 'teams', '--order', 'up'], /Invalid --order "up"/],
514
+ [['delivery', 'branch', 'abc'], /Invalid branch ID "abc"/],
515
+ [['delivery', 'spend', '--by', 'tool'], /Invalid --by "tool"/],
516
+ [['delivery', 'spend', '--pr-state', 'merged'], /--pr-state applies only to --by work-group/],
517
+ [['delivery', 'summary', '--time-window', 'THREE_MONTHS'], /Invalid --time-window "THREE_MONTHS"/],
518
+ [['delivery', 'repos', '--start', '2026-11-01'], /--start and --end must be used together/],
519
+ [['delivery', 'summary', '--start', '2026-09-01', '--end', '2026-11-20'],
520
+ /Custom range cannot exceed 31 days \(requested 81 days\)/],
521
+ [['delivery', 'branches', '--start', '2026-10-01', '--end', '2026-11-01'],
522
+ /Custom range cannot exceed 31 days \(requested 32 days\)/],
523
+ [['delivery', 'summary', '--start', '2026-07-01', '--end', '2026-11-20'],
524
+ /Custom range cannot exceed 31 days \(requested 143 days\)/],
525
+ ];
526
+ await withBackend(async ({ seen, run }) => {
527
+ for (const [args, message] of cases) {
528
+ const r = await run(args);
529
+ assert.equal(r.code, 1, args.join(' '));
530
+ assert.match(r.stderr, message);
531
+ }
532
+ assert.equal(seen.length, 0);
533
+ });
534
+ });
535
+
536
+ test('a 403 explains the role needed and a 404 explains what is missing', async () => {
537
+ await withBackend(async ({ run }) => {
538
+ const r = await run(['delivery', 'summary']);
539
+ assert.equal(r.code, 1);
540
+ assert.match(r.stderr, /needs Admin or Analytics Viewer over the whole organization/);
541
+ }, () => startServer(() => [403, { error: 'Forbidden' }]));
542
+
543
+ await withBackend(async ({ run }) => {
544
+ const branch = await run(['delivery', 'branch', '99']);
545
+ assert.equal(branch.code, 1);
546
+ assert.match(branch.stderr, /Branch 99 not found in your organization/);
547
+ }, () => startServer(() => [404, { error: 'Branch not found' }]));
548
+
549
+ await withBackend(async ({ run }) => {
550
+ const branch = await run(['delivery', 'branch', '99']);
551
+ assert.equal(branch.code, 1);
552
+ assert.match(branch.stderr, /does not serve Delivery analytics yet/);
553
+ const list = await run(['delivery', 'branches']);
554
+ assert.equal(list.code, 1);
555
+ assert.match(list.stderr, /does not serve Delivery analytics yet/);
556
+ }, () => startServer(() => [404, '<html>Not Found</html>']));
557
+
558
+ await withBackend(async ({ run }) => {
559
+ const branch = await run(['delivery', 'branch', '99']);
560
+ assert.equal(branch.code, 1);
561
+ assert.match(branch.stderr, /Organization not found/);
562
+ assert.doesNotMatch(branch.stderr, /Branch 99|does not serve/);
563
+ const summary = await run(['delivery', 'summary']);
564
+ assert.match(summary.stderr, /Organization not found/);
565
+ }, () => startServer(() => [404, { error: 'Organization not found' }]));
566
+ });
567
+
568
+ test('a server 400 message is passed through with escapes stripped', async () => {
569
+ const message = 'start_date cannot be earlier than 30 days ago (2026-10-28).';
570
+ await withBackend(async ({ run }) => {
571
+ const r = await run(['delivery', 'summary', '--start', '2026-10-01', '--end', '2026-10-20']);
572
+ assert.equal(r.code, 1);
573
+ assert.ok(r.stderr.includes(message), r.stderr);
574
+ assert.ok(!r.stderr.includes(`${ESC}]8`), JSON.stringify(r.stderr));
575
+ }, () => startServer(() => [400, { error: `${EVIL}${message}` }]));
576
+ });
577
+
578
+ test('a 31-day custom range is sent with both dates', async () => {
579
+ await withBackend(async ({ run, seen }) => {
580
+ const r = await run(['delivery', 'summary', '--start', '2026-10-01', '--end', '2026-10-31', '--json']);
581
+ assert.equal(r.code, 0, r.stderr);
582
+ assert.equal(seen.length, 1);
583
+ assert.equal(seen[0].query.get('start_date'), '2026-10-01');
584
+ assert.equal(seen[0].query.get('end_date'), '2026-10-31');
585
+ }, mockBackend);
586
+ });
587
+
588
+ test('every request the suite sent was a GET', () => {
589
+ assert.ok(allRequests.length > 0);
590
+ assert.deepEqual([...new Set(allRequests.map((request) => request.method))], ['GET']);
591
+ });