docks-kit 0.25.0 → 0.26.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.
Files changed (38) hide show
  1. package/AGENTS.md +6 -6
  2. package/README.md +29 -9
  3. package/cli/dist/docks-kit.js +24688 -0
  4. package/cli/docs/command-guards.md +1 -1
  5. package/cli/docs/install.md +26 -6
  6. package/cli/docs/omp-context.md +1 -1
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/src/agentDocs/agentFirstCheck.ts +786 -0
  9. package/cli/src/agentDocs/bridgeCheck.ts +226 -0
  10. package/cli/src/agentDocs/commands.ts +63 -0
  11. package/cli/src/agentDocs/prTemplate.ts +211 -0
  12. package/cli/src/agentDocs/services.ts +202 -0
  13. package/cli/src/agentDocs/shared.ts +730 -0
  14. package/cli/src/agentDocs/verifySkill.ts +136 -0
  15. package/cli/src/argv.ts +25 -1
  16. package/cli/src/commands/agentDocs.ts +29 -0
  17. package/cli/src/commands/plan.ts +29 -0
  18. package/cli/src/commands/skill.ts +29 -0
  19. package/cli/src/commands/update.ts +87 -28
  20. package/cli/src/generated/sotPayload.ts +50 -78
  21. package/cli/src/main.ts +12 -3
  22. package/cli/src/plan/bytes.ts +110 -0
  23. package/cli/src/plan/checkout.ts +341 -0
  24. package/cli/src/plan/commands.ts +1192 -0
  25. package/cli/src/plan/github.ts +816 -0
  26. package/cli/src/plan/records.ts +623 -0
  27. package/cli/src/plan/repository.ts +53 -0
  28. package/cli/src/plan/reviews.ts +292 -0
  29. package/cli/src/plan/services.ts +256 -0
  30. package/cli/src/plan/types.ts +164 -0
  31. package/cli/src/skills/commands.ts +142 -0
  32. package/cli/src/skills/config.json +30 -0
  33. package/cli/src/skills/files.ts +74 -0
  34. package/cli/src/skills/frontmatter.ts +148 -0
  35. package/cli/src/skills/guard.ts +366 -0
  36. package/cli/src/skills/kitGate.ts +406 -0
  37. package/cli/src/skills/rubric.ts +143 -0
  38. package/package.json +7 -4
