@kyuki3rain/cupola 0.0.0-stage → 0.2.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 (125) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/LICENSE +202 -0
  3. package/README.md +41 -2
  4. package/dist/adr.js +106 -0
  5. package/dist/branch-store.js +73 -0
  6. package/dist/catalog.js +137 -0
  7. package/dist/check.js +192 -0
  8. package/dist/cli.js +8 -0
  9. package/dist/code.js +216 -0
  10. package/dist/commands/change.js +728 -0
  11. package/dist/commands/epic.js +311 -0
  12. package/dist/commands/execution.js +482 -0
  13. package/dist/commands/install.js +109 -0
  14. package/dist/commands/locks.js +243 -0
  15. package/dist/commands/reaction.js +185 -0
  16. package/dist/commands/revision.js +139 -0
  17. package/dist/commands/run.js +1021 -0
  18. package/dist/commands/setup.js +414 -0
  19. package/dist/commands/spec.js +80 -0
  20. package/dist/commands/status.js +1457 -0
  21. package/dist/commands/trace.js +474 -0
  22. package/dist/commands/wait.js +105 -0
  23. package/dist/commands/work.js +126 -0
  24. package/dist/commands/workspace.js +137 -0
  25. package/dist/commands/worktree.js +422 -0
  26. package/dist/config.js +353 -0
  27. package/dist/day.js +29 -0
  28. package/dist/e2e-project.js +62 -0
  29. package/dist/e2e.js +207 -0
  30. package/dist/engine/cc-sdd.js +164 -0
  31. package/dist/epic.js +379 -0
  32. package/dist/execution.js +272 -0
  33. package/dist/feedback.js +20 -0
  34. package/dist/frontmatter.js +20 -0
  35. package/dist/git.js +365 -0
  36. package/dist/host/git.js +224 -0
  37. package/dist/host/github.js +387 -0
  38. package/dist/host/host.js +3 -0
  39. package/dist/host/index.js +63 -0
  40. package/dist/install.js +182 -0
  41. package/dist/io.js +46 -0
  42. package/dist/main.js +866 -0
  43. package/dist/method/v1.js +56 -0
  44. package/dist/reaction.js +110 -0
  45. package/dist/record.js +507 -0
  46. package/dist/release.js +84 -0
  47. package/dist/repo.js +13 -0
  48. package/dist/runbook.js +132 -0
  49. package/dist/safe-write.js +80 -0
  50. package/dist/spec.js +171 -0
  51. package/dist/status.js +321 -0
  52. package/dist/templates.js +50 -0
  53. package/dist/trace.js +275 -0
  54. package/dist/tracker/files.js +99 -0
  55. package/dist/tracker/github-issues.js +217 -0
  56. package/dist/tracker/index.js +34 -0
  57. package/dist/tracker/tracker.js +69 -0
  58. package/dist/tree.js +59 -0
  59. package/dist/trust.js +13 -0
  60. package/dist/version.js +5 -0
  61. package/dist/work.js +170 -0
  62. package/dist/workspace.js +324 -0
  63. package/npm-shrinkwrap.json +2014 -0
  64. package/package.json +41 -4
  65. package/skills/cupola-abort/SKILL.md +51 -0
  66. package/skills/cupola-adr/SKILL.md +54 -0
  67. package/skills/cupola-ask/SKILL.md +42 -0
  68. package/skills/cupola-catalog/SKILL.md +41 -0
  69. package/skills/cupola-catalog-draft/SKILL.md +116 -0
  70. package/skills/cupola-complete/SKILL.md +107 -0
  71. package/skills/cupola-decide/SKILL.md +99 -0
  72. package/skills/cupola-doc/SKILL.md +52 -0
  73. package/skills/cupola-e2e-setup/SKILL.md +78 -0
  74. package/skills/cupola-e2e-test/SKILL.md +115 -0
  75. package/skills/cupola-epic-accept/SKILL.md +166 -0
  76. package/skills/cupola-epic-create/SKILL.md +160 -0
  77. package/skills/cupola-epic-revise/SKILL.md +92 -0
  78. package/skills/cupola-epic-run/SKILL.md +166 -0
  79. package/skills/cupola-fix/SKILL.md +117 -0
  80. package/skills/cupola-init/SKILL.md +143 -0
  81. package/skills/cupola-intake/SKILL.md +95 -0
  82. package/skills/cupola-operate/SKILL.md +81 -0
  83. package/skills/cupola-resolve/SKILL.md +93 -0
  84. package/skills/cupola-respond/SKILL.md +73 -0
  85. package/skills/cupola-review/SKILL.md +131 -0
  86. package/skills/cupola-spec-design/SKILL.md +169 -0
  87. package/skills/cupola-spec-impl/SKILL.md +137 -0
  88. package/skills/cupola-spec-run/SKILL.md +137 -0
  89. package/skills/cupola-steering/SKILL.md +53 -0
  90. package/skills/cupola-try/SKILL.md +38 -0
  91. package/templates/install/.kiro/steering/e2e.md +48 -0
  92. package/templates/install/.kiro/steering/operations.md +109 -0
  93. package/templates/install/.kiro/steering/principles.md +25 -0
  94. package/templates/install/CLAUDE.md +19 -0
  95. package/templates/install/adr/TEMPLATE.md +38 -0
  96. package/templates/install/cc-sdd/patches.json +31 -0
  97. package/templates/method-1/behavior-area.md +43 -0
  98. package/templates/method-1/behavior-index.md +16 -0
  99. package/templates/method-1/card.md +49 -0
  100. package/templates/method-1/case-draft.md +25 -0
  101. package/templates/method-1/case.md +38 -0
  102. package/templates/method-1/catalog-spec.md +33 -0
  103. package/templates/method-1/changes/adr.md +4 -0
  104. package/templates/method-1/changes/catalog.md +29 -0
  105. package/templates/method-1/changes/doc.md +5 -0
  106. package/templates/method-1/changes/e2e.md +7 -0
  107. package/templates/method-1/changes/epic.md +30 -0
  108. package/templates/method-1/changes/fix.md +21 -0
  109. package/templates/method-1/changes/release.md +23 -0
  110. package/templates/method-1/changes/spec.md +55 -0
  111. package/templates/method-1/changes/system.md +13 -0
  112. package/templates/method-1/cupola-issue-draft.md +17 -0
  113. package/templates/method-1/epic.md +147 -0
  114. package/templates/method-1/execution.md +55 -0
  115. package/templates/method-1/fix-spec.md +34 -0
  116. package/templates/method-1/fix.md +39 -0
  117. package/templates/method-1/lock.json +13 -0
  118. package/templates/method-1/no-go.md +28 -0
  119. package/templates/method-1/phase-outcome.json +29 -0
  120. package/templates/method-1/reaction.md +17 -0
  121. package/templates/method-1/record.json +63 -0
  122. package/templates/method-1/report.md +27 -0
  123. package/templates/method-1/runbook.md +45 -0
  124. package/templates/method-1/runner-result.json +6 -0
  125. package/templates/methods.json +13 -0
