@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
package/dist/main.js ADDED
@@ -0,0 +1,866 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { listAdrs, renderAdrList } from "./adr.js";
7
+ import { changeAnswer, changeChecks, changeClose, changeDraft, changeFeedback, changeMerge, changeOpen, changeReady, changeReview, changeShow, } from "./commands/change.js";
8
+ import { epicAbort, epicBranch, epicSync } from "./commands/epic.js";
9
+ import { executionRecord, executionStart } from "./commands/execution.js";
10
+ import { initCommand, updateCommand } from "./commands/install.js";
11
+ import { listLocks } from "./commands/locks.js";
12
+ import { reactionAdd, reactionList, reactionReply, tryRemove, tryStart, } from "./commands/reaction.js";
13
+ import { runEnd, runFinish, runNext, runRecord } from "./commands/run.js";
14
+ import { claudeItems, SQUASH_JQ, setup } from "./commands/setup.js";
15
+ import { specInit } from "./commands/spec.js";
16
+ import { status } from "./commands/status.js";
17
+ import { check, trace } from "./commands/trace.js";
18
+ import { wait } from "./commands/wait.js";
19
+ import { workClose, workFile, workList, workLog, workReopen, workShow } from "./commands/work.js";
20
+ import { cloneUrl, workspaceSetup } from "./commands/workspace.js";
21
+ import { worktree, worktreeRemove } from "./commands/worktree.js";
22
+ import { CONFIG_PATH, ConfigError, cloneUrlOf, DEFAULT_PATHS, hostKindOf, loadConfig, parseConfig, resolveComponents, } from "./config.js";
23
+ import { today } from "./day.js";
24
+ import { E2E_PROFILE, parseProfile } from "./e2e.js";
25
+ import { CC_SDD_VERSION, ENGINE_LANGUAGE, specPath } from "./engine/cc-sdd.js";
26
+ import { forgetRemotes, git, originDefaultBranch } from "./git.js";
27
+ import { gh } from "./host/github.js";
28
+ import { readManifest } from "./install.js";
29
+ import { terminalIo } from "./io.js";
30
+ import { repoRoot } from "./repo.js";
31
+ import { templateKinds, templatePath } from "./templates.js";
32
+ import { version } from "./version.js";
33
+ import { identifyRepo, NotClonedError, reposOf, slugsOf, workspace, } from "./workspace.js";
34
+ const USAGE = `Usage: cupola <command> [options]
35
+
36
+ Commands:
37
+ init Write .cupola/config.json and install Cupola (--config-file <file>, or --hub, --component name[:path[:role]], --language, --tracker, --reviewer). The dialogue is the cupola-init skill
38
+ setup claude|host What Claude Code and the code host need, item by item (--apply makes the items it can; claude: --scope project|local, --subagents <n>)
39
+ update Install or update Cupola's files (--keep <path>, --take-new <path> for local edits; a directory chooses every file under it)
40
+ doctor Validate the configuration and its copies, managed files edited here, Claude Code's permissions and limits, e2e environments; repositories still to set up are listed as pending (--host: also the code host's authentication and squash merges)
41
+ workspace setup Clone the other repositories under the hub (several repositories)
42
+ run next <work> The next phase of a work item and what it is given
43
+ run record <work> Record a phase's outcome (--outcome <file>)
44
+ run finish <work> File case drafts, remove the record, describe the change, mark it ready (--body-file <file>)
45
+ run end <work> Carry out a card that ends the run: abort, or file a case (to-case)
46
+ worktree <work> Create or find the work's worktree (--from <ref>; --epic-branch for an epic's own; --remove after the merge; --component <name> for work in that component's repository)
47
+ change open <work> Push the work's branch and open its change, a draft unless --ready (--title, --body-file)
48
+ change show <work> The work's change (--release: the epic's release, from any branch)
49
+ change draft <work> Turn the change back into a draft: after a No-Go, or an epic's change while cards are open (--body-file: describe it anew)
50
+ change ready <work> Mark the change ready for its gate: an epic's change once no card is open (--body-file: describe it anew)
51
+ change close <work> Close the change without merging, its branch kept (--body-file <why>)
52
+ change merge <work> For people: merge the ready changes on a git host, each as one commit (--release: the epic's release)
53
+ change review <work> Ask the configured reviewer to review the change
54
+ change feedback <work> The reviewer's open feedback, and whether it answered (--since <time>, --wait <seconds>)
55
+ change answer <work> Answer the reviewer's feedback (--feedback <id> --body-file <file> [--settle])
56
+ reaction list <work> The reactions of the work's gate (comment, try, No-Go), on its change and from sessions, and which are not processed
57
+ reaction reply <work> Answer a reaction, which processes it (--reaction <id> --body-file <file>; a session's needs no body)
58
+ reaction add <work> Keep a reaction given in a session for the next gate (--kind comment|try|no-go [--body-file <words>] [--who <name>])
59
+ try start <work> A try branch from the change's head, pushed, in a worktree of its own
60
+ try remove <work> Delete the work's tries once its gate is passed
61
+ change checks <work> The change's CI result (--wait <seconds>)
62
+ work list Every case in the tracker, open and closed
63
+ work show <case> A case's document
64
+ work file File a case or a run's case draft (--body-file <file>)
65
+ work log <case> Append a line to a case's Log (--body-file <file>)
66
+ work close <case> Resolution: the problem is gone; log the human's words and close the case (--body-file <file>; --without-epic for a case that needs no work)
67
+ work reopen <case> Resolution: not solved yet; log why, and the epics judged no longer count (--body-file <file>)
68
+ template <kind> Print a template this method serves (card, changes/catalog, …)
69
+ trace [<area>] Requirements → tests → latest results (--index regenerates the catalog index)
70
+ check Self-check the catalog and Cupola documents before opening a change
71
+ status <work> Where a work item stands, whose turn it is, and what comes next (--case: a case only)
72
+ locks [<component>] The locks on shared e2e environments: who holds each, since when, and the id to take it over
73
+ wait <work> At start, acceptance, or release: waits, with no model running, until the human merges, reacts, or closes the change, then prints the new status (--timeout <s>, --interval <s>)
74
+ adr list The decision records, newest first, derived from their front matter (--applies-to x,y)
75
+ epic branch <epic> Create the epic branch of an agreed epic with two or more specs
76
+ epic sync <epic> Merge origin's default branch into the epic branch
77
+ epic abort <epic> Carry out an abort: close the epic's changes, record it on its cases (--body-file <reason>)
78
+ execution start <runbook> Start an execution of an agreed runbook: its record on its own branch, a draft change (--for <epic|case>; --param <name>=<value> for each param, for a case)
79
+ execution record <execution> Record a step in the human's words (--step <P#|X#> --result done|stopped), or the end (--result finished|given-up, marks the change ready); --body-file <line>
80
+ spec path <spec> Where the spec engine keeps a spec's documents
81
+ spec init <spec> Create a spec of an agreed epic on its branch (--epic <epic>)
82
+
83
+ Options:
84
+ --json Print machine-readable output (commands called by skills)
85
+ --session <id> The session running the work (run; or CUPOLA_SESSION)
86
+ --take-over <id> Release a marker left by a session that died (run next)
87
+ -h, --help
88
+ -v, --version`;
89
+ export async function main(argv, given) {
90
+ forgetRemotes();
91
+ const { values, positionals } = parseArgs({
92
+ args: argv,
93
+ allowPositionals: true,
94
+ strict: false,
95
+ options: {
96
+ help: { type: "boolean", short: "h" },
97
+ version: { type: "boolean", short: "v" },
98
+ json: { type: "boolean" },
99
+ session: { type: "string" },
100
+ "take-over": { type: "string" },
101
+ outcome: { type: "string" },
102
+ title: { type: "string" },
103
+ "body-file": { type: "string" },
104
+ base: { type: "string" },
105
+ ready: { type: "boolean" },
106
+ release: { type: "boolean" },
107
+ from: { type: "string" },
108
+ index: { type: "boolean" },
109
+ "applies-to": { type: "string", multiple: true },
110
+ remove: { type: "boolean" },
111
+ since: { type: "string" },
112
+ wait: { type: "string" },
113
+ timeout: { type: "string" },
114
+ interval: { type: "string" },
115
+ feedback: { type: "string" },
116
+ reaction: { type: "string" },
117
+ kind: { type: "string" },
118
+ who: { type: "string" },
119
+ settle: { type: "boolean" },
120
+ keep: { type: "string", multiple: true },
121
+ "take-new": { type: "string", multiple: true },
122
+ hub: { type: "string" },
123
+ component: { type: "string", multiple: true },
124
+ language: { type: "string" },
125
+ tracker: { type: "string" },
126
+ reviewer: { type: "string" },
127
+ host: { type: "boolean" },
128
+ "config-file": { type: "string" },
129
+ apply: { type: "boolean" },
130
+ scope: { type: "string" },
131
+ subagents: { type: "string" },
132
+ epic: { type: "string" },
133
+ case: { type: "boolean" },
134
+ "epic-branch": { type: "boolean" },
135
+ step: { type: "string" },
136
+ for: { type: "string" },
137
+ param: { type: "string", multiple: true },
138
+ result: { type: "string" },
139
+ "without-epic": { type: "boolean" },
140
+ },
141
+ });
142
+ const [command] = positionals;
143
+ const json = values.json === true;
144
+ // JSON is printed as it is; anything for a person to read has control characters taken out.
145
+ const io = json ? given : terminalIo(given);
146
+ const usage = (line) => {
147
+ io.err(`Usage: ${line}\n\n${USAGE}`);
148
+ return 1;
149
+ };
150
+ const guard = async (f) => {
151
+ try {
152
+ return await f();
153
+ }
154
+ catch (error) {
155
+ return fail(io, json, error);
156
+ }
157
+ };
158
+ if (values.version) {
159
+ io.out(version());
160
+ return 0;
161
+ }
162
+ if (values.help || command === undefined) {
163
+ io.out(USAGE);
164
+ return command === undefined && !values.help ? 1 : 0;
165
+ }
166
+ switch (command) {
167
+ case "init":
168
+ case "update": {
169
+ const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
170
+ const opts = {
171
+ json,
172
+ keep: list(values.keep),
173
+ takeNew: list(values["take-new"]),
174
+ hub: str(values.hub),
175
+ components: list(values.component),
176
+ language: str(values.language),
177
+ tracker: str(values.tracker),
178
+ reviewer: str(values.reviewer),
179
+ configFile: str(values["config-file"]),
180
+ };
181
+ return guard(() => (command === "init" ? initCommand(io, opts) : updateCommand(io, opts)));
182
+ }
183
+ case "setup": {
184
+ const what = positionals[1];
185
+ if (!what)
186
+ return usage("cupola setup claude|host [--apply]");
187
+ return guard(() => setup(io, what, {
188
+ json,
189
+ apply: values.apply === true,
190
+ scope: str(values.scope),
191
+ subagents: str(values.subagents),
192
+ }));
193
+ }
194
+ case "workspace": {
195
+ if (positionals[1] !== "setup")
196
+ return usage("cupola workspace setup");
197
+ return guard(() => workspaceSetup(io, { json }));
198
+ }
199
+ case "doctor":
200
+ return doctor(io, values.json === true, values.host === true);
201
+ case "wait": {
202
+ const [, id] = positionals;
203
+ if (!id)
204
+ return usage("cupola wait <work> [--timeout <seconds>] [--interval <seconds>]");
205
+ return guard(() => wait(io, id, {
206
+ json,
207
+ timeout: values.timeout,
208
+ interval: values.interval,
209
+ }));
210
+ }
211
+ case "status": {
212
+ const [, id] = positionals;
213
+ if (!id) {
214
+ io.err(`Usage: cupola status <work> [--json]\n\n${USAGE}`);
215
+ return 1;
216
+ }
217
+ try {
218
+ return await status(io, id, values.json === true, values.case === true);
219
+ }
220
+ catch (error) {
221
+ return fail(io, values.json === true, error);
222
+ }
223
+ }
224
+ case "run": {
225
+ const [, sub, id] = positionals;
226
+ const run = { next: runNext, record: runRecord, finish: runFinish, end: runEnd }[sub ?? ""];
227
+ if (!run || !id) {
228
+ io.err(`Usage: cupola run next|record|finish|end <work> [options]\n\n${USAGE}`);
229
+ return 1;
230
+ }
231
+ const opts = {
232
+ json,
233
+ session: str(values.session),
234
+ takeOver: str(values["take-over"]),
235
+ outcome: str(values.outcome),
236
+ bodyFile: str(values["body-file"]),
237
+ };
238
+ return guard(() => run(io, id, opts));
239
+ }
240
+ case "worktree": {
241
+ const [, id] = positionals;
242
+ if (!id)
243
+ return usage("cupola worktree <work> [--from <ref> | --remove]");
244
+ if (values.remove === true) {
245
+ return guard(() => worktreeRemove(io, id, {
246
+ json,
247
+ epicBranch: values["epic-branch"] === true,
248
+ component: first(values.component),
249
+ }));
250
+ }
251
+ return guard(() => worktree(io, id, {
252
+ json,
253
+ from: str(values.from),
254
+ epicBranch: values["epic-branch"] === true,
255
+ component: first(values.component),
256
+ }));
257
+ }
258
+ case "change": {
259
+ const [, sub, id] = positionals;
260
+ const run = {
261
+ open: changeOpen,
262
+ show: changeShow,
263
+ draft: changeDraft,
264
+ ready: changeReady,
265
+ close: changeClose,
266
+ merge: changeMerge,
267
+ review: changeReview,
268
+ feedback: changeFeedback,
269
+ answer: changeAnswer,
270
+ checks: changeChecks,
271
+ }[sub ?? ""];
272
+ if (!run || !id) {
273
+ return usage("cupola change open|show|draft|ready|close|merge|review|feedback|answer|checks <work> [options]");
274
+ }
275
+ const opts = {
276
+ json,
277
+ title: str(values.title),
278
+ bodyFile: str(values["body-file"]),
279
+ base: str(values.base),
280
+ since: str(values.since),
281
+ wait: str(values.wait),
282
+ feedback: str(values.feedback),
283
+ settle: values.settle === true,
284
+ ready: values.ready === true,
285
+ release: values.release === true,
286
+ };
287
+ return guard(() => run(io, id, opts));
288
+ }
289
+ case "reaction":
290
+ case "try": {
291
+ const [, sub, id] = positionals;
292
+ const run = command === "reaction"
293
+ ? { list: reactionList, reply: reactionReply, add: reactionAdd }[sub ?? ""]
294
+ : { start: tryStart, remove: tryRemove }[sub ?? ""];
295
+ if (!run || !id)
296
+ return usage(command === "reaction"
297
+ ? "cupola reaction list|reply|add <work> [options]"
298
+ : "cupola try start|remove <work>");
299
+ const opts = {
300
+ json,
301
+ reaction: str(values.reaction),
302
+ kind: str(values.kind),
303
+ who: str(values.who),
304
+ bodyFile: str(values["body-file"]),
305
+ };
306
+ return guard(() => run(io, id, opts));
307
+ }
308
+ case "work": {
309
+ const [, sub, id] = positionals;
310
+ const opts = {
311
+ json,
312
+ bodyFile: str(values["body-file"]),
313
+ withoutEpic: values["without-epic"] === true,
314
+ };
315
+ const line = "cupola work list | show <case> | file --body-file <f> | log|close|reopen <case> --body-file <f> (close: --without-epic)";
316
+ if (sub === "list")
317
+ return guard(() => workList(io, opts));
318
+ if (sub === "file")
319
+ return guard(() => workFile(io, opts));
320
+ if (sub === "close" && id)
321
+ return guard(() => workClose(io, id, opts));
322
+ if (sub === "reopen" && id)
323
+ return guard(() => workReopen(io, id, opts));
324
+ if ((sub === "show" || sub === "log") && id) {
325
+ return guard(() => (sub === "show" ? workShow(io, id, opts) : workLog(io, id, opts)));
326
+ }
327
+ return usage(line);
328
+ }
329
+ case "trace": {
330
+ const [, area] = positionals;
331
+ return guard(() => trace(io, area, { json, index: values.index === true }));
332
+ }
333
+ case "locks": {
334
+ const [, component] = positionals;
335
+ return guard(() => listLocks(io, component, { json }));
336
+ }
337
+ case "check":
338
+ return guard(() => check(io, { json }));
339
+ case "adr": {
340
+ if (positionals[1] !== "list")
341
+ return usage("cupola adr list [--applies-to <x>[,<y>…]]");
342
+ return guard(async () => {
343
+ const { root, dir } = await adrPlace(io);
344
+ const appliesTo = values["applies-to"] ?? [];
345
+ const { adrs, problems } = await listAdrs(root, dir, appliesTo
346
+ .flatMap((v) => v.split(","))
347
+ .map((v) => v.trim())
348
+ .filter(Boolean));
349
+ if (json)
350
+ io.out(JSON.stringify({ adrs, problems }));
351
+ else {
352
+ io.out(renderAdrList(adrs));
353
+ for (const p of problems)
354
+ io.out(`${p.file}: ${p.message}`);
355
+ }
356
+ return problems.length > 0 ? 1 : 0;
357
+ });
358
+ }
359
+ case "epic": {
360
+ const [, sub, id] = positionals;
361
+ if (sub === "branch" && id)
362
+ return guard(() => epicBranch(io, id, { json }));
363
+ if (sub === "sync" && id)
364
+ return guard(() => epicSync(io, id, { json }));
365
+ if (sub === "abort" && id) {
366
+ return guard(() => epicAbort(io, id, { json, bodyFile: str(values["body-file"]) }));
367
+ }
368
+ return usage("cupola epic branch <epic> | epic sync <epic> | epic abort <epic> --body-file <f>");
369
+ }
370
+ case "execution": {
371
+ const [, sub, id] = positionals;
372
+ const opts = {
373
+ json,
374
+ for: str(values.for),
375
+ params: Array.isArray(values.param)
376
+ ? values.param.filter((p) => typeof p === "string")
377
+ : [],
378
+ bodyFile: str(values["body-file"]),
379
+ step: str(values.step),
380
+ result: str(values.result),
381
+ };
382
+ if (sub === "start" && id)
383
+ return guard(() => executionStart(io, id, opts));
384
+ if (sub === "record" && id)
385
+ return guard(() => executionRecord(io, id, opts));
386
+ return usage("cupola execution start <runbook> --for <epic|case> [--param <name>=<value>…] | execution record <execution> (--step <P#> --result done|stopped | --result finished|given-up) --body-file <f>");
387
+ }
388
+ case "spec": {
389
+ const [, sub, spec] = positionals;
390
+ if (sub === "init" && spec) {
391
+ return guard(() => specInit(io, spec, { epic: str(values.epic), json }));
392
+ }
393
+ if (sub !== "path" || !spec)
394
+ return usage("cupola spec path <spec> | spec init <spec> --epic <epic>");
395
+ return guard(async () => {
396
+ const root = await repoRoot(io.cwd);
397
+ const path = specPath(spec);
398
+ const exists = existsSync(join(root, path));
399
+ io.out(json ? JSON.stringify({ spec, path, exists }) : path);
400
+ return 0;
401
+ });
402
+ }
403
+ case "template": {
404
+ const [, kind] = positionals;
405
+ if (!kind)
406
+ return usage(`cupola template <kind>; kinds: ${[...templateKinds().keys()].sort().join(", ")}`);
407
+ return guard(async () => {
408
+ const path = templatePath(kind);
409
+ // Today comes filled in, in the configured zone, so a record is dated as the CLI dates it.
410
+ const text = readFileSync(path, "utf8").replaceAll("{{YYYY-MM-DD}}", await today(io));
411
+ io.out(json ? JSON.stringify({ kind, path }) : text.trimEnd());
412
+ return 0;
413
+ });
414
+ }
415
+ default:
416
+ io.err(`Unknown command: ${command}\n\n${USAGE}`);
417
+ return 1;
418
+ }
419
+ }
420
+ /**
421
+ * Where the decision records are: this checkout when it holds them (the hub,
422
+ * or a worktree of it), otherwise the hub's checkout.
423
+ */
424
+ async function adrPlace(io) {
425
+ const root = await repoRoot(io.cwd);
426
+ try {
427
+ const ws = await workspace(io);
428
+ const dir = ws.config.paths.adr;
429
+ return { root: existsSync(join(root, dir)) ? root : ws.hub.main, dir };
430
+ }
431
+ catch {
432
+ return { root, dir: DEFAULT_PATHS.adr };
433
+ }
434
+ }
435
+ /** Cupola's own files that the repository's ignore rules would keep out of commits. */
436
+ async function ignoredFiles(root, config) {
437
+ const out = [];
438
+ const files = [CONFIG_PATH.replaceAll("\\", "/"), ".cupola/manifest.json"];
439
+ // A directory is probed by a document in it: `.cupola/*` with only `!.cupola/config.json`
440
+ // ignores them.
441
+ // Epics, runbooks, ADRs, and acceptance checks are the hub's; outside it, the epics are a copy
442
+ // kept out of git.
443
+ const slug = await identifyRepo(root, config).catch(() => undefined);
444
+ const hub = !slug || slug.toLowerCase() === config.hub.toLowerCase();
445
+ const { behavior, ...hubOnly } = config.paths;
446
+ for (const dir of [behavior, ".cupola/specs", ...(hub ? Object.values(hubOnly) : [])]) {
447
+ const ignored = await git(root, ["check-ignore", "-q", "--no-index", `${dir}/x.md`]).then(() => true, () => false);
448
+ if (ignored)
449
+ out.push(`${dir}/ is ignored by .gitignore: add \`!${dir}/\` so its documents can be committed`);
450
+ }
451
+ for (const path of files) {
452
+ // Exit 0: ignored and not tracked. A tracked file is never reported.
453
+ const ignored = await git(root, ["check-ignore", "-q", path]).then(() => true, () => false);
454
+ if (ignored)
455
+ out.push(`${path} is ignored by .gitignore: add \`!${path}\` so it can be committed`);
456
+ }
457
+ return out;
458
+ }
459
+ /**
460
+ * A diagnosis reports a remote that does not answer rather than waiting it out:
461
+ * a short limit and no retry, unlike the calls a run makes.
462
+ */
463
+ const DOCTOR_NETWORK = { timeoutMs: 15_000, retry: false };
464
+ async function doctor(io, json, host = false) {
465
+ try {
466
+ const root = await repoRoot(io.cwd);
467
+ const config = await loadConfig(root);
468
+ const components = resolveComponents(config);
469
+ const warnings = config.verification.test_reports.length === 0
470
+ ? [
471
+ 'verification.test_reports is empty: `cupola trace` finds tagged tests but shows no results; list where the test run writes JUnit XML (`node --test --test-reporter=junit --test-reporter-destination=reports/junit.xml`, vitest\'s `--reporter=junit`), e.g. ["reports/*.xml"]',
472
+ ]
473
+ : [];
474
+ warnings.push(...(await engineWarnings(inTree(root), ENGINE_LANGUAGE)));
475
+ if (!existsSync(join(root, ".kiro", "steering", "operations.md"))) {
476
+ warnings.push("no .kiro/steering/operations.md: compatibility, exposure, and unacceptable failures fall back to the safe side");
477
+ }
478
+ const across = await acrossRepositories(io, config);
479
+ warnings.push(...across.warnings);
480
+ warnings.push(...(await e2eWarnings(root, config, across.checkouts, across.here)));
481
+ warnings.push(...(await driftWarnings(root)));
482
+ const claude = await claudeItems(root, {
483
+ home: io.env?.HOME ?? homedir(),
484
+ env: io.env ?? {},
485
+ });
486
+ for (const i of claude)
487
+ if (i.state === "manual")
488
+ warnings.push(i.detail);
489
+ const claudeTodo = claude.filter((i) => i.state === "todo");
490
+ // The deny and ask rules are many: counted, not listed.
491
+ const lacking = [
492
+ ...claudeTodo
493
+ .filter((i) => /^(permission|limit) /.test(i.id))
494
+ .map((i) => i.id.replace(/^(permission|limit) /, "")),
495
+ ...["deny", "ask"].flatMap((list) => {
496
+ const n = claudeTodo.filter((i) => i.id.startsWith(`${list} `)).length;
497
+ return n > 0 ? [`${n} permissions.${list} rule${n > 1 ? "s" : ""}`] : [];
498
+ }),
499
+ ];
500
+ if (lacking.length > 0)
501
+ warnings.push(`Claude Code lacks ${lacking.join(", ")}: \`cupola setup claude\``);
502
+ if (host)
503
+ warnings.push(...(await hostWarnings(root, config)));
504
+ across.problems.push(...(await ignoredFiles(root, config)));
505
+ // `checkout` is where a component's documents are; `code.checkout`, where its code is when
506
+ // that is another repository mounted in the hub's tree. The code comes first, so that the
507
+ // hub's `repo` beside it reads as where the documents are.
508
+ const listed = components.map(({ code, name, role, ...c }) => ({
509
+ name,
510
+ role,
511
+ ...(code ? { code: { ...code, checkout: across.checkouts.get(code.repo) } } : {}),
512
+ ...c,
513
+ checkout: across.checkouts.get(c.repo),
514
+ }));
515
+ // Repositories not set up yet are not problems: the setup goes on, and doctor is ok once it is done.
516
+ const ok = across.problems.length === 0 && across.pending.length === 0;
517
+ if (json) {
518
+ io.out(JSON.stringify({
519
+ ok,
520
+ problems: across.problems,
521
+ pending: across.pending,
522
+ warnings,
523
+ components: listed,
524
+ paths: config.paths,
525
+ }));
526
+ }
527
+ else {
528
+ io.out(ok
529
+ ? "Configuration is valid."
530
+ : across.problems.length > 0
531
+ ? "Configuration has problems:"
532
+ : "Configuration is valid; repositories still to set up:");
533
+ for (const p of across.problems)
534
+ io.out(`problem: ${p}`);
535
+ for (const p of across.pending)
536
+ io.out(`pending: ${p}`);
537
+ const where = (repo, path, checkout) => `${repo} ${path}${checkout ? ` (${checkout})` : ""}`;
538
+ for (const c of listed)
539
+ io.out(c.code
540
+ ? ` ${c.name}: code ${where(c.code.repo, c.code.path, c.code.checkout)}; documents in ${where(c.repo, c.path, c.checkout)} — ${c.role}`
541
+ : ` ${c.name}: ${where(c.repo, c.path, c.checkout)} — ${c.role}`);
542
+ io.out(` paths: ${Object.entries(config.paths)
543
+ .map(([k, v]) => `${k} ${v}`)
544
+ .join(", ")}`);
545
+ for (const w of warnings)
546
+ io.out(`warning: ${w}`);
547
+ }
548
+ return ok ? 0 : 1;
549
+ }
550
+ catch (error) {
551
+ const problems = error instanceof ConfigError ? error.problems : [];
552
+ const message = error instanceof Error ? error.message : String(error);
553
+ if (json) {
554
+ io.out(JSON.stringify({ ok: false, error: message, problems }));
555
+ }
556
+ else {
557
+ io.err(message);
558
+ for (const p of problems)
559
+ io.err(` ${p}`);
560
+ }
561
+ return 1;
562
+ }
563
+ }
564
+ /**
565
+ * Managed files edited here: `cupola update` keeps them, and
566
+ * reports a conflict once Cupola changes them too. A missing one is put back.
567
+ */
568
+ async function driftWarnings(root) {
569
+ const manifest = await readManifest(root);
570
+ if (!manifest)
571
+ return [];
572
+ const out = [];
573
+ if (manifest.package !== version() && manifest.package !== "0.0.0" && version() !== "0.0.0")
574
+ out.push(`installed by Cupola ${manifest.package}; this CLI is ${version()}: \`cupola update\``);
575
+ for (const [path, file] of Object.entries(manifest.files)) {
576
+ if (file.owner !== "cupola" && file.owner !== "engine-patched")
577
+ continue;
578
+ const full = join(root, path);
579
+ if (!existsSync(full)) {
580
+ out.push(`${path} is missing: \`cupola update\` installs it again`);
581
+ continue;
582
+ }
583
+ const sha = createHash("sha256").update(readFileSync(full, "utf8")).digest("hex");
584
+ if (sha !== file.sha256)
585
+ out.push(`${path} was edited here: \`cupola update\` keeps it, and asks once Cupola changes it too (--keep or --take-new)`);
586
+ }
587
+ return out;
588
+ }
589
+ /** The code host (`doctor --host`): authentication, and squash merges on every repository. */
590
+ function derivedUrl(hubUrl, slug) {
591
+ try {
592
+ return hubUrl ? cloneUrl(hubUrl, slug) : undefined;
593
+ }
594
+ catch {
595
+ return undefined;
596
+ }
597
+ }
598
+ async function hostWarnings(root, config) {
599
+ // Every repository a change is merged into, code included.
600
+ const all = reposOf(config);
601
+ const plain = all.filter((slug) => hostKindOf(config, slug) === "git");
602
+ const slugs = all.filter((slug) => !plain.includes(slug));
603
+ const out = [];
604
+ // A git host is reached through origin; its URL is the one it names, or the hub's with its name.
605
+ const hubUrl = await git(root, ["remote", "get-url", "origin"]).catch(() => "");
606
+ for (const slug of plain) {
607
+ const url = cloneUrlOf(config, slug) ?? derivedUrl(hubUrl, slug);
608
+ if (!url) {
609
+ out.push(`${slug}: no clone URL; name it in repositories.${slug}.url`);
610
+ continue;
611
+ }
612
+ try {
613
+ await git(root, ["ls-remote", "--heads", url], { timeoutMs: 30_000 });
614
+ }
615
+ catch {
616
+ out.push(`${slug}: ${url} cannot be reached (git's credentials for it)`);
617
+ }
618
+ }
619
+ if (slugs.length === 0)
620
+ return out;
621
+ try {
622
+ await gh(root, ["auth", "status"]);
623
+ }
624
+ catch {
625
+ return [...out, "the code host is not authenticated: `gh auth login`"];
626
+ }
627
+ const squashes = await Promise.all(slugs.map((slug) => gh(root, ["api", `repos/${slug}`, "--jq", SQUASH_JQ]).catch(() => undefined)));
628
+ return [
629
+ ...out,
630
+ ...slugs.flatMap((slug, i) => {
631
+ const squash = squashes[i];
632
+ if (squash === undefined)
633
+ return [`${slug}: its settings could not be read`];
634
+ if (squash !== "true")
635
+ return [`${slug} does not squash merges titled by the change: \`cupola setup host\``];
636
+ return [];
637
+ }),
638
+ ];
639
+ }
640
+ /**
641
+ * Components no e2e environment runs: their work is verified only
642
+ * by tests that run without the platform. Said here so that it is a choice, not
643
+ * a silent fallback. Each repository's profile is read where its configuration
644
+ * is: this one's here, the others' on origin's default branch.
645
+ */
646
+ async function e2eWarnings(root, config, checkouts, here) {
647
+ const run = new Set();
648
+ const profiles = await Promise.all(slugsOf(config).map(async (slug) => {
649
+ const main = checkouts.get(slug);
650
+ if (slug === here) {
651
+ const path = join(root, E2E_PROFILE);
652
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
653
+ }
654
+ if (main === undefined)
655
+ return undefined;
656
+ const branch = (await originDefaultBranch(main, DOCTOR_NETWORK)) ?? "main";
657
+ return git(main, ["show", `origin/${branch}:${E2E_PROFILE}`]).catch(() => undefined);
658
+ }));
659
+ for (const raw of profiles) {
660
+ if (raw === undefined)
661
+ continue;
662
+ for (const e of parseProfile(raw).environments) {
663
+ run.add(e.component);
664
+ for (const c of e.covers)
665
+ run.add(c);
666
+ }
667
+ }
668
+ return resolveComponents(config)
669
+ .filter((c) => !run.has(c.name))
670
+ .map((c) => `no e2e environment runs ${c.name}: its work is verified only by tests that run without the platform, and a requirement verified \`e2e\` blocks; \`cupola-e2e-setup ${c.name}\` builds one`);
671
+ }
672
+ /**
673
+ * With several repositories: every repository is cloned under
674
+ * the hub, and its copy of the configuration on origin's default branch is the
675
+ * hub's. A copy that differs is a problem: it would route work elsewhere. A
676
+ * repository not cloned yet, or with no copy on its default branch yet, is
677
+ * pending: the setup is not done, nothing is wrong.
678
+ */
679
+ async function acrossRepositories(io, config) {
680
+ const problems = [];
681
+ const pending = [];
682
+ const warnings = [];
683
+ const checkouts = new Map();
684
+ const slugs = slugsOf(config);
685
+ if (slugs.length === 1) {
686
+ checkouts.set(config.hub, ".");
687
+ if (reposOf(config).length > 1)
688
+ await codeRepositories(io, problems, pending, warnings, checkouts);
689
+ return { problems, pending, warnings, checkouts, here: config.hub };
690
+ }
691
+ let ws;
692
+ try {
693
+ ws = await workspace(io);
694
+ }
695
+ catch (error) {
696
+ problems.push(error.message);
697
+ return { problems, pending, warnings, checkouts, here: undefined };
698
+ }
699
+ const want = canonicalJson(config);
700
+ // Each repository is checked at once; the results are gathered in the configuration's order.
701
+ const results = await Promise.all(slugs.map(async (slug) => {
702
+ const r = {
703
+ problems: [],
704
+ pending: [],
705
+ warnings: [],
706
+ main: undefined,
707
+ };
708
+ let main;
709
+ try {
710
+ main = ws.checkout(slug).main;
711
+ }
712
+ catch (error) {
713
+ (error instanceof NotClonedError ? r.pending : r.problems).push(error.message);
714
+ return r;
715
+ }
716
+ // Absolute: skills run `git -C <checkout>` from any worktree.
717
+ r.main = main;
718
+ const branch = (await originDefaultBranch(main, DOCTOR_NETWORK)) ?? "main";
719
+ // Compared as on origin now: clones are never pulled, so their tracking refs may be old.
720
+ try {
721
+ await git(main, ["fetch", "--quiet", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], DOCTOR_NETWORK);
722
+ }
723
+ catch {
724
+ r.warnings.push(`${slug}: origin could not be fetched; its configuration is compared as last fetched`);
725
+ }
726
+ let raw;
727
+ try {
728
+ raw = await git(main, ["show", `origin/${branch}:${CONFIG_PATH.replaceAll("\\", "/")}`]);
729
+ }
730
+ catch {
731
+ raw = undefined;
732
+ }
733
+ if (raw === undefined) {
734
+ r.pending.push(slug === config.hub
735
+ ? `${slug} has no ${CONFIG_PATH} on origin's ${branch} yet: merge the setup there`
736
+ : `${slug} has no ${CONFIG_PATH} on origin's ${branch} yet: install Cupola there with the hub's configuration (\`cupola init --config-file ${join(ws.hub.main, CONFIG_PATH)}\` in a worktree of it) and merge it`);
737
+ return r;
738
+ }
739
+ let theirs;
740
+ try {
741
+ theirs = canonicalJson(parseConfig(raw));
742
+ }
743
+ catch {
744
+ r.problems.push(`${slug}'s ${CONFIG_PATH} is invalid: copy the hub's there`);
745
+ return r;
746
+ }
747
+ if (theirs !== want)
748
+ r.problems.push(`${slug}'s ${CONFIG_PATH} differs from this one: make the copies the same`);
749
+ if (slug !== ws.here.slug) {
750
+ // As on origin's default branch, like the configuration: the clone may be on any branch.
751
+ const onOrigin = (path) => git(main, ["show", `origin/${branch}:${path}`]).catch(() => undefined);
752
+ for (const w of await engineWarnings(onOrigin, ENGINE_LANGUAGE))
753
+ r.warnings.push(`${slug}: ${w}`);
754
+ }
755
+ return r;
756
+ }));
757
+ slugs.forEach((slug, i) => {
758
+ const r = results[i];
759
+ if (!r)
760
+ return;
761
+ if (r.main !== undefined)
762
+ checkouts.set(slug, r.main);
763
+ problems.push(...r.problems);
764
+ pending.push(...r.pending);
765
+ warnings.push(...r.warnings);
766
+ });
767
+ return { problems, pending, warnings, checkouts, here: ws.here.slug };
768
+ }
769
+ /**
770
+ * With every document in the hub: each repository that holds only
771
+ * code is cloned under the hub. Cupola's files on its default branch are
772
+ * reported: nothing of Cupola's belongs there, and its work never reads them.
773
+ */
774
+ async function codeRepositories(io, problems, pending, warnings, checkouts) {
775
+ let ws;
776
+ try {
777
+ ws = await workspace(io);
778
+ }
779
+ catch (error) {
780
+ problems.push(error.message);
781
+ return;
782
+ }
783
+ for (const slug of ws.repos.filter((r) => !ws.slugs.includes(r))) {
784
+ let main;
785
+ try {
786
+ main = ws.checkout(slug).main;
787
+ }
788
+ catch (error) {
789
+ (error instanceof NotClonedError ? pending : problems).push(error.message);
790
+ continue;
791
+ }
792
+ checkouts.set(slug, main);
793
+ const branch = (await originDefaultBranch(main, DOCTOR_NETWORK)) ?? "main";
794
+ // As on origin now: clones are never pulled, so their tracking refs may be old.
795
+ try {
796
+ await git(main, ["fetch", "--quiet", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], DOCTOR_NETWORK);
797
+ }
798
+ catch {
799
+ warnings.push(`${slug}: origin could not be fetched; it is checked as last fetched`);
800
+ }
801
+ const has = await git(main, ["ls-tree", "--name-only", `origin/${branch}`, ".cupola", ".kiro"])
802
+ .then((out) => out.split("\n").filter(Boolean))
803
+ .catch(() => []);
804
+ if (has.length > 0) {
805
+ warnings.push(`${slug} has ${has.join(" and ")} on origin's ${branch}: with documents in the hub, nothing of Cupola's belongs there, and Cupola does not read it`);
806
+ }
807
+ }
808
+ }
809
+ /** JSON with sorted keys, so two copies compare by content. */
810
+ function canonicalJson(value) {
811
+ const sort = (v) => Array.isArray(v)
812
+ ? v.map(sort)
813
+ : v && typeof v === "object"
814
+ ? Object.fromEntries(Object.keys(v)
815
+ .sort()
816
+ .map((k) => [k, sort(v[k])]))
817
+ : v;
818
+ return JSON.stringify(sort(value));
819
+ }
820
+ const inTree = (root) => async (path) => {
821
+ const full = join(root, ...path.split("/"));
822
+ return existsSync(full) ? readFileSync(full, "utf8") : undefined;
823
+ };
824
+ async function engineWarnings(read, language) {
825
+ const manifest = await read(".cupola/manifest.json");
826
+ let engine;
827
+ try {
828
+ engine = manifest === undefined ? undefined : JSON.parse(manifest).engine;
829
+ }
830
+ catch {
831
+ engine = undefined;
832
+ }
833
+ const want = `cc-sdd ${CC_SDD_VERSION} (${language})`;
834
+ if (!engine)
835
+ return [`the spec engine is not installed: \`cupola update\` installs ${want}`];
836
+ if (engine.version !== CC_SDD_VERSION || engine.language !== language) {
837
+ return [
838
+ `the spec engine is cc-sdd ${engine.version} (${engine.language}); \`cupola update\` installs ${want}`,
839
+ ];
840
+ }
841
+ const impl = await read(".claude/skills/kiro-impl/SKILL.md");
842
+ if (impl === undefined)
843
+ return ["kiro-impl is missing: `cupola update` installs it again"];
844
+ if (!impl.includes("disable-model-invocation: false")) {
845
+ return [
846
+ "kiro-impl cannot be invoked by Cupola's skills: it lacks Cupola's patch (`cupola update --take-new` it)",
847
+ ];
848
+ }
849
+ return [];
850
+ }
851
+ function str(value) {
852
+ return typeof value === "string" ? value : undefined;
853
+ }
854
+ function fail(io, json, error) {
855
+ const message = error instanceof Error ? error.message : String(error);
856
+ if (json)
857
+ io.out(JSON.stringify({ error: message }));
858
+ else
859
+ io.err(message);
860
+ return 1;
861
+ }
862
+ /** The first value of an option that may be given several times. */
863
+ function first(v) {
864
+ const all = Array.isArray(v) ? v : [v];
865
+ return all.find((x) => typeof x === "string");
866
+ }