@@ -0,0 +1,1192 @@
1
+ /**
2
+ * The subcommands of `docks-kit plan`, one function each, and the dispatcher. Each port keeps the arguments, the
3
+ * output lines, and the refusals of plan.mjs; a line that named `plan.mjs` names `docks-kit plan`.
4
+ */
5
+ import path from "node:path";
6
+
7
+ import { Effect } from "effect";
8
+
9
+ import { baseBlob, checkoutState } from "./checkout";
10
+ import {
11
+ associatedNodes,
12
+ connectionNodes,
13
+ createdLabelId,
14
+ currentRepository,
15
+ ghOutput,
16
+ ghResult,
17
+ graphql,
18
+ graphqlData,
19
+ ISSUE_SUMMARY_FIELDS,
20
+ issueConnectionSelection,
21
+ issueSummaries,
22
+ linkSubIssue,
23
+ ownedPreWriteIssue,
24
+ parseJson,
25
+ pullRequestNodes,
26
+ readPullRequest,
27
+ readRepositorySnapshot,
28
+ readSnapshot,
29
+ runGh,
30
+ withBodyFile,
31
+ writeIssueIfUnchanged,
32
+ type PullRequestRead,
33
+ type SnapshotOptions,
34
+ } from "./github";
35
+ import {
36
+ ACCEPTANCE_HEADER,
37
+ ACCEPTANCE_SEPARATOR,
38
+ adviceLines,
39
+ blankFencedRegions,
40
+ bodyDigest,
41
+ budgetAdvice,
42
+ changedLines,
43
+ contractVersion,
44
+ dependencyStep,
45
+ hasClosingKeyword,
46
+ headerStrip,
47
+ isPhaseLabel,
48
+ labelsToRemove,
49
+ LEGACY_MARKER,
50
+ MARKER,
51
+ normalizePlan,
52
+ parentRowChildren,
53
+ parseIssueNumber,
54
+ parseOptions,
55
+ parsePlan,
56
+ PLAN_STATUSES,
57
+ plannedWorkChanges,
58
+ refuseMalformedSteps,
59
+ refuseStuck,
60
+ render,
61
+ replaceTable,
62
+ RESEARCH_PLACEHOLDER,
63
+ researchFilled,
64
+ scopeChanged,
65
+ STEP_STATUSES,
66
+ stepCells,
67
+ stepId,
68
+ STEPS_HEADER,
69
+ STEPS_SEPARATOR,
70
+ STUCK_ADVICE,
71
+ stuckClosed,
72
+ terminal,
73
+ token,
74
+ statusFromIssue as statusFromIssueOf,
75
+ type NormalizeOptions,
76
+ type ParsedPlan,
77
+ type Step,
78
+ } from "./records";
79
+ import { argumentBytes, asBytes } from "./bytes";
80
+ import { reviewDirectory } from "./repository";
81
+ import {
82
+ archiveKind,
83
+ authorityEvents,
84
+ cycleComments,
85
+ grantState,
86
+ landingRecord,
87
+ parentRecord,
88
+ recorded,
89
+ reviewVerdicts,
90
+ type GrantState,
91
+ } from "./reviews";
92
+ import { PlanFiles, PlanWaits, type PlanProcess, type PlanRepository } from "./services";
93
+ import {
94
+ attempt,
95
+ fail,
96
+ field,
97
+ GhError,
98
+ GraphqlError,
99
+ PlanRefusal,
100
+ type Closer,
101
+ type IssueSummary,
102
+ type PlanFailure,
103
+ type PlanIssue,
104
+ } from "./types";
105
+
106
+ export type PlanServices = PlanProcess | PlanRepository | PlanFiles | PlanWaits;
107
+
108
+ // `list` reads the newest plans first, as `gh issue list` did, so the 500-plan cap keeps the same plans.
109
+ const PLAN_LIST_ARGS =
110
+ ',labels:["plan"],states:[OPEN,CLOSED],orderBy:{field:CREATED_AT,direction:DESC}';
111
+ const PLAN_LIST_LIMIT = 500;
112
+ // GitHub closes a plan for a merged pull request a while after the merge. `archive` reads an open plan up to
113
+ // CLOSE_WAIT_READS times until it reads closed, and `reopen` until GitHub records the close by that pull request.
114
+ // Between reads they pause for the next entry of CLOSE_WAIT_PAUSES_MS, and the last entry repeats: about 60 s in all.
115
+ // Once the close shows, `reopen` waits REOPEN_SETTLE_MS before it reads the plan again and writes. A reopen 1 s after
116
+ // GitHub closed a plan for a merged pull request raced that close and left the issue stuck closed with reason
117
+ // REOPENED (#90).
118
+ const CLOSE_WAIT_PAUSES_MS = [250, 500, 1000, 2000];
119
+ const CLOSE_WAIT_READS = 34;
120
+ const REOPEN_SETTLE_MS = 10_000;
121
+ // A child plan that closed as completed, not planned, or duplicate runs no more work.
122
+ const CHILD_TERMINAL_STATUSES: ReadonlySet<string> = new Set(["finished", "retired", "duplicate"]);
123
+ const USAGE =
124
+ "usage: docks-kit plan <new|show|export|edit|status|step|list|archive|retire|reopen> ...";
125
+ const FILE_OPTION: ReadonlySet<string> = new Set(["--file"]);
126
+ // The provenance file of an export is the plan file with this suffix.
127
+ const ORIGIN_SUFFIX = Buffer.from(".origin");
128
+
129
+ /** Write domain output to stdout as is. */
130
+ const writeOut = (text: string | Uint8Array): Effect.Effect<void> =>
131
+ Effect.sync(() => {
132
+ process.stdout.write(text);
133
+ });
134
+ const printLine = (line: string): Effect.Effect<void> => writeOut(`${line}\n`);
135
+ const printErrorLine = (line: string): Effect.Effect<void> =>
136
+ Effect.sync(() => {
137
+ process.stderr.write(`${line}\n`);
138
+ });
139
+
140
+ const refuse = (message: string): PlanRefusal => new PlanRefusal({ message });
141
+
142
+ const printAdvice = Effect.fn("plan.printAdvice")(function* (
143
+ text: string,
144
+ status: string,
145
+ extra: ReadonlyArray<string> = [],
146
+ options: NormalizeOptions = {},
147
+ ) {
148
+ for (const message of yield* attempt(() => adviceLines(text, status, extra, options)))
149
+ yield* printLine(`advice: ${message}`);
150
+ });
151
+
152
+ const isClosed = (issue: Pick<PlanIssue, "state">): boolean =>
153
+ String(issue.state).toUpperCase() === "CLOSED";
154
+
155
+ /** A plan issue with its parsed body, its derived status, and the acting viewer of a write read. */
156
+ interface PlanRead {
157
+ readonly issue: PlanIssue;
158
+ readonly parsed: ParsedPlan;
159
+ readonly status: string;
160
+ readonly labelIds: ReadonlyMap<string, string | null> | undefined;
161
+ readonly login: string | undefined;
162
+ readonly viewerId: string | undefined;
163
+ }
164
+
165
+ const readPlanIssue = Effect.fn("plan.readPlanIssue")(function* (
166
+ value: string | undefined,
167
+ forWrite = false,
168
+ connections: SnapshotOptions = {},
169
+ ) {
170
+ const number = yield* attempt(() => parseIssueNumber(value));
171
+ const { issue, login, viewerId, labelIds } = yield* readSnapshot(number, {
172
+ acting: forWrite,
173
+ ...connections,
174
+ });
175
+ if (!contractVersion(issue.body))
176
+ return yield* refuse(`unreadable plan contract: #${issue.number}`);
177
+ if (forWrite) {
178
+ const owners = issue.assignees.map((owner) => owner.login);
179
+ const foreign = owners.find((owner) => owner !== login);
180
+ if (foreign) return yield* refuse(`plan #${issue.number} is owned by ${foreign}`);
181
+ // The write claims an unassigned plan for the acting viewer.
182
+ if (!owners.length) issue.claimantId = viewerId;
183
+ }
184
+ const parsed = yield* attempt(() => parsePlan(issue.body));
185
+ const read: PlanRead = {
186
+ issue,
187
+ parsed,
188
+ status: statusFromIssueOf(issue),
189
+ labelIds,
190
+ login,
191
+ viewerId,
192
+ };
193
+ return read;
194
+ });
195
+
196
+ function workStarted(issue: PlanIssue, recordStatus: string): boolean {
197
+ if (recordStatus !== "drafting" && recordStatus !== "planned") return true;
198
+ return issue.history.some((label) => token(label.name) === "plan:ongoing");
199
+ }
200
+
201
+ // A started v3 or v4 plan keeps the partial-pull-request flow, so each write keeps it at v4. Every other write
202
+ // writes v5 (E2).
203
+ const writeMarker = (issue: PlanIssue, status: string): string =>
204
+ contractVersion(issue.body) === 5 || !workStarted(issue, status) ? MARKER : LEGACY_MARKER;
205
+
206
+ // A child plan needs a parent that the acting login owns alone and that is still open as a plan (E1).
207
+ function openPlanOf(issue: PlanIssue, login: string | undefined): boolean {
208
+ return (
209
+ contractVersion(issue.body) > 0 &&
210
+ String(issue.state).toUpperCase() === "OPEN" &&
211
+ PLAN_STATUSES.has(statusFromIssueOf(issue)) &&
212
+ issue.assignees.length === 1 &&
213
+ issue.assignees[0].login === login
214
+ );
215
+ }
216
+
217
+ function describeCloser(closer: Closer | null | undefined): string {
218
+ if (closer?.__typename === "PullRequest") return closer.url;
219
+ if (closer?.__typename === "Commit") return `commit ${closer.oid}`;
220
+ return "an unknown closer";
221
+ }
222
+
223
+ const exportPlan = Effect.fn("plan.export")(function* (args: ReadonlyArray<string>) {
224
+ if (args.length !== 1) return yield* refuse("export requires one issue");
225
+ const { issue } = yield* readPlanIssue(args[0]);
226
+ // A byte string, one character per byte, so a folder whose path is not UTF-8 keeps its bytes.
227
+ const directory = yield* reviewDirectory();
228
+ const files = yield* PlanFiles;
229
+ yield* files.ensurePrivateDirectory(Buffer.from(directory, "latin1"));
230
+ const destination = path.join(directory, `plan-${issue.number}.md`);
231
+ const destinationBytes = Buffer.from(destination, "latin1");
232
+ const originBytes = Buffer.from(`${destination}.origin`, "latin1");
233
+ yield* files.writeFile(destinationBytes, issue.body, 0o600);
234
+ yield* files.writeFile(originBytes, `${bodyDigest(issue.body)}\n`, 0o600);
235
+ yield* files.chmod(destinationBytes, 0o600);
236
+ yield* files.chmod(originBytes, 0o600);
237
+ yield* writeOut(Buffer.from(`${destination}\n`, "latin1"));
238
+ });
239
+
240
+ /**
241
+ * The recorded digest of `<planFile>.origin`, or undefined when the file does not exist. `planFile` is the text of
242
+ * the path for messages, and `planBytes` its bytes.
243
+ */
244
+ const readOrigin = Effect.fn("plan.readOrigin")(function* (planFile: string, planBytes: Buffer) {
245
+ const source = `${planFile}.origin`;
246
+ const files = yield* PlanFiles;
247
+ const read = yield* Effect.result(files.readFile(Buffer.concat([planBytes, ORIGIN_SUFFIX])));
248
+ if (read._tag === "Failure") {
249
+ if (read.failure.code === "ENOENT") return undefined;
250
+ return yield* refuse(`unreadable export provenance: ${source}`);
251
+ }
252
+ const digest = read.success.trim();
253
+ if (!/^[0-9a-f]{64}$/.test(digest))
254
+ return yield* refuse(`unreadable export provenance: ${source}`);
255
+ return digest;
256
+ });
257
+
258
+ const createPlan = Effect.fn("plan.new")(function* (args: ReadonlyArray<string>) {
259
+ const options = yield* attempt(() =>
260
+ parseOptions(
261
+ args,
262
+ new Set(["--title", "--goal", "--mode", "--label", "--parent"]),
263
+ new Set(["--label"]),
264
+ ),
265
+ );
266
+ const title = options.values.get("--title");
267
+ const goal = options.values.get("--goal");
268
+ const mode = options.values.get("--mode");
269
+ const parentValue = options.values.get("--parent");
270
+ if (!title?.trim() || goal === undefined || !goal.trim())
271
+ return yield* refuse("new requires --title and --goal");
272
+ const extras = options.lists.get("--label") ?? [];
273
+ for (const label of extras)
274
+ if (/^plan(?::|$)/i.test(label)) return yield* refuse(`reserved label namespace: ${label}`);
275
+ const parent =
276
+ parentValue === undefined
277
+ ? undefined
278
+ : yield* attempt(() => parseIssueNumber(parentValue, "parent issue"));
279
+ const snapshotOptions = { acting: true, labelLookup: true };
280
+ const { labelIds } =
281
+ parent === undefined
282
+ ? yield* readRepositorySnapshot(snapshotOptions)
283
+ : yield* readSnapshot(parent, snapshotOptions).pipe(
284
+ Effect.filterOrFail(
285
+ (snapshot) => openPlanOf(snapshot.issue, snapshot.login),
286
+ () => refuse(`parent #${parent} is not an open plan`),
287
+ ),
288
+ );
289
+ const { nameWithOwner } = yield* currentRepository();
290
+ for (const [label, id] of labelIds ?? [])
291
+ if (id === null) yield* runGh(["label", "create", label, "--repo", nameWithOwner]);
292
+ const goalLines = goal.split("\n");
293
+ const goalText = blankFencedRegions(goal)
294
+ .split("\n")
295
+ .map((masked, index) => {
296
+ const line = goalLines[index];
297
+ return /^ {0,3}##[ \t]/.test(masked) ? line.replace(/^( {0,3})##/, "$1###") : line;
298
+ })
299
+ .join("\n");
300
+ const source = `## Goal\n${goalText}\n## Research\n${RESEARCH_PLACEHOLDER}\n## Steps\n${STEPS_HEADER}\n${STEPS_SEPARATOR}\n## Acceptance\n${ACCEPTANCE_HEADER}\n${ACCEPTANCE_SEPARATOR}`;
301
+ const { body } = yield* attempt(() => normalizePlan(source, { mode }));
302
+ let linkByRest = false;
303
+ const url = yield* withBodyFile(body, (file) =>
304
+ Effect.gen(function* () {
305
+ const argv = [
306
+ "issue",
307
+ "create",
308
+ "--title",
309
+ title.replaceAll("\u2014", " - ").replace(/ {2,}/g, " ").trim(),
310
+ "--body-file",
311
+ file,
312
+ "--label",
313
+ "plan",
314
+ "--label",
315
+ "plan:drafting",
316
+ "--assignee",
317
+ "@me",
318
+ ...extras.flatMap((label) => ["--label", label]),
319
+ "--repo",
320
+ nameWithOwner,
321
+ ];
322
+ if (parent === undefined) return (yield* runGh(argv)).trim();
323
+ const withParent = [...argv, "--parent", String(parent)];
324
+ const result = yield* ghResult(withParent);
325
+ // gh refuses an unknown flag before it creates anything, so the plain create runs once.
326
+ linkByRest = result.status !== 0 && /unknown flag: --parent\b/.test(result.stderr);
327
+ return (linkByRest ? yield* runGh(argv) : yield* ghOutput(withParent, result)).trim();
328
+ }),
329
+ );
330
+ const number = /\/issues\/([1-9]\d*)\/?$/.exec(url)?.[1];
331
+ if (!number)
332
+ return yield* new GhError({ message: "gh issue create returned an invalid issue URL" });
333
+ if (linkByRest && parent !== undefined) yield* linkSubIssue(parent, Number(number));
334
+ yield* printLine(`plan created: #${number} ${url}`);
335
+ yield* printAdvice(source, "drafting", [], { mode });
336
+ });
337
+
338
+ /** The `grant:` state of a plan, with the parent read when the grant rule needs it. */
339
+ const readGrantState = Effect.fn("plan.readGrantState")(function* (issue: PlanIssue, goal: string) {
340
+ const { nameWithOwner } = yield* currentRepository();
341
+ const first = grantState(issue, goal, nameWithOwner);
342
+ if (!("readParent" in first)) return first;
343
+ const parentRead = yield* Effect.result(readSnapshot(first.readParent, { comments: true }));
344
+ const second = grantState(
345
+ issue,
346
+ goal,
347
+ nameWithOwner,
348
+ parentRead._tag === "Failure"
349
+ ? { kind: "unreadable" }
350
+ : { kind: "read", events: authorityEvents(parentRead.success.issue) },
351
+ );
352
+ const state: GrantState = "readParent" in second ? { line: "grant: none", advice: [] } : second;
353
+ return state;
354
+ });
355
+
356
+ const showPlan = Effect.fn("plan.show")(function* (args: ReadonlyArray<string>) {
357
+ const [value, ...flags] = args;
358
+ if (!value || flags.length > 1 || flags.some((flag) => flag !== "--body"))
359
+ return yield* refuse("show requires an issue and optional --body");
360
+ const connections = { comments: true, closure: true, children: true, parent: true };
361
+ const { issue, parsed, status } = yield* readPlanIssue(value, false, connections);
362
+ const reviews = reviewVerdicts(issue);
363
+ const grant = yield* readGrantState(issue, parsed.sections.get("Goal") ?? "");
364
+ const metadata = [
365
+ headerStrip(issue, status),
366
+ `reviews: plan=${reviews.plan ?? "none"} code=${reviews.code ?? "none"}`,
367
+ grant.line,
368
+ ...issue.children.map(
369
+ (child) => `child #${child.number} · ${statusFromIssueOf(child)} · ${child.title}`,
370
+ ),
371
+ ].join("\n");
372
+ if (flags.length) {
373
+ yield* printErrorLine(metadata);
374
+ yield* writeOut(issue.body);
375
+ return;
376
+ }
377
+ yield* printLine(metadata);
378
+ const unfinished =
379
+ status === "finished" ? parsed.steps.find((step) => !terminal(step.status)) : undefined;
380
+ const extra = unfinished
381
+ ? [
382
+ `plan is closed as completed while step ${unfinished.id} is ${unfinished.status}; closed by ${describeCloser(issue.closer)}; reopen the issue if work remains`,
383
+ ]
384
+ : [];
385
+ if (stuckClosed(issue)) extra.push(STUCK_ADVICE);
386
+ if (status === "finished") extra.push(...closedChildAdvice(issue, parsed));
387
+ extra.push(...budgetAdvice(issue.body, parsed, issue.comments.length), ...grant.advice);
388
+ yield* printAdvice(issue.body, status, extra);
389
+ });
390
+
391
+ const childStatuses = (children: ReadonlyArray<IssueSummary>): Map<number, string> =>
392
+ new Map(children.map((child) => [child.number, statusFromIssueOf(child)]));
393
+
394
+ // The children that the rows of a parent name, for the parent recovery rules. They apply only while the latest trusted
395
+ // archive record says that the plan was archived as a parent: a plan archived with its landing pull request, or one
396
+ // that no archive record names, landed or closed without the child proof, so these rules would misread it.
397
+ const parentRecoveryChildren = (issue: PlanIssue, parsed: ParsedPlan): Array<number> | undefined =>
398
+ archiveKind(issue) === "parent" ? parentRowChildren(parsed) : undefined;
399
+
400
+ // Whether no named child is linked and finished. `statuses` maps each linked child to its status.
401
+ const noNamedChildFinished = (
402
+ named: ReadonlyArray<number>,
403
+ statuses: ReadonlyMap<number, string>,
404
+ ): boolean => !named.some((child) => statuses.get(child) === "finished");
405
+
406
+ // The open work that `archive` reopens safely on a plan closed as completed (see openWork): a linked child that is not
407
+ // terminal and, on a parent that no merged pull request closed, a row that names a child that is not linked or rows
408
+ // that name no finished child.
409
+ function closedChildAdvice(issue: PlanIssue, parsed: ParsedPlan): Array<string> {
410
+ const recovery = `run archive ${issue.number} again to reopen it safely`;
411
+ const statuses = childStatuses(issue.children);
412
+ const named = parentRecoveryChildren(issue, parsed);
413
+ const advice: Array<string> = [];
414
+ for (const [child, status] of statuses)
415
+ if (!CHILD_TERMINAL_STATUSES.has(status))
416
+ advice.push(`plan is closed as completed while child #${child} is ${status}; ${recovery}`);
417
+ if (!named) return advice;
418
+ for (const child of named)
419
+ if (!statuses.has(child))
420
+ advice.push(
421
+ `plan names child #${child}, which is not linked; relink it or edit the row; ${recovery}`,
422
+ );
423
+ if (noNamedChildFinished(named, statuses))
424
+ advice.push(`plan is closed as completed but no child finished; ${recovery}`);
425
+ return advice;
426
+ }
427
+
428
+ // The edit rules once work started: each step keeps its id, display, Depends, Effect, and Status, and a new step
429
+ // appends as planned on an open plan.
430
+ function refuseFrozenChanges(
431
+ issue: PlanIssue,
432
+ parsed: ParsedPlan,
433
+ incoming: ReadonlyArray<Step>,
434
+ ): void {
435
+ refuseMalformedSteps(parsed);
436
+ const frozen = (detail: string): never =>
437
+ fail(`step state is frozen once work starts: ${detail}`);
438
+ const ids = new Set(parsed.steps.map((row) => row.id));
439
+ const last = incoming.reduce((position, row, index) => (ids.has(row.id) ? index : position), -1);
440
+ const frozenKeys = ["id", "display", "depends", "effect", "status"] as const;
441
+ for (const row of parsed.steps) {
442
+ const matches = incoming.filter((next) => next.id === row.id);
443
+ if (matches.length !== 1) frozen(`step ${row.id} removed or duplicated`);
444
+ for (const key of frozenKeys)
445
+ if (matches[0][key] !== row[key]) frozen(`step ${row.id} ${key} changed`);
446
+ }
447
+ incoming.forEach((row, index) => {
448
+ if (!ids.has(row.id) && (isClosed(issue) || row.status !== "planned" || index < last))
449
+ frozen(`new step ${row.id} must append as planned on an open plan`);
450
+ });
451
+ }
452
+
453
+ const editPlan = Effect.fn("plan.edit")(function* (args: ReadonlyArray<string>) {
454
+ const [value, ...flags] = args;
455
+ const file = (yield* attempt(() => parseOptions(flags, FILE_OPTION))).values.get("--file");
456
+ if (!file) return yield* refuse("edit requires an issue and --file");
457
+ // The bytes of the path from the command line; `file` is its text for messages.
458
+ const flagBytes = yield* argumentBytes(flags);
459
+ if (!flagBytes.ok) return yield* refuse(flagBytes.cause);
460
+ const fileBytes = Buffer.from(
461
+ (yield* attempt(() => parseOptions(flagBytes.value, FILE_OPTION))).values.get("--file") ??
462
+ asBytes(file),
463
+ "latin1",
464
+ );
465
+ const originBytes = Buffer.concat([fileBytes, ORIGIN_SUFFIX]);
466
+ const { issue, parsed, status } = yield* readPlanIssue(value, true, {
467
+ history: true,
468
+ comments: true,
469
+ });
470
+ const origin = yield* readOrigin(file, fileBytes);
471
+ if (!origin)
472
+ return yield* refuse(
473
+ `missing export provenance: ${file}.origin does not exist; run \`docks-kit plan export ${issue.number}\` and re-apply the edit`,
474
+ );
475
+ if (origin !== bodyDigest(issue.body))
476
+ return yield* refuse(
477
+ `stale export: ${file} was exported from a superseded body; run \`docks-kit plan export ${issue.number}\` and re-apply the edit`,
478
+ );
479
+ const files = yield* PlanFiles;
480
+ const started = workStarted(issue, status);
481
+ const source = yield* files.readFile(fileBytes);
482
+ const { body } = yield* attempt(() =>
483
+ normalizePlan(source, { marker: writeMarker(issue, status) }),
484
+ );
485
+ const incomingPlan = yield* attempt(() => parsePlan(body));
486
+ const incoming = incomingPlan.steps;
487
+ yield* attempt(() => refuseMalformedSteps(incomingPlan));
488
+ const seenIds = new Set<string>();
489
+ for (const row of incoming) {
490
+ if (seenIds.has(row.id))
491
+ return yield* refuse(`duplicate step id after normalization: ${row.id}`);
492
+ seenIds.add(row.id);
493
+ }
494
+ if (started) yield* attempt(() => refuseFrozenChanges(issue, parsed, incoming));
495
+ yield* files.writeFile(fileBytes, body);
496
+ yield* writeIssueIfUnchanged(issue, { body });
497
+ // Refresh provenance only after the remote write, so a failed write can be retried with the same file (#78).
498
+ yield* files.writeFile(originBytes, `${bodyDigest(body)}\n`, 0o600);
499
+ yield* files.chmod(originBytes, 0o600);
500
+ const changes = changedLines(issue.body, body);
501
+ yield* printLine(headerStrip(issue, status));
502
+ yield* printLine(`changed: ${changes.length} line(s)`);
503
+ for (const line of changes) yield* printLine(line);
504
+ const changedWork =
505
+ reviewVerdicts(issue).plan === "pass" ? plannedWorkChanges(parsed, incomingPlan) : [];
506
+ const extra = changedWork.length
507
+ ? [
508
+ `plan review passed before this edit; changed sections: ${changedWork.join(", ")}; review all such edits in one plan-review round before code that depends on them or the next code-review round`,
509
+ ]
510
+ : [];
511
+ if (started && contractVersion(issue.body) === 5 && scopeChanged(parsed, incomingPlan))
512
+ extra.push(
513
+ `check for new scope; move new work into a child plan (new --parent ${issue.number})`,
514
+ );
515
+ extra.push(...budgetAdvice(body, incomingPlan, issue.comments.length));
516
+ yield* printAdvice(source, status, extra);
517
+ });
518
+
519
+ const setPlanStatus = Effect.fn("plan.status")(function* (args: ReadonlyArray<string>) {
520
+ const [value, raw, ...flags] = args;
521
+ const target = token(raw ?? "");
522
+ const reason = (yield* attempt(() => parseOptions(flags, new Set(["--reason"])))).values.get(
523
+ "--reason",
524
+ );
525
+ if (!PLAN_STATUSES.has(target)) return yield* refuse(`unknown plan status: ${target}`);
526
+ if (target === "blocked" && (!reason?.trim() || /[\r\n]/.test(reason)))
527
+ return yield* refuse("blocked status requires --reason as single-line text");
528
+ const { issue, parsed, status, labelIds } = yield* readPlanIssue(value, true, {
529
+ history: true,
530
+ labelLookup: true,
531
+ });
532
+ if (isClosed(issue))
533
+ return yield* refuse(`plan #${issue.number} is closed; status applies to open plans`);
534
+ if (workStarted(issue, status) && !["ongoing", "blocked"].includes(target))
535
+ return yield* refuse(`illegal plan status transition: ${status} -> ${target}`);
536
+ if (["planned", "ongoing"].includes(target) && !researchFilled(parsed))
537
+ return yield* refuse(`status ${target} requires a filled Research section`);
538
+ const content = (parsed.sections.get("Open questions") ?? "").replace(
539
+ /^Blocked:[^\n]*\n?\s*/i,
540
+ "",
541
+ );
542
+ parsed.sections.set(
543
+ "Open questions",
544
+ `${target === "blocked" ? `Blocked: ${reason}\n\n` : ""}${content}`.trim(),
545
+ );
546
+ const source = render(parsed.sections);
547
+ const { body } = yield* attempt(() =>
548
+ normalizePlan(source, { marker: writeMarker(issue, status) }),
549
+ );
550
+ yield* writeIssueIfUnchanged(issue, {
551
+ body,
552
+ add: `plan:${target}`,
553
+ remove: labelsToRemove(issue.labels, target),
554
+ ...(labelIds === undefined ? {} : { labelIds }),
555
+ });
556
+ yield* printLine(`plan #${issue.number} status: ${status} -> ${target}`);
557
+ yield* printAdvice(issue.body, target);
558
+ });
559
+
560
+ const setStepStatus = Effect.fn("plan.step")(function* (args: ReadonlyArray<string>) {
561
+ if (args.length !== 3) return yield* refuse("step requires an issue, step id, and status");
562
+ const [value, id, raw] = args;
563
+ const target = token(raw);
564
+ const { issue, parsed, status } = yield* readPlanIssue(value, true);
565
+ if (!STEP_STATUSES.has(target)) return yield* refuse(`unknown step status: ${target}`);
566
+ if (status !== "ongoing" && status !== "finished")
567
+ return yield* refuse(`plan status is ${status}; expected ongoing`);
568
+ yield* attempt(() => refuseMalformedSteps(parsed));
569
+ const row = parsed.steps.find((step) => step.id === stepId(id));
570
+ if (!row) return yield* refuse(`unknown step id: ${id}`);
571
+ const current = row.status;
572
+ if (status === "finished" && !terminal(target))
573
+ return yield* refuse(
574
+ `plan #${issue.number} is finished; reopen it before moving step ${row.id} to ${target}`,
575
+ );
576
+ if (status !== "finished" && terminal(current) && current !== target)
577
+ return yield* refuse(`illegal step status transition: ${current} -> ${target}`);
578
+ const advice = (yield* attempt(() => normalizePlan(issue.body))).advice.filter((message) =>
579
+ message.startsWith("Mode defaulted"),
580
+ );
581
+ const unfinished = row.depends
582
+ .split(",")
583
+ .map((part) => part.trim())
584
+ .filter((part) => part !== "-" && !terminal(dependencyStep(parsed.steps, part)?.status));
585
+ if (["in-flight", "done"].includes(target) && unfinished.length)
586
+ advice.push(`step ${row.id} has unfinished dependency ${unfinished.join(", ")}`);
587
+ row.status = target;
588
+ replaceTable(
589
+ parsed.sections,
590
+ "Steps",
591
+ STEPS_HEADER,
592
+ STEPS_SEPARATOR,
593
+ parsed.steps.map(stepCells),
594
+ );
595
+ const source = render(parsed.sections);
596
+ const { body } = yield* attempt(() =>
597
+ normalizePlan(source, { marker: writeMarker(issue, status) }),
598
+ );
599
+ yield* writeIssueIfUnchanged(issue, { body });
600
+ yield* printLine(`plan #${issue.number} step ${row.id}: ${current} -> ${target}`);
601
+ yield* printAdvice(source, status, advice);
602
+ });
603
+
604
+ const listPlans = Effect.fn("plan.list")(function* (args: ReadonlyArray<string>) {
605
+ const selected = (yield* attempt(() => parseOptions(args, new Set(["--status"])))).values.get(
606
+ "--status",
607
+ );
608
+ // One GraphQL query per 100 plans; like every snapshot, it names the repository through gh's {owner}/{repo}.
609
+ const query = `query($owner:String!,$name:String!,$after:String){repository(owner:$owner,name:$name){${issueConnectionSelection("issues", ISSUE_SUMMARY_FIELDS, PLAN_LIST_ARGS, true)}}}`;
610
+ const page = (variables: Readonly<Record<string, string>> = {}) =>
611
+ graphql(query, variables).pipe(
612
+ Effect.map((data) => field(field(data, "repository"), "issues")),
613
+ );
614
+ const nodes = yield* connectionNodes(
615
+ yield* page(),
616
+ "plan issues",
617
+ (after) => page({ after }),
618
+ PLAN_LIST_LIMIT,
619
+ );
620
+ const issues = yield* issueSummaries(nodes.slice(0, PLAN_LIST_LIMIT), "plan issues");
621
+ issues.sort(
622
+ (a, b) =>
623
+ Number(a.state.toUpperCase() === "CLOSED") - Number(b.state.toUpperCase() === "CLOSED") ||
624
+ a.number - b.number,
625
+ );
626
+ for (const issue of issues) {
627
+ const status = statusFromIssueOf(issue);
628
+ if (!selected || status === token(selected))
629
+ yield* printLine(`${status}\t#${issue.number}\t${issue.title}`);
630
+ }
631
+ if (issues.length >= PLAN_LIST_LIMIT)
632
+ yield* printLine("advice: list stopped at 500 plans; more plans may exist");
633
+ });
634
+
635
+ // GitHub closes a plan for its merged pull request a while after the merge, so an archive takes the plan open and
636
+ // ongoing as well as closed and finished. A plan finishes only after each of its child plans closed (E1).
637
+ function refuseUnarchivable(plan: PlanRead, codeReview = true): void {
638
+ const { issue, parsed, status } = plan;
639
+ refuseStuck(issue);
640
+ if (status !== (isClosed(issue) ? "finished" : "ongoing"))
641
+ fail(`archive requires ongoing or finished status, found ${status}`);
642
+ refuseMalformedSteps(parsed);
643
+ if (parsed.steps.length === 0) fail("archive refused: no Steps rows parsed");
644
+ const unfinished = parsed.steps.find((row) => !terminal(row.status));
645
+ if (unfinished) fail(`archive refused: non-terminal step ${unfinished.id}`);
646
+ if (codeReview && reviewVerdicts(issue).code !== "pass")
647
+ fail("archive requires Code-review: pass");
648
+ const openChild = issue.children.find(
649
+ (child) => !CHILD_TERMINAL_STATUSES.has(statusFromIssueOf(child)),
650
+ );
651
+ if (openChild)
652
+ fail(`archive refused: child #${openChild.number} is ${statusFromIssueOf(openChild)}`);
653
+ }
654
+
655
+ interface ChildWork {
656
+ readonly number: number;
657
+ readonly status: string;
658
+ }
659
+
660
+ // The first child of the plan that has a new status in a fresh read: a new child, a child with another status, or a
661
+ // child that is no longer linked (status `unlinked`). Undefined when the children are as the snapshot read them.
662
+ const changedChild = Effect.fn("plan.changedChild")(function* (issue: PlanIssue) {
663
+ const before = childStatuses(issue.children);
664
+ const now = childStatuses((yield* readSnapshot(issue.number, { children: true })).issue.children);
665
+ const number = [...now.keys(), ...before.keys()].find(
666
+ (child) => before.get(child) !== now.get(child),
667
+ );
668
+ const work: ChildWork | undefined =
669
+ number === undefined ? undefined : { number, status: now.get(number) ?? "unlinked" };
670
+ return work;
671
+ });
672
+
673
+ // A rerun cannot take a close back, so the close runs only while the plan keeps the snapshot body, no other owner, and
674
+ // the snapshot children with their statuses: a child that reopened or a new child is open work.
675
+ const refuseChangedBeforeClose = Effect.fn("plan.refuseChangedBeforeClose")(function* (
676
+ plan: PlanRead,
677
+ ) {
678
+ const current = yield* ownedPreWriteIssue(plan.issue.number, plan.login);
679
+ if (current.body !== plan.issue.body || (yield* changedChild(plan.issue)))
680
+ return yield* refuse("plan issue changed remotely; re-read and retry");
681
+ });
682
+
683
+ // The open work of a plan that reads closed as completed, as one child and its status, or undefined when it shows none.
684
+ // A child that is not terminal is open work on every plan. On a plan archived as a parent, after archive's own close,
685
+ // `snapshot` holds the children of its pre-close read, and a child that is new, a child that is no longer linked
686
+ // (status `unlinked`), or child rows that name no finished child count too. On such a plan without a snapshot, a row
687
+ // that names a child that is not linked, and rows that name no finished child, count too.
688
+ function openWork(
689
+ { issue, parsed }: PlanRead,
690
+ snapshot?: ReadonlyArray<IssueSummary>,
691
+ ): ChildWork | undefined {
692
+ const now = childStatuses(issue.children);
693
+ const before = snapshot && childStatuses(snapshot);
694
+ const named = parentRecoveryChildren(issue, parsed);
695
+ const work = (number: number): ChildWork => ({ number, status: now.get(number) ?? "unlinked" });
696
+ const open = [...now.keys()].find(
697
+ (child) =>
698
+ !CHILD_TERMINAL_STATUSES.has(now.get(child) ?? "") || (named && before?.has(child) === false),
699
+ );
700
+ if (open !== undefined) return work(open);
701
+ if (!named) return undefined;
702
+ const unlinked = (before ? [...before.keys()] : named).find((child) => !now.has(child));
703
+ if (unlinked !== undefined) return work(unlinked);
704
+ if (noNamedChildFinished(named, now))
705
+ return work(named.find((child) => before?.get(child) === "finished") ?? named[0]);
706
+ return undefined;
707
+ }
708
+
709
+ // The read of a plan for archive's recovery and close checks.
710
+ const archiveConnections: SnapshotOptions = {
711
+ comments: true,
712
+ children: true,
713
+ closure: true,
714
+ labelLookup: true,
715
+ };
716
+
717
+ // Archive found open `work` on `observed`, a plan that it closed or that reads closed as completed. It reopens the plan
718
+ // as `reopen` does, after the settle wait, while the settled read still shows the same close and open work, and then
719
+ // refuses with that work. A plan that someone reopened gets no write.
720
+ const reopenForOpenWork = Effect.fn("plan.reopenForOpenWork")(function* (
721
+ observed: PlanRead,
722
+ work: ChildWork,
723
+ snapshot?: ReadonlyArray<IssueSummary>,
724
+ ) {
725
+ const { number } = observed.issue;
726
+ if (isClosed(observed.issue))
727
+ yield* settleAndReopen({
728
+ observed,
729
+ read: () => readPlanIssue(String(number), true, archiveConnections),
730
+ command: "archive",
731
+ stillReopenable: (plan) =>
732
+ attempt(() => {
733
+ refuseStuck(plan.issue);
734
+ return openWork(plan, snapshot) !== undefined;
735
+ }),
736
+ comment: `Reopened: child #${work.number} changed while plan #${number} closed; work continues.`,
737
+ });
738
+ return yield* refuse(`archive refused: child #${work.number} is ${work.status}`);
739
+ });
740
+
741
+ // A close cannot see a child change that races it, so archive reads the plan again after its own close and compares
742
+ // the children with `snapshot`, the children of its pre-close read.
743
+ const checkAfterOwnClose = Effect.fn("plan.checkAfterOwnClose")(function* (
744
+ number: number,
745
+ snapshot: ReadonlyArray<IssueSummary>,
746
+ ) {
747
+ const after = yield* readPlanIssue(String(number), true, archiveConnections);
748
+ const work = openWork(after, snapshot);
749
+ if (work) return yield* reopenForOpenWork(after, work, snapshot);
750
+ if (!isClosed(after.issue))
751
+ return yield* refuse("plan issue changed remotely; re-read and retry");
752
+ });
753
+
754
+ // A parent holds one row per child plan, with Files `-` and Done when `child #<c> finished`, and every child has its
755
+ // row (E1). Any other plan with children landed work of its own, so it needs the proof of `--pr`.
756
+ function isParentPlan({ issue, parsed }: PlanRead): boolean {
757
+ const children = new Set(issue.children.map((child) => child.number));
758
+ const named = parentRowChildren(parsed);
759
+ return (
760
+ named !== undefined &&
761
+ named.every((child) => children.has(child)) &&
762
+ new Set(named).size === named.length &&
763
+ named.length === children.size
764
+ );
765
+ }
766
+
767
+ // An unassigned plan is claimed before archive closes it, so that the record of the close is a trusted comment when the
768
+ // read after the close needs it.
769
+ const claimBeforeClose = Effect.fn("plan.claimBeforeClose")(function* (plan: PlanRead) {
770
+ if (plan.issue.claimantId === undefined) return;
771
+ yield* writeIssueIfUnchanged(plan.issue);
772
+ plan.issue.claimantId = undefined;
773
+ });
774
+
775
+ // Post the archive `record` on a plan that archive did not close itself, unless a rerun posted it already.
776
+ const postRecordOnce = Effect.fn("plan.postRecordOnce")(function* (plan: PlanRead, record: string) {
777
+ if (recorded(plan.issue, record)) return;
778
+ const { id } = yield* ownedPreWriteIssue(plan.issue.number, plan.login);
779
+ yield* graphqlData([
780
+ "-f",
781
+ "query=mutation($issue:ID!,$body:String!){addComment(input:{subjectId:$issue,body:$body}){clientMutationId}}",
782
+ "-f",
783
+ `issue=${id}`,
784
+ "-f",
785
+ `body=${record}`,
786
+ ]);
787
+ });
788
+
789
+ // The archive of a parent plan: its work landed through its child plans, so a child that closed as completed is the
790
+ // landing proof, and the parent needs no pull request and no code review (E1). A plan that reads closed as completed
791
+ // while its children show open work, such as after a failed read that followed the close, is reopened safely. The
792
+ // close posts the parent archive record.
793
+ const archiveParent = Effect.fn("plan.archiveParent")(function* (number: number) {
794
+ const plan = yield* readPlanIssue(String(number), true, archiveConnections);
795
+ const work = plan.status === "finished" ? openWork(plan) : undefined;
796
+ if (work) return yield* reopenForOpenWork(plan, work);
797
+ const { children } = plan.issue;
798
+ if (children.length === 0) return yield* refuse("archive requires an issue and --pr");
799
+ yield* attempt(() => refuseUnarchivable(plan, false));
800
+ if (!isParentPlan(plan))
801
+ return yield* refuse(
802
+ `archive refused: plan #${number} has its own landing work; archive it with --pr`,
803
+ );
804
+ if (!children.some((child) => statusFromIssueOf(child) === "finished"))
805
+ return yield* refuse(
806
+ `archive refused: no child of plan #${number} finished; retire the parent`,
807
+ );
808
+ const record = parentRecord(children);
809
+ if (!isClosed(plan.issue)) {
810
+ yield* claimBeforeClose(plan);
811
+ yield* refuseChangedBeforeClose(plan);
812
+ // gh posts the comment before it closes, so the record of a close that failed after it is not posted again.
813
+ const comment = recorded(plan.issue, record) ? [] : ["--comment", record];
814
+ const { nameWithOwner } = yield* currentRepository();
815
+ yield* runGh([
816
+ "issue",
817
+ "close",
818
+ String(number),
819
+ "--reason",
820
+ "completed",
821
+ ...comment,
822
+ "--repo",
823
+ nameWithOwner,
824
+ ]);
825
+ yield* checkAfterOwnClose(number, children);
826
+ } else yield* postRecordOnce(plan, record);
827
+ yield* writeIssueIfUnchanged(plan.issue, { remove: labelsToRemove(plan.issue.labels) });
828
+ yield* printLine(`plan #${number} finished (all ${children.length} children finished)`);
829
+ });
830
+
831
+ // The archive of a plan whose work landed through the pull request that `--pr` names. That pull request is the landing
832
+ // proof: the latest close of the plan can come from a commit, another pull request, or a person.
833
+ const archivePlan = Effect.fn("plan.archive")(function* (args: ReadonlyArray<string>) {
834
+ const [value, ...flags] = args;
835
+ const pr = (yield* attempt(() => parseOptions(flags, new Set(["--pr"])))).values.get("--pr");
836
+ if (!value) return yield* refuse("archive requires an issue and --pr");
837
+ if (pr === undefined) return yield* archiveParent(yield* attempt(() => parseIssueNumber(value)));
838
+ const number = yield* attempt(() => parseIssueNumber(value));
839
+ const pullRequest = yield* readPullRequest(
840
+ yield* attempt(() => parseIssueNumber(pr, "pull request")),
841
+ number,
842
+ );
843
+ if (!pullRequest.merged)
844
+ return yield* refuse(`pull request #${pullRequest.number} is not merged`);
845
+ // Each read is a snapshot for the write: it checks ownership, decides the claim, and must still be archivable. A plan
846
+ // that reads closed as completed while a child shows open work, such as after a failed read that followed archive's
847
+ // close, is reopened safely before the archive refusals.
848
+ const read = Effect.fn("plan.archive.read")(function* () {
849
+ const plan = yield* readPlanIssue(String(number), true, {
850
+ comments: true,
851
+ defaultBranch: true,
852
+ children: true,
853
+ closure: true,
854
+ labelLookup: true,
855
+ });
856
+ const work = plan.status === "finished" ? openWork(plan) : undefined;
857
+ if (work) return yield* reopenForOpenWork(plan, work);
858
+ yield* attempt(() => refuseUnarchivable(plan));
859
+ return plan;
860
+ });
861
+ let observed = yield* read();
862
+ const { nameWithOwner, defaultBranch } = yield* currentRepository();
863
+ if (pullRequest.baseRefName !== defaultBranch)
864
+ return yield* refuse(
865
+ `pull request #${pullRequest.number} merged into ${pullRequest.baseRefName}; archive requires a merge into ${nameWithOwner}:${defaultBranch}`,
866
+ );
867
+ if (
868
+ typeof pullRequest.body !== "string" ||
869
+ !hasClosingKeyword(pullRequest.body, number, nameWithOwner)
870
+ )
871
+ return yield* refuse(
872
+ `pull request #${pullRequest.number} has no closing keyword for plan #${number} in its description; ask the owner before you add \`Closes #${number}\` to the merged pull request, then run archive again`,
873
+ );
874
+ // A state change that races GitHub's own close for a merge can leave the plan stuck (#90), so an open plan gets the
875
+ // waits of reopen before archive closes it.
876
+ const waits = yield* PlanWaits;
877
+ for (let reads = 1; !isClosed(observed.issue) && reads < CLOSE_WAIT_READS; reads += 1) {
878
+ yield* waits.sleep(CLOSE_WAIT_PAUSES_MS[Math.min(reads, CLOSE_WAIT_PAUSES_MS.length) - 1]);
879
+ observed = yield* read();
880
+ }
881
+ // The close comes before the label removal: a failed close leaves the plan ongoing and a failed removal leaves it
882
+ // finished, so a rerun archives it either way. Without its phase label, an open plan would no longer be archivable.
883
+ const record = landingRecord(pullRequest.number);
884
+ if (!isClosed(observed.issue)) {
885
+ yield* refuseChangedBeforeClose(observed);
886
+ // One comment explains the close and holds the archive record.
887
+ const comment = `Closed by archive: pull request #${pullRequest.number} merged into ${defaultBranch} and closes this plan, but GitHub left the plan open.\n\n${record}`;
888
+ // gh posts the comment before it closes, so the comment of a close that failed after it is not posted again.
889
+ const commented = cycleComments(observed.issue).some((entry) => entry.body === comment);
890
+ yield* runGh([
891
+ "issue",
892
+ "close",
893
+ String(number),
894
+ "--reason",
895
+ "completed",
896
+ ...(commented ? [] : ["--comment", comment]),
897
+ "--repo",
898
+ nameWithOwner,
899
+ ]);
900
+ yield* checkAfterOwnClose(number, observed.issue.children);
901
+ } else yield* postRecordOnce(observed, record);
902
+ yield* writeIssueIfUnchanged(observed.issue, { remove: labelsToRemove(observed.issue.labels) });
903
+ yield* printLine(`plan #${number} finished (closed by ${pullRequest.url})`);
904
+ });
905
+
906
+ const retirePlan = Effect.fn("plan.retire")(function* (args: ReadonlyArray<string>) {
907
+ const [value, ...flags] = args;
908
+ const reason = (yield* attempt(() => parseOptions(flags, new Set(["--reason"])))).values.get(
909
+ "--reason",
910
+ );
911
+ if (reason === undefined || !reason.trim() || /[\r\n]/.test(reason))
912
+ return yield* refuse("retire requires a single-line --reason");
913
+ const { issue, status } = yield* readPlanIssue(value, true);
914
+ if (isClosed(issue)) return yield* refuse(`cannot retire a ${status} plan`);
915
+ yield* writeIssueIfUnchanged(issue, { remove: labelsToRemove(issue.labels) });
916
+ const { nameWithOwner } = yield* currentRepository();
917
+ yield* runGh([
918
+ "issue",
919
+ "close",
920
+ String(issue.number),
921
+ "--reason",
922
+ "not planned",
923
+ "--comment",
924
+ reason.replaceAll("\u2014", " - ").replace(/ {2,}/g, " "),
925
+ "--repo",
926
+ nameWithOwner,
927
+ ]);
928
+ yield* printLine(`plan #${issue.number} retired`);
929
+ });
930
+
931
+ // Whether the latest close of the plan came from the merged pull request, directly or through a commit associated
932
+ // with it; false while that close predates the merge or the plan has none. Refuses a stuck plan and a close by
933
+ // another closer after the merge.
934
+ const closedByPullRequest = Effect.fn("plan.closedByPullRequest")(function* (
935
+ issue: PlanIssue,
936
+ pullRequest: PullRequestRead,
937
+ ) {
938
+ yield* attempt(() => refuseStuck(issue));
939
+ if (
940
+ issue.closedEventAt === undefined ||
941
+ Date.parse(issue.closedEventAt) < Date.parse(String(pullRequest.mergedAt))
942
+ )
943
+ return false;
944
+ const { closer } = issue;
945
+ const { nameWithOwner } = yield* currentRepository();
946
+ const isPullRequest = (candidate: {
947
+ readonly number: number;
948
+ readonly repository: { readonly nameWithOwner: string };
949
+ }): boolean =>
950
+ candidate.number === pullRequest.number && candidate.repository.nameWithOwner === nameWithOwner;
951
+ const fromPullRequest =
952
+ closer?.__typename === "PullRequest"
953
+ ? isPullRequest(closer)
954
+ : closer?.__typename === "Commit" &&
955
+ (yield* pullRequestNodes(yield* associatedNodes(closer))).some(isPullRequest);
956
+ if (!fromPullRequest)
957
+ return yield* refuse(
958
+ `plan #${issue.number} was closed by ${describeCloser(closer)} after pull request #${pullRequest.number} merged; reopen it by hand only if that close was a mistake`,
959
+ );
960
+ return true;
961
+ });
962
+
963
+ // One write request reopens the plan, posts `comment`, and claims an unassigned plan. It changes no label that the plan
964
+ // holds, so a label that someone adds meanwhile survives. Only when the read right before the write shows no phase
965
+ // label, as after a finished archive, does the same request add `plan:ongoing`. GitHub labels have no compare-and-set,
966
+ // so a phase label can still change around the write: the read after it must show an open plan with exactly one phase
967
+ // label. A plan that reads closed again was closed by someone after the write, and the refusal names `command`, whose
968
+ // rerun reads that close and decides again. An open plan with no phase label or with more than one is refused with the
969
+ // repair through `status`. A reopen compares no body, so the pre-write read is its last ownership check: an owner that
970
+ // appeared after the snapshot is refused, and the claim follows that read. The last field returns the stored state,
971
+ // which shows whether GitHub left the plan stuck.
972
+ const writeReopen = Effect.fn("plan.writeReopen")(function* (
973
+ plan: PlanRead,
974
+ comment: string,
975
+ command: string,
976
+ ) {
977
+ const { issue, login, viewerId, labelIds } = plan;
978
+ const { id, assignees } = yield* ownedPreWriteIssue(issue.number, login);
979
+ const claims = assignees.length === 0;
980
+ const restoresPhase = !(yield* readSnapshot(issue.number)).issue.labels.some((label) =>
981
+ isPhaseLabel(label.name),
982
+ );
983
+ const phaseLabelId = restoresPhase
984
+ ? (labelIds?.get("plan:ongoing") ?? (yield* createdLabelId("plan:ongoing")))
985
+ : undefined;
986
+ const stored = "{... on Issue{state stateReason}}";
987
+ const fields = [
988
+ "reopenIssue(input:{issueId:$issue}){clientMutationId}",
989
+ ...(restoresPhase
990
+ ? ["addLabelsToLabelable(input:{labelableId:$issue,labelIds:$labels}){clientMutationId}"]
991
+ : []),
992
+ `addComment(input:{subjectId:$issue,body:$body}){${claims ? "clientMutationId" : `subject${stored}`}}`,
993
+ ];
994
+ if (claims)
995
+ fields.push(
996
+ `addAssigneesToAssignable(input:{assignableId:$issue,assigneeIds:$assignees}){assignable${stored}}`,
997
+ );
998
+ const declarations = [
999
+ "$issue:ID!",
1000
+ "$body:String!",
1001
+ ...(restoresPhase ? ["$labels:[ID!]!"] : []),
1002
+ ...(claims ? ["$assignees:[ID!]!"] : []),
1003
+ ];
1004
+ const data = yield* graphqlData([
1005
+ "-f",
1006
+ `query=mutation(${declarations.join(",")}){${fields.join(" ")}}`,
1007
+ "-f",
1008
+ `issue=${id}`,
1009
+ "-f",
1010
+ `body=${comment}`,
1011
+ ...(restoresPhase ? ["-f", `labels[]=${phaseLabelId}`] : []),
1012
+ ...(claims ? ["-f", `assignees[]=${viewerId}`] : []),
1013
+ ]).pipe(
1014
+ // GitHub answers the reopen of a stuck plan with "Could not reopen the issue." (#90); the request is not retried.
1015
+ Effect.tapError(() =>
1016
+ readSnapshot(issue.number).pipe(
1017
+ Effect.flatMap((snapshot) => attempt(() => refuseStuck(snapshot.issue))),
1018
+ ),
1019
+ ),
1020
+ );
1021
+ const payload = claims
1022
+ ? field(field(data, "addAssigneesToAssignable"), "assignable")
1023
+ : field(field(data, "addComment"), "subject");
1024
+ const state = field(payload, "state");
1025
+ const stateReason = field(payload, "stateReason");
1026
+ if (typeof state !== "string" || (stateReason !== null && typeof stateReason !== "string"))
1027
+ return yield* new GraphqlError({
1028
+ message: "gh api graphql returned malformed stored plan issue",
1029
+ });
1030
+ yield* attempt(() => refuseStuck({ number: issue.number, state, stateReason }));
1031
+ // The status comes from a fresh read, which must show an open plan with exactly one phase label.
1032
+ const current = (yield* readSnapshot(issue.number)).issue;
1033
+ const status = statusFromIssueOf(current);
1034
+ yield* attempt(() => refuseStuck(current));
1035
+ if (isClosed(current))
1036
+ return yield* refuse(
1037
+ `plan #${issue.number} closed again after the reopen; run ${command} again`,
1038
+ );
1039
+ if (!PLAN_STATUSES.has(status))
1040
+ return yield* refuse(
1041
+ `plan issue state differs after reopen; run status ${issue.number} ongoing to repair the phase labels`,
1042
+ );
1043
+ yield* printLine(`plan #${issue.number} reopened: ${status}`);
1044
+ });
1045
+
1046
+ interface SettleOptions {
1047
+ readonly observed: PlanRead;
1048
+ readonly read: () => Effect.Effect<PlanRead, PlanFailure, PlanServices>;
1049
+ readonly command: string;
1050
+ readonly stillReopenable: (plan: PlanRead) => Effect.Effect<boolean, PlanFailure, PlanServices>;
1051
+ readonly comment: string;
1052
+ }
1053
+
1054
+ // A reopen right after a close can leave the plan stuck closed with reason REOPENED (#90). So a reopen of `observed`, a
1055
+ // plan that reads closed, waits REOPEN_SETTLE_MS and reads the plan again. It writes only while that read shows the
1056
+ // same close as completed and `stillReopenable` accepts it. When someone reopened the plan during the wait, it writes
1057
+ // nothing and returns that read.
1058
+ const settleAndReopen = Effect.fn("plan.settleAndReopen")(function* ({
1059
+ observed,
1060
+ read,
1061
+ command,
1062
+ stillReopenable,
1063
+ comment,
1064
+ }: SettleOptions) {
1065
+ yield* (yield* PlanWaits).sleep(REOPEN_SETTLE_MS);
1066
+ const current = yield* read();
1067
+ const sameClose =
1068
+ (yield* stillReopenable(current)) &&
1069
+ current.issue.closedEventAt === observed.issue.closedEventAt &&
1070
+ describeCloser(current.issue.closer) === describeCloser(observed.issue.closer);
1071
+ if (isClosed(current.issue) && (current.status !== "finished" || !sameClose))
1072
+ return yield* refuse(
1073
+ `plan #${current.issue.number} changed during the settle wait; run ${command} again`,
1074
+ );
1075
+ if (!isClosed(current.issue)) return current;
1076
+ yield* writeReopen(current, comment, command);
1077
+ return undefined;
1078
+ });
1079
+
1080
+ // A v5 plan lands each pull request through a child plan with `Closes #<child>`, so a partial pull request never
1081
+ // closes it (E2). The refusal comes before the pull request read, whatever the state of that pull request. `gh issue
1082
+ // view` resolves the repository as the GraphQL reads do, and it is no GraphQL read of the plan, so the reads that the
1083
+ // close waits count stay the same.
1084
+ const refuseChildPlanReopen = Effect.fn("plan.refuseChildPlanReopen")(function* (number: number) {
1085
+ const viewed = yield* parseJson(
1086
+ yield* runGh(["issue", "view", String(number), "--json", "body"]),
1087
+ "gh issue view",
1088
+ );
1089
+ const body = field(viewed, "body");
1090
+ if (typeof body !== "string")
1091
+ return yield* new GhError({ message: "gh issue view returned malformed plan issue" });
1092
+ if (contractVersion(body) === 5)
1093
+ return yield* refuse(
1094
+ `plan #${number} uses child plans; a partial pull request is not allowed (open a child plan with new --parent ${number})`,
1095
+ );
1096
+ });
1097
+
1098
+ // The reopen after a partial pull request closed the plan through its linked branch (#90).
1099
+ const reopenPlan = Effect.fn("plan.reopen")(function* (args: ReadonlyArray<string>) {
1100
+ const [value, ...flags] = args;
1101
+ const pr = (yield* attempt(() => parseOptions(flags, new Set(["--pr"])))).values.get("--pr");
1102
+ if (!value || !pr) return yield* refuse("reopen requires an issue and --pr");
1103
+ const number = yield* attempt(() => parseIssueNumber(value));
1104
+ const prNumber = yield* attempt(() => parseIssueNumber(pr, "pull request"));
1105
+ yield* refuseChildPlanReopen(number);
1106
+ const pullRequest = yield* readPullRequest(prNumber, number);
1107
+ if (!pullRequest.merged)
1108
+ return yield* refuse(`pull request #${pullRequest.number} is not merged`);
1109
+ if (!pullRequest.closesPlan) {
1110
+ yield* printLine(
1111
+ `pull request #${pullRequest.number} does not close plan #${number}; nothing to reopen`,
1112
+ );
1113
+ return;
1114
+ }
1115
+ // Each read is a snapshot for the write: it checks ownership and decides the claim.
1116
+ const read = () => readPlanIssue(String(number), true, { closure: true, labelLookup: true });
1117
+ const waits = yield* PlanWaits;
1118
+ let observed = yield* read();
1119
+ for (let reads = 1; !(yield* closedByPullRequest(observed.issue, pullRequest)); reads += 1) {
1120
+ if (reads === CLOSE_WAIT_READS) {
1121
+ // GitHub cannot close a closed issue, so a plan that still reads closed by an earlier close never gets the
1122
+ // close from this merge; telling the caller to run reopen again would loop forever.
1123
+ if (isClosed(observed.issue))
1124
+ return yield* refuse(
1125
+ `plan #${number} was closed by ${describeCloser(observed.issue.closer)} before pull request #${pullRequest.number} merged; reopen it by hand only if that close was a mistake`,
1126
+ );
1127
+ return yield* refuse(
1128
+ `GitHub has not closed plan #${number} for pull request #${pullRequest.number} yet; run reopen again once it has`,
1129
+ );
1130
+ }
1131
+ yield* waits.sleep(CLOSE_WAIT_PAUSES_MS[Math.min(reads, CLOSE_WAIT_PAUSES_MS.length) - 1]);
1132
+ observed = yield* read();
1133
+ }
1134
+ // A plan that reads open was reopened after that close.
1135
+ if (!isClosed(observed.issue)) {
1136
+ yield* printLine(`plan #${number} is open: ${observed.status}`);
1137
+ return;
1138
+ }
1139
+ const current = yield* settleAndReopen({
1140
+ observed,
1141
+ read,
1142
+ command: "reopen",
1143
+ stillReopenable: (plan) => closedByPullRequest(plan.issue, pullRequest),
1144
+ comment: `Reopened: partial pull request #${pullRequest.number} closed this plan through its linked branch. Work continues.`,
1145
+ });
1146
+ if (current) yield* printLine(`plan #${number} is open: ${current.status}`);
1147
+ });
1148
+
1149
+ const COMMANDS: Readonly<
1150
+ Record<string, (args: ReadonlyArray<string>) => Effect.Effect<unknown, PlanFailure, PlanServices>>
1151
+ > = {
1152
+ new: createPlan,
1153
+ show: showPlan,
1154
+ export: exportPlan,
1155
+ edit: editPlan,
1156
+ status: setPlanStatus,
1157
+ step: setStepStatus,
1158
+ list: listPlans,
1159
+ archive: archivePlan,
1160
+ retire: retirePlan,
1161
+ reopen: reopenPlan,
1162
+ };
1163
+
1164
+ const printFailure = (error: PlanFailure): Effect.Effect<number> =>
1165
+ printErrorLine(error.message).pipe(Effect.as(1));
1166
+
1167
+ /**
1168
+ * Run `docks-kit plan <args>` and return its exit code. A plan command prints a failure as its message on stderr and
1169
+ * exits 1, as plan.mjs did. `base-blob` and `checkout-state` keep the exit codes of their shell scripts.
1170
+ */
1171
+ export const runPlan = Effect.fn("plan.run")(function* (args: ReadonlyArray<string>) {
1172
+ const [command, ...rest] = args;
1173
+ if (command === "base-blob")
1174
+ return yield* baseBlob(rest).pipe(
1175
+ Effect.catchTag("SpawnError", (error) => printErrorLine(error.message).pipe(Effect.as(2))),
1176
+ );
1177
+ if (command === "checkout-state") return yield* checkoutState(rest);
1178
+ const run =
1179
+ command !== undefined && Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;
1180
+ const outcome = run === undefined ? Effect.fail(refuse(USAGE)) : run(rest);
1181
+ return yield* outcome.pipe(
1182
+ Effect.as(0),
1183
+ Effect.catchTags({
1184
+ PlanRefusal: printFailure,
1185
+ GhError: printFailure,
1186
+ GraphqlError: printFailure,
1187
+ GitError: printFailure,
1188
+ FileError: printFailure,
1189
+ SpawnError: printFailure,
1190
+ }),
1191
+ );
1192
+ });