@kyuki3rain/cupola 0.1.0 → 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 (84) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +3 -2
  3. package/dist/branch-store.js +73 -0
  4. package/dist/commands/change.js +245 -39
  5. package/dist/commands/epic.js +3 -3
  6. package/dist/commands/execution.js +482 -0
  7. package/dist/commands/locks.js +69 -1
  8. package/dist/commands/reaction.js +185 -0
  9. package/dist/commands/revision.js +4 -4
  10. package/dist/commands/run.js +68 -62
  11. package/dist/commands/setup.js +54 -22
  12. package/dist/commands/spec.js +1 -1
  13. package/dist/commands/status.js +437 -138
  14. package/dist/commands/trace.js +106 -29
  15. package/dist/commands/wait.js +14 -11
  16. package/dist/commands/work.js +12 -7
  17. package/dist/commands/workspace.js +16 -5
  18. package/dist/commands/worktree.js +3 -3
  19. package/dist/config.js +66 -2
  20. package/dist/epic.js +24 -5
  21. package/dist/execution.js +272 -0
  22. package/dist/feedback.js +3 -17
  23. package/dist/host/git.js +224 -0
  24. package/dist/host/github.js +145 -48
  25. package/dist/host/host.js +3 -1
  26. package/dist/host/index.js +63 -0
  27. package/dist/main.js +143 -48
  28. package/dist/reaction.js +110 -0
  29. package/dist/record.js +52 -18
  30. package/dist/runbook.js +26 -5
  31. package/dist/status.js +158 -27
  32. package/dist/templates.js +2 -1
  33. package/dist/tracker/files.js +9 -66
  34. package/dist/tracker/index.js +8 -1
  35. package/dist/tree.js +17 -0
  36. package/dist/work.js +27 -6
  37. package/dist/workspace.js +37 -12
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
  40. package/skills/cupola-abort/SKILL.md +11 -5
  41. package/skills/cupola-adr/SKILL.md +23 -10
  42. package/skills/cupola-catalog/SKILL.md +1 -1
  43. package/skills/cupola-catalog-draft/SKILL.md +6 -4
  44. package/skills/cupola-complete/SKILL.md +35 -15
  45. package/skills/cupola-decide/SKILL.md +64 -25
  46. package/skills/cupola-e2e-setup/SKILL.md +1 -1
  47. package/skills/cupola-epic-accept/SKILL.md +14 -10
  48. package/skills/cupola-epic-create/SKILL.md +67 -27
  49. package/skills/cupola-epic-revise/SKILL.md +39 -18
  50. package/skills/cupola-epic-run/SKILL.md +81 -42
  51. package/skills/cupola-fix/SKILL.md +7 -5
  52. package/skills/cupola-init/SKILL.md +79 -24
  53. package/skills/cupola-intake/SKILL.md +19 -2
  54. package/skills/cupola-operate/SKILL.md +62 -45
  55. package/skills/cupola-resolve/SKILL.md +21 -14
  56. package/skills/cupola-respond/SKILL.md +73 -0
  57. package/skills/cupola-review/SKILL.md +14 -15
  58. package/skills/cupola-spec-design/SKILL.md +15 -10
  59. package/skills/cupola-spec-impl/SKILL.md +6 -4
  60. package/skills/cupola-spec-run/SKILL.md +29 -17
  61. package/skills/cupola-steering/SKILL.md +13 -6
  62. package/skills/cupola-try/SKILL.md +38 -0
  63. package/templates/install/.kiro/steering/operations.md +2 -2
  64. package/templates/install/.kiro/steering/principles.md +1 -1
  65. package/templates/install/cc-sdd/patches.json +1 -1
  66. package/templates/method-1/card.md +11 -3
  67. package/templates/method-1/case.md +2 -2
  68. package/templates/method-1/changes/catalog.md +1 -1
  69. package/templates/method-1/changes/epic.md +3 -2
  70. package/templates/method-1/changes/fix.md +1 -1
  71. package/templates/method-1/changes/release.md +1 -1
  72. package/templates/method-1/changes/spec.md +1 -1
  73. package/templates/method-1/cupola-issue-draft.md +1 -1
  74. package/templates/method-1/epic.md +17 -6
  75. package/templates/method-1/execution.md +55 -0
  76. package/templates/method-1/no-go.md +28 -0
  77. package/templates/method-1/reaction.md +17 -0
  78. package/templates/method-1/record.json +3 -3
  79. package/templates/method-1/report.md +3 -3
  80. package/templates/method-1/runbook.md +8 -2
  81. package/templates/method-1/runner-result.json +1 -1
  82. package/dist/commands/procedure.js +0 -92
  83. package/dist/procedure.js +0 -60
  84. package/templates/method-1/send-back.md +0 -23
