@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,126 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { loadConfig } from "../config.js";
4
+ import { today } from "../day.js";
5
+ import { parseFrontMatter } from "../frontmatter.js";
6
+ import { repoRoot } from "../repo.js";
7
+ import { trackerFor } from "../tracker/index.js";
8
+ import { fromDraft } from "../tracker/tracker.js";
9
+ import { workspace } from "../workspace.js";
10
+ import { caseStatus, judgedEpics, notSolvedMarker } from "./status.js";
11
+ export async function trackerOf(io) {
12
+ // Cases live in the hub: from another repository, through the hub's checkout.
13
+ const ws = await workspace(io);
14
+ const root = ws.here.isHub ? ws.root : ws.hub.main;
15
+ return io.tracker ? io.tracker(root) : await trackerFor(root, ws.config);
16
+ }
17
+ /** `cupola work list`: every case, open and closed, so that duplicates can be looked for. */
18
+ export async function workList(io, opts) {
19
+ const cases = await (await trackerOf(io)).list();
20
+ if (opts.json)
21
+ io.out(JSON.stringify({ cases }));
22
+ else
23
+ for (const c of cases)
24
+ io.out(`${c.open ? "open " : "closed"} ${c.id} — ${c.title}`);
25
+ return 0;
26
+ }
27
+ /** `cupola work show <case>`: the case document, as Markdown with front matter. */
28
+ export async function workShow(io, id, opts) {
29
+ const found = await (await trackerOf(io)).show(id);
30
+ if (!found)
31
+ throw new Error(`no case ${id}`);
32
+ io.out(opts.json ? JSON.stringify(found) : found.text.trimEnd());
33
+ return 0;
34
+ }
35
+ /**
36
+ * `cupola work file --body-file <case.md>`: files a case. A case draft from a
37
+ * run is accepted as it is: its draft keys are dropped and `filed` is set.
38
+ */
39
+ export async function workFile(io, opts) {
40
+ if (!opts.bodyFile)
41
+ throw new Error("give the case: --body-file <file>");
42
+ const text = await readFile(resolve(io.cwd, opts.bodyFile), "utf8");
43
+ const doc = parseFrontMatter(text).data.draft === true ? fromDraft(text, await today(io)) : text;
44
+ const filed = await (await trackerOf(io)).file(doc);
45
+ io.out(opts.json ? JSON.stringify(filed) : `filed ${filed.id}: ${filed.url}`);
46
+ return 0;
47
+ }
48
+ async function oneLine(io, opts) {
49
+ if (!opts.bodyFile)
50
+ throw new Error("give the line: --body-file <file>");
51
+ const line = (await readFile(resolve(io.cwd, opts.bodyFile), "utf8")).trim();
52
+ if (line === "" || line.includes("\n"))
53
+ throw new Error("a Log entry is one line");
54
+ if (line.includes("{{"))
55
+ throw new Error("the Log entry still has template placeholders ({{…}})");
56
+ return line;
57
+ }
58
+ /** `cupola work log <case> --body-file <f>`: appends one dated line to the case's Log. */
59
+ export async function workLog(io, id, opts) {
60
+ const line = await oneLine(io, opts);
61
+ await (await trackerOf(io)).log(id, `${await today(io)} ${line}`);
62
+ io.out(opts.json ? JSON.stringify({ logged: id }) : `logged on ${id}`);
63
+ return 0;
64
+ }
65
+ /**
66
+ * `cupola work close <case> --body-file <f>`: resolution found the problem gone. The
67
+ * human's words go to the Log, and the case is closed.
68
+ */
69
+ export async function workClose(io, id, opts) {
70
+ const line = await oneLine(io, opts);
71
+ const root = await repoRoot(io.cwd);
72
+ const found = await caseStatus(io, root, await loadConfig(root), id);
73
+ if (!found)
74
+ throw new Error(`no case ${id}`);
75
+ const caseId = found.work.id;
76
+ const ready = opts.withoutEpic ? "open" : "awaiting-resolution";
77
+ if (found.status !== "resolved" && found.status !== ready) {
78
+ throw new Error(opts.withoutEpic
79
+ ? `${caseId} is ${found.status}: only a case no epic works on is closed without one`
80
+ : `${caseId} is ${found.status}: a case is closed at resolution, once its epics are done (one that needs no work: --without-epic)`);
81
+ }
82
+ const day = await today(io);
83
+ const closed = found.status === "resolved"
84
+ ? false
85
+ : await (await trackerOf(io)).close(caseId, `${day} resolved${opts.withoutEpic ? " without an epic" : ""}: ${line}`, day);
86
+ io.out(opts.json
87
+ ? JSON.stringify({ closed: caseId, already: !closed })
88
+ : closed
89
+ ? `closed ${caseId}`
90
+ : `${caseId} was closed already`);
91
+ return 0;
92
+ }
93
+ /**
94
+ * `cupola work reopen <case> --body-file <f>`: resolution found the problem not gone.
95
+ * The reason goes to the Log with the epics judged, which then no longer
96
+ * count, so the case is open again.
97
+ */
98
+ export async function workReopen(io, id, opts) {
99
+ const line = await oneLine(io, opts);
100
+ const root = await repoRoot(io.cwd);
101
+ const found = await caseStatus(io, root, await loadConfig(root), id);
102
+ if (!found)
103
+ throw new Error(`no case ${id}`);
104
+ const caseId = found.work.id;
105
+ // Its epics and executions alike: the marker names each work judged.
106
+ const judgedBefore = judgedEpics((await (await trackerOf(io)).show(caseId))?.text ?? "");
107
+ const epics = [
108
+ ...(found.epics ?? []),
109
+ ...(found.executions ?? []).flatMap((e) => e.id ? [{ id: e.id, status: e.status, judged: judgedBefore.has(e.id) }] : []),
110
+ ];
111
+ // Run again after a lost answer: every done epic is judged, and the case is open.
112
+ if (found.status === "open" && epics.some((e) => e.status === "done" && e.judged)) {
113
+ const left = epics.filter((e) => e.status === "done" && !e.judged);
114
+ if (left.length === 0) {
115
+ io.out(opts.json ? JSON.stringify({ reopened: caseId, epics: [] }) : `${caseId} is open`);
116
+ return 0;
117
+ }
118
+ }
119
+ if (found.status !== "awaiting-resolution") {
120
+ throw new Error(`${caseId} is ${found.status}: a case is judged at resolution, once all its epics are done`);
121
+ }
122
+ const judged = epics.filter((e) => e.status === "done" && !e.judged).map((e) => e.id);
123
+ await (await trackerOf(io)).log(caseId, `${await today(io)} not solved yet after ${judged.join(", ")}: ${line} ${notSolvedMarker(judged)}`);
124
+ io.out(opts.json ? JSON.stringify({ reopened: caseId, epics: judged }) : `reopened ${caseId}`);
125
+ return 0;
126
+ }
@@ -0,0 +1,137 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { appendFile, mkdir, readdir, readFile, stat } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { cloneUrlOf } from "../config.js";
7
+ import { git } from "../git.js";
8
+ import { repoOf } from "../host/github.js";
9
+ import { checkoutDirs, cloneDir, sameUrl, workspaceOfHub } from "../workspace.js";
10
+ const run = promisify(execFile);
11
+ /** The clone URL of a repository, from the hub's: the same host and form, another `owner/name`. */
12
+ export function cloneUrl(hubUrl, slug) {
13
+ const m = /^(.*[:/])[^/:]+\/[^/]+?(\.git)?(\/?)$/.exec(hubUrl.trim());
14
+ if (!m)
15
+ throw new Error(`cannot derive a clone URL for ${slug} from the hub's origin ${hubUrl}`);
16
+ return `${m[1]}${slug}${m[2] ?? ""}`;
17
+ }
18
+ /**
19
+ * `cupola workspace setup`: clones every other repository of the
20
+ * configuration under the hub, records in each checkout which repository it
21
+ * is and where its hub is, and keeps the clones out of the hub's status.
22
+ * Running it again verifies what is there and clones what is missing.
23
+ */
24
+ export async function workspaceSetup(io, opts) {
25
+ const ws = await workspaceOfHub(io);
26
+ const hubUrl = await git(ws.hub.main, ["remote", "get-url", "origin"]);
27
+ await git(ws.hub.main, ["config", "cupola.repo", ws.hub.slug]);
28
+ const results = [];
29
+ const exclude = [];
30
+ const known = await checkoutDirs(ws.hub.main);
31
+ for (const slug of ws.repos.filter((s) => s !== ws.hub.slug)) {
32
+ // A workspace that exists may hold the clone under another name: found by its origin.
33
+ // Code mounted in the hub's tree is always at its clone's name, where every worktree mounts it.
34
+ const codeOnly = !ws.slugs.includes(slug);
35
+ const recorded = codeOnly ? undefined : known.get(slug.toLowerCase());
36
+ const found = codeOnly ? undefined : (recorded ?? (await existingClone(ws.hub.main, slug)));
37
+ const dir = found ? join(ws.hub.main, found) : cloneDir(ws.hub.main, slug);
38
+ const name = dir.slice(ws.hub.main.length + 1);
39
+ if (name !== cloneDir(ws.hub.main, slug).slice(ws.hub.main.length + 1)) {
40
+ await git(ws.hub.main, ["config", `cupola.${slug}.checkout`, name]);
41
+ }
42
+ exclude.push(`/${name}/`, `/${name}.worktrees/`);
43
+ let cloned = false;
44
+ if (!existsSync(dir)) {
45
+ try {
46
+ await run("git", [
47
+ "clone",
48
+ "--quiet",
49
+ cloneUrlOf(ws.config, slug) ?? cloneUrl(hubUrl, slug),
50
+ dir,
51
+ ]);
52
+ cloned = true;
53
+ }
54
+ catch (error) {
55
+ results.push({ repo: slug, dir, cloned, problem: `clone failed: ${firstLine(error)}` });
56
+ continue;
57
+ }
58
+ }
59
+ else if (!existsSync(join(dir, ".git"))) {
60
+ results.push({ repo: slug, dir, cloned, problem: `${dir} exists and is not a git checkout` });
61
+ continue;
62
+ }
63
+ const originUrl = await git(dir, ["remote", "get-url", "origin"]).catch(() => "");
64
+ const origin = repoOf(originUrl);
65
+ const named = await git(dir, ["config", "--get", "cupola.repo"]).catch(() => "");
66
+ const local = /^(\/|file:|\.)/.test(originUrl);
67
+ const byUrl = sameUrl(cloneUrlOf(ws.config, slug), originUrl);
68
+ if (!local &&
69
+ !byUrl &&
70
+ origin !== slug.toLowerCase() &&
71
+ named.toLowerCase() !== slug.toLowerCase()) {
72
+ results.push({
73
+ repo: slug,
74
+ dir,
75
+ cloned,
76
+ problem: `${dir}'s origin is ${origin ?? "missing"}, not ${slug}`,
77
+ });
78
+ continue;
79
+ }
80
+ await git(dir, ["config", "cupola.repo", slug]);
81
+ await git(dir, ["config", "cupola.hub", ws.hub.main]);
82
+ results.push({ repo: slug, dir, cloned });
83
+ }
84
+ await excludeFromHub(ws.hub.main, exclude);
85
+ const ok = results.every((r) => !r.problem);
86
+ if (opts.json)
87
+ io.out(JSON.stringify({ ok, hub: ws.hub.main, repos: results }));
88
+ else {
89
+ for (const r of results)
90
+ io.out(`${r.repo}: ${r.problem ?? (r.cloned ? `cloned into ${r.dir}` : `at ${r.dir}`)}`);
91
+ if (results.length === 0)
92
+ io.out("One repository: nothing to set up.");
93
+ }
94
+ return ok ? 0 : 1;
95
+ }
96
+ /**
97
+ * A main checkout directly under the hub whose origin is the repository (a
98
+ * `.git` directory: a worktree has a `.git` file), when the clone is not at its
99
+ * default place.
100
+ */
101
+ async function existingClone(hubMain, slug) {
102
+ if (existsSync(cloneDir(hubMain, slug)))
103
+ return undefined;
104
+ for (const entry of await readdir(hubMain, { withFileTypes: true })) {
105
+ if (!entry.isDirectory())
106
+ continue;
107
+ const dotGit = join(hubMain, entry.name, ".git");
108
+ if (!existsSync(dotGit) || !(await stat(dotGit)).isDirectory())
109
+ continue;
110
+ const url = await git(join(hubMain, entry.name), ["remote", "get-url", "origin"]).catch(() => "");
111
+ if (repoOf(url) === slug.toLowerCase())
112
+ return entry.name;
113
+ }
114
+ return undefined;
115
+ }
116
+ /** Adds the clones and their worktrees to the hub's `.git/info/exclude`, once each. */
117
+ async function excludeFromHub(hubMain, lines) {
118
+ if (lines.length === 0)
119
+ return;
120
+ const file = await git(hubMain, [
121
+ "rev-parse",
122
+ "--path-format=absolute",
123
+ "--git-path",
124
+ "info/exclude",
125
+ ]);
126
+ await mkdir(dirname(file), { recursive: true });
127
+ const have = existsSync(file) ? (await readFile(file, "utf8")).split("\n") : [];
128
+ const add = lines.filter((l) => !have.includes(l));
129
+ if (add.length === 0)
130
+ return;
131
+ const sep = have.length > 0 && have[have.length - 1] !== "" ? "\n" : "";
132
+ await appendFile(file, `${sep}${add.join("\n")}\n`);
133
+ }
134
+ function firstLine(error) {
135
+ const e = error;
136
+ return (e.stderr || e.message || String(error)).trim().split("\n")[0] ?? "";
137
+ }
@@ -0,0 +1,422 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
+ import { mountWork } from "../code.js";
4
+ import { git, originDefaultBranch } from "../git.js";
5
+ import { codeHost } from "../host/index.js";
6
+ import { assertWorkId, workBranchName } from "../work.js";
7
+ import { locateWork, workspace } from "../workspace.js";
8
+ /** The main checkout of the repository the work lives in. */
9
+ async function workCheckout(io, id, branch, component) {
10
+ const ws = await workspace(io);
11
+ // An epic's own record runs on the hub's epic branch.
12
+ if (branch.startsWith("epic/"))
13
+ return { main: ws.hub.main, ws };
14
+ return { main: (await locateWork(ws, id, { component, branch })).main, ws };
15
+ }
16
+ export async function existingWorktree(cwd, branch) {
17
+ // Forget worktrees whose directories were deleted, so a missing path is never returned.
18
+ await git(cwd, ["worktree", "prune"]);
19
+ const list = await git(cwd, ["worktree", "list", "--porcelain"]);
20
+ let path;
21
+ for (const line of list.split("\n")) {
22
+ if (line.startsWith("worktree "))
23
+ path = line.slice("worktree ".length);
24
+ if (line === `branch refs/heads/${branch}`)
25
+ return path;
26
+ }
27
+ return undefined;
28
+ }
29
+ export async function hasRef(cwd, ref) {
30
+ try {
31
+ await git(cwd, ["rev-parse", "--verify", "--quiet", ref]);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * Adds a worktree of `branch` at `path`: the local branch, origin's, or a new
40
+ * branch from `from` (origin's default branch when not given). With
41
+ * `mustExist`, a branch origin does not have is an error, explained by it.
42
+ */
43
+ export async function addWorktree(main, path, branch, opts) {
44
+ if (existsSync(path))
45
+ throw new Error(`${path} exists but is not the worktree of ${branch}`);
46
+ const remotes = (await git(main, ["remote"])).split("\n");
47
+ let onOrigin = false;
48
+ if (remotes.includes("origin")) {
49
+ try {
50
+ await git(main, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`]);
51
+ onOrigin = true;
52
+ }
53
+ catch (error) {
54
+ // Exit code 2: origin is reachable and the branch is not on it. Anything else
55
+ // must stop: creating the branch afresh would fork someone else's progress.
56
+ if (error.code !== 2) {
57
+ throw new Error(`cannot reach origin to look for ${branch}; try again when it is reachable`);
58
+ }
59
+ }
60
+ if (onOrigin) {
61
+ await git(main, [
62
+ "fetch",
63
+ "--quiet",
64
+ "origin",
65
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
66
+ ]);
67
+ }
68
+ }
69
+ if (opts.mustExist && !onOrigin) {
70
+ throw new Error(`${branch} is not on origin; ${opts.mustExist}`);
71
+ }
72
+ if (await hasRef(main, `refs/heads/${branch}`)) {
73
+ await git(main, ["worktree", "add", "--quiet", path, branch]);
74
+ }
75
+ else if (onOrigin) {
76
+ await git(main, [
77
+ "worktree",
78
+ "add",
79
+ "--quiet",
80
+ "--track",
81
+ "-b",
82
+ branch,
83
+ path,
84
+ `origin/${branch}`,
85
+ ]);
86
+ }
87
+ else {
88
+ let from = opts.from;
89
+ if (!from) {
90
+ const base = await originDefaultBranch(main);
91
+ if (!base)
92
+ throw new Error("cannot tell origin's default branch; name the starting point with --from <ref>");
93
+ await git(main, ["fetch", "--quiet", "origin", base]);
94
+ from = `origin/${base}`;
95
+ }
96
+ await git(main, ["worktree", "add", "--quiet", "--no-track", "-b", branch, path, from]);
97
+ }
98
+ }
99
+ /**
100
+ * `cupola worktree <work>`: creates or finds the worktree of a work item, on
101
+ * its branch, next to the repository (`<repo>.worktrees/<work>`), and prints
102
+ * its path. A new branch starts from `--from`, or origin's default branch.
103
+ */
104
+ export async function worktree(io, id, opts) {
105
+ assertWorkId(id);
106
+ // An epic's own record runs on its epic branch, which exists already (`cupola epic branch`).
107
+ const branch = opts.epicBranch ? `epic/${id}` : workBranchName(id);
108
+ const located = opts.inRepo
109
+ ? undefined
110
+ : await workCheckout(io, id, branch, opts.epicBranch ? undefined : opts.component);
111
+ const main = opts.inRepo ?? located.main;
112
+ let path = await existingWorktree(main, branch);
113
+ let created = false;
114
+ if (!path) {
115
+ path = join(dirname(main), `${basename(main)}.worktrees`, opts.epicBranch ? `epic-${id}` : id);
116
+ await addWorktree(main, path, branch, {
117
+ from: opts.from,
118
+ ...(opts.epicBranch
119
+ ? { mustExist: `an epic branch is made by \`cupola epic branch ${id}\`` }
120
+ : {}),
121
+ });
122
+ created = true;
123
+ }
124
+ // The epic branch moves on without this worktree: every spec merged into it, every sync.
125
+ if (opts.epicBranch)
126
+ await catchUp(path, branch);
127
+ // With every document in the hub, the code the work changes is mounted in it.
128
+ const mounts = located ? await mountWork(located.ws, path, id, branch, opts.component) : [];
129
+ if (opts.epicBranch)
130
+ for (const m of mounts)
131
+ await catchUp(m.path, branch);
132
+ io.out(opts.json
133
+ ? JSON.stringify({
134
+ path,
135
+ branch,
136
+ created,
137
+ ...(mounts.length > 0
138
+ ? { code: mounts.map((m) => ({ repo: m.slug, path: m.path })) }
139
+ : {}),
140
+ })
141
+ : path);
142
+ return 0;
143
+ }
144
+ /** Fast-forwards a clean worktree to origin's copy of its branch; refuses anything else. */
145
+ export async function catchUp(path, branch) {
146
+ await git(path, [
147
+ "fetch",
148
+ "--quiet",
149
+ "origin",
150
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
151
+ ]);
152
+ if ((await git(path, ["status", "--porcelain"])) !== "") {
153
+ throw new Error(`${path} has uncommitted changes; commit or discard them before going on`);
154
+ }
155
+ try {
156
+ await git(path, ["merge", "--ff-only", "--quiet", `origin/${branch}`]);
157
+ }
158
+ catch {
159
+ throw new Error(`${path} and origin's ${branch} have both moved on; merge origin/${branch} into it (or rebase), push, and run this again`);
160
+ }
161
+ }
162
+ /**
163
+ * `cupola worktree <work> --remove`: removes the work's worktree and its local
164
+ * branch after its change is merged (cupola-complete). A worktree
165
+ * with uncommitted changes is kept.
166
+ */
167
+ export async function worktreeRemove(io, id, opts) {
168
+ assertWorkId(id);
169
+ // An epic branch is removed once its release change is merged.
170
+ const branch = opts.epicBranch ? `epic/${id}` : workBranchName(id);
171
+ const { main, ws } = await workCheckout(io, id, branch, opts.epicBranch ? undefined : opts.component);
172
+ const change = await (io.host ?? codeHost)(main).findChange(branch);
173
+ if (change?.state !== "merged" && change?.state !== "closed") {
174
+ throw new Error(`${id}'s change is ${change ? change.state : "not opened"}; worktrees are removed after the merge`);
175
+ }
176
+ const path = await existingWorktree(main, branch);
177
+ if (path) {
178
+ const rel = relative(path, resolve(io.cwd));
179
+ if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))) {
180
+ throw new Error(`this command runs inside ${path}; run it from ${main}`);
181
+ }
182
+ const dirty = await git(path, ["status", "--porcelain"]);
183
+ if (dirty !== "")
184
+ throw new Error(`${path} has uncommitted changes; commit or discard them first`);
185
+ }
186
+ // Code mounted in the worktree is checked first: removing the worktree would delete it unseen.
187
+ const code = await codeToRemove(io, ws, branch, {
188
+ epicBranch: opts.epicBranch === true,
189
+ hub: change.state,
190
+ });
191
+ const local = (await hasRef(main, `refs/heads/${branch}`))
192
+ ? await git(main, ["rev-parse", `refs/heads/${branch}`])
193
+ : undefined;
194
+ if (local && !(await holds(main, change, local))) {
195
+ throw new Error(`${branch} has commits that are not in its change; push them to a new change or drop them first`);
196
+ }
197
+ const codeDeleted = await removeCode(code, branch, path, {
198
+ epicBranch: opts.epicBranch === true,
199
+ });
200
+ if (path)
201
+ await git(main, ["worktree", "remove", path]);
202
+ if (local)
203
+ await git(main, ["branch", "-D", branch]);
204
+ // An epic branch has worktrees in the other repositories too (the epic's acceptance check).
205
+ const kept = [];
206
+ if (opts.epicBranch) {
207
+ for (const other of await epicBranchRepos(io, ws, id)) {
208
+ if (other.main === main)
209
+ continue;
210
+ const there = await existingWorktree(other.main, branch);
211
+ if (there) {
212
+ if ((await git(there, ["status", "--porcelain"])) !== "") {
213
+ kept.push(there);
214
+ continue;
215
+ }
216
+ await git(other.main, ["worktree", "remove", there]);
217
+ }
218
+ if (await hasRef(other.main, `refs/heads/${branch}`)) {
219
+ const sha = await git(other.main, ["rev-parse", `refs/heads/${branch}`]);
220
+ if (other.change && (await holds(other.main, other.change, sha))) {
221
+ await git(other.main, ["branch", "-D", branch]);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ // A merged change holds the branch: origin's copy goes too, in every repository it is in
227
+ // (an epic branch is in each repository the epic touches). A closed one keeps it for reference.
228
+ const remoteDeleted = [];
229
+ remoteDeleted.push(...codeDeleted);
230
+ if (change.state === "merged") {
231
+ const where = opts.epicBranch
232
+ ? await epicBranchRepos(io, ws, id)
233
+ : [{ slug: "", main, change }];
234
+ for (const w of where) {
235
+ if (w.change?.state !== "merged")
236
+ continue;
237
+ if (await deleteRemote(w.main, branch, w.change))
238
+ remoteDeleted.push(w.slug || branch);
239
+ }
240
+ }
241
+ io.out(opts.json
242
+ ? JSON.stringify({
243
+ removed: path ?? null,
244
+ branchDeleted: local !== undefined,
245
+ remoteDeleted: remoteDeleted.length > 0,
246
+ ...(kept.length > 0 ? { kept } : {}),
247
+ })
248
+ : path
249
+ ? `removed ${path}`
250
+ : `nothing to remove: ${id} has no worktree here (already removed)`);
251
+ return 0;
252
+ }
253
+ /**
254
+ * With every document in the hub: the code repositories' worktrees
255
+ * of a branch, checked before anything is removed. Each must be clean, and a
256
+ * work's code change merged or closed (or never opened).
257
+ */
258
+ async function codeToRemove(io, ws, branch, opts) {
259
+ if (ws.config.documents !== "hub")
260
+ return [];
261
+ const found = [];
262
+ for (const slug of ws.repos.filter((r) => !ws.slugs.includes(r))) {
263
+ let main;
264
+ try {
265
+ main = ws.checkout(slug).main;
266
+ }
267
+ catch {
268
+ continue; // not cloned: nothing of it is here
269
+ }
270
+ const path = await existingWorktree(main, branch);
271
+ const change = (await ws.host(io, slug).findChange(branch)) ?? undefined;
272
+ if (!opts.epicBranch && change?.state === "open") {
273
+ throw new Error(`the code change of ${slug} is open (${change.url}); worktrees are removed after the merge`);
274
+ }
275
+ // The documents are merged but the code is not: the work is not done, and its code is kept.
276
+ if (!opts.epicBranch && opts.hub === "merged" && change?.state === "closed") {
277
+ throw new Error(`the code change of ${slug} was closed without merging (${change.url}); reopen and merge it first`);
278
+ }
279
+ if (path && (await git(path, ["status", "--porcelain"])) !== "") {
280
+ throw new Error(`${path} has uncommitted changes; commit or discard them first`);
281
+ }
282
+ // Checked before anything is removed, so that a refusal leaves every worktree in place.
283
+ if (!opts.epicBranch && (await hasRef(main, `refs/heads/${branch}`))) {
284
+ const sha = await git(main, ["rev-parse", `refs/heads/${branch}`]);
285
+ const held = change ? await holds(main, change, sha) : await merged(main, sha);
286
+ if (!held) {
287
+ throw new Error(`${branch} of ${slug} has commits that are not in its change; push them to a new change or drop them first`);
288
+ }
289
+ }
290
+ found.push({ slug, main, path, change });
291
+ }
292
+ return found;
293
+ }
294
+ /**
295
+ * Removes the code repositories' worktrees of a branch, before the hub's
296
+ * worktree that mounts them. A work branch is deleted when its change holds
297
+ * it, and origin's copy when the change was merged; returns the repositories
298
+ * whose origin copy went. An epic branch's other worktrees and branches are
299
+ * left to the epic's removal, which handles every repository.
300
+ */
301
+ async function removeCode(found, branch, inside, opts) {
302
+ const remoteDeleted = [];
303
+ for (const f of found) {
304
+ const mounted = f.path !== undefined && inside !== undefined && isInside(inside, f.path);
305
+ if (opts.epicBranch) {
306
+ if (mounted && f.path)
307
+ await git(f.main, ["worktree", "remove", f.path]);
308
+ continue;
309
+ }
310
+ if (f.path)
311
+ await git(f.main, ["worktree", "remove", f.path]);
312
+ // Every commit is in its change: checked by codeToRemove before anything was removed.
313
+ if (await hasRef(f.main, `refs/heads/${branch}`))
314
+ await git(f.main, ["branch", "-D", branch]);
315
+ if (f.change?.state === "merged" && (await deleteRemote(f.main, branch, f.change)))
316
+ remoteDeleted.push(f.slug);
317
+ }
318
+ return remoteDeleted;
319
+ }
320
+ /** Whether `path` is `dir` or lies under it, by their real paths. */
321
+ function isInside(dir, path) {
322
+ const real = (p) => (existsSync(p) ? realpathSync(p) : resolve(p));
323
+ const rel = relative(real(dir), real(path));
324
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
325
+ }
326
+ /** Whether a commit is on origin's default branch already: a branch with nothing of its own. */
327
+ async function merged(main, sha) {
328
+ const base = await originDefaultBranch(main);
329
+ if (!base)
330
+ return false;
331
+ try {
332
+ await git(main, ["fetch", "--quiet", "origin", base]);
333
+ await git(main, ["merge-base", "--is-ancestor", sha, "FETCH_HEAD"]);
334
+ return true;
335
+ }
336
+ catch {
337
+ return false;
338
+ }
339
+ }
340
+ /** The repositories that have the epic branch, each with its release change. */
341
+ async function epicBranchRepos(io, ws, id) {
342
+ const out = [];
343
+ for (const slug of ws.repos) {
344
+ let main;
345
+ try {
346
+ main = ws.checkout(slug).main;
347
+ }
348
+ catch {
349
+ continue;
350
+ }
351
+ out.push({
352
+ slug,
353
+ main,
354
+ change: (await (io.host ?? codeHost)(main).findChange(`epic/${id}`)) ?? undefined,
355
+ });
356
+ }
357
+ return out;
358
+ }
359
+ /** Deletes origin's branch when the merged change holds its head; whether it did. */
360
+ async function deleteRemote(main, branch, change) {
361
+ let sha;
362
+ try {
363
+ sha =
364
+ (await git(main, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`])).split(/\s/)[0] ?? "";
365
+ }
366
+ catch (error) {
367
+ // Exit code 2: gone already (deleted on merge). Its tracking ref goes too, so that nothing
368
+ // later takes it for a live branch; unreachable leaves everything as it is.
369
+ if (error.code === 2)
370
+ await git(main, ["update-ref", "-d", `refs/remotes/origin/${branch}`]).catch(() => { });
371
+ return false;
372
+ }
373
+ if (sha === "")
374
+ return false;
375
+ await git(main, [
376
+ "fetch",
377
+ "--quiet",
378
+ "origin",
379
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
380
+ ]);
381
+ if (!(await holds(main, change, sha)))
382
+ return false;
383
+ await git(main, ["push", "--quiet", "origin", "--delete", branch]);
384
+ return true;
385
+ }
386
+ /**
387
+ * Whether the merged or closed change holds every commit of the local branch.
388
+ * The remote branch may be gone (deleted on merge), so the change's own head
389
+ * is the measure; without it, the branch must be reachable from origin's
390
+ * default branch. When neither can be checked, the answer is no.
391
+ */
392
+ async function holds(main, change, local) {
393
+ if (change.head === local)
394
+ return true;
395
+ const contains = async (ref) => {
396
+ try {
397
+ await git(main, ["merge-base", "--is-ancestor", local, ref]);
398
+ return true;
399
+ }
400
+ catch {
401
+ return false;
402
+ }
403
+ };
404
+ try {
405
+ await git(main, ["fetch", "--quiet", "origin", `refs/pull/${change.number}/head`]);
406
+ if (await contains("FETCH_HEAD"))
407
+ return true;
408
+ }
409
+ catch {
410
+ // not a GitHub remote, or unreachable
411
+ }
412
+ const base = await originDefaultBranch(main);
413
+ if (!base)
414
+ return false;
415
+ try {
416
+ await git(main, ["fetch", "--quiet", "origin", base]);
417
+ }
418
+ catch {
419
+ return false;
420
+ }
421
+ return contains("FETCH_HEAD");
422
+ }