@kyuki3rain/cupola 0.0.0-stage → 0.1.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 (116) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +202 -0
  3. package/README.md +40 -2
  4. package/dist/adr.js +106 -0
  5. package/dist/catalog.js +137 -0
  6. package/dist/check.js +192 -0
  7. package/dist/cli.js +8 -0
  8. package/dist/code.js +216 -0
  9. package/dist/commands/change.js +522 -0
  10. package/dist/commands/epic.js +311 -0
  11. package/dist/commands/install.js +109 -0
  12. package/dist/commands/locks.js +175 -0
  13. package/dist/commands/procedure.js +92 -0
  14. package/dist/commands/revision.js +139 -0
  15. package/dist/commands/run.js +1015 -0
  16. package/dist/commands/setup.js +382 -0
  17. package/dist/commands/spec.js +80 -0
  18. package/dist/commands/status.js +1158 -0
  19. package/dist/commands/trace.js +397 -0
  20. package/dist/commands/wait.js +102 -0
  21. package/dist/commands/work.js +121 -0
  22. package/dist/commands/workspace.js +126 -0
  23. package/dist/commands/worktree.js +422 -0
  24. package/dist/config.js +289 -0
  25. package/dist/day.js +29 -0
  26. package/dist/e2e-project.js +62 -0
  27. package/dist/e2e.js +207 -0
  28. package/dist/engine/cc-sdd.js +164 -0
  29. package/dist/epic.js +360 -0
  30. package/dist/feedback.js +34 -0
  31. package/dist/frontmatter.js +20 -0
  32. package/dist/git.js +365 -0
  33. package/dist/host/github.js +290 -0
  34. package/dist/host/host.js +1 -0
  35. package/dist/install.js +182 -0
  36. package/dist/io.js +46 -0
  37. package/dist/main.js +771 -0
  38. package/dist/method/v1.js +56 -0
  39. package/dist/procedure.js +60 -0
  40. package/dist/record.js +473 -0
  41. package/dist/release.js +84 -0
  42. package/dist/repo.js +13 -0
  43. package/dist/runbook.js +111 -0
  44. package/dist/safe-write.js +80 -0
  45. package/dist/spec.js +171 -0
  46. package/dist/status.js +190 -0
  47. package/dist/templates.js +49 -0
  48. package/dist/trace.js +275 -0
  49. package/dist/tracker/files.js +156 -0
  50. package/dist/tracker/github-issues.js +217 -0
  51. package/dist/tracker/index.js +27 -0
  52. package/dist/tracker/tracker.js +69 -0
  53. package/dist/tree.js +42 -0
  54. package/dist/trust.js +13 -0
  55. package/dist/version.js +5 -0
  56. package/dist/work.js +149 -0
  57. package/dist/workspace.js +299 -0
  58. package/npm-shrinkwrap.json +2014 -0
  59. package/package.json +41 -4
  60. package/skills/cupola-abort/SKILL.md +45 -0
  61. package/skills/cupola-adr/SKILL.md +41 -0
  62. package/skills/cupola-ask/SKILL.md +42 -0
  63. package/skills/cupola-catalog/SKILL.md +41 -0
  64. package/skills/cupola-catalog-draft/SKILL.md +114 -0
  65. package/skills/cupola-complete/SKILL.md +87 -0
  66. package/skills/cupola-decide/SKILL.md +60 -0
  67. package/skills/cupola-doc/SKILL.md +52 -0
  68. package/skills/cupola-e2e-setup/SKILL.md +78 -0
  69. package/skills/cupola-e2e-test/SKILL.md +115 -0
  70. package/skills/cupola-epic-accept/SKILL.md +162 -0
  71. package/skills/cupola-epic-create/SKILL.md +120 -0
  72. package/skills/cupola-epic-revise/SKILL.md +71 -0
  73. package/skills/cupola-epic-run/SKILL.md +127 -0
  74. package/skills/cupola-fix/SKILL.md +115 -0
  75. package/skills/cupola-init/SKILL.md +88 -0
  76. package/skills/cupola-intake/SKILL.md +78 -0
  77. package/skills/cupola-operate/SKILL.md +64 -0
  78. package/skills/cupola-resolve/SKILL.md +86 -0
  79. package/skills/cupola-review/SKILL.md +132 -0
  80. package/skills/cupola-spec-design/SKILL.md +164 -0
  81. package/skills/cupola-spec-impl/SKILL.md +135 -0
  82. package/skills/cupola-spec-run/SKILL.md +125 -0
  83. package/skills/cupola-steering/SKILL.md +46 -0
  84. package/templates/install/.kiro/steering/e2e.md +48 -0
  85. package/templates/install/.kiro/steering/operations.md +109 -0
  86. package/templates/install/.kiro/steering/principles.md +25 -0
  87. package/templates/install/CLAUDE.md +19 -0
  88. package/templates/install/adr/TEMPLATE.md +38 -0
  89. package/templates/install/cc-sdd/patches.json +31 -0
  90. package/templates/method-1/behavior-area.md +43 -0
  91. package/templates/method-1/behavior-index.md +16 -0
  92. package/templates/method-1/card.md +41 -0
  93. package/templates/method-1/case-draft.md +25 -0
  94. package/templates/method-1/case.md +38 -0
  95. package/templates/method-1/catalog-spec.md +33 -0
  96. package/templates/method-1/changes/adr.md +4 -0
  97. package/templates/method-1/changes/catalog.md +29 -0
  98. package/templates/method-1/changes/doc.md +5 -0
  99. package/templates/method-1/changes/e2e.md +7 -0
  100. package/templates/method-1/changes/epic.md +29 -0
  101. package/templates/method-1/changes/fix.md +21 -0
  102. package/templates/method-1/changes/release.md +23 -0
  103. package/templates/method-1/changes/spec.md +55 -0
  104. package/templates/method-1/changes/system.md +13 -0
  105. package/templates/method-1/cupola-issue-draft.md +17 -0
  106. package/templates/method-1/epic.md +136 -0
  107. package/templates/method-1/fix-spec.md +34 -0
  108. package/templates/method-1/fix.md +39 -0
  109. package/templates/method-1/lock.json +13 -0
  110. package/templates/method-1/phase-outcome.json +29 -0
  111. package/templates/method-1/record.json +63 -0
  112. package/templates/method-1/report.md +27 -0
  113. package/templates/method-1/runbook.md +39 -0
  114. package/templates/method-1/runner-result.json +6 -0
  115. package/templates/method-1/send-back.md +23 -0
  116. package/templates/methods.json +13 -0
