@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,1158 @@
1
+ import { codeChanges } from "../code.js";
2
+ import { epicPath, resolveComponents } from "../config.js";
3
+ import { E2E_PROFILE } from "../e2e.js";
4
+ import { projectProfile } from "../e2e-project.js";
5
+ import { EpicFront, parseEpic } from "../epic.js";
6
+ import { fromPeople, trusted } from "../feedback.js";
7
+ import { git, originDefaultBranch } from "../git.js";
8
+ import { github } from "../host/github.js";
9
+ import { currentProcedure, procedureRecords } from "../procedure.js";
10
+ import { endingCard, parseRecord } from "../record.js";
11
+ import { releaseChanges, releasesOf } from "../release.js";
12
+ import { epicBranchName, specName, specNamesOf } from "../spec.js";
13
+ import { deriveStatus } from "../status.js";
14
+ import { gitTree } from "../tree.js";
15
+ import { findSpecDocument, MissingWorkError, readCards, runDir, workBranchName } from "../work.js";
16
+ import { locateWork, workspace } from "../workspace.js";
17
+ import { recordsAbort } from "./epic.js";
18
+ import { environmentsInUse } from "./locks.js";
19
+ import { carriedOut, droppedBecause, pendingPlan, redesignToTakeIn } from "./revision.js";
20
+ import { trackerOf } from "./work.js";
21
+ /**
22
+ * Fetches a branch into its tracking ref. Runners of one epic fetch the same
23
+ * refs at once, and git refuses a ref another fetch has locked: the tracking
24
+ * ref that fetch is writing is then as fresh as this one would be.
25
+ */
26
+ export async function fetchOrKeep(root, branch, tracking) {
27
+ try {
28
+ await git(root, ["fetch", "--quiet", "origin", `+${branch}:${tracking}`]);
29
+ }
30
+ catch (error) {
31
+ if (!(await hasRef(root, tracking)))
32
+ throw error;
33
+ }
34
+ }
35
+ async function hasRef(root, ref) {
36
+ try {
37
+ await git(root, ["rev-parse", "--verify", "--quiet", ref]);
38
+ return true;
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ /**
45
+ * Where a work item's files are: its branch — origin's copy, or the local one
46
+ * when that holds everything origin has and more (a push that failed) — else
47
+ * the current commit, for a merged item whose branch is gone.
48
+ */
49
+ export async function workTree(root, branch) {
50
+ const local = `refs/heads/${branch}`;
51
+ const tracking = `refs/remotes/origin/${branch}`;
52
+ const remotes = (await git(root, ["remote"])).split("\n");
53
+ let onOrigin = false;
54
+ if (remotes.includes("origin")) {
55
+ try {
56
+ await git(root, ["ls-remote", "--exit-code", "--heads", "origin", local]);
57
+ onOrigin = true;
58
+ }
59
+ catch (error) {
60
+ // Exit code 2: origin is reachable and the branch is not on it.
61
+ if (error.code !== 2) {
62
+ throw new Error(`cannot reach origin to read ${branch}; try again when it is reachable`);
63
+ }
64
+ }
65
+ if (onOrigin)
66
+ await fetchOrKeep(root, local, tracking);
67
+ }
68
+ const hasLocal = await hasRef(root, local);
69
+ if (onOrigin) {
70
+ if (hasLocal) {
71
+ try {
72
+ await git(root, ["merge-base", "--is-ancestor", tracking, local]);
73
+ return { tree: gitTree(root, local), ref: local };
74
+ }
75
+ catch {
76
+ // the local branch lacks origin's commits: origin is the newer account
77
+ }
78
+ }
79
+ return { tree: gitTree(root, tracking), ref: tracking };
80
+ }
81
+ if (hasLocal)
82
+ return { tree: gitTree(root, local), ref: local };
83
+ return { tree: gitTree(root, "HEAD"), ref: "HEAD" };
84
+ }
85
+ export async function status(io, id, json,
86
+ /** Only a case: its name may also be a work item's. */
87
+ onlyCase = false) {
88
+ // Cases and epics are the hub's: from another repository, read through it.
89
+ const ws = await workspace(io);
90
+ const root = ws.here.isHub ? ws.root : ws.hub.main;
91
+ const config = ws.config;
92
+ let result;
93
+ if (onlyCase) {
94
+ const found = await caseStatus(io, root, config, id);
95
+ if (!found)
96
+ throw new MissingWorkError(`no case ${id} in the tracker`);
97
+ io.out(json ? JSON.stringify(found) : describe(found));
98
+ return 0;
99
+ }
100
+ try {
101
+ result = await workStatus(io, root, config, id);
102
+ }
103
+ catch (error) {
104
+ if (!(error instanceof MissingWorkError))
105
+ throw error;
106
+ const found = await caseStatus(io, root, config, id);
107
+ if (!found)
108
+ throw new MissingWorkError(`${error.message}, and no case ${id} in the tracker`);
109
+ result = found;
110
+ }
111
+ io.out(json ? JSON.stringify(result) : describe(result));
112
+ return 0;
113
+ }
114
+ /** Marks a Log line of a case found not solved at G5, naming the epics judged. */
115
+ const NOT_SOLVED = /<!--\s*cupola:not-solved\s+(\{.*?\})\s*-->/g;
116
+ /** The epics a case's Log says G5 already judged not enough. */
117
+ export function judgedEpics(caseText) {
118
+ const judged = new Set();
119
+ for (const m of caseText.matchAll(NOT_SOLVED)) {
120
+ try {
121
+ const epics = JSON.parse(m[1] ?? "{}").epics;
122
+ if (Array.isArray(epics))
123
+ for (const e of epics)
124
+ judged.add(String(e));
125
+ }
126
+ catch {
127
+ // a marker someone edited by hand: it names nothing
128
+ }
129
+ }
130
+ return judged;
131
+ }
132
+ /** The marker that `cupola work reopen` appends to the Log line. */
133
+ export function notSolvedMarker(epics) {
134
+ return `<!-- cupola:not-solved ${JSON.stringify({ epics })} -->`;
135
+ }
136
+ /**
137
+ * A case's agreed epics — those on origin's default branch that list it —
138
+ * with their statuses. Undefined when the tracker has no such case.
139
+ */
140
+ export async function caseEpics(io, root, config, id) {
141
+ const doc = await (await trackerOf(io)).show(id);
142
+ if (!doc)
143
+ return undefined;
144
+ // The tracker may find it by another name (an issue number): the epics list the case's id.
145
+ const caseId = doc.id;
146
+ const base = await originDefaultBranch(root);
147
+ if (!base)
148
+ throw new Error("cannot tell origin's default branch, where agreed epics are");
149
+ const ref = `refs/remotes/origin/${base}`;
150
+ await git(root, ["fetch", "--quiet", "origin", `+refs/heads/${base}:${ref}`]);
151
+ const agreed = gitTree(root, ref);
152
+ const judged = judgedEpics(doc.text);
153
+ const epics = [];
154
+ for (const file of (await agreed.list(config.paths.epics))
155
+ .filter((f) => f.endsWith(".md"))
156
+ .sort()) {
157
+ const raw = (await agreed.read(`${config.paths.epics}/${file}`)) ?? "";
158
+ const front = EpicFront.safeParse(parseEpic(raw).front);
159
+ if (!front.success || !front.data.cases.includes(caseId))
160
+ continue;
161
+ const epic = file.slice(0, -3);
162
+ const of = await workStatus(io, root, config, epic);
163
+ epics.push({ id: epic, status: of.status, judged: judged.has(epic) });
164
+ }
165
+ return { doc, epics };
166
+ }
167
+ /**
168
+ * The status of a case: open until an agreed epic exists, in
169
+ * progress while one is not done, awaiting resolution (G5) when all are, and
170
+ * resolved once closed. Epics G5 found not enough, and aborted ones, no longer
171
+ * count, so the case is open again.
172
+ */
173
+ export async function caseStatus(io, root, config, id) {
174
+ const found = await caseEpics(io, root, config, id);
175
+ if (!found)
176
+ return undefined;
177
+ const { doc, epics } = found;
178
+ id = doc.id;
179
+ const base = {
180
+ work: { kind: "case", id, component: "" },
181
+ change: null,
182
+ cards: [],
183
+ run: null,
184
+ epics,
185
+ };
186
+ if (!doc.open) {
187
+ return {
188
+ ...base,
189
+ status: "resolved",
190
+ turn: "none",
191
+ gate: null,
192
+ next: { kind: "nothing", text: "Resolved." },
193
+ };
194
+ }
195
+ const counted = epics.filter((e) => !e.judged && e.status !== "aborted" && e.status !== "dropped");
196
+ if (counted.length === 0) {
197
+ return {
198
+ ...base,
199
+ status: "open",
200
+ turn: "none",
201
+ gate: null,
202
+ next: {
203
+ kind: "nothing",
204
+ text: "No agreed epic works on it; turn it into one when you choose.",
205
+ command: `cupola-epic-create ${id}`,
206
+ },
207
+ };
208
+ }
209
+ const running = counted.filter((e) => e.status !== "done");
210
+ if (running.length > 0) {
211
+ return {
212
+ ...base,
213
+ status: "in-progress",
214
+ turn: "none",
215
+ gate: null,
216
+ next: {
217
+ kind: "nothing",
218
+ text: `It follows its epics: ${running.map((e) => `${e.id} (${e.status})`).join(", ")}.`,
219
+ },
220
+ };
221
+ }
222
+ return {
223
+ ...base,
224
+ status: "awaiting-resolution",
225
+ turn: "human",
226
+ gate: "G5",
227
+ next: {
228
+ kind: "gate",
229
+ text: `Its epics are done (${counted.map((e) => e.id).join(", ")}); judge whether the problem is gone.`,
230
+ command: `cupola-resolve ${id}`,
231
+ },
232
+ };
233
+ }
234
+ /**
235
+ * With every document in the hub, a work's documents and code are
236
+ * merged together, the code first. What is left when they are not: the
237
+ * change to act on and what to do, or undefined when nothing is.
238
+ */
239
+ async function codeLeft(io, ws, branch, component, hub) {
240
+ if (component === "system" || (hub?.state !== "merged" && hub?.state !== "closed"))
241
+ return undefined;
242
+ const codes = (await codeChanges(io, ws, branch, [component])).flatMap((c) => c.change ? [c.change] : []);
243
+ if (hub.state === "closed") {
244
+ // The code reached main while its documents did not: they have to follow it.
245
+ const merged = codes.find((c) => c.state === "merged");
246
+ return merged
247
+ ? {
248
+ change: hub,
249
+ text: `has its code change merged (${merged.url}), but its documents' change was closed (${hub.url}): reopen and merge it, then run the command.`,
250
+ }
251
+ : undefined;
252
+ }
253
+ const draft = codes.find((c) => c.state === "open" && c.draft);
254
+ if (draft)
255
+ return {
256
+ change: draft,
257
+ text: `is merged; its code change is still a draft (${draft.url}): mark it ready and merge it, then run the command.`,
258
+ };
259
+ const open = codes.find((c) => c.state === "open");
260
+ if (open)
261
+ return {
262
+ change: open,
263
+ text: `is merged; merge its code change too (${open.url}), then run the command.`,
264
+ };
265
+ const closed = codes.find((c) => c.state === "closed");
266
+ if (closed)
267
+ return {
268
+ change: closed,
269
+ text: `is merged, but its code change was closed without merging (${closed.url}): the documents describe code that is not there; reopen and merge it, then run the command.`,
270
+ };
271
+ return undefined;
272
+ }
273
+ /** The status of any work item: a spec, fix, or catalog spec, or else an epic. */
274
+ export async function workStatus(io, hubRoot, config, id) {
275
+ const branch = workBranchName(id);
276
+ // The work lives in its component's repository; epics, cases, and revisions in the hub.
277
+ const ws = await workspace({ ...io, cwd: hubRoot });
278
+ const hub = hubRoot;
279
+ const located = await locateWork(ws, id, { branch });
280
+ const root = located.slug === ws.here.slug ? hubRoot : located.main;
281
+ const rootOf = (component) => {
282
+ const slug = ws.repoOf(component);
283
+ return slug === located.slug ? root : ws.checkout(slug).main;
284
+ };
285
+ const { tree, ref } = await workTree(root, branch);
286
+ let doc;
287
+ try {
288
+ doc = await findSpecDocument(tree, config, id, located.slug);
289
+ }
290
+ catch (error) {
291
+ if (!(error instanceof MissingWorkError))
292
+ throw error;
293
+ const epic = await epicStatus(io, hub, config, root === hub ? tree : gitTree(hub, "HEAD"), id);
294
+ if (epic)
295
+ return epic;
296
+ // Only a document missing from the branch sends us to the current commit.
297
+ const missing = (e) => e instanceof MissingWorkError
298
+ ? new MissingWorkError(`${e.message}, and no ${epicPath(config.paths, id)}`)
299
+ : e;
300
+ // A merged item whose branch is gone is on origin's default branch, which the main
301
+ // checkout (the human's, never pulled by Cupola) may not have caught up with.
302
+ const trees = ref === "HEAD" ? [] : [gitTree(root, "HEAD")];
303
+ const base = await originDefaultBranch(root);
304
+ if (base) {
305
+ try {
306
+ await git(root, [
307
+ "fetch",
308
+ "--quiet",
309
+ "origin",
310
+ `+refs/heads/${base}:refs/remotes/origin/${base}`,
311
+ ]);
312
+ trees.push(gitTree(root, `refs/remotes/origin/${base}`));
313
+ }
314
+ catch {
315
+ // origin unreachable: the current commit is all there is
316
+ }
317
+ }
318
+ // A spec of an epic with two or more specs is merged into its epic branch.
319
+ trees.push(...(await epicBranchTrees(root, id)));
320
+ let found;
321
+ let last = error;
322
+ for (const t of trees) {
323
+ try {
324
+ found = await findSpecDocument(t, config, id);
325
+ break;
326
+ }
327
+ catch (e) {
328
+ if (!(e instanceof MissingWorkError))
329
+ throw e;
330
+ last = e;
331
+ }
332
+ }
333
+ if (!found)
334
+ throw missing(last);
335
+ doc = found;
336
+ }
337
+ const raw = await tree.read(`${runDir(id)}/record.json`);
338
+ const record = raw === undefined ? undefined : parseRecord(raw);
339
+ const read = await readCards(tree, id);
340
+ const inEpic = doc.kind === "spec" && doc.epic ? doc.epic : undefined;
341
+ const cards = inEpic ? await carriedOut(io, hub, id, inEpic, read) : read;
342
+ const host = (io.host ?? github)(root);
343
+ const change = await host.findChange(branch);
344
+ // The only spec of an epic outside the hub is released with its `system` change:
345
+ // merged alone, it is not done until that one is merged too.
346
+ if (inEpic && change?.state === "merged" && located.slug !== ws.hub.slug) {
347
+ const system = await (io.host ?? github)(hub).findChange(workBranchName(`${inEpic}-system`));
348
+ if (system?.state === "open") {
349
+ return {
350
+ work: { kind: doc.kind, id, component: doc.component },
351
+ change: system,
352
+ cards: [],
353
+ run: null,
354
+ status: "awaiting-acceptance",
355
+ turn: "human",
356
+ gate: "G3",
357
+ next: {
358
+ kind: "gate",
359
+ text: `${id} is merged; merge its system change too (${system.url}), then run the command.`,
360
+ command: `cupola-complete ${id}`,
361
+ },
362
+ };
363
+ }
364
+ }
365
+ // With every document in the hub, its code change is merged with it.
366
+ const code = ws.config.documents === "hub"
367
+ ? await codeLeft(io, ws, branch, doc.component, change)
368
+ : undefined;
369
+ if (code) {
370
+ return {
371
+ work: { kind: doc.kind, id, component: doc.component },
372
+ change: code.change,
373
+ cards: [],
374
+ run: null,
375
+ status: "awaiting-acceptance",
376
+ turn: "human",
377
+ gate: "G3",
378
+ next: {
379
+ kind: "gate",
380
+ text: `${id} ${code.text}`,
381
+ command: `cupola-complete ${id}`,
382
+ },
383
+ };
384
+ }
385
+ const subject = ref === "HEAD" ? "" : await git(root, ["log", "-1", "--format=%s", ref]);
386
+ // Outside the hub, the epic is read from the hub: the spec's branch has no epics.
387
+ const waitsFor = inEpic
388
+ ? await waitingFor(rootOf, ws.config.paths, root === hub ? tree : await hubAgreed(hub), inEpic, doc.component)
389
+ : [];
390
+ const dropped = inEpic ? await droppedBecause(io, hub, inEpic, doc.component) : undefined;
391
+ const redesign = inEpic ? await redesignToTakeIn(hub, tree, id) : undefined;
392
+ const pending = inEpic && change?.state !== "merged" && change?.state !== "closed"
393
+ ? await pendingPlan(io, hub, inEpic, doc.component)
394
+ : undefined;
395
+ const environment = await environmentWait(root, tree, record, id);
396
+ const people = await peopleFeedback(host, change, record, ws.config);
397
+ const left = change?.state === "merged" && (await untidy(root, branch));
398
+ const derived = deriveStatus({
399
+ work: { kind: doc.kind, id, component: doc.component },
400
+ change,
401
+ record,
402
+ cards,
403
+ ...(people > 0 ? { feedback: people } : {}),
404
+ ...(left ? { untidy: true } : {}),
405
+ ...(environment ? { environment } : {}),
406
+ finished: subject === `cupola: ${id}: finish`,
407
+ ...(doc.epic && waitsFor.length > 0
408
+ ? { waiting: { for: waitsFor, resume: `cupola-epic-run ${doc.epic}` } }
409
+ : {}),
410
+ ...(inEpic && change?.state !== "merged" && dropped ? { dropped } : {}),
411
+ ...(inEpic && redesign && change?.state === "open" && !change.draft && !record
412
+ ? {
413
+ retake: {
414
+ text: `R${redesign} of ${inEpic}, agreed, redesigns it: the epic's run sends its change back and runs it again.`,
415
+ command: `cupola-epic-run ${inEpic}`,
416
+ },
417
+ }
418
+ : {}),
419
+ ...(inEpic && pending
420
+ ? {
421
+ revision: `R${pending.revision} of ${inEpic} plans to ${pending.plan} it; it waits until the revision is agreed (G1)`,
422
+ }
423
+ : {}),
424
+ });
425
+ // At G3 with every document in the hub, its code change is merged first.
426
+ if (derived.gate === "G3" && change?.state === "open" && ws.config.documents === "hub") {
427
+ const codes = (await codeChanges(io, ws, branch, [doc.component])).flatMap((c) => c.change?.state === "open" ? [c.change.url] : []);
428
+ if (codes.length > 0)
429
+ return {
430
+ ...derived,
431
+ next: {
432
+ ...derived.next,
433
+ text: `Its code change goes first: ${codes.join(", ")}. ${derived.next.text.replace(/merge it,/, "merge both, the code change first,")}`,
434
+ },
435
+ };
436
+ }
437
+ return derived;
438
+ }
439
+ /**
440
+ * Why a run whose next phase needs shared e2e environments cannot take them
441
+ * now; undefined when it can, or when no phase needs any.
442
+ */
443
+ async function environmentWait(root, tree, record, id) {
444
+ if (!record || record.active)
445
+ return undefined;
446
+ const phase = record.phases.find((p) => p.state === "running") ??
447
+ record.phases.find((p) => p.state === "pending" || p.state === "redo");
448
+ if (!phase?.needs?.length)
449
+ return undefined;
450
+ const ws = await workspace({ out: () => { }, err: () => { }, cwd: root });
451
+ const project = await projectProfile(ws, root, await tree.read(E2E_PROFILE));
452
+ if (!project.profile)
453
+ return undefined;
454
+ return environmentsInUse(project.rootOf, project.profile, phase.needs, id);
455
+ }
456
+ /** Trees of the epic branches on origin whose epic a spec named `id` may belong to. */
457
+ async function epicBranchTrees(root, id) {
458
+ let out;
459
+ try {
460
+ out = await git(root, ["ls-remote", "--heads", "origin", "refs/heads/epic/*"]);
461
+ }
462
+ catch {
463
+ return [];
464
+ }
465
+ const trees = [];
466
+ for (const line of out.split("\n")) {
467
+ const epic = /refs\/heads\/epic\/(\S+)$/.exec(line)?.[1];
468
+ if (!epic || !id.startsWith(`${epic}-`))
469
+ continue;
470
+ const ref = `refs/remotes/origin/${epicBranchName(epic)}`;
471
+ await fetchOrKeep(root, `refs/heads/${epicBranchName(epic)}`, ref);
472
+ trees.push(gitTree(root, ref));
473
+ }
474
+ return trees;
475
+ }
476
+ /**
477
+ * The fix specs an epic's acceptance check added (`<epic>-<component>-fix-<n>`), found by their
478
+ * branches on origin. Merged ones are done and
479
+ * no longer have a branch.
480
+ */
481
+ export async function fixSpecsOf(root, config, epic, known) {
482
+ const ws = await workspace({ out: () => { }, err: () => { }, cwd: root });
483
+ if (ws.slugs.length === 1)
484
+ return fixSpecsIn(root, config, epic, known);
485
+ const found = [];
486
+ for (const slug of ws.slugs) {
487
+ let main;
488
+ try {
489
+ main = ws.checkout(slug).main;
490
+ }
491
+ catch {
492
+ continue;
493
+ }
494
+ found.push(...(await fixSpecsIn(main, config, epic, [...known, ...found])));
495
+ }
496
+ return found;
497
+ }
498
+ async function fixSpecsIn(root, config, epic, known) {
499
+ let out;
500
+ try {
501
+ out = await git(root, ["ls-remote", "--heads", "origin", `refs/heads/cupola/${epic}-*`]);
502
+ }
503
+ catch {
504
+ return [];
505
+ }
506
+ const found = [];
507
+ for (const line of out.split("\n")) {
508
+ const id = /refs\/heads\/cupola\/(\S+)$/.exec(line)?.[1];
509
+ if (!id || known.includes(id) || !/-fix-\d+$/.test(id))
510
+ continue;
511
+ try {
512
+ // Another epic's name may start the same way: the document says whose it is.
513
+ const doc = await findSpecDocument((await workTree(root, workBranchName(id))).tree, config, id);
514
+ if (doc.kind === "fix-spec" && doc.epic === epic)
515
+ found.push(id);
516
+ }
517
+ catch (error) {
518
+ if (error instanceof MissingWorkError)
519
+ continue;
520
+ // A broken document named like another epic's fix spec is that epic's to report, not this
521
+ // one's.
522
+ const component = id.slice(epic.length + 1).replace(/-fix-\d+$/, "");
523
+ if (config.components.some((c) => c.name === component))
524
+ throw error;
525
+ }
526
+ }
527
+ return found;
528
+ }
529
+ /**
530
+ * An epic whose specs are all done: *accepting* while its own
531
+ * record on the epic branch runs the acceptance check and opens the release,
532
+ * *awaiting release* (G4) once the release change is ready, *done* once it is
533
+ * merged.
534
+ */
535
+ async function acceptance(io, root, id, specs, result) {
536
+ const branch = epicBranchName(id);
537
+ // With several repositories, one release per repository, merged in order.
538
+ const ws = await workspace({ ...io, cwd: root });
539
+ const each = ws.repos.length > 1 ? await releaseChanges(io, ws, id, releasesOf(ws, specs)) : undefined;
540
+ const pendingRelease = each?.find((r) => r.change?.state !== "merged");
541
+ const release = each
542
+ ? ((pendingRelease ?? each.at(-1))?.change ?? null)
543
+ : ((await (io.host ?? github)(root).findChange(branch)) ?? null);
544
+ const releases = each?.map((r) => ({
545
+ repo: r.repo.slug,
546
+ order: r.order,
547
+ of: r.of,
548
+ change: r.change,
549
+ }));
550
+ const withRelease = (r) => ({
551
+ ...r,
552
+ change: release,
553
+ ...(releases ? { releases } : {}),
554
+ });
555
+ if (release?.state === "merged") {
556
+ return withRelease(result({
557
+ status: "done",
558
+ turn: "none",
559
+ gate: null,
560
+ next: { kind: "nothing", text: "Released." },
561
+ }));
562
+ }
563
+ const { tree } = await workTree(root, branch);
564
+ const raw = await tree.read(`${runDir(id)}/record.json`);
565
+ const record = raw === undefined ? undefined : parseRecord(raw);
566
+ // A wrong composition stops the check with a card: the human's turn, at G2.
567
+ const cards = await carriedOut(io, root, id, id, await readCards(tree, id));
568
+ const unanswered = cards.filter((c) => !c.answered).map((c) => c.card);
569
+ if (unanswered.length > 0) {
570
+ return {
571
+ ...withRelease(result({
572
+ status: "awaiting-decision",
573
+ turn: "human",
574
+ gate: "G2",
575
+ next: {
576
+ kind: "gate",
577
+ text: `Answer cards ${unanswered.join(", ")} of the acceptance check.`,
578
+ command: `cupola-decide ${id}`,
579
+ },
580
+ })),
581
+ cards: unanswered,
582
+ };
583
+ }
584
+ const ending = endingCard(record, cards);
585
+ if (ending) {
586
+ return withRelease(result({
587
+ status: "accepting",
588
+ turn: "ai",
589
+ gate: null,
590
+ next: {
591
+ kind: "run",
592
+ text: `Card ${ending.card} chose ${ending.effect}, which is not carried out yet.`,
593
+ command: `cupola-decide ${id}`,
594
+ },
595
+ }));
596
+ }
597
+ if (release?.state === "closed" && !record) {
598
+ return withRelease(result({
599
+ status: "in-progress",
600
+ turn: "human",
601
+ gate: null,
602
+ next: {
603
+ kind: "nothing",
604
+ text: `The release change ${release.url} was closed without merging. Reopen it to release the epic, or bring the reason to cupola-intake.`,
605
+ },
606
+ }));
607
+ }
608
+ if (release?.state === "open" && !release.draft && !record) {
609
+ const merged = each?.filter((r) => r.change?.state === "merged").length ?? 0;
610
+ const k = pendingRelease
611
+ ? `${pendingRelease.order} of ${pendingRelease.of} (${pendingRelease.repo.slug})`
612
+ : "";
613
+ return withRelease(result({
614
+ status: "awaiting-release",
615
+ turn: "human",
616
+ gate: "G4",
617
+ next: {
618
+ kind: "gate",
619
+ text: each
620
+ ? `Read "Release" on ${release.url} and merge it, release ${k}${merged > 0 ? `, after the ${merged} merged before it are deployed` : ""}; merge the rest in order, then run the command.`
621
+ : `Read "Release" on ${release.url} and merge it to release the epic, then run the command.`,
622
+ command: `cupola-complete ${id}`,
623
+ },
624
+ }));
625
+ }
626
+ const active = record?.active;
627
+ const environment = await environmentWait(root, tree, record, id);
628
+ if (environment) {
629
+ return withRelease(result({
630
+ status: "accepting",
631
+ turn: "ai",
632
+ gate: null,
633
+ next: {
634
+ kind: "nothing",
635
+ text: `The acceptance check waits: ${environment}. It resumes when that is released.`,
636
+ command: `cupola-epic-accept ${id}`,
637
+ },
638
+ }));
639
+ }
640
+ return withRelease(result({
641
+ status: "accepting",
642
+ turn: "ai",
643
+ gate: null,
644
+ next: active
645
+ ? {
646
+ kind: "nothing",
647
+ text: `The acceptance check is running (${active.who}, session ${active.session}). If that session has ended, resume with --take-over ${active.id}.`,
648
+ command: `cupola-epic-accept ${id} --take-over ${active.id}`,
649
+ }
650
+ : {
651
+ kind: "run",
652
+ text: "Every spec is done; run the acceptance check across specs and open the release.",
653
+ command: `cupola-epic-accept ${id}`,
654
+ },
655
+ }));
656
+ }
657
+ /**
658
+ * Whether a spec's design is done (a consumer's design waits for
659
+ * its provider's design, not its merge): its tasks are approved in the
660
+ * engine's spec.json, on its branch or wherever it was merged.
661
+ */
662
+ export async function specDesignDone(root, spec) {
663
+ const path = `.kiro/specs/${spec}/spec.json`;
664
+ const own = (await workTree(root, workBranchName(spec))).tree;
665
+ // A design that ended with G2 cards is settled only once they are answered; cards from
666
+ // later phases do not reopen it.
667
+ const raw = await own.read(`${runDir(spec)}/record.json`);
668
+ if (raw !== undefined) {
669
+ const fromDesign = new Set(parseRecord(raw)
670
+ .events.filter((e) => e.phase === "design" && e.what === "card")
671
+ .flatMap((e) => (e.note ?? "").split(",").map((f) => f.trim())));
672
+ const cards = await readCards(own, spec);
673
+ if (cards.some((c) => !c.answered && fromDesign.has(c.file)))
674
+ return false;
675
+ }
676
+ const trees = [own, ...(await epicBranchTrees(root, spec))];
677
+ for (const t of trees) {
678
+ const raw = await t.read(path);
679
+ if (raw === undefined)
680
+ continue;
681
+ try {
682
+ const json = JSON.parse(raw);
683
+ if (json.approvals?.tasks?.approved === true)
684
+ return true;
685
+ }
686
+ catch {
687
+ // a spec.json being rewritten: not done
688
+ }
689
+ }
690
+ return false;
691
+ }
692
+ /** The specs whose design a spec of `epic` in `component` still waits for (its `after`). */
693
+ export async function waitingFor(rootOf,
694
+ /** The hub's paths: the epic is read from the hub's tree. */
695
+ paths, tree, epic, component) {
696
+ const raw = await tree.read(epicPath(paths, epic));
697
+ if (raw === undefined)
698
+ return [];
699
+ const front = EpicFront.safeParse(parseEpic(raw).front);
700
+ if (!front.success)
701
+ return [];
702
+ const after = front.data.specs.find((s) => s.component === component)?.after ?? [];
703
+ const waits = [];
704
+ for (const dep of after) {
705
+ const spec = specName(epic, dep);
706
+ if (!(await specDesignDone(rootOf(dep), spec)))
707
+ waits.push(spec);
708
+ }
709
+ return waits;
710
+ }
711
+ /**
712
+ * Each spec of an epic with two or more specs, then the fix specs its
713
+ * acceptance check added, with its status and whether the epic's run can
714
+ * start it now.
715
+ */
716
+ async function specsOfEpic(io, root, config, id, specs) {
717
+ const each = [];
718
+ const named = specNamesOf(id, specs);
719
+ const names = named.map((s) => s.name);
720
+ const fixes = await fixSpecsOf(root, config, id, names);
721
+ const all = [...names, ...fixes];
722
+ // Each spec's status needs calls to its repository's origin and code host: the repositories
723
+ // are asked at once, and within one repository one spec after another (its refs are shared).
724
+ const repoOf = new Map(resolveComponents(config).map((c) => [c.name, c.repo.toLowerCase()]));
725
+ const componentOf = (spec, i) => named[i]?.component ?? spec.slice(id.length + 1).replace(/-fix-\d+$/, "");
726
+ const lanes = new Map();
727
+ const statuses = all.map((spec, i) => {
728
+ const lane = repoOf.get(componentOf(spec, i)) ?? "";
729
+ const run = (lanes.get(lane) ?? Promise.resolve()).then(() => workStatus(io, root, config, spec));
730
+ lanes.set(lane, run.catch(() => undefined));
731
+ return run.then((of) => ({ of }), (error) => ({ error }));
732
+ });
733
+ for (const [i, spec] of all.entries()) {
734
+ try {
735
+ const got = await statuses[i];
736
+ if (!got)
737
+ throw new Error(`no status for ${spec}`);
738
+ if ("error" in got)
739
+ throw got.error;
740
+ const of = got.of;
741
+ const active = of.run?.active
742
+ ? { id: of.run.active.id, session: of.run.active.session }
743
+ : null;
744
+ each.push({
745
+ id: spec,
746
+ status: of.status,
747
+ gate: of.gate,
748
+ active,
749
+ movable: of.status === "ai-working" && active === null,
750
+ });
751
+ }
752
+ catch (error) {
753
+ if (!(error instanceof MissingWorkError))
754
+ throw error;
755
+ const component = named[i]?.component ?? "";
756
+ // Not created: a dropped one never is; a follow-up waits for the earlier spec of its
757
+ // component.
758
+ const dropped = await droppedBecause(io, root, id, component);
759
+ // Nor is one a revision under agreement is about to change.
760
+ const pending = dropped ? undefined : await pendingPlan(io, root, id, component);
761
+ const earlier = named
762
+ .slice(0, i)
763
+ .filter((s) => s.component === component)
764
+ .at(-1);
765
+ const before = earlier ? each.find((e) => e.id === earlier.name) : undefined;
766
+ const ready = !before || before.status === "done" || before.status === "dropped";
767
+ each.push({
768
+ id: spec,
769
+ status: dropped ? "dropped" : "not-created",
770
+ gate: null,
771
+ active: null,
772
+ movable: !dropped && !pending && ready,
773
+ });
774
+ }
775
+ }
776
+ return each;
777
+ }
778
+ /**
779
+ * The status of an epic: awaiting agreement while its `epic`
780
+ * change is open; once merged, an epic with one spec takes its spec's
781
+ * statuses, and the run that creates the spec is `cupola-epic-run`.
782
+ */
783
+ async function epicStatus(io, root, config, tree, id) {
784
+ const path = epicPath(config.paths, id);
785
+ const base = await originDefaultBranch(root);
786
+ let agreed;
787
+ if (base) {
788
+ try {
789
+ await git(root, [
790
+ "fetch",
791
+ "--quiet",
792
+ "origin",
793
+ `+refs/heads/${base}:refs/remotes/origin/${base}`,
794
+ ]);
795
+ agreed = await gitTree(root, `refs/remotes/origin/${base}`).read(path);
796
+ }
797
+ catch {
798
+ agreed = undefined;
799
+ }
800
+ }
801
+ const draft = agreed ?? (await tree.read(path)) ?? (await gitTree(root, "HEAD").read(path));
802
+ if (draft === undefined)
803
+ return undefined;
804
+ const front = EpicFront.safeParse(parseEpic(draft).front);
805
+ if (!front.success)
806
+ throw new Error(`${path}: its front matter is not an epic's (cupola check says why)`);
807
+ const specs = front.data.specs;
808
+ const procedures = front.data.procedures.map((r) => r.runbook);
809
+ // After G1, the instruction that moves the epic: its specs' run, or its procedures.
810
+ const start = specs.length > 0 ? `cupola-epic-run ${id}` : `cupola-operate ${id}`;
811
+ const work = {
812
+ kind: "epic",
813
+ id,
814
+ component: specs.length === 1 ? (specs[0]?.component ?? "") : specs.map((s) => s.component).join(", "),
815
+ };
816
+ const change = (await (io.host ?? github)(root).findChange(workBranchName(id))) ?? null;
817
+ const result = (r) => ({
818
+ work,
819
+ change,
820
+ cards: [],
821
+ run: null,
822
+ ...r,
823
+ });
824
+ // An open epic change — the first one, or a revision of an agreed epic — is G1.
825
+ if (change?.state === "open") {
826
+ if (agreed === undefined) {
827
+ return result({
828
+ status: "awaiting-agreement",
829
+ turn: "human",
830
+ gate: "G1",
831
+ next: {
832
+ kind: "gate",
833
+ text: `Read the epic and merge its change to agree (${change.url}); to change the draft, run cupola-epic-create on it again.`,
834
+ command: start,
835
+ },
836
+ });
837
+ }
838
+ // A revision of a running epic: G1 again, while the specs it leaves alone go on.
839
+ const running = specs.length >= 2 ? await specsOfEpic(io, root, config, id, specs) : undefined;
840
+ return {
841
+ ...result({
842
+ status: "awaiting-agreement",
843
+ turn: "human",
844
+ gate: "G1",
845
+ next: {
846
+ kind: "gate",
847
+ text: `Read the revision and merge its change to agree (${change.url}); to change it, run cupola-epic-revise on it again. Specs it leaves alone go on with the command.`,
848
+ command: start,
849
+ },
850
+ }),
851
+ ...(running ? { specs: running } : {}),
852
+ };
853
+ }
854
+ // A merged change is agreement even when origin's default branch could not be read.
855
+ if (agreed === undefined && change?.state !== "merged") {
856
+ if (change?.state === "closed") {
857
+ return result({
858
+ status: "aborted",
859
+ turn: "none",
860
+ gate: null,
861
+ next: { kind: "nothing", text: "Aborted." },
862
+ });
863
+ }
864
+ // Written on its branch, but the dialogue has not opened its change yet.
865
+ return result({
866
+ status: "draft",
867
+ turn: "human",
868
+ gate: null,
869
+ next: {
870
+ kind: "run",
871
+ text: "The epic is a draft whose change is not open yet; finish the dialogue.",
872
+ command: `cupola-epic-create ${id}`,
873
+ },
874
+ });
875
+ }
876
+ // Aborted after G1: recorded on its cases, where its status comes from.
877
+ const tracker = await trackerOf(io);
878
+ const caseTexts = [];
879
+ for (const c of front.data.cases) {
880
+ const shown = await tracker.show(c);
881
+ if (shown)
882
+ caseTexts.push(shown.text);
883
+ if (shown && recordsAbort(shown.text, id)) {
884
+ return result({
885
+ status: "aborted",
886
+ turn: "none",
887
+ gate: null,
888
+ next: { kind: "nothing", text: "Aborted." },
889
+ });
890
+ }
891
+ }
892
+ // Released, or nothing to release: its procedures run, in order.
893
+ const operate = (released) => {
894
+ const now = currentProcedure(procedures, procedureRecords(caseTexts, id));
895
+ if (!now)
896
+ return released;
897
+ const at = now.stopped
898
+ ? `It stopped at ${now.runbook} ${now.stopped}: resume it, or change the plan with cupola-epic-revise ${id}, or stop with cupola-abort ${id}.`
899
+ : now.done.length > 0
900
+ ? `Carry on with ${now.runbook} after ${now.done.at(-1)}.`
901
+ : `Carry out ${now.runbook}.`;
902
+ return {
903
+ ...released,
904
+ status: "operating",
905
+ turn: "human",
906
+ gate: null,
907
+ procedure: now,
908
+ next: { kind: "run", text: at, command: `cupola-operate ${id}` },
909
+ };
910
+ };
911
+ if (specs.length === 0) {
912
+ return operate(result({
913
+ status: "done",
914
+ turn: "none",
915
+ gate: null,
916
+ next: { kind: "nothing", text: "Done." },
917
+ }));
918
+ }
919
+ // Agreed. An epic with one spec takes its spec's statuses, once the spec exists.
920
+ const only = specs.length === 1 ? specs[0] : undefined;
921
+ if (only) {
922
+ const spec = specName(id, only.component);
923
+ // Released: the spec's change is merged, and its branch may be gone.
924
+ // The spec's change is in its component's repository.
925
+ const ws = await workspace({ ...io, cwd: root });
926
+ const slug = ws.repoOf(only.component);
927
+ const specRoot = slug === ws.here.slug ? root : ws.checkout(slug).main;
928
+ const specChange = await (io.host ?? github)(specRoot).findChange(workBranchName(spec));
929
+ // Outside the hub, its system catalog entries came in a `system` change merged with it.
930
+ const system = specChange?.state === "merged" && slug !== ws.hub.slug
931
+ ? await (io.host ?? github)(root).findChange(workBranchName(`${id}-system`))
932
+ : undefined;
933
+ if (system?.state === "open") {
934
+ return {
935
+ work,
936
+ spec,
937
+ change: system,
938
+ cards: [],
939
+ run: null,
940
+ status: "awaiting-acceptance",
941
+ turn: "human",
942
+ gate: "G3",
943
+ next: {
944
+ kind: "gate",
945
+ text: `${spec} is merged; merge its system change too (${system.url}), then run the command.`,
946
+ command: `cupola-complete ${spec}`,
947
+ },
948
+ };
949
+ }
950
+ const code = ws.config.documents === "hub"
951
+ ? await codeLeft(io, ws, workBranchName(spec), only.component, specChange ?? undefined)
952
+ : undefined;
953
+ if (code) {
954
+ return {
955
+ work,
956
+ spec,
957
+ change: code.change,
958
+ cards: [],
959
+ run: null,
960
+ status: "awaiting-acceptance",
961
+ turn: "human",
962
+ gate: "G3",
963
+ next: {
964
+ kind: "gate",
965
+ text: `${spec} ${code.text}`,
966
+ command: `cupola-complete ${spec}`,
967
+ },
968
+ };
969
+ }
970
+ if (specChange?.state === "merged") {
971
+ // Merging it released the epic; `cupola-complete <spec>` tidies up and moves the cases on.
972
+ if (await untidy(ws.config.documents === "hub" ? root : specRoot, workBranchName(spec))) {
973
+ const complete = `cupola-complete ${spec}`;
974
+ return {
975
+ work,
976
+ spec,
977
+ change: specChange,
978
+ cards: [],
979
+ run: null,
980
+ status: "done",
981
+ turn: "human",
982
+ gate: null,
983
+ next: {
984
+ kind: "run",
985
+ text: `Merged: \`${complete}\` tidies up and moves on.`,
986
+ command: complete,
987
+ },
988
+ };
989
+ }
990
+ return operate({
991
+ work,
992
+ spec,
993
+ change: specChange,
994
+ cards: [],
995
+ run: null,
996
+ status: "done",
997
+ turn: "none",
998
+ gate: null,
999
+ next: { kind: "nothing", text: "Done." },
1000
+ });
1001
+ }
1002
+ try {
1003
+ const of = await workStatus(io, root, config, spec);
1004
+ return { ...of, work, spec };
1005
+ }
1006
+ catch (error) {
1007
+ if (!(error instanceof MissingWorkError))
1008
+ throw error;
1009
+ }
1010
+ }
1011
+ if (!only) {
1012
+ // Two or more specs: in progress, per spec.
1013
+ const each = await specsOfEpic(io, root, config, id, specs);
1014
+ const movable = each.filter((s) => s.movable);
1015
+ const gates = each.filter((s) => s.gate).map((s) => `${s.id} at ${s.gate}`);
1016
+ const running = each.filter((s) => s.active);
1017
+ const finished = each.every((s) => s.status === "done" || s.status === "dropped");
1018
+ if (finished) {
1019
+ const accepted = await acceptance(io, root, id, specs, result);
1020
+ return {
1021
+ ...(accepted.status === "done" ? operate(accepted) : accepted),
1022
+ specs: each,
1023
+ };
1024
+ }
1025
+ let next;
1026
+ let turn;
1027
+ if (movable.length > 0) {
1028
+ turn = "ai";
1029
+ next = {
1030
+ kind: "run",
1031
+ text: `Run ${movable.map((s) => s.id).join(", ")}${gates.length > 0 ? `; waiting for you: ${gates.join(", ")}` : ""}.`,
1032
+ command: `cupola-epic-run ${id}`,
1033
+ };
1034
+ }
1035
+ else if (gates.length > 0) {
1036
+ turn = "human";
1037
+ next = {
1038
+ kind: "gate",
1039
+ text: `Waiting for you: ${gates.join(", ")}; see each spec's status.`,
1040
+ };
1041
+ }
1042
+ else if (running.length > 0) {
1043
+ turn = "ai";
1044
+ next = {
1045
+ kind: "nothing",
1046
+ text: `Running: ${running.map((s) => `${s.id} (session ${s.active?.session})`).join(", ")}. If a session has ended, resume its spec with \`cupola-spec-run <spec> --take-over <marker>\` (\`cupola status <spec>\` gives it).`,
1047
+ };
1048
+ }
1049
+ else if (each.some((s) => s.status === "waiting")) {
1050
+ turn = "ai";
1051
+ next = {
1052
+ kind: "nothing",
1053
+ text: "Its specs wait: for other specs' designs, or for a shared e2e environment; they move once that is done or released.",
1054
+ command: `cupola-epic-run ${id}`,
1055
+ };
1056
+ }
1057
+ else {
1058
+ turn = "none";
1059
+ next = {
1060
+ kind: "nothing",
1061
+ text: `Nothing can move: ${each.map((s) => `${s.id} (${s.status})`).join(", ")}.`,
1062
+ };
1063
+ }
1064
+ return { ...result({ status: "in-progress", turn, gate: null, next }), specs: each };
1065
+ }
1066
+ return result({
1067
+ status: specs.length === 1 ? "ai-working" : "in-progress",
1068
+ turn: "ai",
1069
+ gate: null,
1070
+ next: {
1071
+ kind: "run",
1072
+ text: only ? "Agreed; create its spec and run it." : "Agreed; run its specs.",
1073
+ command: `cupola-epic-run ${id}`,
1074
+ },
1075
+ });
1076
+ }
1077
+ const LABELS = {
1078
+ accepting: "accepting",
1079
+ "awaiting-release": "awaiting release (G4)",
1080
+ waiting: "waiting",
1081
+ open: "open",
1082
+ "awaiting-resolution": "awaiting resolution (G5)",
1083
+ resolved: "resolved",
1084
+ "awaiting-agreement": "awaiting agreement (G1)",
1085
+ "in-progress": "in progress",
1086
+ draft: "draft",
1087
+ aborted: "aborted",
1088
+ "ai-working": "AI working",
1089
+ "awaiting-decision": "awaiting decision (G2)",
1090
+ "awaiting-acceptance": "awaiting acceptance (G3)",
1091
+ operating: "operating",
1092
+ done: "done",
1093
+ dropped: "dropped",
1094
+ };
1095
+ export function describe(r) {
1096
+ const whose = r.turn === "human"
1097
+ ? r.gate
1098
+ ? `your turn, at ${r.gate}`
1099
+ : "your turn"
1100
+ : r.turn === "ai"
1101
+ ? "the AI's turn"
1102
+ : "nobody's turn";
1103
+ const lines = [
1104
+ `${r.work.kind} ${r.work.id}${r.work.component ? ` (${r.work.component})` : ""}: ${LABELS[r.status]} — ${whose}`,
1105
+ ];
1106
+ if (r.spec)
1107
+ lines.push(` spec: ${r.spec}`);
1108
+ for (const e of r.epics ?? [])
1109
+ lines.push(` epic: ${e.id} (${LABELS[e.status]}${e.judged ? ", judged not enough at G5" : ""})`);
1110
+ if (r.procedure)
1111
+ lines.push(` procedure: ${r.procedure.runbook}${r.procedure.stopped ? ` (stopped at ${r.procedure.stopped})` : r.procedure.done.length > 0 ? ` (done: ${r.procedure.done.join(", ")})` : ""}`);
1112
+ if (r.change)
1113
+ lines.push(` change: ${r.change.url}${r.change.draft ? " (draft)" : ""}`);
1114
+ if (r.run?.phase)
1115
+ lines.push(` phase: ${r.run.phase}${r.run.active ? ` (running, ${r.run.active.who})` : ""}`);
1116
+ lines.push(` next: ${r.next.text}${r.next.command ? ` → ${r.next.command}` : ""}`);
1117
+ return lines.join("\n");
1118
+ }
1119
+ /** The hub's agreed epics: origin's default branch, or this commit when it cannot be read. */
1120
+ async function hubAgreed(hub) {
1121
+ const base = await originDefaultBranch(hub);
1122
+ return base ? gitTree(hub, `refs/remotes/origin/${base}`) : gitTree(hub, "HEAD");
1123
+ }
1124
+ /**
1125
+ * How much feedback people left on a change with no run going, that Cupola
1126
+ * has not answered: the human sending it back on the change itself. Read only
1127
+ * then, so that a run in progress costs no request.
1128
+ */
1129
+ export async function peopleFeedback(host, change, record, config) {
1130
+ // At the gate: ready, with no run going. A draft with no record is a run finishing.
1131
+ if (change?.state !== "open" || change.draft || record !== undefined)
1132
+ return 0;
1133
+ const { reviewer } = config.review;
1134
+ const ok = (a) => trusted(a, reviewer, config.trust);
1135
+ try {
1136
+ const { feedback } = await host.feedback(change.number, ok);
1137
+ return fromPeople(feedback, reviewer, config.trust).length;
1138
+ }
1139
+ catch {
1140
+ // Feedback that cannot be read (too much of it) sends nothing back; the dialogue still can.
1141
+ return 0;
1142
+ }
1143
+ }
1144
+ /**
1145
+ * Whether a merged work's own worktree is still here: `cupola-complete` removes
1146
+ * it last, so one left means it has not run. The main checkout is not the work's,
1147
+ * even with the branch checked out there.
1148
+ */
1149
+ async function untidy(cwd, branch) {
1150
+ try {
1151
+ await git(cwd, ["worktree", "prune"]);
1152
+ const blocks = (await git(cwd, ["worktree", "list", "--porcelain"])).split("\n\n").slice(1);
1153
+ return blocks.some((b) => b.split("\n").includes(`branch refs/heads/${branch}`));
1154
+ }
1155
+ catch {
1156
+ return false;
1157
+ }
1158
+ }