@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,474 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { checkAdrs } from "../adr.js";
5
+ import { behaviorDirs, loadCatalog, renderIndex } from "../catalog.js";
6
+ import { checkCatalog, checkFixCatalog, checkFixMarkers, checkIndexes, checkOrphans, checkPlaceholders, checkStrayCatalog, } from "../check.js";
7
+ import { EPIC_FILE, epicCardsDir, epicPath, loadConfig, resolveComponents, } from "../config.js";
8
+ import { checkProfile, E2E_PROFILE } from "../e2e.js";
9
+ import { checkEpic, parseEpic } from "../epic.js";
10
+ import { checkExecution } from "../execution.js";
11
+ import { git, originDefaultBranch } from "../git.js";
12
+ import { repoRoot } from "../repo.js";
13
+ import { checkRunbook, executionsDir, parseRunbook, RUNBOOK_FILE, RunbookFront, runbookPath, } from "../runbook.js";
14
+ import { writeInside } from "../safe-write.js";
15
+ import { buildTrace, findAllMarkers, readReports, } from "../trace.js";
16
+ import { fsTree, gitTree } from "../tree.js";
17
+ import { findSpecDocument, readCardsIn } from "../work.js";
18
+ import { checkoutDirs, identifyRepo, workspace } from "../workspace.js";
19
+ /**
20
+ * `cupola trace [<area>] [--index]`: the map requirement → tests → latest
21
+ * result, unverified entries, and orphaned tags. `--index`
22
+ * regenerates each behavior directory's README.md.
23
+ */
24
+ export async function trace(io, area, opts) {
25
+ const root = await repoRoot(io.cwd);
26
+ const config = await loadConfig(root);
27
+ const repo = await repoHere(io, root, config);
28
+ const areas = await loadCatalog(root, config, repo);
29
+ if (opts.index) {
30
+ const written = [];
31
+ for (const { dir } of behaviorDirs(config, repo)) {
32
+ const own = areas.filter((a) => a.dir === dir);
33
+ if (own.length === 0)
34
+ continue;
35
+ await writeInside(root, join(dir, "README.md"), renderIndex(own));
36
+ written.push(join(dir, "README.md"));
37
+ }
38
+ io.out(opts.json
39
+ ? JSON.stringify({ written })
40
+ : written.length
41
+ ? `wrote ${written.join(", ")}`
42
+ : "no areas yet");
43
+ return 0;
44
+ }
45
+ const selected = area ? areas.filter((a) => a.area === area) : areas;
46
+ if (area && selected.length === 0)
47
+ throw new Error(`no area ${area} in the catalog`);
48
+ // In the hub, the other repositories are cloned inside it: their reports are theirs.
49
+ const ws = await workspace({ ...io, cwd: root }).catch(() => undefined);
50
+ const named = ws?.here.isHub === true ? await checkoutDirs(ws.hub.main) : new Map();
51
+ const clones = ws?.here.isHub === true
52
+ ? ws.slugs
53
+ .filter((x) => x !== ws.hub.slug)
54
+ .map((x) => named.get(x.toLowerCase()) ?? x.split("/")[1] ?? x)
55
+ : [];
56
+ const reports = await readReports(root, config.verification.test_reports, [
57
+ ...clones,
58
+ ...clones.map((c) => `${c}.worktrees`),
59
+ ]);
60
+ const t = buildTrace(selected, await findAllMarkers(root, await codeSources(root, config, ws), behaviorDirs(config, repo).map((d) => d.dir)), reports.results, reports.warnings, await epicExamples(root, config));
61
+ if (area)
62
+ t.orphans = [];
63
+ if (opts.json) {
64
+ io.out(JSON.stringify(t));
65
+ return 0;
66
+ }
67
+ const count = (s) => t.entries.filter((e) => e.status === s).length;
68
+ io.out(`${t.entries.length} entries: ${count("passing")} passing, ${count("failing")} failing, ` +
69
+ `${count("no-result")} tested without a result, ${count("unverified")} unverified, ` +
70
+ `${count("manual") + count("untestable")} manual or untestable`);
71
+ for (const e of t.entries.filter((e) => e.status === "failing" || e.status === "unverified")) {
72
+ io.out(` ${e.status}: ${e.id} (${e.path})`);
73
+ }
74
+ for (const o of t.orphans)
75
+ io.out(` orphaned: @req ${o.ref} at ${o.file}:${o.line}`);
76
+ for (const w of t.warnings)
77
+ io.out(` warning: ${w}`);
78
+ return 0;
79
+ }
80
+ /** `cupola check`: self-checks a change before it is opened. */
81
+ export async function check(io, opts) {
82
+ const root = await repoRoot(io.cwd);
83
+ const config = await loadConfig(root);
84
+ const repo = await repoHere(io, root, config);
85
+ const areas = await loadCatalog(root, config, repo);
86
+ const ws = config.documents === "hub"
87
+ ? await workspace({ ...io, cwd: root }).catch(() => undefined)
88
+ : undefined;
89
+ const t = buildTrace(areas, await findAllMarkers(root, config.documents === "hub" ? await codeSources(root, config, ws) : [], behaviorDirs(config, repo).map((d) => d.dir)), []);
90
+ const problems = [
91
+ ...checkCatalog(areas, config, repo),
92
+ ...checkOrphans(t.orphans),
93
+ ...(await checkIndexes(root, areas, config, repo)),
94
+ ...(await checkStrayCatalog(root, config, repo)),
95
+ ...(await checkPlaceholders(root, areas)),
96
+ ...(await checkWork(root, config)),
97
+ ...(await checkEpics(root, config)),
98
+ ...(await checkRunbooks(root, config)),
99
+ ...(await checkEpicRefs(root, config, t.epicRefs)),
100
+ ...(await checkAdrs(root, config.paths.adr)),
101
+ ...(await checkE2eProfile(root, config)),
102
+ ];
103
+ if (opts.json)
104
+ io.out(JSON.stringify({ ok: problems.length === 0, problems }));
105
+ else if (problems.length === 0)
106
+ io.out("No problems found.");
107
+ else
108
+ for (const p of problems)
109
+ io.out(`${p.file}${p.line ? `:${p.line}` : ""}: ${p.message}`);
110
+ return problems.length === 0 ? 0 : 1;
111
+ }
112
+ /** The examples each requirement of every epic rests on (its `examples` field). */
113
+ async function epicExamples(root, config) {
114
+ const epics = config.paths.epics;
115
+ const out = new Map();
116
+ // Outside the hub, the hub's agreed epics.
117
+ const ws = await workspace({ out: () => { }, err: () => { }, cwd: root }).catch(() => undefined);
118
+ let files;
119
+ if (ws && !ws.here.isHub) {
120
+ const base = await originDefaultBranch(ws.hub.main);
121
+ const tree = gitTree(ws.hub.main, base ? `refs/remotes/origin/${base}` : "HEAD");
122
+ files = (await tree.dirs(epics)).map((id) => ({
123
+ name: id,
124
+ read: () => tree.read(epicPath(config.paths, id)),
125
+ }));
126
+ }
127
+ else {
128
+ const here = fsTree(root);
129
+ files = (await here.dirs(epics)).map((id) => ({
130
+ name: id,
131
+ read: () => here.read(epicPath(config.paths, id)),
132
+ }));
133
+ }
134
+ for (const f of files) {
135
+ const byId = new Map();
136
+ for (const e of parseEpic((await f.read()) ?? "").entries) {
137
+ const examples = e.fields.find((x) => x.key === "examples")?.value ?? "";
138
+ byId.set(e.id, examples.split(/[,\s]+/).filter((x) => /^X\d+$/.test(x)));
139
+ }
140
+ out.set(f.name, byId);
141
+ }
142
+ return out;
143
+ }
144
+ /** The e2e profile, when the repository has one. */
145
+ async function checkE2eProfile(root, config) {
146
+ const path = join(root, E2E_PROFILE);
147
+ if (!existsSync(path))
148
+ return [];
149
+ const all = resolveComponents(config);
150
+ const here = await repoHere({ out: () => { }, err: () => { }, cwd: root }, root, config);
151
+ const own = all.filter((c) => c.repo.toLowerCase() === here.toLowerCase());
152
+ return checkProfile(await readFile(path, "utf8"), all.map((c) => c.name), own.map((c) => c.name));
153
+ }
154
+ /** Every epic in the hub. */
155
+ async function checkEpics(root, config) {
156
+ const { epics } = config.paths;
157
+ const dir = join(root, epics);
158
+ // Outside the hub, the epics are copies of the hub's agreed ones: checked in the hub.
159
+ if (!existsSync(dir) || (await hubEpics(root, config)))
160
+ return [];
161
+ const components = resolveComponents(config).map((c) => c.name);
162
+ const here = fsTree(root);
163
+ const runbooks = new Map();
164
+ for (const id of await here.dirs(config.paths.runbooks)) {
165
+ const raw = await here.read(runbookPath(config.paths, id));
166
+ if (raw === undefined)
167
+ continue;
168
+ const front = RunbookFront.safeParse(parseRunbook(raw).front);
169
+ runbooks.set(id, front.success ? Object.keys(front.data.params) : []);
170
+ }
171
+ const problems = [];
172
+ // An epic is a folder: its document and its cards.
173
+ for (const f of (await here.list(epics)).filter((f) => f.endsWith(".md")).sort()) {
174
+ problems.push({
175
+ file: `${epics}/${f}`,
176
+ message: `an epic is a folder: move it to ${epics}/${f.slice(0, -3)}/${EPIC_FILE}`,
177
+ });
178
+ }
179
+ for (const id of (await here.dirs(epics)).sort()) {
180
+ const path = epicPath(config.paths, id);
181
+ const text = await here.read(path);
182
+ if (text === undefined) {
183
+ problems.push({
184
+ file: `${epics}/${id}`,
185
+ message: `no ${EPIC_FILE}: an epic's folder holds it`,
186
+ });
187
+ continue;
188
+ }
189
+ problems.push(...checkEpic(path, text, components, runbooks));
190
+ problems.push(...(await checkEpicCards(root, epicCardsDir(config.paths, id))));
191
+ }
192
+ return problems;
193
+ }
194
+ /**
195
+ * An epic's decision cards: numbered files `<n>-<slug>.md`, each a `decision`
196
+ * whose options all continue — at the start gate an answer is reflected in the epic, it
197
+ * starts or ends nothing. Open cards are no problem: the start gate is where they are answered.
198
+ */
199
+ async function checkEpicCards(root, dir) {
200
+ const problems = [];
201
+ let cards;
202
+ try {
203
+ cards = await readCardsIn(fsTree(root), dir);
204
+ }
205
+ catch (error) {
206
+ return [{ file: dir, message: error.message }];
207
+ }
208
+ const seen = new Set();
209
+ for (const c of cards) {
210
+ const file = `${dir}/${c.file}`;
211
+ if (seen.has(c.card))
212
+ problems.push({ file, message: `card ${c.card} is numbered twice` });
213
+ seen.add(c.card);
214
+ if (!c.file.startsWith(`${c.card}-`))
215
+ problems.push({ file, message: `card ${c.card}: its file name starts with ${c.card}-` });
216
+ if (c.type !== "decision")
217
+ problems.push({ file, message: `an epic's card is a decision, not ${c.type}` });
218
+ const other = (c.offers ?? []).filter((e) => e !== "continue");
219
+ if (other.length > 0)
220
+ problems.push({
221
+ file,
222
+ message: `an epic's card only continues (its answer is reflected in the epic), not ${other.join(", ")}`,
223
+ });
224
+ }
225
+ return problems;
226
+ }
227
+ /** Every runbook in the hub. */
228
+ async function checkRunbooks(root, config) {
229
+ const { runbooks } = config.paths;
230
+ const dir = join(root, runbooks);
231
+ if (!existsSync(dir) || (await hubEpics(root, config)))
232
+ return [];
233
+ const components = resolveComponents(config).map((c) => c.name);
234
+ const problems = [];
235
+ const here = fsTree(root);
236
+ // A runbook is a folder: its document and its executions.
237
+ for (const f of (await here.list(runbooks)).filter((f) => f.endsWith(".md")).sort()) {
238
+ problems.push({
239
+ file: `${runbooks}/${f}`,
240
+ message: `a runbook is a folder: move it to ${runbooks}/${f.slice(0, -3)}/${RUNBOOK_FILE}`,
241
+ });
242
+ }
243
+ for (const id of (await here.dirs(runbooks)).sort()) {
244
+ const path = runbookPath(config.paths, id);
245
+ const raw = await here.read(path);
246
+ if (raw === undefined) {
247
+ problems.push({
248
+ file: `${runbooks}/${id}`,
249
+ message: `no ${RUNBOOK_FILE}: a runbook's folder holds it`,
250
+ });
251
+ continue;
252
+ }
253
+ problems.push(...checkRunbook(path, raw, components));
254
+ const steps = parseRunbook(raw).steps.map((s) => s.id);
255
+ const dir = executionsDir(config.paths, id);
256
+ for (const f of (await here.list(dir)).sort()) {
257
+ if (!/^\d+\.md$/.test(f)) {
258
+ problems.push({ file: `${dir}/${f}`, message: "an execution is numbered: <n>.md" });
259
+ continue;
260
+ }
261
+ problems.push(...checkExecution(`${dir}/${f}`, (await here.read(`${dir}/${f}`)) ?? "", steps));
262
+ }
263
+ }
264
+ return problems;
265
+ }
266
+ /**
267
+ * Tests tagged with an epic's IDs (`@req <epic>#X1`, `#E2`, `#C1.g1`) before
268
+ * catalog entries exist: the epic and the entry must exist. A
269
+ * repository without the epics directory is not the hub, and cannot tell.
270
+ */
271
+ async function checkEpicRefs(root, config, refs) {
272
+ if (refs.length === 0)
273
+ return [];
274
+ const hub = await hubEpics(root, config);
275
+ if (hub)
276
+ return checkRefsIn(refs, config, hub);
277
+ const dir = join(root, config.paths.epics);
278
+ if (!existsSync(dir))
279
+ return [];
280
+ return checkRefsIn(refs, config, (epicId) => fsTree(root).read(epicPath(config.paths, epicId)));
281
+ }
282
+ /**
283
+ * Outside the hub, the epics are the hub's agreed ones: its origin's
284
+ * default branch, read through its checkout. Undefined in the hub itself.
285
+ */
286
+ async function hubEpics(root, config) {
287
+ const ws = await workspace({ out: () => { }, err: () => { }, cwd: root }).catch(() => undefined);
288
+ if (!ws || ws.here.isHub)
289
+ return undefined;
290
+ const base = await originDefaultBranch(ws.hub.main);
291
+ const tree = gitTree(ws.hub.main, base ? `refs/remotes/origin/${base}` : "HEAD");
292
+ return (epic) => tree.read(epicPath(config.paths, epic));
293
+ }
294
+ async function checkRefsIn(refs, config, read) {
295
+ const epics = new Map();
296
+ const problems = [];
297
+ for (const m of refs) {
298
+ const [epicId = "", id = ""] = m.ref.split("#");
299
+ if (!epics.has(epicId)) {
300
+ const text = await read(epicId);
301
+ if (text === undefined)
302
+ epics.set(epicId, undefined);
303
+ else {
304
+ const ids = new Set();
305
+ for (const e of parseEpic(text).entries) {
306
+ ids.add(e.id);
307
+ if (e.type === "C")
308
+ for (const f of e.fields)
309
+ ids.add(`${e.id}.${f.key}`);
310
+ }
311
+ epics.set(epicId, ids);
312
+ }
313
+ }
314
+ const ids = epics.get(epicId);
315
+ if (!ids)
316
+ problems.push({
317
+ file: m.file,
318
+ line: m.line,
319
+ message: `@req ${m.ref}: no ${epicPath(config.paths, epicId)}`,
320
+ });
321
+ else if (!ids.has(id)) {
322
+ problems.push({
323
+ file: m.file,
324
+ line: m.line,
325
+ message: `@req ${m.ref}: epic ${epicId} has no ${id}`,
326
+ });
327
+ }
328
+ }
329
+ return problems;
330
+ }
331
+ /**
332
+ * Checks of the work item this checkout is on, by its branch `cupola/<id>`.
333
+ * Only a fix has its own: it is measured against where it left origin's
334
+ * default branch.
335
+ */
336
+ async function checkWork(root, config) {
337
+ let branch;
338
+ try {
339
+ branch = await git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
340
+ }
341
+ catch {
342
+ return [];
343
+ }
344
+ const id = /^cupola\/(.+)$/.exec(branch)?.[1];
345
+ if (!id)
346
+ return [];
347
+ let doc;
348
+ try {
349
+ doc = await findSpecDocument(fsTree(root), config, id);
350
+ }
351
+ catch {
352
+ return [];
353
+ }
354
+ if (doc.kind !== "fix")
355
+ return [];
356
+ const own = resolveComponents(config).find((c) => c.name === doc.component)?.code?.dir;
357
+ const target = await originDefaultBranch(root);
358
+ if (!target) {
359
+ return [
360
+ { file: ".", message: "cannot tell origin's default branch, so the fix cannot be checked" },
361
+ ];
362
+ }
363
+ // Measured from where the fix left origin's default branch as it is now, so that main
364
+ // merged into the fix's branch is not taken for the fix's own change.
365
+ let base;
366
+ try {
367
+ await git(root, ["fetch", "--quiet", "origin", target]);
368
+ base = await git(root, ["merge-base", "HEAD", "FETCH_HEAD"]);
369
+ }
370
+ catch {
371
+ return [
372
+ { file: ".", message: `cannot fetch origin's ${target}, so the fix cannot be checked` },
373
+ ];
374
+ }
375
+ const dirs = behaviorDirs(config, await repoHere({ out: () => { }, err: () => { }, cwd: root }, root, config)).map((d) => d.dir);
376
+ // Code mounted here is measured the same way, from where its branch left its own default branch.
377
+ const codeAt = async (dir) => {
378
+ const there = join(root, dir);
379
+ const own = await originDefaultBranch(there);
380
+ if (!own)
381
+ return undefined;
382
+ try {
383
+ await git(there, ["fetch", "--quiet", "origin", own]);
384
+ return await git(there, ["merge-base", "HEAD", "FETCH_HEAD"]);
385
+ }
386
+ catch {
387
+ return undefined;
388
+ }
389
+ };
390
+ // A repository whose base cannot be told is left out of both sides, and said so.
391
+ const measured = [];
392
+ const bases = new Map();
393
+ const unmeasured = [];
394
+ for (const dir of codeDirs(config)) {
395
+ if (!existsSync(join(root, dir, ".git")))
396
+ continue;
397
+ const at = await codeAt(dir);
398
+ if (at) {
399
+ measured.push(dir);
400
+ bases.set(dir, at);
401
+ }
402
+ else if (dir === own)
403
+ // Only the fix's own code matters: another repository that cannot be measured is left out.
404
+ unmeasured.push({
405
+ file: dir,
406
+ message: `cannot tell where ${dir} left its default branch, so the fix's code there cannot be checked`,
407
+ });
408
+ }
409
+ const before = await findAllMarkers(root, measured, dirs, {
410
+ hub: base,
411
+ codeAt: async (dir) => bases.get(dir),
412
+ });
413
+ const after = await findAllMarkers(root, measured, dirs);
414
+ const diff = await git(root, ["diff", "-U0", base, "--", ...dirs.map((d) => `${d}/*.md`)]);
415
+ return [...unmeasured, ...checkFixMarkers(before, after), ...checkFixCatalog(diff)];
416
+ }
417
+ /**
418
+ * Where each code repository's markers are read: a work's own
419
+ * mounted checkout, on its work branch, as it is; otherwise — not mounted
420
+ * here, or a checkout on its default branch that is never pulled — the
421
+ * repository as merged, at its origin's default branch.
422
+ */
423
+ async function codeSources(root, config, ws) {
424
+ const out = [];
425
+ const seen = new Set();
426
+ for (const c of resolveComponents(config)) {
427
+ if (!c.code || seen.has(c.code.dir))
428
+ continue;
429
+ seen.add(c.code.dir);
430
+ const { dir, repo } = c.code;
431
+ const mounted = join(root, dir);
432
+ let path = mounted;
433
+ if (existsSync(join(mounted, ".git"))) {
434
+ const branch = await git(mounted, ["symbolic-ref", "--quiet", "--short", "HEAD"]).catch(() => "");
435
+ const own = await originDefaultBranch(mounted);
436
+ if (branch !== "" && branch !== own) {
437
+ out.push({ dir, path: mounted });
438
+ continue;
439
+ }
440
+ }
441
+ else {
442
+ try {
443
+ path = ws ? ws.checkout(repo).main : mounted;
444
+ }
445
+ catch {
446
+ continue; // not cloned: nothing to read
447
+ }
448
+ if (!existsSync(join(path, ".git")))
449
+ continue;
450
+ }
451
+ const own = await originDefaultBranch(path);
452
+ if (!own) {
453
+ out.push({ dir, path });
454
+ continue;
455
+ }
456
+ await git(path, [
457
+ "fetch",
458
+ "--quiet",
459
+ "origin",
460
+ `+refs/heads/${own}:refs/remotes/origin/${own}`,
461
+ ]).catch(() => "");
462
+ out.push({ dir, path, ref: `refs/remotes/origin/${own}` });
463
+ }
464
+ return out;
465
+ }
466
+ /** Where code in repositories of its own is mounted in the hub's tree. */
467
+ function codeDirs(config) {
468
+ return [...new Set(resolveComponents(config).flatMap((c) => (c.code ? [c.code.dir] : [])))];
469
+ }
470
+ /** The repository this checkout is, for its catalog; the hub when it cannot tell. */
471
+ async function repoHere(io, root, config) {
472
+ const ws = await workspace({ ...io, cwd: root }).catch(() => undefined);
473
+ return ws?.here.slug ?? (await identifyRepo(root, config)) ?? config.hub;
474
+ }
@@ -0,0 +1,105 @@
1
+ import { forgetRemotes } from "../git.js";
2
+ import { MissingWorkError } from "../work.js";
3
+ import { workspace } from "../workspace.js";
4
+ import { caseStatus, describe, workStatus } from "./status.js";
5
+ /** The gates of an epic's lifecycle a session waits on: the human merges, then the work goes on. */
6
+ const WAITED = ["start", "acceptance", "release"];
7
+ const INTERVAL_S = 60;
8
+ /** Readings that fail in a row before the wait gives up: the code host is gone, not slow. */
9
+ const FAILURES = 10;
10
+ function seconds(value, flag) {
11
+ if (value === undefined)
12
+ return undefined;
13
+ const n = Number(value);
14
+ if (!Number.isFinite(n) || n <= 0)
15
+ throw new Error(`${flag} takes seconds, not ${value}`);
16
+ return n;
17
+ }
18
+ /** What a change of status is: where it stands and what comes next. */
19
+ function key(r) {
20
+ return JSON.stringify([r.status, r.gate, r.next.kind, r.next.command ?? null]);
21
+ }
22
+ /**
23
+ * `cupola wait <work> [--timeout <s>] [--interval <s>]`: waits, without a
24
+ * model running, until a work item at a gate of its epic's lifecycle (start,
25
+ * acceptance, release) moves on — the human merged, reacted (a comment, a try, a No-Go: its
26
+ * next is then `cupola-respond`, which the waiting session runs), or closed
27
+ * it — and prints its new status. A work at a gate with reactions not
28
+ * processed yet is not waited on: they are processed first. Nor is a work at
29
+ * no such gate: running,
30
+ * done, awaiting a decision (answered in the session), blocked (the human fixes it, then
31
+ * resumes the run), or a case (resolution is the case's own, judged later).
32
+ */
33
+ export async function wait(io, id, opts) {
34
+ const timeout = seconds(opts.timeout, "--timeout");
35
+ const interval = seconds(opts.interval, "--interval") ?? INTERVAL_S;
36
+ const ws = await workspace(io);
37
+ const root = ws.here.isHub ? ws.root : ws.hub.main;
38
+ const read = () => {
39
+ // Each reading asks origin again: what one command learned is not kept across readings.
40
+ forgetRemotes();
41
+ return workStatus(io, root, ws.config, id);
42
+ };
43
+ let first;
44
+ try {
45
+ first = await read();
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof MissingWorkError))
49
+ throw error;
50
+ // A case, not a work item: its resolution is the case's own gate, judged later.
51
+ const found = await caseStatus(io, root, ws.config, id);
52
+ if (!found)
53
+ throw error;
54
+ io.out(opts.json
55
+ ? JSON.stringify({ waited: false, changed: false, next: found.next, status: found })
56
+ : `nothing to wait for; a case's resolution is judged later. ${describe(found)}`);
57
+ return 0;
58
+ }
59
+ const out = (result, s, next = s.next) => io.out(opts.json
60
+ ? JSON.stringify({ ...result, next, status: s })
61
+ : `${result.changed ? "moved on" : result.timedOut ? "timed out; still" : "nothing to wait for;"} ${describe(s)}${next !== s.next ? `\nnext: ${next.command}` : ""}`);
62
+ if (first.turn !== "human" || !(first.gate && WAITED.includes(first.gate))) {
63
+ out({ waited: false, changed: false }, first);
64
+ return 0;
65
+ }
66
+ const now = () => (io.now?.() ?? new Date()).getTime();
67
+ const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
68
+ const deadline = timeout === undefined ? Number.POSITIVE_INFINITY : now() + timeout * 1000;
69
+ let failures = 0;
70
+ for (;;) {
71
+ if (now() >= deadline) {
72
+ out({ waited: true, changed: false, timedOut: true }, first);
73
+ return 0;
74
+ }
75
+ await sleep(Math.min(interval * 1000, Math.max(0, deadline - now())));
76
+ let current;
77
+ try {
78
+ current = await read();
79
+ failures = 0;
80
+ }
81
+ catch (error) {
82
+ // A work that is gone is not coming back: only a reading that could not be made is retried.
83
+ if (error instanceof MissingWorkError)
84
+ throw error;
85
+ failures += 1;
86
+ if (failures >= FAILURES)
87
+ throw error;
88
+ io.err(`warning: could not read the status (${error.message}); trying again`);
89
+ continue;
90
+ }
91
+ if (key(current) !== key(first)) {
92
+ // Merged at acceptance or release: what follows is the gate's own command (merge it, then run it),
93
+ // though the status, derived from the merge alone, says there is nothing left.
94
+ const merged = first.gate !== "start" && current.change?.state === "merged" && first.next.command
95
+ ? {
96
+ kind: "run",
97
+ text: `Merged: ${first.next.command}.`,
98
+ command: first.next.command,
99
+ }
100
+ : current.next;
101
+ out({ waited: true, changed: true }, current, merged);
102
+ return 0;
103
+ }
104
+ }
105
+ }