@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,243 @@
1
+ import { candidatesOf, pushLock, readLocks, removeLock, } from "../e2e.js";
2
+ import { takeOverNames } from "../record.js";
3
+ import { ago } from "../status.js";
4
+ import { workspace } from "../workspace.js";
5
+ function inUse(env, held) {
6
+ const l = held.lock;
7
+ return (`the shared e2e environment ${env} is in use by ${l.work} (${l.who}, session ${l.session}, since ${l.since}); ` +
8
+ `if that session has ended, run again with --take-over ${l.id}`);
9
+ }
10
+ /** The needs the profile does not know: neither an environment nor a pool of shared ones. */
11
+ export function unknownNeeds(profile, needs) {
12
+ return needs.filter((n) => candidatesOf(profile, n) === undefined);
13
+ }
14
+ function needed(profile, need) {
15
+ const candidates = candidatesOf(profile, need);
16
+ if (!candidates) {
17
+ throw new Error(`${need} is neither an environment nor a pool of shared environments in the e2e profile`);
18
+ }
19
+ return candidates;
20
+ }
21
+ function placeOf(where) {
22
+ return typeof where === "string" ? () => where : where;
23
+ }
24
+ /** The locks of the environments, read from each root they live in. */
25
+ async function readAll(rootOf, environments) {
26
+ const roots = [...new Set(environments.map(rootOf))];
27
+ const out = new Map();
28
+ for (const root of roots) {
29
+ for (const [env, held] of await readLocks(root))
30
+ if (rootOf(env) === root)
31
+ out.set(env, held);
32
+ }
33
+ return out;
34
+ }
35
+ /** Every environment a set of needs may take. */
36
+ function envsOf(profile, needs) {
37
+ return needs.flatMap((n) => (candidatesOf(profile, n) ?? []).map((c) => c.id));
38
+ }
39
+ /**
40
+ * Takes a shared environment for each need; when one is in use, takes none —
41
+ * giving back what it took, and what this work held already — and says why.
42
+ */
43
+ export async function claimEnvironments(where, profile, claim) {
44
+ const rootOf = placeOf(where);
45
+ const locks = await readAll(rootOf, envsOf(profile, claim.needs));
46
+ const taken = [];
47
+ const tookOver = [];
48
+ // Every lock this call counts as this work's, with its commit: given back unless all are taken.
49
+ const pushed = [];
50
+ const lockFor = (environment) => ({
51
+ kind: "lock",
52
+ method: 1,
53
+ id: claim.marker,
54
+ environment,
55
+ work: claim.work,
56
+ phase: claim.phase,
57
+ who: claim.runner.who,
58
+ session: claim.runner.session,
59
+ since: claim.runner.now,
60
+ cli: claim.runner.cli,
61
+ });
62
+ const take = async (env, replacing) => {
63
+ if (replacing)
64
+ await removeLock(rootOf(env), env, replacing.sha);
65
+ const sha = await pushLock(rootOf(env), lockFor(env));
66
+ if (!sha)
67
+ return false;
68
+ pushed.push({ env, sha });
69
+ taken.push(env);
70
+ return true;
71
+ };
72
+ const giveBack = async () => {
73
+ for (const p of pushed)
74
+ await removeLock(rootOf(p.env), p.env, p.sha);
75
+ };
76
+ const choices = [];
77
+ const chosen = (id) => choices.some((c) => c.env === id);
78
+ for (const need of claim.needs) {
79
+ const all = needed(profile, need);
80
+ if (all.length === 0)
81
+ continue; // no lock needed
82
+ const candidates = all.filter((c) => !chosen(c.id));
83
+ // Already this work's (a run resumed, perhaps in another session), then a free one, then a
84
+ // take-over.
85
+ const mine = candidates.find((c) => locks.get(c.id)?.lock.work === claim.work);
86
+ const free = candidates.find((c) => !locks.has(c.id));
87
+ const over = candidates.find((c) => {
88
+ const held = locks.get(c.id);
89
+ return held !== undefined && takeOverNames(claim.runner.takeOver, held.lock);
90
+ });
91
+ if (mine) {
92
+ const held = locks.get(mine.id);
93
+ const same = held.lock.session === claim.runner.session && held.lock.id === claim.marker;
94
+ choices.push({ env: mine.id, held, how: same ? "keep" : "retake" });
95
+ }
96
+ else if (free)
97
+ choices.push({ env: free.id, how: "free" });
98
+ else if (over)
99
+ choices.push({ env: over.id, held: locks.get(over.id), how: "over" });
100
+ else {
101
+ // It waits holding nothing: what this work held already is given back (all or none).
102
+ for (const [env, held] of locks) {
103
+ if (held.lock.work === claim.work)
104
+ await removeLock(rootOf(env), env, held.sha);
105
+ }
106
+ const busy = candidates.map((c) => [c.id, locks.get(c.id)]).find(([, h]) => h);
107
+ return {
108
+ waiting: busy
109
+ ? inUse(busy[0], busy[1])
110
+ : `every shared e2e environment for ${need} is taken by this run's other needs`,
111
+ };
112
+ }
113
+ }
114
+ try {
115
+ for (const c of choices) {
116
+ if (c.how === "keep" && c.held) {
117
+ pushed.push({ env: c.env, sha: c.held.sha });
118
+ taken.push(c.env);
119
+ continue;
120
+ }
121
+ if (await take(c.env, c.how === "free" ? undefined : c.held)) {
122
+ if (c.how === "over" && c.held) {
123
+ const l = c.held.lock;
124
+ tookOver.push(`${c.env} from ${l.work} (${l.who}, session ${l.session})`);
125
+ }
126
+ continue;
127
+ }
128
+ // Someone pushed first, just now.
129
+ await giveBack();
130
+ const now = await readAll(rootOf, [c.env]);
131
+ const held = now.get(c.env);
132
+ return {
133
+ waiting: held
134
+ ? inUse(c.env, held)
135
+ : `the shared e2e environment ${c.env} was taken just now; run again`,
136
+ };
137
+ }
138
+ }
139
+ catch (error) {
140
+ // All or none: a failure halfway gives back what this call took.
141
+ await giveBack().catch(() => { });
142
+ throw error;
143
+ }
144
+ return { taken, tookOver };
145
+ }
146
+ /** Releases this work's locks on the environments. */
147
+ export async function releaseEnvironments(where, environments, work) {
148
+ if (environments.length === 0)
149
+ return;
150
+ const rootOf = placeOf(where);
151
+ const locks = await readAll(rootOf, environments);
152
+ for (const env of environments) {
153
+ const held = locks.get(env);
154
+ if (held && held.lock.work === work)
155
+ await removeLock(rootOf(env), env, held.sha);
156
+ }
157
+ }
158
+ /** Why the needs cannot be met now, without taking anything; undefined when they can. */
159
+ export async function environmentsInUse(where, profile, needs, work) {
160
+ let locks;
161
+ try {
162
+ locks = await readAll(placeOf(where), envsOf(profile, needs));
163
+ }
164
+ catch {
165
+ return undefined; // origin unreachable: the run itself will find out
166
+ }
167
+ for (const need of needs) {
168
+ const candidates = candidatesOf(profile, need) ?? [];
169
+ if (candidates.length === 0)
170
+ continue;
171
+ const open = candidates.some((c) => {
172
+ const held = locks.get(c.id);
173
+ return !held || held.lock.work === work;
174
+ });
175
+ if (!open) {
176
+ const [env, held] = candidates.map((c) => [c.id, locks.get(c.id)])[0];
177
+ return inUse(env, held);
178
+ }
179
+ }
180
+ return undefined;
181
+ }
182
+ /**
183
+ * `cupola locks [<component>]`: the locks on shared e2e environments, read from origin of each
184
+ * repository that keeps a component's work. Read only: nothing is taken or released.
185
+ */
186
+ export async function listLocks(io, component, opts) {
187
+ const ws = await workspace(io);
188
+ if (component !== undefined && !ws.config.components.some((c) => c.name === component))
189
+ throw new Error(`${component} is not a component of the configuration`);
190
+ const now = io.now?.() ?? new Date();
191
+ const locks = [];
192
+ const unreachable = [];
193
+ for (const slug of ws.slugs) {
194
+ let root;
195
+ try {
196
+ root = slug === ws.here.slug ? ws.root : ws.checkout(slug).main;
197
+ }
198
+ catch {
199
+ unreachable.push(`${slug}: not cloned (\`cupola workspace setup\`)`);
200
+ continue;
201
+ }
202
+ let held;
203
+ try {
204
+ held = await readLocks(root);
205
+ }
206
+ catch {
207
+ unreachable.push(`${slug}: its origin could not be read`);
208
+ continue;
209
+ }
210
+ for (const [environment, { lock }] of held) {
211
+ // An environment is named `<component>.<name>`.
212
+ const of = environment.split(".")[0] ?? "";
213
+ if (component !== undefined && of !== component)
214
+ continue;
215
+ locks.push({
216
+ environment,
217
+ component: of,
218
+ repo: slug,
219
+ work: lock.work,
220
+ phase: lock.phase,
221
+ who: lock.who,
222
+ session: lock.session,
223
+ since: lock.since,
224
+ ago: ago(lock.since, now) ?? null,
225
+ id: lock.id,
226
+ });
227
+ }
228
+ }
229
+ locks.sort((a, b) => a.environment.localeCompare(b.environment));
230
+ if (opts.json) {
231
+ io.out(JSON.stringify({ locks, ...(unreachable.length > 0 ? { unreachable } : {}) }));
232
+ return 0;
233
+ }
234
+ if (locks.length === 0)
235
+ io.out("No shared e2e environment is locked.");
236
+ for (const l of locks) {
237
+ io.out(`${l.environment}: ${l.work} (${l.phase}), ${l.who}, session ${l.session}, since ${l.since}` +
238
+ `${l.ago ? ` (${l.ago})` : ""}; if that session has ended, its run takes it over with --take-over ${l.id}`);
239
+ }
240
+ for (const u of unreachable)
241
+ io.out(`not read: ${u}`);
242
+ return 0;
243
+ }
@@ -0,0 +1,185 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, rm } from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { loadConfig } from "../config.js";
5
+ import { commitPaths, git, gitUserEmail, workBranch } from "../git.js";
6
+ import { gateComments, hostReactions, REACTION_KINDS, reactionFile, reactionsDir, SESSION, sessionReactions, triesOf, tryBranch, } from "../reaction.js";
7
+ import { repoRoot } from "../repo.js";
8
+ import { assertInsideRepository, writeInside } from "../safe-write.js";
9
+ import { fsTree } from "../tree.js";
10
+ import { runsOn, workBranchName } from "../work.js";
11
+ import { openChangeOf, readBody } from "./change.js";
12
+ import { addWorktree, existingWorktree } from "./worktree.js";
13
+ /** Every reaction of the work in this checkout: on its open changes, and given in a session. */
14
+ async function gather(io, id) {
15
+ const { root, all } = await openChangeOf(io, id);
16
+ const config = await loadConfig(root);
17
+ const where = new Map();
18
+ const reactions = [];
19
+ const unread = [];
20
+ for (const c of all) {
21
+ const got = await hostReactions(c.host, c.change, config);
22
+ if (got.unread)
23
+ unread.push(`${c.change.url}: ${got.unread}`);
24
+ for (const r of got.reactions) {
25
+ where.set(r.id, c);
26
+ reactions.push({ ...r, from: "host" });
27
+ }
28
+ }
29
+ for (const r of await sessionReactions(fsTree(root), id))
30
+ reactions.push({ ...r, from: "session" });
31
+ reactions.sort((a, b) => a.at.localeCompare(b.at));
32
+ return { root, reactions, where, unread };
33
+ }
34
+ /**
35
+ * `cupola reaction list <work>`: the reactions of the work's gate, oldest
36
+ * first, from its changes and from sessions: each with whether it is
37
+ * answered, and `gate` for the comments a No-Go takes in (those given since
38
+ * the last No-Go was processed). `pending` lists the ones not processed yet.
39
+ */
40
+ export async function reactionList(io, id, opts) {
41
+ const { root, reactions, unread } = await gather(io, id);
42
+ const taken = new Set(gateComments(reactions).map((r) => r.id));
43
+ const shown = reactions.map((r) => ({
44
+ id: r.id,
45
+ kind: r.kind,
46
+ who: r.author,
47
+ at: r.at,
48
+ body: r.body,
49
+ place: r.place,
50
+ answered: r.answered,
51
+ from: r.from,
52
+ ...(taken.has(r.id) ? { gate: true } : {}),
53
+ }));
54
+ const pending = shown.filter((r) => !r.answered).map((r) => r.id);
55
+ const tries = await triesOf(root, id);
56
+ if (opts.json) {
57
+ io.out(JSON.stringify({ reactions: shown, pending, tries, ...(unread.length ? { unread } : {}) }));
58
+ return 0;
59
+ }
60
+ io.out(`${pending.length} not processed${tries.length ? `; tries: ${tries.join(", ")}` : ""}`);
61
+ for (const r of shown)
62
+ io.out(` ${r.id} ${r.kind} by ${r.who}${r.answered ? " (answered)" : ""}: ${r.body.split("\n")[0] ?? ""}`);
63
+ for (const u of unread)
64
+ io.out(` not read: ${u}`);
65
+ return 0;
66
+ }
67
+ /**
68
+ * `cupola reaction reply <work> --reaction <id> --body-file <f>`: answers a
69
+ * reaction, which processes it. On the change, the reply goes there; a
70
+ * session's reaction has its file removed (the reply is the session's report).
71
+ */
72
+ export async function reactionReply(io, id, opts) {
73
+ if (!opts.reaction)
74
+ throw new Error("give the reaction to answer: --reaction <id>");
75
+ if (opts.reaction.startsWith(SESSION)) {
76
+ const root = await repoRoot(io.cwd);
77
+ const branch = await workBranch(root);
78
+ if (!runsOn(branch, id))
79
+ throw new Error(`${id} is on ${workBranchName(id)}, but this checkout is on ${branch}`);
80
+ const n = opts.reaction.slice(SESSION.length);
81
+ const file = join(reactionsDir(id), `${n}.md`);
82
+ if (!/^\d+$/.test(n) || !existsSync(join(root, file)))
83
+ throw new Error(`no reaction ${opts.reaction} of ${id} waits in this checkout`);
84
+ await rm(assertInsideRepository(root, file));
85
+ await commitPaths(root, branch, [file], `cupola: ${id}: reaction ${n} processed`);
86
+ io.out(opts.json ? JSON.stringify({ answered: opts.reaction }) : `processed ${opts.reaction}`);
87
+ return 0;
88
+ }
89
+ if (!opts.bodyFile)
90
+ throw new Error("give the reply: --body-file <file>");
91
+ const body = await readBody(io.cwd, opts.bodyFile);
92
+ const { reactions, where } = await gather(io, id);
93
+ const r = reactions.find((x) => x.id === opts.reaction);
94
+ const c = where.get(opts.reaction);
95
+ if (!r || !c)
96
+ throw new Error(`no reaction ${opts.reaction} on the changes of ${id}`);
97
+ await c.host.reply(c.change.number, r.id, body);
98
+ io.out(opts.json ? JSON.stringify({ answered: r.id }) : `answered ${r.id}`);
99
+ return 0;
100
+ }
101
+ /**
102
+ * `cupola reaction add <work> --kind comment|try|no-go [--body-file <f>] [--who <name>]`:
103
+ * keeps a reaction given in a session outside a gate (or to a work whose host
104
+ * takes none) for the next gate, as a file on the work's branch.
105
+ */
106
+ export async function reactionAdd(io, id, opts) {
107
+ const kind = (opts.kind ?? "");
108
+ if (!REACTION_KINDS.includes(kind))
109
+ throw new Error(`give its kind: --kind ${REACTION_KINDS.join("|")}`);
110
+ if (!opts.bodyFile && kind !== "no-go")
111
+ throw new Error("give its words: --body-file <file>");
112
+ const body = opts.bodyFile ? await readFile(resolve(io.cwd, opts.bodyFile), "utf8") : "";
113
+ if (body.includes("{{"))
114
+ throw new Error(`${opts.bodyFile} still has template placeholders`);
115
+ const root = await repoRoot(io.cwd);
116
+ const branch = await workBranch(root);
117
+ if (!runsOn(branch, id))
118
+ throw new Error(`${id} is on ${workBranchName(id)}, but this checkout is on ${branch}`);
119
+ const dir = reactionsDir(id);
120
+ const taken = (await fsTree(root).list(dir))
121
+ .map((f) => Number(/^(\d+)\.md$/.exec(f)?.[1] ?? 0))
122
+ .filter((n) => n > 0);
123
+ // Numbers are never reused while the branch remembers them: a processed one is gone from the
124
+ // directory, but not from its history.
125
+ const history = await git(root, [
126
+ "log",
127
+ "--format=%s",
128
+ "--fixed-strings",
129
+ `--grep=cupola: ${id}: reaction `,
130
+ ]);
131
+ const used = [...history.matchAll(/reaction (\d+)/g)].map((m) => Number(m[1]));
132
+ const n = Math.max(0, ...taken, ...used) + 1;
133
+ const who = opts.who ?? (await gitUserEmail(root));
134
+ const at = (io.now?.() ?? new Date()).toISOString();
135
+ const file = join(dir, `${n}.md`);
136
+ await writeInside(root, file, reactionFile(n, kind, who, at, body));
137
+ await commitPaths(root, branch, [file], `cupola: ${id}: reaction ${n} kept for the gate`);
138
+ const out = { reaction: `${SESSION}${n}`, kind, who, at, file };
139
+ io.out(opts.json ? JSON.stringify(out) : `kept ${out.reaction} (${kind}) for the next gate`);
140
+ return 0;
141
+ }
142
+ /**
143
+ * `cupola try start <work>`: a try of the work in this checkout — the next
144
+ * try branch, from the head of its change, pushed, in a worktree next to this
145
+ * one. The work and its status do not change.
146
+ */
147
+ export async function tryStart(io, id, opts) {
148
+ const root = await repoRoot(io.cwd);
149
+ const branch = await workBranch(root);
150
+ if (!runsOn(branch, id))
151
+ throw new Error(`${id} is on ${workBranchName(id)}, but this checkout is on ${branch}`);
152
+ await git(root, [
153
+ "fetch",
154
+ "--quiet",
155
+ "origin",
156
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
157
+ ]);
158
+ const n = Math.max(0, ...(await triesOf(root, id))) + 1;
159
+ const name = tryBranch(id, n);
160
+ const path = join(dirname(root), `${id}-try-${n}`);
161
+ await addWorktree(root, path, name, { from: `origin/${branch}` });
162
+ await git(path, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${name}`]);
163
+ const out = { try: n, branch: name, path, from: branch };
164
+ io.out(opts.json ? JSON.stringify(out) : `try-${n} on ${name} at ${path}`);
165
+ return 0;
166
+ }
167
+ /**
168
+ * `cupola try remove <work>`: deletes the work's tries — their branches on
169
+ * origin and here, and their worktrees — once its gate is passed.
170
+ */
171
+ export async function tryRemove(io, id, opts) {
172
+ const root = await repoRoot(io.cwd);
173
+ const removed = [];
174
+ for (const n of await triesOf(root, id)) {
175
+ const name = tryBranch(id, n);
176
+ const path = await existingWorktree(root, name);
177
+ if (path)
178
+ await git(root, ["worktree", "remove", "--force", path]);
179
+ await git(root, ["branch", "-D", name]).catch(() => "");
180
+ await git(root, ["push", "--quiet", "origin", "--delete", name]);
181
+ removed.push(name);
182
+ }
183
+ io.out(opts.json ? JSON.stringify({ removed }) : `removed ${removed.length} tries`);
184
+ return 0;
185
+ }
@@ -0,0 +1,139 @@
1
+ import { existsSync } from "node:fs";
2
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { epicPath, pathsAt } from "../config.js";
5
+ import { git, originDefaultBranch } from "../git.js";
6
+ import { codeHost } from "../host/index.js";
7
+ import { writeInside } from "../safe-write.js";
8
+ import { epicFront, readBlock, revisionsOf } from "../spec.js";
9
+ import { gitTree } from "../tree.js";
10
+ import { assertWorkId, workBranchName } from "../work.js";
11
+ import { recordsAbort } from "./epic.js";
12
+ import { fetchOrKeep, workTree } from "./status.js";
13
+ import { trackerOf } from "./work.js";
14
+ /**
15
+ * Revisions of a running epic: the agreed epic on origin's
16
+ * default branch, and the draft of a revision whose `epic` change is open.
17
+ */
18
+ /** The agreed epic's text, from origin's default branch. */
19
+ export async function agreedEpicText(root, epic) {
20
+ const base = await originDefaultBranch(root);
21
+ if (!base)
22
+ return undefined;
23
+ const ref = `refs/remotes/origin/${base}`;
24
+ try {
25
+ await fetchOrKeep(root, `refs/heads/${base}`, ref);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ return gitTree(root, ref).read(epicPath(await pathsAt(root), epic));
31
+ }
32
+ /** The draft of a revision under agreement (its `epic` change is open), or undefined. */
33
+ async function draftEpicText(io, root, epic) {
34
+ const change = await (io.host ?? codeHost)(root).findChange(workBranchName(epic));
35
+ if (change?.state !== "open")
36
+ return undefined;
37
+ return (await workTree(root, workBranchName(epic))).tree.read(epicPath(await pathsAt(root), epic));
38
+ }
39
+ function revisions(path, text) {
40
+ return text === undefined ? [] : revisionsOf(epicFront(path, text).epic);
41
+ }
42
+ /**
43
+ * The plan a revision under agreement has for a component other than
44
+ * `continue`: the spec waits until it is agreed.
45
+ */
46
+ export async function pendingPlan(io, root, epic, component) {
47
+ const path = epicPath(await pathsAt(root), epic);
48
+ const draft = revisions(path, await draftEpicText(io, root, epic));
49
+ if (draft.length === 0)
50
+ return undefined;
51
+ const agreed = Math.max(1, ...revisions(path, await agreedEpicText(root, epic)).map((r) => r.n));
52
+ for (const r of draft.filter((r) => r.n > agreed)) {
53
+ const plan = r.plans.get(component);
54
+ if (plan && plan !== "continue")
55
+ return { revision: r.n, plan };
56
+ }
57
+ return undefined;
58
+ }
59
+ /** The agreed revisions a spec has not taken in yet, with its component's plan in each. */
60
+ export async function revisionsToApply(root, block) {
61
+ const path = epicPath(await pathsAt(root), block.epic);
62
+ return revisions(path, await agreedEpicText(root, block.epic))
63
+ .filter((r) => r.n > (block.revision ?? 1))
64
+ .map((r) => ({ revision: r.n, plan: r.plans.get(block.component) ?? "continue" }));
65
+ }
66
+ /**
67
+ * Cards whose `revise-epic` answer a revision has carried out (its `from:
68
+ * card <spec>#<n>`, agreed or under agreement): they no longer end the run.
69
+ */
70
+ export async function carriedOut(io, root, spec, epic, cards) {
71
+ if (!cards.some((c) => c.effect === "revise-epic"))
72
+ return cards;
73
+ const path = epicPath(await pathsAt(root), epic);
74
+ const from = new Set([
75
+ ...revisions(path, await agreedEpicText(root, epic)),
76
+ ...revisions(path, await draftEpicText(io, root, epic)),
77
+ ].flatMap((r) => (r.from ? [r.from] : [])));
78
+ return cards.map((c) => c.effect === "revise-epic" && from.has(`${spec}#${c.card}`) ? { ...c, effect: "continue" } : c);
79
+ }
80
+ /**
81
+ * Why a spec of a running epic no longer runs, if it does not: an agreed
82
+ * revision drops its component, or the epic was aborted (recorded on its
83
+ * cases).
84
+ */
85
+ export async function droppedBecause(io, root, epic, component) {
86
+ const path = epicPath(await pathsAt(root), epic);
87
+ const agreed = await agreedEpicText(root, epic);
88
+ if (agreed === undefined)
89
+ return undefined;
90
+ const drop = revisionsOf(epicFront(path, agreed).epic).find((r) => r.plans.get(component) === "drop");
91
+ if (drop)
92
+ return `R${drop.n} of ${epic} drops it`;
93
+ const tracker = await trackerOf(io);
94
+ for (const c of epicFront(path, agreed).front.cases) {
95
+ const shown = await tracker.show(c);
96
+ if (shown && recordsAbort(shown.text, epic))
97
+ return `epic ${epic} is aborted`;
98
+ }
99
+ return undefined;
100
+ }
101
+ /** The first agreed revision a spec has not taken in that redesigns it, if any. */
102
+ export async function redesignToTakeIn(root, tree, spec) {
103
+ const file = `.kiro/specs/${spec}/spec.json`;
104
+ const raw = await tree.read(file);
105
+ const block = raw === undefined ? undefined : readBlock(file, raw);
106
+ if (!block)
107
+ return undefined;
108
+ return (await revisionsToApply(root, block)).find((t) => t.plan === "redesign")?.revision;
109
+ }
110
+ /**
111
+ * In a component's repository, which has no epics of its own, the
112
+ * agreed epic a spec runs against is copied from the hub into the worktree at
113
+ * the same path as in the hub, kept out of git by the repository's exclude file, so that
114
+ * the spec and its phases read it where the hub's specs do. Returns whether a
115
+ * copy was written; in the hub, the epic is on the branch itself.
116
+ */
117
+ export async function snapshotEpic(ws, root, epic) {
118
+ assertWorkId(epic);
119
+ if (ws.here.isHub)
120
+ return false;
121
+ const text = await agreedEpicText(ws.hub.main, epic);
122
+ if (text === undefined) {
123
+ throw new Error(`${epicPath(ws.config.paths, epic)} is not on the hub's default branch: is the epic agreed?`);
124
+ }
125
+ const dir = ws.config.paths.epics;
126
+ const exclude = await git(root, [
127
+ "rev-parse",
128
+ "--path-format=absolute",
129
+ "--git-path",
130
+ "info/exclude",
131
+ ]);
132
+ const have = existsSync(exclude) ? await readFile(exclude, "utf8") : "";
133
+ if (!have.split("\n").includes(`/${dir}/`)) {
134
+ await mkdir(dirname(exclude), { recursive: true });
135
+ await appendFile(exclude, `${have === "" || have.endsWith("\n") ? "" : "\n"}/${dir}/\n`);
136
+ }
137
+ await writeInside(root, epicPath(ws.config.paths, epic), text);
138
+ return true;
139
+ }