@kyuki3rain/cupola 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +202 -0
  3. package/README.md +40 -2
  4. package/dist/adr.js +106 -0
  5. package/dist/catalog.js +137 -0
  6. package/dist/check.js +192 -0
  7. package/dist/cli.js +8 -0
  8. package/dist/code.js +216 -0
  9. package/dist/commands/change.js +522 -0
  10. package/dist/commands/epic.js +311 -0
  11. package/dist/commands/install.js +109 -0
  12. package/dist/commands/locks.js +175 -0
  13. package/dist/commands/procedure.js +92 -0
  14. package/dist/commands/revision.js +139 -0
  15. package/dist/commands/run.js +1015 -0
  16. package/dist/commands/setup.js +382 -0
  17. package/dist/commands/spec.js +80 -0
  18. package/dist/commands/status.js +1158 -0
  19. package/dist/commands/trace.js +397 -0
  20. package/dist/commands/wait.js +102 -0
  21. package/dist/commands/work.js +121 -0
  22. package/dist/commands/workspace.js +126 -0
  23. package/dist/commands/worktree.js +422 -0
  24. package/dist/config.js +289 -0
  25. package/dist/day.js +29 -0
  26. package/dist/e2e-project.js +62 -0
  27. package/dist/e2e.js +207 -0
  28. package/dist/engine/cc-sdd.js +164 -0
  29. package/dist/epic.js +360 -0
  30. package/dist/feedback.js +34 -0
  31. package/dist/frontmatter.js +20 -0
  32. package/dist/git.js +365 -0
  33. package/dist/host/github.js +290 -0
  34. package/dist/host/host.js +1 -0
  35. package/dist/install.js +182 -0
  36. package/dist/io.js +46 -0
  37. package/dist/main.js +771 -0
  38. package/dist/method/v1.js +56 -0
  39. package/dist/procedure.js +60 -0
  40. package/dist/record.js +473 -0
  41. package/dist/release.js +84 -0
  42. package/dist/repo.js +13 -0
  43. package/dist/runbook.js +111 -0
  44. package/dist/safe-write.js +80 -0
  45. package/dist/spec.js +171 -0
  46. package/dist/status.js +190 -0
  47. package/dist/templates.js +49 -0
  48. package/dist/trace.js +275 -0
  49. package/dist/tracker/files.js +156 -0
  50. package/dist/tracker/github-issues.js +217 -0
  51. package/dist/tracker/index.js +27 -0
  52. package/dist/tracker/tracker.js +69 -0
  53. package/dist/tree.js +42 -0
  54. package/dist/trust.js +13 -0
  55. package/dist/version.js +5 -0
  56. package/dist/work.js +149 -0
  57. package/dist/workspace.js +299 -0
  58. package/npm-shrinkwrap.json +2014 -0
  59. package/package.json +41 -4
  60. package/skills/cupola-abort/SKILL.md +45 -0
  61. package/skills/cupola-adr/SKILL.md +41 -0
  62. package/skills/cupola-ask/SKILL.md +42 -0
  63. package/skills/cupola-catalog/SKILL.md +41 -0
  64. package/skills/cupola-catalog-draft/SKILL.md +114 -0
  65. package/skills/cupola-complete/SKILL.md +87 -0
  66. package/skills/cupola-decide/SKILL.md +60 -0
  67. package/skills/cupola-doc/SKILL.md +52 -0
  68. package/skills/cupola-e2e-setup/SKILL.md +78 -0
  69. package/skills/cupola-e2e-test/SKILL.md +115 -0
  70. package/skills/cupola-epic-accept/SKILL.md +162 -0
  71. package/skills/cupola-epic-create/SKILL.md +120 -0
  72. package/skills/cupola-epic-revise/SKILL.md +71 -0
  73. package/skills/cupola-epic-run/SKILL.md +127 -0
  74. package/skills/cupola-fix/SKILL.md +115 -0
  75. package/skills/cupola-init/SKILL.md +88 -0
  76. package/skills/cupola-intake/SKILL.md +78 -0
  77. package/skills/cupola-operate/SKILL.md +64 -0
  78. package/skills/cupola-resolve/SKILL.md +86 -0
  79. package/skills/cupola-review/SKILL.md +132 -0
  80. package/skills/cupola-spec-design/SKILL.md +164 -0
  81. package/skills/cupola-spec-impl/SKILL.md +135 -0
  82. package/skills/cupola-spec-run/SKILL.md +125 -0
  83. package/skills/cupola-steering/SKILL.md +46 -0
  84. package/templates/install/.kiro/steering/e2e.md +48 -0
  85. package/templates/install/.kiro/steering/operations.md +109 -0
  86. package/templates/install/.kiro/steering/principles.md +25 -0
  87. package/templates/install/CLAUDE.md +19 -0
  88. package/templates/install/adr/TEMPLATE.md +38 -0
  89. package/templates/install/cc-sdd/patches.json +31 -0
  90. package/templates/method-1/behavior-area.md +43 -0
  91. package/templates/method-1/behavior-index.md +16 -0
  92. package/templates/method-1/card.md +41 -0
  93. package/templates/method-1/case-draft.md +25 -0
  94. package/templates/method-1/case.md +38 -0
  95. package/templates/method-1/catalog-spec.md +33 -0
  96. package/templates/method-1/changes/adr.md +4 -0
  97. package/templates/method-1/changes/catalog.md +29 -0
  98. package/templates/method-1/changes/doc.md +5 -0
  99. package/templates/method-1/changes/e2e.md +7 -0
  100. package/templates/method-1/changes/epic.md +29 -0
  101. package/templates/method-1/changes/fix.md +21 -0
  102. package/templates/method-1/changes/release.md +23 -0
  103. package/templates/method-1/changes/spec.md +55 -0
  104. package/templates/method-1/changes/system.md +13 -0
  105. package/templates/method-1/cupola-issue-draft.md +17 -0
  106. package/templates/method-1/epic.md +136 -0
  107. package/templates/method-1/fix-spec.md +34 -0
  108. package/templates/method-1/fix.md +39 -0
  109. package/templates/method-1/lock.json +13 -0
  110. package/templates/method-1/phase-outcome.json +29 -0
  111. package/templates/method-1/record.json +63 -0
  112. package/templates/method-1/report.md +27 -0
  113. package/templates/method-1/runbook.md +39 -0
  114. package/templates/method-1/runner-result.json +6 -0
  115. package/templates/method-1/send-back.md +23 -0
  116. package/templates/methods.json +13 -0
