@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,522 @@
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 { github } from "../host/github.js";
8
+ import { releaseBody, releasesOf } from "../release.js";
9
+ import { repoRoot } from "../repo.js";
10
+ import { epicBranchName, epicFront, readBlock } from "../spec.js";
11
+ import { fsTree } from "../tree.js";
12
+ import { findSpecDocument, runsOn, workBranchName } from "../work.js";
13
+ import { workspace } from "../workspace.js";
14
+ import { snapshotEpic } from "./revision.js";
15
+ /** A change description must be finished: no template placeholders left. */
16
+ export async function readBody(cwd, file) {
17
+ const body = await readFile(resolve(cwd, file), "utf8");
18
+ if (body.includes("{{"))
19
+ throw new Error(`${file} still has template placeholders ({{…}})`);
20
+ return body;
21
+ }
22
+ /**
23
+ * `cupola change open <work> --title <t> --body-file <f> [--base <b>]`: pushes
24
+ * the work's branch and opens its change as a draft, so that it is visible at
25
+ * once. Opening again returns the open change.
26
+ */
27
+ export async function changeOpen(io, id, opts) {
28
+ const root = await repoRoot(io.cwd);
29
+ const branch = await workBranch(root);
30
+ if (!runsOn(branch, id)) {
31
+ throw new Error(`${id} is on ${workBranchName(id)}, but this checkout is on ${branch}`);
32
+ }
33
+ const host = (io.host ?? github)(root);
34
+ const existing = await host.findChange(branch);
35
+ const onEpic = branch === epicBranchName(id);
36
+ // The workspace is read only where it matters: an epic's release, or code kept apart.
37
+ const ws0 = onEpic || (await loadConfig(root)).documents === "hub" ? await workspace(io) : undefined;
38
+ // An epic's release across repositories goes on below: some of its changes may be missing.
39
+ const fanOut = onEpic && (ws0?.repos.length ?? 1) > 1;
40
+ // With every document in the hub, the code is a change of its own in its repository.
41
+ const codes = onEpic || !ws0 ? [] : await codeOf(io, ws0, root, id, branch);
42
+ if (existing?.state === "open" && !fanOut && codes.every((c) => c.change?.state === "open")) {
43
+ io.out(opts.json ? JSON.stringify(withCode(existing, codes)) : existing.url);
44
+ return 0;
45
+ }
46
+ if (existing?.state === "open" && !fanOut && ws0) {
47
+ const opened = await openCodeChanges(io, ws0, root, id, branch, {
48
+ title: opts.title ?? `Code: ${id}`,
49
+ hub: existing,
50
+ ready: opts.ready === true,
51
+ base: opts.base,
52
+ });
53
+ io.out(opts.json ? JSON.stringify(withCode(existing, opened)) : existing.url);
54
+ return 0;
55
+ }
56
+ if (!opts.title || !opts.bodyFile)
57
+ throw new Error("give --title and --body-file");
58
+ // Outside the hub, the spec's epic (which says its base) is the hub's: copied in first.
59
+ await snapshotOwnEpic(io, root, id);
60
+ const body = await readBody(io.cwd, opts.bodyFile);
61
+ const base = opts.base ?? (await epicBaseOf(root, id)) ?? (await originDefaultBranch(root));
62
+ if (!base)
63
+ throw new Error("cannot tell origin's default branch; name it with --base <branch>");
64
+ try {
65
+ await git(root, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]);
66
+ }
67
+ catch (error) {
68
+ const lines = (error.stderr ?? "").split("\n").map((l) => l.trim());
69
+ const reason = lines.filter((l) => /^(!|error:|fatal:)/.test(l)).join("; ") || "unknown reason";
70
+ throw new Error(`could not push ${branch} (${reason}); pull origin ${branch} first if it moved on`);
71
+ }
72
+ // An epic's release across repositories: one change per repository, in merge order.
73
+ if (onEpic && ws0) {
74
+ const ws = ws0;
75
+ if (ws.repos.length > 1) {
76
+ const path = epicPath(ws.config.paths, id);
77
+ const raw = await fsTree(root).read(path);
78
+ if (raw === undefined)
79
+ throw new Error(`${path} is not on ${branch}`);
80
+ const releases = releasesOf(ws, epicFront(path, raw).front.specs);
81
+ const opened = [];
82
+ for (const r of releases) {
83
+ const there = ws.host(io, r.repo.slug);
84
+ const found = await there.findChange(branch);
85
+ const repoBase = r.repo.isHub ? base : await originDefaultBranch(r.repo.main);
86
+ if (!repoBase)
87
+ throw new Error(`cannot tell origin's default branch of ${r.repo.slug}`);
88
+ // Open or merged already: kept (a release merged before a retry is not opened again).
89
+ const change = found && found.state !== "closed"
90
+ ? found
91
+ : await there.openChange({
92
+ branch,
93
+ base: repoBase,
94
+ title: opts.title,
95
+ body: releaseBody(body, r, releases),
96
+ draft: !opts.ready,
97
+ });
98
+ opened.push({ repo: r.repo.slug, order: r.order, of: r.of, change });
99
+ }
100
+ const hubChange = opened.find((o) => o.repo === ws.hub.slug)?.change ?? opened[0]?.change;
101
+ io.out(opts.json
102
+ ? JSON.stringify({ ...hubChange, releases: opened })
103
+ : opened.map((o) => `${o.order}/${o.of} ${o.repo}: ${o.change.url}`).join("\n"));
104
+ return 0;
105
+ }
106
+ }
107
+ const change = existing?.state === "open"
108
+ ? existing
109
+ : await host.openChange({
110
+ branch,
111
+ base,
112
+ title: opts.title,
113
+ body,
114
+ draft: !opts.ready,
115
+ });
116
+ const opened = ws0
117
+ ? await openCodeChanges(io, ws0, root, id, branch, {
118
+ title: opts.title,
119
+ hub: change,
120
+ ready: opts.ready === true,
121
+ base: opts.base,
122
+ })
123
+ : [];
124
+ io.out(opts.json ? JSON.stringify(withCode(change, opened)) : change.url);
125
+ return 0;
126
+ }
127
+ /** A work item's code changes, one per code repository its worktree mounts. */
128
+ async function codeOf(io, ws, root, id, branch) {
129
+ if (ws.config.documents !== "hub")
130
+ return [];
131
+ const { components } = await workComponents(ws, root, id, branch);
132
+ return codeChanges(io, ws, branch, components);
133
+ }
134
+ /** The code changes of the work this checkout runs; the workspace is read only when they can exist. */
135
+ async function codeOfHere(io, root, id, branch) {
136
+ if ((await loadConfig(root)).documents !== "hub")
137
+ return [];
138
+ return codeOf(io, await workspace(io), root, id, branch);
139
+ }
140
+ /** A hub change with its code changes, as `change open` and `change show` print it. */
141
+ function withCode(change, codes) {
142
+ return codes.length === 0
143
+ ? change
144
+ : { ...change, code: codes.map((c) => ({ repo: c.slug, change: c.change ?? null })) };
145
+ }
146
+ /** The description of a code change: what it is, where its documents are, and the hub's description. */
147
+ export function codeBody(id, hubUrl, described) {
148
+ return [
149
+ `<!-- cupola:change ${JSON.stringify({ kind: "code", work: id, method: 1 })} -->`,
150
+ `The code and tests of \`${id}\`. Its documents and record are in ${hubUrl}: the two are merged together, this one first.`,
151
+ // The hub's description without its own marker: a change carries one marker, its own.
152
+ ...(described
153
+ ? ["", described.replace(/^\s*<!--\s*cupola:change\s+\{.*?\}\s*-->\s*\n?/, "").trim()]
154
+ : []),
155
+ "",
156
+ ].join("\n");
157
+ }
158
+ /**
159
+ * Pushes the branch of each code repository the work's worktree mounts and
160
+ * opens its change, against the same base as the hub's change: the epic
161
+ * branch, or its own default branch. A branch with nothing on it yet is not a
162
+ * change: it is opened when it has commits (`change open` again, or the run's
163
+ * finish). Returns every code change there is.
164
+ */
165
+ export async function openCodeChanges(io, ws, root, id, branch, opts) {
166
+ if (ws.config.documents !== "hub")
167
+ return [];
168
+ const { components, base: epicBase } = await workComponents(ws, root, id, branch);
169
+ const out = [];
170
+ for (const m of mountsIn(ws, root, components)) {
171
+ const there = ws.host(io, m.slug);
172
+ const found = await there.findChange(branch);
173
+ const base = opts.base ?? epicBase ?? (await originDefaultBranch(m.main));
174
+ if (!base)
175
+ throw new Error(`cannot tell origin's default branch of ${m.slug}`);
176
+ await git(m.path, [
177
+ "fetch",
178
+ "--quiet",
179
+ "origin",
180
+ `+refs/heads/${base}:refs/remotes/origin/${base}`,
181
+ ]);
182
+ // Merged already: a squash merge leaves HEAD looking ahead, and nothing is pushed again.
183
+ if (found?.state === "merged") {
184
+ out.push({ slug: m.slug, host: there, change: found });
185
+ continue;
186
+ }
187
+ const ahead = await git(m.path, ["rev-list", "--count", `refs/remotes/origin/${base}..HEAD`]);
188
+ // What is committed there is pushed, so that its change holds it.
189
+ if (ahead !== "0") {
190
+ try {
191
+ await git(m.path, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]);
192
+ }
193
+ catch (error) {
194
+ const lines = (error.stderr ?? "")
195
+ .split("\n")
196
+ .map((l) => l.trim());
197
+ const reason = lines.filter((l) => /^(!|error:|fatal:)/.test(l)).join("; ") || "unknown reason";
198
+ throw new Error(`could not push ${branch} of ${m.slug} (${reason}); pull origin ${branch} there first if it moved on`);
199
+ }
200
+ }
201
+ if (found && found.state !== "closed") {
202
+ out.push({ slug: m.slug, host: there, change: found });
203
+ continue;
204
+ }
205
+ if (ahead === "0") {
206
+ out.push({ slug: m.slug, host: there, change: undefined });
207
+ continue;
208
+ }
209
+ const change = await there.openChange({
210
+ branch,
211
+ base,
212
+ title: opts.title,
213
+ body: codeBody(id, opts.hub.url),
214
+ draft: !opts.ready,
215
+ });
216
+ out.push({ slug: m.slug, host: there, change });
217
+ }
218
+ return out;
219
+ }
220
+ /**
221
+ * The branch whose change a command means: on an epic's own branch, the epic's
222
+ * release; anywhere else, the work's own branch.
223
+ */
224
+ async function changeBranch(root, id) {
225
+ try {
226
+ if ((await workBranch(root)) === epicBranchName(id))
227
+ return epicBranchName(id);
228
+ }
229
+ catch {
230
+ // the default branch, or detached: the work's own branch
231
+ }
232
+ return workBranchName(id);
233
+ }
234
+ /** `cupola change show <work>`: the work item's change, or null. */
235
+ export async function changeShow(io, id, opts) {
236
+ const root = await repoRoot(io.cwd);
237
+ const host = (io.host ?? github)(root);
238
+ const branch = await changeBranch(root, id);
239
+ const change = await host.findChange(branch);
240
+ const codes = change ? await codeOfHere(io, root, id, branch) : [];
241
+ if (!opts.json) {
242
+ io.out(change
243
+ ? [change.url, ...codes.flatMap((c) => (c.change ? [c.change.url] : []))].join("\n")
244
+ : `${id} has no change`);
245
+ return 0;
246
+ }
247
+ // The description too: after the merge it is where the run's account of the work lives.
248
+ io.out(JSON.stringify(change ? { ...withCode(change, codes), body: await host.body(change.number) } : null));
249
+ return 0;
250
+ }
251
+ /**
252
+ * The work's open changes: the hub's, and with every document in the hub its
253
+ * open code changes. One that is merged or closed is left out, so
254
+ * a command interrupted halfway, or a change a human merged first, still
255
+ * reaches the others. `change` is the hub's change, whatever its state.
256
+ */
257
+ async function openChangeOf(io, id) {
258
+ const root = await repoRoot(io.cwd);
259
+ const host = (io.host ?? github)(root);
260
+ const branch = await changeBranch(root, id);
261
+ const change = await host.findChange(branch);
262
+ if (!change)
263
+ throw new Error(`${id} has no open change`);
264
+ const codes = await codeOfHere(io, root, id, branch);
265
+ const all = [
266
+ ...(change.state === "open" ? [{ host, change, repo: undefined }] : []),
267
+ ...codes.flatMap((c) => c.change?.state === "open" ? [{ host: c.host, change: c.change, repo: c.slug }] : []),
268
+ ];
269
+ if (all.length === 0)
270
+ throw new Error(`${id} has no open change`);
271
+ return { root, host, change, all, codes };
272
+ }
273
+ const sleep = (io, ms) => (io.sleep ?? ((t) => new Promise((r) => setTimeout(r, t))))(ms);
274
+ const POLL_MS = 15_000;
275
+ /** How long `checks --wait` waits for CI to report at all, before taking "none" as the answer. */
276
+ const NONE_GRACE_MS = 120_000;
277
+ function seconds(value) {
278
+ if (value === undefined)
279
+ return 0;
280
+ const n = Number(value);
281
+ if (!Number.isFinite(n) || n < 0)
282
+ throw new Error(`--wait takes seconds, not ${value}`);
283
+ return n;
284
+ }
285
+ /** `cupola change draft <work>`: turns the change back into a draft, as a send-back does. */
286
+ export async function changeDraft(io, id, opts) {
287
+ const { change, all, codes } = await openChangeOf(io, id);
288
+ // Code merged already cannot take rework: what was sent back goes into a fix of its own.
289
+ const merged = codes.filter((c) => c.change?.state === "merged");
290
+ if (merged.length > 0)
291
+ 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`);
292
+ for (const c of all)
293
+ if (!c.change.draft)
294
+ await c.host.markDraft(c.change.number);
295
+ const urls = all.map((c) => c.change.url);
296
+ io.out(opts.json
297
+ ? JSON.stringify({
298
+ ...change,
299
+ ...(change.state === "open" ? { draft: true } : {}),
300
+ drafted: urls,
301
+ })
302
+ : `${urls.join(", ")} ${urls.length > 1 ? "are drafts" : "is a draft"} again`);
303
+ return 0;
304
+ }
305
+ /**
306
+ * `cupola change close <work> --body-file <f>`: closes the work's change
307
+ * without merging, its branch kept (a spec a revision drops).
308
+ */
309
+ export async function changeClose(io, id, opts) {
310
+ if (!opts.bodyFile)
311
+ throw new Error("say why: --body-file <file>");
312
+ const body = await readBody(io.cwd, opts.bodyFile);
313
+ const { change, all } = await openChangeOf(io, id);
314
+ // The code changes first: a retry after a failure halfway still finds the hub's change open.
315
+ for (const c of [...all].reverse())
316
+ await c.host.closeChange(c.change.number, body);
317
+ const urls = all.map((c) => c.change.url);
318
+ io.out(opts.json
319
+ ? JSON.stringify({
320
+ ...change,
321
+ ...(change.state === "open" ? { state: "closed" } : {}),
322
+ closed: urls,
323
+ })
324
+ : `${urls.join(", ")} ${urls.length > 1 ? "are" : "is"} closed`);
325
+ return 0;
326
+ }
327
+ /** `cupola change review <work>`: asks the configured host reviewer to review the change. */
328
+ export async function changeReview(io, id, opts) {
329
+ const { root, change, all } = await openChangeOf(io, id);
330
+ const { reviewer } = (await loadConfig(root)).review;
331
+ if (reviewer === "subagent") {
332
+ throw new Error("review.reviewer is subagent: the review phase runs its own agent, not the host's");
333
+ }
334
+ const requestedAt = (io.now?.() ?? new Date()).toISOString();
335
+ for (const c of all)
336
+ await c.host.requestReview(c.change.number, reviewer);
337
+ io.out(opts.json
338
+ ? JSON.stringify({ reviewer, requestedAt })
339
+ : `asked ${reviewer} to review ${change.url}; wait with \`cupola change feedback ${id} --since ${requestedAt} --wait 540\` (repeated while it times out)`);
340
+ return 0;
341
+ }
342
+ /** Who wrote what was left out, and how much. */
343
+ function others(items) {
344
+ const counts = new Map();
345
+ for (const i of items)
346
+ counts.set(i.author, (counts.get(i.author) ?? 0) + 1);
347
+ return [...counts].map(([author, count]) => ({ author, count }));
348
+ }
349
+ function time(value, flag) {
350
+ const t = Date.parse(value);
351
+ if (Number.isNaN(t))
352
+ throw new Error(`${flag} takes a time, not ${value}`);
353
+ return t;
354
+ }
355
+ /**
356
+ * `cupola change feedback <work> [--since <time>] [--wait <seconds>]`: the
357
+ * open feedback on the work's changes that someone trusted wrote, and whether
358
+ * the configured reviewer has answered since `since`. With `--wait`, polls
359
+ * until it has, or the time is up. What anyone else wrote is counted under
360
+ * `others`, never shown.
361
+ */
362
+ export async function changeFeedback(io, id, opts) {
363
+ const { root, all } = await openChangeOf(io, id);
364
+ const config = await loadConfig(root);
365
+ const { reviewer } = config.review;
366
+ const ok = (r) => trusted(r, reviewer, config.trust);
367
+ const since = opts.since === undefined ? 0 : time(opts.since, "--since");
368
+ const now = () => (io.now?.() ?? new Date()).getTime();
369
+ const deadline = now() + seconds(opts.wait) * 1000;
370
+ for (;;) {
371
+ const got = await Promise.all(all.map((c) => c.host.feedback(c.change.number, ok)));
372
+ // Each change is reviewed: the reviewer has answered when every one has a review of it since.
373
+ const answered = got.every((g) => g.answers.some((a) => byReviewer(a, reviewer) && Date.parse(a.at) > since));
374
+ const waiting = opts.wait !== undefined && !answered;
375
+ if (!waiting || now() >= deadline) {
376
+ const open = got.flatMap((g) => g.feedback).filter((f) => f.open);
377
+ const shown = open
378
+ .filter((f) => ok(f))
379
+ .map((f) => ({
380
+ id: f.id,
381
+ author: f.author,
382
+ place: f.place,
383
+ body: f.body,
384
+ replies: f.replies.filter(ok).map((r) => ({ author: r.author, body: r.body })),
385
+ answered: f.answered,
386
+ }));
387
+ const left = others([
388
+ ...open.filter((f) => !ok(f)),
389
+ ...open.filter((f) => ok(f)).flatMap((f) => f.replies.filter((r) => !ok(r))),
390
+ ]);
391
+ const result = {
392
+ reviewer,
393
+ answered,
394
+ feedback: shown,
395
+ timedOut: waiting,
396
+ ...(left.length > 0 ? { others: left } : {}),
397
+ };
398
+ if (opts.json)
399
+ io.out(JSON.stringify(result));
400
+ else {
401
+ io.out(`${shown.length} open${answered ? "" : ` (${reviewer} has not answered${waiting ? ", timed out" : ""})`}`);
402
+ for (const f of shown) {
403
+ const where = f.place ? `${f.place.path}:${f.place.line ?? "?"}` : "the change";
404
+ io.out(` ${f.id} ${where} (${f.author})${f.answered ? " answered" : ""} ${f.body.split("\n")[0]}`);
405
+ }
406
+ for (const o of left)
407
+ io.out(` left out: ${o.count} by ${o.author} (not trusted by the configuration)`);
408
+ }
409
+ return 0;
410
+ }
411
+ await sleep(io, POLL_MS);
412
+ }
413
+ }
414
+ /**
415
+ * `cupola change answer <work> --feedback <id> --body-file <f> [--settle]`:
416
+ * answers open feedback that `change feedback` shows; with `--settle`, also
417
+ * closes it (fixed, declined, or already answered). Feedback that goes to a
418
+ * human is answered without `--settle`, and stays open.
419
+ */
420
+ export async function changeAnswer(io, id, opts) {
421
+ if (!opts.feedback)
422
+ throw new Error("give the feedback to answer: --feedback <id>");
423
+ if (!opts.bodyFile)
424
+ throw new Error("give the answer: --body-file <file>");
425
+ const body = await readBody(io.cwd, opts.bodyFile);
426
+ const { root, all } = await openChangeOf(io, id);
427
+ const config = await loadConfig(root);
428
+ const { reviewer } = config.review;
429
+ const ok = (a) => trusted(a, reviewer, config.trust);
430
+ for (const c of all) {
431
+ const item = (await c.host.feedback(c.change.number, ok)).feedback.find((f) => f.id === opts.feedback && f.open && ok(f));
432
+ if (!item)
433
+ continue;
434
+ // A person settles what they opened; Cupola settles only what the reviewer did.
435
+ if (opts.settle && !byReviewer(item, reviewer)) {
436
+ throw new Error(`${item.id} was opened by ${item.author}, not the reviewer: answer it without --settle`);
437
+ }
438
+ await c.host.answer(c.change.number, item.id, body, opts.settle === true);
439
+ io.out(opts.json
440
+ ? JSON.stringify({ answered: item.id, settled: opts.settle === true })
441
+ : `answered ${item.id}${opts.settle ? ", settled" : ""}`);
442
+ return 0;
443
+ }
444
+ throw new Error(`no open feedback ${opts.feedback} on ${all.map((c) => c.change.url).join(" or ")}`);
445
+ }
446
+ /**
447
+ * `cupola change checks <work> [--wait <seconds>]`: the change's CI result:
448
+ * pass, fail, pending, or none. With `--wait`, polls while checks are pending.
449
+ */
450
+ export async function changeChecks(io, id, opts) {
451
+ const { all } = await openChangeOf(io, id);
452
+ const now = () => (io.now?.() ?? new Date()).getTime();
453
+ const deadline = now() + seconds(opts.wait) * 1000;
454
+ const started = now();
455
+ // Per change: whether its repository defines no CI, once that has been asked.
456
+ const noCi = all.map(() => undefined);
457
+ for (;;) {
458
+ // A code change's checks count with the hub's: the work passes when every change's do.
459
+ const each = await Promise.all(all.map((c) => c.host.checks(c.change.number)));
460
+ const checks = each.flat();
461
+ const states = each.map((list) => list.length === 0
462
+ ? "none"
463
+ : list.some((c) => c.state === "fail" || c.state === "cancel")
464
+ ? "fail"
465
+ : list.some((c) => c.state === "pending")
466
+ ? "pending"
467
+ : "pass");
468
+ // Right after a push the checks may not have started: "none" is waited on too, and is never a
469
+ // pass.
470
+ // Nothing reported after a short grace is "none" only in a repository that defines no CI;
471
+ // where CI exists, its checks have not started yet, and the wait goes on.
472
+ // Without --wait, at once: a change of a repository with no CI does not count. With it,
473
+ // after the grace: right after a push, checks that exist may not have reported yet.
474
+ if (opts.wait === undefined || now() - started >= NONE_GRACE_MS) {
475
+ for (const [i, st] of states.entries()) {
476
+ if (st === "none" && noCi[i] === undefined)
477
+ noCi[i] = !(await all[i]?.host.hasCi());
478
+ }
479
+ }
480
+ // A change with no checks counts only when its repository defines no CI.
481
+ const waitedOn = states.filter((st, i) => st !== "none" || noCi[i] !== true);
482
+ const state = states.includes("fail")
483
+ ? "fail"
484
+ : states.includes("pending")
485
+ ? "pending"
486
+ : waitedOn.includes("none") || waitedOn.length === 0
487
+ ? "none"
488
+ : "pass";
489
+ const settled = state === "pass" ||
490
+ state === "fail" ||
491
+ (state === "none" && (opts.wait === undefined || waitedOn.length === 0));
492
+ if (settled || now() >= deadline) {
493
+ io.out(opts.json
494
+ ? JSON.stringify({ state, checks })
495
+ : `checks: ${state}${state === "none" ? " (no CI has reported; this is not a pass)" : ""}`);
496
+ return 0;
497
+ }
498
+ await sleep(io, POLL_MS);
499
+ }
500
+ }
501
+ /** Outside the hub, copies a spec's agreed epic into its worktree, if it has one. */
502
+ async function snapshotOwnEpic(io, root, id) {
503
+ const ws = await workspace(io);
504
+ if (ws.here.isHub)
505
+ return;
506
+ const file = `.kiro/specs/${id}/spec.json`;
507
+ const raw = await fsTree(root).read(file);
508
+ const block = raw === undefined ? undefined : readBlock(file, raw);
509
+ let epic = block?.epic;
510
+ if (!epic) {
511
+ try {
512
+ const doc = await findSpecDocument(fsTree(root), ws.config, id);
513
+ if (doc.kind === "fix-spec" && doc.epic)
514
+ epic = doc.epic;
515
+ }
516
+ catch {
517
+ // not a work item with an epic
518
+ }
519
+ }
520
+ if (epic)
521
+ await snapshotEpic(ws, root, epic);
522
+ }