@@ -0,0 +1,1015 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, rm } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { mountWork } from "../code.js";
5
+ import { epicPath, loadConfig, resolveComponents } from "../config.js";
6
+ import { today } from "../day.js";
7
+ import { E2E_PROFILE } from "../e2e.js";
8
+ import { projectProfile } from "../e2e-project.js";
9
+ import { specPath } from "../engine/cc-sdd.js";
10
+ import { parseFrontMatter } from "../frontmatter.js";
11
+ import { behindOrigin, commitPaths, git, gitUserEmail, head, originDefaultBranch, pushBranch, workBranch, } from "../git.js";
12
+ import { github } from "../host/github.js";
13
+ import { phaseDef } from "../method/v1.js";
14
+ import { createFromSendBacks, createRecord, endingCard, next, parseOutcome, parseRecord, pendingSendBacks, RecordError, recordOutcome, serializeRecord, } from "../record.js";
15
+ import { releaseBody, releasesOf } from "../release.js";
16
+ import { assertInsideRepository, writeInside } from "../safe-write.js";
17
+ import { epicBranchName, epicFront, newBlock, readBlock, reassertBlock } from "../spec.js";
18
+ import { runTemplates } from "../templates.js";
19
+ import { fromDraft, parseCase } from "../tracker/tracker.js";
20
+ import { fsTree, gitTree } from "../tree.js";
21
+ import { version } from "../version.js";
22
+ import { findSpecDocument, readCards, runDir, runsOn, workBranchName, } from "../work.js";
23
+ import { workspace } from "../workspace.js";
24
+ import { codeBody, openCodeChanges, readBody } from "./change.js";
25
+ import { claimEnvironments, releaseEnvironments, unknownNeeds } from "./locks.js";
26
+ import { agreedEpicText, carriedOut, droppedBecause, pendingPlan, redesignToTakeIn, revisionsToApply, snapshotEpic, } from "./revision.js";
27
+ import { peopleFeedback, waitingFor } from "./status.js";
28
+ import { trackerOf } from "./work.js";
29
+ import { worktree } from "./worktree.js";
30
+ async function context(io, id, opts) {
31
+ const session = opts.session ?? io.env?.CUPOLA_SESSION;
32
+ if (!session) {
33
+ throw new Error("name the session that runs this: --session <id> (or CUPOLA_SESSION)");
34
+ }
35
+ const ws = await workspace(io);
36
+ const root = ws.root;
37
+ const hub = ws.here.isHub ? root : ws.hub.main;
38
+ const branch = await workBranch(root);
39
+ if (!runsOn(branch, id)) {
40
+ throw new Error(`${id} runs on ${workBranchName(id)}, but this checkout is on ${branch}`);
41
+ }
42
+ const dir = runDir(id);
43
+ const runner = {
44
+ who: await gitUserEmail(root),
45
+ session,
46
+ cli: version(),
47
+ now: (io.now?.() ?? new Date()).toISOString(),
48
+ ...(opts.takeOver ? { takeOver: opts.takeOver } : {}),
49
+ };
50
+ return { root, hub, ws, branch, dir, file: join(dir, "record.json"), runner };
51
+ }
52
+ /**
53
+ * Reads the local record, refusing while origin's branch has commits this
54
+ * checkout lacks: writing on top would lose another person's progress.
55
+ */
56
+ async function load(ctx) {
57
+ if (await behindOrigin(ctx.root, ctx.branch)) {
58
+ throw new RecordError(`origin has commits on ${ctx.branch} that are not here; pull origin ${ctx.branch} first`);
59
+ }
60
+ const path = join(ctx.root, ctx.file);
61
+ return existsSync(path) ? parseRecord(await readFile(path, "utf8")) : undefined;
62
+ }
63
+ async function save(ctx, record, message, afterWrite) {
64
+ await writeInside(ctx.root, ctx.file, serializeRecord(record));
65
+ const more = (await afterWrite?.()) ?? [];
66
+ await commitPaths(ctx.root, ctx.branch, [ctx.dir, ...more], message);
67
+ }
68
+ /** The agreed epic of a full spec, as on the spec's branch. */
69
+ async function epicOf(ctx, epicId) {
70
+ const path = epicPath(ctx.ws.config.paths, epicId);
71
+ const raw = await fsTree(ctx.root).read(path);
72
+ if (raw === undefined)
73
+ throw new Error(`${path} is not on ${ctx.branch}`);
74
+ return { path, ...epicFront(path, raw) };
75
+ }
76
+ /**
77
+ * Cupola's block for a full spec's spec.json when a phase's engine skill
78
+ * dropped or changed it: the file and its new text, or
79
+ * undefined when the block is intact. Read before anything is written, so
80
+ * that a spec.json the phase broke stops the record unchanged.
81
+ */
82
+ async function reassert(ctx, record) {
83
+ const { work } = record;
84
+ if (work.kind !== "spec" || !work.epic)
85
+ return undefined;
86
+ const file = join(specPath(work.id), "spec.json");
87
+ const raw = await fsTree(ctx.root).read(file);
88
+ if (raw === undefined) {
89
+ throw new Error(`${file} is missing; restore it from git before recording the outcome`);
90
+ }
91
+ const { epic } = await epicOf(ctx, work.epic);
92
+ const expected = { ...newBlock(work.epic, epic, work.component), method: record.method };
93
+ let text;
94
+ try {
95
+ text = reassertBlock(file, raw, expected);
96
+ }
97
+ catch (error) {
98
+ throw new Error(`${error.message}; repair it before recording the outcome`);
99
+ }
100
+ return text === undefined ? undefined : { file, text };
101
+ }
102
+ /** The record as it was just before the work's last finish removed it, if it was finished. */
103
+ async function finishedRecord(ctx, id) {
104
+ const sha = await git(ctx.root, [
105
+ "log",
106
+ "-1",
107
+ "--format=%H",
108
+ "--fixed-strings",
109
+ `--grep=cupola: ${id}: finish`,
110
+ ]);
111
+ if (sha === "")
112
+ return undefined;
113
+ const raw = await gitTree(ctx.root, `${sha}^`).read(ctx.file);
114
+ return raw === undefined ? undefined : parseRecord(raw);
115
+ }
116
+ /**
117
+ * The document of the work this checkout runs: a spec's, fix's, or catalog
118
+ * spec's — or, on an epic branch, the epic's own (mode `epic`).
119
+ */
120
+ async function workDocument(ctx, config, id) {
121
+ if (ctx.branch === epicBranchName(id)) {
122
+ const path = epicPath(config.paths, id);
123
+ const raw = await fsTree(ctx.root).read(path);
124
+ if (raw === undefined)
125
+ throw new Error(`${path} is not on ${ctx.branch}`);
126
+ epicFront(path, raw);
127
+ return { kind: "epic", id, component: "system", epic: id, path };
128
+ }
129
+ return findSpecDocument(fsTree(ctx.root), config, id, ctx.ws.here.slug);
130
+ }
131
+ /**
132
+ * Takes the agreed revisions a spec has not taken in yet: the
133
+ * agreed epic and the spec's block are brought up to date, `redesign` sends
134
+ * the run back to its design, and `drop` stops it — the epic's run closes its
135
+ * change. Changes `record` in place; returns the files it rewrote.
136
+ */
137
+ async function takeInRevisions(ctx, id, record) {
138
+ const file = join(specPath(id), "spec.json");
139
+ const raw = await fsTree(ctx.root).read(file);
140
+ const block = raw === undefined ? undefined : readBlock(file, raw);
141
+ if (raw === undefined || !block)
142
+ return { files: [] };
143
+ const todo = await revisionsToApply(ctx.hub, block);
144
+ if (todo.length === 0)
145
+ return { files: [] };
146
+ const dropped = todo.find((t) => t.plan === "drop");
147
+ if (dropped) {
148
+ return { files: [], stop: `R${dropped.revision} drops it; the epic's run closes its change` };
149
+ }
150
+ const epicFile = epicPath(ctx.ws.config.paths, block.epic);
151
+ const agreed = await agreedEpicText(ctx.hub, block.epic);
152
+ if (agreed === undefined) {
153
+ throw new Error(`cannot read the agreed ${epicFile} from origin to take its revisions in`);
154
+ }
155
+ const { epic } = epicFront(epicFile, agreed);
156
+ const order = record.phases.map((p) => p.name);
157
+ const redesign = todo.find((t) => t.plan === "redesign");
158
+ if (redesign) {
159
+ // From the acceptance tests: they were written from the examples the revision may change.
160
+ const from = order.indexOf("acceptance");
161
+ for (const p of record.phases.slice(from)) {
162
+ if (p.state === "done")
163
+ p.state = "redo";
164
+ else if (p.state === "running")
165
+ p.state = "pending";
166
+ else if (p.state === "skipped" && p.skipped_by && order.indexOf(p.skipped_by) >= from) {
167
+ p.state = "pending";
168
+ delete p.skipped_by;
169
+ delete p.note;
170
+ }
171
+ }
172
+ }
173
+ record.events.push({
174
+ at: ctx.runner.now,
175
+ phase: redesign
176
+ ? "acceptance"
177
+ : (record.phases.find((p) => p.state !== "done")?.name ?? "acceptance"),
178
+ what: "revised",
179
+ note: todo.map((t) => `R${t.revision}: ${t.plan}`).join(", "),
180
+ });
181
+ // A spec that continues keeps the contract revisions it implements; a redesigned one takes the
182
+ // new.
183
+ const fresh = newBlock(block.epic, epic, block.component);
184
+ const updated = {
185
+ ...fresh,
186
+ method: block.method,
187
+ contracts: redesign ? fresh.contracts : block.contracts,
188
+ };
189
+ const json = JSON.parse(raw);
190
+ return {
191
+ files: [
192
+ { path: file, text: `${JSON.stringify({ ...json, cupola: updated }, null, 2)}\n` },
193
+ { path: epicFile, text: agreed },
194
+ ],
195
+ };
196
+ }
197
+ /** `cupola run next <work>`: the next phase and what it is given, or where the run stops. */
198
+ export async function runNext(io, id, opts) {
199
+ const ctx = await context(io, id, opts);
200
+ const config = await loadConfig(ctx.root);
201
+ const doc = await workDocument(ctx, config, id);
202
+ const inEpic = doc.kind === "spec" && doc.epic ? doc.epic : undefined;
203
+ if (inEpic)
204
+ await snapshotEpic(ctx.ws, ctx.root, inEpic);
205
+ const read = await readCards(fsTree(ctx.root), id);
206
+ // A revise-epic answer a revision carried out no longer ends the run.
207
+ // The epic's own run too: a revision may carry out a card of its acceptance check.
208
+ const cardsOf = inEpic ?? (doc.kind === "epic" ? id : undefined);
209
+ const cards = cardsOf ? await carriedOut(io, ctx.hub, id, cardsOf, read) : read;
210
+ // A spec its epic no longer runs: dropped by an agreed revision, or the epic aborted.
211
+ const dropped = inEpic ? await droppedBecause(io, ctx.hub, inEpic, doc.component) : undefined;
212
+ if (dropped) {
213
+ const result = { spec: id, stopped: "blocked", note: `${dropped}; it does not run` };
214
+ io.out(opts.json ? JSON.stringify(result) : `${id}: stopped at blocked — ${result.note}`);
215
+ return 0;
216
+ }
217
+ const loaded = await load(ctx);
218
+ const epic = (doc.kind === "spec" || doc.kind === "epic") && doc.epic
219
+ ? await epicOf(ctx, doc.epic)
220
+ : undefined;
221
+ const work = {
222
+ kind: doc.kind,
223
+ id,
224
+ epic: doc.epic,
225
+ component: doc.component,
226
+ // An epic with one spec runs its acceptance check in that spec's run.
227
+ onlySpecOfEpic: epic ? epic.front.specs.length === 1 : false,
228
+ };
229
+ const sendBacks = pendingSendBacks(loaded, cards);
230
+ // Feedback a person left on the change, with no run going, sends it back as a card does:
231
+ // the review phase answers it, and may send the work back further.
232
+ // Only a work whose run has a review phase, at its gate (G4 still sends back only in dialogue).
233
+ let toDraft;
234
+ if (!loaded && sendBacks.length === 0 && doc.kind !== "epic") {
235
+ const host = (io.host ?? github)(ctx.root);
236
+ const change = await host.findChange(ctx.branch);
237
+ const people = await peopleFeedback(host, change, loaded, config);
238
+ if (change && people > 0) {
239
+ sendBacks.push({
240
+ card: Math.max(0, ...cards.map((c) => c.card)),
241
+ type: "send-back",
242
+ file: "",
243
+ effect: null,
244
+ answered: true,
245
+ redo: "review",
246
+ label: `feedback on the change (${people})`,
247
+ });
248
+ // Back to draft once the record exists, so that a failure leaves the change at its gate.
249
+ toDraft = () => host.markDraft(change.number);
250
+ }
251
+ }
252
+ // A send-back starts a new record, with a new lineage, even over a finished one; the
253
+ // record the finish removed still says what is owed and which phases were skipped.
254
+ const finished = !loaded && sendBacks.length > 0 ? await finishedRecord(ctx, id) : undefined;
255
+ const record = sendBacks.length > 0
256
+ ? createFromSendBacks(work, config.review.max_rounds, sendBacks, ctx.runner.now, loaded ?? finished, !loaded && finished !== undefined)
257
+ : (loaded ?? createRecord(work, config.review.max_rounds));
258
+ const created = record !== loaded;
259
+ if (toDraft)
260
+ await toDraft();
261
+ if (!loaded && sendBacks.length === 0) {
262
+ // Without a record, a ready or finished change means the run already reached its gate.
263
+ const change = await (io.host ?? github)(ctx.root).findChange(ctx.branch);
264
+ if (change && (change.state !== "open" || !change.draft)) {
265
+ const gate = ctx.branch === epicBranchName(id) ? "awaiting release (G4)" : "awaiting acceptance (G3)";
266
+ const where = change.state === "open" ? gate : change.state;
267
+ throw new Error(`${id} is ${where} at ${change.url}; there is nothing to run (see \`cupola status ${id}\`)`);
268
+ }
269
+ // A finish followed by an agreed revision that redesigns it is not an interrupted finish: the
270
+ // run starts again, still owing what the finished run left outside the repository.
271
+ const redesign = inEpic ? await redesignToTakeIn(ctx.hub, fsTree(ctx.root), id) : undefined;
272
+ if (redesign !== undefined) {
273
+ const before = await finishedRecord(ctx, id);
274
+ if (before)
275
+ record.outside = before.outside.filter((o) => o.cleanup !== "done");
276
+ }
277
+ if (redesign === undefined &&
278
+ (await git(ctx.root, ["log", "-1", "--format=%s"])) === `cupola: ${id}: finish`) {
279
+ const result = {
280
+ spec: id,
281
+ stopped: ctx.branch === epicBranchName(id) ? "G4" : "G3",
282
+ resume: "finish",
283
+ note: `the finish was interrupted; run \`cupola run finish ${id}\` again (the description is already written)`,
284
+ };
285
+ io.out(opts.json ? JSON.stringify(result) : `${id}: ${result.note}`);
286
+ return 0;
287
+ }
288
+ }
289
+ // An agreed revision of the epic is taken in before anything runs.
290
+ const revised = inEpic ? await takeInRevisions(ctx, id, record) : { files: [] };
291
+ // Written only with the record, so that a run that stops before saving leaves nothing half done.
292
+ const withFiles = async () => {
293
+ for (const f of revised.files)
294
+ await writeInside(ctx.root, f.path, f.text);
295
+ // Outside the hub the epic is a copy kept out of git: it is not committed.
296
+ return revised.files
297
+ .map((f) => f.path)
298
+ .filter((p) => ctx.ws.here.isHub || !p.startsWith(`${ctx.ws.config.paths.epics}/`));
299
+ };
300
+ if (revised.stop) {
301
+ const note = revised.stop;
302
+ if (record.active || created) {
303
+ await save(ctx, { ...record, active: null, serial: record.serial + (created ? 0 : 1) }, `cupola: ${id}: stop at blocked`);
304
+ }
305
+ const result = { spec: id, stopped: "blocked", note };
306
+ io.out(opts.json ? JSON.stringify(result) : `${id}: stopped at blocked — ${note}`);
307
+ return 0;
308
+ }
309
+ const { record: updated, action } = next(record, cards, ctx.runner);
310
+ // Nothing starts while it waits: for a revision under agreement (any phase), or for its
311
+ // providers' designs (its design; acceptance does not wait).
312
+ let note;
313
+ if (action.kind === "phase" && inEpic) {
314
+ const pending = await pendingPlan(io, ctx.hub, inEpic, doc.component);
315
+ const waits = action.phase === "design"
316
+ ? await waitingFor((c) => ctx.ws.repoOf(c) === ctx.ws.here.slug
317
+ ? ctx.root
318
+ : ctx.ws.checkout(ctx.ws.repoOf(c)).main, ctx.ws.config.paths, fsTree(ctx.root), inEpic, doc.component)
319
+ : [];
320
+ note = pending
321
+ ? `R${pending.revision} of ${inEpic}, under agreement, plans to ${pending.plan} it`
322
+ : waits.length > 0
323
+ ? `its design waits for the design of ${waits.join(", ")}`
324
+ : undefined;
325
+ }
326
+ // Nor does a phase whose plan needs a shared e2e environment someone else holds.
327
+ const target = action.kind === "phase" ? updated.phases.find((p) => p.name === action.phase) : undefined;
328
+ let taken = [];
329
+ // Locks live in the repository of each environment's component.
330
+ const project = await projectProfile(ctx.ws, ctx.root, await fsTree(ctx.root).read(E2E_PROFILE));
331
+ if (!note && action.kind === "phase" && target?.needs?.length) {
332
+ const profile = project.profile;
333
+ const unknown = profile ? unknownNeeds(profile, target.needs) : [];
334
+ if (!profile || unknown.length > 0) {
335
+ // The plan cannot be met as written: the phase is given again, to plan again.
336
+ await releaseEnvironments(project.rootOf, target.locks ?? [], id);
337
+ updated.events.push({
338
+ at: ctx.runner.now,
339
+ phase: action.phase,
340
+ what: "replan",
341
+ note: !profile
342
+ ? `${E2E_PROFILE} is not on ${ctx.branch}`
343
+ : `${E2E_PROFILE} has no ${unknown.join(", ")}`,
344
+ });
345
+ delete target.needs;
346
+ delete target.locks;
347
+ }
348
+ }
349
+ if (!note && action.kind === "phase" && target?.needs?.length) {
350
+ const got = await claimEnvironments(project.rootOf, project.profile, {
351
+ needs: target.needs,
352
+ work: id,
353
+ phase: action.phase,
354
+ runner: ctx.runner,
355
+ marker: updated.active?.id ?? "",
356
+ });
357
+ if ("waiting" in got)
358
+ note = got.waiting;
359
+ else {
360
+ taken = got.taken;
361
+ target.locks = got.taken;
362
+ for (const over of got.tookOver) {
363
+ updated.events.push({
364
+ at: ctx.runner.now,
365
+ phase: action.phase,
366
+ what: "lock-taken-over",
367
+ note: over,
368
+ });
369
+ }
370
+ }
371
+ }
372
+ if (note) {
373
+ // Nothing runs while it waits, so it holds no shared environment either.
374
+ await releaseEnvironments(project.rootOf, record.phases.flatMap((p) => p.locks ?? []), id);
375
+ if (created ||
376
+ revised.files.length > 0 ||
377
+ record.active ||
378
+ updated.events.length !== record.events.length) {
379
+ // Keep what next() recorded (a take-over), but no phase starts and nobody holds the run.
380
+ const released = {
381
+ ...record,
382
+ // Locks it held before are given back while it waits (all or none).
383
+ phases: record.phases.map(({ locks: _, ...p }) => p),
384
+ events: [
385
+ ...record.events,
386
+ ...updated.events.slice(record.events.length).filter((e) => e.what === "taken-over"),
387
+ ],
388
+ active: null,
389
+ serial: record.serial + (created ? 0 : 1),
390
+ };
391
+ await save(ctx, released, `cupola: ${id}: stop at waiting`, withFiles);
392
+ }
393
+ const result = { spec: id, stopped: "waiting", note };
394
+ io.out(opts.json ? JSON.stringify(result) : `${id}: stopped at waiting — ${note}`);
395
+ return 0;
396
+ }
397
+ if (created || revised.files.length > 0 || updated.serial !== record.serial) {
398
+ const what = action.kind === "phase" ? `start ${action.phase}` : `stop at ${action.stopped}`;
399
+ try {
400
+ await save(ctx, updated, `cupola: ${id}: ${what}`, withFiles);
401
+ }
402
+ catch (error) {
403
+ // A record that says nothing of the locks must not leave them held.
404
+ await releaseEnvironments(project.rootOf, taken, id).catch(() => { });
405
+ throw error;
406
+ }
407
+ }
408
+ if (action.kind === "stop") {
409
+ const result = { spec: id, stopped: action.stopped, note: action.note };
410
+ io.out(opts.json ? JSON.stringify(result) : `${id}: stopped at ${action.stopped} — ${action.note}`);
411
+ return 0;
412
+ }
413
+ // Finishing clears the cards, so every send-back here belongs to this run's restart.
414
+ const sentBack = cards.filter((c) => c.type === "send-back").sort((a, b) => a.card - b.card);
415
+ // The only spec of an epic outside the hub writes the epic's own files (its system catalog
416
+ // entries) in the hub, on a branch of their own merged with it: the `system` change.
417
+ let hubFiles;
418
+ let components;
419
+ let mounts = [];
420
+ try {
421
+ hubFiles =
422
+ action.phase === "accept" && work.onlySpecOfEpic && doc.epic && !ctx.ws.here.isHub
423
+ ? await systemWorktree(io, ctx, doc.epic)
424
+ : undefined;
425
+ // With every document in the hub, the code the work changes is mounted in its worktree.
426
+ mounts = await mountWork(ctx.ws, ctx.root, id, ctx.branch);
427
+ // An epic's own run checks the components together: each repository's epic branch.
428
+ components =
429
+ doc.kind === "epic" && epic && ctx.ws.repos.length > 1
430
+ ? await epicBranchWorktrees(io, ctx, id, epic.front.specs.map((s) => s.component))
431
+ : undefined;
432
+ }
433
+ catch (error) {
434
+ // The phase cannot be given: what it locked is free for others until it runs again.
435
+ await releaseEnvironments(project.rootOf, taken, id).catch(() => { });
436
+ throw error;
437
+ }
438
+ const given = {
439
+ work: updated.work,
440
+ document: doc.path,
441
+ record: ctx.file,
442
+ cards: join(ctx.dir, "cards"),
443
+ drafts: join(ctx.dir, "drafts"),
444
+ notes: join(ctx.dir, "notes"),
445
+ outcome: join(ctx.dir, "outcome.json"),
446
+ templates: runTemplates(updated.method),
447
+ ...(phaseDef(updated.work.mode, action.phase)?.locks && existsSync(join(ctx.root, E2E_PROFILE))
448
+ ? { e2e: E2E_PROFILE }
449
+ : {}),
450
+ // Other repositories' environments a check may use (their `covers`), copied to read.
451
+ ...(phaseDef(updated.work.mode, action.phase)?.locks && project.others.length > 0
452
+ ? { e2eOthers: project.others }
453
+ : {}),
454
+ ...(target?.locks ? { locks: target.locks } : {}),
455
+ ...(epic ? { epic: epic.path } : {}),
456
+ ...(hubFiles ? { hub: hubFiles } : {}),
457
+ ...(components ? { components } : {}),
458
+ // Code in a repository of its own, mounted here: committed and pushed there, not at the root.
459
+ ...(mounts.length > 0 ? { code: mounts.map((m) => ({ repo: m.slug, dir: m.dir })) } : {}),
460
+ ...(doc.kind === "spec" ? { spec: specPath(id) } : {}),
461
+ // A run restarted at G3: the send-back cards say what the human found wrong.
462
+ ...(sentBack.length > 0
463
+ ? { sendBacks: sentBack.map((c) => join(ctx.dir, "cards", c.file)) }
464
+ : {}),
465
+ };
466
+ if (opts.json) {
467
+ io.out(JSON.stringify({
468
+ phase: action.phase,
469
+ skill: action.skill,
470
+ restarted: action.restarted,
471
+ given,
472
+ }));
473
+ }
474
+ else {
475
+ io.out(`${id}: run ${action.phase} with ${action.skill}${action.restarted ? " (restarted)" : ""}`);
476
+ io.out(` document: ${doc.path}`);
477
+ io.out(` outcome: write ${given.outcome}, then \`cupola run record ${id} --outcome ${given.outcome}\``);
478
+ }
479
+ return 0;
480
+ }
481
+ /**
482
+ * `cupola run record <work> --outcome <file>`: records a phase's outcome. A
483
+ * relative path is taken from the repository root, as `run next` gives it.
484
+ */
485
+ export async function runRecord(io, id, opts) {
486
+ if (!opts.outcome)
487
+ throw new Error("give the phase outcome: --outcome <file>");
488
+ const ctx = await context(io, id, opts);
489
+ const record = await load(ctx);
490
+ if (!record) {
491
+ throw new Error(`${id} has no progress record; start with \`cupola run next ${id}\``);
492
+ }
493
+ const outcomePath = resolve(ctx.root, opts.outcome);
494
+ if (!inside(ctx.root, outcomePath)) {
495
+ throw new Error(`the outcome must be a file in this repository, not ${opts.outcome}`);
496
+ }
497
+ const outcome = parseOutcome(await readFile(outcomePath, "utf8"));
498
+ const project = await projectProfile(ctx.ws, ctx.root, await fsTree(ctx.root).read(E2E_PROFILE));
499
+ if (outcome.result === "needs-environment") {
500
+ if (!project.profile) {
501
+ throw new RecordError(`needs-environment, but ${E2E_PROFILE} is not on ${ctx.branch}`);
502
+ }
503
+ const unknown = unknownNeeds(project.profile, outcome.environments ?? []);
504
+ if (unknown.length > 0) {
505
+ throw new RecordError(`environments: ${unknown.join(", ")} is neither an environment nor a pool of shared environments in ${E2E_PROFILE}`);
506
+ }
507
+ }
508
+ const cards = await readCards(fsTree(ctx.root), id);
509
+ const { record: updated, result } = recordOutcome(record, outcome, { ...ctx.runner, commit: await head(ctx.root) }, cards);
510
+ // The outcome is merged into the record once the record is written; a copy
511
+ // left in the run directory would go stale.
512
+ const inRunDir = inside(join(ctx.root, ctx.dir), outcomePath);
513
+ const block = await reassert(ctx, updated);
514
+ // The phase ended: its shared environments are free for others.
515
+ const held = record.phases.find((p) => p.state === "running")?.locks ?? [];
516
+ await releaseEnvironments(project.rootOf, held, id);
517
+ await save(ctx, updated, `cupola: ${id}: ${outcome.phase} ${outcome.result}`, async () => {
518
+ if (inRunDir)
519
+ await rm(assertInsideRepository(ctx.root, outcomePath));
520
+ if (!block)
521
+ return [];
522
+ await writeInside(ctx.root, block.file, block.text);
523
+ return [block.file];
524
+ });
525
+ // Code committed by the phase is pushed and its change opened as a draft, so that its CI
526
+ // runs while the work is reviewed, not only after the finish.
527
+ const code = await pushCode(io, ctx, id);
528
+ const out = {
529
+ ...(result.continue
530
+ ? { continue: true }
531
+ : { continue: false, result: { spec: id, stopped: result.stopped, note: result.note } }),
532
+ ...(code.length > 0 ? { code } : {}),
533
+ };
534
+ if (opts.json)
535
+ io.out(JSON.stringify(out));
536
+ else
537
+ io.out(result.continue
538
+ ? `${id}: ${outcome.phase} recorded; ask \`cupola run next ${id}\``
539
+ : `${id}: stopped at ${result.stopped} — ${result.note}`);
540
+ return 0;
541
+ }
542
+ /**
543
+ * `cupola run finish <work> --body-file <f>`: after the runner has looked back
544
+ * over the record, removes the run directory in a last commit,
545
+ * writes the change description, and marks the change ready: G3.
546
+ */
547
+ export async function runFinish(io, id, opts) {
548
+ const ctx = await context(io, id, opts);
549
+ const body = opts.bodyFile ? await readBody(io.cwd, opts.bodyFile) : undefined;
550
+ const host = (io.host ?? github)(ctx.root);
551
+ const change = await host.findChange(ctx.branch);
552
+ if (change?.state !== "open") {
553
+ throw new Error(`${id} has no open change; open it with \`cupola change open ${id}\``);
554
+ }
555
+ const record = await load(ctx);
556
+ const finishCommit = `cupola: ${id}: finish`;
557
+ let finishedWork;
558
+ // An epic's release across repositories; one release is the hub's alone.
559
+ const releases = ctx.branch === epicBranchName(id) && ctx.ws.repos.length > 1
560
+ ? releasesOf(ctx.ws, (await epicOf(ctx, id)).front.specs)
561
+ : [];
562
+ const hubRelease = () => releases.find((r) => r.repo.slug === ctx.ws.hub.slug) ?? {
563
+ repo: ctx.ws.hub,
564
+ order: 1,
565
+ of: 1,
566
+ };
567
+ if (!record) {
568
+ // A finish that removed the record but stopped before the change was ready resumes
569
+ // here, checking the description against the record as it was before the finish.
570
+ const last = await git(ctx.root, ["log", "-1", "--format=%s"]);
571
+ if (last !== finishCommit)
572
+ throw new Error(`${id} has no progress record to finish`);
573
+ const before = gitTree(ctx.root, "HEAD^");
574
+ const raw = await before.read(ctx.file);
575
+ if (raw === undefined)
576
+ throw new Error(`${id}: the commit before ${finishCommit} has no record`);
577
+ finishedWork = parseRecord(raw).work;
578
+ // The description was written before the record was removed; a new one replaces it.
579
+ if (body === undefined && (await host.body(change.number)).trim() === "") {
580
+ throw new Error(`${change.url} has no description; give one with --body-file <file>`);
581
+ }
582
+ if (body !== undefined) {
583
+ const ref = await git(ctx.root, ["rev-parse", "--short", "HEAD^"]);
584
+ const described = await describe(io, before, ctx, parseRecord(raw), body, ref);
585
+ await host.setBody(change.number, releases.length > 1 ? releaseBody(described, hubRelease(), releases) : described);
586
+ }
587
+ await pushBranch(ctx.root, ctx.branch); // the finish commit, if its push failed
588
+ }
589
+ else {
590
+ if (record.active && record.active.session !== ctx.runner.session) {
591
+ throw new Error(`${id} is being run by ${record.active.who} (session ${record.active.session}); finish from that session, or take it over with \`cupola run next ${id} --take-over ${record.active.id}\``);
592
+ }
593
+ const left = record.phases.filter((p) => p.state !== "done" && p.state !== "skipped");
594
+ if (left.length > 0) {
595
+ throw new Error(`${id} still has phases to run: ${left.map((p) => `${p.name} (${p.state})`).join(", ")}`);
596
+ }
597
+ const unanswered = (await readCards(fsTree(ctx.root), id)).filter((c) => !c.answered);
598
+ if (unanswered.length > 0) {
599
+ throw new Error(`${id} has unanswered cards: ${unanswered.map((c) => c.card).join(", ")}`);
600
+ }
601
+ if (body === undefined)
602
+ throw new Error("give the final change description: --body-file <file>");
603
+ // The description goes first: if anything after it fails, finishing again picks up from there.
604
+ const ref = await head(ctx.root);
605
+ const described = await describe(io, fsTree(ctx.root), ctx, record, body, ref);
606
+ await host.setBody(change.number, releases.length > 1 ? releaseBody(described, hubRelease(), releases) : described);
607
+ await rm(assertInsideRepository(ctx.root, ctx.dir), { recursive: true, force: true });
608
+ await commitPaths(ctx.root, ctx.branch, [ctx.dir], finishCommit);
609
+ }
610
+ // The system change first: if it cannot be opened, the spec is not offered at G3 alone.
611
+ const work = record?.work ?? finishedWork;
612
+ const system = work?.kind === "spec" &&
613
+ work.epic &&
614
+ !ctx.ws.here.isHub &&
615
+ (await epicOf(ctx, work.epic)).front.specs.length === 1
616
+ ? await openSystemChange(io, ctx, work.epic)
617
+ : undefined;
618
+ // With every document in the hub, the code changes are ready with it, after it was described.
619
+ const code = await finishCode(io, ctx, id, change);
620
+ if (change.draft)
621
+ await host.markReady(change.number);
622
+ // The other repositories' release changes take the same description, each with its place.
623
+ const released = [];
624
+ if (releases.length > 1) {
625
+ const text = await host.body(change.number);
626
+ for (const rel of releases) {
627
+ if (rel.repo.slug === ctx.ws.hub.slug) {
628
+ released.push({ order: rel.order, url: change.url });
629
+ continue;
630
+ }
631
+ const there = ctx.ws.host(io, rel.repo.slug);
632
+ const other = await there.findChange(ctx.branch);
633
+ if (other?.state !== "open") {
634
+ throw new Error(`the release change of ${rel.repo.slug} is not open; open it with \`cupola change open ${id}\``);
635
+ }
636
+ await there.setBody(other.number, releaseBody(text, rel, releases));
637
+ if (other.draft)
638
+ await there.markReady(other.number);
639
+ released.push({ order: rel.order, url: other.url });
640
+ }
641
+ }
642
+ // Every repository's release change, in the order they are merged.
643
+ const changes = released.sort((a, b) => a.order - b.order).map((r) => r.url);
644
+ const gate = ctx.branch === epicBranchName(id) ? "G4" : "G3";
645
+ const where = changes.length > 1
646
+ ? `${changes.join(", then ")} (merged in this order)`
647
+ : code.length > 0
648
+ ? `${code.join(", ")}, then ${change.url} (merged in this order)`
649
+ : change.url;
650
+ const result = {
651
+ spec: id,
652
+ stopped: gate,
653
+ note: `ready for ${gate === "G4" ? "release" : "acceptance"}: ${where}${system ? `, with the system change ${system}` : ""}`,
654
+ ...(system ? { system } : {}),
655
+ ...(changes.length > 1 ? { changes } : {}),
656
+ ...(code.length > 0 ? { code } : {}),
657
+ };
658
+ io.out(opts.json ? JSON.stringify(result) : `${id}: ${result.note}`);
659
+ return 0;
660
+ }
661
+ /**
662
+ * `cupola run end <work>`: carries out an answered card whose effect ends the
663
+ * run. `abort` closes the change; `to-case` files
664
+ * the record's case drafts first. The branch is kept for reference, and the
665
+ * work's status becomes *dropped*.
666
+ */
667
+ export async function runEnd(io, id, opts) {
668
+ const ws = await workspace(io);
669
+ const root = ws.root;
670
+ const branch = await workBranch(root);
671
+ if (!runsOn(branch, id)) {
672
+ throw new Error(`${id} runs on ${workBranchName(id)}, but this checkout is on ${branch}`);
673
+ }
674
+ const ctx = { root, branch, dir: runDir(id), file: join(runDir(id), "record.json") };
675
+ const record = await load(ctx);
676
+ if (!record)
677
+ throw new Error(`${id} has no progress record`);
678
+ const ending = endingCard(record, await readCards(fsTree(root), id));
679
+ if (!ending)
680
+ throw new Error(`no answered card ends ${id}'s run`);
681
+ if (ending.effect === "revise-epic") {
682
+ throw new Error(`card ${ending.card} chose to revise the epic: that is \`cupola-epic-revise\``);
683
+ }
684
+ const host = (io.host ?? github)(root);
685
+ const change = await host.findChange(branch);
686
+ // Problems the run found are filed either way. The stop-fix card's own case
687
+ // is filed only by to-case: abort leaves it unfiled.
688
+ if (ending.effect === "to-case" && !(ending.case && record.drafts.includes(ending.case))) {
689
+ throw new Error(`card ${ending.card} chose to-case, but names no case draft of the record in \`case:\``);
690
+ }
691
+ const drafts = [];
692
+ const cupolaIssues = [];
693
+ for (const d of record.drafts) {
694
+ if (ending.effect === "abort" && d === ending.case)
695
+ continue;
696
+ const text = await fsTree(root).read(join(ctx.dir, "drafts", d));
697
+ if (text === undefined)
698
+ continue;
699
+ if (parseFrontMatter(text).data.kind === "case")
700
+ drafts.push(text);
701
+ else
702
+ cupolaIssues.push(join(ctx.dir, "drafts", d));
703
+ }
704
+ const cases = await fileCases(io, drafts);
705
+ const owed = record.outside.filter((o) => o.cleanup !== "done");
706
+ if (change?.state === "open") {
707
+ const lines = [
708
+ `Ended by card ${ending.card} (${ending.effect}).`,
709
+ ...cases.map((c) => `Filed as case \`${c.id}\`: ${c.url}`),
710
+ ...owed.map((o) => `Left outside the repository: ${o.kind} ${o.id} (${o.where})`),
711
+ ...cupolaIssues.map((p) => `Cupola issue draft for a human to file: \`${p}\` on ${branch}`),
712
+ `The branch ${branch} is kept for reference.`,
713
+ ];
714
+ await host.closeChange(change.number, lines.join("\n"));
715
+ }
716
+ const result = {
717
+ spec: id,
718
+ ended: ending.effect,
719
+ card: ending.card,
720
+ cases,
721
+ outside: owed,
722
+ cupolaIssues,
723
+ change: change?.url ?? null,
724
+ };
725
+ io.out(opts.json ? JSON.stringify(result) : `${id}: ended (${ending.effect}) by card ${ending.card}`);
726
+ return 0;
727
+ }
728
+ /** GitHub refuses descriptions longer than this; keep a margin below it. */
729
+ const MAX_BODY = 60_000;
730
+ /**
731
+ * The final description: the runner's text, which must name every resource
732
+ * left outside the repository, followed by the case drafts, which the record's
733
+ * removal would otherwise lose until the tracker files them. When they do not
734
+ * fit, each is replaced by the command that shows it at `ref`.
735
+ */
736
+ async function describe(io, tree, ctx, record, body, ref) {
737
+ const owed = record.outside.filter((o) => o.cleanup !== "done" && !names(body, o.id));
738
+ if (owed.length > 0) {
739
+ throw new Error(`the change description must name what is left outside the repository: ${owed.map((o) => `${o.kind} ${o.id}`).join(", ")}`);
740
+ }
741
+ if (record.drafts.length === 0)
742
+ return body;
743
+ // Case drafts are filed now; drafts of issues for Cupola itself leave the
744
+ // project only when a human files them, so they stay in the description for the report.
745
+ const drafts = [];
746
+ const cases = [];
747
+ for (const d of record.drafts) {
748
+ const path = join(ctx.dir, "drafts", d);
749
+ const text = await tree.read(path);
750
+ if (text === undefined)
751
+ throw new Error(`case draft ${d} is in the record but not in drafts/`);
752
+ if (parseFrontMatter(text).data.kind === "case")
753
+ cases.push(text);
754
+ else
755
+ drafts.push({ name: d, path, text: text.trim() });
756
+ }
757
+ const filed = await fileCases(io, cases);
758
+ const listed = filed.length === 0
759
+ ? body.trimEnd()
760
+ : `${body.trimEnd()}\n\n## Cases filed\n\n${filed.map((c) => `- \`${c.id}\` — ${c.title} (${c.url})`).join("\n")}`;
761
+ if (drafts.length === 0)
762
+ return `${listed}\n`;
763
+ const section = (parts) => `${listed}\n\n<details><summary>Cupola issue drafts for a human to file (${drafts.length})</summary>\n\n${parts.join("\n\n")}\n\n</details>\n`;
764
+ const full = section(drafts.map((d) => `### ${d.name}\n\n${fenced(d.text)}`));
765
+ if (full.length <= MAX_BODY)
766
+ return full;
767
+ const pointers = section(drafts.map((d) => `### ${d.name}\n\n\`git show ${ref}:${d.path}\``));
768
+ if (pointers.length <= MAX_BODY)
769
+ return pointers;
770
+ throw new Error(`the change description is longer than GitHub accepts (${body.length} characters); shorten it`);
771
+ }
772
+ /**
773
+ * Files case drafts through the tracker. A draft this work already filed — the
774
+ * same id from the same origin — is not filed again, so a finish that stopped
775
+ * midway can run again; an id another case holds is refused.
776
+ */
777
+ export async function fileCases(io, drafts) {
778
+ if (drafts.length === 0)
779
+ return [];
780
+ const tracker = await trackerOf(io);
781
+ const existing = await tracker.list();
782
+ const day = await today(io);
783
+ const filed = [];
784
+ for (const draft of drafts) {
785
+ const doc = fromDraft(draft, day);
786
+ const { id, data } = parseCase(doc);
787
+ const taken = existing.find((c) => c.id === id);
788
+ if (filed.some((c) => c.id === id))
789
+ continue; // the same draft listed twice
790
+ if (!taken) {
791
+ const one = await tracker.file(doc);
792
+ filed.push(one);
793
+ existing.push(one);
794
+ continue;
795
+ }
796
+ const shown = await tracker.show(id);
797
+ const origin = shown ? parseFrontMatter(shown.text).data.origin : undefined;
798
+ if (data.origin === undefined || origin !== data.origin) {
799
+ throw new Error(`case id ${id} is taken by another case (${taken.url}); rename the draft and its entry in the record`);
800
+ }
801
+ filed.push(taken);
802
+ }
803
+ return filed;
804
+ }
805
+ /** Text in a code fence longer than any run of backticks inside it, so it cannot break out. */
806
+ function fenced(text) {
807
+ const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
808
+ const fence = "`".repeat(longest + 1);
809
+ return `${fence}markdown\n${text}\n${fence}`;
810
+ }
811
+ /** Whether the text names an id as a whole word, not as part of another. */
812
+ function names(text, id) {
813
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
814
+ return new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`).test(text);
815
+ }
816
+ /** Whether `path` is `dir` itself or lies under it. */
817
+ function inside(dir, path) {
818
+ const rel = relative(dir, resolve(path));
819
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
820
+ }
821
+ /** The line that heads the hub description's list of code changes, which the finish writes once. */
822
+ const CODE_LIST = "Merged first, each into its own repository:";
823
+ /**
824
+ * After a phase of a work item whose code is in repositories of its own:
825
+ * what it committed there is pushed, and its change opened as a
826
+ * draft once there is something on it, next to the hub's open change. A
827
+ * failure here does not undo the recorded phase: it is said, and the next
828
+ * record or the finish pushes again. Returns the code changes' URLs.
829
+ */
830
+ async function pushCode(io, ctx, id) {
831
+ if (ctx.ws.config.documents !== "hub" || ctx.branch === epicBranchName(id))
832
+ return [];
833
+ try {
834
+ const hub = await (io.host ?? github)(ctx.root).findChange(ctx.branch);
835
+ if (hub?.state !== "open")
836
+ return [];
837
+ const opened = await openCodeChanges(io, ctx.ws, ctx.root, id, ctx.branch, {
838
+ title: `Code: ${id}`,
839
+ hub,
840
+ ready: false,
841
+ });
842
+ return opened.flatMap((c) => (c.change ? [c.change.url] : []));
843
+ }
844
+ catch (error) {
845
+ io.err(`warning: the code was not pushed: ${error.message}`);
846
+ return [];
847
+ }
848
+ }
849
+ /**
850
+ * At the finish of a work item whose code is in repositories of its own:
851
+ * each code change is opened if it was not (its branch had
852
+ * nothing on it before), takes the hub's description after its own lines,
853
+ * and is marked ready; the hub's description lists them. A code repository
854
+ * the work changed nothing in has no change. Returns the code changes' URLs.
855
+ */
856
+ async function finishCode(io, ctx, id, change) {
857
+ if (ctx.ws.config.documents !== "hub" || ctx.branch === epicBranchName(id))
858
+ return [];
859
+ const host = (io.host ?? github)(ctx.root);
860
+ // Everything committed in a code repository is pushed to its change before it is offered at G3.
861
+ await mountWork(ctx.ws, ctx.root, id, ctx.branch);
862
+ const opened = await openCodeChanges(io, ctx.ws, ctx.root, id, ctx.branch, {
863
+ title: `Code: ${id}`,
864
+ hub: change,
865
+ ready: true,
866
+ });
867
+ const codes = opened.filter((c) => c.change);
868
+ if (codes.length === 0)
869
+ return [];
870
+ const text = await host.body(change.number);
871
+ const listed = text.includes(CODE_LIST)
872
+ ? text
873
+ : `${text.trimEnd()}\n\n## Code\n\n${CODE_LIST}\n\n${codes
874
+ .map((c) => `- ${c.slug}: ${c.change?.url}`)
875
+ .join("\n")}\n`;
876
+ if (listed !== text)
877
+ await host.setBody(change.number, listed);
878
+ const urls = [];
879
+ for (const c of codes) {
880
+ const code = c.change;
881
+ if (!code)
882
+ continue;
883
+ // Merged already (after an interrupted finish, the human merged the ready code change): kept.
884
+ if (code.state === "merged") {
885
+ urls.push(code.url);
886
+ continue;
887
+ }
888
+ if (code.state !== "open") {
889
+ throw new Error(`the code change of ${c.slug} is ${code.state}, not open: ${code.url}`);
890
+ }
891
+ await c.host.setBody(code.number, codeBody(id, change.url, text));
892
+ if (code.draft)
893
+ await c.host.markReady(code.number);
894
+ urls.push(code.url);
895
+ }
896
+ return urls;
897
+ }
898
+ /** The hub's worktree on `cupola/<epic>-system`, where the epic's own files are written. */
899
+ async function systemWorktree(io, ctx, epic) {
900
+ const lines = [];
901
+ await worktree({ ...io, cwd: ctx.ws.hub.main, out: (l) => lines.push(l) }, systemWork(epic), {
902
+ json: true,
903
+ });
904
+ return JSON.parse(lines.join("\n")).path;
905
+ }
906
+ /** The work id of an epic's `system` change. */
907
+ export function systemWork(epic) {
908
+ return `${epic}-system`;
909
+ }
910
+ /**
911
+ * At the finish of an epic's only spec outside the hub: the `system` change,
912
+ * opened ready from what the accept phase committed in the hub, unless it
913
+ * committed nothing. Undefined when there is none.
914
+ */
915
+ async function openSystemChange(io, ctx, epic) {
916
+ const branch = workBranchName(systemWork(epic));
917
+ const hub = ctx.ws.hub.main;
918
+ const host = ctx.ws.host(io, ctx.ws.hub.slug);
919
+ const found = await host.findChange(branch);
920
+ if (found?.state === "open") {
921
+ if (found.draft)
922
+ await host.markReady(found.number);
923
+ return found.url;
924
+ }
925
+ const base = await originDefaultBranch(hub);
926
+ if (!base)
927
+ throw new Error(`cannot tell origin's default branch of the hub`);
928
+ // What the accept phase wrote: uncommitted is an error, not nothing; the local branch is
929
+ // pushed when it is ahead; origin's branch counts when this machine has none.
930
+ const path = join(dirname(hub), `${basename(hub)}.worktrees`, systemWork(epic));
931
+ if (existsSync(path) && (await git(path, ["status", "--porcelain"])) !== "") {
932
+ throw new Error(`${path} has uncommitted changes: the accept phase's system entries must be committed first`);
933
+ }
934
+ await git(hub, ["fetch", "--quiet", "origin", `+refs/heads/${base}:refs/remotes/origin/${base}`]);
935
+ const local = await git(hub, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).catch(() => "");
936
+ // Pushed only when the phase committed something: an empty branch is not a change.
937
+ if (local !== "" &&
938
+ (await git(hub, ["rev-list", "--count", `refs/remotes/origin/${base}..${local}`])) !== "0") {
939
+ await git(hub, [
940
+ "push",
941
+ "--quiet",
942
+ "-u",
943
+ "origin",
944
+ `refs/heads/${branch}:refs/heads/${branch}`,
945
+ ]);
946
+ }
947
+ try {
948
+ await git(hub, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`]);
949
+ }
950
+ catch (error) {
951
+ // Exit 2: origin has no such branch, so the phase wrote nothing for the hub. Anything else
952
+ // (origin unreachable) must not pass for that.
953
+ if (error.code === 2)
954
+ return undefined;
955
+ throw new Error(`cannot reach the hub's origin to look for ${branch}; finish again when it is reachable`);
956
+ }
957
+ await git(hub, [
958
+ "fetch",
959
+ "--quiet",
960
+ "origin",
961
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
962
+ ]);
963
+ const files = (await git(hub, [
964
+ "diff",
965
+ "--name-only",
966
+ `refs/remotes/origin/${base}...refs/remotes/origin/${branch}`,
967
+ ]))
968
+ .split("\n")
969
+ .filter(Boolean);
970
+ if (files.length === 0)
971
+ return undefined;
972
+ const body = [
973
+ `<!-- cupola:change ${JSON.stringify({ kind: "system", work: epic, method: 1 })} -->`,
974
+ "## Release",
975
+ "",
976
+ `Merged with the release of epic \`${epic}\` — its \`spec\` change; nothing to judge on its own.`,
977
+ "",
978
+ "## Related",
979
+ "",
980
+ `Refs: epic \`${epic}\` · spec \`${ctx.branch.replace(/^cupola\//, "")}\``,
981
+ "",
982
+ "## Contents",
983
+ "",
984
+ ...files.map((f) => `- ${f}`),
985
+ "",
986
+ ].join("\n");
987
+ const change = await host.openChange({
988
+ branch,
989
+ base,
990
+ title: `System: ${epic}`,
991
+ body,
992
+ draft: false,
993
+ });
994
+ return change.url;
995
+ }
996
+ /** Each component's worktree of the epic branch, made or caught up in its repository. */
997
+ async function epicBranchWorktrees(io, ctx, epic, components) {
998
+ const out = {};
999
+ for (const c of [...new Set(components)]) {
1000
+ const slug = ctx.ws.repoOf(c);
1001
+ const path = resolveComponents(ctx.ws.config).find((x) => x.name === c)?.path ?? ".";
1002
+ let root = ctx.root;
1003
+ if (slug !== ctx.ws.here.slug) {
1004
+ const lines = [];
1005
+ await worktree({ ...io, out: (l) => lines.push(l) }, epic, {
1006
+ json: true,
1007
+ epicBranch: true,
1008
+ inRepo: ctx.ws.checkout(slug).main,
1009
+ });
1010
+ root = JSON.parse(lines.join("\n")).path;
1011
+ }
1012
+ out[c] = path === "." ? root : join(root, path);
1013
+ }
1014
+ return out;
1015
+ }