@@ -0,0 +1,69 @@
1
+ import { stringify } from "yaml";
2
+ import { parseFrontMatter } from "../frontmatter.js";
3
+ export class CaseError extends Error {
4
+ }
5
+ /** Kebab-case with at least one letter, so that an id is never taken for an issue number. */
6
+ const CASE_ID = /^(?=[a-z0-9-]*[a-z])[a-z0-9]+(?:-[a-z0-9]+)*$/;
7
+ /** A finished case document: checked before it reaches the tracker. */
8
+ export function parseCase(text) {
9
+ const { data, body } = parseFrontMatter(text);
10
+ const problems = [];
11
+ if (data.kind !== "case")
12
+ problems.push("front matter kind must be case");
13
+ if (typeof data.method !== "number")
14
+ problems.push("front matter method must be a number");
15
+ const id = typeof data.id === "string" ? data.id : "";
16
+ if (!CASE_ID.test(id))
17
+ problems.push(`id ${id || "(missing)"} is not a kebab-case name`);
18
+ const title = typeof data.title === "string" ? data.title.trim() : "";
19
+ if (title === "")
20
+ problems.push("title is missing");
21
+ if (data.draft !== undefined)
22
+ problems.push("`draft` is left in the front matter");
23
+ if (text.includes("{{"))
24
+ problems.push("template placeholders are left ({{…}})");
25
+ for (const section of ["## Problem", "## Solved when"]) {
26
+ if (!body.split(/\r?\n/).some((l) => l.trim() === section))
27
+ problems.push(`no "${section}" section`);
28
+ }
29
+ if (problems.length > 0)
30
+ throw new CaseError(`not a case to file: ${problems.join("; ")}`);
31
+ return { id, title, data, body };
32
+ }
33
+ /**
34
+ * A case draft from a run, made into the case to file: `draft` and
35
+ * `duplicates-checked` are dropped, `filed` is set (case-draft).
36
+ */
37
+ export function fromDraft(text, today) {
38
+ const { data, body } = parseFrontMatter(text);
39
+ const { draft: _draft, "duplicates-checked": _checked, ...rest } = data;
40
+ const ordered = {};
41
+ for (const key of ["kind", "method", "id", "title"])
42
+ if (key in rest)
43
+ ordered[key] = rest[key];
44
+ ordered.filed = today;
45
+ for (const [key, value] of Object.entries(rest))
46
+ if (!(key in ordered))
47
+ ordered[key] = value;
48
+ return `---\n${stringify(ordered).trimEnd()}\n---\n${body.startsWith("\n") ? "" : "\n"}${body}`;
49
+ }
50
+ /** The case document with `closed` set to the day, the rest left as it is. */
51
+ export function closeCase(text, day) {
52
+ const end = text.indexOf("\n---", 4);
53
+ if (!text.startsWith("---\n") || end < 0)
54
+ throw new CaseError("the case has no front matter");
55
+ const front = text.slice(0, end);
56
+ const rest = text.slice(end);
57
+ const closed = `closed: ${day}`;
58
+ return /^closed:.*$/m.test(front)
59
+ ? front.replace(/^closed:.*$/m, closed) + rest
60
+ : `${front}\n${closed}${rest}`;
61
+ }
62
+ /** The body with one line appended to its Log section, which is the last one. */
63
+ export function appendLog(body, line) {
64
+ const lines = body.replace(/\s+$/, "").split("\n");
65
+ if (!lines.some((l) => l.trim() === "## Log"))
66
+ lines.push("", "## Log");
67
+ lines.push(`- ${line}`);
68
+ return `${lines.join("\n")}\n`;
69
+ }
package/dist/tree.js ADDED
@@ -0,0 +1,42 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { git } from "./git.js";
5
+ export function fsTree(root) {
6
+ return {
7
+ async read(path) {
8
+ const file = join(root, path);
9
+ return existsSync(file) ? readFile(file, "utf8") : undefined;
10
+ },
11
+ async list(dir) {
12
+ const path = join(root, dir);
13
+ if (!existsSync(path))
14
+ return [];
15
+ return (await readdir(path, { withFileTypes: true }))
16
+ .filter((e) => e.isFile())
17
+ .map((e) => e.name);
18
+ },
19
+ };
20
+ }
21
+ /** Files at a commit, read with git without touching the working tree. */
22
+ export function gitTree(cwd, ref) {
23
+ return {
24
+ async read(path) {
25
+ try {
26
+ return await git(cwd, ["show", `${ref}:${path}`]);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ },
32
+ async list(dir) {
33
+ try {
34
+ const out = await git(cwd, ["ls-tree", "--name-only", `${ref}:${dir}`]);
35
+ return out === "" ? [] : out.split("\n");
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ },
41
+ };
42
+ }
package/dist/trust.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Whose words may steer the work (configuration `trust`): someone whose
3
+ * association with the repository is listed (by default, who can write to
4
+ * it), or a listed login. What anyone else writes is kept as information,
5
+ * never acted on.
6
+ */
7
+ export const ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"];
8
+ export const DEFAULT_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"];
9
+ export const DEFAULT_TRUST = { associations: DEFAULT_ASSOCIATIONS, logins: [] };
10
+ export function trustedBy(trust, who) {
11
+ return (trust.associations.includes(who.association) ||
12
+ trust.logins.some((l) => l.toLowerCase() === who.author.toLowerCase()));
13
+ }
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function version() {
3
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
4
+ return pkg.version;
5
+ }
package/dist/work.js ADDED
@@ -0,0 +1,149 @@
1
+ import { join } from "node:path";
2
+ import { resolveComponents } from "./config.js";
3
+ import { parseFrontMatter } from "./frontmatter.js";
4
+ import { readBlock } from "./spec.js";
5
+ const DOC_KINDS = new Set(["fix", "fix-spec", "catalog"]);
6
+ export class WorkError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "WorkError";
10
+ }
11
+ }
12
+ /** No document for the work item exists in the tree that was searched. */
13
+ export class MissingWorkError extends WorkError {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "MissingWorkError";
17
+ }
18
+ }
19
+ const WORK_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
20
+ export function isWorkId(id) {
21
+ return typeof id === "string" && WORK_ID.test(id);
22
+ }
23
+ /** Work ids are kebab-case names; anything else could leave `.cupola/`. */
24
+ export function assertWorkId(id) {
25
+ if (!isWorkId(id))
26
+ throw new WorkError(`${JSON.stringify(id)} is not a work id (kebab-case)`);
27
+ }
28
+ /**
29
+ * Finds the document of a work item in this repository: a full spec's
30
+ * `spec.json` with Cupola's block, or the document of a fix, fix spec, or
31
+ * catalog spec in `.cupola/specs/`.
32
+ */
33
+ export async function findSpecDocument(tree, config, id,
34
+ /** The repository the tree is of, when known: the document's component must be one of its. */
35
+ repo) {
36
+ assertWorkId(id);
37
+ const components = resolveComponents(config);
38
+ const specJson = `.kiro/specs/${id}/spec.json`;
39
+ const raw = await tree.read(specJson);
40
+ const block = raw === undefined ? undefined : readBlock(specJson, raw);
41
+ if (block) {
42
+ if (!components.some((c) => c.name === block.component)) {
43
+ throw new WorkError(`${specJson}: component ${block.component} is not configured`);
44
+ }
45
+ // A follow-up spec of the same component is `-2`, `-3`, ….
46
+ if (id !== `${block.epic}-${block.component}` &&
47
+ !id.startsWith(`${block.epic}-${block.component}-`)) {
48
+ throw new WorkError(`${specJson}: a spec of ${block.epic} in ${block.component} is named ${block.epic}-${block.component}, not ${id}`);
49
+ }
50
+ return { kind: "spec", id, component: block.component, epic: block.epic, path: specJson };
51
+ }
52
+ const path = specDocPath(id);
53
+ const text = await tree.read(path);
54
+ if (text !== undefined) {
55
+ const { data } = parseFrontMatter(text);
56
+ if (typeof data.kind !== "string" || !DOC_KINDS.has(data.kind)) {
57
+ throw new WorkError(`${path}: kind must be fix, fix-spec, or catalog`);
58
+ }
59
+ if (data.id !== id)
60
+ throw new WorkError(`${path}: id is ${String(data.id)}, expected ${id}`);
61
+ const named = components.find((c) => c.name === data.component);
62
+ if (!named)
63
+ throw new WorkError(`${path}: component ${String(data.component)} is not configured`);
64
+ if (repo && named.repo.toLowerCase() !== repo.toLowerCase())
65
+ throw new WorkError(`${path}: component ${named.name} is in ${named.repo}, not ${repo}`);
66
+ if (data.epic !== undefined && data.epic !== null && !isWorkId(data.epic))
67
+ throw new WorkError(`${path}: epic ${JSON.stringify(data.epic)} is not a work id (kebab-case)`);
68
+ return {
69
+ kind: data.kind,
70
+ id,
71
+ component: named.name,
72
+ epic: typeof data.epic === "string" ? data.epic : null,
73
+ path,
74
+ };
75
+ }
76
+ throw new MissingWorkError(`no work item ${id}: no ${path}, and no ${specJson} with a cupola block`);
77
+ }
78
+ /** The document of a fix, fix spec, or catalog spec, at the repository's root. */
79
+ export function specDocPath(id) {
80
+ return `.cupola/specs/${id}.md`;
81
+ }
82
+ export function runDir(id) {
83
+ assertWorkId(id);
84
+ return join(".cupola", "runs", id);
85
+ }
86
+ /** Reads the cards of a work item's progress record. */
87
+ export async function readCards(tree, id) {
88
+ const dir = join(runDir(id), "cards");
89
+ const cards = [];
90
+ for (const file of (await tree.list(dir)).filter((f) => f.endsWith(".md"))) {
91
+ const where = join(dir, file);
92
+ const { data } = parseFrontMatter((await tree.read(where)) ?? "");
93
+ if (data.kind !== "card" || typeof data.card !== "number") {
94
+ throw new WorkError(`${where}: not a card`);
95
+ }
96
+ const type = String(data.type ?? "");
97
+ if (type === "send-back") {
98
+ cards.push({
99
+ card: data.card,
100
+ type,
101
+ file,
102
+ effect: "continue",
103
+ answered: true,
104
+ redo: str(data.redo),
105
+ });
106
+ continue;
107
+ }
108
+ const answer = str(data.answer);
109
+ let effect = null;
110
+ if (answer === "other")
111
+ effect = "continue";
112
+ else if (answer !== undefined) {
113
+ const options = (data.options ?? {});
114
+ const chosen = options[answer];
115
+ if (typeof chosen !== "string")
116
+ throw new WorkError(`${where}: answer ${answer} is not one of the options`);
117
+ effect = chosen;
118
+ }
119
+ const offers = Object.values((data.options ?? {})).map(String);
120
+ cards.push({
121
+ card: data.card,
122
+ type,
123
+ file,
124
+ effect,
125
+ answered: effect !== null,
126
+ offers,
127
+ case: type === "stop-fix" ? str(data.case) : undefined,
128
+ });
129
+ }
130
+ return cards.sort((a, b) => a.card - b.card);
131
+ }
132
+ function str(value) {
133
+ if (value === null || value === undefined || value === "")
134
+ return undefined;
135
+ return String(value);
136
+ }
137
+ /**
138
+ * Whether a checkout's branch is one a work item runs on: its own branch, or,
139
+ * for an epic with two or more specs, its epic branch (where its own record
140
+ * lives).
141
+ */
142
+ export function runsOn(branch, id) {
143
+ return branch === workBranchName(id) || branch === `epic/${id}`;
144
+ }
145
+ /** The branch a work item runs on; an internal convention of Cupola. */
146
+ export function workBranchName(id) {
147
+ assertWorkId(id);
148
+ return `cupola/${id}`;
149
+ }
@@ -0,0 +1,299 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { CONFIG_PATH, cloneName, loadConfig, resolveComponents, } from "./config.js";
4
+ import { git, originDefaultBranch } from "./git.js";
5
+ import { github, repoOf } from "./host/github.js";
6
+ import { repoRoot } from "./repo.js";
7
+ import { specDocPath } from "./work.js";
8
+ /** The main checkout of the repository containing `cwd`, whichever worktree it is in. */
9
+ export async function mainCheckout(cwd) {
10
+ const common = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
11
+ return basename(common) === ".git" ? dirname(common) : repoRoot(cwd);
12
+ }
13
+ async function gitConfig(cwd, key) {
14
+ try {
15
+ const value = await git(cwd, ["config", "--get", key]);
16
+ return value === "" ? undefined : value;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ async function originSlug(cwd) {
23
+ try {
24
+ return repoOf(await git(cwd, ["remote", "get-url", "origin"]));
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** The repositories that keep documents: the hub first, then in the components' order. */
31
+ export function slugsOf(config) {
32
+ const out = [config.hub];
33
+ for (const c of resolveComponents(config))
34
+ if (!same(out, c.repo))
35
+ out.push(c.repo);
36
+ return out;
37
+ }
38
+ /** Every repository of a configuration, code included: the hub first, then in the components' order. */
39
+ export function reposOf(config) {
40
+ const out = [config.hub];
41
+ for (const c of resolveComponents(config)) {
42
+ const repo = c.code?.repo ?? c.repo;
43
+ if (!same(out, repo))
44
+ out.push(repo);
45
+ }
46
+ return out;
47
+ }
48
+ function same(slugs, slug) {
49
+ return slugs.some((s) => s.toLowerCase() === slug.toLowerCase());
50
+ }
51
+ function canonical(slugs, slug) {
52
+ return slugs.find((s) => s.toLowerCase() === slug.toLowerCase());
53
+ }
54
+ /** The directory a repository is cloned into under the hub: its last path segment. */
55
+ export function cloneDir(hubMain, slug) {
56
+ return join(hubMain, cloneName(slug));
57
+ }
58
+ /**
59
+ * Clones `cupola workspace setup` found under another name than their last
60
+ * path segment (an existing workspace), from the hub's git config
61
+ * `cupola.<owner/name>.checkout`: lowercased slug → directory under the hub.
62
+ */
63
+ export async function checkoutDirs(hubMain) {
64
+ const out = new Map();
65
+ let list = "";
66
+ try {
67
+ list = await git(hubMain, ["config", "--get-regexp", "^cupola\\..*\\.checkout$"]);
68
+ }
69
+ catch {
70
+ return out; // none recorded
71
+ }
72
+ for (const line of list.split("\n")) {
73
+ const m = /^cupola\.(.+)\.checkout\s+(.+)$/.exec(line.trim());
74
+ if (m?.[1] && m[2])
75
+ out.set(m[1].toLowerCase(), m[2]);
76
+ }
77
+ return out;
78
+ }
79
+ /** Which configured repository a checkout is: git config first, then origin. */
80
+ async function identify(main, slugs) {
81
+ const named = await gitConfig(main, "cupola.repo");
82
+ if (named)
83
+ return canonical(slugs, named);
84
+ const origin = await originSlug(main);
85
+ if (origin) {
86
+ const found = canonical(slugs, origin);
87
+ if (found)
88
+ return found;
89
+ }
90
+ // One repository: whatever origin says (a local path in tests), it is the hub.
91
+ return slugs.length === 1 ? slugs[0] : undefined;
92
+ }
93
+ /** The workspace of the hub, for `cupola workspace setup`: the checkout it runs in is taken as the hub. */
94
+ export async function workspaceOfHub(io) {
95
+ const ws = await workspace(io, true);
96
+ if (!ws.here.isHub) {
97
+ throw new Error(`${ws.here.main} is ${ws.here.slug}, not the hub ${ws.hub.slug}: run this in the hub`);
98
+ }
99
+ return ws;
100
+ }
101
+ export async function workspace(io, assumeHub = false) {
102
+ const root = await repoRoot(io.cwd);
103
+ const config = await loadConfig(root);
104
+ const slugs = slugsOf(config);
105
+ const repos = reposOf(config);
106
+ const main = await mainCheckout(root);
107
+ const slug = (await identify(main, slugs)) ?? (assumeHub ? config.hub : undefined);
108
+ if (!slug) {
109
+ throw new Error(`${main} is none of the configured repositories (${slugs.join(", ")}): run \`cupola workspace setup\` in the hub`);
110
+ }
111
+ const here = { slug, main, isHub: slug === config.hub };
112
+ let hubMain = here.isHub ? main : await gitConfig(main, "cupola.hub");
113
+ if (!hubMain) {
114
+ const parent = dirname(main);
115
+ if (existsSync(join(parent, CONFIG_PATH)) && cloneDir(parent, slug) === main)
116
+ hubMain = parent;
117
+ }
118
+ if (!hubMain) {
119
+ throw new Error(`cannot find the hub ${config.hub} from ${main}: clone the repositories with \`cupola workspace setup\` in the hub`);
120
+ }
121
+ const hub = { slug: config.hub, main: hubMain, isHub: true };
122
+ const dirs = await checkoutDirs(hub.main);
123
+ const codeOnly = new Set(repos.filter((r) => !same(slugs, r)).map((r) => r.toLowerCase()));
124
+ const checkout = (s) => {
125
+ const known = canonical(repos, s);
126
+ if (!known)
127
+ throw new Error(`${s} is not a configured repository`);
128
+ if (known === hub.slug)
129
+ return hub;
130
+ if (known === here.slug)
131
+ return here;
132
+ // Code mounted in the hub's tree is found where every worktree mounts it: its clone's name.
133
+ const named = codeOnly.has(known.toLowerCase()) ? undefined : dirs.get(known.toLowerCase());
134
+ 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
+ }
138
+ return { slug: known, main: dir, isHub: false };
139
+ };
140
+ const components = resolveComponents(config);
141
+ const component = (name) => {
142
+ const c = components.find((x) => x.name === name);
143
+ if (!c)
144
+ throw new Error(`no component ${name} in the configuration`);
145
+ return c;
146
+ };
147
+ return {
148
+ config,
149
+ root,
150
+ here,
151
+ hub,
152
+ slugs,
153
+ repos,
154
+ checkout,
155
+ repoOf: (name) => {
156
+ const c = component(name);
157
+ return canonical(slugs, c.repo) ?? c.repo;
158
+ },
159
+ codeRepoOf: (name) => {
160
+ const c = component(name);
161
+ const repo = c.code?.repo ?? c.repo;
162
+ return canonical(repos, repo) ?? repo;
163
+ },
164
+ codeOf: (name) => component(name).code,
165
+ host: (io2, s) => (io2.host ?? github)(checkout(s).main),
166
+ };
167
+ }
168
+ async function hasBranch(main, branch) {
169
+ try {
170
+ await git(main, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
171
+ return true;
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ }
177
+ async function onOrigin(main, branch) {
178
+ try {
179
+ await git(main, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`]);
180
+ return true;
181
+ }
182
+ catch {
183
+ return false;
184
+ }
185
+ }
186
+ /** The epics of the hub, by the files of its epics directory on origin's default branch (or here). */
187
+ async function hubEpicIds(ws) {
188
+ const base = await originDefaultBranch(ws.hub.main);
189
+ const list = await git(ws.hub.main, [
190
+ "ls-tree",
191
+ "--name-only",
192
+ base ? `refs/remotes/origin/${base}` : "HEAD",
193
+ `${ws.config.paths.epics}/`,
194
+ ]).catch(() => "");
195
+ return list
196
+ .split("\n")
197
+ .filter((f) => f.endsWith(".md"))
198
+ .map((f) => f.slice(ws.config.paths.epics.length + 1, -3));
199
+ }
200
+ /**
201
+ * The component a work id names by the method's naming: a spec
202
+ * of an epic `<epic>-<component>`, a follow-up `-<n>`, a fix spec `-fix-<n>`,
203
+ * and the e2e setup `e2e-<component>`.
204
+ */
205
+ async function componentByName(ws, id) {
206
+ const names = resolveComponents(ws.config).map((c) => c.name);
207
+ const e2e = /^e2e-(.+)$/.exec(id)?.[1];
208
+ if (e2e && names.includes(e2e))
209
+ return e2e;
210
+ for (const epic of await hubEpicIds(ws)) {
211
+ if (!id.startsWith(`${epic}-`))
212
+ continue;
213
+ const rest = id.slice(epic.length + 1);
214
+ const c = names.find((n) => rest === n || new RegExp(`^${n}-(\\d+|fix-\\d+)$`).test(rest));
215
+ if (c)
216
+ return c;
217
+ }
218
+ return undefined;
219
+ }
220
+ /**
221
+ * The repository a work item lives in: a component it is given; the
222
+ * repository where its branch already is, locally or on origin; the component
223
+ * its id names; otherwise the hub (cases' epics, ADRs, steering).
224
+ */
225
+ export async function locateWork(ws, id, opts) {
226
+ if (ws.slugs.length === 1)
227
+ return ws.hub;
228
+ if (opts.component)
229
+ return ws.checkout(ws.repoOf(opts.component));
230
+ const cloned = ws.slugs.flatMap((s) => {
231
+ try {
232
+ return [ws.checkout(s)];
233
+ }
234
+ catch {
235
+ return [];
236
+ }
237
+ });
238
+ for (const c of cloned)
239
+ if (await hasBranch(c.main, opts.branch))
240
+ return c;
241
+ const named = await componentByName(ws, id);
242
+ if (named)
243
+ return ws.checkout(ws.repoOf(named));
244
+ for (const c of cloned)
245
+ if (await onOrigin(c.main, opts.branch))
246
+ return c;
247
+ // Merged and its branch gone: its document is on the default branch of its repository.
248
+ for (const c of cloned)
249
+ if (await hasDocument(c, id))
250
+ return c;
251
+ return ws.hub;
252
+ }
253
+ /** Whether a repository's default branch (or its checkout) has the work's document. */
254
+ async function hasDocument(repo, id) {
255
+ const base = await originDefaultBranch(repo.main);
256
+ if (base) {
257
+ // Clones are never pulled: what was merged since is on origin, not in the tracking ref.
258
+ await git(repo.main, [
259
+ "fetch",
260
+ "--quiet",
261
+ "origin",
262
+ `+refs/heads/${base}:refs/remotes/origin/${base}`,
263
+ ]).catch(() => "");
264
+ }
265
+ const refs = [...(base ? [`refs/remotes/origin/${base}`] : []), "HEAD"];
266
+ const paths = [`.kiro/specs/${id}/spec.json`, specDocPath(id)];
267
+ for (const ref of refs) {
268
+ for (const path of paths) {
269
+ try {
270
+ await git(repo.main, ["cat-file", "-e", `${ref}:${path}`]);
271
+ return true;
272
+ }
273
+ catch {
274
+ // not there
275
+ }
276
+ }
277
+ }
278
+ return false;
279
+ }
280
+ /**
281
+ * The repositories an epic touches: the hub, which holds the
282
+ * epic's own record and acceptance-check scripts, then each repository of its
283
+ * specs' components' code, in the configuration's order. Each is checked out:
284
+ * its main checkout, or the checkout the command runs in when it is that one.
285
+ */
286
+ export function epicRepos(ws, components) {
287
+ const wanted = new Set(components.map((c) => ws.codeRepoOf(c)));
288
+ return ws.repos
289
+ .filter((s) => s === ws.hub.slug || wanted.has(s))
290
+ .map((s) => (s === ws.here.slug ? { ...ws.here, main: ws.root } : ws.checkout(s)));
291
+ }
292
+ /**
293
+ * Which configured repository a checkout is, without needing the hub: for a
294
+ * checkout outside any workspace (a temporary clone, CI). Undefined when it
295
+ * cannot tell.
296
+ */
297
+ export async function identifyRepo(root, config) {
298
+ return identify(await mainCheckout(root), slugsOf(config));
299
+ }