@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,414 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { hostKindOf, loadConfig } from "../config.js";
6
+ import { originDefaultBranch } from "../git.js";
7
+ import { gh } from "../host/github.js";
8
+ import { repoRoot } from "../repo.js";
9
+ import { writeInside } from "../safe-write.js";
10
+ import { reposOf } from "../workspace.js";
11
+ export async function setup(io, what, opts) {
12
+ const root = await repoRoot(io.cwd);
13
+ let items;
14
+ if (what === "claude")
15
+ items = await claude(root, opts, io);
16
+ else if (what === "host")
17
+ items = await host(root, opts.apply);
18
+ else
19
+ throw new Error(`cupola setup ${what}: expected claude or host`);
20
+ if (opts.json)
21
+ io.out(JSON.stringify({ setup: what, items }));
22
+ else
23
+ for (const i of items)
24
+ io.out(`${i.state}: ${i.id} — ${i.detail}`);
25
+ return 0;
26
+ }
27
+ /** The CLI and git run without a prompt each time; the project's own commands are explained, not set. */
28
+ export const CLAUDE_ALLOW = ["Bash(npx @kyuki3rain/cupola *)", "Bash(cupola *)", "Bash(git *)"];
29
+ /**
30
+ * A guard against mistakes, not a security boundary: what `Bash(git *)` would
31
+ * otherwise let a run do that only a human does — run a program through
32
+ * git's configuration (`-c core.sshCommand=…`, `-c alias.x='!…'`, `git
33
+ * config`), change where the repository pushes, push to a URL, force a push,
34
+ * or push to the default branch (humans merge). Claude Code's `*` patterns
35
+ * cannot hold against a run set on getting around them (`--git-dir`, `env
36
+ * git`, `sh -c`, a push without a refspec all pass); the guards are the
37
+ * default branch requiring a pull request (`cupola setup host`) and text from
38
+ * the tracker, the code host, or fetched pages read as data, never as
39
+ * instructions. Each rule is written for `git …` and `git -C <dir> …`, the two
40
+ * ways the skills call git; no skill tells an agent to run any of them, and
41
+ * the CLI runs git itself, outside Claude Code's permissions. A rule that
42
+ * also matches an ordinary command only returns a denial the run can work
43
+ * around (a commit message reworded), but such matches are kept rare.
44
+ */
45
+ /** A push to one of these branches, by name, `:<branch>`, or `refs/heads/<branch>`. */
46
+ function pushTo(branches) {
47
+ return [
48
+ ...branches.flatMap((b) => [`push * ${b}`, `push * ${b} *`]),
49
+ ...branches.flatMap((b) => [`push *:${b}`, `push *:${b} *`]),
50
+ ...branches.flatMap((b) => [`push *refs/heads/${b}`, `push *refs/heads/${b} *`]),
51
+ ];
52
+ }
53
+ // `main` and `master` always: the default branch of a repository whose origin cannot be read.
54
+ const PUSH_TO_DEFAULT = pushTo(["main", "master"]);
55
+ const GIT_DENIED = [
56
+ "--config-env*",
57
+ "remote add*",
58
+ "remote set-url*",
59
+ "push --force*",
60
+ "push -f*",
61
+ "push * --force*",
62
+ "push * -f*",
63
+ "push * +*",
64
+ "push --mirror*",
65
+ "push * --mirror*",
66
+ ...PUSH_TO_DEFAULT,
67
+ "push http*",
68
+ "push * http*",
69
+ "push git@*",
70
+ "push * git@*",
71
+ "push ssh:*",
72
+ "push * ssh:*",
73
+ ];
74
+ // After `-C <dir>`, `*` can reach into a commit message, so `-c` takes a `key=value` (not
75
+ // `commit -c <commit>`), and `config` names the sections whose keys run a program or move a
76
+ // push (core.editor, core.pager, core.fsmonitor, core.hooksPath, core.sshCommand,
77
+ // credential.helper, gpg.program, diff.external, diff.<driver>.textconv, filter.<driver>.clean,
78
+ // merge.<driver>.driver, sequence.editor, ssh.variant, remote.<name>.uploadpack, url.<base>,
79
+ // include.path, …) rather than every `config` in a message.
80
+ const GIT_C_CONFIG = [
81
+ "-c *=*",
82
+ "config --*",
83
+ "config set *",
84
+ ...[
85
+ "alias",
86
+ "core",
87
+ "credential",
88
+ "diff",
89
+ "difftool",
90
+ "filter",
91
+ "gpg",
92
+ "http",
93
+ "include",
94
+ "includeIf",
95
+ "interactive",
96
+ "merge",
97
+ "mergetool",
98
+ "pager",
99
+ "protocol",
100
+ "receive",
101
+ "remote",
102
+ "sequence",
103
+ "ssh",
104
+ "uploadpack",
105
+ "url",
106
+ ].map((section) => `config ${section}.*`),
107
+ ];
108
+ /**
109
+ * The deny rules, for a repository whose default branch is `defaultBranch`: pushes to it are
110
+ * denied as pushes to `main` and `master` are, in the same forms.
111
+ */
112
+ export function claudeDeny(defaultBranch) {
113
+ const extra = defaultBranch && !["main", "master"].includes(defaultBranch) ? pushTo([defaultBranch]) : [];
114
+ const denied = [...GIT_DENIED, ...extra];
115
+ return [
116
+ ...["-c *", "config *", ...denied].map((r) => `Bash(git ${r})`),
117
+ ...[...GIT_C_CONFIG, ...denied].map((r) => `Bash(git -C * ${r})`),
118
+ ];
119
+ }
120
+ export const CLAUDE_DENY = claudeDeny();
121
+ /**
122
+ * The CLI's operations that only a human decides, prompted each time: closing a case (resolution), and
123
+ * merging a change on a git host (acceptance, release). Only
124
+ * what no execution skill runs: `cupola change close` (a dropped spec, in `cupola-epic-run`) and
125
+ * `cupola epic abort` (`cupola-abort`, on a human's instruction) run without a prompt.
126
+ */
127
+ export const CLAUDE_ASK = ["work close", "change merge"].flatMap((c) => [
128
+ `Bash(cupola ${c}*)`,
129
+ `Bash(npx @kyuki3rain/cupola ${c}*)`,
130
+ ]);
131
+ const LISTS = [
132
+ { key: "allow", prefix: "permission", rules: CLAUDE_ALLOW, have: "allowed" },
133
+ { key: "deny", prefix: "deny", rules: CLAUDE_DENY, have: "denied" },
134
+ { key: "ask", prefix: "ask", rules: CLAUDE_ASK, have: "asked each time" },
135
+ ];
136
+ /** The lists, with pushes to the repository's default branch denied too. */
137
+ function listsFor(defaultBranch) {
138
+ return LISTS.map((l) => (l.key === "deny" ? { ...l, rules: claudeDeny(defaultBranch) } : l));
139
+ }
140
+ /** What a run needs of Claude Code's limits; the default is in parentheses. */
141
+ export const CLAUDE_LIMITS = [
142
+ { key: "CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH", want: 3, absent: 3 },
143
+ { key: "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS", want: 100, absent: 20 },
144
+ ];
145
+ function settingsFiles(root, home) {
146
+ return [
147
+ { scope: "project", file: join(root, ".claude", "settings.json") },
148
+ { scope: "local", file: join(root, ".claude", "settings.local.json") },
149
+ { scope: "user", file: join(home, ".claude", "settings.json") },
150
+ ];
151
+ }
152
+ /** A settings file, or `invalid` when it is not a JSON object Cupola can add to: never written over. */
153
+ async function readSettings(file) {
154
+ if (!existsSync(file))
155
+ return {};
156
+ let value;
157
+ try {
158
+ value = JSON.parse(await readFile(file, "utf8"));
159
+ }
160
+ catch {
161
+ return "invalid";
162
+ }
163
+ if (!value || typeof value !== "object" || Array.isArray(value))
164
+ return "invalid";
165
+ const s = value;
166
+ if (s.permissions !== undefined && (typeof s.permissions !== "object" || s.permissions === null))
167
+ return "invalid";
168
+ for (const { key } of LISTS)
169
+ if (s.permissions?.[key] !== undefined && !Array.isArray(s.permissions[key]))
170
+ return "invalid";
171
+ if (s.env !== undefined && (typeof s.env !== "object" || s.env === null || Array.isArray(s.env)))
172
+ return "invalid";
173
+ return s;
174
+ }
175
+ /**
176
+ * What Claude Code has of Cupola's needs, read across the project's, the
177
+ * local, and the user's settings and the environment (they merge): the
178
+ * permissions for the CLI and git, and the subagent limits.
179
+ */
180
+ export async function claudeItems(root, opts) {
181
+ const defaultBranch = "defaultBranch" in opts
182
+ ? opts.defaultBranch
183
+ : await originDefaultBranch(root, { timeoutMs: 15_000, retry: false });
184
+ const lists = listsFor(defaultBranch);
185
+ const files = settingsFiles(root, opts.home);
186
+ const read = await Promise.all(files.map((f) => readSettings(f.file)));
187
+ const all = read.filter((s) => s !== "invalid");
188
+ const invalid = files
189
+ .filter((_, i) => read[i] === "invalid")
190
+ .map((f) => ({
191
+ id: `settings ${f.scope}`,
192
+ state: "manual",
193
+ detail: `${f.file} is not a JSON object with arrays permissions.allow, deny, and ask and an object env: Cupola neither reads nor writes it until it is fixed`,
194
+ }));
195
+ // Claude Code's precedence for a value: the local file, then the project's, then the user's.
196
+ const byPrecedence = ["local", "project", "user"].flatMap((scope) => {
197
+ const s = read[files.findIndex((f) => f.scope === scope)];
198
+ return s && s !== "invalid" ? [s] : [];
199
+ });
200
+ const where = opts.target ?? ".claude/settings.json";
201
+ const items = lists.flatMap((list) => {
202
+ const set = new Set(all.flatMap((s) => s.permissions?.[list.key] ?? []));
203
+ return list.rules.map((rule) => ({
204
+ id: `${list.prefix} ${rule}`,
205
+ state: set.has(rule) ? "ok" : "todo",
206
+ detail: set.has(rule) ? list.have : `add to permissions.${list.key} in ${where}`,
207
+ }));
208
+ });
209
+ for (const limit of CLAUDE_LIMITS) {
210
+ const want = limit.key === "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"
211
+ ? (opts.subagents ?? limit.want)
212
+ : limit.want;
213
+ const raw = opts.env[limit.key] ??
214
+ byPrecedence.map((s) => s.env?.[limit.key]).find((v) => v !== undefined);
215
+ const have = raw === undefined ? limit.absent : Number(raw);
216
+ if (Number.isNaN(have)) {
217
+ items.push({
218
+ id: `limit ${limit.key}`,
219
+ state: "manual",
220
+ detail: `${limit.key} is "${raw}", not a number: set it to ${want} or more`,
221
+ });
222
+ continue;
223
+ }
224
+ items.push({
225
+ id: `limit ${limit.key}`,
226
+ state: have >= want ? "ok" : "todo",
227
+ detail: have >= want
228
+ ? `${have}${raw === undefined ? " (Claude Code's default)" : ""}`
229
+ : `${have}${raw === undefined ? " (Claude Code's default)" : ""}, below ${want}: set env ${limit.key}=${want} in ${where}`,
230
+ });
231
+ }
232
+ return [...invalid, ...items];
233
+ }
234
+ async function claude(root, opts, io) {
235
+ const scope = opts.scope ?? "project";
236
+ const home = io.env?.HOME ?? homedir();
237
+ const target = settingsFiles(root, home).find((f) => f.scope === scope);
238
+ if (!target)
239
+ throw new Error("--scope is project (.claude/settings.json), local (.claude/settings.local.json), or user (~/.claude/settings.json)");
240
+ let subagents;
241
+ if (opts.subagents !== undefined) {
242
+ subagents = Number(opts.subagents);
243
+ if (!Number.isInteger(subagents) || subagents < 1)
244
+ throw new Error("--subagents takes a positive number");
245
+ }
246
+ const shown = target.scope === "user" ? "~/.claude/settings.json" : rel(root, target.file);
247
+ const items = await claudeItems(root, {
248
+ home,
249
+ env: io.env ?? {},
250
+ subagents,
251
+ target: shown,
252
+ });
253
+ items.push({
254
+ id: "permissions of the project's own commands",
255
+ state: "manual",
256
+ detail: "tests, builds, and deploys are allowed by the human, command by command, when a run first needs them",
257
+ });
258
+ if (!opts.apply || !items.some((i) => i.state === "todo"))
259
+ return items;
260
+ const settings = await readSettings(target.file);
261
+ if (settings === "invalid")
262
+ throw new Error(`${target.file} is not valid settings JSON; fix it, and run this again (nothing was written)`);
263
+ const env = { ...settings.env };
264
+ for (const i of items) {
265
+ if (i.state !== "todo" || !i.id.startsWith("limit "))
266
+ continue;
267
+ const key = i.id.slice("limit ".length);
268
+ const limit = CLAUDE_LIMITS.find((l) => l.key === key);
269
+ if (limit)
270
+ env[key] = String(key === "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS" ? (subagents ?? limit.want) : limit.want);
271
+ }
272
+ const permissions = { ...settings.permissions };
273
+ for (const list of LISTS) {
274
+ const rules = items
275
+ .filter((i) => i.state === "todo" && i.id.startsWith(`${list.prefix} `))
276
+ .map((i) => i.id.slice(list.prefix.length + 1));
277
+ if (rules.length === 0)
278
+ continue;
279
+ const have = settings.permissions?.[list.key] ?? [];
280
+ permissions[list.key] = [...have, ...rules.filter((r) => !have.includes(r))];
281
+ }
282
+ const next = {
283
+ ...settings,
284
+ ...(Object.keys(permissions).length > 0 ? { permissions } : {}),
285
+ ...(Object.keys(env).length > 0 ? { env } : {}),
286
+ };
287
+ const text = `${JSON.stringify(next, null, 2)}\n`;
288
+ if (target.scope === "user") {
289
+ await mkdir(dirname(target.file), { recursive: true });
290
+ await writeFile(target.file, text);
291
+ }
292
+ else {
293
+ // The project's own settings are in the repository: no link there leads the write out of it.
294
+ await writeInside(root, target.file, text);
295
+ }
296
+ return items.map((i) => (i.state === "todo" ? { ...i, state: "applied" } : i));
297
+ }
298
+ function rel(root, file) {
299
+ return file.slice(root.length + 1).replaceAll("\\", "/");
300
+ }
301
+ /** Squash merges allowed, the commit titled by the change's title. */
302
+ export const SQUASH_JQ = '.allow_squash_merge and .squash_merge_commit_title == "PR_TITLE"';
303
+ /** Squash merges on every repository: one commit per change on `main`. */
304
+ async function host(root, apply) {
305
+ const config = await loadConfig(root);
306
+ const items = [];
307
+ const onGithub = reposOf(config).filter((slug) => hostKindOf(config, slug) === "github");
308
+ for (const slug of reposOf(config).filter((s) => !onGithub.includes(s))) {
309
+ // A git host has no settings to read: people merge through Cupola, one commit per change.
310
+ items.push({
311
+ id: `squash merge ${slug}`,
312
+ state: "ok",
313
+ detail: "a git host: people merge with `cupola change merge`, one commit per change",
314
+ });
315
+ items.push({
316
+ id: `pull requests required ${slug}`,
317
+ state: "manual",
318
+ detail: "a git host: let only the people who merge push to its default branch, on the git server",
319
+ });
320
+ }
321
+ for (const slug of onGithub) {
322
+ let squash;
323
+ try {
324
+ squash = (await gh(root, ["api", `repos/${slug}`, "--jq", SQUASH_JQ])) === "true";
325
+ }
326
+ catch (error) {
327
+ items.push({
328
+ id: `squash merge ${slug}`,
329
+ state: "manual",
330
+ detail: `could not read the repository's settings (${error.message.split("\n")[0]}); in its Settings → General → Pull Requests, allow squash merging`,
331
+ });
332
+ continue;
333
+ }
334
+ if (squash) {
335
+ items.push({ id: `squash merge ${slug}`, state: "ok", detail: "allowed" });
336
+ continue;
337
+ }
338
+ if (!apply) {
339
+ items.push({
340
+ id: `squash merge ${slug}`,
341
+ state: "todo",
342
+ detail: "squash merging, titled by the change, is not set",
343
+ });
344
+ continue;
345
+ }
346
+ try {
347
+ await gh(root, [
348
+ "api",
349
+ "-X",
350
+ "PATCH",
351
+ `repos/${slug}`,
352
+ "-F",
353
+ "allow_squash_merge=true",
354
+ "-f",
355
+ "squash_merge_commit_title=PR_TITLE",
356
+ "-f",
357
+ "squash_merge_commit_message=PR_BODY",
358
+ ]);
359
+ items.push({
360
+ id: `squash merge ${slug}`,
361
+ state: "applied",
362
+ detail: "squash merging allowed, titled by the change",
363
+ });
364
+ }
365
+ catch (error) {
366
+ items.push({
367
+ id: `squash merge ${slug}`,
368
+ state: "manual",
369
+ detail: `could not change it (${error.message.split("\n")[0]}); an admin allows squash merging in Settings → General → Pull Requests`,
370
+ });
371
+ }
372
+ }
373
+ for (const slug of onGithub)
374
+ items.push(await pullRequestRequired(root, slug));
375
+ return items;
376
+ }
377
+ /**
378
+ * Whether the default branch takes changes only through a pull request — a ruleset or a branch
379
+ * protection rule — so that nothing reaches `main` but what a human merges. Only reported: an
380
+ * admin sets it, as the project's rules for it are its own.
381
+ */
382
+ async function pullRequestRequired(root, slug) {
383
+ const id = `pull requests required ${slug}`;
384
+ let branch;
385
+ try {
386
+ branch = await gh(root, ["api", `repos/${slug}`, "--jq", ".default_branch"]);
387
+ }
388
+ catch (error) {
389
+ return {
390
+ id,
391
+ state: "manual",
392
+ detail: `could not read the repository (${error.message.split("\n")[0]}); require a pull request before merging into the default branch`,
393
+ };
394
+ }
395
+ const branchPath = `repos/${slug}/branches/${encodeURIComponent(branch)}`;
396
+ const byRules = await gh(root, [
397
+ "api",
398
+ `repos/${slug}/rules/branches/${encodeURIComponent(branch)}`,
399
+ "--jq",
400
+ 'any(.[]; .type == "pull_request")',
401
+ ]).catch(() => "false");
402
+ // Branch protection is read only by admins; a failure is a branch not known to be protected.
403
+ const required = byRules === "true" ||
404
+ (await gh(root, ["api", `${branchPath}/protection/required_pull_request_reviews`])
405
+ .then(() => true)
406
+ .catch(() => false));
407
+ if (required)
408
+ return { id, state: "ok", detail: `${branch} takes changes only through a pull request` };
409
+ return {
410
+ id,
411
+ state: "manual",
412
+ detail: `${branch} is not known to require a pull request: an admin adds a ruleset (Settings → Rules → Rulesets) or a branch protection rule that requires one, so that only what a human merges reaches it`,
413
+ };
414
+ }
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { mountWork } from "../code.js";
5
+ import { epicPath, resolveComponents } from "../config.js";
6
+ import { ENGINE_LANGUAGE, specPath } from "../engine/cc-sdd.js";
7
+ import { commitPaths, workBranch } from "../git.js";
8
+ import { repoRoot } from "../repo.js";
9
+ import { writeInside } from "../safe-write.js";
10
+ import { epicFront, initSpecJson, newBlock, readBlock, specNamesOf } from "../spec.js";
11
+ import { assertWorkId, workBranchName } from "../work.js";
12
+ import { workspace } from "../workspace.js";
13
+ import { snapshotEpic } from "./revision.js";
14
+ const INIT_TEMPLATE = ".kiro/settings/templates/specs/init.json";
15
+ /**
16
+ * `cupola spec init <spec> --epic <epic>`: creates a full spec's `spec.json`
17
+ * on the spec's branch, from the engine's template and with Cupola's block,
18
+ * and pushes it. Run in the spec's worktree, after the epic's start. Running
19
+ * it again on a spec that exists changes nothing.
20
+ */
21
+ export async function specInit(io, spec, opts) {
22
+ if (!opts.epic)
23
+ throw new Error("name the spec's epic: --epic <epic>");
24
+ assertWorkId(spec);
25
+ assertWorkId(opts.epic);
26
+ const root = await repoRoot(io.cwd);
27
+ const branch = await workBranch(root);
28
+ if (branch !== workBranchName(spec)) {
29
+ throw new Error(`${spec} is created on ${workBranchName(spec)}, but this checkout is on ${branch}`);
30
+ }
31
+ const ws = await workspace(io);
32
+ const config = ws.config;
33
+ // In a component's repository the agreed epic is copied from the hub.
34
+ await snapshotEpic(ws, root, opts.epic);
35
+ const epicFile = epicPath(config.paths, opts.epic);
36
+ if (!existsSync(join(root, epicFile))) {
37
+ throw new Error(`${epicFile} is not on this branch: is the epic agreed (its change merged)?`);
38
+ }
39
+ const { front, epic } = epicFront(epicFile, await readFile(join(root, epicFile), "utf8"));
40
+ const named = specNamesOf(opts.epic, front.specs);
41
+ const component = named.find((s) => s.name === spec)?.component;
42
+ if (!component) {
43
+ const names = named.map((s) => s.name).join(", ");
44
+ throw new Error(`${spec} is not a spec of ${opts.epic}; its specs are ${names}`);
45
+ }
46
+ if (!resolveComponents(config).some((c) => c.name === component)) {
47
+ throw new Error(`component ${component} is not configured in .cupola/config.json`);
48
+ }
49
+ if (ws.repoOf(component) !== ws.here.slug) {
50
+ throw new Error(`${spec} is a spec of ${component}, which lives in ${ws.repoOf(component)}, not ${ws.here.slug}: create its worktree with \`cupola worktree ${spec}\``);
51
+ }
52
+ const dir = specPath(spec);
53
+ const file = join(dir, "spec.json");
54
+ const block = newBlock(opts.epic, epic, component);
55
+ let created = false;
56
+ if (existsSync(join(root, file))) {
57
+ const existing = readBlock(file, await readFile(join(root, file), "utf8"));
58
+ if (!existing)
59
+ throw new Error(`${file} exists without Cupola's block: it is not this spec`);
60
+ if (existing.epic !== block.epic || existing.component !== block.component) {
61
+ throw new Error(`${file} belongs to ${existing.epic} (${existing.component})`);
62
+ }
63
+ }
64
+ else {
65
+ const template = join(root, INIT_TEMPLATE);
66
+ if (!existsSync(template)) {
67
+ throw new Error(`${INIT_TEMPLATE} is missing; install the spec engine with \`cupola update\``);
68
+ }
69
+ const now = (io.now?.() ?? new Date()).toISOString();
70
+ await writeInside(root, file, initSpecJson(await readFile(template, "utf8"), spec, ENGINE_LANGUAGE, now, block));
71
+ created = true;
72
+ }
73
+ // Pushes too when an earlier run committed but could not push.
74
+ await commitPaths(root, branch, [dir], `spec: init ${spec}`);
75
+ // With every document in the hub, the component's code is mounted next to it.
76
+ await mountWork(ws, root, spec, branch);
77
+ const result = { spec, epic: opts.epic, component, path: file, created };
78
+ io.out(opts.json ? JSON.stringify(result) : `${spec}: ${created ? "created" : "exists"} ${file}`);
79
+ return 0;
80
+ }