@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,311 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { epicPath, loadConfig, pathsAt } from "../config.js";
5
+ import { today } from "../day.js";
6
+ import { parseFrontMatter } from "../frontmatter.js";
7
+ import { git, originDefaultBranch } from "../git.js";
8
+ import { codeHost } from "../host/index.js";
9
+ import { parseRecord } from "../record.js";
10
+ import { epicBranchName, epicFront, specNamesOf } from "../spec.js";
11
+ import { gitTree } from "../tree.js";
12
+ import { assertWorkId, runDir, workBranchName } from "../work.js";
13
+ import { epicRepos, mainCheckout, workspace } from "../workspace.js";
14
+ import { fileCases } from "./run.js";
15
+ import { fixSpecsOf, workTree } from "./status.js";
16
+ import { trackerOf } from "./work.js";
17
+ async function fetchBranch(root, branch) {
18
+ try {
19
+ await git(root, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`]);
20
+ }
21
+ catch (error) {
22
+ if (error.code === 2)
23
+ return false;
24
+ throw new Error(`cannot reach origin to look for ${branch}; try again when it is reachable`);
25
+ }
26
+ await git(root, [
27
+ "fetch",
28
+ "--quiet",
29
+ "origin",
30
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
31
+ ]);
32
+ return true;
33
+ }
34
+ /** The agreed epic, read from origin's default branch, and that branch's name. */
35
+ async function agreedEpic(root, id) {
36
+ assertWorkId(id);
37
+ const base = await originDefaultBranch(root);
38
+ if (!base)
39
+ throw new Error("cannot tell origin's default branch, where agreed epics are");
40
+ await fetchBranch(root, base);
41
+ const path = epicPath(await pathsAt(root), id);
42
+ const raw = await gitTree(root, `refs/remotes/origin/${base}`).read(path);
43
+ if (raw === undefined)
44
+ throw new Error(`${path} is not on origin's ${base}: the epic is not agreed`);
45
+ return { base, ...epicFront(path, raw) };
46
+ }
47
+ /**
48
+ * `cupola epic branch <epic>`: the epic branch `epic/<id>` of an agreed epic
49
+ * with two or more specs, created from origin's default branch
50
+ * and pushed when it does not exist yet. Running it again changes nothing.
51
+ */
52
+ export async function epicBranch(io, id, opts) {
53
+ const { hub, repos } = await epicPlaces(io, id);
54
+ const { front } = await agreedEpic(hub, id);
55
+ if (front.specs.length < 2) {
56
+ throw new Error(`${id} has one spec: it runs on its spec's branch, without an epic branch`);
57
+ }
58
+ const branch = epicBranchName(id);
59
+ // One epic branch per repository the epic touches, the hub's included.
60
+ // The repositories are independent: each is reached at once, not one after another.
61
+ const settled = await Promise.allSettled(repos.map(async (repo) => {
62
+ const base = await originDefaultBranch(repo.main);
63
+ if (!base)
64
+ throw new Error(`cannot tell origin's default branch of ${repo.slug}`);
65
+ // Within one repository, one fetch at a time: two at once contend for its refs.
66
+ await fetchBranch(repo.main, base);
67
+ const exists = await fetchBranch(repo.main, branch);
68
+ if (!exists) {
69
+ await git(repo.main, [
70
+ "push",
71
+ "--quiet",
72
+ "origin",
73
+ `refs/remotes/origin/${base}:refs/heads/${branch}`,
74
+ ]);
75
+ await fetchBranch(repo.main, branch);
76
+ }
77
+ return { repo: repo.slug, created: !exists };
78
+ }));
79
+ // Every repository is tried; then every failure is told, not only the first.
80
+ const failed = settled.flatMap((r, i) => r.status === "rejected"
81
+ ? [`${repos[i]?.slug}: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`]
82
+ : []);
83
+ if (failed.length > 0)
84
+ throw new Error(failed.join("\n"));
85
+ const branches = settled.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
86
+ const created = branches.some((b) => b.created);
87
+ const result = {
88
+ epic: id,
89
+ branch,
90
+ created,
91
+ ...(repos.length > 1 ? { branches } : {}),
92
+ };
93
+ io.out(opts.json ? JSON.stringify(result) : `${branch}${created ? " (created)" : ""}`);
94
+ return 0;
95
+ }
96
+ /** The hub's checkout and the repositories an epic touches. */
97
+ async function epicPlaces(io, id) {
98
+ // Checked here, not only in agreedEpic, whose failure below is taken as "not agreed".
99
+ assertWorkId(id);
100
+ const ws = await workspace(io);
101
+ const hub = ws.here.isHub ? ws.root : ws.hub.main;
102
+ if (ws.repos.length === 1)
103
+ return { hub, repos: [{ ...ws.hub, main: ws.root }] };
104
+ const { front } = await agreedEpic(hub, id).catch(async () => {
105
+ // Not agreed: an abort of a draft touches the hub alone.
106
+ return { front: { specs: [] } };
107
+ });
108
+ return {
109
+ hub,
110
+ repos: epicRepos(ws, front.specs.map((s) => s.component)),
111
+ };
112
+ }
113
+ /**
114
+ * `cupola epic sync <epic>`: merges origin's default branch into the epic
115
+ * branch (after every release and fix), in a worktree of its
116
+ * own. On a conflict the worktree is left with the merge in progress, for the
117
+ * AI to resolve, commit, and push; nothing is pushed until then.
118
+ */
119
+ export async function epicSync(io, id, opts) {
120
+ const { repos } = await epicPlaces(io, id);
121
+ // Each repository's epic branch takes in its own default branch; the first conflict stops.
122
+ let merged = false;
123
+ for (const repo of repos) {
124
+ const lines = [];
125
+ const code = await syncOne({ ...io, out: (l) => lines.push(l) }, repo.main, id, { json: true });
126
+ const r = JSON.parse(lines.join("\n"));
127
+ merged ||= r.merged;
128
+ if (code !== 0 || r.conflicts.length > 0) {
129
+ const result = { ...r, ...(repos.length > 1 ? { repo: repo.slug } : {}) };
130
+ io.out(opts.json ? JSON.stringify(result) : `conflicts in ${repo.slug}: ${r.conflicts.join(", ")}`);
131
+ return 1;
132
+ }
133
+ }
134
+ const branch = epicBranchName(id);
135
+ io.out(opts.json
136
+ ? JSON.stringify({ epic: id, branch, merged, conflicts: [] })
137
+ : merged
138
+ ? `merged into ${branch}`
139
+ : `${branch} is up to date`);
140
+ return 0;
141
+ }
142
+ /** Merges one repository's default branch into its epic branch. */
143
+ async function syncOne(io, root, id, opts) {
144
+ const base = await originDefaultBranch(root);
145
+ if (!base)
146
+ throw new Error(`cannot tell origin's default branch in ${root}`);
147
+ await fetchBranch(root, base);
148
+ const branch = epicBranchName(id);
149
+ if (!(await fetchBranch(root, branch)))
150
+ throw new Error(`${branch} is not on origin`);
151
+ const remoteBase = `refs/remotes/origin/${base}`;
152
+ const remoteEpic = `refs/remotes/origin/${branch}`;
153
+ const out = (r, text) => io.out(opts.json ? JSON.stringify(r) : text);
154
+ try {
155
+ await git(root, ["merge-base", "--is-ancestor", remoteBase, remoteEpic]);
156
+ out({ epic: id, branch, merged: false, conflicts: [] }, `${branch} already has ${base}`);
157
+ return 0;
158
+ }
159
+ catch {
160
+ // behind: merge below
161
+ }
162
+ const main = await mainCheckout(root);
163
+ const path = join(dirname(main), `${basename(main)}.worktrees`, `epic-${id}-sync`);
164
+ if (existsSync(path)) {
165
+ throw new Error(`${path} exists: an earlier sync stopped on a conflict. Resolve it there, commit, push to ${branch}, remove the worktree, and run this again`);
166
+ }
167
+ await git(main, ["worktree", "add", "--quiet", "--detach", path, remoteEpic]);
168
+ // Never hides the error that made the sync stop.
169
+ const drop = () => git(main, ["worktree", "remove", "--force", path]).catch(() => "");
170
+ try {
171
+ await git(path, ["merge", "--quiet", "--no-edit", `origin/${base}`]);
172
+ }
173
+ catch (error) {
174
+ const conflicts = (await git(path, ["diff", "--name-only", "--diff-filter=U"]))
175
+ .split("\n")
176
+ .filter(Boolean);
177
+ if (conflicts.length === 0) {
178
+ // Not a conflict: nothing is left behind for a later sync to trip on.
179
+ await drop();
180
+ throw error;
181
+ }
182
+ out({ epic: id, branch, merged: false, conflicts, path }, `conflicts merging ${base} into ${branch} in ${path}: ${conflicts.join(", ")}`);
183
+ return 1;
184
+ }
185
+ try {
186
+ await git(path, ["push", "--quiet", "origin", `HEAD:refs/heads/${branch}`]);
187
+ }
188
+ finally {
189
+ // Pushed, or refused (a spec merged into the epic branch meanwhile): run again either way.
190
+ await drop();
191
+ }
192
+ await fetchBranch(root, branch);
193
+ out({ epic: id, branch, merged: true, conflicts: [] }, `merged ${base} into ${branch}`);
194
+ return 0;
195
+ }
196
+ /** The Log marker of an epic aborted after its start, on each of its cases (its status derives from it). */
197
+ export function abortedMarker(epic) {
198
+ return `<!-- cupola:aborted ${JSON.stringify({ epic })} -->`;
199
+ }
200
+ /** Whether a case's text records the epic as aborted. */
201
+ export function recordsAbort(caseText, epic) {
202
+ for (const m of caseText.matchAll(/<!--\s*cupola:aborted\s+(\{.*?\})\s*-->/g)) {
203
+ try {
204
+ if (JSON.parse(m[1] ?? "{}").epic === epic)
205
+ return true;
206
+ }
207
+ catch {
208
+ // a marker edited by hand names nothing
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+ /**
214
+ * `cupola epic abort <epic> --body-file <reason>`: carries out an abort a
215
+ * human decided. Every open change of the epic is closed — its
216
+ * `epic` change, its specs' and fix specs', its release — with their branches
217
+ * kept for reference; an agreed epic's cases record the abort and its reason.
218
+ * Running it again changes nothing more.
219
+ */
220
+ export async function epicAbort(io, id, opts) {
221
+ if (!opts.bodyFile)
222
+ throw new Error("give the reason, one line: --body-file <file>");
223
+ const reason = (await readFile(resolve(io.cwd, opts.bodyFile), "utf8")).trim();
224
+ if (reason === "" || reason.includes("\n"))
225
+ throw new Error("the reason is one line");
226
+ assertWorkId(id);
227
+ const { hub: root, repos } = await epicPlaces(io, id);
228
+ const base = await originDefaultBranch(root);
229
+ if (base)
230
+ await fetchBranch(root, base);
231
+ const path = epicPath(await pathsAt(root), id);
232
+ const agreedText = base
233
+ ? await gitTree(root, `refs/remotes/origin/${base}`).read(path)
234
+ : undefined;
235
+ let text = agreedText;
236
+ if (text === undefined && (await fetchBranch(root, workBranchName(id)))) {
237
+ text = await gitTree(root, `refs/remotes/origin/${workBranchName(id)}`).read(path);
238
+ }
239
+ if (text === undefined)
240
+ throw new Error(`no epic ${id}: no ${path} agreed or drafted`);
241
+ const { front } = epicFront(path, text);
242
+ // The `system` change of an only spec outside the hub goes with them.
243
+ const branches = [workBranchName(id), epicBranchName(id), workBranchName(`${id}-system`)];
244
+ const names = specNamesOf(id, front.specs).map((s) => s.name);
245
+ // Fix specs are matched by their document: another epic's name may start the same way.
246
+ names.push(...(await fixSpecsOf(root, await loadConfig(root), id, names)));
247
+ branches.push(...names.map(workBranchName));
248
+ // What the runs split off is filed either way; Cupola issue drafts are
249
+ // listed for a human. Only runs that did not reach their gate still hold drafts.
250
+ const drafts = [];
251
+ const cupolaIssues = [];
252
+ for (const [work, branch] of [
253
+ ...names.map((n) => [n, workBranchName(n)]),
254
+ [id, epicBranchName(id)],
255
+ ]) {
256
+ // A spec's run is in its component's repository: the first that has its branch.
257
+ let raw;
258
+ let tree;
259
+ for (const repo of repos) {
260
+ const t = (await workTree(repo.main, branch)).tree;
261
+ raw = await t.read(`${runDir(work)}/record.json`);
262
+ if (raw !== undefined) {
263
+ tree = t;
264
+ break;
265
+ }
266
+ }
267
+ if (raw === undefined || !tree)
268
+ continue;
269
+ for (const d of parseRecord(raw).drafts) {
270
+ const path = `${runDir(work)}/drafts/${d}`;
271
+ const text = await tree.read(path);
272
+ if (text === undefined)
273
+ continue;
274
+ if (parseFrontMatter(text).data.kind === "case")
275
+ drafts.push(text);
276
+ else
277
+ cupolaIssues.push(`${path} on ${branch}`);
278
+ }
279
+ }
280
+ const filed = (await fileCases(io, drafts)).map((c) => c.id);
281
+ const comment = `Aborted: ${reason}\n\nThe branch is kept for reference.`;
282
+ const closed = [];
283
+ // Every repository the epic touches: its epic branch's change and its specs'.
284
+ for (const repo of repos) {
285
+ const host = (io.host ?? codeHost)(repo.main);
286
+ for (const branch of branches) {
287
+ const change = await host.findChange(branch);
288
+ if (change?.state !== "open")
289
+ continue;
290
+ await host.closeChange(change.number, comment);
291
+ closed.push(change.url);
292
+ }
293
+ }
294
+ const logged = [];
295
+ if (agreedText !== undefined) {
296
+ const tracker = await trackerOf(io);
297
+ const day = await today(io);
298
+ for (const c of front.cases) {
299
+ const shown = await tracker.show(c);
300
+ if (!shown || recordsAbort(shown.text, id))
301
+ continue;
302
+ await tracker.log(c, `${day} epic ${id} aborted: ${reason} ${abortedMarker(id)}`);
303
+ logged.push(c);
304
+ }
305
+ }
306
+ const result = { epic: id, closed, logged, filed, cupolaIssues };
307
+ io.out(opts.json
308
+ ? JSON.stringify(result)
309
+ : `aborted ${id}: closed ${closed.length} changes, logged on ${logged.join(", ") || "no case"}`);
310
+ return 0;
311
+ }