@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,84 @@
1
+ import { epicBranchName } from "./spec.js";
2
+ import { epicRepos } from "./workspace.js";
3
+ /**
4
+ * The merge order: a repository whose specs others rely on (`after`) comes
5
+ * first; otherwise the configuration's order. The hub, when it holds no spec
6
+ * of the epic, comes last: it carries the epic's own files (system catalog,
7
+ * acceptance-check scripts). With every document in the hub, it comes last
8
+ * too, unless another repository relies on code in it. A cycle across
9
+ * repositories falls back to the configuration's order.
10
+ */
11
+ export function releaseOrder(ws, specs) {
12
+ const repos = epicRepos(ws, specs.map((s) => s.component));
13
+ const own = new Set(specs.map((s) => ws.codeRepoOf(s.component)));
14
+ const ordered = repos.filter((r) => own.has(r.slug));
15
+ const before = new Map(ordered.map((r) => [r.slug, new Set()]));
16
+ for (const s of specs) {
17
+ const to = ws.codeRepoOf(s.component);
18
+ for (const a of s.after ?? []) {
19
+ const from = ws.codeRepoOf(a);
20
+ if (from !== to)
21
+ before.get(to)?.add(from);
22
+ }
23
+ }
24
+ const out = [];
25
+ const placed = new Set();
26
+ while (out.length < ordered.length) {
27
+ const next = ordered.find((r) => !placed.has(r.slug) && [...(before.get(r.slug) ?? [])].every((b) => placed.has(b)));
28
+ if (!next) {
29
+ // A cycle: the rest in the configuration's order.
30
+ for (const r of ordered)
31
+ if (!placed.has(r.slug))
32
+ out.push(r);
33
+ break;
34
+ }
35
+ out.push(next);
36
+ placed.add(next.slug);
37
+ }
38
+ const hub = repos.find((r) => r.isHub);
39
+ if (hub && !own.has(hub.slug))
40
+ out.push(hub);
41
+ // With every document in the hub, its release carries every spec's catalog: it goes after
42
+ // the code, unless code elsewhere relies on the hub's own code, which must be deployed first.
43
+ if (hub && own.has(hub.slug) && ws.config.documents === "hub") {
44
+ const relied = [...before.values()].some((from) => from.has(hub.slug));
45
+ if (!relied)
46
+ return [...out.filter((r) => r.slug !== hub.slug), hub];
47
+ }
48
+ return out;
49
+ }
50
+ /** The releases of an epic, in merge order. */
51
+ export function releasesOf(ws, specs) {
52
+ const order = releaseOrder(ws, specs);
53
+ return order.map((repo, i) => ({ repo, order: i + 1, of: order.length }));
54
+ }
55
+ /**
56
+ * A release change's description for one repository: its marker names the
57
+ * repository and its place in the order, and the "Merge order" line says so.
58
+ */
59
+ export function releaseBody(body, release, all) {
60
+ const names = all.map((r) => r.repo.slug).join(" → ");
61
+ const previous = all[release.order - 2]?.repo.slug;
62
+ const line = `- Merge order: **${release.order} of ${release.of}** — ${names}. ${previous ? `Merge this after ${previous} is deployed.` : "Merge this first."}`;
63
+ return body
64
+ .replace(/(<!--\s*cupola:change\s+)(\{.*?\})(\s*-->)/, (_m, a, json, c) => {
65
+ let marker;
66
+ try {
67
+ marker = JSON.parse(json);
68
+ }
69
+ catch {
70
+ return `${a}${json}${c}`;
71
+ }
72
+ return `${a}${JSON.stringify({ ...marker, repo: release.repo.slug, order: release.order, of: release.of })}${c}`;
73
+ })
74
+ .replace(/^- Merge order:.*$/m, line);
75
+ }
76
+ /** Each release with its change, if opened. */
77
+ export async function releaseChanges(io, ws, epic, releases) {
78
+ const out = [];
79
+ for (const r of releases) {
80
+ const host = ws.host(io, r.repo.slug);
81
+ out.push({ ...r, host, change: (await host.findChange(epicBranchName(epic))) ?? null });
82
+ }
83
+ return out;
84
+ }
package/dist/repo.js ADDED
@@ -0,0 +1,13 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const run = promisify(execFile);
4
+ /** The root of the git repository containing `cwd`. */
5
+ export async function repoRoot(cwd) {
6
+ try {
7
+ const { stdout } = await run("git", ["rev-parse", "--show-toplevel"], { cwd });
8
+ return stdout.trim();
9
+ }
10
+ catch {
11
+ throw new Error(`${cwd} is not inside a git repository`);
12
+ }
13
+ }
@@ -0,0 +1,132 @@
1
+ import { z } from "zod";
2
+ import { PRECISE, stripComments } from "./epic.js";
3
+ import { parseFrontMatter } from "./frontmatter.js";
4
+ /**
5
+ * A runbook: a procedure a human carries out on the running system or outside
6
+ * the code, agreed once at an epic's start and run any number of times. It is a
7
+ * folder in the hub (`<paths.runbooks>/<id>/`): `runbook.md`, front matter then
8
+ * steps `P#` with `- key: value` bullets, and `executions/<n>.md`, one record
9
+ * per run of it.
10
+ */
11
+ const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
12
+ const STEP = /^P\d+$/;
13
+ const KEYS = ["do", "check", "stop-if", "undo"];
14
+ const PARAM = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
15
+ /** The name of a runbook's document inside its folder. */
16
+ export const RUNBOOK_FILE = "runbook.md";
17
+ /** A runbook's document, relative to the hub's root. */
18
+ export function runbookPath(paths, id) {
19
+ return `${paths.runbooks}/${id}/${RUNBOOK_FILE}`;
20
+ }
21
+ /** Where a runbook's executions are, relative to the hub's root. */
22
+ export function executionsDir(paths, runbook) {
23
+ return `${paths.runbooks}/${runbook}/executions`;
24
+ }
25
+ /** The record of one execution of a runbook. */
26
+ export function executionPath(paths, runbook, n) {
27
+ return `${executionsDir(paths, runbook)}/${n}.md`;
28
+ }
29
+ export const RunbookFront = z.strictObject({
30
+ kind: z.literal("runbook"),
31
+ method: z.number().int(),
32
+ id: z.string().regex(KEBAB, "a kebab-case name"),
33
+ title: z.string().min(1),
34
+ "applies-to": z.array(z.string().min(1)).min(1),
35
+ /** What one run is given, by name, with what it means: each execution records their values. */
36
+ params: z
37
+ .record(z.string().regex(PARAM, "param names are kebab-case"), z.string().min(1))
38
+ .default({}),
39
+ });
40
+ const FIELD = /^-\s+([a-z][a-z0-9-]*):\s*(.*)$/;
41
+ export function parseRunbook(raw) {
42
+ const text = raw.replace(/^/, "").replace(/\r\n?/g, "\n");
43
+ const { data, body } = parseFrontMatter(text);
44
+ const offset = text.slice(0, text.length - body.length).split("\n").length - 1;
45
+ const steps = [];
46
+ const placeholders = [];
47
+ let current;
48
+ let precise = false;
49
+ let comment = false;
50
+ let fence = false;
51
+ body.split("\n").forEach((original, i) => {
52
+ const n = offset + i + 1;
53
+ if (!comment && !fence && original.trim() === PRECISE) {
54
+ precise = true;
55
+ return;
56
+ }
57
+ if (/^\s*(```|~~~)/.test(original)) {
58
+ fence = !fence;
59
+ return;
60
+ }
61
+ if (fence)
62
+ return;
63
+ const had = comment || original.includes("<!--");
64
+ let line;
65
+ [line, comment] = stripComments(original, comment);
66
+ if (had && line.trim() === "")
67
+ return;
68
+ if (line.includes("{{"))
69
+ placeholders.push(n);
70
+ const heading = /^#{1,6}\s+(\S+)\s*(.*)$/.exec(line);
71
+ if (heading) {
72
+ const id = heading[1] ?? "";
73
+ current =
74
+ precise && STEP.test(id)
75
+ ? { id, title: (heading[2] ?? "").trim(), line: n, fields: [] }
76
+ : undefined;
77
+ if (current)
78
+ steps.push(current);
79
+ return;
80
+ }
81
+ const field = FIELD.exec(line);
82
+ if (field && current)
83
+ current.fields.push({ key: field[1] ?? "", value: (field[2] ?? "").trim(), line: n });
84
+ });
85
+ return { front: data, steps, precise, placeholders };
86
+ }
87
+ /** Whether a step cannot be undone: the human's go is needed before it starts. */
88
+ export function irreversible(step) {
89
+ return step.fields.find((f) => f.key === "undo")?.value.toLowerCase() === "none";
90
+ }
91
+ /** What `cupola check` lints in a runbook. */
92
+ export function checkRunbook(file, raw, components) {
93
+ const problems = [];
94
+ const p = (message, line) => problems.push({ file, ...(line ? { line } : {}), message });
95
+ const book = parseRunbook(raw);
96
+ const front = RunbookFront.safeParse(book.front);
97
+ if (!front.success) {
98
+ for (const issue of front.error.issues)
99
+ p(`front matter ${issue.path.join(".") || "(root)"}: ${issue.message}`);
100
+ }
101
+ const name = file.split("/").at(-2);
102
+ if (front.success && front.data.id !== name)
103
+ p(`id is ${front.data.id}, but its folder is ${name}`);
104
+ for (const c of front.success ? front.data["applies-to"] : [])
105
+ if (!components.includes(c))
106
+ p(`applies-to: ${c} is not a configured component`);
107
+ if (!book.precise)
108
+ p("no `<!-- precise layer -->` marker, so no step is read");
109
+ for (const line of book.placeholders)
110
+ p("template placeholder left ({{…}})", line);
111
+ if (book.precise && book.steps.length === 0)
112
+ p("no steps (### P1 …)");
113
+ const seen = new Set();
114
+ for (const s of book.steps) {
115
+ if (seen.has(s.id))
116
+ p(`${s.id} is used twice`, s.line);
117
+ seen.add(s.id);
118
+ if (s.title === "")
119
+ p(`${s.id} has no title`, s.line);
120
+ for (const f of s.fields)
121
+ if (!KEYS.includes(f.key))
122
+ p(`${s.id}: unknown key ${f.key}`, f.line);
123
+ const count = (key) => s.fields.filter((f) => f.key === key && f.value !== "").length;
124
+ if (count("do") === 0)
125
+ p(`${s.id} has no do`, s.line);
126
+ if (count("check") === 0)
127
+ p(`${s.id} has no check`, s.line);
128
+ if (count("undo") !== 1)
129
+ p(`${s.id} needs one undo: how to undo it, or none when it cannot be undone`, s.line);
130
+ }
131
+ return problems;
132
+ }
@@ -0,0 +1,80 @@
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ /** A write that would leave the repository through a symbolic link, or a path outside it. */
5
+ export class OutsideRepositoryError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "OutsideRepositoryError";
9
+ }
10
+ }
11
+ /**
12
+ * Checks that writing `path` (absolute, or relative to `root`) stays inside
13
+ * the repository at `root`: the target is not a symbolic link, and the real
14
+ * path of its nearest existing directory is under the repository's real path,
15
+ * so that no link committed to the repository leads the write elsewhere.
16
+ * Returns the absolute path.
17
+ */
18
+ export function assertInsideRepository(root, path) {
19
+ const target = resolve(root, path);
20
+ let realRoot;
21
+ try {
22
+ realRoot = realpathSync(root);
23
+ }
24
+ catch (error) {
25
+ throw new OutsideRepositoryError(`the repository at ${root} cannot be resolved (${error.code ?? "unknown"}); nothing was written`);
26
+ }
27
+ // Paths are compared as strings: on a case-insensitive file system, or with
28
+ // Windows short (8.3) names, a path inside may be spelled differently and be refused.
29
+ if (!within(resolve(root), target)) {
30
+ throw new OutsideRepositoryError(`${path} is outside the repository; nothing was written`);
31
+ }
32
+ let stat;
33
+ try {
34
+ stat = lstatSync(target);
35
+ }
36
+ catch {
37
+ stat = undefined;
38
+ }
39
+ if (stat?.isSymbolicLink()) {
40
+ throw new OutsideRepositoryError(`${relative(root, target)} is a symbolic link; Cupola does not write through links`);
41
+ }
42
+ let dir = stat?.isDirectory() ? target : dirname(target);
43
+ for (;;) {
44
+ try {
45
+ lstatSync(dir);
46
+ break;
47
+ }
48
+ catch {
49
+ const up = dirname(dir);
50
+ if (up === dir)
51
+ break;
52
+ dir = up;
53
+ }
54
+ }
55
+ let real;
56
+ try {
57
+ real = realpathSync(dir);
58
+ }
59
+ catch {
60
+ real = "";
61
+ }
62
+ if (real === "" || !within(realRoot, real)) {
63
+ throw new OutsideRepositoryError(`${relative(root, target)} leads outside the repository through a symbolic link; nothing was written`);
64
+ }
65
+ return target;
66
+ }
67
+ /** Creates a directory inside the repository, with its parents, refusing to follow links out of it. */
68
+ export async function mkdirInside(root, path) {
69
+ await mkdir(assertInsideRepository(root, path), { recursive: true });
70
+ }
71
+ /** Writes a file inside the repository, creating its directory, refusing to follow links out of it. */
72
+ export async function writeInside(root, path, text) {
73
+ const target = assertInsideRepository(root, path);
74
+ await mkdir(dirname(target), { recursive: true });
75
+ await writeFile(target, text);
76
+ }
77
+ function within(dir, path) {
78
+ const rel = relative(dir, path);
79
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
80
+ }
package/dist/spec.js ADDED
@@ -0,0 +1,171 @@
1
+ import { z } from "zod";
2
+ import { EpicFront, parseEpic } from "./epic.js";
3
+ import { METHOD } from "./method/v1.js";
4
+ /**
5
+ * A full-mode spec: the spec engine's documents under
6
+ * `.kiro/specs/<epic>-<component>/`, whose `spec.json` carries Cupola's
7
+ * namespaced block.
8
+ */
9
+ export const CupolaBlock = z.strictObject({
10
+ method: z.int().positive(),
11
+ epic: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "must be a work id (kebab-case)"),
12
+ component: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "must be kebab-case"),
13
+ /** Each implemented contract, with the epic revision it implements. */
14
+ contracts: z.record(z.string().regex(/^C\d+$/), z.int().positive()),
15
+ /** The epic's revision this spec has taken in (the highest `R#`, 1 without one). */
16
+ revision: z.int().positive().optional(),
17
+ });
18
+ export class SpecError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = "SpecError";
22
+ }
23
+ }
24
+ /** The branch an epic with two or more specs integrates on. */
25
+ export function epicBranchName(epic) {
26
+ return `epic/${epic}`;
27
+ }
28
+ /** The spec's name: the epic's and its component's. */
29
+ export function specName(epic, component) {
30
+ return `${epic}-${component}`;
31
+ }
32
+ /**
33
+ * The names of an epic's specs, in the order of its `specs`: a
34
+ * follow-up spec of the same component, added by a revision, is `-2`, `-3`, ….
35
+ */
36
+ export function specNamesOf(epic, specs) {
37
+ const seen = new Map();
38
+ return specs.map(({ component }) => {
39
+ const n = (seen.get(component) ?? 0) + 1;
40
+ seen.set(component, n);
41
+ return {
42
+ name: n === 1 ? specName(epic, component) : `${specName(epic, component)}-${n}`,
43
+ component,
44
+ };
45
+ });
46
+ }
47
+ export function revisionsOf(epic) {
48
+ return epic.entries
49
+ .filter((e) => e.type === "R")
50
+ .map((e) => {
51
+ const plans = new Map();
52
+ let changed = [];
53
+ let from;
54
+ for (const f of e.fields) {
55
+ if (f.key === "changed")
56
+ changed = f.value.split(/[,\s]+/).filter(Boolean);
57
+ else if (f.key === "from")
58
+ from = /card\s+(\S+#\d+)/.exec(f.value)?.[1];
59
+ else if (f.key !== "removed")
60
+ plans.set(f.key, f.value.trim().split(/\s/)[0] ?? "");
61
+ }
62
+ return { n: Number(e.id.slice(1)), changed, from, plans };
63
+ })
64
+ .sort((a, b) => a.n - b.n);
65
+ }
66
+ /** The epic's revision: its highest `R#`, 1 without one. */
67
+ export function currentRevision(epic) {
68
+ return Math.max(1, ...revisionsOf(epic).map((r) => r.n));
69
+ }
70
+ /** The epic's front matter, or an error naming the file. */
71
+ export function epicFront(path, raw) {
72
+ const epic = parseEpic(raw);
73
+ const front = EpicFront.safeParse(epic.front);
74
+ if (!front.success) {
75
+ throw new SpecError(`${path}: its front matter is not an epic's (cupola check says why)`);
76
+ }
77
+ return { front: front.data, epic };
78
+ }
79
+ /** The contracts an epic gives a component, with their revisions. */
80
+ export function contractsOf(epic, component) {
81
+ const out = {};
82
+ for (const e of epic.entries) {
83
+ if (e.type !== "C")
84
+ continue;
85
+ const owner = e.title.split(/\s+[—–-]\s+/)[0]?.trim();
86
+ if (owner !== component)
87
+ continue;
88
+ const rev = Number(e.fields.find((f) => f.key === "rev")?.value);
89
+ out[e.id] = Number.isInteger(rev) && rev > 0 ? rev : 1;
90
+ }
91
+ return out;
92
+ }
93
+ /** The block a new spec of `component` in `epic` starts with. */
94
+ export function newBlock(epicId, epic, component) {
95
+ return {
96
+ method: METHOD,
97
+ epic: epicId,
98
+ component,
99
+ contracts: contractsOf(epic, component),
100
+ revision: currentRevision(epic),
101
+ };
102
+ }
103
+ /** Reads the Cupola block of a spec.json; undefined for a plain cc-sdd spec. */
104
+ export function readBlock(path, raw) {
105
+ let json;
106
+ try {
107
+ json = JSON.parse(raw);
108
+ }
109
+ catch (error) {
110
+ throw new SpecError(`${path}: not valid JSON: ${error.message}`);
111
+ }
112
+ const block = json?.cupola;
113
+ if (block === undefined)
114
+ return undefined;
115
+ const parsed = CupolaBlock.safeParse(block);
116
+ if (!parsed.success) {
117
+ const why = parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
118
+ throw new SpecError(`${path}: its cupola block is invalid: ${why}`);
119
+ }
120
+ return parsed.data;
121
+ }
122
+ /**
123
+ * A new spec.json from the engine's `init.json`: the spec's name, the time,
124
+ * the language, and Cupola's block.
125
+ */
126
+ export function initSpecJson(template, spec, language, now, block) {
127
+ const filled = template
128
+ .replaceAll("{{FEATURE_NAME}}", spec)
129
+ .replaceAll("{{TIMESTAMP}}", now)
130
+ .replace(/("language"\s*:\s*)"[^"]*"/, `$1${JSON.stringify(language)}`);
131
+ let json;
132
+ try {
133
+ json = JSON.parse(filled);
134
+ }
135
+ catch (error) {
136
+ throw new SpecError(`the engine's init.json is not valid JSON: ${error.message}`);
137
+ }
138
+ return `${JSON.stringify({ ...json, language, cupola: block }, null, 2)}\n`;
139
+ }
140
+ /**
141
+ * Puts the block back when the engine's skills rewrote spec.json without it
142
+ * or changed it. Returns the new text, or undefined when the
143
+ * block is intact. The method and the contract revisions the spec was created
144
+ * with are kept; only a block lost whole takes `expected`'s.
145
+ */
146
+ export function reassertBlock(path, raw, expected) {
147
+ let json;
148
+ try {
149
+ json = JSON.parse(raw);
150
+ }
151
+ catch (error) {
152
+ throw new SpecError(`${path}: not valid JSON: ${error.message}`);
153
+ }
154
+ const parsed = CupolaBlock.safeParse(json.cupola);
155
+ // Work in flight keeps its method; only a block lost whole takes the expected one.
156
+ const block = parsed.success
157
+ ? {
158
+ ...expected,
159
+ method: parsed.data.method,
160
+ contracts: parsed.data.contracts,
161
+ revision: parsed.data.revision ?? expected.revision,
162
+ }
163
+ : expected;
164
+ // The contracts are kept as they were, so only the identifying fields can differ.
165
+ if (parsed.success &&
166
+ parsed.data.epic === block.epic &&
167
+ parsed.data.component === block.component) {
168
+ return undefined;
169
+ }
170
+ return `${JSON.stringify({ ...json, cupola: block }, null, 2)}\n`;
171
+ }