@@ -0,0 +1,728 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { codeChanges, epicBaseOf, mountsIn, workComponents } from "../code.js";
4
+ import { epicPath, loadConfig } from "../config.js";
5
+ import { byReviewer, trusted } from "../feedback.js";
6
+ import { git, originDefaultBranch, workBranch } from "../git.js";
7
+ import { MergedOnHost } from "../host/host.js";
8
+ import { codeHost } from "../host/index.js";
9
+ import { releaseBody, releaseChanges, releasesOf } from "../release.js";
10
+ import { repoRoot } from "../repo.js";
11
+ import { epicBranchName, epicFront, readBlock } from "../spec.js";
12
+ import { fsTree } from "../tree.js";
13
+ import { findSpecDocument, runsOn, workBranchName } from "../work.js";
14
+ import { workspace } from "../workspace.js";
15
+ import { snapshotEpic } from "./revision.js";
16
+ /** A change description must be finished: no template placeholders left. */
17
+ export async function readBody(cwd, file) {
18
+ const body = await readFile(resolve(cwd, file), "utf8");
19
+ if (body.includes("{{"))
20
+ throw new Error(`${file} still has template placeholders ({{…}})`);
21
+ return body;
22
+ }
23
+ /**
24
+ * `cupola change open <work> --title <t> --body-file <f> [--base <b>]`: pushes
25
+ * the work's branch and opens its change as a draft, so that it is visible at
26
+ * once. Opening again returns the open change.
27
+ */
28
+ export async function changeOpen(io, id, opts) {
29
+ const root = await repoRoot(io.cwd);
30
+ const branch = await workBranch(root);
31
+ if (!runsOn(branch, id)) {
32
+ throw new Error(`${id} is on ${workBranchName(id)}, but this checkout is on ${branch}`);
33
+ }
34
+ const host = (io.host ?? codeHost)(root);
35
+ const existing = await host.findChange(branch);
36
+ const onEpic = branch === epicBranchName(id);
37
+ // The workspace is read only where it matters: an epic's release, or code kept apart.
38
+ const ws0 = onEpic || (await loadConfig(root)).documents === "hub" ? await workspace(io) : undefined;
39
+ // An epic's release across repositories goes on below: some of its changes may be missing.
40
+ const fanOut = onEpic && (ws0?.repos.length ?? 1) > 1;
41
+ // With every document in the hub, the code is a change of its own in its repository.
42
+ const codes = onEpic || !ws0 ? [] : await codeOf(io, ws0, root, id, branch);
43
+ if (existing?.state === "open" && !fanOut && codes.every((c) => c.change?.state === "open")) {
44
+ io.out(opts.json ? JSON.stringify(withCode(existing, codes)) : existing.url);
45
+ return 0;
46
+ }
47
+ if (existing?.state === "open" && !fanOut && ws0) {
48
+ const opened = await openCodeChanges(io, ws0, root, id, branch, {
49
+ title: opts.title ?? `Code: ${id}`,
50
+ hub: existing,
51
+ ready: opts.ready === true,
52
+ base: opts.base,
53
+ });
54
+ io.out(opts.json ? JSON.stringify(withCode(existing, opened)) : existing.url);
55
+ return 0;
56
+ }
57
+ if (!opts.title || !opts.bodyFile)
58
+ throw new Error("give --title and --body-file");
59
+ // Outside the hub, the spec's epic (which says its base) is the hub's: copied in first.
60
+ await snapshotOwnEpic(io, root, id);
61
+ const body = await readBody(io.cwd, opts.bodyFile);
62
+ const base = opts.base ?? (await epicBaseOf(root, id)) ?? (await originDefaultBranch(root));
63
+ if (!base)
64
+ throw new Error("cannot tell origin's default branch; name it with --base <branch>");
65
+ try {
66
+ await git(root, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]);
67
+ }
68
+ catch (error) {
69
+ const lines = (error.stderr ?? "").split("\n").map((l) => l.trim());
70
+ const reason = lines.filter((l) => /^(!|error:|fatal:)/.test(l)).join("; ") || "unknown reason";
71
+ throw new Error(`could not push ${branch} (${reason}); pull origin ${branch} first if it moved on`);
72
+ }
73
+ // An epic's release across repositories: one change per repository, in merge order.
74
+ if (onEpic && ws0) {
75
+ const ws = ws0;
76
+ if (ws.repos.length > 1) {
77
+ const path = epicPath(ws.config.paths, id);
78
+ const raw = await fsTree(root).read(path);
79
+ if (raw === undefined)
80
+ throw new Error(`${path} is not on ${branch}`);
81
+ const releases = releasesOf(ws, epicFront(path, raw).front.specs);
82
+ const opened = [];
83
+ for (const r of releases) {
84
+ const there = ws.host(io, r.repo.slug);
85
+ const found = await there.findChange(branch);
86
+ const repoBase = r.repo.isHub ? base : await originDefaultBranch(r.repo.main);
87
+ if (!repoBase)
88
+ throw new Error(`cannot tell origin's default branch of ${r.repo.slug}`);
89
+ // Open or merged already: kept (a release merged before a retry is not opened again).
90
+ const change = found && found.state !== "closed"
91
+ ? found
92
+ : await there.openChange({
93
+ branch,
94
+ base: repoBase,
95
+ title: opts.title,
96
+ body: releaseBody(body, r, releases),
97
+ draft: !opts.ready,
98
+ });
99
+ opened.push({ repo: r.repo.slug, order: r.order, of: r.of, change });
100
+ }
101
+ const hubChange = opened.find((o) => o.repo === ws.hub.slug)?.change ?? opened[0]?.change;
102
+ io.out(opts.json
103
+ ? JSON.stringify({ ...hubChange, releases: opened })
104
+ : opened.map((o) => `${o.order}/${o.of} ${o.repo}: ${o.change.url}`).join("\n"));
105
+ return 0;
106
+ }
107
+ }
108
+ const open = (draft) => host.openChange({ branch, base, title: opts.title ?? "", body, draft });
109
+ let change;
110
+ if (existing?.state === "open")
111
+ change = existing;
112
+ else {
113
+ try {
114
+ change = await open(!opts.ready);
115
+ }
116
+ catch (error) {
117
+ // An epic's change is a draft only while cards are open, at best: where the host
118
+ // cannot open drafts, it opens ready.
119
+ if (opts.ready || !(await isEpic(root, id)))
120
+ throw error;
121
+ change = await open(false);
122
+ }
123
+ }
124
+ const opened = ws0
125
+ ? await openCodeChanges(io, ws0, root, id, branch, {
126
+ title: opts.title,
127
+ hub: change,
128
+ ready: opts.ready === true,
129
+ base: opts.base,
130
+ })
131
+ : [];
132
+ io.out(opts.json ? JSON.stringify(withCode(change, opened)) : change.url);
133
+ return 0;
134
+ }
135
+ /** A work item's code changes, one per code repository its worktree mounts. */
136
+ async function codeOf(io, ws, root, id, branch) {
137
+ if (ws.config.documents !== "hub")
138
+ return [];
139
+ const { components } = await workComponents(ws, root, id, branch);
140
+ return codeChanges(io, ws, branch, components);
141
+ }
142
+ /** The code changes of the work this checkout runs; the workspace is read only when they can exist. */
143
+ async function codeOfHere(io, root, id, branch) {
144
+ if ((await loadConfig(root)).documents !== "hub")
145
+ return [];
146
+ return codeOf(io, await workspace(io), root, id, branch);
147
+ }
148
+ /** A hub change with its code changes, as `change open` and `change show` print it. */
149
+ function withCode(change, codes) {
150
+ return codes.length === 0
151
+ ? change
152
+ : { ...change, code: codes.map((c) => ({ repo: c.slug, change: c.change ?? null })) };
153
+ }
154
+ /** The description of a code change: what it is, where its documents are, and the hub's description. */
155
+ export function codeBody(id, hubUrl, described) {
156
+ return [
157
+ `<!-- cupola:change ${JSON.stringify({ kind: "code", work: id, method: 1 })} -->`,
158
+ `The code and tests of \`${id}\`. Its documents and record are in ${hubUrl}: the two are merged together, this one first.`,
159
+ // The hub's description without its own marker: a change carries one marker, its own.
160
+ ...(described
161
+ ? ["", described.replace(/^\s*<!--\s*cupola:change\s+\{.*?\}\s*-->\s*\n?/, "").trim()]
162
+ : []),
163
+ "",
164
+ ].join("\n");
165
+ }
166
+ /**
167
+ * Pushes the branch of each code repository the work's worktree mounts and
168
+ * opens its change, against the same base as the hub's change: the epic
169
+ * branch, or its own default branch. A branch with nothing on it yet is not a
170
+ * change: it is opened when it has commits (`change open` again, or the run's
171
+ * finish). Returns every code change there is.
172
+ */
173
+ export async function openCodeChanges(io, ws, root, id, branch, opts) {
174
+ if (ws.config.documents !== "hub")
175
+ return [];
176
+ const { components, base: epicBase } = await workComponents(ws, root, id, branch);
177
+ const out = [];
178
+ for (const m of mountsIn(ws, root, components)) {
179
+ const there = ws.host(io, m.slug);
180
+ const found = await there.findChange(branch);
181
+ const base = opts.base ?? epicBase ?? (await originDefaultBranch(m.main));
182
+ if (!base)
183
+ throw new Error(`cannot tell origin's default branch of ${m.slug}`);
184
+ await git(m.path, [
185
+ "fetch",
186
+ "--quiet",
187
+ "origin",
188
+ `+refs/heads/${base}:refs/remotes/origin/${base}`,
189
+ ]);
190
+ // Merged already: a squash merge leaves HEAD looking ahead, and nothing is pushed again.
191
+ if (found?.state === "merged") {
192
+ out.push({ slug: m.slug, host: there, change: found });
193
+ continue;
194
+ }
195
+ const ahead = await git(m.path, ["rev-list", "--count", `refs/remotes/origin/${base}..HEAD`]);
196
+ // What is committed there is pushed, so that its change holds it.
197
+ if (ahead !== "0") {
198
+ try {
199
+ await git(m.path, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]);
200
+ }
201
+ catch (error) {
202
+ const lines = (error.stderr ?? "")
203
+ .split("\n")
204
+ .map((l) => l.trim());
205
+ const reason = lines.filter((l) => /^(!|error:|fatal:)/.test(l)).join("; ") || "unknown reason";
206
+ throw new Error(`could not push ${branch} of ${m.slug} (${reason}); pull origin ${branch} there first if it moved on`);
207
+ }
208
+ }
209
+ if (found && found.state !== "closed") {
210
+ out.push({ slug: m.slug, host: there, change: found });
211
+ continue;
212
+ }
213
+ if (ahead === "0") {
214
+ out.push({ slug: m.slug, host: there, change: undefined });
215
+ continue;
216
+ }
217
+ const change = await there.openChange({
218
+ branch,
219
+ base,
220
+ title: opts.title,
221
+ body: codeBody(id, opts.hub.url),
222
+ draft: !opts.ready,
223
+ });
224
+ out.push({ slug: m.slug, host: there, change });
225
+ }
226
+ return out;
227
+ }
228
+ /**
229
+ * The branch whose change a command means: on an epic's own branch, the epic's
230
+ * release; anywhere else, the work's own branch.
231
+ */
232
+ async function changeBranch(root, id) {
233
+ try {
234
+ if ((await workBranch(root)) === epicBranchName(id))
235
+ return epicBranchName(id);
236
+ }
237
+ catch {
238
+ // the default branch, or detached: the work's own branch
239
+ }
240
+ return workBranchName(id);
241
+ }
242
+ /**
243
+ * `cupola change show <work>`: the work item's change, or null. For a person,
244
+ * it reads as the change: its title, state, where it is, its code changes, and
245
+ * its description, which on a host without pages is nowhere else to read.
246
+ * With `--release`, the epic's release changes, whichever branch is checked out.
247
+ */
248
+ export async function changeShow(io, id, opts) {
249
+ const root = await repoRoot(io.cwd);
250
+ if (opts.release)
251
+ return releaseShow(io, root, id, opts);
252
+ const host = (io.host ?? codeHost)(root);
253
+ const branch = await changeBranch(root, id);
254
+ const change = await host.findChange(branch);
255
+ const codes = change ? await codeOfHere(io, root, id, branch) : [];
256
+ // The description too: after the merge it is where the run's account of the work lives.
257
+ const body = change ? await host.body(change.number) : undefined;
258
+ if (opts.json) {
259
+ io.out(JSON.stringify(change ? { ...withCode(change, codes), body } : null));
260
+ return 0;
261
+ }
262
+ if (!change) {
263
+ io.out(`${id} has no change`);
264
+ return 0;
265
+ }
266
+ io.out(readable(change, `the change of ${id}`, codes.map((c) => c.change
267
+ ? `code in ${c.slug}, ${stateOf(c.change)}: ${c.change.url}`
268
+ : `code in ${c.slug}: no change yet`), body));
269
+ return 0;
270
+ }
271
+ /** `cupola change show <epic> --release`: each release change, in merge order, with its description. */
272
+ async function releaseShow(io, root, id, opts) {
273
+ const ws = await workspace(io);
274
+ const items = ws.repos.length > 1
275
+ ? await epicReleases(io, ws, id)
276
+ : await (async () => {
277
+ const host = (io.host ?? codeHost)(root);
278
+ const change = await host.findChange(epicBranchName(id));
279
+ return change ? [{ repo: ws.here.slug, host, change }] : [];
280
+ })();
281
+ const shown = [];
282
+ for (const it of items)
283
+ shown.push({ repo: it.repo, change: it.change, body: await it.host.body(it.change.number) });
284
+ if (opts.json) {
285
+ io.out(JSON.stringify(shown.map((s) => ({ repo: s.repo, ...s.change, body: s.body }))));
286
+ return 0;
287
+ }
288
+ io.out(shown.length === 0
289
+ ? `${id} has no release change`
290
+ : shown
291
+ .map((s, i) => readable(s.change, `the release of ${id}`, [`release ${i + 1} of ${shown.length}, in ${s.repo}`], s.body))
292
+ .join("\n\n"));
293
+ return 0;
294
+ }
295
+ /** A change as a person reads it: title, state and name, more lines, then its description. */
296
+ function readable(change, untitled, more, body) {
297
+ return [
298
+ change.title || untitled,
299
+ `${stateOf(change)}: ${change.url}`,
300
+ ...more,
301
+ "",
302
+ body?.trim() || "(no description)",
303
+ ].join("\n");
304
+ }
305
+ /** An epic's release changes across the workspace's repositories, in merge order: those opened. */
306
+ async function epicReleases(io, ws, id) {
307
+ const branch = epicBranchName(id);
308
+ const path = epicPath(ws.config.paths, id);
309
+ const raw = (await git(ws.hub.main, ["show", `refs/remotes/origin/${branch}:${path}`]).catch(() => undefined)) ?? (await fsTree(ws.hub.main).read(path));
310
+ if (raw === undefined)
311
+ throw new Error(`${path} is not on ${branch}`);
312
+ const releases = await releaseChanges(io, ws, id, releasesOf(ws, epicFront(path, raw).front.specs));
313
+ return releases.flatMap((r) => r.change ? [{ repo: r.repo.slug, host: r.host, change: r.change }] : []);
314
+ }
315
+ /** A change's state as a person reads it. */
316
+ function stateOf(change) {
317
+ return change.state === "open" && change.draft ? "draft" : change.state;
318
+ }
319
+ /**
320
+ * `cupola change merge <work> [--release]`: a person merges the work's ready
321
+ * changes that are on a host without a merge of its own (a git host), each as
322
+ * one commit on its base, in the order they go in: code before the hub, a
323
+ * release in its merge order. It stops at the first change that is merged on
324
+ * its host, saying so; run again once that one is merged. No skill runs it.
325
+ */
326
+ export async function changeMerge(io, id, opts) {
327
+ const root = await repoRoot(io.cwd);
328
+ const branch = opts.release ? epicBranchName(id) : await changeBranch(root, id);
329
+ let items;
330
+ const config = await loadConfig(root);
331
+ const ws = config.documents === "hub" || branch === epicBranchName(id) ? await workspace(io) : undefined;
332
+ if (branch === epicBranchName(id) && ws && ws.repos.length > 1) {
333
+ items = await epicReleases(io, ws, id);
334
+ }
335
+ else {
336
+ const host = (io.host ?? codeHost)(root);
337
+ const change = await host.findChange(branch);
338
+ if (!change)
339
+ throw new Error(`${id} has no change`);
340
+ const codes = ws ? await codeOf(io, ws, root, id, branch) : [];
341
+ items = [
342
+ ...codes.flatMap((c) => (c.change ? [{ repo: c.slug, host: c.host, change: c.change }] : [])),
343
+ { repo: ws?.here.slug ?? "", host, change },
344
+ ];
345
+ }
346
+ const done = [];
347
+ let waiting;
348
+ for (const it of items) {
349
+ if (it.change.state === "merged")
350
+ continue;
351
+ if (it.change.state === "closed")
352
+ throw new Error(`${it.change.url} is closed`);
353
+ if (!it.host.merge) {
354
+ waiting = it.change.url;
355
+ break;
356
+ }
357
+ try {
358
+ await it.host.merge(it.change.number);
359
+ }
360
+ catch (error) {
361
+ if (error instanceof MergedOnHost) {
362
+ waiting = it.change.url;
363
+ break;
364
+ }
365
+ throw error;
366
+ }
367
+ done.push(it.change.url);
368
+ }
369
+ if (opts.json)
370
+ io.out(JSON.stringify({ merged: done, ...(waiting ? { merge_on_host: waiting } : {}) }));
371
+ else {
372
+ const lines = done.map((u) => `merged ${u}`);
373
+ if (waiting)
374
+ lines.push(`merge ${waiting} on its host, then run this again`);
375
+ io.out(lines.length > 0 ? lines.join("\n") : `every change of ${id} is merged`);
376
+ }
377
+ return 0;
378
+ }
379
+ /**
380
+ * The work's open changes: the hub's, and with every document in the hub its
381
+ * open code changes. One that is merged or closed is left out, so
382
+ * a command interrupted halfway, or a change a human merged first, still
383
+ * reaches the others. `change` is the hub's change, whatever its state.
384
+ */
385
+ export async function openChangeOf(io, id) {
386
+ const root = await repoRoot(io.cwd);
387
+ const host = (io.host ?? codeHost)(root);
388
+ const branch = await changeBranch(root, id);
389
+ const change = await host.findChange(branch);
390
+ if (!change)
391
+ throw new Error(`${id} has no open change`);
392
+ const codes = await codeOfHere(io, root, id, branch);
393
+ const all = [
394
+ ...(change.state === "open" ? [{ host, change, repo: undefined }] : []),
395
+ ...codes.flatMap((c) => c.change?.state === "open" ? [{ host: c.host, change: c.change, repo: c.slug }] : []),
396
+ ];
397
+ if (all.length === 0)
398
+ throw new Error(`${id} has no open change`);
399
+ return { root, host, change, all, codes };
400
+ }
401
+ const sleep = (io, ms) => (io.sleep ?? ((t) => new Promise((r) => setTimeout(r, t))))(ms);
402
+ const POLL_MS = 15_000;
403
+ /** How long `checks --wait` waits for CI to report at all, before taking "none" as the answer. */
404
+ const NONE_GRACE_MS = 120_000;
405
+ function seconds(value) {
406
+ if (value === undefined)
407
+ return 0;
408
+ const n = Number(value);
409
+ if (!Number.isFinite(n) || n < 0)
410
+ throw new Error(`--wait takes seconds, not ${value}`);
411
+ return n;
412
+ }
413
+ /** Whether the work is an epic: its document is in this checkout. */
414
+ async function isEpic(root, id) {
415
+ try {
416
+ return (await fsTree(root).read(epicPath((await loadConfig(root)).paths, id))) !== undefined;
417
+ }
418
+ catch {
419
+ return false;
420
+ }
421
+ }
422
+ /** Replaces the description of the work's own change when a file is given. */
423
+ async function describeAnew(io, all, bodyFile) {
424
+ if (!bodyFile)
425
+ return;
426
+ const body = await readBody(io.cwd, bodyFile);
427
+ const own = all.find((c) => c.repo === undefined);
428
+ if (!own)
429
+ throw new Error("the work's own change is not open: its description cannot change");
430
+ await own.host.setBody(own.change.number, body);
431
+ }
432
+ /**
433
+ * `cupola change ready <work> [--body-file <f>]`: describes the change anew
434
+ * when a file is given, then marks it ready for its gate — an epic's change
435
+ * once none of its cards is open. Best effort: a host that refuses leaves the
436
+ * change as it is, and the output says so; nothing fails because of it.
437
+ */
438
+ export async function changeReady(io, id, opts) {
439
+ const { change, all } = await openChangeOf(io, id);
440
+ await describeAnew(io, all, opts.bodyFile);
441
+ const skipped = [];
442
+ for (const c of all) {
443
+ if (!c.change.draft)
444
+ continue;
445
+ try {
446
+ await c.host.markReady(c.change.number);
447
+ }
448
+ catch (error) {
449
+ skipped.push(`${c.change.url}: ${error.message.split("\n")[0]}`);
450
+ }
451
+ }
452
+ const urls = all.map((c) => c.change.url);
453
+ io.out(opts.json
454
+ ? JSON.stringify({
455
+ ...change,
456
+ ...(change.state === "open" && skipped.length === 0 ? { draft: false } : {}),
457
+ ready: urls,
458
+ ...(skipped.length > 0 ? { skipped } : {}),
459
+ })
460
+ : [
461
+ `${urls.join(", ")} ${urls.length > 1 ? "are" : "is"} ready`,
462
+ ...skipped.map((s) => `not marked ready (left as it is): ${s}`),
463
+ ].join("\n"));
464
+ return 0;
465
+ }
466
+ /**
467
+ * `cupola change draft <work> [--body-file <f>]`: turns the change back into a
468
+ * draft, as a No-Go does, describing it anew when a file is given. For an
469
+ * epic's change (kept a draft while cards are open) it is best effort: a host
470
+ * that refuses leaves it as it is.
471
+ */
472
+ export async function changeDraft(io, id, opts) {
473
+ const { root, change, all, codes } = await openChangeOf(io, id);
474
+ // Code merged already cannot take rework: what a No-Go asks goes into a fix of its own.
475
+ const merged = codes.filter((c) => c.change?.state === "merged");
476
+ if (merged.length > 0)
477
+ throw new Error(`the code change of ${id} is merged already (${merged.map((c) => c.change?.url).join(", ")}): rework cannot go into it; file a case for a fix instead`);
478
+ await describeAnew(io, all, opts.bodyFile);
479
+ const epic = await isEpic(root, id);
480
+ const skipped = [];
481
+ for (const c of all) {
482
+ if (c.change.draft)
483
+ continue;
484
+ try {
485
+ await c.host.markDraft(c.change.number);
486
+ }
487
+ catch (error) {
488
+ if (!epic)
489
+ throw error;
490
+ skipped.push(`${c.change.url}: ${error.message.split("\n")[0]}`);
491
+ }
492
+ }
493
+ const urls = all.map((c) => c.change.url);
494
+ io.out(opts.json
495
+ ? JSON.stringify({
496
+ ...change,
497
+ ...(change.state === "open" && skipped.length === 0 ? { draft: true } : {}),
498
+ drafted: urls,
499
+ ...(skipped.length > 0 ? { skipped } : {}),
500
+ })
501
+ : [
502
+ `${urls.join(", ")} ${urls.length > 1 ? "are drafts" : "is a draft"}`,
503
+ ...skipped.map((s) => `not made a draft (left as it is): ${s}`),
504
+ ].join("\n"));
505
+ return 0;
506
+ }
507
+ /**
508
+ * `cupola change close <work> --body-file <f>`: closes the work's change
509
+ * without merging, its branch kept (a spec a revision drops).
510
+ */
511
+ export async function changeClose(io, id, opts) {
512
+ if (!opts.bodyFile)
513
+ throw new Error("say why: --body-file <file>");
514
+ const body = await readBody(io.cwd, opts.bodyFile);
515
+ const { change, all } = await openChangeOf(io, id);
516
+ // The code changes first: a retry after a failure halfway still finds the hub's change open.
517
+ for (const c of [...all].reverse())
518
+ await c.host.closeChange(c.change.number, body);
519
+ const urls = all.map((c) => c.change.url);
520
+ io.out(opts.json
521
+ ? JSON.stringify({
522
+ ...change,
523
+ ...(change.state === "open" ? { state: "closed" } : {}),
524
+ closed: urls,
525
+ })
526
+ : `${urls.join(", ")} ${urls.length > 1 ? "are" : "is"} closed`);
527
+ return 0;
528
+ }
529
+ /** `cupola change review <work>`: asks the configured host reviewer to review the change. */
530
+ export async function changeReview(io, id, opts) {
531
+ const { root, change, all } = await openChangeOf(io, id);
532
+ const { reviewer } = (await loadConfig(root)).review;
533
+ if (reviewer === "subagent") {
534
+ throw new Error("review.reviewer is subagent: the review phase runs its own agent, not the host's");
535
+ }
536
+ const requestedAt = (io.now?.() ?? new Date()).toISOString();
537
+ for (const c of all)
538
+ await c.host.requestReview(c.change.number, reviewer);
539
+ io.out(opts.json
540
+ ? JSON.stringify({ reviewer, requestedAt })
541
+ : `asked ${reviewer} to review ${change.url}; wait with \`cupola change feedback ${id} --since ${requestedAt} --wait 540\` (repeated while it times out)`);
542
+ return 0;
543
+ }
544
+ /** Who wrote what was left out, and how much. */
545
+ function others(items) {
546
+ const counts = new Map();
547
+ for (const i of items)
548
+ counts.set(i.author, (counts.get(i.author) ?? 0) + 1);
549
+ return [...counts].map(([author, count]) => ({ author, count }));
550
+ }
551
+ function time(value, flag) {
552
+ const t = Date.parse(value);
553
+ if (Number.isNaN(t))
554
+ throw new Error(`${flag} takes a time, not ${value}`);
555
+ return t;
556
+ }
557
+ /**
558
+ * `cupola change feedback <work> [--since <time>] [--wait <seconds>]`: the
559
+ * review phase's findings — the open feedback the configured reviewer opened,
560
+ * with the replies someone trusted wrote in it — and whether the reviewer has
561
+ * answered since `since`. With `--wait`, polls until it has, or the time is
562
+ * up. What people opened is a reaction, processed at the gate (`cupola
563
+ * reaction`), not here; replies by anyone untrusted are counted under
564
+ * `others`, never shown.
565
+ */
566
+ export async function changeFeedback(io, id, opts) {
567
+ const { root, all } = await openChangeOf(io, id);
568
+ const config = await loadConfig(root);
569
+ const { reviewer } = config.review;
570
+ const ok = (r) => trusted(r, reviewer, config.trust);
571
+ const since = opts.since === undefined ? 0 : time(opts.since, "--since");
572
+ const now = () => (io.now?.() ?? new Date()).getTime();
573
+ const deadline = now() + seconds(opts.wait) * 1000;
574
+ for (;;) {
575
+ const got = await Promise.all(all.map((c) => c.host.feedback(c.change.number, ok)));
576
+ // Each change is reviewed: the reviewer has answered when every one has a review of it since.
577
+ const answered = got.every((g) => g.answers.some((a) => byReviewer(a, reviewer) && Date.parse(a.at) > since));
578
+ const waiting = opts.wait !== undefined && !answered;
579
+ if (!waiting || now() >= deadline) {
580
+ const open = got
581
+ .flatMap((g) => g.feedback)
582
+ .filter((f) => f.open && (!ok(f) || byReviewer(f, reviewer)));
583
+ const shown = open
584
+ .filter((f) => ok(f))
585
+ .map((f) => ({
586
+ id: f.id,
587
+ author: f.author,
588
+ place: f.place,
589
+ body: f.body,
590
+ replies: f.replies.filter(ok).map((r) => ({ author: r.author, body: r.body })),
591
+ answered: f.answered,
592
+ }));
593
+ const left = others([
594
+ ...open.filter((f) => !ok(f)),
595
+ ...open.filter((f) => ok(f)).flatMap((f) => f.replies.filter((r) => !ok(r))),
596
+ ]);
597
+ const result = {
598
+ reviewer,
599
+ answered,
600
+ feedback: shown,
601
+ timedOut: waiting,
602
+ ...(left.length > 0 ? { others: left } : {}),
603
+ };
604
+ if (opts.json)
605
+ io.out(JSON.stringify(result));
606
+ else {
607
+ io.out(`${shown.length} open${answered ? "" : ` (${reviewer} has not answered${waiting ? ", timed out" : ""})`}`);
608
+ for (const f of shown) {
609
+ const where = f.place ? `${f.place.path}:${f.place.line ?? "?"}` : "the change";
610
+ io.out(` ${f.id} ${where} (${f.author})${f.answered ? " answered" : ""} ${f.body.split("\n")[0]}`);
611
+ }
612
+ for (const o of left)
613
+ io.out(` left out: ${o.count} by ${o.author} (not trusted by the configuration)`);
614
+ }
615
+ return 0;
616
+ }
617
+ await sleep(io, POLL_MS);
618
+ }
619
+ }
620
+ /**
621
+ * `cupola change answer <work> --feedback <id> --body-file <f> [--settle]`:
622
+ * answers open feedback of the reviewer that `change feedback` shows; with
623
+ * `--settle`, also closes it (fixed, declined, or already answered). Feedback
624
+ * that goes to a human is answered without `--settle`, and stays open. What a
625
+ * person opened is a reaction: `cupola reaction reply` answers it at the gate.
626
+ */
627
+ export async function changeAnswer(io, id, opts) {
628
+ if (!opts.feedback)
629
+ throw new Error("give the feedback to answer: --feedback <id>");
630
+ if (!opts.bodyFile)
631
+ throw new Error("give the answer: --body-file <file>");
632
+ const body = await readBody(io.cwd, opts.bodyFile);
633
+ const { root, all } = await openChangeOf(io, id);
634
+ const config = await loadConfig(root);
635
+ const { reviewer } = config.review;
636
+ const ok = (a) => trusted(a, reviewer, config.trust);
637
+ for (const c of all) {
638
+ const item = (await c.host.feedback(c.change.number, ok)).feedback.find((f) => f.id === opts.feedback && f.open && ok(f));
639
+ if (!item)
640
+ continue;
641
+ if (!byReviewer(item, reviewer)) {
642
+ throw new Error(`${item.id} was opened by ${item.author}, not the reviewer: it is a reaction, answered at the gate with \`cupola reaction reply\``);
643
+ }
644
+ await c.host.answer(c.change.number, item.id, body, opts.settle === true);
645
+ io.out(opts.json
646
+ ? JSON.stringify({ answered: item.id, settled: opts.settle === true })
647
+ : `answered ${item.id}${opts.settle ? ", settled" : ""}`);
648
+ return 0;
649
+ }
650
+ throw new Error(`no open feedback ${opts.feedback} on ${all.map((c) => c.change.url).join(" or ")}`);
651
+ }
652
+ /**
653
+ * `cupola change checks <work> [--wait <seconds>]`: the change's CI result:
654
+ * pass, fail, pending, or none. With `--wait`, polls while checks are pending.
655
+ */
656
+ export async function changeChecks(io, id, opts) {
657
+ const { all } = await openChangeOf(io, id);
658
+ const now = () => (io.now?.() ?? new Date()).getTime();
659
+ const deadline = now() + seconds(opts.wait) * 1000;
660
+ const started = now();
661
+ // Per change: whether its repository defines no CI, once that has been asked.
662
+ const noCi = all.map(() => undefined);
663
+ for (;;) {
664
+ // A code change's checks count with the hub's: the work passes when every change's do.
665
+ const each = await Promise.all(all.map((c) => c.host.checks(c.change.number)));
666
+ const checks = each.flat();
667
+ const states = each.map((list) => list.length === 0
668
+ ? "none"
669
+ : list.some((c) => c.state === "fail" || c.state === "cancel")
670
+ ? "fail"
671
+ : list.some((c) => c.state === "pending")
672
+ ? "pending"
673
+ : "pass");
674
+ // Right after a push the checks may not have started: "none" is waited on too, and is never a
675
+ // pass.
676
+ // Nothing reported after a short grace is "none" only in a repository that defines no CI;
677
+ // where CI exists, its checks have not started yet, and the wait goes on.
678
+ // Without --wait, at once: a change of a repository with no CI does not count. With it,
679
+ // after the grace: right after a push, checks that exist may not have reported yet.
680
+ if (opts.wait === undefined || now() - started >= NONE_GRACE_MS) {
681
+ for (const [i, st] of states.entries()) {
682
+ if (st === "none" && noCi[i] === undefined)
683
+ noCi[i] = !(await all[i]?.host.hasCi());
684
+ }
685
+ }
686
+ // A change with no checks counts only when its repository defines no CI.
687
+ const waitedOn = states.filter((st, i) => st !== "none" || noCi[i] !== true);
688
+ const state = states.includes("fail")
689
+ ? "fail"
690
+ : states.includes("pending")
691
+ ? "pending"
692
+ : waitedOn.includes("none") || waitedOn.length === 0
693
+ ? "none"
694
+ : "pass";
695
+ const settled = state === "pass" ||
696
+ state === "fail" ||
697
+ (state === "none" && (opts.wait === undefined || waitedOn.length === 0));
698
+ if (settled || now() >= deadline) {
699
+ io.out(opts.json
700
+ ? JSON.stringify({ state, checks })
701
+ : `checks: ${state}${state === "none" ? " (no CI has reported; this is not a pass)" : ""}`);
702
+ return 0;
703
+ }
704
+ await sleep(io, POLL_MS);
705
+ }
706
+ }
707
+ /** Outside the hub, copies a spec's agreed epic into its worktree, if it has one. */
708
+ async function snapshotOwnEpic(io, root, id) {
709
+ const ws = await workspace(io);
710
+ if (ws.here.isHub)
711
+ return;
712
+ const file = `.kiro/specs/${id}/spec.json`;
713
+ const raw = await fsTree(root).read(file);
714
+ const block = raw === undefined ? undefined : readBlock(file, raw);
715
+ let epic = block?.epic;
716
+ if (!epic) {
717
+ try {
718
+ const doc = await findSpecDocument(fsTree(root), ws.config, id);
719
+ if (doc.kind === "fix-spec" && doc.epic)
720
+ epic = doc.epic;
721
+ }
722
+ catch {
723
+ // not a work item with an epic
724
+ }
725
+ }
726
+ if (epic)
727
+ await snapshotEpic(ws, root, epic);
728
+ }