package/dist/runbook.js CHANGED
@@ -2,19 +2,40 @@ import { z } from "zod";
2
2
  import { PRECISE, stripComments } from "./epic.js";
3
3
  import { parseFrontMatter } from "./frontmatter.js";
4
4
  /**
5
- * A runbook: the procedure an epic runs on the running system
6
- * or outside the code, kept in the hub (`paths.runbooks`) so that later epics reuse
7
- * it. Front matter, then steps `P#` with `- key: value` bullets.
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.
8
10
  */
9
11
  const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
10
12
  const STEP = /^P\d+$/;
11
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
+ }
12
29
  export const RunbookFront = z.strictObject({
13
30
  kind: z.literal("runbook"),
14
31
  method: z.number().int(),
15
32
  id: z.string().regex(KEBAB, "a kebab-case name"),
16
33
  title: z.string().min(1),
17
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({}),
18
39
  });
19
40
  const FIELD = /^-\s+([a-z][a-z0-9-]*):\s*(.*)$/;
20
41
  export function parseRunbook(raw) {
@@ -77,9 +98,9 @@ export function checkRunbook(file, raw, components) {
77
98
  for (const issue of front.error.issues)
78
99
  p(`front matter ${issue.path.join(".") || "(root)"}: ${issue.message}`);
79
100
  }
80
- const name = file.split("/").at(-1)?.replace(/\.md$/, "");
101
+ const name = file.split("/").at(-2);
81
102
  if (front.success && front.data.id !== name)
82
- p(`id is ${front.data.id}, but the file is ${name}.md`);
103
+ p(`id is ${front.data.id}, but its folder is ${name}`);
83
104
  for (const c of front.success ? front.data["applies-to"] : [])
84
105
  if (!components.includes(c))
85
106
  p(`applies-to: ${c} is not a configured component`);
package/dist/status.js CHANGED
@@ -1,5 +1,99 @@
1
- import { endingCard, pendingSendBacks } from "./record.js";
2
- export function deriveStatus({ work, change, record, cards, finished, feedback, untidy, waiting, revision, dropped, retake, environment, }) {
1
+ import { endingCard, pendingNoGos } from "./record.js";
2
+ /** How long ago `since` was, in words: "3 minutes ago"; undefined when it is not a time. */
3
+ export function ago(since, now = new Date()) {
4
+ const at = Date.parse(since);
5
+ if (Number.isNaN(at))
6
+ return undefined;
7
+ const minutes = Math.max(0, Math.floor((now.getTime() - at) / 60_000));
8
+ const [n, unit] = minutes < 1
9
+ ? [0, ""]
10
+ : minutes < 60
11
+ ? [minutes, "minute"]
12
+ : minutes < 48 * 60
13
+ ? [Math.floor(minutes / 60), "hour"]
14
+ : [Math.floor(minutes / (24 * 60)), "day"];
15
+ return n === 0 ? "less than a minute ago" : `${n} ${unit}${n === 1 ? "" : "s"} ago`;
16
+ }
17
+ /** What a person does at acceptance, by how its host lets them reach the change. */
18
+ function acceptanceText(id, reach) {
19
+ const where = reach.reactions
20
+ ? `on the change (a review that requests changes is a No-Go) or with \`cupola-decide ${id}\``
21
+ : `with \`cupola-decide ${id}\``;
22
+ return `Read "Needs confirmation" in ${reach.read}, ${reach.merge}, then run the command; or comment, ask for a try, or give a No-Go ${where}.`;
23
+ }
24
+ /**
25
+ * A status at a gate (start, acceptance, release) with its reactions: those not processed yet
26
+ * come first — the AI's to process, by a session waiting at the gate or by
27
+ * the command — while the status keeps its name and gate. Tries made, and
28
+ * reactions that could not be read, are told in the text.
29
+ */
30
+ export function withReactions(r, id, g = {}) {
31
+ const pending = g.reactions ?? [];
32
+ const tries = g.tries ?? [];
33
+ const out = {
34
+ ...r,
35
+ ...(pending.length > 0 ? { reactions: pending } : {}),
36
+ ...(tries.length > 0 ? { tries } : {}),
37
+ ...(g.unread ? { unread: g.unread } : {}),
38
+ };
39
+ const told = [
40
+ ...(tries.length > 0
41
+ ? [
42
+ `Tries built: ${tries.map((n) => `try-${n}`).join(", ")} (compared in the replies; a No-Go naming one takes it in).`,
43
+ ]
44
+ : []),
45
+ ...(g.unread
46
+ ? [
47
+ `Reactions on the change could not be read (${g.unread}), so none given there is processed: give them with \`cupola-decide ${id}\`.`,
48
+ ]
49
+ : []),
50
+ ];
51
+ if (pending.length > 0) {
52
+ const listed = pending.map((p) => `${p.kind} ${p.id} by ${p.who}`).join(", ");
53
+ return {
54
+ ...out,
55
+ turn: "ai",
56
+ next: {
57
+ kind: "run",
58
+ text: [
59
+ `${pending.length} reaction${pending.length === 1 ? "" : "s"} not processed yet (${listed}): a session waiting at this gate processes them; with none waiting, run the command.`,
60
+ ...told,
61
+ ].join(" "),
62
+ command: `cupola-respond ${id}`,
63
+ },
64
+ };
65
+ }
66
+ return told.length > 0
67
+ ? { ...out, next: { ...r.next, text: [r.next.text, ...told].join(" ") } }
68
+ : out;
69
+ }
70
+ /** The `ask` of a status listing these open cards: only cards that name someone, and only when any does. */
71
+ export function askOf(cards, open) {
72
+ const ask = cards
73
+ .filter((c) => open.includes(c.card) && (c.ask?.length ?? 0) > 0)
74
+ .map((c) => ({ card: c.card, ask: c.ask ?? [] }));
75
+ return ask.length > 0 ? { ask } : {};
76
+ }
77
+ /**
78
+ * Why a run stopped on something outside the AI's control, while nothing has
79
+ * happened since: the record is not held, its latest event is `blocked`, and
80
+ * the phase it stopped at has not started again (a start, or any outcome
81
+ * after it, clears it). Undefined when it is not blocked.
82
+ */
83
+ export function blockedBy(record) {
84
+ if (!record || record.active)
85
+ return undefined;
86
+ const last = record.events.at(-1);
87
+ if (last?.what !== "blocked")
88
+ return undefined;
89
+ const at = record.phases.find((p) => p.name === last.phase);
90
+ if (at?.state !== "pending" || at.started)
91
+ return undefined;
92
+ if (record.phases.some((p) => p.finished !== undefined && p.finished > last.at))
93
+ return undefined;
94
+ return { blocker: last.note?.replace(/\.\s*$/, "") || "no reason was given", at: last.at };
95
+ }
96
+ export function deriveStatus({ work, change, reach, record, cards, finished, gate, closedByHand, untidy, waiting, revision, dropped, retake, environment, now, }) {
3
97
  const base = { work, change: change ?? null, cards: [], run: null };
4
98
  const id = work.id;
5
99
  const resume = `cupola-spec-run ${id}`;
@@ -19,6 +113,22 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
19
113
  : { kind: "nothing", text: "Done." },
20
114
  };
21
115
  }
116
+ if (change?.state === "closed" && closedByHand && !dropped) {
117
+ // Closing is no reaction: nothing says whether the spec is to go, or the epic.
118
+ const epic = closedByHand;
119
+ const blocker = `its change was closed by hand, with nothing recorded (${change.url})`;
120
+ return {
121
+ ...base,
122
+ status: "blocked",
123
+ turn: "human",
124
+ gate: null,
125
+ blocked: { blocker },
126
+ next: {
127
+ kind: "gate",
128
+ text: `Its change was closed by hand, and nothing records what is to happen. Stop the epic with \`cupola-abort ${epic}\`, drop this spec with a revision (\`cupola-epic-revise ${epic}\`, then its start gate), or reopen the change if closing it was a mistake.`,
129
+ },
130
+ };
131
+ }
22
132
  if (change?.state === "closed") {
23
133
  return {
24
134
  ...base,
@@ -44,8 +154,9 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
44
154
  ...base,
45
155
  status: "awaiting-decision",
46
156
  turn: "human",
47
- gate: "G2",
157
+ gate: null,
48
158
  cards: unanswered,
159
+ ...askOf(cards, unanswered),
49
160
  next: {
50
161
  kind: "gate",
51
162
  text: `Answer cards ${unanswered.join(", ")}; the run resumes when the answers are recorded.`,
@@ -61,22 +172,14 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
61
172
  run,
62
173
  next,
63
174
  });
64
- // A send-back is written before the change goes back to draft; the run resumes from it.
65
- // The run removes its whole directory, cards included, before G3, so a
66
- // card found without a record is a send-back written after that.
67
- const sendBacks = pendingSendBacks(record, cards);
68
- if (sendBacks.length > 0) {
175
+ // A No-Go processed at acceptance is a card written before the change goes back to draft; the run
176
+ // resumes from it. The run removes its directory, cards included, before acceptance, so a
177
+ // card found without a record is a No-Go written after that.
178
+ const noGos = pendingNoGos(record, cards);
179
+ if (noGos.length > 0) {
69
180
  return aiWorking({ phase: null, active: null }, {
70
181
  kind: "run",
71
- text: `Sent back (card ${sendBacks.map((c) => c.card).join(", ")}); resume the run.`,
72
- command: resume,
73
- });
74
- }
75
- // Feedback a person left on the change sends it back as a card does: the run answers it.
76
- if (feedback && feedback > 0 && !record) {
77
- return aiWorking({ phase: null, active: null }, {
78
- kind: "run",
79
- text: `Sent back on the change (${feedback} remark${feedback === 1 ? "" : "s"} to answer); resume the run.`,
182
+ text: `No-Go (card ${noGos.map((c) => c.card).join(", ")}): the run goes back to ${noGos.map((c) => c.redo).join(", ")}; resume it.`,
80
183
  command: resume,
81
184
  });
82
185
  }
@@ -89,15 +192,21 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
89
192
  command: `cupola-decide ${id}`,
90
193
  });
91
194
  }
