@tuanhv/op-cli 0.3.1 → 0.5.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.
@@ -1,14 +1,17 @@
1
- import { OpCliError, writeRefusal } from "../core/errors.js";
2
- import { buildWpFilters, filtersQuery, } from "../core/filters.js";
1
+ import { Option } from "commander";
2
+ import { OpCliError, refuseCombined, unknownIfUnfinished, writeFailure, } from "../core/errors.js";
3
+ import { applyScalars, SCALAR_OPTIONS, scalarFlag, validateScalars, } from "../core/scalars.js";
4
+ import { buildWpFilters, filtersQuery, parseSort, sortByQuery, } from "../core/filters.js";
3
5
  import { defineCollectionCommand, emitRows, PAGED_JSON_HELP, } from "../core/define.js";
4
6
  import { flattenHalRecord, isFlatLink, toFormattable } from "../core/hal.js";
5
- import { apiDelete, apiGet, apiPost, apiPatchRaw, apiPostRaw, authenticate, } from "../core/http.js";
7
+ import { apiDelete, apiDeleteRaw, apiGet, apiPost, apiPatchRaw, apiPostRaw, authenticate, } from "../core/http.js";
6
8
  import { allPageSize, DEFAULT_PAGE_SIZE, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
7
9
  import { explicitCustomFieldKey, isIdForm, matchByName, rankByCloseness, resolveName, } from "../context/resolve.js";
8
10
  import { parseProjectOverride, } from "../context/profile.js";
9
- import { resolveProjectRef } from "../context/projectref.js";
10
- import { loadProjectVocabulary, loadStoredMetadata, refreshStoredMetadata, } from "../context/metadata.js";
11
+ import { resolveProjectRef, withMovedRetry } from "../context/projectref.js";
12
+ import { loadProjectVocabulary, loadProjectVocabularyById, loadStoredMetadata, readStoredMetadata, refreshProjectVocabulary, refreshStoredMetadata, requireVocabulary, } from "../context/metadata.js";
11
13
  import { formatCell, renderTable } from "../output/table.js";
14
+ import { registerAttachmentCommands } from "./attachments.js";
12
15
  // Canonical row order for a single-record table; every other key of the
13
16
  // flattened record follows in server order.
14
17
  const PREFERRED_FIELDS = [
@@ -21,9 +24,15 @@ const PREFERRED_FIELDS = [
21
24
  "author",
22
25
  "project",
23
26
  "version",
27
+ "targetVersions",
28
+ "observedInVersions",
24
29
  "category",
25
30
  "startDate",
26
31
  "dueDate",
32
+ "estimatedTime",
33
+ "remainingTime",
34
+ "percentageDone",
35
+ "storyPoints",
27
36
  "createdAt",
28
37
  "updatedAt",
29
38
  "lockVersion",
@@ -97,44 +106,84 @@ async function openProfile(runtime, options) {
97
106
  project: parseProjectOverride(options.project),
98
107
  });
99
108
  }
100
- function collectValue(value, previous) {
109
+ export function collectValue(value, previous) {
101
110
  return [...previous, value];
102
111
  }
112
+ /** Like collectValue, but a flag left out stays undefined, not empty. */
113
+ export function collectOptional(value, previous) {
114
+ return [...(previous ?? []), value];
115
+ }
103
116
  /**
104
117
  * Attach the shared filter surface of `wp list` and `wp count`. Both
105
118
  * commands accept exactly the same flags; repeating a value flag ORs.
106
119
  */
107
- function addFilterFlags(command) {
108
- return command
120
+ export function addFilterFlags(command, withScope = true) {
121
+ const filters = command
109
122
  .option("--status <name>", "status name or id; repeat to OR values", collectValue, [])
110
123
  .option("--type <name>", "type name or id; repeat to OR values", collectValue, [])
111
124
  .option("--assignee <name>", "user name, id, or me; repeat to OR values", collectValue, [])
125
+ .option("--accountable <name>", "Accountable (API field responsible): user name, id, or me; repeat to OR values", collectValue, [])
112
126
  .option("--author <name>", "user name, id, or me; repeat to OR values", collectValue, [])
127
+ .option("--watcher <name>", "user name, id, or me, watching the work package; repeat to OR values", collectValue, [])
113
128
  .option("--version <name>", "version name or id; repeat to OR values", collectValue, [])
129
+ .option("--observed-in <name>", "observed-in version name or id; repeat to OR values", collectValue, [])
114
130
  .option("--category <name>", "category name or id; repeat to OR values", collectValue, [])
131
+ .option("--sprint <name>", "sprint name or id; repeat to OR values", collectValue, [])
132
+ .option("--bucket <name>", "backlog bucket name or id; repeat to OR values", collectValue, [])
133
+ .option("--backlog-inbox", "only work packages in the backlog inbox: in neither a sprint nor a backlog bucket")
115
134
  .option("--priority <name>", "priority name or id; repeat to OR values", collectValue, [])
116
135
  .option("--parent <reference>", "parent work package id or exact subject", collectValue, [])
117
136
  .option("--updated-after <value>", "today, yesterday, days back such as 7d, or YYYY-MM-DD")
118
137
  .option("--created-after <value>", "only work packages created since; same date forms as --updated-after")
138
+ .option("--due-before <date>", "due on or before this date: YYYY-MM-DD, today, yesterday, or Nd; "
139
+ + "today/yesterday/Nd count back from today, only YYYY-MM-DD reaches the future")
140
+ .option("--due-after <date>", "due on or after this date; same date forms as --due-before")
141
+ .option("--overdue", "open work packages whose due date is before today")
119
142
  .option("--search <text>", "substring matched against work package subjects")
143
+ .option("--id <id>", "work package id; repeat to OR values", collectValue, [])
144
+ .option("--include-subprojects", "include subprojects in a --project listing (the default; an instance setting may change what a project clause covers)")
145
+ .option("--no-include-subprojects", "only the project's own work packages, not its subprojects' (needs a project)")
120
146
  .option("--open", "shorthand for every open status")
121
- .option("--closed", "shorthand for every closed status")
122
- .option("--profile <name>", "use this profile for this command only")
123
- .option("--project <name-or-id>", "override the profile default project");
147
+ .option("--closed", "shorthand for every closed status");
148
+ return withScope
149
+ ? filters
150
+ .option("--profile <name>", "use this profile for this command only")
151
+ .option("--project <name-or-id>", "override the profile default project")
152
+ : filters;
153
+ }
154
+ /** Normalise --id values ("12" or "#12") to digit strings. */
155
+ function parseIdValues(raw) {
156
+ return raw.map((value) => {
157
+ const id = value.trim().replace(/^#/, "");
158
+ if (!/^[1-9]\d*$/.test(id)) {
159
+ throw new OpCliError("USAGE_ERROR", `"${value}" is not a work package id.`, "--id takes a positive number such as 1234 or #1234.");
160
+ }
161
+ return id;
162
+ });
124
163
  }
125
- function rawListFlags(options) {
164
+ export function rawListFlags(options) {
126
165
  return {
127
166
  statuses: options.status,
128
167
  types: options.type,
129
168
  assignees: options.assignee,
169
+ accountables: options.accountable,
130
170
  authors: options.author,
171
+ watchers: options.watcher,
131
172
  versions: options.version,
173
+ observedIn: options.observedIn,
132
174
  categories: options.category,
175
+ sprints: options.sprint,
176
+ buckets: options.bucket,
177
+ backlogInbox: options.backlogInbox,
133
178
  priorities: options.priority,
134
179
  parents: options.parent,
135
180
  updatedAfter: options.updatedAfter,
136
181
  createdAfter: options.createdAfter,
182
+ dueBefore: options.dueBefore,
183
+ dueAfter: options.dueAfter,
184
+ overdue: options.overdue,
137
185
  search: options.search,
186
+ ids: parseIdValues(options.id ?? []),
138
187
  open: options.open,
139
188
  closed: options.closed,
140
189
  };
@@ -160,7 +209,7 @@ function projectSource(runtime, profile, flag, label, select, memo) {
160
209
  label,
161
210
  load: async () => {
162
211
  if (profile.project === undefined) {
163
- throw new OpCliError("USAGE_ERROR", `--${flag} needs a project to look names up in.`, "pass --project <name-or-id> or set a default project on the profile.");
212
+ throw new OpCliError("USAGE_ERROR", `--${flag} needs a project to look names up in.`, "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
164
213
  }
165
214
  return select(await (memo === undefined
166
215
  ? loadProjectVocabulary(runtime.env, profile)
@@ -172,6 +221,47 @@ function projectSource(runtime, profile, flag, label, select, memo) {
172
221
  },
173
222
  };
174
223
  }
224
+ /** The two backlog placements a work package link can name (#46). */
225
+ const BACKLOG_SOURCES = {
226
+ sprint: { source: "sprints", owner: "Sprint", plural: "sprints" },
227
+ bucket: { source: "buckets", owner: "Bucket", plural: "backlog buckets" },
228
+ };
229
+ /**
230
+ * The sprints or backlog buckets of the profile's project, on the same
231
+ * footing as the other project sources. A store from before #46 lacks
232
+ * them and an empty list may simply be stale, so an empty read re-reads
233
+ * this project once; a project that still has none fails naming the
234
+ * project instead of matching against nothing. Only this project is
235
+ * refreshed: the failure path would otherwise re-fetch every cached
236
+ * project on each call.
237
+ */
238
+ function backlogSource(runtime, profile, flag, memo) {
239
+ const { source, owner, plural } = BACKLOG_SOURCES[flag];
240
+ const project = projectSource(runtime, profile, flag, flag, (vocabulary) => {
241
+ const entries = requireVocabulary(vocabulary, source);
242
+ return entries.map((entry) => ({ name: entry.name, owner, value: entry.id }));
243
+ }, memo);
244
+ const refresh = async () => {
245
+ memo?.invalidate();
246
+ await refreshProjectVocabulary(runtime.env, profile, Number(profile.project));
247
+ };
248
+ return {
249
+ label: project.label,
250
+ load: async () => {
251
+ let entries = await project.load();
252
+ if (entries.length === 0) {
253
+ await refresh();
254
+ entries = await project.load();
255
+ }
256
+ if (entries.length === 0) {
257
+ throw new OpCliError("USAGE_ERROR", `--${flag}: project ${String(profile.project)} has no ${plural}.`, `run op-cli project ${source} ${String(profile.project)} to check, `
258
+ + `or leave --${flag} out.`);
259
+ }
260
+ return entries;
261
+ },
262
+ refresh,
263
+ };
264
+ }
175
265
  async function resolveValues(raws, source) {
176
266
  const ids = [];
177
267
  for (const raw of raws) {
@@ -218,6 +308,33 @@ function membersSource(runtime, profile, flag, memo) {
218
308
  value: member.user_id,
219
309
  })), memo);
220
310
  }
311
+ /**
312
+ * Every value flag, once. A key added to CreateValueFlags fails to compile
313
+ * until it is listed here, and this list feeds the stdin key check and the
314
+ * update "touches something" guard, so a new flag cannot be forgotten in
315
+ * either.
316
+ */
317
+ const VALUE_OPTIONS = {
318
+ type: true,
319
+ status: true,
320
+ priority: true,
321
+ assignee: true,
322
+ accountable: true,
323
+ version: true,
324
+ observedIn: true,
325
+ category: true,
326
+ sprint: true,
327
+ bucket: true,
328
+ parent: true,
329
+ description: true,
330
+ field: true,
331
+ start: true,
332
+ due: true,
333
+ estimate: true,
334
+ remaining: true,
335
+ done: true,
336
+ storyPoints: true,
337
+ };
221
338
  function newResolutionMemo(runtime, profile) {
222
339
  let metadata;
223
340
  let vocabulary;
@@ -287,18 +404,56 @@ async function submitCreate(runtime, profile, payload, refs, memo) {
287
404
  }
288
405
  return response.body;
289
406
  }
407
+ /**
408
+ * OpenProject subscribes the creator to every work package it creates, and
409
+ * no create flag turns that off. The only lever is removing oneself
410
+ * afterwards. The create already succeeded, so a failure here is a warning
411
+ * and never an error: a non-zero exit would invite a retry that duplicates
412
+ * the work package. Returns false when the watcher is gone and null when
413
+ * that is not known.
414
+ */
415
+ async function removeCreatorWatch(runtime, profile, id, memo) {
416
+ if (typeof id !== "number") {
417
+ runtime.writeErr("warning: work package was created without a numeric id; "
418
+ + "cannot remove you from its watchers.\n");
419
+ return null;
420
+ }
421
+ try {
422
+ const userId = await memo.me();
423
+ await deleteWatcher(profile, id, userId);
424
+ return false;
425
+ }
426
+ catch (error) {
427
+ const failure = error instanceof OpCliError
428
+ ? error
429
+ : new OpCliError("INTERNAL_ERROR");
430
+ runtime.writeErr(`work package ${String(id)} was created, but removing you from its watchers `
431
+ + `failed: ${failure.code}: ${failure.message}`
432
+ + `${failure.hint ? ` (${failure.hint})` : ""}\n`);
433
+ return null;
434
+ }
435
+ }
436
+ /** DELETE one watcher; any non-2xx answer becomes a write failure. */
437
+ async function deleteWatcher(profile, wpId, userId) {
438
+ const response = await unknownIfUnfinished(() => apiDeleteRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${String(wpId)}/watchers/${String(userId)}`), WATCH_WRITE(String(wpId)));
439
+ if (response.status < 200 || response.status >= 300) {
440
+ throw writeFailure(response.status, response.body, WATCH_WRITE(String(wpId)));
441
+ }
442
+ }
443
+ /**
444
+ * Kebab spellings a stdin item may use for a camelCase key, mirroring the
445
+ * flag. Both spell the same attribute; giving both is refused.
446
+ */
447
+ const BULK_KEY_ALIASES = {
448
+ "story-points": "storyPoints",
449
+ "observed-in": "observedIn",
450
+ };
290
451
  /** Keys one stdin item may carry; everything else is a loud usage error. */
291
452
  const BULK_ITEM_KEYS = [
292
453
  "subject",
293
- "type",
294
- "status",
295
- "priority",
296
- "assignee",
297
- "version",
298
- "category",
299
- "parent",
300
- "description",
301
- "field",
454
+ "watch",
455
+ ...Object.keys(VALUE_OPTIONS),
456
+ ...Object.keys(BULK_KEY_ALIASES),
302
457
  ];
303
458
  /**
304
459
  * One element of the --stdin array. Mirrors the value flags of the
@@ -310,7 +465,18 @@ function parseBulkItem(raw, index) {
310
465
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
311
466
  throw usage('every input must be an object with a non-empty "subject".');
312
467
  }
313
- const record = raw;
468
+ // Normalise into a copy: the caller's parsed object stays as it came in.
469
+ const record = { ...raw };
470
+ for (const [alias, key] of Object.entries(BULK_KEY_ALIASES)) {
471
+ if (record[alias] === undefined) {
472
+ continue;
473
+ }
474
+ if (record[key] !== undefined) {
475
+ throw usage(`"${alias}" and "${key}" are the same key; give one.`);
476
+ }
477
+ record[key] = record[alias];
478
+ delete record[alias];
479
+ }
314
480
  const unknownKeys = Object.keys(record)
315
481
  .filter((key) => !BULK_ITEM_KEYS.includes(key));
316
482
  if (unknownKeys.length > 0) {
@@ -320,14 +486,20 @@ function parseBulkItem(raw, index) {
320
486
  if (typeof subject !== "string" || subject.trim() === "") {
321
487
  throw usage('every input needs a non-empty "subject" string.');
322
488
  }
489
+ const watch = record.watch;
490
+ if (watch !== undefined && typeof watch !== "boolean") {
491
+ throw usage('"watch" must be true or false.', 'false removes you from the watchers after the create, e.g. {"subject": "...", "watch": false}.');
492
+ }
323
493
  const values = {};
324
494
  const scalarKeys = [
325
495
  "type",
326
496
  "status",
327
497
  "priority",
328
498
  "assignee",
329
- "version",
499
+ "accountable",
330
500
  "category",
501
+ "sprint",
502
+ "bucket",
331
503
  "parent",
332
504
  "description",
333
505
  ];
@@ -341,6 +513,55 @@ function parseBulkItem(raw, index) {
341
513
  }
342
514
  values[key] = rawValue;
343
515
  }
516
+ try {
517
+ refuseTwoPlacements(values);
518
+ }
519
+ catch (error) {
520
+ if (error instanceof OpCliError) {
521
+ throw usage(error.message, error.hint);
522
+ }
523
+ throw error;
524
+ }
525
+ // A version key takes one name-or-id string or an array of them.
526
+ for (const key of ["version", "observedIn"]) {
527
+ const rawValue = record[key];
528
+ if (rawValue === undefined) {
529
+ continue;
530
+ }
531
+ const list = Array.isArray(rawValue) ? rawValue : [rawValue];
532
+ if (list.length === 0
533
+ || list.some((entry) => typeof entry !== "string" || entry === "")) {
534
+ throw usage(`"${key}" must be a non-empty name-or-id string or an array of them.`);
535
+ }
536
+ values[key] = list;
537
+ }
538
+ for (const key of SCALAR_OPTIONS) {
539
+ const rawValue = record[key];
540
+ if (rawValue === undefined) {
541
+ continue;
542
+ }
543
+ // Numbers are natural in JSON for done and story points, and hours
544
+ // for the durations; they travel as the text a flag would carry.
545
+ if (typeof rawValue === "number" && Number.isFinite(rawValue)) {
546
+ values[key] = String(rawValue);
547
+ }
548
+ else if (typeof rawValue === "string" && rawValue !== "") {
549
+ values[key] = rawValue;
550
+ }
551
+ else {
552
+ throw usage(`"${key}" must be a non-empty string or number.`);
553
+ }
554
+ }
555
+ try {
556
+ validateScalars(values);
557
+ }
558
+ catch (error) {
559
+ // Re-raised with the item index; only a usage error is ours to relabel.
560
+ if (error instanceof OpCliError && error.code === "USAGE_ERROR") {
561
+ throw usage(error.message, error.hint);
562
+ }
563
+ throw error;
564
+ }
344
565
  const field = record.field;
345
566
  if (field !== undefined) {
346
567
  if (!Array.isArray(field)
@@ -349,7 +570,7 @@ function parseBulkItem(raw, index) {
349
570
  }
350
571
  values.field = field;
351
572
  }
352
- return { subject, values };
573
+ return { subject, values, ...(watch === undefined ? {} : { watch }) };
353
574
  }
354
575
  /**
355
576
  * The --stdin batch: one NDJSON result line per input, in input order,
@@ -388,7 +609,7 @@ async function runBulkCreate(runtime, subjectArg, options) {
388
609
  project: parseProjectOverride(options.project),
389
610
  });
390
611
  if (profile.project === undefined) {
391
- throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> or set a default project on the profile.");
612
+ throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
392
613
  }
393
614
  const memo = newResolutionMemo(runtime, profile);
394
615
  const dryRun = options.dryRun === true;
@@ -413,12 +634,18 @@ async function runBulkCreate(runtime, subjectArg, options) {
413
634
  const id = typeof body === "object" && body !== null
414
635
  ? body.id
415
636
  : undefined;
637
+ // An item's own "watch" wins; otherwise --no-watch (watch === false).
638
+ const unwatchWanted = (item.watch ?? options.watch) === false;
639
+ const watching = unwatchWanted
640
+ ? await removeCreatorWatch(runtime, profile, id, memo)
641
+ : undefined;
416
642
  runtime.write(`${JSON.stringify({
417
643
  index,
418
644
  ok: true,
419
645
  status: "created",
420
646
  ...(typeof id === "number" ? { id } : {}),
421
647
  subject: item.subject,
648
+ ...(watching === undefined ? {} : { watching }),
422
649
  })}\n`);
423
650
  }
424
651
  catch (error) {
@@ -479,7 +706,7 @@ function customFieldRows(metadata, vocabulary) {
479
706
  }
480
707
  async function resolveFieldDefinition(runtime, profile, rawName, memo) {
481
708
  if (profile.project === undefined) {
482
- throw new OpCliError("USAGE_ERROR", "--field needs a project to look field names up in.", "pass --project <name-or-id> or set a default project on the profile.");
709
+ throw new OpCliError("USAGE_ERROR", "--field needs a project to look field names up in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
483
710
  }
484
711
  const metadata = memo === undefined
485
712
  ? loadStoredMetadata(runtime.env, profile)
@@ -507,6 +734,86 @@ async function resolveFieldDefinition(runtime, profile, rawName, memo) {
507
734
  return field;
508
735
  }
509
736
  const CUSTOM_OPTIONS_HREF = "/api/v3/custom_options/";
737
+ /**
738
+ * The clearing convention for a link attribute: an empty value sends the
739
+ * link with a null href. Array links clear by sending an empty array
740
+ * instead (see listFieldValues).
741
+ */
742
+ function clearLink(links, attribute) {
743
+ links[attribute] = { href: null };
744
+ }
745
+ /** Flags whose empty value is refused: the attribute cannot be empty. */
746
+ const REQUIRED_VALUE_FLAGS = [
747
+ "type",
748
+ "status",
749
+ "priority",
750
+ ];
751
+ /** Flags whose empty value clears the link on update. */
752
+ const CLEARABLE_LINK_FLAGS = [
753
+ "assignee",
754
+ "accountable",
755
+ "category",
756
+ "sprint",
757
+ "bucket",
758
+ "parent",
759
+ ];
760
+ /**
761
+ * A work package sits in a sprint or in a backlog bucket, never both, so
762
+ * one command naming both is refused whatever the values (#46). Moving
763
+ * between the two is one command per placement.
764
+ */
765
+ function refuseTwoPlacements(options) {
766
+ refuseCombined([
767
+ options.sprint === undefined ? undefined : "--sprint",
768
+ options.bucket === undefined ? undefined : "--bucket",
769
+ ], "a work package sits in a sprint or in a backlog bucket; pass one of the two.");
770
+ }
771
+ /** The repeatable version flags; their empty value is `[""]`. */
772
+ const VERSION_FLAGS = [
773
+ { option: "version", flag: "--version" },
774
+ { option: "observedIn", flag: "--observed-in" },
775
+ ];
776
+ /**
777
+ * Refuse empty values that cannot mean anything, before any request: a
778
+ * required attribute never clears, and a create has nothing to clear.
779
+ * On update the clearable link flags pass through; the resolvers turn
780
+ * their empty value into a null href.
781
+ */
782
+ function refuseEmptyValues(options, mode) {
783
+ if (mode === "update" && options.subject === "") {
784
+ throw new OpCliError("USAGE_ERROR", "--subject cannot be empty.", "a work package always has a subject; give the new text.");
785
+ }
786
+ for (const flag of REQUIRED_VALUE_FLAGS) {
787
+ if (options[flag] === "") {
788
+ throw new OpCliError("USAGE_ERROR", `--${flag} cannot be empty.`, `a work package always has a ${flag}; give a name or id.`);
789
+ }
790
+ }
791
+ for (const { option, flag } of VERSION_FLAGS) {
792
+ const values = options[option];
793
+ if (values === undefined || !values.includes("")) {
794
+ continue;
795
+ }
796
+ if (mode === "create") {
797
+ throw new OpCliError("USAGE_ERROR", `${flag} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
798
+ }
799
+ if (values.length > 1) {
800
+ throw new OpCliError("USAGE_ERROR", `${flag} mixes a clearing "" with other values.`, `either pass ${flag} "" alone to clear, or give every occurrence a value.`);
801
+ }
802
+ }
803
+ validateScalars(options);
804
+ if (mode === "create") {
805
+ for (const option of SCALAR_OPTIONS) {
806
+ if (options[option] === "") {
807
+ throw new OpCliError("USAGE_ERROR", `${scalarFlag(option)} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
808
+ }
809
+ }
810
+ for (const flag of CLEARABLE_LINK_FLAGS) {
811
+ if (options[flag] === "") {
812
+ throw new OpCliError("USAGE_ERROR", `--${flag} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
813
+ }
814
+ }
815
+ }
816
+ }
510
817
  /**
511
818
  * Resolve one link-valued option into the payload. An all-digits value is
512
819
  * an id and goes straight in; anything else is resolved here and
@@ -514,22 +821,37 @@ const CUSTOM_OPTIONS_HREF = "/api/v3/custom_options/";
514
821
  * retried after one real refresh.
515
822
  */
516
823
  async function resolveLinkOption(links, attribute, hrefBase, flag, raw, source, refs) {
517
- if (raw === undefined || raw === "") {
824
+ if (raw === undefined) {
518
825
  return;
519
826
  }
520
- let id;
521
- if (isIdForm(raw)) {
522
- id = Number(raw);
523
- }
524
- else {
525
- id = Number(await resolveName(raw, source));
526
- refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
827
+ if (raw === "") {
828
+ clearLink(links, attribute);
829
+ return;
527
830
  }
831
+ const id = await resolveOneLinkId(raw, attribute, hrefBase, source, refs);
528
832
  links[attribute] = { href: `${hrefBase}${String(id)}` };
529
833
  }
834
+ /**
835
+ * One link value to its id: an id-form value is the caller's own and goes
836
+ * straight through; a name is resolved and remembered in `refs`, so a
837
+ * rejection that blames this attribute can be retried with a fresh id
838
+ * (ADR-0002). Every link-valued flag records its refs here and only here.
839
+ */
840
+ async function resolveOneLinkId(raw, attribute, hrefBase, source, refs) {
841
+ if (isIdForm(raw)) {
842
+ return Number(raw);
843
+ }
844
+ const id = Number(await resolveName(raw, source));
845
+ refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
846
+ return id;
847
+ }
530
848
  /** Same contract as resolveLinkOption for members: names, ids, and me. */
531
849
  async function resolveUserOption(runtime, profile, links, attribute, hrefBase, flag, raw, refs, memo) {
532
- if (raw === undefined || raw === "") {
850
+ if (raw === undefined) {
851
+ return;
852
+ }
853
+ if (raw === "") {
854
+ clearLink(links, attribute);
533
855
  return;
534
856
  }
535
857
  let id;
@@ -538,13 +860,8 @@ async function resolveUserOption(runtime, profile, links, attribute, hrefBase, f
538
860
  ? (await authenticate(profile.instanceUrl, profile.apiKey)).id
539
861
  : await memo.me();
540
862
  }
541
- else if (isIdForm(raw)) {
542
- id = Number(raw);
543
- }
544
863
  else {
545
- const source = membersSource(runtime, profile, flag, memo);
546
- id = Number(await resolveName(raw, source));
547
- refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
864
+ id = await resolveOneLinkId(raw, attribute, hrefBase, membersSource(runtime, profile, flag, memo), refs);
548
865
  }
549
866
  links[attribute] = { href: `${hrefBase}${String(id)}` };
550
867
  }
@@ -653,65 +970,70 @@ function pointedAttribute(body) {
653
970
  // Link rejections sometimes spell the target "links/status".
654
971
  return name.replace(/^links[./]/i, "");
655
972
  }
973
+ /** What a work package write says when its outcome cannot be known. */
974
+ const WP_WRITES = {
975
+ create: {
976
+ action: "create",
977
+ unknown: "whether the work package was created is unknown",
978
+ check: "check whether the work package exists before repeating the command.",
979
+ },
980
+ update: {
981
+ action: "update",
982
+ unknown: "whether the change was applied is unknown",
983
+ check: "run op-cli wp get to see the stored values before repeating the command.",
984
+ },
985
+ move: {
986
+ action: "move",
987
+ unknown: "whether the change was applied is unknown",
988
+ check: "run op-cli wp get to see the stored values before repeating the command.",
989
+ },
990
+ };
656
991
  /**
657
992
  * Catalogue mapping for a write that survived the proof-carrying retry:
658
- * 404 stays NOT_FOUND, 5xx becomes the unknown-state NETWORK_ERROR, and
659
- * everything else is the shared refusal mapping.
993
+ * 409 is the optimistic-locking CONFLICT, everything else is the shared
994
+ * write mapping (404, the unknown-state 5xx, the refusal).
660
995
  */
661
996
  function writeRejection(status, body, verb = "create") {
662
- if (status === 404) {
663
- return new OpCliError("NOT_FOUND");
664
- }
665
997
  // A 409 is the optimistic-locking catalogue entry: the caller either
666
998
  // already handled the retry rule or has nothing safe left to try.
667
999
  if (status === 409) {
668
1000
  return new OpCliError("CONFLICT");
669
1001
  }
670
- // A 5xx means the request may still have been applied server-side, so
671
- // the honest answer is "unknown state", never a retry that could
672
- // duplicate the work package.
673
- if (status >= 500) {
674
- const unknownState = verb === "create"
675
- ? "whether the work package was created is unknown."
676
- : "whether the change was applied is unknown.";
677
- const hint = verb === "create"
678
- ? "check whether the work package exists before repeating the command."
679
- : "run op-cli wp get to see the stored values before repeating the command.";
680
- return new OpCliError("NETWORK_ERROR", `the ${verb} failed with HTTP ${status}; ${unknownState}`, hint);
681
- }
682
- return writeRefusal(verb, status, body);
1002
+ return writeFailure(status, body, WP_WRITES[verb]);
683
1003
  }
684
1004
  /**
685
1005
  * A create request whose failure to complete leaves the state unknown:
686
1006
  * timeouts and network errors are never retried on writes, and exit 6
687
1007
  * says so instead of inviting a duplicate.
688
1008
  */
689
- async function postCreate(profile, payload) {
690
- try {
691
- return await apiPostRaw(profile.instanceUrl, profile.apiKey, "/api/v3/work_packages", payload);
692
- }
693
- catch (error) {
694
- if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
695
- throw new OpCliError("NETWORK_ERROR", "the create request did not complete; whether the work package was created is unknown.", "check whether the work package exists before repeating the command.");
696
- }
697
- throw error;
698
- }
1009
+ function postCreate(profile, payload) {
1010
+ return unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, "/api/v3/work_packages", payload), WP_WRITES.create);
699
1011
  }
700
1012
  /**
701
1013
  * An update request whose failure to complete leaves the state unknown:
702
1014
  * like create, timeouts and network errors are never retried on writes.
703
1015
  */
704
- async function patchWp(profile, id, payload) {
705
- try {
706
- return await apiPatchRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${id}`, payload);
707
- }
708
- catch (error) {
709
- if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
710
- throw new OpCliError("NETWORK_ERROR", "the update request did not complete; whether the change was applied is unknown.", "run op-cli wp get to see the stored values before repeating the command.");
711
- }
712
- throw error;
713
- }
1016
+ function patchWp(profile, id, payload) {
1017
+ return unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${id}`, payload), WP_WRITES.update);
714
1018
  }
1019
+ /** What a comment write says when its outcome cannot be known. */
1020
+ const COMMENT_WRITE = (reference) => ({
1021
+ action: "comment",
1022
+ unknown: "whether the comment was posted is unknown",
1023
+ check: `run op-cli wp comments ${reference} before repeating the command.`,
1024
+ });
1025
+ /** What a comment edit says when its outcome cannot be known. */
1026
+ const COMMENT_EDIT_WRITE = (activityId) => ({
1027
+ action: "comment edit",
1028
+ unknown: "whether the comment was changed is unknown",
1029
+ check: `run op-cli wp comments to see comment ${activityId} before repeating the command.`,
1030
+ });
1031
+ /** What a watch or unwatch says when its outcome cannot be known. */
1032
+ const WATCH_WRITE = (reference) => ({
1033
+ action: "watch change",
1034
+ unknown: "whether the watcher list changed is unknown",
1035
+ check: `run op-cli wp watchers ${reference} before repeating the command.`,
1036
+ });
715
1037
  /** The lockVersion a stored record carries; without it there is no safe update. */
716
1038
  function lockVersionOf(record) {
717
1039
  const value = typeof record === "object" && record !== null
@@ -860,7 +1182,7 @@ async function resolveParents(profile, raws) {
860
1182
  }
861
1183
  return ids;
862
1184
  }
863
- async function resolveListFlags(runtime, profile, options) {
1185
+ export async function resolveListFlags(runtime, profile, options) {
864
1186
  const flags = {};
865
1187
  // The project in context scopes the listing itself, not just the
866
1188
  // vocabularies resolved below; without it every listing is
@@ -888,25 +1210,44 @@ async function resolveListFlags(runtime, profile, options) {
888
1210
  if (assignee.length > 0) {
889
1211
  flags.assignees = await resolveUserValues(runtime, profile, "assignee", assignee);
890
1212
  }
1213
+ const accountable = options.accountable ?? [];
1214
+ if (accountable.length > 0) {
1215
+ flags.accountables = await resolveUserValues(runtime, profile, "accountable", accountable);
1216
+ }
891
1217
  const author = options.author ?? [];
892
1218
  if (author.length > 0) {
893
1219
  flags.authors = await resolveUserValues(runtime, profile, "author", author);
894
1220
  }
1221
+ const watcher = options.watcher ?? [];
1222
+ if (watcher.length > 0) {
1223
+ flags.watchers = await resolveUserValues(runtime, profile, "watcher", watcher);
1224
+ }
895
1225
  const version = options.version ?? [];
896
1226
  if (version.length > 0) {
897
- flags.versions = await resolveValues(version, projectSource(runtime, profile, "version", "version", (vocabulary) => vocabulary.versions.map((entry) => ({
898
- name: entry.name,
899
- owner: "Version",
900
- value: entry.id,
901
- }))));
1227
+ flags.versions = await resolveValues(version, versionSource(runtime, profile, "version"));
1228
+ }
1229
+ const observedIn = options.observedIn ?? [];
1230
+ if (observedIn.length > 0) {
1231
+ if (profile.project !== undefined) {
1232
+ // A filter spans the whole project: the field is there when any type has it.
1233
+ const byType = await versionFieldsByType(runtime, profile, undefined, undefined, undefined);
1234
+ if (!Object.values(byType).some((fields) => fields.observedInVersions !== undefined)) {
1235
+ throw new OpCliError("USAGE_ERROR", "--observed-in is not available in this project.", "its work package schema has no observedInVersions field.");
1236
+ }
1237
+ }
1238
+ flags.observedIn = await resolveValues(observedIn, versionSource(runtime, profile, "observed-in"));
902
1239
  }
903
1240
  const category = options.category ?? [];
904
1241
  if (category.length > 0) {
905
- flags.categories = await resolveValues(category, projectSource(runtime, profile, "category", "category", (vocabulary) => vocabulary.categories.map((entry) => ({
906
- name: entry.name,
907
- owner: "Category",
908
- value: entry.id,
909
- }))));
1242
+ flags.categories = await resolveValues(category, categorySource(runtime, profile));
1243
+ }
1244
+ const sprint = options.sprint ?? [];
1245
+ if (sprint.length > 0) {
1246
+ flags.sprints = await resolveValues(sprint, backlogSource(runtime, profile, "sprint"));
1247
+ }
1248
+ const bucket = options.bucket ?? [];
1249
+ if (bucket.length > 0) {
1250
+ flags.buckets = await resolveValues(bucket, backlogSource(runtime, profile, "bucket"));
910
1251
  }
911
1252
  const priority = options.priority ?? [];
912
1253
  if (priority.length > 0) {
@@ -926,23 +1267,239 @@ async function resolveListFlags(runtime, profile, options) {
926
1267
  if (options.createdAfter !== undefined && options.createdAfter !== "") {
927
1268
  flags.createdAfter = options.createdAfter;
928
1269
  }
1270
+ if (options.dueBefore !== undefined && options.dueBefore !== "") {
1271
+ flags.dueBefore = options.dueBefore;
1272
+ }
1273
+ if (options.dueAfter !== undefined && options.dueAfter !== "") {
1274
+ flags.dueAfter = options.dueAfter;
1275
+ }
929
1276
  if (options.search !== undefined && options.search !== "") {
930
1277
  flags.search = options.search;
931
1278
  }
932
- return { ...flags, open: options.open, closed: options.closed };
1279
+ return {
1280
+ ...flags,
1281
+ ids: parseIdValues(options.id ?? []),
1282
+ includeSubprojects: options.includeSubprojects,
1283
+ open: options.open,
1284
+ closed: options.closed,
1285
+ overdue: options.overdue,
1286
+ backlogInbox: options.backlogInbox,
1287
+ };
1288
+ }
1289
+ /**
1290
+ * `subprojectId` is only valid on the project's own collection: the global
1291
+ * endpoint answers 500, so --no-include-subprojects reads from there.
1292
+ * `ownCollection` is that collection's path, see ownCollectionOf.
1293
+ */
1294
+ function workPackagesPath(filters, sort = [], ownCollection) {
1295
+ const sortBy = sort.length > 0 ? `&sortBy=${sortByQuery(sort)}` : "";
1296
+ const collection = ownCollection ?? "/api/v3/work_packages";
1297
+ return `${collection}?filters=${filtersQuery(filters)}${sortBy}`;
1298
+ }
1299
+ /**
1300
+ * The project's own work package collection, when subprojects are
1301
+ * excluded: the stored `workPackages` link of that project (#57), else the
1302
+ * projects path. Reads the local store only; no request is made to find a
1303
+ * link. A stored link can go stale, so it carries the projects path as the
1304
+ * fallback for readOwnPages.
1305
+ */
1306
+ async function ownCollectionOf(runtime, profile, flags) {
1307
+ if (flags.includeSubprojects !== false || flags.project === undefined) {
1308
+ return undefined;
1309
+ }
1310
+ const stored = await readStoredMetadata(runtime.env, profile);
1311
+ const id = Number(flags.project);
1312
+ const linked = stored?.projectScoped?.[flags.project]?.links?.work_packages
1313
+ ?? (stored?.project?.id === id ? stored.project.links?.work_packages : undefined);
1314
+ const projectsPath = `/api/v3/projects/${encodeURIComponent(flags.project)}/work_packages`;
1315
+ // The collection takes the filters as its query, so a link that already
1316
+ // carries one cannot be extended.
1317
+ return linked !== undefined && !linked.includes("?")
1318
+ ? { path: linked, fallback: projectsPath }
1319
+ : { path: projectsPath };
933
1320
  }
934
- function workPackagesPath(filters) {
935
- return `/api/v3/work_packages?filters=${filtersQuery(filters)}`;
1321
+ /**
1322
+ * A page reader for a listing that starts on a stored link: when that
1323
+ * first page answers NOT_FOUND the link is stale, and the same listing is
1324
+ * read once from the projects path instead. Later pages follow whichever
1325
+ * collection answered.
1326
+ */
1327
+ function readOwnPages(getPage, startPath, fallbackStartPath) {
1328
+ if (fallbackStartPath === undefined) {
1329
+ return getPage;
1330
+ }
1331
+ return (path) => path === startPath
1332
+ ? withMovedRetry(() => getPage(path), () => getPage(fallbackStartPath))
1333
+ : getPage(path);
936
1334
  }
937
1335
  function renderWorkPackages(records) {
938
1336
  return renderTable(LIST_COLUMNS.map((column) => column.title), records.map((record) => LIST_COLUMNS.map((column) => formatCell(record[column.field]))));
939
1337
  }
1338
+ /** The id at the end of a link's href, such as a type or project link. */
1339
+ function typeIdOf(link) {
1340
+ if (link === undefined || Array.isArray(link)) {
1341
+ return undefined;
1342
+ }
1343
+ const href = link.href;
1344
+ const match = href === null ? null : /(\d+)$/.exec(href);
1345
+ return match === null ? undefined : Number(match[1]);
1346
+ }
1347
+ /**
1348
+ * The version fields of every type of one project, as the cached schema
1349
+ * shape has them. A vocabulary stored before these fields were captured, or
1350
+ * one that predates the type being asked about, is refreshed once for that
1351
+ * project alone, so the decision always comes from the schema (ADR-0002).
1352
+ * The project is the work package's own when given, else the profile's.
1353
+ */
1354
+ async function versionFieldsByType(runtime, profile, typeId, memo, projectId) {
1355
+ const own = projectId !== undefined && projectId !== profile.project;
1356
+ const load = () => own
1357
+ ? loadProjectVocabularyById(runtime.env, profile, projectId)
1358
+ : memo === undefined
1359
+ ? loadProjectVocabulary(runtime.env, profile)
1360
+ : memo.vocabulary();
1361
+ let vocabulary = await load();
1362
+ const known = (candidate) => candidate.version_fields !== undefined
1363
+ && (typeId === undefined || candidate.version_fields[String(typeId)] !== undefined);
1364
+ if (!known(vocabulary)) {
1365
+ await refreshProjectVocabulary(runtime.env, profile, vocabulary.project_id);
1366
+ memo?.invalidate();
1367
+ vocabulary = await load();
1368
+ }
1369
+ return vocabulary.version_fields ?? {};
1370
+ }
1371
+ /**
1372
+ * The version fields the schema of this project and type exposes. A type of
1373
+ * unknown identity (a create without --type, whose default type the server
1374
+ * picks) is decided only when every type of the project agrees; otherwise
1375
+ * guessing would send a field the real type refuses.
1376
+ */
1377
+ async function versionFieldsFor(runtime, profile, typeId, memo, projectId,
1378
+ /** The fields the caller will write; only these must be agreed on. */
1379
+ needs) {
1380
+ const byType = await versionFieldsByType(runtime, profile, typeId, memo, projectId);
1381
+ const own = typeId === undefined ? undefined : byType[String(typeId)];
1382
+ if (own !== undefined) {
1383
+ return own;
1384
+ }
1385
+ const fields = Object.values(byType);
1386
+ // Only what every type marks deprecated is safe to warn about untyped.
1387
+ const deprecated = (fields[0]?.deprecated ?? []).filter((name) => fields.every((entry) => entry.deprecated?.includes(name) === true));
1388
+ const agreed = (name) => {
1389
+ const found = fields.map((entry) => entry[name]);
1390
+ const present = found.filter((entry) => entry !== undefined);
1391
+ if (present.length === 0) {
1392
+ return {};
1393
+ }
1394
+ const first = present[0];
1395
+ if (present.length < found.length
1396
+ || present.some((entry) => entry.multiple !== first?.multiple)) {
1397
+ throw new OpCliError("USAGE_ERROR", "the project's types disagree on its version fields, so --version and --observed-in cannot be judged without a type.", "pass --type <name-or-id> (or a type in the stdin item) so the schema of that type decides.");
1398
+ }
1399
+ return { [name]: { multiple: present[0]?.multiple === true } };
1400
+ };
1401
+ return {
1402
+ ...Object.assign({}, ...needs.map(agreed)),
1403
+ ...(deprecated.length === 0 ? {} : { deprecated }),
1404
+ };
1405
+ }
1406
+ function categorySource(runtime, profile, memo) {
1407
+ return projectSource(runtime, profile, "category", "category", (vocabulary) => requireVocabulary(vocabulary, "categories").map((entry) => ({
1408
+ name: entry.name,
1409
+ owner: "Category",
1410
+ value: entry.id,
1411
+ })), memo);
1412
+ }
1413
+ function versionSource(runtime, profile, flag, memo) {
1414
+ return projectSource(runtime, profile, flag, "version", (vocabulary) => requireVocabulary(vocabulary, "versions").map((entry) => ({
1415
+ name: entry.name,
1416
+ owner: "Version",
1417
+ value: entry.id,
1418
+ })), memo);
1419
+ }
1420
+ /**
1421
+ * Write one repeatable version flag into an array link: `[{href}]`, or
1422
+ * `[]` to clear.
1423
+ */
1424
+ async function resolveVersionList(runtime, profile, links, attribute, flag, values, refs, memo) {
1425
+ if (values.length === 1 && values[0] === "") {
1426
+ links[attribute] = [];
1427
+ return;
1428
+ }
1429
+ const source = versionSource(runtime, profile, flag.replace(/^--/, ""), memo);
1430
+ const hrefs = [];
1431
+ for (const value of values) {
1432
+ const id = await resolveOneLinkId(value, attribute, "/api/v3/versions/", source, refs);
1433
+ const href = `/api/v3/versions/${String(id)}`;
1434
+ if (!hrefs.some((entry) => entry.href === href)) {
1435
+ hrefs.push({ href });
1436
+ }
1437
+ }
1438
+ links[attribute] = hrefs;
1439
+ }
1440
+ /**
1441
+ * --version and --observed-in. The schema decides where --version lands:
1442
+ * `targetVersions` when the type exposes it, the deprecated `version`
1443
+ * otherwise; the server refuses both in one request, so exactly one is
1444
+ * ever sent.
1445
+ */
1446
+ async function resolveVersionLinks(runtime, profile, links, options, typeId, refs, memo, projectId) {
1447
+ if (options.version === undefined && options.observedIn === undefined) {
1448
+ return;
1449
+ }
1450
+ const fields = await versionFieldsFor(runtime, profile, typeId, memo, projectId, [
1451
+ ...(options.version === undefined ? [] : ["targetVersions"]),
1452
+ ...(options.observedIn === undefined ? [] : ["observedInVersions"]),
1453
+ ]);
1454
+ // The attributes this write actually sets, judged against the schema's
1455
+ // own `deprecated` marks once the values resolved.
1456
+ const written = [];
1457
+ if (options.version !== undefined) {
1458
+ const target = fields.targetVersions;
1459
+ if (target === undefined) {
1460
+ if (options.version.length > 1) {
1461
+ throw new OpCliError("USAGE_ERROR", "--version holds one value on this work package.", "its schema has no targetVersions, only the single version field.");
1462
+ }
1463
+ written.push("version");
1464
+ await resolveLinkOption(links, "version", "/api/v3/versions/", "--version", options.version[0], versionSource(runtime, profile, "version", memo), refs);
1465
+ }
1466
+ else {
1467
+ written.push("targetVersions");
1468
+ if (!target.multiple && options.version.length > 1) {
1469
+ throw new OpCliError("USAGE_ERROR", "--version holds one value for this work package.", "the schema's targetVersions takes a single version; pass --version once.");
1470
+ }
1471
+ await resolveVersionList(runtime, profile, links, "targetVersions", "--version", options.version, refs, memo);
1472
+ }
1473
+ }
1474
+ if (options.observedIn !== undefined) {
1475
+ const observed = fields.observedInVersions;
1476
+ if (observed === undefined) {
1477
+ throw new OpCliError("USAGE_ERROR", "--observed-in is not available for this work package.", "its schema has no observedInVersions field; leave the flag out.");
1478
+ }
1479
+ if (!observed.multiple && options.observedIn.length > 1) {
1480
+ throw new OpCliError("USAGE_ERROR", "--observed-in holds one value for this work package.", "the schema's observedInVersions takes a single version; pass --observed-in once.");
1481
+ }
1482
+ written.push("observedInVersions");
1483
+ await resolveVersionList(runtime, profile, links, "observedInVersions", "--observed-in", options.observedIn, refs, memo);
1484
+ }
1485
+ const deprecated = written.filter((name) => fields.deprecated?.includes(name) === true);
1486
+ if (deprecated.length > 0) {
1487
+ runtime.writeErr(deprecated.length === 1
1488
+ ? `warning: the ${deprecated[0] ?? ""} attribute is deprecated in this instance's schema; the write still goes through.\n`
1489
+ : `warning: the ${deprecated.join(", ")} attributes are deprecated in this instance's schema; the write still goes through.\n`);
1490
+ }
1491
+ }
940
1492
  /**
941
1493
  * Everything create and update share: every value flag resolved by name
942
1494
  * into payload entries, with the name-resolved ones remembered so a
943
1495
  * rejection can be retried with fresh ids (the ADR-0002 refs).
944
1496
  */
945
- async function resolveNamedValues(runtime, profile, options, memo) {
1497
+ async function resolveNamedValues(runtime, profile, options, memo,
1498
+ /**
1499
+ * What an update's work package already has: its type, when --type does
1500
+ * not name one, and its project, whose schema decides the version fields.
1501
+ */
1502
+ existing = {}) {
946
1503
  const refs = [];
947
1504
  const links = {};
948
1505
  await resolveLinkOption(links, "type", "/api/v3/types/", "--type", options.type, instanceSource(runtime, profile, "type", (metadata) => metadata.types.map((entry) => ({
@@ -961,20 +1518,19 @@ async function resolveNamedValues(runtime, profile, options, memo) {
961
1518
  value: entry.id,
962
1519
  })), memo), refs);
963
1520
  await resolveUserOption(runtime, profile, links, "assignee", "/api/v3/users/", "assignee", options.assignee, refs, memo);
964
- await resolveLinkOption(links, "version", "/api/v3/versions/", "--version", options.version, projectSource(runtime, profile, "version", "version", (vocabulary) => vocabulary.versions.map((entry) => ({
965
- name: entry.name,
966
- owner: "Version",
967
- value: entry.id,
968
- })), memo), refs);
969
- await resolveLinkOption(links, "category", "/api/v3/categories/", "--category", options.category, projectSource(runtime, profile, "category", "category", (vocabulary) => vocabulary.categories.map((entry) => ({
970
- name: entry.name,
971
- owner: "Category",
972
- value: entry.id,
973
- })), memo), refs);
1521
+ // Accountable is the API's `responsible` link.
1522
+ await resolveUserOption(runtime, profile, links, "responsible", "/api/v3/users/", "accountable", options.accountable, refs, memo);
1523
+ await resolveVersionLinks(runtime, profile, links, options, typeIdOf(links.type) ?? existing.typeId, refs, memo, existing.projectId);
1524
+ await resolveLinkOption(links, "category", "/api/v3/categories/", "--category", options.category, categorySource(runtime, profile, memo), refs);
1525
+ await resolveLinkOption(links, "sprint", "/api/v3/sprints/", "--sprint", options.sprint, backlogSource(runtime, profile, "sprint", memo), refs);
1526
+ await resolveLinkOption(links, "backlogBucket", "/api/v3/backlog_buckets/", "--bucket", options.bucket, backlogSource(runtime, profile, "bucket", memo), refs);
974
1527
  // The parent is a live lookup over work packages, not cached metadata,
975
1528
  // so it never joins the ADR-0002 refs: an id given here is already the
976
1529
  // caller's own, and a subject search re-runs against current state.
977
- if (options.parent !== undefined) {
1530
+ if (options.parent === "") {
1531
+ clearLink(links, "parent");
1532
+ }
1533
+ else if (options.parent !== undefined) {
978
1534
  const parentId = isIdForm(options.parent)
979
1535
  ? options.parent
980
1536
  : String(await searchParentByName(profile, options.parent));
@@ -986,6 +1542,7 @@ async function resolveNamedValues(runtime, profile, options, memo) {
986
1542
  if (options.description !== undefined) {
987
1543
  payload.description = { raw: options.description };
988
1544
  }
1545
+ applyScalars(payload, options);
989
1546
  const groups = new Map();
990
1547
  for (const pair of (options.field ?? []).map(splitFieldPair)) {
991
1548
  const field = await resolveFieldDefinition(runtime, profile, pair.name, memo);
@@ -1055,6 +1612,7 @@ export const COMMENT_COLUMNS = [
1055
1612
  { title: "ID", field: "id" },
1056
1613
  { title: "AUTHOR", field: "user" },
1057
1614
  { title: "COMMENT", field: "comment" },
1615
+ { title: "INTERNAL", field: "internal" },
1058
1616
  { title: "CREATED", field: "createdAt" },
1059
1617
  ];
1060
1618
  export const HISTORY_COLUMNS = [
@@ -1073,6 +1631,10 @@ export const RELATION_COLUMNS = [
1073
1631
  { title: "LAG", field: "lag" },
1074
1632
  { title: "DESCRIPTION", field: "description" },
1075
1633
  ];
1634
+ export const WATCHER_COLUMNS = [
1635
+ { title: "ID", field: "id" },
1636
+ { title: "NAME", field: "name" },
1637
+ ];
1076
1638
  export const SCHEMA_COLUMNS = [
1077
1639
  { title: "FIELD", field: "field" },
1078
1640
  { title: "NAME", field: "name" },
@@ -1122,6 +1684,10 @@ function linkIdOf(link) {
1122
1684
  * behind a system activity, one instance-spelled sentence per attribute
1123
1685
  * ("Status changed from New to In progress"). A comment activity changed
1124
1686
  * nothing, so its details render empty rather than absent.
1687
+ *
1688
+ * `internal` is the visibility flag of a comment: true when only users with
1689
+ * the internal-comment permission may read it. An activity the instance
1690
+ * does not flag reads as false.
1125
1691
  */
1126
1692
  export function activityRow(element) {
1127
1693
  const resource = element;
@@ -1135,6 +1701,7 @@ export function activityRow(element) {
1135
1701
  kind,
1136
1702
  user: record.user,
1137
1703
  comment: typeof comment?.raw === "string" ? comment.raw : "",
1704
+ internal: record.internal === true,
1138
1705
  details: activityDetails(record.details),
1139
1706
  createdAt: record.createdAt,
1140
1707
  };
@@ -1183,7 +1750,9 @@ async function principalName(getPage, id) {
1183
1750
  }
1184
1751
  catch (error) {
1185
1752
  if (error instanceof OpCliError
1186
- && (error.code === "AUTH_FAILED" || error.code === "NOT_FOUND")) {
1753
+ && (error.code === "AUTH_FAILED"
1754
+ || error.code === "PERMISSION_DENIED"
1755
+ || error.code === "NOT_FOUND")) {
1187
1756
  return null;
1188
1757
  }
1189
1758
  throw error;
@@ -1195,10 +1764,12 @@ async function principalName(getPage, id) {
1195
1764
  * show names rather than the ids the API speaks. Each id is looked up at
1196
1765
  * most once per run, and a row that already carries a name costs nothing.
1197
1766
  */
1198
- function authorResolver(getPage) {
1767
+ function authorResolver(getPage,
1768
+ /** The key of the row that holds the user link: comments use `user`. */
1769
+ key = "user") {
1199
1770
  const named = new Map();
1200
1771
  return async (row) => {
1201
- const user = row.user;
1772
+ const user = row[key];
1202
1773
  if (!isFlatLink(user) || user.id === null || user.name !== null) {
1203
1774
  return row;
1204
1775
  }
@@ -1207,7 +1778,7 @@ function authorResolver(getPage) {
1207
1778
  named.set(id, await principalName(getPage, id));
1208
1779
  }
1209
1780
  const name = named.get(id) ?? null;
1210
- return name === null ? row : { ...row, user: { id, name } };
1781
+ return name === null ? row : { ...row, [key]: { id, name } };
1211
1782
  };
1212
1783
  }
1213
1784
  /** Comments are the Comment-kind slice of the same activity stream. */
@@ -1215,6 +1786,10 @@ export function commentRow(element) {
1215
1786
  const row = activityRow(element);
1216
1787
  return row.kind === "Comment" ? row : undefined;
1217
1788
  }
1789
+ /** A watcher is a plain user resource; the whole flat record, `--fields` projects it. */
1790
+ export function watcherRow(element) {
1791
+ return flattenHalRecord(element);
1792
+ }
1218
1793
  /** Only the typed fields and both ends; the action links carry no data. */
1219
1794
  export function relationRow(element) {
1220
1795
  const record = flattenHalRecord(element);
@@ -1264,25 +1839,34 @@ export function registerWpCommands(wp, runtime) {
1264
1839
  addFilterFlags(wp.command("list")
1265
1840
  .description("List work packages by name-resolved filters")
1266
1841
  .option("--json", PAGED_JSON_HELP)
1842
+ .option("--sort <field[:asc|desc]>", "sort by updatedAt, createdAt, dueDate, startDate, priority, status, id or subject; "
1843
+ + "repeat for tie-breakers; the direction defaults to asc", collectValue, [])
1267
1844
  .option("--limit <n>", "maximum number of results to show")
1268
1845
  .option("--all", "fetch every page instead of one limited page")).action(async (options) => {
1269
1846
  runtime.setJsonMode(options.json === true);
1270
1847
  // Refuse impossible flag combinations before any traffic or resolution.
1271
1848
  buildWpFilters(rawListFlags(options), new Date());
1849
+ const sort = parseSort(options.sort ?? []);
1272
1850
  const profile = await runtime.resolve({
1273
1851
  profile: options.profile,
1274
1852
  project: parseProjectOverride(options.project),
1275
1853
  });
1276
1854
  const now = new Date();
1277
1855
  const limit = parsePageSize(options.limit);
1278
- const filters = buildWpFilters(await resolveListFlags(runtime, profile, options), now);
1856
+ const resolved = await resolveListFlags(runtime, profile, options);
1857
+ const filters = buildWpFilters(resolved, now);
1279
1858
  const getPage = (path) => apiGet(profile.instanceUrl, profile.apiKey, path);
1280
1859
  // --all sizes pages by the instance's advertised maximum; --limit
1281
1860
  // only ever sizes the single non-all page.
1282
- const startPath = withPageSize(workPackagesPath(filters), options.all === true ? await allPageSize(getPage) : limit);
1861
+ const own = await ownCollectionOf(runtime, profile, resolved);
1862
+ const pageSize = options.all === true ? await allPageSize(getPage) : limit;
1863
+ const startPath = withPageSize(workPackagesPath(filters, sort, own?.path), pageSize);
1864
+ const readPage = readOwnPages(getPage, startPath, own?.fallback === undefined
1865
+ ? undefined
1866
+ : withPageSize(workPackagesPath(filters, sort, own.fallback), pageSize));
1283
1867
  if (options.all === true) {
1284
1868
  const rows = [];
1285
- for await (const element of halElements(getPage, startPath)) {
1869
+ for await (const element of halElements(readPage, startPath)) {
1286
1870
  const record = flattenHalRecord(element);
1287
1871
  if (options.json === true) {
1288
1872
  runtime.write(`${JSON.stringify(record)}\n`);
@@ -1296,7 +1880,7 @@ export function registerWpCommands(wp, runtime) {
1296
1880
  }
1297
1881
  return;
1298
1882
  }
1299
- const page = (await getPage(startPath));
1883
+ const page = (await readPage(startPath));
1300
1884
  const records = (page._embedded?.elements ?? []).map((element) => flattenHalRecord(element));
1301
1885
  if (options.json === true) {
1302
1886
  runtime.write(`${JSON.stringify(records)}\n`);
@@ -1310,14 +1894,24 @@ export function registerWpCommands(wp, runtime) {
1310
1894
  + "Pass --all to fetch every result.\n");
1311
1895
  }
1312
1896
  });
1313
- addFilterFlags(wp.command("count").description("Count work packages matching the filters")).action(async (options) => {
1897
+ addFilterFlags(wp.command("count")
1898
+ .description("Count work packages matching the filters")
1899
+ .addOption(new Option("--sort <field>").hideHelp())).action(async (options) => {
1900
+ if (options.sort !== undefined) {
1901
+ throw new OpCliError("USAGE_ERROR", "wp count does not take --sort.", "a count has no order; use wp list --sort <field> instead.");
1902
+ }
1314
1903
  buildWpFilters(rawListFlags(options), new Date());
1315
1904
  const profile = await runtime.resolve({
1316
1905
  profile: options.profile,
1317
1906
  project: parseProjectOverride(options.project),
1318
1907
  });
1319
- const filters = buildWpFilters(await resolveListFlags(runtime, profile, options), new Date());
1320
- const body = (await apiGet(profile.instanceUrl, profile.apiKey, `${workPackagesPath(filters)}&pageSize=1`));
1908
+ const resolved = await resolveListFlags(runtime, profile, options);
1909
+ const filters = buildWpFilters(resolved, new Date());
1910
+ const own = await ownCollectionOf(runtime, profile, resolved);
1911
+ const countPath = `${workPackagesPath(filters, [], own?.path)}&pageSize=1`;
1912
+ const body = (await readOwnPages((path) => apiGet(profile.instanceUrl, profile.apiKey, path), countPath, own?.fallback === undefined
1913
+ ? undefined
1914
+ : `${workPackagesPath(filters, [], own.fallback)}&pageSize=1`)(countPath));
1321
1915
  if (typeof body.total !== "number") {
1322
1916
  throw new OpCliError("API_ERROR", "the response carried no total.", "check the instance version with op-cli doctor.");
1323
1917
  }
@@ -1348,14 +1942,26 @@ export function registerWpCommands(wp, runtime) {
1348
1942
  .option("--stdin", "read a JSON array of work packages and report one NDJSON line per item")
1349
1943
  .option("--fail-fast", "with --stdin: stop the batch at the first failing item")
1350
1944
  .option("--dry-run", "with --stdin: resolve and validate everything, create nothing")
1945
+ .option("--no-watch", "after the create, remove yourself from the watchers OpenProject added you to; "
1946
+ + "with --stdin applies to every item unless an item sets \"watch\": true")
1351
1947
  .option("--type <name-or-id>", "work package type, by name or id")
1352
1948
  .option("--status <name-or-id>", "initial status, by name or id")
1353
1949
  .option("--priority <name-or-id>", "priority, by name or id")
1354
1950
  .option("--assignee <name-or-id>", "assignee, by name, id, or me")
1355
- .option("--version <name-or-id>", "version of the project, by name or id")
1951
+ .option("--accountable <name-or-id>", "Accountable (API field responsible), by name, id, or me")
1952
+ .option("--version <name-or-id>", "version of the project, by name or id; repeat when the schema allows several", collectOptional)
1953
+ .option("--observed-in <name-or-id>", "observed-in version, by name or id; repeat when the schema allows several", collectOptional)
1356
1954
  .option("--category <name-or-id>", "category of the project, by name or id")
1955
+ .option("--sprint <name-or-id>", "sprint of the project, by name or id; not with --bucket")
1956
+ .option("--bucket <name-or-id>", "backlog bucket of the project, by name or id; not with --sprint")
1357
1957
  .option("--parent <id-or-subject>", "parent work package, by id or exact subject")
1358
1958
  .option("--description <text>", "markdown description of the work package")
1959
+ .option("--start <date>", "start date, YYYY-MM-DD")
1960
+ .option("--due <date>", "due date, YYYY-MM-DD")
1961
+ .option("--estimate <duration>", "estimated time such as 4h, 1h30m, or PT4H")
1962
+ .option("--remaining <duration>", "remaining work such as 2h, 1h30m, or PT2H")
1963
+ .option("--done <percent>", "percent complete, 0-100")
1964
+ .option("--story-points <n>", "story points, a whole number")
1359
1965
  .option("--field <pair>", 'set a custom field by human name as "Name=Value"; repeat the flag '
1360
1966
  + 'for several values; "Name=" clears the field', collectValue, [])
1361
1967
  .option("--json", "emit a flat JSON record")
@@ -1377,17 +1983,28 @@ export function registerWpCommands(wp, runtime) {
1377
1983
  if (subject === undefined) {
1378
1984
  throw new OpCliError("USAGE_ERROR", "wp create needs a subject or --stdin with an array of work packages.", "give <subject> to create one, or pipe a JSON array with --stdin.");
1379
1985
  }
1986
+ refuseTwoPlacements(options);
1987
+ refuseEmptyValues(options, "create");
1380
1988
  const profile = await runtime.resolve({
1381
1989
  profile: options.profile,
1382
1990
  project: parseProjectOverride(options.project),
1383
1991
  });
1384
1992
  if (profile.project === undefined) {
1385
- throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> or set a default project on the profile.");
1993
+ throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
1386
1994
  }
1387
1995
  const { payload, refs } = await prepareCreatePayload(runtime, profile, subject, options);
1388
1996
  const body = await submitCreate(runtime, profile, payload, refs);
1389
1997
  const created = flattenHalRecord(body);
1390
- renderRecord(runtime, options, created, `work package ${String(created.id)} was created`);
1998
+ let done = `work package ${String(created.id)} was created`;
1999
+ // Commander: --no-watch makes options.watch false; absent it is true.
2000
+ if (options.watch === false) {
2001
+ const watching = await removeCreatorWatch(runtime, profile, created.id, newResolutionMemo(runtime, profile));
2002
+ created.watching = watching;
2003
+ if (watching === false) {
2004
+ done += ", not watching";
2005
+ }
2006
+ }
2007
+ renderRecord(runtime, options, created, done);
1391
2008
  });
1392
2009
  wp.command("update")
1393
2010
  .description("Update one work package with every value given by name")
@@ -1396,11 +2013,21 @@ export function registerWpCommands(wp, runtime) {
1396
2013
  .option("--type <name-or-id>", "work package type, by name or id")
1397
2014
  .option("--status <name-or-id>", "status, by name or id")
1398
2015
  .option("--priority <name-or-id>", "priority, by name or id")
1399
- .option("--assignee <name-or-id>", "assignee, by name, id, or me")
1400
- .option("--version <name-or-id>", "version of the project, by name or id")
1401
- .option("--category <name-or-id>", "category of the project, by name or id")
1402
- .option("--parent <id-or-subject>", "re-parent under this work package, by id or exact subject")
2016
+ .option("--assignee <name-or-id>", 'assignee, by name, id, or me; "" clears')
2017
+ .option("--accountable <name-or-id>", 'Accountable (API field responsible), by name, id, or me; "" clears')
2018
+ .option("--version <name-or-id>", 'version of the project, by name or id; repeat when the schema allows several; "" clears', collectOptional)
2019
+ .option("--observed-in <name-or-id>", 'observed-in version, by name or id; repeat when the schema allows several; "" clears', collectOptional)
2020
+ .option("--category <name-or-id>", 'category of the project, by name or id; "" clears')
2021
+ .option("--sprint <name-or-id>", 'sprint of the project, by name or id; "" clears; not with --bucket')
2022
+ .option("--bucket <name-or-id>", 'backlog bucket of the project, by name or id; "" clears; not with --sprint')
2023
+ .option("--parent <id-or-subject>", 're-parent under this work package, by id or exact subject; "" clears')
1403
2024
  .option("--description <text>", "new markdown description of the work package")
2025
+ .option("--start <date>", 'start date, YYYY-MM-DD; "" clears')
2026
+ .option("--due <date>", 'due date, YYYY-MM-DD; "" clears')
2027
+ .option("--estimate <duration>", 'estimated time such as 4h, 1h30m, or PT4H; "" clears')
2028
+ .option("--remaining <duration>", 'remaining work such as 2h, 1h30m, or PT2H; "" clears')
2029
+ .option("--done <percent>", 'percent complete, 0-100; "" clears')
2030
+ .option("--story-points <n>", 'story points, a whole number; "" clears')
1404
2031
  .option("--field <pair>", 'set a custom field by human name as "Name=Value"; repeat the flag '
1405
2032
  + 'for several values; "Name=" clears the field', collectValue, [])
1406
2033
  .option("--json", "emit a flat JSON record")
@@ -1410,19 +2037,16 @@ export function registerWpCommands(wp, runtime) {
1410
2037
  .action(async (reference, options) => {
1411
2038
  runtime.setJsonMode(options.json === true);
1412
2039
  requireWpId(reference);
2040
+ // A flag counts when it carries a value; --field defaults to [].
1413
2041
  const touchesSomething = options.subject !== undefined
1414
- || options.type !== undefined
1415
- || options.status !== undefined
1416
- || options.priority !== undefined
1417
- || options.parent !== undefined
1418
- || options.assignee !== undefined
1419
- || options.version !== undefined
1420
- || options.category !== undefined
1421
- || options.description !== undefined
1422
- || (options.field?.length ?? 0) > 0;
2042
+ || Object.keys(VALUE_OPTIONS).some((option) => option === "field"
2043
+ ? (options.field?.length ?? 0) > 0
2044
+ : options[option] !== undefined);
1423
2045
  if (!touchesSomething) {
1424
- throw new OpCliError("USAGE_ERROR", "wp update needs at least one value to change.", "pass --subject, an attribute flag like --status, or --field Name=Value.");
2046
+ throw new OpCliError("USAGE_ERROR", "wp update needs at least one value to change.", "pass --subject, an attribute flag like --status or --due, or --field Name=Value.");
1425
2047
  }
2048
+ refuseTwoPlacements(options);
2049
+ refuseEmptyValues(options, "update");
1426
2050
  const profile = await runtime.resolve({
1427
2051
  profile: options.profile,
1428
2052
  project: parseProjectOverride(options.project),
@@ -1434,7 +2058,17 @@ export function registerWpCommands(wp, runtime) {
1434
2058
  // The read already names every column, so a bad --fields name is
1435
2059
  // refused while the work package is still untouched.
1436
2060
  selectedFields(options.fields, flattenHalRecord(before));
1437
- const { payload, refs } = await resolveNamedValues(runtime, profile, options);
2061
+ const beforeLinks = before._links;
2062
+ const ownProject = typeIdOf(beforeLinks?.project);
2063
+ // Names are looked up in --project, else the profile's default; with
2064
+ // neither, the work package's own project is the one that can matter.
2065
+ const scope = profile.project === undefined && ownProject !== undefined
2066
+ ? { ...profile, project: ownProject }
2067
+ : profile;
2068
+ const { payload, refs } = await resolveNamedValues(runtime, scope, options, undefined, {
2069
+ typeId: typeIdOf(beforeLinks?.type),
2070
+ projectId: ownProject,
2071
+ });
1438
2072
  if (options.subject !== undefined) {
1439
2073
  payload.subject = options.subject;
1440
2074
  }
@@ -1456,7 +2090,7 @@ export function registerWpCommands(wp, runtime) {
1456
2090
  response = await patchWp(profile, reference, payload);
1457
2091
  }
1458
2092
  else {
1459
- response = await retryWithFreshIds(runtime, profile, response, payload, refs, () => patchWp(profile, reference, payload));
2093
+ response = await retryWithFreshIds(runtime, scope, response, payload, refs, () => patchWp(profile, reference, payload));
1460
2094
  }
1461
2095
  }
1462
2096
  if (response.status >= 400) {
@@ -1598,7 +2232,7 @@ export function registerWpCommands(wp, runtime) {
1598
2232
  };
1599
2233
  wp.addCommand(defineCollectionCommand({
1600
2234
  name: "comments",
1601
- description: "List comments of one work package",
2235
+ description: "List comments of one work package (API v3 has no comment delete)",
1602
2236
  path: (id) => `/api/v3/work_packages/${id}/activities`,
1603
2237
  row: commentRow,
1604
2238
  columns: COMMENT_COLUMNS,
@@ -1612,6 +2246,14 @@ export function registerWpCommands(wp, runtime) {
1612
2246
  columns: HISTORY_COLUMNS,
1613
2247
  resolve: authorResolver,
1614
2248
  }, collectionRuntime));
2249
+ registerAttachmentCommands(wp, runtime, {
2250
+ authorResolver,
2251
+ selectedFields,
2252
+ renderRecord,
2253
+ openProfile,
2254
+ requireWpId,
2255
+ collectionRuntime,
2256
+ });
1615
2257
  wp.addCommand(defineCollectionCommand({
1616
2258
  name: "relations",
1617
2259
  description: "List the relations of one work package",
@@ -1619,6 +2261,13 @@ export function registerWpCommands(wp, runtime) {
1619
2261
  row: relationRow,
1620
2262
  columns: RELATION_COLUMNS,
1621
2263
  }, collectionRuntime));
2264
+ wp.addCommand(defineCollectionCommand({
2265
+ name: "watchers",
2266
+ description: "List the watchers of one work package",
2267
+ path: (id) => `/api/v3/work_packages/${id}/watchers`,
2268
+ row: watcherRow,
2269
+ columns: WATCHER_COLUMNS,
2270
+ }, collectionRuntime));
1622
2271
  const recordOptions = {
1623
2272
  json: "--json",
1624
2273
  fields: "--fields <list>",
@@ -1629,6 +2278,7 @@ export function registerWpCommands(wp, runtime) {
1629
2278
  .description("Add a comment to one work package")
1630
2279
  .argument("<id>")
1631
2280
  .argument("<text>", "markdown body of the comment")
2281
+ .option("--internal", "post an internal comment, visible only to users who may see internal comments")
1632
2282
  .option(recordOptions.json, "emit a flat JSON record")
1633
2283
  .option(recordOptions.fields, "comma-separated columns to show")
1634
2284
  .option(recordOptions.profile, "use this profile for this command only")
@@ -1639,10 +2289,157 @@ export function registerWpCommands(wp, runtime) {
1639
2289
  // a caller who fixes the flag and retries cannot post it twice.
1640
2290
  selectedFields(options.fields, ACTIVITY_ROW_SHAPE);
1641
2291
  const profile = await openProfile(runtime, options);
1642
- const created = activityRow(await apiPost(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${reference}/activities`, { comment: { raw: text } }));
2292
+ // The key is sent only with the flag: an instance without the
2293
+ // internal_comments feature then sees exactly the public request.
2294
+ const body = options.internal === true
2295
+ ? { comment: { raw: text }, internal: true }
2296
+ : { comment: { raw: text } };
2297
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${reference}/activities`, body), COMMENT_WRITE(reference));
2298
+ // The instance explains its own refusals (an internal comment with
2299
+ // the feature off is a 422, not a 403), so the status goes through
2300
+ // the shared write mapping instead of a bare API_ERROR.
2301
+ if (response.status < 200 || response.status >= 300) {
2302
+ throw writeFailure(response.status, response.body, COMMENT_WRITE(reference));
2303
+ }
2304
+ const created = activityRow(response.body);
2305
+ // An instance without internal comments ignores the key and stores a
2306
+ // public comment without any error. The POST itself succeeded, so
2307
+ // this stays a warning (exit 0): a failing exit would break the
2308
+ // outcome contract and read as "nothing was posted".
2309
+ if (options.internal === true && created.internal !== true) {
2310
+ runtime.writeErr("warning: the instance stored the comment as public; it may not support internal comments.\n");
2311
+ }
1643
2312
  const named = await authorResolver((path) => apiGet(profile.instanceUrl, profile.apiKey, path))(created);
1644
2313
  renderRecord(runtime, options, named);
1645
2314
  });
2315
+ // A separate command rather than `wp comment --edit`: the target is an
2316
+ // activity id, not a work package id, so the `<id>` of `wp comment`
2317
+ // would mean two different things. The API has no activity delete, so
2318
+ // there is deliberately no `comment-delete`.
2319
+ wp.command("comment-edit")
2320
+ .description("Edit an existing comment by activity id (see `wp comments`); API v3 has no comment delete")
2321
+ .argument("<activity-id>", "id of the comment, as listed by `wp comments`")
2322
+ .argument("<text>", "new markdown body of the comment")
2323
+ .option(recordOptions.json, "emit a flat JSON record")
2324
+ .option(recordOptions.fields, "comma-separated columns to show")
2325
+ .option(recordOptions.profile, "use this profile for this command only")
2326
+ // An activity id is global, so the project never matters here; the flag
2327
+ // stays so a call copied from `wp comment` is not refused.
2328
+ .option(recordOptions.project, "accepted and ignored: activity ids are global")
2329
+ .action(async (activityId, text, options) => {
2330
+ if (!isIdForm(activityId)) {
2331
+ throw new OpCliError("USAGE_ERROR", `activity "${activityId}" is not an id.`, "comments are addressed by the numeric id `wp comments` lists.");
2332
+ }
2333
+ if (text.trim() === "") {
2334
+ throw new OpCliError("USAGE_ERROR", "the new comment text is empty.", "an edit cannot blank a comment; the API has no comment delete either.");
2335
+ }
2336
+ // Writing: --fields misuse is refused before the comment changes.
2337
+ selectedFields(options.fields, ACTIVITY_ROW_SHAPE);
2338
+ const profile = await openProfile(runtime, options);
2339
+ const path = `/api/v3/activities/${activityId}`;
2340
+ const current = activityRow(await apiGet(profile.instanceUrl, profile.apiKey, path));
2341
+ if (current.kind !== "Comment" || current.comment === "") {
2342
+ throw new OpCliError("USAGE_ERROR", `activity ${activityId} is a change journal, not a comment.`, "only entries listed by `wp comments` can be edited.");
2343
+ }
2344
+ let updated;
2345
+ try {
2346
+ // PATCH takes the comment as a plain string; the {raw} object the
2347
+ // POST takes is a 400 here.
2348
+ const response = await unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, path, { comment: text }), COMMENT_EDIT_WRITE(activityId));
2349
+ if (response.status < 200 || response.status >= 300) {
2350
+ throw writeFailure(response.status, response.body, COMMENT_EDIT_WRITE(activityId));
2351
+ }
2352
+ updated = activityRow(response.body);
2353
+ }
2354
+ catch (error) {
2355
+ // A 401 stays AUTH_FAILED as http.ts raised it; only a 403 is
2356
+ // this key lacking the right to edit someone else's comment.
2357
+ if (error instanceof OpCliError && error.code === "PERMISSION_DENIED") {
2358
+ throw new OpCliError("PERMISSION_DENIED", `this key may not edit comment ${activityId}.`, "only your own comments, or any comment with the \"Edit notes\" permission, can be edited.", error.details);
2359
+ }
2360
+ throw error;
2361
+ }
2362
+ const named = await authorResolver((lookup) => apiGet(profile.instanceUrl, profile.apiKey, lookup))(updated);
2363
+ renderRecord(runtime, options, named);
2364
+ });
2365
+ const watchTarget = async (reference, options) => {
2366
+ requireWpId(reference);
2367
+ const profile = await openProfile(runtime, options);
2368
+ const [userId] = await resolveUserValues(runtime, profile, "user", [options.user ?? "me"]);
2369
+ return {
2370
+ profile,
2371
+ userId: userId,
2372
+ path: `/api/v3/work_packages/${reference}/watchers`,
2373
+ myself: (options.user ?? "me").toLowerCase() === "me",
2374
+ };
2375
+ };
2376
+ /** `changed` is null when the outcome of the write was not observed. */
2377
+ const reportWatch = (reference, options, userId, name, watching, changed) => {
2378
+ if (options.json === true) {
2379
+ runtime.write(`${JSON.stringify({
2380
+ id: Number(reference),
2381
+ user: Number(userId),
2382
+ name,
2383
+ watching,
2384
+ changed,
2385
+ })}\n`);
2386
+ return;
2387
+ }
2388
+ const who = name === null ? `user ${userId}` : `${name} (${userId})`;
2389
+ const verdict = watching
2390
+ ? (changed === false ? "is already watching" : "now watches")
2391
+ : (changed === false ? "was not watching" : "no longer watches");
2392
+ runtime.write(`${who} ${verdict} work package ${reference}.\n`);
2393
+ };
2394
+ const watchOptions = (command) => command
2395
+ .argument("<id>")
2396
+ .option("--user <name-or-id>", "user name, id, or me", "me")
2397
+ .option(recordOptions.json, "emit a flat JSON record")
2398
+ .option(recordOptions.profile, "use this profile for this command only")
2399
+ .option(recordOptions.project, "override the profile default project");
2400
+ watchOptions(wp.command("watch")
2401
+ .description("Add a watcher to one work package (default: me); no-op when already watching"))
2402
+ .action(async (reference, options) => {
2403
+ const { profile, userId, path } = await watchTarget(reference, options);
2404
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, path, { user: { href: `/api/v3/users/${userId}` } }), WATCH_WRITE(reference));
2405
+ if (response.status < 200 || response.status >= 300) {
2406
+ throw writeFailure(response.status, response.body, WATCH_WRITE(reference));
2407
+ }
2408
+ const watcher = watcherRow(response.body);
2409
+ reportWatch(reference, options, userId, typeof watcher.name === "string" ? watcher.name : null, true, response.status === 201);
2410
+ });
2411
+ watchOptions(wp.command("unwatch")
2412
+ .description("Remove a watcher from one work package (default: me); no-op when not watching"))
2413
+ .action(async (reference, options) => {
2414
+ const { profile, userId, path, myself } = await watchTarget(reference, options);
2415
+ const getPage = (lookup) => apiGet(profile.instanceUrl, profile.apiKey, lookup);
2416
+ let name = null;
2417
+ let present = false;
2418
+ try {
2419
+ for await (const element of halElements(getPage, withPageSize(path, DEFAULT_PAGE_SIZE))) {
2420
+ const watcher = watcherRow(element);
2421
+ if (String(watcher.id) === userId) {
2422
+ present = true;
2423
+ name = typeof watcher.name === "string" ? watcher.name : null;
2424
+ }
2425
+ }
2426
+ }
2427
+ catch (error) {
2428
+ // Reading the list needs a permission that removing oneself does
2429
+ // not: for oneself the read is only a courtesy, so go on and
2430
+ // report the outcome as unobserved.
2431
+ if (!(myself && error instanceof OpCliError && error.code === "PERMISSION_DENIED")) {
2432
+ throw error;
2433
+ }
2434
+ present = null;
2435
+ }
2436
+ if (present === false) {
2437
+ reportWatch(reference, options, userId, name, false, false);
2438
+ return;
2439
+ }
2440
+ await deleteWatcher(profile, reference, userId);
2441
+ reportWatch(reference, options, userId, name, false, present === null ? null : true);
2442
+ });
1646
2443
  wp.command("relate")
1647
2444
  .description("Relate one work package to another")
1648
2445
  .argument("<id>")