unbound-cli 1.23.0 → 1.25.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.25.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 };