92
- // A revision under agreement plans to change it: it waits, even at G3.
195
+ // A revision under agreement plans to change it: it waits, even at acceptance, for a human to agree
196
+ // the revision (its start gate) by merging the epic's change.
93
197
  if (revision && !record?.active) {
198
+ const where = revision.url ? ` (${revision.url})` : "";
94
199
  return {
95
200
  ...base,
96
201
  status: "waiting",
97
- turn: "ai",
202
+ turn: "human",
98
203
  gate: null,
99
204
  run: null,
100
- next: { kind: "nothing", text: `${revision}.` },
205
+ next: {
206
+ kind: "gate",
207
+ text: `${revision.text}. Read the revision of ${revision.epic} and merge its change to agree${where}; the epic's run then takes it in.`,
208
+ command: `cupola-epic-run ${revision.epic}`,
209
+ },
101
210
  };
102
211
  }
103
212
  if (retake) {
@@ -110,17 +219,17 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
110
219
  };
111
220
  }
112
221
  if (change?.state === "open" && !change.draft && !record) {
113
- return {
222
+ return withReactions({
114
223
  ...base,
115
224
  status: "awaiting-acceptance",
116
225
  turn: "human",
117
- gate: "G3",
226
+ gate: "acceptance",
118
227
  next: {
119
228
  kind: "gate",
120
- text: `Read "Needs confirmation" on ${change.url}, merge it, then run the command; or send it back by leaving feedback on the change, or with \`cupola-decide ${id}\`.`,
229
+ text: acceptanceText(id, reach ?? { read: change.url, merge: "merge it", reactions: true }),
121
230
  command: `cupola-complete ${id}`,
122
231
  },
123
- };
232
+ }, id, gate);
124
233
  }
