knitmd 0.0.0-stage → 0.1.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,503 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { checkTicket, checkTracker, formatProblem, isClosed, isStarted, openDependencies, TICKET_FIELDS, TICKET_LIST_FIELDS, RENAMED_FIELDS, hasTag, daysBetween, inboxItems, waitsFor, withWorkflowGuide, workflowGuide, appendLog, criteria, parseDoc, serialize, set, str, syncTitleHeading, fillDates, formatDoc, findMilestone, repoPath, ticketId, UserError, slugify, textTable, attachmentsJson, children, compareWorkOrder, criteriaProgress, epicProgress, ticketDetailJson, ticketJson, formatSize, } from '@knitmd/core';
4
+ import { guardStatusChange } from '../approval.js';
5
+ import { waitingSince } from '../inbox.js';
6
+ import { linkedCommits, ticketsInRange } from '../linked.js';
7
+ import { displayPath, loadTracker, resolveTicketArg, save } from '../tracker.js';
8
+ import { currentPerson } from '../person.js';
9
+ import { nextNumber, publish, refreshTracker } from '../publish.js';
10
+ import { today } from '../ctx.js';
11
+ import { claimedIds } from './flow.js';
12
+ export function open(ctx, o, opts = {}) {
13
+ let t = loadTracker(ctx, o.dir);
14
+ if (opts.fresh && refreshTracker(t, ctx))
15
+ t = loadTracker(ctx, o.dir);
16
+ return t;
17
+ }
18
+ function json(ctx, value) {
19
+ ctx.out(JSON.stringify(value, null, 2));
20
+ }
21
+ /** Parses `field=value` for a front matter field. An empty value removes the field. */
22
+ export function parseAssignment(arg) {
23
+ const i = arg.indexOf('=');
24
+ if (i <= 0)
25
+ throw new UserError(`expected field=value, got '${arg}'`);
26
+ const key = arg.slice(0, i).trim().replace(/-/g, '_');
27
+ const raw = arg.slice(i + 1).trim();
28
+ const given = key.startsWith('x_') ? key.replace(/_/g, '-') : key;
29
+ const fieldKey = RENAMED_FIELDS[given] ?? given;
30
+ if (!TICKET_FIELDS.includes(fieldKey) && !fieldKey.startsWith('x-')) {
31
+ throw new UserError(`unknown field '${fieldKey}'; fields are ${TICKET_FIELDS.join(', ')} and x-<name>`);
32
+ }
33
+ if (raw === '')
34
+ return { key: fieldKey, value: undefined };
35
+ if (TICKET_LIST_FIELDS.has(fieldKey)) {
36
+ const items = raw
37
+ .replace(/^\[|\]$/g, '')
38
+ .split(',')
39
+ .map((s) => s.trim())
40
+ .filter(Boolean);
41
+ return { key: fieldKey, value: fieldKey === 'depends_on' ? items.map((s) => s.toUpperCase()) : items };
42
+ }
43
+ return { key: fieldKey, value: fieldKey === 'parent' ? raw.toUpperCase() : raw };
44
+ }
45
+ function errorsOf(problems) {
46
+ return problems.filter((p) => p.severity === 'error');
47
+ }
48
+ // ---------------------------------------------------------------- new
49
+ const BUILTIN_TEMPLATE = `---
50
+ ---
51
+
52
+ ## Goal
53
+
54
+ ## Acceptance criteria
55
+
56
+ - [ ]
57
+ `;
58
+ export function cmdNew(ctx, o, type, title) {
59
+ if (!type || !title)
60
+ throw new UserError('usage: nit new <type> "<title>" [field=value…]');
61
+ const t = open(ctx, o, { fresh: true });
62
+ if (!t.config.types.includes(type))
63
+ throw new UserError(`type '${type}' is not one of: ${t.config.types.join(', ')}`);
64
+ const tpl = [join(t.dir, 'templates', `${type}.md`), join(t.dir, 'templates', 'default.md')].find(existsSync);
65
+ const num = nextNumber(t);
66
+ const id = `${t.config.key}-${num}`;
67
+ const path = join(t.dir, 'tickets', `${id}-${slugify(title)}.md`);
68
+ const doc = parseDoc('ticket', path, tpl ? readFileSync(tpl, 'utf8') : BUILTIN_TEMPLATE);
69
+ doc.original = '';
70
+ const defaults = {
71
+ status: t.config.workflow.statuses[0],
72
+ priority: t.config.priorities.includes('medium')
73
+ ? 'medium'
74
+ : t.config.priorities[Math.floor(t.config.priorities.length / 2)],
75
+ };
76
+ set(doc, 'id', id);
77
+ set(doc, 'title', title);
78
+ set(doc, 'type', type);
79
+ for (const [k, v] of Object.entries(defaults))
80
+ if (!str(doc, k))
81
+ set(doc, k, v);
82
+ set(doc, 'created', today(ctx));
83
+ if (t.code && t.config.repos[t.code.repo] && !str(doc, 'repos'))
84
+ set(doc, 'repos', [t.code.repo]);
85
+ for (const a of o.fields) {
86
+ const { key, value } = parseAssignment(a);
87
+ set(doc, key, value);
88
+ }
89
+ guardStatusChange(ctx, t, t.root, doc, undefined, str(doc, 'status'));
90
+ fillDates(t, doc, today(ctx));
91
+ syncTitleHeading(doc);
92
+ const blocking = errorsOf(checkTicket({ ...t, tickets: [...t.tickets, doc] }, doc));
93
+ if (blocking.length > 0 && !o.force) {
94
+ for (const p of blocking)
95
+ ctx.err(formatProblem(p));
96
+ throw new UserError('ticket not created; fix the fields or use --force', 1);
97
+ }
98
+ writeFileSync(path, serialize(doc));
99
+ publish(t, ctx, [repoPath(t, path)], `Add ${id}: ${title}`, o);
100
+ if (o.json)
101
+ json(ctx, { id, file: repoPath(t, path) });
102
+ else
103
+ ctx.out(displayPath(ctx, path));
104
+ return 0;
105
+ }
106
+ export function cmdList(ctx, o) {
107
+ const t = open(ctx, o);
108
+ const inRange = o.in ? ticketsInRange(t, o.in) : undefined;
109
+ const docs = t.tickets.filter((d) => {
110
+ const status = str(d, 'status');
111
+ if (inRange && !inRange.has(d))
112
+ return false;
113
+ if (o.status?.length) {
114
+ if (!o.status.includes(status ?? ''))
115
+ return false;
116
+ }
117
+ else if (!o.all && !inRange && isClosed(t, status))
118
+ return false;
119
+ if (o.assignee && str(d, 'assignee') !== o.assignee)
120
+ return false;
121
+ if (o.milestone && str(d, 'milestone') !== o.milestone)
122
+ return false;
123
+ if (o.type && str(d, 'type') !== o.type)
124
+ return false;
125
+ for (const q of [...(o.tag ?? []), ...(o.label ? [o.label] : [])])
126
+ if (!hasTag(d, q))
127
+ return false;
128
+ if (o.repo) {
129
+ const repos = d.fields.find((f) => f.key === 'repos')?.value;
130
+ if (Array.isArray(repos) && repos.length > 0 && !repos.includes(o.repo))
131
+ return false;
132
+ }
133
+ return true;
134
+ });
135
+ if (o.json) {
136
+ json(ctx, docs.map((d) => ({
137
+ ...ticketJson(t, d),
138
+ ...(inRange ? { commits: inRange.get(d).map(({ where: _, ...c }) => c) } : {}),
139
+ })));
140
+ return 0;
141
+ }
142
+ if (docs.length === 0) {
143
+ ctx.out(o.all || o.status?.length || inRange ? 'no tickets' : 'no open tickets (use --all to include closed ones)');
144
+ return 0;
145
+ }
146
+ const rows = [['ID', 'STATUS', 'PRIORITY', 'ASSIGNEE', 'TITLE']];
147
+ for (const d of docs) {
148
+ const blocked = openDependencies(t, d).length > 0 && !isClosed(t, str(d, 'status'));
149
+ rows.push([
150
+ ticketId(d),
151
+ (str(d, 'status') ?? '?') + (blocked ? ' (blocked)' : ''),
152
+ str(d, 'priority') ?? '',
153
+ str(d, 'assignee') ?? '',
154
+ str(d, 'title') ?? '',
155
+ ]);
156
+ }
157
+ for (const line of textTable(rows))
158
+ ctx.out(line);
159
+ return 0;
160
+ }
161
+ // ---------------------------------------------------------------- show
162
+ export function cmdShow(ctx, o, id) {
163
+ const t = open(ctx, o);
164
+ const doc = resolveTicketArg(t, id);
165
+ if (o.json) {
166
+ json(ctx, ticketDetailJson(t, doc, linkedCommits(t, doc)));
167
+ return 0;
168
+ }
169
+ ctx.out(`# ${repoPath(t, doc.path)}`);
170
+ ctx.out(serialize(doc).replace(/\s+$/, ''));
171
+ const extra = [];
172
+ const blocked = openDependencies(t, doc);
173
+ if (blocked.length > 0 && !isClosed(t, str(doc, 'status')))
174
+ extra.push(`blocked by: ${blocked.join(', ')}`);
175
+ const kids = children(t, doc);
176
+ if (kids.length > 0) {
177
+ const p = epicProgress(t, doc);
178
+ const cancelled = p.cancelled > 0 ? `, ${p.cancelled} cancelled` : '';
179
+ extra.push(`children: ${p.done}/${p.total} done${cancelled}`);
180
+ for (const k of kids) {
181
+ const progress = criteriaProgress(k);
182
+ extra.push(` ${ticketId(k)} ${str(k, 'status')}${progress ? ` ${progress}` : ''}: ${str(k, 'title')}`);
183
+ }
184
+ }
185
+ const progress = criteriaProgress(doc);
186
+ if (progress) {
187
+ extra.push(`acceptance criteria: ${progress}`);
188
+ for (const [i, c] of criteria(doc).entries())
189
+ extra.push(` ${i + 1}. [${c.checked ? 'x' : ' '}] ${c.text}`);
190
+ }
191
+ const attachments = attachmentsJson(t, doc);
192
+ if (attachments.length > 0) {
193
+ extra.push('attachments:');
194
+ for (const a of attachments) {
195
+ const where = String(a.file ?? a.url);
196
+ const facts = [
197
+ a.size !== undefined ? formatSize(a.size) : '',
198
+ a.lfs ? 'LFS' : '',
199
+ a.missing ? 'MISSING' : '',
200
+ ].filter(Boolean);
201
+ extra.push(` ${where}${facts.length ? ` (${facts.join(', ')})` : ''}${a.description ? `: ${a.description}` : ''}`);
202
+ }
203
+ }
204
+ const commits = linkedCommits(t, doc);
205
+ if (commits.length > 0) {
206
+ extra.push('commits:');
207
+ for (const c of commits) {
208
+ const where = [c.repo, c.where === 'branch' ? 'not merged' : ''].filter(Boolean).join(', ');
209
+ const by = c.author ? ` ${c.author}:` : '';
210
+ extra.push(` ${c.hash.slice(0, 7)} ${c.date}${by} ${c.subject} (${c.kind}${where ? `; ${where}` : ''})`);
211
+ }
212
+ }
213
+ if (extra.length > 0) {
214
+ ctx.out('');
215
+ ctx.out('---');
216
+ for (const e of extra)
217
+ ctx.out(e);
218
+ }
219
+ return 0;
220
+ }
221
+ // ---------------------------------------------------------------- set
222
+ export function cmdSet(ctx, o, args) {
223
+ const t = open(ctx, o, { fresh: true });
224
+ const id = args[0] && !args[0].includes('=') ? args[0] : undefined;
225
+ const assignments = id ? args.slice(1) : args;
226
+ if (assignments.length === 0)
227
+ throw new UserError('usage: nit set [ID] field=value…');
228
+ const doc = resolveTicketArg(t, id);
229
+ const before = str(doc, 'status');
230
+ for (const a of assignments) {
231
+ const { key, value } = parseAssignment(a);
232
+ if (key === 'id')
233
+ throw new UserError('use `nit renumber` to change an ID');
234
+ set(doc, key, value);
235
+ if (key === 'status' && typeof value === 'string') {
236
+ if (isStarted(t, value) && !assignments.some((x) => x.startsWith('assignee=')) && !str(doc, 'assignee')) {
237
+ set(doc, 'assignee', currentPerson(ctx, t.config, t.root));
238
+ }
239
+ }
240
+ }
241
+ guardStatusChange(ctx, t, t.root, doc, before, str(doc, 'status'));
242
+ fillDates(t, doc, today(ctx));
243
+ syncTitleHeading(doc);
244
+ const errors = errorsOf(checkTicket(t, doc));
245
+ if (errors.length > 0 && !o.force) {
246
+ for (const p of errors)
247
+ ctx.err(formatProblem(p));
248
+ throw new UserError(`${ticketId(doc)} not changed; fix the problems above or use --force`, 1);
249
+ }
250
+ if (save(doc)) {
251
+ ctx.out(displayPath(ctx, doc.path));
252
+ publish(t, ctx, [repoPath(t, doc.path)], `Update ${ticketId(doc)}: ${assignments.join(' ')}`, o);
253
+ }
254
+ else
255
+ ctx.out('no change');
256
+ return 0;
257
+ }
258
+ // ---------------------------------------------------------------- tick
259
+ /** `tick [ID] <n>…`: checks acceptance criteria by number (as `show` lists them); `--undo` unchecks. */
260
+ export function cmdTick(ctx, o, args) {
261
+ const id = args[0] && !/^\d+$/.test(args[0]) ? args[0] : undefined;
262
+ const nums = (id ? args.slice(1) : args).map(Number);
263
+ if (nums.length === 0 || nums.some((n) => !Number.isInteger(n) || n < 1)) {
264
+ throw new UserError('usage: nit tick [ID] <criterion number>… [--undo] (numbers as `nit show` lists them)');
265
+ }
266
+ const t = open(ctx, o, { fresh: true });
267
+ const doc = resolveTicketArg(t, id);
268
+ const crit = criteria(doc);
269
+ for (const n of nums) {
270
+ const c = crit[n - 1];
271
+ if (!c)
272
+ throw new UserError(`${ticketId(doc)} has ${crit.length} acceptance criteria; there is no ${n}`);
273
+ const i = c.line - 1 - doc.bodyOffset;
274
+ doc.body[i] = doc.body[i].replace(/\[[ xX]\]/, o.undo ? '[ ]' : '[x]');
275
+ }
276
+ if (save(doc)) {
277
+ ctx.out(displayPath(ctx, doc.path));
278
+ publish(t, ctx, [repoPath(t, doc.path)], `${o.undo ? 'Uncheck' : 'Check'} criteria ${nums.join(', ')} of ${ticketId(doc)}`, o);
279
+ }
280
+ else
281
+ ctx.out('no change');
282
+ for (const [i, c] of criteria(doc).entries())
283
+ ctx.out(` ${i + 1}. [${c.checked ? 'x' : ' '}] ${c.text}`);
284
+ return 0;
285
+ }
286
+ // ---------------------------------------------------------------- log
287
+ export function cmdLog(ctx, o, args) {
288
+ const id = args.length >= 2 ? args[0] : undefined;
289
+ const text = args.length >= 2 ? args.slice(1).join(' ') : args[0];
290
+ if (!text)
291
+ throw new UserError('usage: nit log [ID] "<text>"');
292
+ const t = open(ctx, o, { fresh: true });
293
+ const doc = resolveTicketArg(t, id);
294
+ const who = currentPerson(ctx, t.config, t.code?.root ?? t.root);
295
+ appendLog(doc, `- ${today(ctx)} ${who}: ${text.replace(/\s*\n\s*/g, ' ')}`);
296
+ save(doc);
297
+ ctx.out(displayPath(ctx, doc.path));
298
+ publish(t, ctx, [repoPath(t, doc.path)], `Log ${ticketId(doc)}: ${text.split('\n')[0].slice(0, 60)}`, o);
299
+ return 0;
300
+ }
301
+ // ---------------------------------------------------------------- next
302
+ export function cmdNext(ctx, o) {
303
+ const t = open(ctx, o, { fresh: o.fetch !== false });
304
+ const claimed = claimedIds(t, ctx, { fetch: o.fetch !== false });
305
+ const repo = o.repo ?? t.code?.repo;
306
+ const docs = t.tickets
307
+ .filter((d) => str(d, 'status') === t.config.workflow.ready)
308
+ .filter((d) => openDependencies(t, d).length === 0)
309
+ .filter((d) => !claimed.has(ticketId(d)))
310
+ .filter((d) => !o.assignee || !str(d, 'assignee') || str(d, 'assignee') === o.assignee)
311
+ .filter((d) => {
312
+ if (!repo)
313
+ return true;
314
+ const repos = d.fields.find((f) => f.key === 'repos')?.value;
315
+ return !Array.isArray(repos) || repos.length === 0 || repos.includes(repo);
316
+ })
317
+ .filter((d) => str(d, 'type') !== 'epic')
318
+ .sort(compareWorkOrder(t))
319
+ .slice(0, Number(o.limit ?? 5));
320
+ if (o.json) {
321
+ json(ctx, docs.map((d) => ticketJson(t, d)));
322
+ return 0;
323
+ }
324
+ if (docs.length === 0) {
325
+ ctx.out(`no ${t.config.workflow.ready} tickets that are unblocked and unclaimed`);
326
+ return 0;
327
+ }
328
+ const rows = [['ID', 'PRIORITY', 'MILESTONE', 'TITLE']];
329
+ for (const d of docs)
330
+ rows.push([ticketId(d), str(d, 'priority') ?? '', str(d, 'milestone') ?? '', str(d, 'title') ?? '']);
331
+ for (const line of textTable(rows))
332
+ ctx.out(line);
333
+ ctx.out('');
334
+ ctx.out(`start with: nit start ${ticketId(docs[0])} --worktree`);
335
+ return 0;
336
+ }
337
+ // ---------------------------------------------------------------- status
338
+ export function cmdStatus(ctx, o) {
339
+ const t = open(ctx, o);
340
+ const date = today(ctx);
341
+ const wf = t.config.workflow;
342
+ const counts = Object.fromEntries(wf.statuses.map((s) => [s, t.tickets.filter((d) => str(d, 'status') === s).length]));
343
+ const open_ = t.tickets.filter((d) => !isClosed(t, str(d, 'status')));
344
+ const inProgress = open_.filter((d) => isStarted(t, str(d, 'status')));
345
+ const blocked = open_.filter((d) => openDependencies(t, d).length > 0);
346
+ const overdue = open_.filter((d) => (str(d, 'due') ?? '9999') < date);
347
+ const soon = open_.filter((d) => {
348
+ const due = str(d, 'due');
349
+ return due !== undefined && due >= date && due <= addDaysIso(date, 7);
350
+ });
351
+ const milestones = t.milestones
352
+ .filter((m) => str(m, 'status') !== 'done')
353
+ .map((m) => {
354
+ const id = str(m, 'id');
355
+ const ts = t.tickets.filter((d) => str(d, 'milestone') === id);
356
+ return {
357
+ id,
358
+ title: str(m, 'title'),
359
+ due: str(m, 'due'),
360
+ done: ts.filter((d) => str(d, 'status') === wf.done).length,
361
+ total: ts.length,
362
+ };
363
+ });
364
+ if (o.json) {
365
+ const ids = (ds) => ds.map(ticketId);
366
+ json(ctx, {
367
+ date,
368
+ counts,
369
+ in_progress: inProgress.map((d) => ({
370
+ id: ticketId(d),
371
+ assignee: str(d, 'assignee'),
372
+ started: str(d, 'started'),
373
+ })),
374
+ blocked: blocked.map((d) => ({ id: ticketId(d), by: openDependencies(t, d) })),
375
+ overdue: ids(overdue),
376
+ due_soon: ids(soon),
377
+ milestones,
378
+ });
379
+ return 0;
380
+ }
381
+ ctx.out(`${t.config.key}: ${wf.statuses.map((s) => `${counts[s]} ${s}`).join(', ')}`);
382
+ const section = (title, lines) => {
383
+ if (lines.length === 0)
384
+ return;
385
+ ctx.out('');
386
+ ctx.out(`${title}:`);
387
+ for (const l of lines)
388
+ ctx.out(` ${l}`);
389
+ };
390
+ const line = (d, extra = '') => `${ticketId(d)} ${str(d, 'title')}${extra}`;
391
+ section('Milestones', milestones.map((m) => `${m.id} ${m.title} ${m.done}/${m.total} done${m.due ? `, due ${m.due}` : ''}`));
392
+ section('In progress', inProgress.map((d) => line(d, ` (${str(d, 'assignee') ?? '?'} since ${str(d, 'started') ?? '?'})`)));
393
+ section('Overdue', overdue.map((d) => line(d, ` (due ${str(d, 'due')})`)));
394
+ section('Due in 7 days', soon.map((d) => line(d, ` (due ${str(d, 'due')})`)));
395
+ section('Blocked', blocked.map((d) => line(d, ` (by ${openDependencies(t, d).join(', ')})`)));
396
+ return 0;
397
+ }
398
+ function addDaysIso(date, n) {
399
+ const d = new Date(`${date}T00:00:00Z`);
400
+ d.setUTCDate(d.getUTCDate() + n);
401
+ return d.toISOString().slice(0, 10);
402
+ }
403
+ // ---------------------------------------------------------------- check / fmt
404
+ export function cmdCheck(ctx, o) {
405
+ const t = open(ctx, o);
406
+ const problems = checkTracker(t);
407
+ if (o.json)
408
+ json(ctx, problems);
409
+ else
410
+ for (const p of problems)
411
+ ctx.out(formatProblem(p));
412
+ const errors = problems.filter((p) => p.severity === 'error').length;
413
+ const warnings = problems.length - errors;
414
+ if (!o.json) {
415
+ ctx.err(errors + warnings === 0
416
+ ? `${t.tickets.length} tickets, ${t.milestones.length} milestones: ok`
417
+ : `${errors} error(s), ${warnings} warning(s)`);
418
+ }
419
+ return errors > 0 || (o.strict && warnings > 0) ? 1 : 0;
420
+ }
421
+ export function cmdFmt(ctx, o, files) {
422
+ const t = open(ctx, o);
423
+ const wanted = files.map((f) => resolve(ctx.cwd, f));
424
+ const docs = [...t.tickets, ...t.milestones].filter((d) => wanted.length === 0 || wanted.includes(resolve(d.path)));
425
+ const date = today(ctx);
426
+ let n = 0;
427
+ for (const doc of docs) {
428
+ const before = doc.original;
429
+ const text = formatDoc(t, doc, date);
430
+ if (text === before)
431
+ continue;
432
+ n++;
433
+ if (o.check)
434
+ ctx.out(`${repoPath(t, doc.path)}: not formatted`);
435
+ else {
436
+ writeFileSync(doc.path, text);
437
+ doc.original = text;
438
+ ctx.out(displayPath(ctx, doc.path));
439
+ }
440
+ }
441
+ if (o.check && n > 0) {
442
+ ctx.err(`${n} file(s) need \`nit fmt\``);
443
+ return 1;
444
+ }
445
+ return 0;
446
+ }
447
+ export { findMilestone };
448
+ // ---------------------------------------------------------------- guide
449
+ /** `guide [--write]`: prints the workflow section of GUIDE.md generated from proj.yml, or writes it. */
450
+ export function cmdGuide(ctx, o) {
451
+ const t = open(ctx, o);
452
+ if (!o.write) {
453
+ ctx.out(workflowGuide(t));
454
+ return 0;
455
+ }
456
+ const path = join(t.dir, 'GUIDE.md');
457
+ const before = existsSync(path) ? readFileSync(path, 'utf8') : '# Working with tickets\n';
458
+ const after = withWorkflowGuide(t, before);
459
+ if (after === before) {
460
+ ctx.out('no change');
461
+ return 0;
462
+ }
463
+ writeFileSync(path, after);
464
+ ctx.out(displayPath(ctx, path));
465
+ publish(t, ctx, [repoPath(t, path)], 'Update the workflow section of GUIDE.md', o);
466
+ return 0;
467
+ }
468
+ // ---------------------------------------------------------------- inbox
469
+ /**
470
+ * `inbox [--for who] [--all]`: what waits for a person (default: you), a team, a role or an
471
+ * agent, by reason, with the waiting time. `--all` lists every wait.
472
+ */
473
+ export function cmdInbox(ctx, o) {
474
+ const t = open(ctx, o);
475
+ const date = today(ctx);
476
+ const items = inboxItems(t, t.tickets, waitingSince(t));
477
+ const who = o.all ? undefined : (o.for ?? currentPerson(ctx, t.config, t.root));
478
+ const mine = who ? items.filter((i) => waitsFor(t, i, who)) : items;
479
+ const days = (since) => (since ? daysBetween(since, date) : undefined);
480
+ if (o.json) {
481
+ json(ctx, mine.map((i) => ({ ...i, waiting_days: days(i.since) ?? null })));
482
+ return 0;
483
+ }
484
+ if (mine.length === 0) {
485
+ ctx.out(who ? `nothing waits for ${who}` : 'nothing waits');
486
+ return 0;
487
+ }
488
+ const rows = [['REASON', 'FOR', 'ID', 'STATUS', 'WAITING', 'TITLE']];
489
+ for (const i of mine) {
490
+ const d = days(i.since);
491
+ rows.push([
492
+ i.reason,
493
+ i.who,
494
+ i.id,
495
+ i.status,
496
+ d === undefined ? '' : `${d}d`,
497
+ i.question ? `${i.title}: ${i.question}` : i.title,
498
+ ]);
499
+ }
500
+ for (const line of textTable(rows))
501
+ ctx.out(line);
502
+ return 0;
503
+ }