pi-roundtable-coding 0.43.0 → 0.44.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.
@@ -0,0 +1,248 @@
1
+ import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
2
+ import { isAbsolute, join, relative, resolve } from "node:path";
3
+ import { AgentError, scrubDiagnostic } from "pi-roundtable/kit";
4
+ import type { GitRunner } from "./git-run.ts";
5
+ import {
6
+ type Integration,
7
+ type RepoState,
8
+ WORKTREES_DIR,
9
+ type WorkerTree,
10
+ } from "./repo-types.ts";
11
+
12
+ /** The worker worktrees under one shelf: cut from a clone, integrated back, removed. */
13
+ export class WorkerTrees {
14
+ readonly #shelfDir: string;
15
+ readonly #dirOf: (repo: string) => string;
16
+ readonly #runner: GitRunner;
17
+ /** The last change to each clone's worktrees, which the next waits for. */
18
+ readonly #changing = new Map<string, Promise<unknown>>();
19
+
20
+ constructor(
21
+ shelfDir: string,
22
+ dirOf: (repo: string) => string,
23
+ runner: GitRunner,
24
+ ) {
25
+ this.#shelfDir = shelfDir;
26
+ this.#dirOf = dirOf;
27
+ this.#runner = runner;
28
+ }
29
+
30
+ /**
31
+ * Cuts a worktree for coding job `id` from the clone's HEAD, on a fresh branch `worker/<id>`
32
+ * (with a suffix when an earlier run kept one of that name), under `<shelf>/.worktrees/`.
33
+ */
34
+ async add(repo: string, id: number): Promise<WorkerTree> {
35
+ const clone = this.#dirOf(repo);
36
+ const base = await this.#runner.git(clone, "rev-parse", "HEAD");
37
+ const parent = join(this.#shelfDir, WORKTREES_DIR, repo);
38
+ mkdirSync(parent, { recursive: true });
39
+ const rel = relative(realpathSync(this.#shelfDir), realpathSync(parent));
40
+ if (rel.startsWith("..") || isAbsolute(rel))
41
+ throw new AgentError("The worktree folder escapes the shelf.");
42
+ for (let attempt = 1; ; attempt++) {
43
+ const name = attempt === 1 ? `${id}` : `${id}-${attempt}`;
44
+ const branch = `worker/${name}`;
45
+ const dir = join(parent, name);
46
+ const taken =
47
+ existsSync(dir) ||
48
+ (
49
+ await this.#runner.run([
50
+ "git",
51
+ "-C",
52
+ clone,
53
+ "rev-parse",
54
+ "--verify",
55
+ "--quiet",
56
+ `refs/heads/${branch}`,
57
+ ])
58
+ ).code === 0;
59
+ if (taken) continue;
60
+ await this.#alone(clone, () =>
61
+ this.#runner.git(
62
+ clone,
63
+ "worktree",
64
+ "add",
65
+ "--quiet",
66
+ "-b",
67
+ branch,
68
+ dir,
69
+ base,
70
+ ),
71
+ );
72
+ return { repo, dir: realpathSync(dir), branch, base };
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Rebases the worker's branch onto the clone's current HEAD inside its worktree and
78
+ * fast-forwards the clone, then removes the worktree and branch. The clone is never left
79
+ * mid-rebase: a conflict aborts the rebase in the worktree and keeps both. A clone or worktree
80
+ * with uncommitted changes is not touched. The caller serializes integrations of one clone.
81
+ */
82
+ async integrate(tree: WorkerTree): Promise<Integration> {
83
+ const clone = this.#dirOf(tree.repo);
84
+ const kept = { branch: tree.branch, dir: tree.dir };
85
+ const dirty = await this.#runner.git(clone, "status", "--porcelain");
86
+ if (dirty)
87
+ return {
88
+ status: "refused",
89
+ ...kept,
90
+ reason: `the clone has uncommitted changes, so it was left as it is:\n${dirty}`,
91
+ };
92
+ const head = await this.#runner.git(clone, "rev-parse", "HEAD");
93
+ const ahead = Number(
94
+ await this.#runner.git(
95
+ clone,
96
+ "rev-list",
97
+ "--count",
98
+ `${head}..${tree.branch}`,
99
+ ),
100
+ );
101
+ if (ahead === 0) {
102
+ await this.remove(tree);
103
+ return { status: "nothing" };
104
+ }
105
+ const treeDir = this.#treeDir(tree);
106
+ const treeDirty = await this.#runner.git(treeDir, "status", "--porcelain");
107
+ if (treeDirty)
108
+ return {
109
+ status: "refused",
110
+ ...kept,
111
+ reason: `the worker left uncommitted changes in its worktree:\n${treeDirty}`,
112
+ };
113
+ const rebase = await this.#runner.run([
114
+ "git",
115
+ "-C",
116
+ treeDir,
117
+ "rebase",
118
+ "--quiet",
119
+ head,
120
+ ]);
121
+ if (rebase.code !== 0) {
122
+ const conflicted = await this.#runner.run([
123
+ "git",
124
+ "-C",
125
+ treeDir,
126
+ "diff",
127
+ "--name-only",
128
+ "--diff-filter=U",
129
+ ]);
130
+ await this.#runner.run(["git", "-C", treeDir, "rebase", "--abort"]);
131
+ return {
132
+ status: "conflict",
133
+ ...kept,
134
+ files: conflicted.out ? conflicted.out.split("\n") : [],
135
+ };
136
+ }
137
+ const merge = await this.#runner.run([
138
+ "git",
139
+ "-C",
140
+ clone,
141
+ "merge",
142
+ "--ff-only",
143
+ "--quiet",
144
+ tree.branch,
145
+ ]);
146
+ if (merge.code !== 0)
147
+ return {
148
+ status: "refused",
149
+ ...kept,
150
+ reason: `the clone could not fast-forward to the branch: ${scrubDiagnostic(merge.err, this.#runner.diagnosticChars) || `exit ${merge.code}`}`,
151
+ };
152
+ const log = await this.#runner.git(
153
+ clone,
154
+ "log",
155
+ "--format=%h %s",
156
+ "--abbrev=12",
157
+ `${head}..HEAD`,
158
+ );
159
+ await this.remove(tree);
160
+ return {
161
+ status: "merged",
162
+ branch: tree.branch,
163
+ commits: log ? log.split("\n") : [],
164
+ };
165
+ }
166
+
167
+ /** A worker worktree's state, as `state` reads a clone's. */
168
+ async state(tree: WorkerTree): Promise<RepoState> {
169
+ const dir = this.#treeDir(tree);
170
+ const status = await this.#runner.git(dir, "status", "--porcelain");
171
+ return {
172
+ branch: await this.#runner.git(dir, "rev-parse", "--abbrev-ref", "HEAD"),
173
+ head: await this.#runner.git(dir, "rev-parse", "--short=12", "HEAD"),
174
+ uncommitted: status ? status.split("\n") : [],
175
+ };
176
+ }
177
+
178
+ /** `<short sha> <subject>` of each commit on the worker's branch after its base, newest first. */
179
+ async commits(tree: WorkerTree): Promise<string[]> {
180
+ const log = await this.#runner.git(
181
+ this.#treeDir(tree),
182
+ "log",
183
+ "--format=%h %s",
184
+ "--abbrev=12",
185
+ `${tree.base}..HEAD`,
186
+ );
187
+ return log ? log.split("\n") : [];
188
+ }
189
+
190
+ /** Removes a worker's worktree and its branch; what is already gone is skipped. */
191
+ async remove(tree: WorkerTree): Promise<void> {
192
+ const clone = this.#dirOf(tree.repo);
193
+ this.#treeDir(tree, false);
194
+ await this.#alone(clone, async () => {
195
+ await this.#runner.run([
196
+ "git",
197
+ "-C",
198
+ clone,
199
+ "worktree",
200
+ "remove",
201
+ "--force",
202
+ tree.dir,
203
+ ]);
204
+ if (existsSync(tree.dir))
205
+ rmSync(tree.dir, { recursive: true, force: true });
206
+ await this.#runner.run(["git", "-C", clone, "worktree", "prune"]);
207
+ await this.#runner.run([
208
+ "git",
209
+ "-C",
210
+ clone,
211
+ "branch",
212
+ "-D",
213
+ "--quiet",
214
+ tree.branch,
215
+ ]);
216
+ });
217
+ }
218
+
219
+ /**
220
+ * Runs a change to a clone's worktrees after the one before it. Git lists every linked
221
+ * worktree while it adds, removes or prunes one, and fails on a folder another such call is
222
+ * still writing (`failed to read .git/worktrees/1/commondir`), so two workers starting at
223
+ * once, or one starting as another's branch is removed, cannot each go ahead alone.
224
+ */
225
+ async #alone<T>(clone: string, change: () => Promise<T>): Promise<T> {
226
+ const previous = this.#changing.get(clone) ?? Promise.resolve();
227
+ const mine = previous.catch(() => {}).then(change);
228
+ this.#changing.set(clone, mine);
229
+ try {
230
+ return await mine;
231
+ } finally {
232
+ if (this.#changing.get(clone) === mine) this.#changing.delete(clone);
233
+ }
234
+ }
235
+
236
+ /** A worktree path, refused unless it lies in this repository's worktree folder. */
237
+ #treeDir(tree: WorkerTree, mustExist = true): string {
238
+ const parent = resolve(this.#shelfDir, WORKTREES_DIR, tree.repo);
239
+ const path = mustExist ? realpathSync(tree.dir) : resolve(tree.dir);
240
+ const root = existsSync(parent) ? realpathSync(parent) : parent;
241
+ const rel = relative(root, path);
242
+ if (!rel || rel.startsWith("..") || isAbsolute(rel) || rel.includes("/"))
243
+ throw new AgentError(
244
+ "The worktree lies outside the shelf's worktree folder.",
245
+ );
246
+ return path;
247
+ }
248
+ }