125
234
  const phase = record?.phases.find((p) => p.state === "running")?.name ??
126
235
  record?.phases.find((p) => p.state === "pending" || p.state === "redo")?.name ??
@@ -135,11 +244,17 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
135
244
  : null;
136
245
  const run = { phase, active };
137
246
  if (active) {
247
+ const started = ago(active.since, now);
248
+ // A work its epic runs is taken over through the epic's run, by the session that held it.
249
+ const takeOver = work.epic
250
+ ? `cupola-epic-run ${work.epic} --take-over ${active.session}`
251
+ : `${resume} --take-over ${active.id}`;
138
252
  return aiWorking(run, {
139
253
  kind: "nothing",
140
- text: `Running ${phase ?? "its last steps"} (${active.who}, session ${active.session}, since ${active.since}). ` +
141
- `If that session has ended, resume with --take-over ${active.id}.`,
142
- command: `${resume} --take-over ${active.id}`,
254
+ text: `Running ${phase ?? "its last steps"}: ${active.who} started it in session ${active.session}` +
255
+ `${started ? `, ${started}` : ""} (${active.since}). ` +
256
+ `If that session is gone, take the run over with \`${takeOver}\`.`,
257
+ command: takeOver,
143
258
  });
144
259
  }
145
260
  if (!record && finished) {
@@ -149,6 +264,22 @@ export function deriveStatus({ work, change, record, cards, finished, feedback,
149
264
  command: resume,
150
265
  });
151
266
  }
