@ductape/cli 0.5.9 → 0.6.1

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.
@@ -0,0 +1,520 @@
1
+ import fs from 'node:fs';
2
+ import { printJson } from '../lib/output.js';
3
+ import { WorkClient, list, resolveClient } from '../lib/work.js';
4
+ import { registerWorkHooks } from './work-hooks.js';
5
+ import { runRecordedTests } from './work-test.js';
6
+ const client = (opts) => new WorkClient({ session: opts.session, client: resolveClient(opts.client) });
7
+ /** Fields from --input <file> (JSON), merged over the flags. Lets callers pass free text without shell quoting. */
8
+ function withInput(opts, body) {
9
+ if (!opts.input)
10
+ return body;
11
+ const extra = JSON.parse(fs.readFileSync(opts.input, 'utf8'));
12
+ if (!extra || typeof extra !== 'object' || Array.isArray(extra))
13
+ throw new Error('--input must hold a JSON object.');
14
+ return { ...body, ...extra };
15
+ }
16
+ /**
17
+ * Artifacts from flags: --doc, --test-report, --release, --deployment, --build, --link. Each takes "ref", "url", or
18
+ * "ref=url" (a document path and where to read it, a release hash and its page).
19
+ */
20
+ export function artifactsFromFlags(opts) {
21
+ const map = [['doc', 'document'], ['testReport', 'test_report'], ['release', 'release'], ['deployment', 'deployment'], ['build', 'build'], ['link', 'link']];
22
+ const out = [];
23
+ for (const [flag, kind] of map) {
24
+ for (const value of [opts[flag]].flat().filter(Boolean)) {
25
+ const eq = value.indexOf('=');
26
+ const [ref, url] = eq > 0 && /^https?:\/\//.test(value.slice(eq + 1)) ? [value.slice(0, eq), value.slice(eq + 1)] : /^https?:\/\//.test(value) ? [undefined, value] : [value, undefined];
27
+ out.push({ kind, ...(ref ? { ref } : {}), ...(url ? { url } : {}) });
28
+ }
29
+ }
30
+ return out.length ? out : undefined;
31
+ }
32
+ const collect = (value, previous = []) => [...previous, value];
33
+ const artifactOptions = (c) => c
34
+ .option('--doc <ref=url>', 'A document it produced (repeatable)', collect)
35
+ .option('--test-report <ref=url>', 'A test report (repeatable)', collect)
36
+ .option('--release <ref>', 'A Deploy release it produced (repeatable)', collect)
37
+ .option('--deployment <ref>', 'A deployment it produced (repeatable)', collect)
38
+ .option('--build <ref=url>', 'A build (repeatable)', collect)
39
+ .option('--link <url>', 'Any other link (repeatable)', collect);
40
+ const CLIENT_NAME = { 'claude-code': 'Claude Code', codex: 'Codex', cursor: 'Cursor', other: 'Agent' };
41
+ const pad = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}~` : s.padEnd(n));
42
+ function printItems(items, json, total) {
43
+ if (json)
44
+ return printJson({ items, total }, true);
45
+ if (!items.length)
46
+ return console.log('No work items match.');
47
+ console.log(`${pad('REF', 8)}${pad('STATUS', 18)}${pad('PRIORITY', 9)}${pad('ASSIGNEE', 9)}TITLE`);
48
+ for (const i of items) {
49
+ const who = i.assignee ? i.assignee.type : '-';
50
+ console.log(`${pad(i.ref, 8)}${pad(i.status, 18)}${pad(i.priority, 9)}${pad(who, 9)}${i.title}${i.critical ? ' [critical]' : ''}`);
51
+ }
52
+ if (total !== undefined && total > items.length)
53
+ console.log(`(${items.length} of ${total})`);
54
+ }
55
+ function printItem(i) {
56
+ console.log(`${i.ref} ${i.title}`);
57
+ console.log(` status ${i.status}, priority ${i.priority}, ${i.kind}${i.critical ? ', critical' : ''}${i.product ? `, product ${i.product}` : ''}`);
58
+ if (i.assignee)
59
+ console.log(` assigned to ${i.assignee.type} ${i.assignee.id}`);
60
+ if (i.components?.length)
61
+ console.log(` ductape ${i.components.map((c) => `${c.type}:${c.tag}${c.planned ? ' (planned)' : ''}`).join(', ')}`);
62
+ if (i.paths?.length)
63
+ console.log(` paths ${i.paths.join(', ')}`);
64
+ if (i.labels?.length)
65
+ console.log(` labels ${i.labels.join(', ')}`);
66
+ if (i.artifacts?.length) {
67
+ console.log(' delivered:');
68
+ const how = { ductape: ' [checked by Ductape]', ductape_cli: ' [run by the Ductape CLI]', reported: '' };
69
+ for (const a of i.artifacts)
70
+ console.log(` ${a.kind.replace('_', ' ')} ${a.ref}${a.title ? ` ${a.title}` : ''}${a.url && a.url !== a.ref ? ` ${a.url}` : ''}${a.current ? ` (now ${String(a.current.state).replace(/_/g, ' ')}, ${a.current.traffic_percent}% of traffic)` : ''}${how[a.source ?? 'reported'] ?? ''}`);
71
+ }
72
+ for (const a of i.approvals ?? [])
73
+ console.log(` ${a.decision === 'approved' ? 'approved' : 'sent back'} ${new Date(a.at).toISOString().slice(0, 16).replace('T', ' ')} UTC${a.note ? `: ${a.note}` : ''}`);
74
+ if (i.body)
75
+ console.log(`\n${i.body}`);
76
+ if (i.outcome)
77
+ console.log(`\nOutcome: ${i.outcome}`);
78
+ }
79
+ function printOverlaps(overlaps) {
80
+ for (const o of overlaps ?? []) {
81
+ const who = o.held_by.type === 'agent' ? `${o.held_by.client} on ${o.held_by.machine}` : `person ${o.held_by.user_id}`;
82
+ const what = [
83
+ o.paths?.length ? `the same files (${o.paths.map((p) => `${p.mine} / ${p.theirs}`).join('; ')})` : '',
84
+ o.components?.length ? `the same Ductape components (${o.components.join(', ')})` : '',
85
+ ].filter(Boolean).join(' and ');
86
+ console.log(` warning: ${o.item?.ref ?? 'another item'} (${o.item?.title ?? ''}) held by ${who} touches ${what}`);
87
+ }
88
+ }
89
+ export function registerWork(program, wrap) {
90
+ const work = program
91
+ .command('work')
92
+ .description('Agentic work tracker: plan, claim, track and finish work with people and coding agents');
93
+ const common = (c) => c
94
+ .option('--client <client>', 'Speak for this agent client: claude-code, codex, cursor, other (or set DUCTAPE_AGENT_CLIENT)')
95
+ .option('--session <id>', 'Agent session id (or set DUCTAPE_WORK_SESSION)')
96
+ .option('--input <file>', 'JSON object of request fields, merged over the flags')
97
+ .option('--json', 'Print JSON');
98
+ // Sessions
99
+ const session = work.command('session').description('Agent sessions');
100
+ common(session.command('start').description('Start an agent session for this repo and list the work waiting for it'))
101
+ .option('--name <name>', 'A name for this agent')
102
+ .option('--product <tag>', 'Product this session works on (default: the linked project\'s product)')
103
+ .action(wrap(async (opts) => {
104
+ const agent = resolveClient(opts.client) ?? 'other';
105
+ const w = new WorkClient({ client: agent });
106
+ const res = await w.startSession({ client: agent, name: opts.name, product: opts.product });
107
+ if (opts.json)
108
+ return printJson(res, true);
109
+ console.log(`Session ${res.session.id} started for ${agent} in ${w.repo.repo || 'this folder'}${w.repo.branch ? ` (${w.repo.branch})` : ''}.`);
110
+ console.log(`Claims last ${Math.round(res.session.claim_ttl_ms / 60000)} minutes without activity.\n`);
111
+ console.log('Assigned to you:');
112
+ printItems(res.assigned, false);
113
+ console.log('\nReady to pick up:');
114
+ printItems(res.ready, false);
115
+ }));
116
+ common(session.command('heartbeat').description('Keep the session alive and renew its claims'))
117
+ .action(wrap(async (opts) => printJson(await client(opts).send('POST', '/sessions/heartbeat'), Boolean(opts.json))));
118
+ common(session.command('end').description('End the session; claims it still holds go back to ready'))
119
+ .option('--summary <text>', 'What this session did')
120
+ .action(wrap(async (opts) => {
121
+ const res = await client(opts).endSession(withInput(opts, { summary: opts.summary }).summary);
122
+ if (opts.json)
123
+ return printJson(res, true);
124
+ console.log(`Session ended.${res.released.length ? ` Released ${res.released.length} claim(s).` : ''}`);
125
+ }));
126
+ common(work.command('sessions').description('Open agent sessions in the workspace and what each holds'))
127
+ .action(wrap(async (opts) => {
128
+ const rows = await client(opts).get('/sessions', {}, false);
129
+ if (opts.json)
130
+ return printJson(rows, true);
131
+ if (!rows.length)
132
+ return console.log('No open agent sessions.');
133
+ for (const s of rows) {
134
+ console.log(`${s.state === 'active' ? 'active ' : 'offline'} ${s.agent?.client ?? '?'} on ${s.agent?.machine ?? '?'} ${s.repo || ''}${s.branch ? ` (${s.branch})` : ''} session ${s.id}`);
135
+ for (const w of s.working_on)
136
+ console.log(` ${w.ref} ${w.status} ${w.title}`);
137
+ }
138
+ }));
139
+ // Reading
140
+ common(work.command('ls').description('List work items'))
141
+ .option('--status <statuses>', 'Comma-separated statuses')
142
+ .option('--ready', 'Ready to pick up (unassigned, no open blockers)')
143
+ .option('--mine', 'Assigned to me or my agents')
144
+ .option('--open', 'Not done or cancelled')
145
+ .option('--product <tag>', 'Product')
146
+ .option('--label <label>', 'Label')
147
+ .option('--component <type:tag>', 'Items that use this Ductape component, e.g. feature:checkout')
148
+ .option('--path <path>', 'Items whose paths touch this file')
149
+ .option('--parent <ref>', 'Children of this item')
150
+ .option('--plan <key>', 'Items of this plan')
151
+ .option('-q, --query <text>', 'Search titles and bodies')
152
+ .option('--limit <n>', 'At most this many', '50')
153
+ .action(wrap(async (opts) => {
154
+ const res = await client(opts).get('/items', {
155
+ status: opts.ready ? 'ready' : opts.status,
156
+ unassigned: opts.ready ? true : undefined,
157
+ mine: opts.mine,
158
+ open: opts.open,
159
+ product: opts.product,
160
+ label: opts.label,
161
+ component: opts.component,
162
+ path: opts.path,
163
+ parent: opts.parent,
164
+ plan_key: opts.plan,
165
+ q: opts.query,
166
+ limit: opts.limit,
167
+ });
168
+ printItems(res.items, Boolean(opts.json), res.total);
169
+ }));
170
+ common(work.command('show <ref>').description('Show one work item'))
171
+ .action(wrap(async (ref, opts) => {
172
+ const item = await client(opts).get(`/items/${encodeURIComponent(ref)}`);
173
+ if (opts.json)
174
+ return printJson(item, true);
175
+ printItem(item);
176
+ }));
177
+ common(work.command('context <ref>').description('Everything to know before working on an item'))
178
+ .action(wrap(async (ref, opts) => {
179
+ const c = await client(opts).get(`/items/${encodeURIComponent(ref)}/context`);
180
+ if (opts.json)
181
+ return printJson(c, true);
182
+ printItem(c.item);
183
+ if (c.parents.length)
184
+ console.log(`\nPart of: ${c.parents.map((p) => `${p.ref} ${p.title}`).join(' < ')}`);
185
+ if (c.blocked_by.length)
186
+ console.log(`Waits on: ${c.blocked_by.map((b) => `${b.ref} (${b.status})`).join(', ')}`);
187
+ if (c.blocks.length)
188
+ console.log(`Blocks: ${c.blocks.map((b) => `${b.ref} (${b.status})`).join(', ')}`);
189
+ if (c.children.length)
190
+ console.log(`Subtasks: ${c.children.map((b) => `${b.ref} (${b.status})`).join(', ')}`);
191
+ if (c.claim)
192
+ console.log(`Claimed until ${c.claim.expires_at}${c.claim.agent_id ? ` by agent ${c.claim.agent_id}` : ''}`);
193
+ if (c.overlaps.length) {
194
+ console.log('');
195
+ printOverlaps(c.overlaps);
196
+ }
197
+ if (c.in_progress_in_product.length) {
198
+ console.log('\nIn progress in the same product:');
199
+ for (const r of c.in_progress_in_product)
200
+ console.log(` ${r.ref} ${r.status} ${r.title}`);
201
+ }
202
+ if (c.events.length) {
203
+ console.log('\nRecent:');
204
+ for (const e of c.events.slice(0, 10))
205
+ console.log(` ${new Date(e.at).toISOString().slice(0, 16).replace('T', ' ')} ${e.type}${e.data?.text ? `: ${e.data.text}` : e.data?.files ? `: ${e.data.files.join(', ')}` : e.data?.components ? `: ${e.data.components.join(', ')}` : e.data?.sha ? `: ${e.data.sha}` : e.data?.url ? `: ${e.data.url}` : ''}`);
206
+ }
207
+ }));
208
+ common(work.command('events <ref>').description('History of an item'))
209
+ .option('--limit <n>', 'At most this many', '100')
210
+ .action(wrap(async (ref, opts) => printJson(await client(opts).get(`/items/${encodeURIComponent(ref)}/events`, { limit: opts.limit }), true)));
211
+ // Writing
212
+ common(work.command('create').description('Create a work item'))
213
+ .option('--title <title>', 'Title (required, here or in --input)')
214
+ .option('--body <text>', 'Description')
215
+ .option('--product <tag>', 'Product (default: the linked project\'s product, or the parent\'s)')
216
+ .option('--env <slug>', 'Environment of the product, if the work is for one')
217
+ .option('--components <list>', 'Comma-separated Ductape components this work uses, type:tag (add + for one it will create), e.g. feature:checkout,job:reminder+')
218
+ .option('--kind <kind>', 'epic, task or subtask')
219
+ .option('--priority <p>', 'urgent, high, medium, low')
220
+ .option('--parent <ref>', 'Parent item')
221
+ .option('--depends-on <refs>', 'Comma-separated items that must finish first')
222
+ .option('--paths <paths>', 'Comma-separated files or globs this work touches')
223
+ .option('--labels <labels>', 'Comma-separated labels')
224
+ .option('--assignee <who>', '"me"')
225
+ .option('--critical', 'A person must finish it (people only)')
226
+ .option('--backlog', 'Create in the backlog instead of ready')
227
+ .action(wrap(async (opts) => {
228
+ const w = client(opts);
229
+ const item = await w.send('POST', '/items', withInput(opts, {
230
+ title: opts.title, body: opts.body, product: opts.product ?? (opts.parent ? undefined : w.linkedProduct), env: opts.env, components: list(opts.components), kind: opts.kind, priority: opts.priority, parent: opts.parent,
231
+ depends_on: list(opts.dependsOn), paths: list(opts.paths), labels: list(opts.labels), assignee: opts.assignee,
232
+ critical: opts.critical, status: opts.backlog ? 'backlog' : undefined,
233
+ }));
234
+ if (opts.json)
235
+ return printJson(item, true);
236
+ console.log(`Created ${item.ref} (${item.status}): ${item.title}`);
237
+ if (item.similar?.length) {
238
+ console.log(' This may be the same work as:');
239
+ for (const x of item.similar)
240
+ console.log(` ${x.ref} (${x.status}) ${x.title} [${x.reason}]`);
241
+ console.log(` If it is, cancel ${item.ref}: ductape work update ${item.ref} --status cancelled`);
242
+ }
243
+ }));
244
+ const plan = work.command('plan').description('Plans: a task tree published in one call');
245
+ common(plan.command('publish').description('Publish or update a plan from a JSON file'))
246
+ .option('-f, --file <file>', 'Plan JSON: { plan_key, title, body?, product?, items: [{ key, title, body?, parent?, depends_on?, paths?, priority? }] }')
247
+ .action(wrap(async (opts) => {
248
+ const body = opts.file ? JSON.parse(fs.readFileSync(opts.file, 'utf8')) : withInput(opts, {});
249
+ const w = client(opts);
250
+ const res = await w.send('POST', '/plans', { repo: w.repo.repo || undefined, product: w.linkedProduct, ...body });
251
+ if (opts.json)
252
+ return printJson(res, true);
253
+ console.log(`Plan ${res.plan.ref} "${res.plan.title}": ${res.created.length} created, ${res.updated.length} updated.`);
254
+ for (const [key, v] of Object.entries(res.items))
255
+ if (key !== '_plan')
256
+ console.log(` ${pad(v.ref, 8)}${pad(v.status, 10)}${key}`);
257
+ if (res.not_in_plan.length)
258
+ console.log(`No longer in the plan (left as they are): ${res.not_in_plan.join(', ')}`);
259
+ }));
260
+ common(work.command('claim <ref>').description('Take an item; warns when another live claim touches the same files'))
261
+ .option('--paths <paths>', 'Comma-separated files or globs you expect to touch')
262
+ .action(wrap(async (ref, opts) => {
263
+ const res = await client(opts).send('POST', `/items/${encodeURIComponent(ref)}/claim`, withInput(opts, { paths: list(opts.paths) }));
264
+ if (opts.json)
265
+ return printJson(res, true);
266
+ console.log(`${res.renewed ? 'Renewed' : 'Claimed'} ${res.item.ref}: ${res.item.title} (until ${res.claim.expires_at})`);
267
+ printOverlaps(res.overlaps);
268
+ }));
269
+ artifactOptions(common(work.command('update <ref>').description('Change an item or report progress')))
270
+ .option('--parent <ref>', 'Put it under this epic ("none" to take it out)')
271
+ .option('--status <status>', 'in_progress, in_review, blocked, awaiting_approval, ready, backlog, cancelled')
272
+ .option('--note <text>', 'Progress note')
273
+ .option('--files <paths>', 'Comma-separated files touched')
274
+ .option('--commit <sha>', 'Commit')
275
+ .option('--commit-message <text>', 'Commit message')
276
+ .option('--pr <url>', 'Pull request')
277
+ .option('--title <title>', 'Title')
278
+ .option('--body <text>', 'Description')
279
+ .option('--priority <p>', 'Priority')
280
+ .option('--paths <paths>', 'Comma-separated files or globs this work touches')
281
+ .option('--components <list>', 'Replace the Ductape components, type:tag (+ for planned)')
282
+ .option('--critical', 'People only: a person must finish it')
283
+ .option('--not-critical', 'People only: an agent may finish it')
284
+ .option('--labels <labels>', 'Comma-separated labels')
285
+ .action(wrap(async (ref, opts) => {
286
+ const item = await client(opts).send('PATCH', `/items/${encodeURIComponent(ref)}`, withInput(opts, {
287
+ status: opts.status, note: opts.note, files_touched: list(opts.files), commit: opts.commit, commit_message: opts.commitMessage,
288
+ pull_request: opts.pr, title: opts.title, body: opts.body, priority: opts.priority, paths: list(opts.paths), labels: list(opts.labels), components: list(opts.components),
289
+ critical: opts.critical ? true : opts.notCritical ? false : undefined,
290
+ parent: opts.parent === undefined ? undefined : opts.parent === 'none' ? null : opts.parent,
291
+ artifacts: artifactsFromFlags(opts),
292
+ }));
293
+ if (opts.json)
294
+ return printJson(item, true);
295
+ console.log(`Updated ${item.ref} (${item.status}).`);
296
+ }));
297
+ common(work.command('block <ref>').description('Mark an item blocked, optionally creating or linking the blocking work'))
298
+ .option('--reason <text>', 'Why it is blocked (required, here or in --input)')
299
+ .option('--blocked-by <ref>', 'An existing item that blocks it')
300
+ .option('--blocker-title <title>', 'Create a new item for the blocking work')
301
+ .option('--blocker-body <text>', 'Description of the new blocking item')
302
+ .action(wrap(async (ref, opts) => {
303
+ const res = await client(opts).send('POST', `/items/${encodeURIComponent(ref)}/block`, withInput(opts, {
304
+ reason: opts.reason, blocked_by: opts.blockedBy, blocker: opts.blockerTitle ? { title: opts.blockerTitle, body: opts.blockerBody } : undefined,
305
+ }));
306
+ if (opts.json)
307
+ return printJson(res, true);
308
+ console.log(`${res.item.ref} is blocked.${res.blocker ? ` Waits on ${res.blocker.ref}: ${res.blocker.title}` : ''}`);
309
+ }));
310
+ common(work.command('release <ref>').description('Give an item back without finishing it'))
311
+ .option('--note <text>', 'Why')
312
+ .action(wrap(async (ref, opts) => {
313
+ const item = await client(opts).send('POST', `/items/${encodeURIComponent(ref)}/release`, withInput(opts, { note: opts.note }));
314
+ if (opts.json)
315
+ return printJson(item, true);
316
+ console.log(`Released ${item.ref}; it is ${item.status}.`);
317
+ }));
318
+ artifactOptions(common(work.command('done <ref>').description('Finish an item with an outcome; dependents waiting only on it become ready')))
319
+ .option('--outcome <text>', 'What was delivered')
320
+ .option('--changed <list>', 'Comma-separated Ductape components created or changed, type:tag; all must exist in the product')
321
+ .option('--force', 'Finish even if a component is missing (people only)')
322
+ .option('--commit <sha>', 'Final commit')
323
+ .option('--pr <url>', 'Pull request')
324
+ .action(wrap(async (ref, opts) => {
325
+ const res = await client(opts).send('POST', `/items/${encodeURIComponent(ref)}/complete`, withInput(opts, { outcome: opts.outcome, commit: opts.commit, pull_request: opts.pr, components_changed: list(opts.changed), force: opts.force, artifacts: artifactsFromFlags(opts) }));
326
+ if (opts.json)
327
+ return printJson(res, true);
328
+ if (res.approval_required)
329
+ return console.log(`${res.item.ref} is critical: it now awaits a person's approval.`);
330
+ console.log(`Done: ${res.item.ref}.${res.unblocked.length ? ` Now ready: ${res.unblocked.join(', ')}` : ''}`);
331
+ }));
332
+ common(work.command('approvals').description('Work waiting for a person\'s approval (people only), oldest first'))
333
+ .option('--product <tag>', 'One product (default: every product in the workspace)')
334
+ .action(wrap(async (opts) => {
335
+ const res = await client({ ...opts, client: undefined }).get('/approvals', { product: opts.product }, false);
336
+ if (opts.json)
337
+ return printJson(res, true);
338
+ if (!res.items.length)
339
+ return console.log('Nothing is waiting for approval.');
340
+ for (const i of res.items) {
341
+ const who = i.finished_by?.agent_id ? res.agents?.[i.finished_by.agent_id] : undefined;
342
+ const name = CLIENT_NAME[who?.client] ?? 'Agent';
343
+ const by = who ? (i.own ? `your ${name}` : `${who.owner?.name ? `${who.owner.name}'s ` : ''}${name}`) : i.own ? 'you' : i.finished_by ? 'a person' : 'unknown';
344
+ console.log(`${pad(i.ref, 8)}${pad(i.product, 12)}${i.title}`);
345
+ console.log(` finished by ${by}, waiting since ${new Date(i.waiting_since).toISOString().replace('T', ' ').slice(0, 16)} UTC`);
346
+ if (i.outcome)
347
+ console.log(` outcome: ${i.outcome.split('\n')[0].slice(0, 160)}`);
348
+ }
349
+ console.log('\nApprove with: ductape work approve <ref> --note "what you checked" Send back with: ductape work send-back <ref> --note "what to change"');
350
+ }));
351
+ common(work.command('approve <ref>').description('Approve work waiting for approval: it is completed and your approval recorded (people only)'))
352
+ .option('--note <text>', 'What you checked')
353
+ .option('--force', 'Approve even if a Ductape component it names is missing')
354
+ .action(wrap(async (ref, opts) => {
355
+ const res = await client({ ...opts, client: undefined }).send('POST', `/items/${encodeURIComponent(ref)}/approve`, withInput(opts, { note: opts.note, force: opts.force }), false);
356
+ if (opts.json)
357
+ return printJson(res, true);
358
+ console.log(`Approved: ${res.item.ref} is done.${res.unblocked?.length ? ` Now ready: ${res.unblocked.join(', ')}` : ''}`);
359
+ }));
360
+ common(work.command('send-back <ref>').description('Send work waiting for approval back, saying what to change (people only)'))
361
+ .option('--note <text>', 'What needs to change (required)')
362
+ .action(wrap(async (ref, opts) => {
363
+ const item = await client({ ...opts, client: undefined }).send('POST', `/items/${encodeURIComponent(ref)}/request-changes`, withInput(opts, { note: opts.note }), false);
364
+ if (opts.json)
365
+ return printJson(item, true);
366
+ console.log(`Sent back: ${item.ref} is ${item.status === 'in_progress' ? 'back with the agent that did it' : 'ready again, still assigned to whoever did it'}.`);
367
+ }));
368
+ // Rules that open work when a product's components keep failing (people only)
369
+ const RULE_KINDS = 'feature, job, database, app, event, notification, storage, cache, function, healthcheck, webhook';
370
+ const printRule = (r) => console.log(`${r.enabled ? 'on ' : 'off'} ${r.id} ${pad(r.product, 12)}${r.name}\n ${r.description}; opens ${r.item.priority}${r.item.critical ? ', critical' : ''} work${r.fired_count ? `; fired ${r.fired_count} time${r.fired_count === 1 ? '' : 's'}` : ''}${r.open_item_id ? ', an item is open' : ''}`);
371
+ common(work.command('rules').description('Rules that open work when a product\'s components keep failing'))
372
+ .option('--product <tag>', 'One product (default: every product)')
373
+ .action(wrap(async (opts) => {
374
+ const rules = await client({ ...opts, client: undefined }).get('/rules', { product: opts.product }, false);
375
+ if (opts.json)
376
+ return printJson(rules, true);
377
+ if (!rules.length)
378
+ return console.log('No rules. Add one with: ductape work rule add --name "..." --watch job:<tag> --failures 3 --within 15');
379
+ rules.forEach(printRule);
380
+ }));
381
+ const rule = work.command('rule').description('Add, switch on or off, and remove rules (people only)');
382
+ common(rule.command('add').description('Open a work item when something keeps failing'))
383
+ .requiredOption('--name <text>', 'What the rule is for')
384
+ .requiredOption('--watch <kind:tag>', `What to watch, as kind:tag. Kinds: ${RULE_KINDS}`)
385
+ .requiredOption('--failures <n>', 'How many failures')
386
+ .requiredOption('--within <minutes>', 'In how many minutes (at most 1440)')
387
+ .option('--product <tag>', 'Product (default: the linked project\'s)')
388
+ .option('--env <slug>', 'Only failures in this environment')
389
+ .option('--priority <p>', 'urgent, high (default), medium or low')
390
+ .option('--critical', 'The work it opens waits for a person when an agent finishes it')
391
+ .action(wrap(async (opts) => {
392
+ const w = client({ ...opts, client: undefined });
393
+ const at = String(opts.watch).indexOf(':');
394
+ if (at < 1)
395
+ throw new Error(`--watch is kind:tag, for example job:nightly-settlement. Kinds: ${RULE_KINDS}`);
396
+ const created = await w.send('POST', '/rules', withInput(opts, {
397
+ product: w.product(opts.product),
398
+ name: opts.name,
399
+ watch: { kind: opts.watch.slice(0, at), tag: opts.watch.slice(at + 1), env: opts.env },
400
+ threshold: { failures: Number(opts.failures), within_minutes: Number(opts.within) },
401
+ item: { priority: opts.priority ?? 'high', critical: Boolean(opts.critical) },
402
+ }), false);
403
+ if (opts.json)
404
+ return printJson(created, true);
405
+ printRule(created);
406
+ }));
407
+ for (const [verb, enabled] of [['enable', true], ['disable', false]]) {
408
+ common(rule.command(`${verb} <id>`).description(enabled ? 'Switch a rule on' : 'Switch a rule off, keeping it'))
409
+ .action(wrap(async (id, opts) => {
410
+ const updated = await client({ ...opts, client: undefined }).send('PATCH', `/rules/${encodeURIComponent(id)}`, { enabled }, false);
411
+ if (opts.json)
412
+ return printJson(updated, true);
413
+ printRule(updated);
414
+ }));
415
+ }
416
+ common(rule.command('rm <id>').description('Remove a rule; work it opened stays'))
417
+ .action(wrap(async (id, opts) => {
418
+ await client({ ...opts, client: undefined }).send('DELETE', `/rules/${encodeURIComponent(id)}`, {}, false);
419
+ if (!opts.json)
420
+ console.log('Removed. Work it opened stays.');
421
+ }));
422
+ // Keys that let outside systems (alerting, issue trackers, CI) open work in a product
423
+ common(work.command('keys').description('Keys that let outside systems open work'))
424
+ .option('--product <tag>', 'One product (default: every product)')
425
+ .action(wrap(async (opts) => {
426
+ const keys = await client({ ...opts, client: undefined }).get('/intake-keys', { product: opts.product }, false);
427
+ if (opts.json)
428
+ return printJson(keys, true);
429
+ if (!keys.length)
430
+ return console.log('No keys. Make one with: ductape work key add --name PagerDuty');
431
+ for (const k of keys)
432
+ console.log(`${k.revoked_at ? 'revoked' : 'active '} ${k.id} ${pad(k.product, 12)}${pad(k.name, 20)}${k.hint}... used ${k.uses} time${k.uses === 1 ? '' : 's'}`);
433
+ }));
434
+ const key = work.command('key').description('Make or revoke a key for an outside system (people only)');
435
+ common(key.command('add').description('Make a key; it is shown once'))
436
+ .requiredOption('--name <name>', 'The system that will use it (PagerDuty, Sentry, nightly CI)')
437
+ .option('--product <tag>', 'Product (default: the linked project\'s)')
438
+ .option('--priority <p>', 'Priority of work it opens unless the call says: urgent, high (default), medium, low')
439
+ .option('--labels <list>', 'Comma-separated labels added to work it opens')
440
+ .action(wrap(async (opts) => {
441
+ const w = client({ ...opts, client: undefined });
442
+ const k = await w.send('POST', '/intake-keys', { product: w.product(opts.product), name: opts.name, priority: opts.priority, labels: list(opts.labels) }, false);
443
+ if (opts.json)
444
+ return printJson(k, true);
445
+ const api = w.ctx.apiUrl.replace(/\/$/, '');
446
+ console.log(`Key for ${k.name} in ${k.product}. It is shown once; keep it in that system's secret settings:\n\n ${k.key}\n`);
447
+ console.log('That system opens work with:\n');
448
+ console.log(` curl -X POST ${api}/tickets/v1/work-intake \\\n -H "Authorization: Bearer $KEY" -H "content-type: application/json" \\\n -d '{"title":"Checkout error rate above 5%","dedupe_key":"INC-123","url":"https://...","source":"${k.name}"}'\n`);
449
+ console.log('Fields: title (required), body, priority, labels, components (type:tag), env, dedupe_key (repeats add a note to the open item), url, source.');
450
+ }));
451
+ common(key.command('revoke <id>').description('Revoke a key; work it opened stays'))
452
+ .action(wrap(async (id, opts) => {
453
+ const k = await client({ ...opts, client: undefined }).send('DELETE', `/intake-keys/${encodeURIComponent(id)}`, {}, false);
454
+ if (opts.json)
455
+ return printJson(k, true);
456
+ console.log(`Revoked ${k.name}. Calls with it are refused from now on.`);
457
+ }));
458
+ // The workspace's work policy
459
+ const printPolicy = (p) => {
460
+ console.log(`Who approves work waiting for a person: ${p.approvers === 'admins' ? 'the owner and admins' : 'any member'}`);
461
+ console.log(`People may approve their own agent's work: ${p.allow_self_approval ? 'yes' : 'no'}`);
462
+ console.log(`Work on these components is always critical: ${p.critical_components.length ? p.critical_components.join(', ') : 'none'}`);
463
+ console.log(`Agents may take work nobody assigned them: ${p.agents_claim_unassigned ? 'yes' : 'no, a person assigns it first'}`);
464
+ console.log(`\nYou are ${p.your_role === 'collaborator' ? 'a collaborator; the owner and admins change this' : `the workspace ${p.your_role}; change it with ductape work policy set`}.`);
465
+ };
466
+ const policy = common(work.command('policy').description('The workspace\'s work policy'))
467
+ .action(wrap(async (opts) => {
468
+ const p = await client({ ...opts, client: undefined }).get('/policy', {}, false);
469
+ if (opts.json)
470
+ return printJson(p, true);
471
+ printPolicy(p);
472
+ }));
473
+ common(policy.command('set').description('Change the work policy (workspace owner and admins)'))
474
+ .option('--approvers <who>', 'members (anyone in the workspace) or admins (the owner and admins)')
475
+ .option('--self-approval <yes|no>', 'Whether people may approve work their own agent did')
476
+ .option('--critical <patterns>', 'Comma-separated type:tag patterns whose work is always critical, * for any (database:*,app:ductape:paystack*); "" for none')
477
+ .option('--agents-claim <any|assigned>', 'Whether agents may take unassigned work (any) or only work assigned to them or their person (assigned)')
478
+ .action(wrap(async (opts) => {
479
+ const yesNo = (v, name) => {
480
+ if (v === undefined)
481
+ return undefined;
482
+ if (!['yes', 'no', 'true', 'false'].includes(v))
483
+ throw new Error(`${name} is yes or no`);
484
+ return v === 'yes' || v === 'true';
485
+ };
486
+ if (opts.agentsClaim !== undefined && !['any', 'assigned'].includes(opts.agentsClaim))
487
+ throw new Error('--agents-claim is any or assigned');
488
+ const body = {
489
+ approvers: opts.approvers,
490
+ allow_self_approval: yesNo(opts.selfApproval, '--self-approval'),
491
+ critical_components: opts.critical === undefined ? undefined : list(opts.critical) ?? [],
492
+ agents_claim_unassigned: opts.agentsClaim === undefined ? undefined : opts.agentsClaim === 'any',
493
+ };
494
+ const p = await client({ ...opts, client: undefined }).send('PUT', '/policy', withInput(opts, Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined))), false);
495
+ if (opts.json)
496
+ return printJson(p, true);
497
+ printPolicy(p);
498
+ }));
499
+ common(work.command('depend <from> <to>').description('Record that <from> must finish before <to>'))
500
+ .option('--relates', 'Only related, not blocking')
501
+ .action(wrap(async (from, to, opts) => {
502
+ const item = await client(opts).send('POST', '/dependencies', { from, to, type: opts.relates ? 'relates' : 'blocks' });
503
+ if (opts.json)
504
+ return printJson(item, true);
505
+ console.log(`${from} ${opts.relates ? 'relates to' : 'now blocks'} ${item.ref} (${item.status}).`);
506
+ }));
507
+ common(work.command('test <command...>').description('Run your tests and record the result (exit code, pass and fail counts, commit) on the work you hold. Put the command after --, e.g. ductape work test -- npm test'))
508
+ .option('--item <ref>', 'The item to record it on (default: the one item you or this agent hold)')
509
+ .action(wrap(async (command, opts) => {
510
+ process.exitCode = await runRecordedTests(command, { item: opts.item, client: resolveClient(opts.client), session: opts.session, json: Boolean(opts.json) });
511
+ }));
512
+ registerWorkHooks(work, wrap);
513
+ // Oversight
514
+ const agent = work.command('agent').description('Pause or resume an agent (people only)');
515
+ common(agent.command('pause <agentId>').description('Pause an agent: its claims are released and its calls refused'))
516
+ .option('--reason <text>', 'Shown to the agent')
517
+ .action(wrap(async (id, opts) => printJson(await client({ ...opts, client: undefined }).send('POST', `/agents/${id}/pause`, { reason: opts.reason }, false), Boolean(opts.json))));
518
+ common(agent.command('resume <agentId>').description('Resume a paused agent'))
519
+ .action(wrap(async (id, opts) => printJson(await client({ ...opts, client: undefined }).send('POST', `/agents/${id}/resume`, {}, false), Boolean(opts.json))));
520
+ }