@unieai/rabi-experimental-worktree 0.0.0-stage → 0.2.2-rc.5
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.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/index.js +1061 -0
- package/lib/types/archive.d.ts +84 -0
- package/lib/types/archive.js +213 -0
- package/lib/types/directory.d.ts +7 -0
- package/lib/types/directory.js +24 -0
- package/lib/types/index.d.ts +130 -0
- package/lib/types/index.js +299 -0
- package/lib/types/name.d.ts +12 -0
- package/lib/types/name.js +17 -0
- package/lib/types/process.d.ts +47 -0
- package/lib/types/process.js +191 -0
- package/lib/types/projection.d.ts +47 -0
- package/lib/types/projection.js +43 -0
- package/lib/types/removal.d.ts +80 -0
- package/lib/types/removal.js +114 -0
- package/lib/types/types.d.ts +62 -0
- package/lib/types/types.js +2 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +53 -4
- package/src/archive.ts +253 -0
- package/src/directory.ts +25 -0
- package/src/index.ts +388 -0
- package/src/name.ts +21 -0
- package/src/process.ts +164 -0
- package/src/projection.ts +70 -0
- package/src/removal.ts +142 -0
- package/src/types.ts +68 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1061 @@
|
|
|
1
|
+
import { Service } from "@unieai/cordis";
|
|
2
|
+
import z from "@unieai/schemastery";
|
|
3
|
+
import { appendPluginRecord, pluginRecordOf } from "@unieai/rabi-session";
|
|
4
|
+
import { MAX_TIMER_DELAY_MS, deadline } from "@unieai/rabi-timeout";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { z as z$1 } from "zod";
|
|
7
|
+
//#region lib/types/archive.js
|
|
8
|
+
/**
|
|
9
|
+
* Whether `path` is `root` or lies below it. Both are canonical absolute
|
|
10
|
+
* directories of one execution world without a trailing separator, so string
|
|
11
|
+
* prefixing is exact.
|
|
12
|
+
*/
|
|
13
|
+
function within(root, path) {
|
|
14
|
+
return path === root || path.startsWith(`${root}/`);
|
|
15
|
+
}
|
|
16
|
+
/** Owns pending cleanup, gates directory entry into a checkout being removed, and drains before the service is released. */
|
|
17
|
+
var WorktreeReclamation = class {
|
|
18
|
+
ctx;
|
|
19
|
+
host;
|
|
20
|
+
projection;
|
|
21
|
+
attempts = /* @__PURE__ */ new Map();
|
|
22
|
+
removing = /* @__PURE__ */ new Map();
|
|
23
|
+
pending = /* @__PURE__ */ new Set();
|
|
24
|
+
lifetime = new AbortController();
|
|
25
|
+
revision = 0;
|
|
26
|
+
/**
|
|
27
|
+
* @param ctx - scope injecting the Workspace registry, Session query, store, working-directory, and
|
|
28
|
+
* sandbox-policy providers; the projection cache is read when mounted.
|
|
29
|
+
* @param host - the service operations the module runs through.
|
|
30
|
+
* @param projection - the `worktree` unit, read live and through the persisted cache.
|
|
31
|
+
*/
|
|
32
|
+
constructor(ctx, host, projection) {
|
|
33
|
+
this.ctx = ctx;
|
|
34
|
+
this.host = host;
|
|
35
|
+
this.projection = projection;
|
|
36
|
+
ctx.on("working-directory/access", ({ agent, path, signal }, next) => {
|
|
37
|
+
const target = path ?? ctx.workingDirectory.get(agent.session);
|
|
38
|
+
const blocked = [...this.removing.keys()].find((root) => within(root, target));
|
|
39
|
+
if (blocked === void 0) return next();
|
|
40
|
+
return this.host.exclusiveCheckout(blocked, async () => {
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
return await next();
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
ctx.on("workspace/session-archived", ({ sessionId }) => {
|
|
46
|
+
this.schedule(sessionId);
|
|
47
|
+
});
|
|
48
|
+
ctx.on("workspace/session-unarchiving", async ({ sessionId }) => {
|
|
49
|
+
const attempt = this.attempts.get(sessionId);
|
|
50
|
+
if (attempt === void 0) return;
|
|
51
|
+
attempt.cancelled = true;
|
|
52
|
+
await attempt.done;
|
|
53
|
+
this.attempts.delete(sessionId);
|
|
54
|
+
});
|
|
55
|
+
ctx.effect(() => async () => {
|
|
56
|
+
this.lifetime.abort(/* @__PURE__ */ new Error("worktree reclamation stopped"));
|
|
57
|
+
for (const attempt of this.attempts.values()) attempt.cancelled = true;
|
|
58
|
+
await Promise.allSettled(this.pending);
|
|
59
|
+
this.attempts.clear();
|
|
60
|
+
}, "worktree: drain archive cleanup");
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Read the most recent cleanup attempt of a Session; waiting never starts one.
|
|
64
|
+
* @param session - archived Session whose attempt is read.
|
|
65
|
+
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
|
66
|
+
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
|
67
|
+
*/
|
|
68
|
+
async cleanupOf(session, revision) {
|
|
69
|
+
const attempt = this.attempts.get(session.id);
|
|
70
|
+
if (attempt === void 0 || revision !== null && revision !== attempt.revision) return null;
|
|
71
|
+
if (revision !== null) await attempt.done;
|
|
72
|
+
if (this.lifetime.signal.aborted || this.attempts.get(session.id) !== attempt) return null;
|
|
73
|
+
return {
|
|
74
|
+
revision: attempt.revision,
|
|
75
|
+
status: attempt.status
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Register attempts for the Session's own creations and return; every inspection runs in the background. */
|
|
79
|
+
schedule(sessionId) {
|
|
80
|
+
if (this.host.retainOnArchive()) return;
|
|
81
|
+
const live = this.ctx.sessions.get(sessionId);
|
|
82
|
+
const owned = live === void 0 ? void 0 : this.projection.stateOf(live).created.filter((creation) => creation.owned);
|
|
83
|
+
if (owned !== void 0 && owned.length === 0) return;
|
|
84
|
+
const attempt = {
|
|
85
|
+
worktree: owned?.[0]?.worktree ?? {
|
|
86
|
+
path: "",
|
|
87
|
+
branch: "",
|
|
88
|
+
baseCommit: "",
|
|
89
|
+
repositoryRoot: ""
|
|
90
|
+
},
|
|
91
|
+
revision: ++this.revision,
|
|
92
|
+
status: "scheduled",
|
|
93
|
+
cancelled: false,
|
|
94
|
+
done: Promise.resolve()
|
|
95
|
+
};
|
|
96
|
+
this.attempts.set(sessionId, attempt);
|
|
97
|
+
const task = this.run(sessionId, attempt, owned);
|
|
98
|
+
this.pending.add(task);
|
|
99
|
+
attempt.done = task.then(() => {
|
|
100
|
+
this.pending.delete(task);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async run(sessionId, attempt, owned) {
|
|
104
|
+
const ctx = this.ctx;
|
|
105
|
+
try {
|
|
106
|
+
const candidate = (owned ?? (await this.creationsOf(sessionId, void 0)).filter((creation) => creation.owned))[0]?.worktree;
|
|
107
|
+
if (candidate === void 0) {
|
|
108
|
+
this.attempts.delete(sessionId);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
Object.assign(attempt, { worktree: candidate });
|
|
112
|
+
ctx.emit("worktree/cleanup", {
|
|
113
|
+
sessionId,
|
|
114
|
+
path: candidate.path,
|
|
115
|
+
cleanup: {
|
|
116
|
+
revision: attempt.revision,
|
|
117
|
+
status: attempt.status
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
const session = await this.creatorSession(sessionId);
|
|
121
|
+
if (session === void 0 || attempt.cancelled || ctx.sandboxPolicy.resolve({ session }).mode === "read-only" || !await this.unused(candidate, sessionId)) attempt.status = "retained";
|
|
122
|
+
else attempt.status = await this.remove(session, candidate, attempt) ? "removed" : "retained";
|
|
123
|
+
} catch (error) {
|
|
124
|
+
attempt.status = "failed";
|
|
125
|
+
ctx.logger.warn("Session %s archived; cleanup of its worktree %s failed and its branch was retained: %s", sessionId, attempt.worktree.path, error);
|
|
126
|
+
}
|
|
127
|
+
ctx.emit("worktree/cleanup", {
|
|
128
|
+
sessionId,
|
|
129
|
+
path: attempt.worktree.path,
|
|
130
|
+
cleanup: {
|
|
131
|
+
revision: attempt.revision,
|
|
132
|
+
status: attempt.status
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Remove under the path lock; a second use check runs inside it, after
|
|
138
|
+
* competing operations settled. A Session has one attempt and unarchiving
|
|
139
|
+
* awaits it, so removals of one path never overlap.
|
|
140
|
+
*/
|
|
141
|
+
async remove(session, worktree, attempt) {
|
|
142
|
+
const operation = this.host.exclusiveCheckout(worktree.path, async () => {
|
|
143
|
+
if (attempt.cancelled || !await this.unused(worktree, void 0)) return false;
|
|
144
|
+
return await this.host.removeCheckout(session, worktree, this.lifetime.signal, () => !attempt.cancelled);
|
|
145
|
+
});
|
|
146
|
+
this.removing.set(worktree.path, operation.then(() => {}, () => {}));
|
|
147
|
+
try {
|
|
148
|
+
return await operation;
|
|
149
|
+
} finally {
|
|
150
|
+
this.removing.delete(worktree.path);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Whether no unarchived Session still refers to the checkout: by a recorded
|
|
155
|
+
* creation, inherited or own, or by a working directory inside it. A Session
|
|
156
|
+
* beneath an archived subagent ancestor counts as archived, as its own
|
|
157
|
+
* archive admission does. Processes are not consulted: Git refuses a
|
|
158
|
+
* removal that would discard changes, and an idle process in a removed
|
|
159
|
+
* directory fails its next command.
|
|
160
|
+
*/
|
|
161
|
+
async unused(worktree, archivingId) {
|
|
162
|
+
const ctx = this.ctx;
|
|
163
|
+
const signal = this.lifetime.signal;
|
|
164
|
+
signal.throwIfAborted();
|
|
165
|
+
const records = await ctx.sessionQuery.listSessions(signal);
|
|
166
|
+
const headers = new Map(records.map((record) => [record.header.id, record.header]));
|
|
167
|
+
const archived = new Set(ctx.workspaceRegistry.archivedSessionIds);
|
|
168
|
+
if (archivingId !== void 0) archived.add(archivingId);
|
|
169
|
+
for (const record of records) {
|
|
170
|
+
const id = record.header.id;
|
|
171
|
+
if (archived.has(id) || ancestorArchived(record.header, headers, archived)) continue;
|
|
172
|
+
const live = ctx.sessions.get(id);
|
|
173
|
+
const cwd = live === void 0 ? await this.directoryOf(record.header) : ctx.workingDirectory.get(live);
|
|
174
|
+
if (cwd !== null && within(worktree.path, cwd)) return false;
|
|
175
|
+
if ((live === void 0 ? await this.creationsOf(id, record.header) : this.projection.stateOf(live).created).some((creation) => creation.worktree.path === worktree.path)) return false;
|
|
176
|
+
signal.throwIfAborted();
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
/** The archived Session itself, prepared cold when not live, whose sandbox policy confines the Git commands. */
|
|
181
|
+
async creatorSession(sessionId) {
|
|
182
|
+
const live = this.ctx.sessions.get(sessionId);
|
|
183
|
+
if (live !== void 0) return live;
|
|
184
|
+
return await this.ctx.sessionQuery.inspectSession(sessionId, (session) => session, this.lifetime.signal);
|
|
185
|
+
}
|
|
186
|
+
/** The recorded directory of a cold Session, null when its log recorded none: the persisted cache when it has one, else its log. */
|
|
187
|
+
async directoryOf(header) {
|
|
188
|
+
const cached = this.ctx.get("sessionProjectionCache")?.cachedSnapshot(header, ["workingDirectory"])?.values.workingDirectory;
|
|
189
|
+
if (cached !== void 0) return cached;
|
|
190
|
+
return await this.ctx.sessionQuery.inspectSession(header.id, (session) => this.ctx.workingDirectory.get(session), this.lifetime.signal);
|
|
191
|
+
}
|
|
192
|
+
/** The recorded creations of a cold Session: the persisted cache when it has one, else its log. */
|
|
193
|
+
async creationsOf(sessionId, header) {
|
|
194
|
+
const cached = header === void 0 ? void 0 : this.ctx.get("sessionProjectionCache")?.cachedSnapshot(header, ["worktree"])?.values.worktree;
|
|
195
|
+
if (cached !== void 0) return cached;
|
|
196
|
+
return await this.ctx.sessionQuery.inspectSession(sessionId, (session) => this.projection.stateOf(session).created, this.lifetime.signal);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
/** Whether any subagent ancestor of `header`, followed through the listed headers, is archived. */
|
|
200
|
+
function ancestorArchived(header, headers, archived) {
|
|
201
|
+
const visited = new Set([header.id]);
|
|
202
|
+
let current = header;
|
|
203
|
+
while (current.origin === "subagent" && current.parentSession !== void 0 && !visited.has(current.parentSession)) {
|
|
204
|
+
if (archived.has(current.parentSession)) return true;
|
|
205
|
+
visited.add(current.parentSession);
|
|
206
|
+
const parent = headers.get(current.parentSession);
|
|
207
|
+
if (parent === void 0) return false;
|
|
208
|
+
current = parent;
|
|
209
|
+
}
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region lib/types/directory.js
|
|
214
|
+
/** Static child program for exclusive checkout-directory allocation inside the process sandbox. */
|
|
215
|
+
/**
|
|
216
|
+
* The child receives the configured root and destination as literal argv. Existing roots retain
|
|
217
|
+
* their files; only the process that creates a root writes its self-ignoring .gitignore.
|
|
218
|
+
*/
|
|
219
|
+
const PREPARE_DIRECTORY = `
|
|
220
|
+
import fs from 'node:fs/promises';
|
|
221
|
+
import path from 'node:path';
|
|
222
|
+
async function main() {
|
|
223
|
+
const [root, destination] = process.argv.slice(1);
|
|
224
|
+
await fs.mkdir(path.dirname(root), { recursive: true });
|
|
225
|
+
let created = false;
|
|
226
|
+
try {
|
|
227
|
+
await fs.mkdir(root);
|
|
228
|
+
created = true;
|
|
229
|
+
} catch (error) {
|
|
230
|
+
if (error.code !== 'EEXIST' || !(await fs.stat(root)).isDirectory()) throw error;
|
|
231
|
+
}
|
|
232
|
+
if (created) await fs.writeFile(path.join(root, '.gitignore'), '*\\n', { flag: 'wx' });
|
|
233
|
+
await fs.mkdir(path.dirname(destination), { recursive: true });
|
|
234
|
+
await fs.mkdir(destination);
|
|
235
|
+
}
|
|
236
|
+
main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
|
237
|
+
`;
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region lib/types/name.js
|
|
240
|
+
/** Generated worktree names that lead back to the Session that created them. */
|
|
241
|
+
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
242
|
+
/**
|
|
243
|
+
* Generate a branch and checkout name: the prefix, the first eight hexadecimal digits of the
|
|
244
|
+
* first UUID in the Session id, a hyphen, and four random hexadecimal digits. A Session id
|
|
245
|
+
* without a UUID gets eight random hexadecimal digits after the prefix instead.
|
|
246
|
+
* @param prefix - validated name prefix.
|
|
247
|
+
* @param sessionId - id of the Session the worktree is created for.
|
|
248
|
+
* @returns the generated name; it is unique only with high probability, so creation still rejects an existing branch.
|
|
249
|
+
*/
|
|
250
|
+
function generatedWorktreeName(prefix, sessionId) {
|
|
251
|
+
const uuid = UUID.exec(sessionId)?.[0];
|
|
252
|
+
return uuid === void 0 ? `${prefix}${randomBytes(4).toString("hex")}` : `${prefix}${uuid.slice(0, 8).toLowerCase()}-${randomBytes(2).toString("hex")}`;
|
|
253
|
+
}
|
|
254
|
+
//#endregion
|
|
255
|
+
//#region lib/types/process.js
|
|
256
|
+
/** Cancellable commands under the calling Session's existing file policy, whose stdout is collected within a bound or streamed. */
|
|
257
|
+
var __addDisposableResource = function(env, value, async) {
|
|
258
|
+
if (value !== null && value !== void 0) {
|
|
259
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
260
|
+
var dispose, inner;
|
|
261
|
+
if (async) {
|
|
262
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
263
|
+
dispose = value[Symbol.asyncDispose];
|
|
264
|
+
}
|
|
265
|
+
if (dispose === void 0) {
|
|
266
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
267
|
+
dispose = value[Symbol.dispose];
|
|
268
|
+
if (async) inner = dispose;
|
|
269
|
+
}
|
|
270
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
271
|
+
if (inner) dispose = function() {
|
|
272
|
+
try {
|
|
273
|
+
inner.call(this);
|
|
274
|
+
} catch (e) {
|
|
275
|
+
return Promise.reject(e);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
env.stack.push({
|
|
279
|
+
value,
|
|
280
|
+
dispose,
|
|
281
|
+
async
|
|
282
|
+
});
|
|
283
|
+
} else if (async) env.stack.push({ async: true });
|
|
284
|
+
return value;
|
|
285
|
+
};
|
|
286
|
+
var __disposeResources = (function(SuppressedError) {
|
|
287
|
+
return function(env) {
|
|
288
|
+
function fail(e) {
|
|
289
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
290
|
+
env.hasError = true;
|
|
291
|
+
}
|
|
292
|
+
var r, s = 0;
|
|
293
|
+
function next() {
|
|
294
|
+
while (r = env.stack.pop()) try {
|
|
295
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
296
|
+
if (r.dispose) {
|
|
297
|
+
var result = r.dispose.call(r.value);
|
|
298
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
299
|
+
fail(e);
|
|
300
|
+
return next();
|
|
301
|
+
});
|
|
302
|
+
} else s |= 1;
|
|
303
|
+
} catch (e) {
|
|
304
|
+
fail(e);
|
|
305
|
+
}
|
|
306
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
307
|
+
if (env.hasError) throw env.error;
|
|
308
|
+
}
|
|
309
|
+
return next();
|
|
310
|
+
};
|
|
311
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
312
|
+
var e = new Error(message);
|
|
313
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
314
|
+
});
|
|
315
|
+
/** Clear inherited repository, attribute-tree, command-line configuration, and replacement-ref selectors. */
|
|
316
|
+
const GIT_ENV = Object.fromEntries([
|
|
317
|
+
"GIT_DIR",
|
|
318
|
+
"GIT_WORK_TREE",
|
|
319
|
+
"GIT_COMMON_DIR",
|
|
320
|
+
"GIT_INDEX_FILE",
|
|
321
|
+
"GIT_OBJECT_DIRECTORY",
|
|
322
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
323
|
+
"GIT_CONFIG",
|
|
324
|
+
"GIT_CONFIG_PARAMETERS",
|
|
325
|
+
"GIT_CONFIG_COUNT",
|
|
326
|
+
"GIT_CEILING_DIRECTORIES",
|
|
327
|
+
"GIT_PREFIX",
|
|
328
|
+
"GIT_SHALLOW_FILE",
|
|
329
|
+
"GIT_GRAFT_FILE",
|
|
330
|
+
"GIT_REPLACE_REF_BASE",
|
|
331
|
+
"GIT_ATTR_SOURCE"
|
|
332
|
+
].map((key) => [key, void 0]));
|
|
333
|
+
/**
|
|
334
|
+
* Run an argv without a shell and await termination of its managed process range.
|
|
335
|
+
* @param ctx - subprocess and sandbox providers in the same execution world.
|
|
336
|
+
* @param config - complete process resource limits.
|
|
337
|
+
* @param policy - unchanged calling Session policy.
|
|
338
|
+
* @param cwd - canonical process working directory.
|
|
339
|
+
* @param argv - executable followed by literal arguments.
|
|
340
|
+
* @param signal - operation cancellation.
|
|
341
|
+
* @param allowedExitCodes - command-specific successful statuses.
|
|
342
|
+
* @param env - command-local environment overrides, applied after Git selector removal.
|
|
343
|
+
* @returns complete bounded stdout and the exit code.
|
|
344
|
+
*/
|
|
345
|
+
async function runCommand(ctx, config, policy, cwd, argv, signal, allowedExitCodes = [0], env = {}) {
|
|
346
|
+
const env_1 = {
|
|
347
|
+
stack: [],
|
|
348
|
+
error: void 0,
|
|
349
|
+
hasError: false
|
|
350
|
+
};
|
|
351
|
+
try {
|
|
352
|
+
const timeout = __addDisposableResource(env_1, deadline(signal, config.timeoutMs, "WORKTREE_TIMEOUT"), false);
|
|
353
|
+
const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes });
|
|
354
|
+
try {
|
|
355
|
+
const outcome = await child.done;
|
|
356
|
+
timeout.signal.throwIfAborted();
|
|
357
|
+
const captured = child.collected;
|
|
358
|
+
const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes);
|
|
359
|
+
const stdout = captured.stdout.readFrom(0);
|
|
360
|
+
if (stdout.lossy) throw new Error("worktree command output exceeds maxOutputBytes");
|
|
361
|
+
return {
|
|
362
|
+
stdout: stdout.text,
|
|
363
|
+
exitCode
|
|
364
|
+
};
|
|
365
|
+
} finally {
|
|
366
|
+
child.terminate();
|
|
367
|
+
await child.waitForExit();
|
|
368
|
+
}
|
|
369
|
+
} catch (e_1) {
|
|
370
|
+
env_1.error = e_1;
|
|
371
|
+
env_1.hasError = true;
|
|
372
|
+
} finally {
|
|
373
|
+
__disposeResources(env_1);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Run an argv as {@link runCommand} does, but pass each NUL-terminated stdout
|
|
378
|
+
* field to `onField` as it arrives instead of retaining the output, so the size
|
|
379
|
+
* of stdout is unbounded and `maxOutputBytes` limits only stderr. An
|
|
380
|
+
* unterminated remainder is ignored. A false return from `onField` terminates
|
|
381
|
+
* the command, whose outcome is then not checked, even when the provider
|
|
382
|
+
* rejects it for a launch cancelled before acknowledgement; otherwise only
|
|
383
|
+
* status 0 succeeds.
|
|
384
|
+
* @param ctx - subprocess and sandbox providers in the same execution world.
|
|
385
|
+
* @param config - complete process resource limits.
|
|
386
|
+
* @param policy - unchanged calling Session policy.
|
|
387
|
+
* @param cwd - canonical process working directory.
|
|
388
|
+
* @param argv - executable followed by literal arguments.
|
|
389
|
+
* @param signal - operation cancellation.
|
|
390
|
+
* @param onField - synchronous consumer of each field in order; false ends the command.
|
|
391
|
+
* @returns true when `onField` ended the command, false when it exited successfully first.
|
|
392
|
+
*/
|
|
393
|
+
async function scanCommand(ctx, config, policy, cwd, argv, signal, onField) {
|
|
394
|
+
const env_2 = {
|
|
395
|
+
stack: [],
|
|
396
|
+
error: void 0,
|
|
397
|
+
hasError: false
|
|
398
|
+
};
|
|
399
|
+
try {
|
|
400
|
+
const timeout = __addDisposableResource(env_2, deadline(signal, config.timeoutMs, "WORKTREE_TIMEOUT"), false);
|
|
401
|
+
const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, "pipe");
|
|
402
|
+
try {
|
|
403
|
+
const stdout = child.stdout;
|
|
404
|
+
stdout.setEncoding("utf8");
|
|
405
|
+
let pending = "";
|
|
406
|
+
let stopped = false;
|
|
407
|
+
for await (const chunk of stdout) {
|
|
408
|
+
const fields = (pending + chunk).split("\0");
|
|
409
|
+
pending = fields.splice(-1).join("");
|
|
410
|
+
if (!fields.every((field) => onField(field))) {
|
|
411
|
+
stopped = true;
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (stopped) {
|
|
416
|
+
child.terminate();
|
|
417
|
+
await Promise.allSettled([child.done]);
|
|
418
|
+
timeout.signal.throwIfAborted();
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
const outcome = await child.done;
|
|
422
|
+
timeout.signal.throwIfAborted();
|
|
423
|
+
allowedExitCode(outcome, child.collected.stderr, [0]);
|
|
424
|
+
return false;
|
|
425
|
+
} finally {
|
|
426
|
+
child.terminate();
|
|
427
|
+
await Promise.allSettled([child.done]);
|
|
428
|
+
await child.waitForExit();
|
|
429
|
+
}
|
|
430
|
+
} catch (e_2) {
|
|
431
|
+
env_2.error = e_2;
|
|
432
|
+
env_2.hasError = true;
|
|
433
|
+
} finally {
|
|
434
|
+
__disposeResources(env_2);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/** Resolve, confine, and start one command whose stderr is collected within `maxOutputBytes`. */
|
|
438
|
+
async function spawnCommand(ctx, config, policy, cwd, argv, signal, env, stdout) {
|
|
439
|
+
signal.throwIfAborted();
|
|
440
|
+
const command = [await ctx.subprocess.resolveExecutable(argv[0], void 0, signal), ...argv.slice(1)];
|
|
441
|
+
const wrapped = policy.mode === "danger-full-access" ? command : (await ctx.sandbox.confine(command, {
|
|
442
|
+
...policy,
|
|
443
|
+
mode: policy.mode
|
|
444
|
+
}, signal)).argv;
|
|
445
|
+
signal.throwIfAborted();
|
|
446
|
+
return ctx.subprocess.spawn({
|
|
447
|
+
argv: wrapped,
|
|
448
|
+
cwd,
|
|
449
|
+
env: {
|
|
450
|
+
...GIT_ENV,
|
|
451
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
452
|
+
GIT_LFS_SKIP_SMUDGE: "1",
|
|
453
|
+
GIT_NO_LAZY_FETCH: "1",
|
|
454
|
+
...env
|
|
455
|
+
},
|
|
456
|
+
signal,
|
|
457
|
+
graceMs: config.graceMs,
|
|
458
|
+
stdio: {
|
|
459
|
+
stdin: "ignore",
|
|
460
|
+
stdout,
|
|
461
|
+
stderr: { maxBytes: config.maxOutputBytes }
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* The exit code of a command that exited with an allowed status.
|
|
467
|
+
* @throws when the command was signalled or exited with another status, quoting its stderr.
|
|
468
|
+
*/
|
|
469
|
+
function allowedExitCode(outcome, stderr, allowedExitCodes) {
|
|
470
|
+
if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) throw new Error(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`);
|
|
471
|
+
return outcome.exitCode;
|
|
472
|
+
}
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region lib/types/projection.js
|
|
475
|
+
/** The `worktree` projection: every checkout this service recorded creating for a Session, and which of them the Session created itself. */
|
|
476
|
+
/** Plugin record type of a checkout this service created for the Session, written after the Session entered it. */
|
|
477
|
+
const CREATED_RECORD = "plugin:worktree/created";
|
|
478
|
+
/** Validates a `plugin:worktree/created` payload; a reader of the record applies it before trusting the data. */
|
|
479
|
+
const createdWorktreeSchema = z$1.object({
|
|
480
|
+
path: z$1.string().min(1),
|
|
481
|
+
branch: z$1.string().min(1),
|
|
482
|
+
baseCommit: z$1.string().min(1),
|
|
483
|
+
repositoryRoot: z$1.string().min(1)
|
|
484
|
+
}).strict();
|
|
485
|
+
const creationSchema = z$1.object({
|
|
486
|
+
worktree: createdWorktreeSchema,
|
|
487
|
+
owned: z$1.boolean()
|
|
488
|
+
}).strict();
|
|
489
|
+
/**
|
|
490
|
+
* Fold `plugin:worktree/created` records; a record whose payload fails
|
|
491
|
+
* validation is skipped, as a restored record carries whatever an earlier
|
|
492
|
+
* build wrote. A creation whose seq lies inside the fork-inherited prefix is a
|
|
493
|
+
* reference the fork carries, not a checkout it created, so `owned` is false
|
|
494
|
+
* there and true for the Session's own records.
|
|
495
|
+
*/
|
|
496
|
+
const worktreeProjection = {
|
|
497
|
+
key: "worktree",
|
|
498
|
+
stateVersion: 1,
|
|
499
|
+
stateSchema: z$1.object({
|
|
500
|
+
created: z$1.array(creationSchema),
|
|
501
|
+
inheritedEventCount: z$1.number().int().nonnegative()
|
|
502
|
+
}).strict(),
|
|
503
|
+
init: (_header, inheritedEventCount) => ({
|
|
504
|
+
created: [],
|
|
505
|
+
inheritedEventCount
|
|
506
|
+
}),
|
|
507
|
+
apply: (state, event) => {
|
|
508
|
+
const record = pluginRecordOf(event);
|
|
509
|
+
if (record?.type !== "plugin:worktree/created") return state;
|
|
510
|
+
const parsed = createdWorktreeSchema.safeParse(record.data);
|
|
511
|
+
if (!parsed.success) return state;
|
|
512
|
+
return {
|
|
513
|
+
...state,
|
|
514
|
+
created: [...state.created, {
|
|
515
|
+
worktree: parsed.data,
|
|
516
|
+
owned: record.seq >= state.inheritedEventCount
|
|
517
|
+
}]
|
|
518
|
+
};
|
|
519
|
+
},
|
|
520
|
+
wire: {
|
|
521
|
+
viewSchema: z$1.array(creationSchema),
|
|
522
|
+
view: (state) => state.created
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
//#endregion
|
|
526
|
+
//#region lib/types/removal.js
|
|
527
|
+
/**
|
|
528
|
+
* Confirm that a recorded checkout names a canonical directory inside the
|
|
529
|
+
* configured pool of the source checkout it claims, and that the source is
|
|
530
|
+
* still that repository's top level.
|
|
531
|
+
* @param ctx - execution-world filesystem provider.
|
|
532
|
+
* @param directory - configured relative worktree pool.
|
|
533
|
+
* @param request - saved checkout identity.
|
|
534
|
+
* @param run - bounded Git runner with the owner's policy.
|
|
535
|
+
* @param signal - cancellation of the lookups.
|
|
536
|
+
* @returns the resolved root and target, or null when any identity check fails.
|
|
537
|
+
*/
|
|
538
|
+
async function checkoutIdentity(ctx, directory, request, run, signal) {
|
|
539
|
+
const { path, repositoryRoot } = request;
|
|
540
|
+
const root = await ctx.fs.resolve(repositoryRoot, { signal });
|
|
541
|
+
const pool = await ctx.fs.resolve(directory, {
|
|
542
|
+
cwd: repositoryRoot,
|
|
543
|
+
signal
|
|
544
|
+
});
|
|
545
|
+
const target = await ctx.fs.resolve(path, {
|
|
546
|
+
cwd: repositoryRoot,
|
|
547
|
+
signal
|
|
548
|
+
});
|
|
549
|
+
if (ctx.fs.processPath(root) !== repositoryRoot || ctx.fs.processPath(target) !== path || !ctx.fs.contains(root, pool) || !ctx.fs.contains(pool, target) || pool.targetKey === target.targetKey) return null;
|
|
550
|
+
const top = await run(repositoryRoot, ["rev-parse", "--show-toplevel"]);
|
|
551
|
+
if ((await ctx.fs.resolve(top.stdout.replace(/\r?\n$/, ""), {
|
|
552
|
+
cwd: repositoryRoot,
|
|
553
|
+
signal
|
|
554
|
+
})).targetKey !== root.targetKey) return null;
|
|
555
|
+
return {
|
|
556
|
+
root,
|
|
557
|
+
target
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Find the registration of `target` among the source repository's worktrees.
|
|
562
|
+
* The listing grows with the number of worktrees; it is streamed without an
|
|
563
|
+
* output limit, and its entries are kept in memory while `target` is resolved.
|
|
564
|
+
* @param ctx - execution-world filesystem provider.
|
|
565
|
+
* @param request - saved checkout identity.
|
|
566
|
+
* @param target - resolved checkout directory.
|
|
567
|
+
* @param scan - streaming Git runner with the owner's policy.
|
|
568
|
+
* @param signal - cancellation of the lookups.
|
|
569
|
+
* @returns the porcelain fields of the matching entry, or undefined when none is registered.
|
|
570
|
+
*/
|
|
571
|
+
async function registration(ctx, request, target, scan, signal) {
|
|
572
|
+
const entries = [];
|
|
573
|
+
let fields = [];
|
|
574
|
+
await scan(request.repositoryRoot, [
|
|
575
|
+
"worktree",
|
|
576
|
+
"list",
|
|
577
|
+
"--porcelain",
|
|
578
|
+
"-z"
|
|
579
|
+
], (field) => {
|
|
580
|
+
if (field.startsWith("worktree ")) {
|
|
581
|
+
fields = [field];
|
|
582
|
+
entries.push({
|
|
583
|
+
path: field.slice(9),
|
|
584
|
+
fields
|
|
585
|
+
});
|
|
586
|
+
} else if (field.length > 0) fields.push(field);
|
|
587
|
+
return true;
|
|
588
|
+
});
|
|
589
|
+
for (const entry of entries) if ((await ctx.fs.resolve(entry.path, {
|
|
590
|
+
cwd: request.repositoryRoot,
|
|
591
|
+
signal
|
|
592
|
+
})).targetKey === target.targetKey) return entry.fields;
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Inspect the checkout and, when eligible and still admitted after inspection,
|
|
596
|
+
* remove it and its registration with a non-force `git worktree remove`. The
|
|
597
|
+
* branch is never deleted; a rejection can leave a partial directory.
|
|
598
|
+
* @param ctx - execution-world filesystem provider.
|
|
599
|
+
* @param directory - configured relative worktree pool.
|
|
600
|
+
* @param request - saved checkout identity.
|
|
601
|
+
* @param git - confined Git runners with the owner's policy.
|
|
602
|
+
* @param signal - cancellation before or during removal.
|
|
603
|
+
* @param admit - synchronous final admission after inspection; false retains the checkout.
|
|
604
|
+
* @returns true when removed; false when inspection or admission retains it; Git failures reject.
|
|
605
|
+
*/
|
|
606
|
+
async function removeCheckout(ctx, directory, request, git, signal, admit) {
|
|
607
|
+
if (!await inspectRemoval(ctx, directory, request, git, signal)) return false;
|
|
608
|
+
signal.throwIfAborted();
|
|
609
|
+
if (!admit()) return false;
|
|
610
|
+
await git.read(request.repositoryRoot, [
|
|
611
|
+
"worktree",
|
|
612
|
+
"remove",
|
|
613
|
+
"--",
|
|
614
|
+
request.path
|
|
615
|
+
]);
|
|
616
|
+
return true;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Verify checkout identity and that `git status` reports no tracked changes or
|
|
620
|
+
* untracked files; its output is read only up to the first entry. Ignored files
|
|
621
|
+
* are not counted, nor are edits to skip-worktree or assume-unchanged files,
|
|
622
|
+
* which `git status` hides; `git worktree remove` discards both. A checkout
|
|
623
|
+
* whose administrative directory holds submodule repositories is ineligible,
|
|
624
|
+
* as Git refuses to remove it; a committed embedded repository is not
|
|
625
|
+
* inspected, so Git's refusal of that removal rejects.
|
|
626
|
+
* @param ctx - execution-world filesystem provider.
|
|
627
|
+
* @param directory - configured relative worktree pool.
|
|
628
|
+
* @param request - saved checkout identity.
|
|
629
|
+
* @param git - confined Git runners with the owner's policy.
|
|
630
|
+
* @param signal - cancellation of inspection.
|
|
631
|
+
* @returns false for an ineligible checkout; inspection failures reject.
|
|
632
|
+
*/
|
|
633
|
+
async function inspectRemoval(ctx, directory, request, git, signal) {
|
|
634
|
+
const { path, branch } = request;
|
|
635
|
+
const identity = await checkoutIdentity(ctx, directory, request, git.read, signal);
|
|
636
|
+
if (identity === null) return false;
|
|
637
|
+
if ((await ctx.fs.lstat(path, void 0, signal))?.type !== "directory") return false;
|
|
638
|
+
const fields = await registration(ctx, request, identity.target, git.scan, signal);
|
|
639
|
+
if (fields === void 0 || !fields.includes(`branch refs/heads/${branch}`) || fields.some((field) => field === "detached" || field.startsWith("locked") || field.startsWith("prunable"))) return false;
|
|
640
|
+
if ((await git.read(path, ["symbolic-ref", "HEAD"])).stdout.trim() !== `refs/heads/${branch}`) return false;
|
|
641
|
+
if (await git.scan(path, [
|
|
642
|
+
"status",
|
|
643
|
+
"--porcelain=v1",
|
|
644
|
+
"-z",
|
|
645
|
+
"--untracked-files=all",
|
|
646
|
+
"--ignore-submodules=none"
|
|
647
|
+
], () => false)) return false;
|
|
648
|
+
const modules = await git.read(path, [
|
|
649
|
+
"rev-parse",
|
|
650
|
+
"--git-path",
|
|
651
|
+
"modules"
|
|
652
|
+
]);
|
|
653
|
+
return await ctx.fs.lstat(modules.stdout.replace(/\r?\n$/, ""), { cwd: path }, signal) === void 0;
|
|
654
|
+
}
|
|
655
|
+
//#endregion
|
|
656
|
+
//#region lib/types/index.js
|
|
657
|
+
/** Creates a new Git branch and checkout, then changes the calling Session's working directory; restores a removed checkout. */
|
|
658
|
+
/** Reject path traversal independently of Git's branch-name grammar. */
|
|
659
|
+
function relativePath(value) {
|
|
660
|
+
return value.length > 0 && !value.includes("\\") && !value.includes(":") && value.split("/").every((part) => part.length > 0 && part !== "." && part !== "..");
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Creates retained Git worktrees under the mounted filesystem and sandbox
|
|
664
|
+
* providers, records each creation in the Session log, and reclaims a clean,
|
|
665
|
+
* unreferenced checkout when the Session that created it is archived.
|
|
666
|
+
*/
|
|
667
|
+
var WorktreeService = class extends Service {
|
|
668
|
+
static inject = [
|
|
669
|
+
"workingDirectory",
|
|
670
|
+
"fs",
|
|
671
|
+
"subprocess",
|
|
672
|
+
"sandbox",
|
|
673
|
+
"sandboxPolicy",
|
|
674
|
+
"sessionProjections"
|
|
675
|
+
];
|
|
676
|
+
static Config = z.object({
|
|
677
|
+
retainOnArchive: z.boolean().default(false).volatile(),
|
|
678
|
+
directory: z.string().default(".agents/worktrees"),
|
|
679
|
+
namePrefix: z.string().default("rabi-"),
|
|
680
|
+
gitCommand: z.string().default("git"),
|
|
681
|
+
nodeCommand: z.string().default("node"),
|
|
682
|
+
timeoutMs: z.number().default(3e5),
|
|
683
|
+
graceMs: z.number().default(3e3),
|
|
684
|
+
maxOutputBytes: z.number().default(65536)
|
|
685
|
+
});
|
|
686
|
+
config;
|
|
687
|
+
lifetime = new AbortController();
|
|
688
|
+
pending = /* @__PURE__ */ new Set();
|
|
689
|
+
checkouts = /* @__PURE__ */ new Map();
|
|
690
|
+
projection;
|
|
691
|
+
reclamation;
|
|
692
|
+
constructor(ctx, config) {
|
|
693
|
+
super(ctx, "worktrees");
|
|
694
|
+
this.config = config;
|
|
695
|
+
if (!relativePath(this.config.directory)) throw new Error("worktree: directory must be a relative directory without dot segments");
|
|
696
|
+
if (!relativePath(`${this.config.namePrefix}name`) || this.config.namePrefix.startsWith("-")) throw new Error("worktree: namePrefix must produce a relative branch name");
|
|
697
|
+
for (const key of ["gitCommand", "nodeCommand"]) if (this.config[key].trim().length === 0) throw new Error(`worktree: ${key} must not be empty`);
|
|
698
|
+
for (const key of [
|
|
699
|
+
"timeoutMs",
|
|
700
|
+
"graceMs",
|
|
701
|
+
"maxOutputBytes"
|
|
702
|
+
]) {
|
|
703
|
+
const value = this.config[key];
|
|
704
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) throw new Error(`worktree: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`);
|
|
705
|
+
}
|
|
706
|
+
ctx.effect(() => async () => {
|
|
707
|
+
this.lifetime.abort(/* @__PURE__ */ new Error("worktree service disposed"));
|
|
708
|
+
await Promise.allSettled(this.pending);
|
|
709
|
+
});
|
|
710
|
+
ctx.inject(["settings"], (child) => {
|
|
711
|
+
child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
async [Service.init]() {
|
|
715
|
+
this.projection = await this.ctx.sessionProjections.register(worktreeProjection);
|
|
716
|
+
this.ctx.inject([
|
|
717
|
+
"workspaceRegistry",
|
|
718
|
+
"sessionQuery",
|
|
719
|
+
"sessions",
|
|
720
|
+
"workingDirectory",
|
|
721
|
+
"sandboxPolicy"
|
|
722
|
+
], (scope) => {
|
|
723
|
+
const reclamation = new WorktreeReclamation(scope, {
|
|
724
|
+
retainOnArchive: () => this.config.retainOnArchive.get(),
|
|
725
|
+
exclusiveCheckout: (path, body) => this.exclusiveCheckout(path, body),
|
|
726
|
+
removeCheckout: (session, request, signal, admit) => this.removeCheckout(session, request, signal, admit)
|
|
727
|
+
}, this.projection);
|
|
728
|
+
this.reclamation = reclamation;
|
|
729
|
+
scope.effect(() => () => {
|
|
730
|
+
this.reclamation = void 0;
|
|
731
|
+
});
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Create a fresh branch and checkout at a pinned local revision, then enter it.
|
|
736
|
+
* Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
|
|
737
|
+
* Checkout disables configured clean, smudge, and process filters without changing Git config.
|
|
738
|
+
* Repository-local replacement refs still apply; baseCommit reports the resolved object name.
|
|
739
|
+
* The new checkout becomes current only after Git setup succeeds. Failures may retain newly
|
|
740
|
+
* allocated Git/filesystem artifacts; no branch or checkout is removed automatically.
|
|
741
|
+
* @param agent - caller whose current directory selects the source repository and file policy.
|
|
742
|
+
* @param request - optional new name and local revision; defaults are generated name and HEAD.
|
|
743
|
+
* @param signal - cancellation of lookup, creation, and working-directory publication.
|
|
744
|
+
* @param onPhase - receives each stage before it begins; it must not throw.
|
|
745
|
+
* @returns canonical checkout path, branch name, pinned commit, and source repository root.
|
|
746
|
+
*/
|
|
747
|
+
async create(agent, request = {}, signal, onPhase) {
|
|
748
|
+
const operationSignal = signal === void 0 ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]);
|
|
749
|
+
operationSignal.throwIfAborted();
|
|
750
|
+
const operation = this.createCheckout(agent, this.resolve(agent, request), operationSignal, onPhase);
|
|
751
|
+
this.pending.add(operation);
|
|
752
|
+
try {
|
|
753
|
+
return await operation;
|
|
754
|
+
} finally {
|
|
755
|
+
this.pending.delete(operation);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Check out a removed worktree again at its recorded directory: its branch
|
|
760
|
+
* when the branch still exists, otherwise a new branch of the same name at
|
|
761
|
+
* `baseCommit`. Only the missing target's unlocked registration is removed, and an
|
|
762
|
+
* existing directory fails. Changes that were never committed are not
|
|
763
|
+
* recovered. Checkout disables configured clean, smudge, and process filters,
|
|
764
|
+
* as creation does. The calling Session's working directory does not change.
|
|
765
|
+
* Failures may retain newly allocated Git/filesystem artifacts.
|
|
766
|
+
* @param agent - caller whose sandbox policy confines the commands.
|
|
767
|
+
* @param request - recorded directory, branch, base commit, and source repository root.
|
|
768
|
+
* @param signal - cancellation of the restoration.
|
|
769
|
+
* @param onPhase - receives each stage before it begins; it must not throw.
|
|
770
|
+
* @returns the directory and whether the branch was created again.
|
|
771
|
+
*/
|
|
772
|
+
async restore(agent, request, signal, onPhase) {
|
|
773
|
+
const operationSignal = signal === void 0 ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]);
|
|
774
|
+
operationSignal.throwIfAborted();
|
|
775
|
+
const operation = this.exclusiveCheckout(request.path, () => this.restoreCheckout(agent, request, operationSignal, onPhase));
|
|
776
|
+
this.pending.add(operation);
|
|
777
|
+
try {
|
|
778
|
+
return await operation;
|
|
779
|
+
} finally {
|
|
780
|
+
this.pending.delete(operation);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Read the archive cleanup of a Session's created checkout; waiting never
|
|
785
|
+
* starts one. Absent without the Workspace and query providers.
|
|
786
|
+
* @param session - archived Session whose cleanup is read.
|
|
787
|
+
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
|
788
|
+
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
|
789
|
+
*/
|
|
790
|
+
async cleanupOf(session, revision) {
|
|
791
|
+
return await this.reclamation?.cleanupOf(session, revision) ?? null;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Inspect a recorded checkout under the Session's policy and, when eligible
|
|
795
|
+
* and admitted, remove it and its registration without force or branch
|
|
796
|
+
* deletion. A rejection can leave a partial directory; the branch stays.
|
|
797
|
+
*/
|
|
798
|
+
async removeCheckout(session, request, signal, admit) {
|
|
799
|
+
const control = AbortSignal.any([this.lifetime.signal, signal]);
|
|
800
|
+
control.throwIfAborted();
|
|
801
|
+
const policy = this.ctx.sandboxPolicy.resolve({ session });
|
|
802
|
+
const git = {
|
|
803
|
+
read: this.gitRunner(policy, control),
|
|
804
|
+
scan: this.gitScanner(policy, control)
|
|
805
|
+
};
|
|
806
|
+
const operation = removeCheckout(this.ctx, this.config.directory, request, git, control, admit);
|
|
807
|
+
this.pending.add(operation);
|
|
808
|
+
try {
|
|
809
|
+
return await operation;
|
|
810
|
+
} finally {
|
|
811
|
+
this.pending.delete(operation);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
exclusiveCheckout(path, body) {
|
|
815
|
+
const operation = (this.checkouts.get(path) ?? Promise.resolve()).then(body);
|
|
816
|
+
const tail = operation.then(() => {}, () => {});
|
|
817
|
+
this.checkouts.set(path, tail);
|
|
818
|
+
tail.then(() => {
|
|
819
|
+
if (this.checkouts.get(path) === tail) this.checkouts.delete(path);
|
|
820
|
+
});
|
|
821
|
+
return operation;
|
|
822
|
+
}
|
|
823
|
+
resolve(agent, request) {
|
|
824
|
+
const branch = request.name ?? generatedWorktreeName(this.config.namePrefix, agent.session.id);
|
|
825
|
+
if (!relativePath(branch) || branch.startsWith("-")) throw new Error("worktree name must be a relative Git branch name");
|
|
826
|
+
const revision = request.from ?? "HEAD";
|
|
827
|
+
if (revision.length === 0) throw new Error("worktree from must name a local commit, branch, or tag");
|
|
828
|
+
return {
|
|
829
|
+
branch,
|
|
830
|
+
revision
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
async createCheckout(agent, { branch, revision }, signal, onPhase) {
|
|
834
|
+
onPhase?.("prepare");
|
|
835
|
+
const cwd = await this.ctx.workingDirectory.ensure(agent, signal);
|
|
836
|
+
const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session });
|
|
837
|
+
const run = this.gitRunner(policy, signal);
|
|
838
|
+
await run(cwd, ["check-ref-format", `refs/heads/${branch}`]);
|
|
839
|
+
const rootOutput = await run(cwd, ["rev-parse", "--show-toplevel"]);
|
|
840
|
+
const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ""), {
|
|
841
|
+
cwd,
|
|
842
|
+
signal
|
|
843
|
+
});
|
|
844
|
+
const repositoryRoot = this.ctx.fs.processPath(rootTarget);
|
|
845
|
+
const baseCommit = (await run(repositoryRoot, [
|
|
846
|
+
"rev-parse",
|
|
847
|
+
"--verify",
|
|
848
|
+
"--end-of-options",
|
|
849
|
+
`${revision}^{commit}`
|
|
850
|
+
])).stdout.trim();
|
|
851
|
+
if ((await run(repositoryRoot, [
|
|
852
|
+
"show-ref",
|
|
853
|
+
"--verify",
|
|
854
|
+
"--quiet",
|
|
855
|
+
`refs/heads/${branch}`
|
|
856
|
+
], [0, 1])).exitCode === 0) throw new Error(`worktree branch already exists: ${branch}`);
|
|
857
|
+
const pool = await this.ctx.fs.resolve(this.config.directory, {
|
|
858
|
+
cwd: repositoryRoot,
|
|
859
|
+
signal
|
|
860
|
+
});
|
|
861
|
+
const poolPath = this.ctx.fs.processPath(pool);
|
|
862
|
+
const destination = await this.ctx.fs.resolve(branch, {
|
|
863
|
+
cwd: poolPath,
|
|
864
|
+
signal
|
|
865
|
+
});
|
|
866
|
+
const path = this.ctx.fs.processPath(destination);
|
|
867
|
+
if (await this.ctx.fs.lstat(path, void 0, signal) !== void 0) throw new Error(`worktree path already exists: ${path}`);
|
|
868
|
+
try {
|
|
869
|
+
await this.prepareDirectory(policy, repositoryRoot, poolPath, path, signal);
|
|
870
|
+
await run(repositoryRoot, [
|
|
871
|
+
"--work-tree",
|
|
872
|
+
repositoryRoot,
|
|
873
|
+
"worktree",
|
|
874
|
+
"add",
|
|
875
|
+
"--no-checkout",
|
|
876
|
+
"-b",
|
|
877
|
+
branch,
|
|
878
|
+
"--",
|
|
879
|
+
path,
|
|
880
|
+
baseCommit
|
|
881
|
+
]);
|
|
882
|
+
const overrides = await filterOverrides(run, path);
|
|
883
|
+
onPhase?.("checkout");
|
|
884
|
+
await run(path, [
|
|
885
|
+
"--work-tree",
|
|
886
|
+
path,
|
|
887
|
+
"reset",
|
|
888
|
+
"--hard",
|
|
889
|
+
"--no-recurse-submodules",
|
|
890
|
+
baseCommit
|
|
891
|
+
], void 0, overrides);
|
|
892
|
+
const created = {
|
|
893
|
+
path: await this.ctx.workingDirectory.set(agent, path, signal),
|
|
894
|
+
branch,
|
|
895
|
+
baseCommit,
|
|
896
|
+
repositoryRoot
|
|
897
|
+
};
|
|
898
|
+
appendPluginRecord(agent.session, CREATED_RECORD, created);
|
|
899
|
+
return created;
|
|
900
|
+
} catch (error) {
|
|
901
|
+
throw new Error(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
async restoreCheckout(agent, { path, branch, baseCommit, repositoryRoot }, signal, onPhase) {
|
|
905
|
+
onPhase?.("prepare");
|
|
906
|
+
const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session });
|
|
907
|
+
const run = this.gitRunner(policy, signal);
|
|
908
|
+
if (await this.ctx.fs.lstat(path, void 0, signal) !== void 0) throw new Error(`worktree path already exists: ${path}`);
|
|
909
|
+
if (!relativePath(branch) || branch.startsWith("-")) throw new Error("worktree branch must be a relative Git branch name");
|
|
910
|
+
if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new Error("worktree baseCommit must be a full commit object name");
|
|
911
|
+
const identity = await checkoutIdentity(this.ctx, this.config.directory, {
|
|
912
|
+
path,
|
|
913
|
+
branch,
|
|
914
|
+
baseCommit,
|
|
915
|
+
repositoryRoot
|
|
916
|
+
}, run, signal);
|
|
917
|
+
if (identity === null) throw new Error("worktree restoration must use a canonical directory inside the configured pool of the source checkout root");
|
|
918
|
+
await run(repositoryRoot, ["check-ref-format", `refs/heads/${branch}`]);
|
|
919
|
+
await run(repositoryRoot, [
|
|
920
|
+
"rev-parse",
|
|
921
|
+
"--verify",
|
|
922
|
+
"--end-of-options",
|
|
923
|
+
`${baseCommit}^{commit}`
|
|
924
|
+
]);
|
|
925
|
+
const scan = this.gitScanner(policy, signal);
|
|
926
|
+
const fields = await registration(this.ctx, {
|
|
927
|
+
path,
|
|
928
|
+
branch,
|
|
929
|
+
baseCommit,
|
|
930
|
+
repositoryRoot
|
|
931
|
+
}, identity.target, scan, signal);
|
|
932
|
+
if (fields !== void 0) {
|
|
933
|
+
if (fields.some((field) => field === "locked" || field.startsWith("locked "))) throw new Error(`worktree is locked: ${path}`);
|
|
934
|
+
if (await this.ctx.fs.lstat(path, void 0, signal) !== void 0) throw new Error(`worktree path already exists: ${path}`);
|
|
935
|
+
await run(repositoryRoot, [
|
|
936
|
+
"worktree",
|
|
937
|
+
"remove",
|
|
938
|
+
"--",
|
|
939
|
+
path
|
|
940
|
+
]);
|
|
941
|
+
}
|
|
942
|
+
const branchRecreated = (await run(repositoryRoot, [
|
|
943
|
+
"show-ref",
|
|
944
|
+
"--verify",
|
|
945
|
+
"--quiet",
|
|
946
|
+
`refs/heads/${branch}`
|
|
947
|
+
], [0, 1])).exitCode !== 0;
|
|
948
|
+
try {
|
|
949
|
+
const pool = await this.ctx.fs.resolve(this.config.directory, {
|
|
950
|
+
cwd: repositoryRoot,
|
|
951
|
+
signal
|
|
952
|
+
});
|
|
953
|
+
await this.prepareDirectory(policy, repositoryRoot, this.ctx.fs.processPath(pool), path, signal);
|
|
954
|
+
await run(repositoryRoot, [
|
|
955
|
+
"--work-tree",
|
|
956
|
+
repositoryRoot,
|
|
957
|
+
"worktree",
|
|
958
|
+
"add",
|
|
959
|
+
"--no-checkout",
|
|
960
|
+
...branchRecreated ? [
|
|
961
|
+
"-b",
|
|
962
|
+
branch,
|
|
963
|
+
"--",
|
|
964
|
+
path,
|
|
965
|
+
baseCommit
|
|
966
|
+
] : [
|
|
967
|
+
"--",
|
|
968
|
+
path,
|
|
969
|
+
branch
|
|
970
|
+
]
|
|
971
|
+
]);
|
|
972
|
+
const overrides = await filterOverrides(run, path);
|
|
973
|
+
onPhase?.("checkout");
|
|
974
|
+
await run(path, [
|
|
975
|
+
"--work-tree",
|
|
976
|
+
path,
|
|
977
|
+
"reset",
|
|
978
|
+
"--hard",
|
|
979
|
+
"--no-recurse-submodules",
|
|
980
|
+
"HEAD"
|
|
981
|
+
], void 0, overrides);
|
|
982
|
+
return {
|
|
983
|
+
path,
|
|
984
|
+
branchRecreated
|
|
985
|
+
};
|
|
986
|
+
} catch (error) {
|
|
987
|
+
throw new Error(`Could not restore worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/** Confine Git commands to the caller's sandbox policy, collecting bounded stdout. */
|
|
991
|
+
gitRunner(policy, signal) {
|
|
992
|
+
return (directory, args, allowedExitCodes, env) => runCommand(this.ctx, this.config, policy, directory, this.gitArgv(args), signal, allowedExitCodes, env);
|
|
993
|
+
}
|
|
994
|
+
/** Confine Git commands to the caller's sandbox policy, streaming stdout instead of collecting it. */
|
|
995
|
+
gitScanner(policy, signal) {
|
|
996
|
+
return (directory, args, onField) => scanCommand(this.ctx, this.config, policy, directory, this.gitArgv(args), signal, onField);
|
|
997
|
+
}
|
|
998
|
+
/** The configured Git executable with hooks and the filesystem monitor disabled, followed by `args`. */
|
|
999
|
+
gitArgv(args) {
|
|
1000
|
+
return [
|
|
1001
|
+
this.config.gitCommand,
|
|
1002
|
+
"-c",
|
|
1003
|
+
"core.hooksPath=/dev/null",
|
|
1004
|
+
"-c",
|
|
1005
|
+
"core.fsmonitor=false",
|
|
1006
|
+
...args
|
|
1007
|
+
];
|
|
1008
|
+
}
|
|
1009
|
+
/** Allocate the checkout directory exclusively inside the pool, creating a self-ignoring pool when it is new. */
|
|
1010
|
+
async prepareDirectory(policy, repositoryRoot, poolPath, path, signal) {
|
|
1011
|
+
await runCommand(this.ctx, this.config, policy, repositoryRoot, [
|
|
1012
|
+
this.config.nodeCommand,
|
|
1013
|
+
"--input-type=module",
|
|
1014
|
+
"-e",
|
|
1015
|
+
PREPARE_DIRECTORY,
|
|
1016
|
+
poolPath,
|
|
1017
|
+
path
|
|
1018
|
+
], signal);
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
/**
|
|
1022
|
+
* Build the environment that disables every configured clean, smudge, and
|
|
1023
|
+
* process filter of the checkout for one command, without changing Git config.
|
|
1024
|
+
* @param run - confined Git runner.
|
|
1025
|
+
* @param path - checkout directory.
|
|
1026
|
+
* @returns `GIT_CONFIG_*` overrides.
|
|
1027
|
+
*/
|
|
1028
|
+
async function filterOverrides(run, path) {
|
|
1029
|
+
const configured = await run(path, [
|
|
1030
|
+
"config",
|
|
1031
|
+
"--null",
|
|
1032
|
+
"--name-only",
|
|
1033
|
+
"--get-regexp",
|
|
1034
|
+
"^filter\\."
|
|
1035
|
+
], [0, 1]);
|
|
1036
|
+
const drivers = /* @__PURE__ */ new Set();
|
|
1037
|
+
for (const key of configured.stdout.split("\0")) {
|
|
1038
|
+
const separator = key.lastIndexOf(".");
|
|
1039
|
+
if (separator > 7 && [
|
|
1040
|
+
"clean",
|
|
1041
|
+
"smudge",
|
|
1042
|
+
"process",
|
|
1043
|
+
"required"
|
|
1044
|
+
].includes(key.slice(separator + 1))) drivers.add(key.slice(7, separator));
|
|
1045
|
+
}
|
|
1046
|
+
const overrides = { GIT_CONFIG_COUNT: String(drivers.size * 4) };
|
|
1047
|
+
let index = 0;
|
|
1048
|
+
for (const driver of drivers) for (const attribute of [
|
|
1049
|
+
"clean",
|
|
1050
|
+
"smudge",
|
|
1051
|
+
"process",
|
|
1052
|
+
"required"
|
|
1053
|
+
]) {
|
|
1054
|
+
overrides[`GIT_CONFIG_KEY_${index}`] = `filter.${driver}.${attribute}`;
|
|
1055
|
+
overrides[`GIT_CONFIG_VALUE_${index}`] = attribute === "required" ? "false" : "";
|
|
1056
|
+
index++;
|
|
1057
|
+
}
|
|
1058
|
+
return overrides;
|
|
1059
|
+
}
|
|
1060
|
+
//#endregion
|
|
1061
|
+
export { CREATED_RECORD, WorktreeService, WorktreeService as default, createdWorktreeSchema, generatedWorktreeName, worktreeProjection };
|