267
+ const blocked = blockedBy(record);
268
+ if (blocked) {
269
+ return {
270
+ ...base,
271
+ status: "blocked",
272
+ turn: "human",
273
+ gate: null,
274
+ run,
275
+ blocked,
276
+ next: {
277
+ kind: "run",
278
+ text: `Blocked at ${phase ?? "its last steps"}: ${blocked.blocker}. Fix that, then resume the run.`,
279
+ command: resume,
280
+ },
281
+ };
282
+ }
152
283
  if (environment) {
153
284
  return {
154
285
  ...base,
package/dist/templates.js CHANGED
@@ -5,7 +5,8 @@ import { METHOD } from "./method/v1.js";
5
5
  /** Templates a run writes from, served from the package per method. */
6
6
  const RUN_TEMPLATES = [
7
7
  "card",
8
- "send-back",
8
+ "no-go",
9
+ "reaction",
9
10
  "case-draft",
10
11
  "cupola-issue-draft",
11
12
  "phase-outcome",
@@ -1,8 +1,6 @@
1
- import { mkdtemp, rm } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
1
+ import { branchStore } from "../branch-store.js";
4
2
  import { parseFrontMatter } from "../frontmatter.js";
5
- import { git, gitWith } from "../git.js";
3
+ import { git } from "../git.js";
6
4
  import { appendLog, CaseError, closeCase, parseCase, } from "./tracker.js";
7
5
  /** The hub's branch that holds cases, committed and pushed to directly. */
8
6
  export const WORK_BRANCH = "cupola/work";
@@ -15,33 +13,9 @@ const TIP = "refs/cupola/work-tip";
15
13
  * case is visible to everyone.
16
14
  */
17
15
  export function filesTracker(root) {
18
- /** origin's tip of the branch, fetched; undefined while no case was ever filed. */
19
- async function tip() {
20
- try {
21
- await git(root, [
22
- "ls-remote",
23
- "--exit-code",
24
- "--heads",
25
- "origin",
26
- `refs/heads/${WORK_BRANCH}`,
27
- ]);
28
- }
29
- catch (error) {
30
- if (error.code === 2)
31
- return undefined;
32
- throw new Error(`cannot reach origin to read ${WORK_BRANCH}; try again when it is reachable`);
33
- }
34
- await git(root, ["fetch", "--quiet", "origin", `+refs/heads/${WORK_BRANCH}:${TIP}`]);
35
- return git(root, ["rev-parse", TIP]);
36
- }
37
- async function read(commit, id) {
38
- try {
39
- return await git(root, ["show", `${commit}:${DIR}/${id}.md`]);
40
- }
41
- catch {
42
- return undefined;
43
- }
44
- }
16
+ const store = branchStore(root, WORK_BRANCH, TIP);
17
+ const tip = () => store.tip();
18
+ const read = (commit, id) => store.read(commit, `${DIR}/${id}.md`);
45
19
  const summary = (id, text) => {
46
20
  const { data } = parseFrontMatter(text);
47
21
  return {
@@ -57,41 +31,10 @@ export function filesTracker(root) {
57
31
  * already there — after a retry, a push that failed to report may have landed.
58
32
  */
59
33
  async function write(id, change, message) {
60
- for (let attempt = 0;; attempt++) {
61
- const parent = await tip();
62
- const text = change(parent ? await read(parent, id) : undefined, attempt > 0);
63
- if (text === undefined)
64
- return;
65
- const dir = await mkdtemp(join(tmpdir(), "cupola-work-"));
66
- try {
67
- const env = { GIT_INDEX_FILE: join(dir, "index") };
68
- await gitWith(root, parent ? ["read-tree", parent] : ["read-tree", "--empty"], { env });
69
- const blob = await gitWith(root, ["hash-object", "-w", "--stdin"], { input: text });
70
- await gitWith(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${DIR}/${id}.md`], { env });
71
- const tree = await gitWith(root, ["write-tree"], { env });
72
- const commit = await gitWith(root, ["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", message], { env });
73
- try {
74
- await git(root, ["push", "--quiet", "origin", `${commit}:refs/heads/${WORK_BRANCH}`]);
75
- return;
76
- }
77
- catch (error) {
78
- const stderr = error.stderr ?? "";
79
- // Only a race is retried: someone else's case landed first. Anything else is reported.
80
- const raced = /non-fast-forward|fetch first|\(stale info\)/.test(stderr);
81
- if (!raced || attempt >= 2) {
82
- const detail = stderr
83
- .split("\n")
84
- .map((l) => l.trim())
85
- .filter((l) => /^(!|error:|fatal:|remote:)/.test(l) && !/^remote:\s*$/.test(l))
86
- .join("; ") || "unknown reason";
87
- throw new Error(`could not push ${WORK_BRANCH} to origin (${detail})`);
88
- }
89
- }
90
- }
91
- finally {
92
- await rm(dir, { recursive: true, force: true });
93
- }
94
- }
34
+ await store.write(async (parent, retried) => {
35
+ const text = change(parent ? await read(parent, id) : undefined, retried);
36
+ return text === undefined ? undefined : { path: `${DIR}/${id}.md`, text };
37
+ }, message);
95
38
  }
96
39
  return {
97
40
  async list() {
@@ -1,5 +1,7 @@
1
+ import { cloneUrlOf } from "../config.js";
1
2
  import { git } from "../git.js";
2
3
  import { repoOf } from "../host/github.js";
4
+ import { sameUrl } from "../workspace.js";
3
5
  import { filesTracker } from "./files.js";
4
6
  import { githubIssues } from "./github-issues.js";
5
7
  /**
@@ -20,7 +22,12 @@ export async function trackerFor(root, config) {
20
22
  // A local path names no hosted repository to compare with the hub: taken as the hub.
21
23
  const local = /^(\/|file:|[A-Za-z]:[\\/]|\.)/.test(url);
22
24
  const origin = repoOf(url);
23
- if (!local && origin !== config.hub.toLowerCase()) {
25
+ // A hub on another host names its clone URL, or was recorded as the hub by `workspace setup`.
26
+ const named = await git(root, ["config", "--get", "cupola.repo"]).catch(() => "");
27
+ const isHub = origin === config.hub.toLowerCase() ||
28
+ sameUrl(cloneUrlOf(config, config.hub), url) ||
29
+ named.toLowerCase() === config.hub.toLowerCase();
30
+ if (!local && !isHub) {
24
31
  throw new Error(`the files tracker keeps cases in the hub ${config.hub}, but origin here is ${origin ?? "missing"}; run from the hub's checkout`);
25
32
  }
26
33
  return filesTracker(root);
package/dist/tree.js CHANGED
@@ -16,6 +16,14 @@ export function fsTree(root) {
16
16
  .filter((e) => e.isFile())
17
17
  .map((e) => e.name);
18
18
  },
19
+ async dirs(dir) {
20
+ const path = join(root, dir);
21
+ if (!existsSync(path))
22
+ return [];
23
+ return (await readdir(path, { withFileTypes: true }))
24
+ .filter((e) => e.isDirectory())
25
+ .map((e) => e.name);
26
+ },
19
27
  };
20
28
  }
21
29
  /** Files at a commit, read with git without touching the working tree. */
@@ -38,5 +46,14 @@ export function gitTree(cwd, ref) {
38
46
  return [];
39
47
  }
40
48
  },
49
+ async dirs(dir) {
50
+ try {
51
+ const out = await git(cwd, ["ls-tree", "-d", "--name-only", `${ref}:${dir}`]);
52
+ return out === "" ? [] : out.split("\n");
53
+ }
54
+ catch {
55
+ return [];
56
+ }
57
+ },
41
58
  };
42
59
  }
package/dist/work.js CHANGED
@@ -85,7 +85,10 @@ export function runDir(id) {
85
85
  }
86
86
  /** Reads the cards of a work item's progress record. */
87
87
  export async function readCards(tree, id) {
88
- const dir = join(runDir(id), "cards");
88
+ return readCardsIn(tree, join(runDir(id), "cards"));
89
+ }
90
+ /** Reads the cards of a directory: a progress record's, or an epic's. */
91
+ export async function readCardsIn(tree, dir) {
89
92
  const cards = [];
90
93
  for (const file of (await tree.list(dir)).filter((f) => f.endsWith(".md"))) {
91
94
  const where = join(dir, file);
@@ -94,14 +97,20 @@ export async function readCards(tree, id) {
94
97
  throw new WorkError(`${where}: not a card`);
95
98
  }
96
99
  const type = String(data.type ?? "");
97
- if (type === "send-back") {
100
+ if (type === "no-go") {
101
+ // Answered once it says where to go back: written so by a gate that read the No-Go, or by
102
+ // cupola-decide when the No-Go had no content and the card asked its giver.
103
+ const redo = str(data.redo);
104
+ const effect = redo === undefined ? null : redo === "revision" ? "revise-epic" : "continue";
98
105
  cards.push({
99
106
  card: data.card,
100
107
  type,
101
108
  file,
102
- effect: "continue",
103
- answered: true,
104
- redo: str(data.redo),
109
+ effect,
110
+ answered: effect !== null,
111
+ redo,
112
+ take: str(data.take),
113
+ ask: asked(data.ask),
105
114
  });
106
115
  continue;
107
116
  }
@@ -125,10 +134,20 @@ export async function readCards(tree, id) {
125
134
  answered: effect !== null,
126
135
  offers,
127
136
  case: type === "stop-fix" ? str(data.case) : undefined,
137
+ recommended: str(data.recommended),
138
+ ask: asked(data.ask),
128
139
  });
129
140
  }
130
141
  return cards.sort((a, b) => a.card - b.card);
131
142
  }
143
+ /** A card's `ask:`: a list, or one value (commas separate several); free text, kept as written. */
144
+ function asked(value) {
145
+ const all = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value];
146
+ return all
147
+ .flatMap((v) => String(v ?? "").split(","))
148
+ .map((v) => v.trim())
149
+ .filter((v) => v !== "");
150
+ }
132
151
  function str(value) {
133
152
  if (value === null || value === undefined || value === "")
134
153
  return undefined;
@@ -142,8 +161,10 @@ function str(value) {
142
161
  export function runsOn(branch, id) {
143
162
  return branch === workBranchName(id) || branch === `epic/${id}`;
144
163
  }
164
+ /** What every work item's branch starts with. */
165
+ export const WORK_BRANCH_PREFIX = "cupola/";
145
166
  /** The branch a work item runs on; an internal convention of Cupola. */
146
167
  export function workBranchName(id) {
147
168
  assertWorkId(id);
148
- return `cupola/${id}`;
169
+ return `${WORK_BRANCH_PREFIX}${id}`;
149
170
  }
package/dist/workspace.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
- import { CONFIG_PATH, cloneName, loadConfig, resolveComponents, } from "./config.js";
3
+ import { CONFIG_PATH, cloneName, cloneUrlOf, loadConfig, resolveComponents, } from "./config.js";
4
4
  import { git, originDefaultBranch } from "./git.js";
5
- import { github, repoOf } from "./host/github.js";
5
+ import { repoOf } from "./host/github.js";
6
+ import { hostFor } from "./host/index.js";
6
7
  import { repoRoot } from "./repo.js";
7
8
  import { specDocPath } from "./work.js";
8
9
  /** The main checkout of the repository containing `cwd`, whichever worktree it is in. */
@@ -45,6 +46,14 @@ export function reposOf(config) {
45
46
  }
46
47
  return out;
47
48
  }
49
+ /** Whether two clone URLs name the same repository, a trailing `.git` or slash aside. */
50
+ export function sameUrl(a, b) {
51
+ const norm = (u) => u
52
+ .trim()
53
+ .replace(/\/+$/, "")
54
+ .replace(/\.git$/, "");
55
+ return a !== undefined && b !== undefined && a !== "" && b !== "" && norm(a) === norm(b);
56
+ }
48
57
  function same(slugs, slug) {
49
58
  return slugs.some((s) => s.toLowerCase() === slug.toLowerCase());
50
59
  }
@@ -77,10 +86,15 @@ export async function checkoutDirs(hubMain) {
77
86
  return out;
78
87
  }
79
88
  /** Which configured repository a checkout is: git config first, then origin. */
80
- async function identify(main, slugs) {
89
+ async function identify(main, slugs, config) {
81
90
  const named = await gitConfig(main, "cupola.repo");
82
91
  if (named)
83
92
  return canonical(slugs, named);
93
+ const url = await git(main, ["remote", "get-url", "origin"]).catch(() => "");
94
+ // A repository on another host names its clone URL: origin is that URL, not `owner/name`.
95
+ const byUrl = slugs.find((s) => sameUrl(cloneUrlOf(config, s), url));
96
+ if (byUrl)
97
+ return byUrl;
84
98
  const origin = await originSlug(main);
85
99
  if (origin) {
86
100
  const found = canonical(slugs, origin);
@@ -90,6 +104,14 @@ async function identify(main, slugs) {
90
104
  // One repository: whatever origin says (a local path in tests), it is the hub.
91
105
  return slugs.length === 1 ? slugs[0] : undefined;
92
106
  }
107
+ /** A configured repository with no clone under the hub yet: set up, not broken. */
108
+ export class NotClonedError extends Error {
109
+ repo;
110
+ constructor(repo, dir) {
111
+ super(`${repo} is not cloned at ${dir}: run \`cupola workspace setup\` in the hub`);
112
+ this.repo = repo;
113
+ }
114
+ }
93
115
  /** The workspace of the hub, for `cupola workspace setup`: the checkout it runs in is taken as the hub. */
94
116
  export async function workspaceOfHub(io) {
95
117
  const ws = await workspace(io, true);
@@ -104,7 +126,7 @@ export async function workspace(io, assumeHub = false) {
104
126
  const slugs = slugsOf(config);
105
127
  const repos = reposOf(config);
106
128
  const main = await mainCheckout(root);
107
- const slug = (await identify(main, slugs)) ?? (assumeHub ? config.hub : undefined);
129
+ const slug = (await identify(main, slugs, config)) ?? (assumeHub ? config.hub : undefined);
108
130
  if (!slug) {
109
131
  throw new Error(`${main} is none of the configured repositories (${slugs.join(", ")}): run \`cupola workspace setup\` in the hub`);
110
132
  }
@@ -132,9 +154,8 @@ export async function workspace(io, assumeHub = false) {
132
154
  // Code mounted in the hub's tree is found where every worktree mounts it: its clone's name.
133
155
  const named = codeOnly.has(known.toLowerCase()) ? undefined : dirs.get(known.toLowerCase());
134
156
  const dir = named ? join(hub.main, named) : cloneDir(hub.main, known);
135
- if (!existsSync(join(dir, ".git"))) {
136
- throw new Error(`${known} is not cloned at ${dir}: run \`cupola workspace setup\` in the hub`);
137
- }
157
+ if (!existsSync(join(dir, ".git")))
158
+ throw new NotClonedError(known, dir);
138
159
  return { slug: known, main: dir, isHub: false };
139
160
  };
140
161
  const components = resolveComponents(config);
@@ -162,7 +183,10 @@ export async function workspace(io, assumeHub = false) {
162
183
  return canonical(repos, repo) ?? repo;
163
184
  },
164
185
  codeOf: (name) => component(name).code,
165
- host: (io2, s) => (io2.host ?? github)(checkout(s).main),
186
+ host: (io2, s) => {
187
+ const main = checkout(s).main;
188
+ return io2.host ? io2.host(main) : hostFor(config, main, canonical(repos, s) ?? s);
189
+ },
166
190
  };
167
191
  }
168
192
  async function hasBranch(main, branch) {
@@ -183,19 +207,20 @@ async function onOrigin(main, branch) {
183
207
  return false;
184
208
  }
185
209
  }
186
- /** The epics of the hub, by the files of its epics directory on origin's default branch (or here). */
210
+ /** The epics of the hub, by the folders of its epics directory on origin's default branch (or here). */
187
211
  async function hubEpicIds(ws) {
188
212
  const base = await originDefaultBranch(ws.hub.main);
189
213
  const list = await git(ws.hub.main, [
190
214
  "ls-tree",
215
+ "-d",
191
216
  "--name-only",
192
217
  base ? `refs/remotes/origin/${base}` : "HEAD",
193
218
  `${ws.config.paths.epics}/`,
194
219
  ]).catch(() => "");
195
220
  return list
196
221
  .split("\n")
197
- .filter((f) => f.endsWith(".md"))
198
- .map((f) => f.slice(ws.config.paths.epics.length + 1, -3));
222
+ .filter((f) => f !== "")
223
+ .map((f) => f.slice(ws.config.paths.epics.length + 1));
199
224
  }
200
225
  /**
201
226
  * The component a work id names by the method's naming: a spec
@@ -295,5 +320,5 @@ export function epicRepos(ws, components) {
295
320
  * cannot tell.
296
321
  */
297
322
  export async function identifyRepo(root, config) {
298
- return identify(await mainCheckout(root), slugsOf(config));
323
+ return identify(await mainCheckout(root), slugsOf(config), config);
299
324
  }