@kyuki3rain/cupola 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +202 -0
  3. package/README.md +40 -2
  4. package/dist/adr.js +106 -0
  5. package/dist/catalog.js +137 -0
  6. package/dist/check.js +192 -0
  7. package/dist/cli.js +8 -0
  8. package/dist/code.js +216 -0
  9. package/dist/commands/change.js +522 -0
  10. package/dist/commands/epic.js +311 -0
  11. package/dist/commands/install.js +109 -0
  12. package/dist/commands/locks.js +175 -0
  13. package/dist/commands/procedure.js +92 -0
  14. package/dist/commands/revision.js +139 -0
  15. package/dist/commands/run.js +1015 -0
  16. package/dist/commands/setup.js +382 -0
  17. package/dist/commands/spec.js +80 -0
  18. package/dist/commands/status.js +1158 -0
  19. package/dist/commands/trace.js +397 -0
  20. package/dist/commands/wait.js +102 -0
  21. package/dist/commands/work.js +121 -0
  22. package/dist/commands/workspace.js +126 -0
  23. package/dist/commands/worktree.js +422 -0
  24. package/dist/config.js +289 -0
  25. package/dist/day.js +29 -0
  26. package/dist/e2e-project.js +62 -0
  27. package/dist/e2e.js +207 -0
  28. package/dist/engine/cc-sdd.js +164 -0
  29. package/dist/epic.js +360 -0
  30. package/dist/feedback.js +34 -0
  31. package/dist/frontmatter.js +20 -0
  32. package/dist/git.js +365 -0
  33. package/dist/host/github.js +290 -0
  34. package/dist/host/host.js +1 -0
  35. package/dist/install.js +182 -0
  36. package/dist/io.js +46 -0
  37. package/dist/main.js +771 -0
  38. package/dist/method/v1.js +56 -0
  39. package/dist/procedure.js +60 -0
  40. package/dist/record.js +473 -0
  41. package/dist/release.js +84 -0
  42. package/dist/repo.js +13 -0
  43. package/dist/runbook.js +111 -0
  44. package/dist/safe-write.js +80 -0
  45. package/dist/spec.js +171 -0
  46. package/dist/status.js +190 -0
  47. package/dist/templates.js +49 -0
  48. package/dist/trace.js +275 -0
  49. package/dist/tracker/files.js +156 -0
  50. package/dist/tracker/github-issues.js +217 -0
  51. package/dist/tracker/index.js +27 -0
  52. package/dist/tracker/tracker.js +69 -0
  53. package/dist/tree.js +42 -0
  54. package/dist/trust.js +13 -0
  55. package/dist/version.js +5 -0
  56. package/dist/work.js +149 -0
  57. package/dist/workspace.js +299 -0
  58. package/npm-shrinkwrap.json +2014 -0
  59. package/package.json +41 -4
  60. package/skills/cupola-abort/SKILL.md +45 -0
  61. package/skills/cupola-adr/SKILL.md +41 -0
  62. package/skills/cupola-ask/SKILL.md +42 -0
  63. package/skills/cupola-catalog/SKILL.md +41 -0
  64. package/skills/cupola-catalog-draft/SKILL.md +114 -0
  65. package/skills/cupola-complete/SKILL.md +87 -0
  66. package/skills/cupola-decide/SKILL.md +60 -0
  67. package/skills/cupola-doc/SKILL.md +52 -0
  68. package/skills/cupola-e2e-setup/SKILL.md +78 -0
  69. package/skills/cupola-e2e-test/SKILL.md +115 -0
  70. package/skills/cupola-epic-accept/SKILL.md +162 -0
  71. package/skills/cupola-epic-create/SKILL.md +120 -0
  72. package/skills/cupola-epic-revise/SKILL.md +71 -0
  73. package/skills/cupola-epic-run/SKILL.md +127 -0
  74. package/skills/cupola-fix/SKILL.md +115 -0
  75. package/skills/cupola-init/SKILL.md +88 -0
  76. package/skills/cupola-intake/SKILL.md +78 -0
  77. package/skills/cupola-operate/SKILL.md +64 -0
  78. package/skills/cupola-resolve/SKILL.md +86 -0
  79. package/skills/cupola-review/SKILL.md +132 -0
  80. package/skills/cupola-spec-design/SKILL.md +164 -0
  81. package/skills/cupola-spec-impl/SKILL.md +135 -0
  82. package/skills/cupola-spec-run/SKILL.md +125 -0
  83. package/skills/cupola-steering/SKILL.md +46 -0
  84. package/templates/install/.kiro/steering/e2e.md +48 -0
  85. package/templates/install/.kiro/steering/operations.md +109 -0
  86. package/templates/install/.kiro/steering/principles.md +25 -0
  87. package/templates/install/CLAUDE.md +19 -0
  88. package/templates/install/adr/TEMPLATE.md +38 -0
  89. package/templates/install/cc-sdd/patches.json +31 -0
  90. package/templates/method-1/behavior-area.md +43 -0
  91. package/templates/method-1/behavior-index.md +16 -0
  92. package/templates/method-1/card.md +41 -0
  93. package/templates/method-1/case-draft.md +25 -0
  94. package/templates/method-1/case.md +38 -0
  95. package/templates/method-1/catalog-spec.md +33 -0
  96. package/templates/method-1/changes/adr.md +4 -0
  97. package/templates/method-1/changes/catalog.md +29 -0
  98. package/templates/method-1/changes/doc.md +5 -0
  99. package/templates/method-1/changes/e2e.md +7 -0
  100. package/templates/method-1/changes/epic.md +29 -0
  101. package/templates/method-1/changes/fix.md +21 -0
  102. package/templates/method-1/changes/release.md +23 -0
  103. package/templates/method-1/changes/spec.md +55 -0
  104. package/templates/method-1/changes/system.md +13 -0
  105. package/templates/method-1/cupola-issue-draft.md +17 -0
  106. package/templates/method-1/epic.md +136 -0
  107. package/templates/method-1/fix-spec.md +34 -0
  108. package/templates/method-1/fix.md +39 -0
  109. package/templates/method-1/lock.json +13 -0
  110. package/templates/method-1/phase-outcome.json +29 -0
  111. package/templates/method-1/record.json +63 -0
  112. package/templates/method-1/report.md +27 -0
  113. package/templates/method-1/runbook.md +39 -0
  114. package/templates/method-1/runner-result.json +6 -0
  115. package/templates/method-1/send-back.md +23 -0
  116. package/templates/methods.json +13 -0
@@ -0,0 +1,382 @@
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 { loadConfig } from "../config.js";
6
+ import { gh } from "../host/github.js";
7
+ import { repoRoot } from "../repo.js";
8
+ import { writeInside } from "../safe-write.js";
9
+ import { reposOf } from "../workspace.js";
10
+ export async function setup(io, what, opts) {
11
+ const root = await repoRoot(io.cwd);
12
+ let items;
13
+ if (what === "claude")
14
+ items = await claude(root, opts, io);
15
+ else if (what === "host")
16
+ items = await host(root, opts.apply);
17
+ else
18
+ throw new Error(`cupola setup ${what}: expected claude or host`);
19
+ if (opts.json)
20
+ io.out(JSON.stringify({ setup: what, items }));
21
+ else
22
+ for (const i of items)
23
+ io.out(`${i.state}: ${i.id} — ${i.detail}`);
24
+ return 0;
25
+ }
26
+ /** The CLI and git run without a prompt each time; the project's own commands are explained, not set. */
27
+ export const CLAUDE_ALLOW = ["Bash(npx @kyuki3rain/cupola *)", "Bash(cupola *)", "Bash(git *)"];
28
+ /**
29
+ * A guard against mistakes, not a security boundary: what `Bash(git *)` would
30
+ * otherwise let a run do that only a human does — run a program through
31
+ * git's configuration (`-c core.sshCommand=…`, `-c alias.x='!…'`, `git
32
+ * config`), change where the repository pushes, push to a URL, force a push,
33
+ * or push to the default branch (humans merge). Claude Code's `*` patterns
34
+ * cannot hold against a run set on getting around them (`--git-dir`, `env
35
+ * git`, `sh -c`, a push without a refspec all pass); the guards are the
36
+ * default branch requiring a pull request (`cupola setup host`) and text from
37
+ * the tracker, the code host, or fetched pages read as data, never as
38
+ * instructions. Each rule is written for `git …` and `git -C <dir> …`, the two
39
+ * ways the skills call git; no skill tells an agent to run any of them, and
40
+ * the CLI runs git itself, outside Claude Code's permissions. A rule that
41
+ * also matches an ordinary command only returns a denial the run can work
42
+ * around (a commit message reworded), but such matches are kept rare.
43
+ */
44
+ const GIT_DENIED = [
45
+ "--config-env*",
46
+ "remote add*",
47
+ "remote set-url*",
48
+ "push --force*",
49
+ "push -f*",
50
+ "push * --force*",
51
+ "push * -f*",
52
+ "push * +*",
53
+ "push --mirror*",
54
+ "push * --mirror*",
55
+ "push * main",
56
+ "push * main *",
57
+ "push * master",
58
+ "push * master *",
59
+ "push *:main",
60
+ "push *:main *",
61
+ "push *:master",
62
+ "push *:master *",
63
+ "push *refs/heads/main",
64
+ "push *refs/heads/main *",
65
+ "push *refs/heads/master",
66
+ "push *refs/heads/master *",
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
+ export const CLAUDE_DENY = [
109
+ ...["-c *", "config *", ...GIT_DENIED].map((r) => `Bash(git ${r})`),
110
+ ...[...GIT_C_CONFIG, ...GIT_DENIED].map((r) => `Bash(git -C * ${r})`),
111
+ ];
112
+ /**
113
+ * The CLI's operations that only a human decides, prompted each time: closing a case (G5). Only
114
+ * what no execution skill runs: `cupola change close` (a dropped spec, in `cupola-epic-run`) and
115
+ * `cupola epic abort` (`cupola-abort`, on a human's instruction) run without a prompt.
116
+ */
117
+ export const CLAUDE_ASK = ["work close"].flatMap((c) => [
118
+ `Bash(cupola ${c}*)`,
119
+ `Bash(npx @kyuki3rain/cupola ${c}*)`,
120
+ ]);
121
+ const LISTS = [
122
+ { key: "allow", prefix: "permission", rules: CLAUDE_ALLOW, have: "allowed" },
123
+ { key: "deny", prefix: "deny", rules: CLAUDE_DENY, have: "denied" },
124
+ { key: "ask", prefix: "ask", rules: CLAUDE_ASK, have: "asked each time" },
125
+ ];
126
+ /** What a run needs of Claude Code's limits; the default is in parentheses. */
127
+ export const CLAUDE_LIMITS = [
128
+ { key: "CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH", want: 3, absent: 3 },
129
+ { key: "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS", want: 100, absent: 20 },
130
+ ];
131
+ function settingsFiles(root, home) {
132
+ return [
133
+ { scope: "project", file: join(root, ".claude", "settings.json") },
134
+ { scope: "local", file: join(root, ".claude", "settings.local.json") },
135
+ { scope: "user", file: join(home, ".claude", "settings.json") },
136
+ ];
137
+ }
138
+ /** A settings file, or `invalid` when it is not a JSON object Cupola can add to: never written over. */
139
+ async function readSettings(file) {
140
+ if (!existsSync(file))
141
+ return {};
142
+ let value;
143
+ try {
144
+ value = JSON.parse(await readFile(file, "utf8"));
145
+ }
146
+ catch {
147
+ return "invalid";
148
+ }
149
+ if (!value || typeof value !== "object" || Array.isArray(value))
150
+ return "invalid";
151
+ const s = value;
152
+ if (s.permissions !== undefined && (typeof s.permissions !== "object" || s.permissions === null))
153
+ return "invalid";
154
+ for (const { key } of LISTS)
155
+ if (s.permissions?.[key] !== undefined && !Array.isArray(s.permissions[key]))
156
+ return "invalid";
157
+ if (s.env !== undefined && (typeof s.env !== "object" || s.env === null || Array.isArray(s.env)))
158
+ return "invalid";
159
+ return s;
160
+ }
161
+ /**
162
+ * What Claude Code has of Cupola's needs, read across the project's, the
163
+ * local, and the user's settings and the environment (they merge): the
164
+ * permissions for the CLI and git, and the subagent limits.
165
+ */
166
+ export async function claudeItems(root, opts) {
167
+ const files = settingsFiles(root, opts.home);
168
+ const read = await Promise.all(files.map((f) => readSettings(f.file)));
169
+ const all = read.filter((s) => s !== "invalid");
170
+ const invalid = files
171
+ .filter((_, i) => read[i] === "invalid")
172
+ .map((f) => ({
173
+ id: `settings ${f.scope}`,
174
+ state: "manual",
175
+ 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`,
176
+ }));
177
+ // Claude Code's precedence for a value: the local file, then the project's, then the user's.
178
+ const byPrecedence = ["local", "project", "user"].flatMap((scope) => {
179
+ const s = read[files.findIndex((f) => f.scope === scope)];
180
+ return s && s !== "invalid" ? [s] : [];
181
+ });
182
+ const where = opts.target ?? ".claude/settings.json";
183
+ const items = LISTS.flatMap((list) => {
184
+ const set = new Set(all.flatMap((s) => s.permissions?.[list.key] ?? []));
185
+ return list.rules.map((rule) => ({
186
+ id: `${list.prefix} ${rule}`,
187
+ state: set.has(rule) ? "ok" : "todo",
188
+ detail: set.has(rule) ? list.have : `add to permissions.${list.key} in ${where}`,
189
+ }));
190
+ });
191
+ for (const limit of CLAUDE_LIMITS) {
192
+ const want = limit.key === "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"
193
+ ? (opts.subagents ?? limit.want)
194
+ : limit.want;
195
+ const raw = opts.env[limit.key] ??
196
+ byPrecedence.map((s) => s.env?.[limit.key]).find((v) => v !== undefined);
197
+ const have = raw === undefined ? limit.absent : Number(raw);
198
+ if (Number.isNaN(have)) {
199
+ items.push({
200
+ id: `limit ${limit.key}`,
201
+ state: "manual",
202
+ detail: `${limit.key} is "${raw}", not a number: set it to ${want} or more`,
203
+ });
204
+ continue;
205
+ }
206
+ items.push({
207
+ id: `limit ${limit.key}`,
208
+ state: have >= want ? "ok" : "todo",
209
+ detail: have >= want
210
+ ? `${have}${raw === undefined ? " (Claude Code's default)" : ""}`
211
+ : `${have}${raw === undefined ? " (Claude Code's default)" : ""}, below ${want}: set env ${limit.key}=${want} in ${where}`,
212
+ });
213
+ }
214
+ return [...invalid, ...items];
215
+ }
216
+ async function claude(root, opts, io) {
217
+ const scope = opts.scope ?? "project";
218
+ const home = io.env?.HOME ?? homedir();
219
+ const target = settingsFiles(root, home).find((f) => f.scope === scope);
220
+ if (!target)
221
+ throw new Error("--scope is project (.claude/settings.json), local (.claude/settings.local.json), or user (~/.claude/settings.json)");
222
+ let subagents;
223
+ if (opts.subagents !== undefined) {
224
+ subagents = Number(opts.subagents);
225
+ if (!Number.isInteger(subagents) || subagents < 1)
226
+ throw new Error("--subagents takes a positive number");
227
+ }
228
+ const shown = target.scope === "user" ? "~/.claude/settings.json" : rel(root, target.file);
229
+ const items = await claudeItems(root, {
230
+ home,
231
+ env: io.env ?? {},
232
+ subagents,
233
+ target: shown,
234
+ });
235
+ items.push({
236
+ id: "permissions of the project's own commands",
237
+ state: "manual",
238
+ detail: "tests, builds, and deploys are allowed by the human, command by command, when a run first needs them",
239
+ });
240
+ if (!opts.apply || !items.some((i) => i.state === "todo"))
241
+ return items;
242
+ const settings = await readSettings(target.file);
243
+ if (settings === "invalid")
244
+ throw new Error(`${target.file} is not valid settings JSON; fix it, and run this again (nothing was written)`);
245
+ const env = { ...settings.env };
246
+ for (const i of items) {
247
+ if (i.state !== "todo" || !i.id.startsWith("limit "))
248
+ continue;
249
+ const key = i.id.slice("limit ".length);
250
+ const limit = CLAUDE_LIMITS.find((l) => l.key === key);
251
+ if (limit)
252
+ env[key] = String(key === "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS" ? (subagents ?? limit.want) : limit.want);
253
+ }
254
+ const permissions = { ...settings.permissions };
255
+ for (const list of LISTS) {
256
+ const rules = items
257
+ .filter((i) => i.state === "todo" && i.id.startsWith(`${list.prefix} `))
258
+ .map((i) => i.id.slice(list.prefix.length + 1));
259
+ if (rules.length === 0)
260
+ continue;
261
+ const have = settings.permissions?.[list.key] ?? [];
262
+ permissions[list.key] = [...have, ...rules.filter((r) => !have.includes(r))];
263
+ }
264
+ const next = {
265
+ ...settings,
266
+ ...(Object.keys(permissions).length > 0 ? { permissions } : {}),
267
+ ...(Object.keys(env).length > 0 ? { env } : {}),
268
+ };
269
+ const text = `${JSON.stringify(next, null, 2)}\n`;
270
+ if (target.scope === "user") {
271
+ await mkdir(dirname(target.file), { recursive: true });
272
+ await writeFile(target.file, text);
273
+ }
274
+ else {
275
+ // The project's own settings are in the repository: no link there leads the write out of it.
276
+ await writeInside(root, target.file, text);
277
+ }
278
+ return items.map((i) => (i.state === "todo" ? { ...i, state: "applied" } : i));
279
+ }
280
+ function rel(root, file) {
281
+ return file.slice(root.length + 1).replaceAll("\\", "/");
282
+ }
283
+ /** Squash merges allowed, the commit titled by the change's title. */
284
+ export const SQUASH_JQ = '.allow_squash_merge and .squash_merge_commit_title == "PR_TITLE"';
285
+ /** Squash merges on every repository: one commit per change on `main`. */
286
+ async function host(root, apply) {
287
+ const config = await loadConfig(root);
288
+ const items = [];
289
+ for (const slug of reposOf(config)) {
290
+ let squash;
291
+ try {
292
+ squash = (await gh(root, ["api", `repos/${slug}`, "--jq", SQUASH_JQ])) === "true";
293
+ }
294
+ catch (error) {
295
+ items.push({
296
+ id: `squash merge ${slug}`,
297
+ state: "manual",
298
+ detail: `could not read the repository's settings (${error.message.split("\n")[0]}); in its Settings → General → Pull Requests, allow squash merging`,
299
+ });
300
+ continue;
301
+ }
302
+ if (squash) {
303
+ items.push({ id: `squash merge ${slug}`, state: "ok", detail: "allowed" });
304
+ continue;
305
+ }
306
+ if (!apply) {
307
+ items.push({
308
+ id: `squash merge ${slug}`,
309
+ state: "todo",
310
+ detail: "squash merging, titled by the change, is not set",
311
+ });
312
+ continue;
313
+ }
314
+ try {
315
+ await gh(root, [
316
+ "api",
317
+ "-X",
318
+ "PATCH",
319
+ `repos/${slug}`,
320
+ "-F",
321
+ "allow_squash_merge=true",
322
+ "-f",
323
+ "squash_merge_commit_title=PR_TITLE",
324
+ "-f",
325
+ "squash_merge_commit_message=PR_BODY",
326
+ ]);
327
+ items.push({
328
+ id: `squash merge ${slug}`,
329
+ state: "applied",
330
+ detail: "squash merging allowed, titled by the change",
331
+ });
332
+ }
333
+ catch (error) {
334
+ items.push({
335
+ id: `squash merge ${slug}`,
336
+ state: "manual",
337
+ detail: `could not change it (${error.message.split("\n")[0]}); an admin allows squash merging in Settings → General → Pull Requests`,
338
+ });
339
+ }
340
+ }
341
+ for (const slug of reposOf(config))
342
+ items.push(await pullRequestRequired(root, slug));
343
+ return items;
344
+ }
345
+ /**
346
+ * Whether the default branch takes changes only through a pull request — a ruleset or a branch
347
+ * protection rule — so that nothing reaches `main` but what a human merges. Only reported: an
348
+ * admin sets it, as the project's rules for it are its own.
349
+ */
350
+ async function pullRequestRequired(root, slug) {
351
+ const id = `pull requests required ${slug}`;
352
+ let branch;
353
+ try {
354
+ branch = await gh(root, ["api", `repos/${slug}`, "--jq", ".default_branch"]);
355
+ }
356
+ catch (error) {
357
+ return {
358
+ id,
359
+ state: "manual",
360
+ detail: `could not read the repository (${error.message.split("\n")[0]}); require a pull request before merging into the default branch`,
361
+ };
362
+ }
363
+ const branchPath = `repos/${slug}/branches/${encodeURIComponent(branch)}`;
364
+ const byRules = await gh(root, [
365
+ "api",
366
+ `repos/${slug}/rules/branches/${encodeURIComponent(branch)}`,
367
+ "--jq",
368
+ 'any(.[]; .type == "pull_request")',
369
+ ]).catch(() => "false");
370
+ // Branch protection is read only by admins; a failure is a branch not known to be protected.
371
+ const required = byRules === "true" ||
372
+ (await gh(root, ["api", `${branchPath}/protection/required_pull_request_reviews`])
373
+ .then(() => true)
374
+ .catch(() => false));
375
+ if (required)
376
+ return { id, state: "ok", detail: `${branch} takes changes only through a pull request` };
377
+ return {
378
+ id,
379
+ state: "manual",
380
+ 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`,
381
+ };
382
+ }
@@ -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 G1. 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
+ }