dsh-taskbridge 1.7.1 → 1.8.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 (75) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +21 -21
  3. package/README.md +149 -290
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +3 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +4 -1
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -55
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -1,679 +1,679 @@
1
- // Isolated git worktrees for delegated runs.
2
- //
3
- // A delegated run is allowed to mutate files. When the operator asks for
4
- // worktree isolation, it must mutate a *different* checkout than the one the
5
- // human is looking at. This module owns that checkout:
6
- //
7
- // - it is created by `git worktree add --detach <pinned-commit>`, so the run
8
- // starts from an exact commit and no branch is moved in either repository;
9
- // - it lives under a plugin-owned root directory, never inside the user's
10
- // checkout, and never at a path a caller supplied directly;
11
- // - every mutation is an argv array handed to the same `runGit` seam the rest
12
- // of the plugin uses — no shell, no `checkout`, no `reset`, no merge, no
13
- // rebase anywhere in this file;
14
- // - it is kept after the run so the host can review it, and it is only removed
15
- // when a host says so. A finished tree is evidence, not garbage.
16
- //
17
- // What this is NOT: a security boundary against the agent process. A delegated
18
- // agent runs as the same OS user; worktree isolation keeps the *human's files*
19
- // from being edited, it does not sandbox a hostile program. That is stated here
20
- // rather than implied by the word "isolated".
21
-
22
- import { randomUUID } from 'node:crypto';
23
- import { lstat, mkdir, realpath } from 'node:fs/promises';
24
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
25
-
26
- import { AUDIT_CODES, AUDIT_LIMITS, AuditError, probeRepository, readRepositoryTopLevel, readStatus } from './audit.js';
27
- import { isInside } from './locks.js';
28
-
29
- /** Worktree refusal codes. Each is a refusal, never a silent fallback. */
30
- export const WORKTREE_CODES = Object.freeze({
31
- gitUnavailable: 'WORKTREE_GIT_UNAVAILABLE',
32
- notRepository: 'WORKTREE_NOT_A_REPOSITORY',
33
- noCommits: 'WORKTREE_NO_COMMITS',
34
- sourceDirty: 'WORKTREE_SOURCE_DIRTY',
35
- rootInvalid: 'WORKTREE_ROOT_INVALID',
36
- pathEscape: 'WORKTREE_PATH_ESCAPE',
37
- nestedDestination: 'WORKTREE_NESTED_DESTINATION',
38
- destinationExists: 'WORKTREE_DESTINATION_EXISTS',
39
- cancelled: 'WORKTREE_CANCELLED',
40
- gitFailed: 'WORKTREE_GIT_FAILED',
41
- unknownTree: 'WORKTREE_UNKNOWN_TREE',
42
- notReviewed: 'WORKTREE_NOT_REVIEWED',
43
- taskIdInvalid: 'WORKTREE_TASK_ID_INVALID',
44
- });
45
-
46
- /** Tree states. `awaiting-host-review` is where a tree stays until a host acts. */
47
- export const WORKTREE_STATES = Object.freeze({
48
- active: 'active',
49
- awaitingHostReview: 'awaiting-host-review',
50
- disposed: 'disposed',
51
- });
52
-
53
- /** Raised when a worktree request is refused. */
54
- export class WorktreeError extends Error {
55
- /**
56
- * @param {string} code - stable machine code.
57
- * @param {string} message - human-readable explanation.
58
- * @param {object} [details] - bounded details; never file content.
59
- */
60
- constructor(code, message, details = {}) {
61
- super(message);
62
- this.name = 'WorktreeError';
63
- this.code = code;
64
- this.details = details;
65
- }
66
- }
67
-
68
- /**
69
- * Reduce a task id to a safe single path segment.
70
- *
71
- * The task id is caller-influenced, so it is not trusted as a path component:
72
- * anything outside `[A-Za-z0-9._-]` becomes `-`, leading dots are dropped so no
73
- * generated name can be mistaken for a hidden or parent directory, and the
74
- * segment is length-bounded.
75
- * @param {unknown} taskId - raw task id.
76
- * @returns {string} safe segment, or an empty string when nothing usable remains.
77
- */
78
- export function safeTaskSegment(taskId) {
79
- if (typeof taskId !== 'string') return '';
80
- const cleaned = taskId.trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '').slice(0, 48);
81
- return cleaned === '' ? '' : cleaned;
82
- }
83
-
84
- /**
85
- * Build a refusal from a failed git invocation.
86
- * @param {string} step - which invocation failed.
87
- * @param {object} result - runner result.
88
- * @returns {WorktreeError} refusal to throw.
89
- */
90
- function gitFailure(step, result) {
91
- return new WorktreeError(WORKTREE_CODES.gitFailed, `git ${step} failed`, {
92
- step,
93
- exitCode: typeof result?.code === 'number' ? result.code : null,
94
- stderr: String(result?.stderr ?? '').trim().slice(0, AUDIT_LIMITS.stderrBytes),
95
- });
96
- }
97
-
98
- /**
99
- * Validate the shape a runner returned.
100
- * @param {unknown} result - runner result.
101
- * @param {string} step - invocation name.
102
- * @returns {{stdout: string, stderr: string, code: number}} result.
103
- */
104
- function requireResult(result, step) {
105
- if (result === null || typeof result !== 'object' || typeof result.stdout !== 'string' || typeof result.code !== 'number') {
106
- throw new WorktreeError(WORKTREE_CODES.gitFailed, `the git runner returned no usable result for ${step}`, { step });
107
- }
108
- return { stdout: result.stdout, stderr: typeof result.stderr === 'string' ? result.stderr : '', code: result.code };
109
- }
110
-
111
- /**
112
- * Whether a path exists, without following a final symlink.
113
- * @param {string} target - absolute path.
114
- * @returns {Promise<boolean>} true when something is there.
115
- */
116
- async function pathExists(target) {
117
- try {
118
- await lstat(target);
119
- return true;
120
- } catch (error) {
121
- if (error?.code === 'ENOENT') return false;
122
- throw error;
123
- }
124
- }
125
-
126
- /**
127
- * Owns plugin-created detached worktrees.
128
- *
129
- * One manager per plugin instance. The manager keeps metadata in memory only: a
130
- * restart forgets the registry. A validated continuation may recover its ONE
131
- * recorded tree through Git's live registry; startup never scans, deletes or
132
- * adopts arbitrary directories.
133
- */
134
- export class WorktreeManager {
135
- /**
136
- * @param {object} deps - `runGit` runner (same seam as the audit module).
137
- * @param {object} options - `rootDir` (required), optional `now` and `randomId`.
138
- */
139
- constructor(deps, options = {}) {
140
- if (typeof deps?.runGit !== 'function') {
141
- throw new WorktreeError(WORKTREE_CODES.gitFailed, 'a runGit runner is required', {});
142
- }
143
- if (typeof options.rootDir !== 'string' || options.rootDir.trim() === '' || !isAbsolute(options.rootDir.trim())) {
144
- throw new WorktreeError(WORKTREE_CODES.rootInvalid, 'an absolute rootDir for worktrees is required', {});
145
- }
146
- this.deps = deps;
147
- this.rootDir = resolve(options.rootDir.trim());
148
- this.now = typeof options.now === 'function' ? options.now : () => Date.now();
149
- this.randomId = typeof options.randomId === 'function' ? options.randomId : () => randomUUID().slice(0, 8);
150
- /** @type {Map<string, object>} keyed by normalized workspace path. */
151
- this.trees = new Map();
152
- this.rootReady = null;
153
- }
154
-
155
- /**
156
- * Create the root directory once and resolve it to its real path.
157
- *
158
- * Resolving after creation matters: every containment check below compares
159
- * real paths, so a symlinked root cannot be used to place a tree anywhere
160
- * else.
161
- * @returns {Promise<string>} resolved root directory.
162
- */
163
- async ensureRoot() {
164
- if (this.rootReady === null) {
165
- this.rootReady = (async () => {
166
- await mkdir(this.rootDir, { recursive: true, mode: 0o700 });
167
- return await realpath(this.rootDir);
168
- })();
169
- }
170
- return await this.rootReady;
171
- }
172
-
173
- /**
174
- * Prepare one detached worktree for a task.
175
- *
176
- * Order is deliberate: every refusal that can be decided without touching the
177
- * filesystem happens first, then the commit is pinned, then the tree is
178
- * created, then it is verified. A cancellation observed at any point before
179
- * the caller receives a workspace means the caller must not run anything.
180
- * @param {object} request - `taskId`, `sourcePath`, optional `signal`.
181
- * @returns {Promise<object>} `{ workspacePath, baseHead, sourcePath, isolated: true, ... }`.
182
- */
183
- async prepare(request = {}) {
184
- const taskId = typeof request.taskId === 'string' ? request.taskId.trim() : '';
185
- if (taskId === '') {
186
- throw new WorktreeError(WORKTREE_CODES.taskIdInvalid, 'a task id is required to prepare a worktree', {});
187
- }
188
- const segment = safeTaskSegment(taskId);
189
- if (segment === '') {
190
- throw new WorktreeError(WORKTREE_CODES.taskIdInvalid, 'the task id has no path-safe characters', { taskId });
191
- }
192
- if (typeof request.sourcePath !== 'string' || request.sourcePath.trim() === '' || !isAbsolute(request.sourcePath.trim())) {
193
- throw new WorktreeError(WORKTREE_CODES.rootInvalid, 'an absolute source repository path is required', {});
194
- }
195
- const signal = request.signal;
196
- this.throwIfAborted(signal, { taskId, phase: 'before-probe' });
197
-
198
- const sourcePath = await realpath(resolve(request.sourcePath.trim())).catch((error) => {
199
- throw new WorktreeError(WORKTREE_CODES.notRepository, 'the source repository path could not be resolved', {
200
- cause: error?.code ?? null,
201
- });
202
- });
203
- // Containment is decided against the repository's canonical top level, not
204
- // against the supplied path. A supplied path may be a directory *inside* the
205
- // repository, and a tree root that sits elsewhere in that same repository is
206
- // exactly as unsafe as one under the subdirectory: either way the agent's
207
- // checkout would land inside the user's repository.
208
- const repositoryRoot = await this.resolveRepositoryRoot(sourcePath, taskId);
209
- const declaredRoot = this.rootDir;
210
- // A tree inside the source checkout would put agent writes back into the
211
- // user's working directory and make `git status` ambiguous. Both the
212
- // declared root and its resolved path are checked, because the root may be
213
- // reached through a symlink that only applies after it exists.
214
- if (isInside(repositoryRoot, declaredRoot)) {
215
- throw new WorktreeError(
216
- WORKTREE_CODES.nestedDestination,
217
- 'the worktree root is inside the source repository; choose a root outside it',
218
- { rootDir: declaredRoot, sourcePath, repositoryRoot },
219
- );
220
- }
221
- const root = await this.ensureRoot();
222
- if (isInside(repositoryRoot, root)) {
223
- throw new WorktreeError(
224
- WORKTREE_CODES.nestedDestination,
225
- 'the worktree root is inside the source repository; choose a root outside it',
226
- { rootDir: root, sourcePath, repositoryRoot },
227
- );
228
- }
229
-
230
- const facts = await this.probeSource(sourcePath, taskId);
231
- const dirty = await this.assertClean(sourcePath, taskId);
232
- this.throwIfAborted(signal, { taskId, phase: 'before-create' });
233
-
234
- const workspacePath = await this.claimDestination(root, segment, taskId, sourcePath, repositoryRoot);
235
- this.throwIfAborted(signal, { taskId, phase: 'before-create' });
236
-
237
- // `--detach` binds the tree to a commit, not a branch: nothing the run does
238
- // can move a ref in the user's repository.
239
- const created = requireResult(
240
- await this.deps.runGit(sourcePath, ['worktree', 'add', '--detach', workspacePath, facts.head]),
241
- 'worktree add',
242
- );
243
- if (created.code !== 0) {
244
- // A partially created tree must not be left behind claiming to be usable.
245
- await this.removeLeftover(sourcePath, workspacePath);
246
- throw gitFailure('worktree add', created);
247
- }
248
-
249
- const record = {
250
- taskId,
251
- workspacePath,
252
- sourcePath,
253
- baseHead: facts.head,
254
- isolated: true,
255
- detachedVerified: false,
256
- state: WORKTREE_STATES.active,
257
- createdAt: this.now(),
258
- completedAt: null,
259
- // Baseline facts the engine records with the task; names and counts only.
260
- sourcePreexistingChanges: dirty.total,
261
- };
262
- this.trees.set(normalizeKey(workspacePath), record);
263
-
264
- try {
265
- await this.verifyTree(record);
266
- } catch (error) {
267
- await this.removeLeftover(sourcePath, workspacePath);
268
- this.trees.delete(normalizeKey(workspacePath));
269
- throw error;
270
- }
271
-
272
- // A cancellation that arrived while `git worktree add` was running must not
273
- // hand the caller a usable workspace.
274
- if (signal?.aborted === true) {
275
- await this.removeLeftover(sourcePath, workspacePath);
276
- this.trees.delete(normalizeKey(workspacePath));
277
- throw new WorktreeError(WORKTREE_CODES.cancelled, 'the worktree was cancelled before the run could start', {
278
- taskId,
279
- phase: 'after-create',
280
- });
281
- }
282
-
283
- return this.view(record);
284
- }
285
-
286
- /**
287
- * Measure the canonical top level of the source repository.
288
- *
289
- * This runs before anything is created, and it is the value every containment
290
- * check below compares against: the supplied `sourcePath` may be a directory
291
- * inside the repository, so using it as the boundary would let a root located
292
- * elsewhere in the same repository pass as "outside the source".
293
- * @param {string} sourcePath - resolved source path.
294
- * @param {string} taskId - task id, for details.
295
- * @returns {Promise<string>} resolved top-level directory.
296
- */
297
- async resolveRepositoryRoot(sourcePath, taskId) {
298
- let topLevel;
299
- try {
300
- topLevel = await readRepositoryTopLevel(this.deps.runGit, sourcePath);
301
- } catch (error) {
302
- if (error instanceof AuditError && error.code === AUDIT_CODES.gitUnavailable) {
303
- throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', {
304
- taskId,
305
- cause: error?.details?.cause ?? null,
306
- });
307
- }
308
- throw error;
309
- }
310
- if (typeof topLevel !== 'string' || topLevel.trim() === '') {
311
- throw new WorktreeError(WORKTREE_CODES.notRepository, 'worktree isolation requires a git work tree', { taskId });
312
- }
313
- return await realpath(topLevel).catch((error) => {
314
- throw new WorktreeError(WORKTREE_CODES.notRepository, 'the repository root could not be resolved', {
315
- taskId,
316
- cause: error?.code ?? null,
317
- });
318
- });
319
- }
320
-
321
- /**
322
- * Confirm the source is a git work tree with a commit.
323
- * @param {string} sourcePath - resolved source repository.
324
- * @param {string} taskId - task id, for details.
325
- * @returns {Promise<{head: string}>} pinned commit facts.
326
- */
327
- async probeSource(sourcePath, taskId) {
328
- let facts;
329
- try {
330
- facts = await probeRepository(this.deps.runGit, sourcePath);
331
- } catch (error) {
332
- if (error instanceof AuditError && error.code === AUDIT_CODES.gitUnavailable) {
333
- throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', {
334
- taskId,
335
- cause: error?.details?.cause ?? null,
336
- });
337
- }
338
- throw error;
339
- }
340
- if (!facts.git) {
341
- throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', { taskId });
342
- }
343
- if (!facts.repository) {
344
- throw new WorktreeError(WORKTREE_CODES.notRepository, 'worktree isolation requires a git work tree', { taskId });
345
- }
346
- if (!facts.hasCommits || typeof facts.head !== 'string') {
347
- throw new WorktreeError(
348
- WORKTREE_CODES.noCommits,
349
- 'worktree isolation requires at least one commit; commit the workspace first',
350
- { taskId },
351
- );
352
- }
353
- return facts;
354
- }
355
-
356
- /**
357
- * Require a clean source checkout.
358
- *
359
- * A dirty source is refused rather than carried into the tree: a worktree is
360
- * created from a commit, so uncommitted edits would silently *not* be there,
361
- * and the delegated run would fail for a reason nobody can see.
362
- * @param {string} sourcePath - resolved source repository.
363
- * @param {string} taskId - task id, for details.
364
- * @returns {Promise<{total: number, paths: string[], truncated: boolean}>} bounded dirt facts.
365
- */
366
- async assertClean(sourcePath, taskId) {
367
- const status = await readStatus(this.deps, sourcePath, { limit: AUDIT_LIMITS.samplePaths });
368
- if (status.total > 0) {
369
- throw new WorktreeError(
370
- WORKTREE_CODES.sourceDirty,
371
- `the source workspace has ${status.total} uncommitted change(s); commit or stash them before requesting worktree isolation`,
372
- {
373
- taskId,
374
- sourcePath,
375
- changes: status.total,
376
- // Names only: the refusal must not read what was changed.
377
- paths: status.entries.slice(0, AUDIT_LIMITS.samplePaths).map((entry) => entry.path),
378
- truncated: status.truncated,
379
- },
380
- );
381
- }
382
- return status;
383
- }
384
-
385
- /**
386
- * Choose a unique destination under the root and prove it is contained.
387
- * @param {string} root - resolved root directory.
388
- * @param {string} segment - safe task segment.
389
- * @param {string} taskId - task id, for details.
390
- * @param {string} sourcePath - resolved source path named by the caller.
391
- * @param {string} repositoryRoot - resolved top level of the source repository.
392
- * @returns {Promise<string>} unused absolute destination path.
393
- */
394
- async claimDestination(root, segment, taskId, sourcePath, repositoryRoot) {
395
- const suffix = String(this.randomId() ?? '').replace(/[^A-Za-z0-9]/g, '').slice(0, 12) || randomUUID().slice(0, 8);
396
- const workspacePath = join(root, `${segment}-${suffix}`);
397
- // The generated name must remain inside the root; a task id that survives
398
- // sanitization cannot escape, and this check proves it rather than assuming.
399
- if (!isInside(root, workspacePath)) {
400
- throw new WorktreeError(WORKTREE_CODES.pathEscape, 'the worktree path escaped the plugin root', { taskId });
401
- }
402
- // Containment is against the repository root, not only the supplied path: a
403
- // destination elsewhere in the same repository is just as much inside the
404
- // user's checkout as one under a supplied subdirectory.
405
- const boundary = typeof repositoryRoot === 'string' && repositoryRoot !== '' ? repositoryRoot : sourcePath;
406
- if (isInside(boundary, workspacePath) || isInside(sourcePath, workspacePath) || workspacePath === sourcePath) {
407
- throw new WorktreeError(
408
- WORKTREE_CODES.nestedDestination,
409
- 'the worktree destination would be inside the source repository',
410
- { taskId, workspacePath, sourcePath, repositoryRoot: boundary },
411
- );
412
- }
413
- if (await pathExists(workspacePath)) {
414
- throw new WorktreeError(WORKTREE_CODES.destinationExists, 'the worktree destination already exists', {
415
- taskId,
416
- workspacePath,
417
- });
418
- }
419
- return workspacePath;
420
- }
421
-
422
- /**
423
- * Verify that the tree really points at the pinned commit.
424
- * @param {object} record - tree record.
425
- * @returns {Promise<void>} resolves when verified.
426
- */
427
- async verifyTree(record) {
428
- const head = requireResult(
429
- await this.deps.runGit(record.workspacePath, ['rev-parse', '--verify', 'HEAD']),
430
- 'rev-parse --verify HEAD',
431
- );
432
- const sha = head.stdout.trim();
433
- if (head.code !== 0 || sha === '') {
434
- throw new WorktreeError(WORKTREE_CODES.gitFailed, 'the created worktree has no commit', {
435
- step: 'rev-parse --verify HEAD',
436
- exitCode: head.code,
437
- });
438
- }
439
- if (sha !== record.baseHead) {
440
- throw new WorktreeError(WORKTREE_CODES.gitFailed, 'the created worktree does not start at the pinned commit', {
441
- step: 'rev-parse --verify HEAD',
442
- expected: record.baseHead,
443
- actual: sha,
444
- });
445
- }
446
- record.detachedVerified = true;
447
- }
448
-
449
- /**
450
- * Throw when a cancellation was already requested.
451
- * @param {AbortSignal | undefined} signal - caller signal.
452
- * @param {object} details - bounded details.
453
- * @returns {void}
454
- */
455
- throwIfAborted(signal, details) {
456
- if (signal?.aborted === true) {
457
- throw new WorktreeError(WORKTREE_CODES.cancelled, 'the worktree request was cancelled', details);
458
- }
459
- }
460
-
461
- /**
462
- * Remove a tree this manager created after a failed or cancelled creation.
463
- *
464
- * This is the only path that deletes without a host decision, and it is
465
- * restricted to trees that never became usable: the caller never received the
466
- * workspace path, so no unreviewed work can exist there.
467
- * @param {string} sourcePath - source repository.
468
- * @param {string} workspacePath - tree to remove.
469
- * @returns {Promise<void>} resolves after the best-effort cleanup.
470
- */
471
- async removeLeftover(sourcePath, workspacePath) {
472
- try {
473
- await this.deps.runGit(sourcePath, ['worktree', 'remove', '--force', workspacePath]);
474
- } catch {
475
- // Fall through to prune: the directory may not exist yet.
476
- }
477
- try {
478
- await this.deps.runGit(sourcePath, ['worktree', 'prune']);
479
- } catch {
480
- // The registry entry is dropped regardless; the operator is told nothing
481
- // was handed out, and a stale administrative entry is harmless.
482
- }
483
- }
484
-
485
- /**
486
- * Mark a prepared tree as finished so a host can review it.
487
- * @param {string} workspacePath - tree path returned by {@link prepare}.
488
- * @returns {object} tree metadata.
489
- */
490
- markComplete(workspacePath) {
491
- const record = this.requireTree(workspacePath);
492
- if (record.state === WORKTREE_STATES.disposed) {
493
- throw new WorktreeError(WORKTREE_CODES.unknownTree, 'the worktree has already been disposed', { workspacePath });
494
- }
495
- record.state = WORKTREE_STATES.awaitingHostReview;
496
- record.completedAt = this.now();
497
- return this.view(record);
498
- }
499
-
500
- /**
501
- * List managed trees as metadata only.
502
- *
503
- * No file contents, no diff: a host reviews a tree through the audit module,
504
- * not through this registry.
505
- * @param {object} [filter] - optional `taskId` and `state`.
506
- * @returns {object[]} tree metadata, newest first.
507
- */
508
- list(filter = {}) {
509
- const out = [];
510
- for (const record of this.trees.values()) {
511
- if (filter.taskId !== undefined && record.taskId !== filter.taskId) continue;
512
- if (filter.state !== undefined && record.state !== filter.state) continue;
513
- out.push(this.view(record));
514
- }
515
- return out.sort((a, b) => b.createdAt - a.createdAt);
516
- }
517
-
518
- /**
519
- * Read one tree's metadata.
520
- * @param {string} workspacePath - tree path.
521
- * @returns {object | null} metadata, or null when unmanaged.
522
- */
523
- get(workspacePath) {
524
- const record = this.trees.get(normalizeKey(workspacePath));
525
- return record === undefined ? null : this.view(record);
526
- }
527
-
528
- /**
529
- * Recover one original tree after a restart, without creating or changing it.
530
- * The engine has already verified the caller, task history and Session identity.
531
- * Here the stored tree identity must also agree with real paths and Git's live
532
- * registration. A directory name alone is never evidence of a managed tree.
533
- * @param {object} request - original taskId, sourcePath, workspacePath, state and signal.
534
- * @returns {Promise<object>} verified metadata, or a refusal.
535
- */
536
- async recover(request) {
537
- const { taskId, sourcePath, workspacePath, signal } = request;
538
- const refuse = (reason) => new WorktreeError(WORKTREE_CODES.unknownTree,
539
- 'the original worktree could not be verified after restart', { reason });
540
- this.throwIfAborted(signal, { taskId, phase: 'recover' });
541
- if (request.state === WORKTREE_STATES.disposed || safeTaskSegment(taskId) === ''
542
- || typeof sourcePath !== 'string' || !isAbsolute(sourcePath)
543
- || typeof workspacePath !== 'string' || !isAbsolute(workspacePath)) {
544
- throw refuse('invalid recorded tree');
545
- }
546
- const present = this.get(workspacePath);
547
- if (present !== null) return present;
548
-
549
- const [root, source, workspace] = await Promise.all([
550
- realpath(this.rootDir), realpath(sourcePath), realpath(workspacePath),
551
- ]);
552
- const key = (path) => normalizeKey(resolve(path));
553
- const prefix = `${safeTaskSegment(taskId)}-`;
554
- const name = basename(workspace);
555
- if (key(source) !== key(sourcePath) || key(workspace) !== key(workspacePath)
556
- || key(dirname(workspace)) !== key(root) || !name.startsWith(prefix)
557
- || !/^[A-Za-z0-9]{1,12}$/.test(name.slice(prefix.length)) || key(source) === key(workspace)) {
558
- throw refuse('recorded tree path mismatch');
559
- }
560
-
561
- const results = await Promise.all([
562
- this.deps.runGit(source, ['worktree', 'list', '--porcelain', '-z']),
563
- this.deps.runGit(source, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
564
- this.deps.runGit(workspace, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
565
- this.deps.runGit(workspace, ['rev-parse', '--show-toplevel']),
566
- ]);
567
- const [listing, sourceCommon, treeCommon, top] = results.map((result) => requireResult(result, 'recover worktree'));
568
- if ([listing, sourceCommon, treeCommon, top].some((result) => result.code !== 0)
569
- || !isAbsolute(sourceCommon.stdout.trim()) || !isAbsolute(treeCommon.stdout.trim())
570
- || key(sourceCommon.stdout.trim()) !== key(treeCommon.stdout.trim())
571
- || key(top.stdout.trim()) !== key(workspace)) {
572
- throw refuse('tree repository mismatch');
573
- }
574
- const registrations = listing.stdout.split('\0\0').filter(Boolean).map((block) => block.split('\0'));
575
- const registration = registrations.find((fields) => fields.some((field) =>
576
- field.startsWith('worktree ') && key(field.slice(9)) === key(workspace)));
577
- const head = registration?.find((field) => field.startsWith('HEAD '))?.slice(5) ?? '';
578
- if (!registration?.includes('detached') || !/^[a-f0-9]{40,64}$/i.test(head)
579
- || registration.some((field) => field === 'prunable' || field.startsWith('prunable '))) {
580
- throw refuse('original detached tree is not registered');
581
- }
582
- this.throwIfAborted(signal, { taskId, phase: 'recover' });
583
- // Unknown original timestamps and source dirtiness stay unknown. The next
584
- // run captures its own audit baseline; recovery never cleans either checkout.
585
- const record = {
586
- taskId, workspacePath: workspace, sourcePath: source, baseHead: head,
587
- isolated: true, detachedVerified: true, state: WORKTREE_STATES.awaitingHostReview,
588
- createdAt: null, completedAt: null, sourcePreexistingChanges: null,
589
- };
590
- this.trees.set(normalizeKey(workspace), record);
591
- return this.view(record);
592
- }
593
-
594
- /**
595
- * Remove one tree at a host's explicit request.
596
- *
597
- * Refuses while the tree is still `active` unless the caller states the tree
598
- * was reviewed: deleting a tree a run is still using, or one nobody looked at,
599
- * would destroy the only evidence of what the run changed.
600
- * @param {string} workspacePath - tree path.
601
- * @param {object} [options] - `reviewed: true` asserts host review happened.
602
- * @returns {Promise<object>} metadata of the removed tree.
603
- */
604
- async dispose(workspacePath, options = {}) {
605
- const record = this.requireTree(workspacePath);
606
- if (record.state === WORKTREE_STATES.disposed) {
607
- throw new WorktreeError(WORKTREE_CODES.unknownTree, 'the worktree has already been disposed', { workspacePath });
608
- }
609
- if (record.state === WORKTREE_STATES.active && options.reviewed !== true) {
610
- throw new WorktreeError(
611
- WORKTREE_CODES.notReviewed,
612
- 'the worktree is still active; mark it complete or state that it was reviewed before removing it',
613
- { workspacePath, state: record.state },
614
- );
615
- }
616
- const removed = requireResult(
617
- await this.deps.runGit(record.sourcePath, ['worktree', 'remove', '--force', record.workspacePath]),
618
- 'worktree remove',
619
- );
620
- if (removed.code !== 0) {
621
- // The directory may already be gone; prune settles the administrative
622
- // entry before any failure is reported.
623
- await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
624
- if (await pathExists(record.workspacePath)) {
625
- throw gitFailure('worktree remove', removed);
626
- }
627
- } else {
628
- await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
629
- }
630
- record.state = WORKTREE_STATES.disposed;
631
- record.reviewedByHost = options.reviewed === true;
632
- return this.view(record);
633
- }
634
-
635
- /**
636
- * Resolve a managed record or refuse.
637
- * @param {string} workspacePath - tree path.
638
- * @returns {object} record.
639
- */
640
- requireTree(workspacePath) {
641
- const record = this.trees.get(normalizeKey(workspacePath));
642
- if (record === undefined) {
643
- throw new WorktreeError(WORKTREE_CODES.unknownTree, 'no such managed worktree', { workspacePath });
644
- }
645
- return record;
646
- }
647
-
648
- /**
649
- * Project a record for callers: metadata only, no content, no error text.
650
- * @param {object} record - internal record.
651
- * @returns {object} metadata view.
652
- */
653
- view(record) {
654
- return {
655
- taskId: record.taskId,
656
- workspacePath: record.workspacePath,
657
- sourcePath: record.sourcePath,
658
- baseHead: record.baseHead,
659
- isolated: record.isolated === true,
660
- detached: record.detachedVerified === true,
661
- state: record.state,
662
- createdAt: record.createdAt,
663
- completedAt: record.completedAt,
664
- sourcePreexistingChanges: record.sourcePreexistingChanges,
665
- disposable: record.state !== WORKTREE_STATES.disposed,
666
- };
667
- }
668
- }
669
-
670
- /**
671
- * Normalize a path for use as a registry key. Case-folded on Windows, where the
672
- * filesystem is case-insensitive.
673
- * @param {string} workspacePath - path.
674
- * @returns {string} key.
675
- */
676
- function normalizeKey(workspacePath) {
677
- const normalized = String(workspacePath).replace(/[\\/]+$/, '');
678
- return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
679
- }
1
+ // Isolated git worktrees for delegated runs.
2
+ //
3
+ // A delegated run is allowed to mutate files. When the operator asks for
4
+ // worktree isolation, it must mutate a *different* checkout than the one the
5
+ // human is looking at. This module owns that checkout:
6
+ //
7
+ // - it is created by `git worktree add --detach <pinned-commit>`, so the run
8
+ // starts from an exact commit and no branch is moved in either repository;
9
+ // - it lives under a plugin-owned root directory, never inside the user's
10
+ // checkout, and never at a path a caller supplied directly;
11
+ // - every mutation is an argv array handed to the same `runGit` seam the rest
12
+ // of the plugin uses — no shell, no `checkout`, no `reset`, no merge, no
13
+ // rebase anywhere in this file;
14
+ // - it is kept after the run so the host can review it, and it is only removed
15
+ // when a host says so. A finished tree is evidence, not garbage.
16
+ //
17
+ // What this is NOT: a security boundary against the agent process. A delegated
18
+ // agent runs as the same OS user; worktree isolation keeps the *human's files*
19
+ // from being edited, it does not sandbox a hostile program. That is stated here
20
+ // rather than implied by the word "isolated".
21
+
22
+ import { randomUUID } from 'node:crypto';
23
+ import { lstat, mkdir, realpath } from 'node:fs/promises';
24
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
25
+
26
+ import { AUDIT_CODES, AUDIT_LIMITS, AuditError, probeRepository, readRepositoryTopLevel, readStatus } from './audit.js';
27
+ import { isInside } from './locks.js';
28
+
29
+ /** Worktree refusal codes. Each is a refusal, never a silent fallback. */
30
+ export const WORKTREE_CODES = Object.freeze({
31
+ gitUnavailable: 'WORKTREE_GIT_UNAVAILABLE',
32
+ notRepository: 'WORKTREE_NOT_A_REPOSITORY',
33
+ noCommits: 'WORKTREE_NO_COMMITS',
34
+ sourceDirty: 'WORKTREE_SOURCE_DIRTY',
35
+ rootInvalid: 'WORKTREE_ROOT_INVALID',
36
+ pathEscape: 'WORKTREE_PATH_ESCAPE',
37
+ nestedDestination: 'WORKTREE_NESTED_DESTINATION',
38
+ destinationExists: 'WORKTREE_DESTINATION_EXISTS',
39
+ cancelled: 'WORKTREE_CANCELLED',
40
+ gitFailed: 'WORKTREE_GIT_FAILED',
41
+ unknownTree: 'WORKTREE_UNKNOWN_TREE',
42
+ notReviewed: 'WORKTREE_NOT_REVIEWED',
43
+ taskIdInvalid: 'WORKTREE_TASK_ID_INVALID',
44
+ });
45
+
46
+ /** Tree states. `awaiting-host-review` is where a tree stays until a host acts. */
47
+ export const WORKTREE_STATES = Object.freeze({
48
+ active: 'active',
49
+ awaitingHostReview: 'awaiting-host-review',
50
+ disposed: 'disposed',
51
+ });
52
+
53
+ /** Raised when a worktree request is refused. */
54
+ export class WorktreeError extends Error {
55
+ /**
56
+ * @param {string} code - stable machine code.
57
+ * @param {string} message - human-readable explanation.
58
+ * @param {object} [details] - bounded details; never file content.
59
+ */
60
+ constructor(code, message, details = {}) {
61
+ super(message);
62
+ this.name = 'WorktreeError';
63
+ this.code = code;
64
+ this.details = details;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Reduce a task id to a safe single path segment.
70
+ *
71
+ * The task id is caller-influenced, so it is not trusted as a path component:
72
+ * anything outside `[A-Za-z0-9._-]` becomes `-`, leading dots are dropped so no
73
+ * generated name can be mistaken for a hidden or parent directory, and the
74
+ * segment is length-bounded.
75
+ * @param {unknown} taskId - raw task id.
76
+ * @returns {string} safe segment, or an empty string when nothing usable remains.
77
+ */
78
+ export function safeTaskSegment(taskId) {
79
+ if (typeof taskId !== 'string') return '';
80
+ const cleaned = taskId.trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '').slice(0, 48);
81
+ return cleaned === '' ? '' : cleaned;
82
+ }
83
+
84
+ /**
85
+ * Build a refusal from a failed git invocation.
86
+ * @param {string} step - which invocation failed.
87
+ * @param {object} result - runner result.
88
+ * @returns {WorktreeError} refusal to throw.
89
+ */
90
+ function gitFailure(step, result) {
91
+ return new WorktreeError(WORKTREE_CODES.gitFailed, `git ${step} failed`, {
92
+ step,
93
+ exitCode: typeof result?.code === 'number' ? result.code : null,
94
+ stderr: String(result?.stderr ?? '').trim().slice(0, AUDIT_LIMITS.stderrBytes),
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Validate the shape a runner returned.
100
+ * @param {unknown} result - runner result.
101
+ * @param {string} step - invocation name.
102
+ * @returns {{stdout: string, stderr: string, code: number}} result.
103
+ */
104
+ function requireResult(result, step) {
105
+ if (result === null || typeof result !== 'object' || typeof result.stdout !== 'string' || typeof result.code !== 'number') {
106
+ throw new WorktreeError(WORKTREE_CODES.gitFailed, `the git runner returned no usable result for ${step}`, { step });
107
+ }
108
+ return { stdout: result.stdout, stderr: typeof result.stderr === 'string' ? result.stderr : '', code: result.code };
109
+ }
110
+
111
+ /**
112
+ * Whether a path exists, without following a final symlink.
113
+ * @param {string} target - absolute path.
114
+ * @returns {Promise<boolean>} true when something is there.
115
+ */
116
+ async function pathExists(target) {
117
+ try {
118
+ await lstat(target);
119
+ return true;
120
+ } catch (error) {
121
+ if (error?.code === 'ENOENT') return false;
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Owns plugin-created detached worktrees.
128
+ *
129
+ * One manager per plugin instance. The manager keeps metadata in memory only: a
130
+ * restart forgets the registry. A validated continuation may recover its ONE
131
+ * recorded tree through Git's live registry; startup never scans, deletes or
132
+ * adopts arbitrary directories.
133
+ */
134
+ export class WorktreeManager {
135
+ /**
136
+ * @param {object} deps - `runGit` runner (same seam as the audit module).
137
+ * @param {object} options - `rootDir` (required), optional `now` and `randomId`.
138
+ */
139
+ constructor(deps, options = {}) {
140
+ if (typeof deps?.runGit !== 'function') {
141
+ throw new WorktreeError(WORKTREE_CODES.gitFailed, 'a runGit runner is required', {});
142
+ }
143
+ if (typeof options.rootDir !== 'string' || options.rootDir.trim() === '' || !isAbsolute(options.rootDir.trim())) {
144
+ throw new WorktreeError(WORKTREE_CODES.rootInvalid, 'an absolute rootDir for worktrees is required', {});
145
+ }
146
+ this.deps = deps;
147
+ this.rootDir = resolve(options.rootDir.trim());
148
+ this.now = typeof options.now === 'function' ? options.now : () => Date.now();
149
+ this.randomId = typeof options.randomId === 'function' ? options.randomId : () => randomUUID().slice(0, 8);
150
+ /** @type {Map<string, object>} keyed by normalized workspace path. */
151
+ this.trees = new Map();
152
+ this.rootReady = null;
153
+ }
154
+
155
+ /**
156
+ * Create the root directory once and resolve it to its real path.
157
+ *
158
+ * Resolving after creation matters: every containment check below compares
159
+ * real paths, so a symlinked root cannot be used to place a tree anywhere
160
+ * else.
161
+ * @returns {Promise<string>} resolved root directory.
162
+ */
163
+ async ensureRoot() {
164
+ if (this.rootReady === null) {
165
+ this.rootReady = (async () => {
166
+ await mkdir(this.rootDir, { recursive: true, mode: 0o700 });
167
+ return await realpath(this.rootDir);
168
+ })();
169
+ }
170
+ return await this.rootReady;
171
+ }
172
+
173
+ /**
174
+ * Prepare one detached worktree for a task.
175
+ *
176
+ * Order is deliberate: every refusal that can be decided without touching the
177
+ * filesystem happens first, then the commit is pinned, then the tree is
178
+ * created, then it is verified. A cancellation observed at any point before
179
+ * the caller receives a workspace means the caller must not run anything.
180
+ * @param {object} request - `taskId`, `sourcePath`, optional `signal`.
181
+ * @returns {Promise<object>} `{ workspacePath, baseHead, sourcePath, isolated: true, ... }`.
182
+ */
183
+ async prepare(request = {}) {
184
+ const taskId = typeof request.taskId === 'string' ? request.taskId.trim() : '';
185
+ if (taskId === '') {
186
+ throw new WorktreeError(WORKTREE_CODES.taskIdInvalid, 'a task id is required to prepare a worktree', {});
187
+ }
188
+ const segment = safeTaskSegment(taskId);
189
+ if (segment === '') {
190
+ throw new WorktreeError(WORKTREE_CODES.taskIdInvalid, 'the task id has no path-safe characters', { taskId });
191
+ }
192
+ if (typeof request.sourcePath !== 'string' || request.sourcePath.trim() === '' || !isAbsolute(request.sourcePath.trim())) {
193
+ throw new WorktreeError(WORKTREE_CODES.rootInvalid, 'an absolute source repository path is required', {});
194
+ }
195
+ const signal = request.signal;
196
+ this.throwIfAborted(signal, { taskId, phase: 'before-probe' });
197
+
198
+ const sourcePath = await realpath(resolve(request.sourcePath.trim())).catch((error) => {
199
+ throw new WorktreeError(WORKTREE_CODES.notRepository, 'the source repository path could not be resolved', {
200
+ cause: error?.code ?? null,
201
+ });
202
+ });
203
+ // Containment is decided against the repository's canonical top level, not
204
+ // against the supplied path. A supplied path may be a directory *inside* the
205
+ // repository, and a tree root that sits elsewhere in that same repository is
206
+ // exactly as unsafe as one under the subdirectory: either way the agent's
207
+ // checkout would land inside the user's repository.
208
+ const repositoryRoot = await this.resolveRepositoryRoot(sourcePath, taskId);
209
+ const declaredRoot = this.rootDir;
210
+ // A tree inside the source checkout would put agent writes back into the
211
+ // user's working directory and make `git status` ambiguous. Both the
212
+ // declared root and its resolved path are checked, because the root may be
213
+ // reached through a symlink that only applies after it exists.
214
+ if (isInside(repositoryRoot, declaredRoot)) {
215
+ throw new WorktreeError(
216
+ WORKTREE_CODES.nestedDestination,
217
+ 'the worktree root is inside the source repository; choose a root outside it',
218
+ { rootDir: declaredRoot, sourcePath, repositoryRoot },
219
+ );
220
+ }
221
+ const root = await this.ensureRoot();
222
+ if (isInside(repositoryRoot, root)) {
223
+ throw new WorktreeError(
224
+ WORKTREE_CODES.nestedDestination,
225
+ 'the worktree root is inside the source repository; choose a root outside it',
226
+ { rootDir: root, sourcePath, repositoryRoot },
227
+ );
228
+ }
229
+
230
+ const facts = await this.probeSource(sourcePath, taskId);
231
+ const dirty = await this.assertClean(sourcePath, taskId);
232
+ this.throwIfAborted(signal, { taskId, phase: 'before-create' });
233
+
234
+ const workspacePath = await this.claimDestination(root, segment, taskId, sourcePath, repositoryRoot);
235
+ this.throwIfAborted(signal, { taskId, phase: 'before-create' });
236
+
237
+ // `--detach` binds the tree to a commit, not a branch: nothing the run does
238
+ // can move a ref in the user's repository.
239
+ const created = requireResult(
240
+ await this.deps.runGit(sourcePath, ['worktree', 'add', '--detach', workspacePath, facts.head]),
241
+ 'worktree add',
242
+ );
243
+ if (created.code !== 0) {
244
+ // A partially created tree must not be left behind claiming to be usable.
245
+ await this.removeLeftover(sourcePath, workspacePath);
246
+ throw gitFailure('worktree add', created);
247
+ }
248
+
249
+ const record = {
250
+ taskId,
251
+ workspacePath,
252
+ sourcePath,
253
+ baseHead: facts.head,
254
+ isolated: true,
255
+ detachedVerified: false,
256
+ state: WORKTREE_STATES.active,
257
+ createdAt: this.now(),
258
+ completedAt: null,
259
+ // Baseline facts the engine records with the task; names and counts only.
260
+ sourcePreexistingChanges: dirty.total,
261
+ };
262
+ this.trees.set(normalizeKey(workspacePath), record);
263
+
264
+ try {
265
+ await this.verifyTree(record);
266
+ } catch (error) {
267
+ await this.removeLeftover(sourcePath, workspacePath);
268
+ this.trees.delete(normalizeKey(workspacePath));
269
+ throw error;
270
+ }
271
+
272
+ // A cancellation that arrived while `git worktree add` was running must not
273
+ // hand the caller a usable workspace.
274
+ if (signal?.aborted === true) {
275
+ await this.removeLeftover(sourcePath, workspacePath);
276
+ this.trees.delete(normalizeKey(workspacePath));
277
+ throw new WorktreeError(WORKTREE_CODES.cancelled, 'the worktree was cancelled before the run could start', {
278
+ taskId,
279
+ phase: 'after-create',
280
+ });
281
+ }
282
+
283
+ return this.view(record);
284
+ }
285
+
286
+ /**
287
+ * Measure the canonical top level of the source repository.
288
+ *
289
+ * This runs before anything is created, and it is the value every containment
290
+ * check below compares against: the supplied `sourcePath` may be a directory
291
+ * inside the repository, so using it as the boundary would let a root located
292
+ * elsewhere in the same repository pass as "outside the source".
293
+ * @param {string} sourcePath - resolved source path.
294
+ * @param {string} taskId - task id, for details.
295
+ * @returns {Promise<string>} resolved top-level directory.
296
+ */
297
+ async resolveRepositoryRoot(sourcePath, taskId) {
298
+ let topLevel;
299
+ try {
300
+ topLevel = await readRepositoryTopLevel(this.deps.runGit, sourcePath);
301
+ } catch (error) {
302
+ if (error instanceof AuditError && error.code === AUDIT_CODES.gitUnavailable) {
303
+ throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', {
304
+ taskId,
305
+ cause: error?.details?.cause ?? null,
306
+ });
307
+ }
308
+ throw error;
309
+ }
310
+ if (typeof topLevel !== 'string' || topLevel.trim() === '') {
311
+ throw new WorktreeError(WORKTREE_CODES.notRepository, 'worktree isolation requires a git work tree', { taskId });
312
+ }
313
+ return await realpath(topLevel).catch((error) => {
314
+ throw new WorktreeError(WORKTREE_CODES.notRepository, 'the repository root could not be resolved', {
315
+ taskId,
316
+ cause: error?.code ?? null,
317
+ });
318
+ });
319
+ }
320
+
321
+ /**
322
+ * Confirm the source is a git work tree with a commit.
323
+ * @param {string} sourcePath - resolved source repository.
324
+ * @param {string} taskId - task id, for details.
325
+ * @returns {Promise<{head: string}>} pinned commit facts.
326
+ */
327
+ async probeSource(sourcePath, taskId) {
328
+ let facts;
329
+ try {
330
+ facts = await probeRepository(this.deps.runGit, sourcePath);
331
+ } catch (error) {
332
+ if (error instanceof AuditError && error.code === AUDIT_CODES.gitUnavailable) {
333
+ throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', {
334
+ taskId,
335
+ cause: error?.details?.cause ?? null,
336
+ });
337
+ }
338
+ throw error;
339
+ }
340
+ if (!facts.git) {
341
+ throw new WorktreeError(WORKTREE_CODES.gitUnavailable, 'worktree isolation requires git in this environment', { taskId });
342
+ }
343
+ if (!facts.repository) {
344
+ throw new WorktreeError(WORKTREE_CODES.notRepository, 'worktree isolation requires a git work tree', { taskId });
345
+ }
346
+ if (!facts.hasCommits || typeof facts.head !== 'string') {
347
+ throw new WorktreeError(
348
+ WORKTREE_CODES.noCommits,
349
+ 'worktree isolation requires at least one commit; commit the workspace first',
350
+ { taskId },
351
+ );
352
+ }
353
+ return facts;
354
+ }
355
+
356
+ /**
357
+ * Require a clean source checkout.
358
+ *
359
+ * A dirty source is refused rather than carried into the tree: a worktree is
360
+ * created from a commit, so uncommitted edits would silently *not* be there,
361
+ * and the delegated run would fail for a reason nobody can see.
362
+ * @param {string} sourcePath - resolved source repository.
363
+ * @param {string} taskId - task id, for details.
364
+ * @returns {Promise<{total: number, paths: string[], truncated: boolean}>} bounded dirt facts.
365
+ */
366
+ async assertClean(sourcePath, taskId) {
367
+ const status = await readStatus(this.deps, sourcePath, { limit: AUDIT_LIMITS.samplePaths });
368
+ if (status.total > 0) {
369
+ throw new WorktreeError(
370
+ WORKTREE_CODES.sourceDirty,
371
+ `the source workspace has ${status.total} uncommitted change(s); commit or stash them before requesting worktree isolation`,
372
+ {
373
+ taskId,
374
+ sourcePath,
375
+ changes: status.total,
376
+ // Names only: the refusal must not read what was changed.
377
+ paths: status.entries.slice(0, AUDIT_LIMITS.samplePaths).map((entry) => entry.path),
378
+ truncated: status.truncated,
379
+ },
380
+ );
381
+ }
382
+ return status;
383
+ }
384
+
385
+ /**
386
+ * Choose a unique destination under the root and prove it is contained.
387
+ * @param {string} root - resolved root directory.
388
+ * @param {string} segment - safe task segment.
389
+ * @param {string} taskId - task id, for details.
390
+ * @param {string} sourcePath - resolved source path named by the caller.
391
+ * @param {string} repositoryRoot - resolved top level of the source repository.
392
+ * @returns {Promise<string>} unused absolute destination path.
393
+ */
394
+ async claimDestination(root, segment, taskId, sourcePath, repositoryRoot) {
395
+ const suffix = String(this.randomId() ?? '').replace(/[^A-Za-z0-9]/g, '').slice(0, 12) || randomUUID().slice(0, 8);
396
+ const workspacePath = join(root, `${segment}-${suffix}`);
397
+ // The generated name must remain inside the root; a task id that survives
398
+ // sanitization cannot escape, and this check proves it rather than assuming.
399
+ if (!isInside(root, workspacePath)) {
400
+ throw new WorktreeError(WORKTREE_CODES.pathEscape, 'the worktree path escaped the plugin root', { taskId });
401
+ }
402
+ // Containment is against the repository root, not only the supplied path: a
403
+ // destination elsewhere in the same repository is just as much inside the
404
+ // user's checkout as one under a supplied subdirectory.
405
+ const boundary = typeof repositoryRoot === 'string' && repositoryRoot !== '' ? repositoryRoot : sourcePath;
406
+ if (isInside(boundary, workspacePath) || isInside(sourcePath, workspacePath) || workspacePath === sourcePath) {
407
+ throw new WorktreeError(
408
+ WORKTREE_CODES.nestedDestination,
409
+ 'the worktree destination would be inside the source repository',
410
+ { taskId, workspacePath, sourcePath, repositoryRoot: boundary },
411
+ );
412
+ }
413
+ if (await pathExists(workspacePath)) {
414
+ throw new WorktreeError(WORKTREE_CODES.destinationExists, 'the worktree destination already exists', {
415
+ taskId,
416
+ workspacePath,
417
+ });
418
+ }
419
+ return workspacePath;
420
+ }
421
+
422
+ /**
423
+ * Verify that the tree really points at the pinned commit.
424
+ * @param {object} record - tree record.
425
+ * @returns {Promise<void>} resolves when verified.
426
+ */
427
+ async verifyTree(record) {
428
+ const head = requireResult(
429
+ await this.deps.runGit(record.workspacePath, ['rev-parse', '--verify', 'HEAD']),
430
+ 'rev-parse --verify HEAD',
431
+ );
432
+ const sha = head.stdout.trim();
433
+ if (head.code !== 0 || sha === '') {
434
+ throw new WorktreeError(WORKTREE_CODES.gitFailed, 'the created worktree has no commit', {
435
+ step: 'rev-parse --verify HEAD',
436
+ exitCode: head.code,
437
+ });
438
+ }
439
+ if (sha !== record.baseHead) {
440
+ throw new WorktreeError(WORKTREE_CODES.gitFailed, 'the created worktree does not start at the pinned commit', {
441
+ step: 'rev-parse --verify HEAD',
442
+ expected: record.baseHead,
443
+ actual: sha,
444
+ });
445
+ }
446
+ record.detachedVerified = true;
447
+ }
448
+
449
+ /**
450
+ * Throw when a cancellation was already requested.
451
+ * @param {AbortSignal | undefined} signal - caller signal.
452
+ * @param {object} details - bounded details.
453
+ * @returns {void}
454
+ */
455
+ throwIfAborted(signal, details) {
456
+ if (signal?.aborted === true) {
457
+ throw new WorktreeError(WORKTREE_CODES.cancelled, 'the worktree request was cancelled', details);
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Remove a tree this manager created after a failed or cancelled creation.
463
+ *
464
+ * This is the only path that deletes without a host decision, and it is
465
+ * restricted to trees that never became usable: the caller never received the
466
+ * workspace path, so no unreviewed work can exist there.
467
+ * @param {string} sourcePath - source repository.
468
+ * @param {string} workspacePath - tree to remove.
469
+ * @returns {Promise<void>} resolves after the best-effort cleanup.
470
+ */
471
+ async removeLeftover(sourcePath, workspacePath) {
472
+ try {
473
+ await this.deps.runGit(sourcePath, ['worktree', 'remove', '--force', workspacePath]);
474
+ } catch {
475
+ // Fall through to prune: the directory may not exist yet.
476
+ }
477
+ try {
478
+ await this.deps.runGit(sourcePath, ['worktree', 'prune']);
479
+ } catch {
480
+ // The registry entry is dropped regardless; the operator is told nothing
481
+ // was handed out, and a stale administrative entry is harmless.
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Mark a prepared tree as finished so a host can review it.
487
+ * @param {string} workspacePath - tree path returned by {@link prepare}.
488
+ * @returns {object} tree metadata.
489
+ */
490
+ markComplete(workspacePath) {
491
+ const record = this.requireTree(workspacePath);
492
+ if (record.state === WORKTREE_STATES.disposed) {
493
+ throw new WorktreeError(WORKTREE_CODES.unknownTree, 'the worktree has already been disposed', { workspacePath });
494
+ }
495
+ record.state = WORKTREE_STATES.awaitingHostReview;
496
+ record.completedAt = this.now();
497
+ return this.view(record);
498
+ }
499
+
500
+ /**
501
+ * List managed trees as metadata only.
502
+ *
503
+ * No file contents, no diff: a host reviews a tree through the audit module,
504
+ * not through this registry.
505
+ * @param {object} [filter] - optional `taskId` and `state`.
506
+ * @returns {object[]} tree metadata, newest first.
507
+ */
508
+ list(filter = {}) {
509
+ const out = [];
510
+ for (const record of this.trees.values()) {
511
+ if (filter.taskId !== undefined && record.taskId !== filter.taskId) continue;
512
+ if (filter.state !== undefined && record.state !== filter.state) continue;
513
+ out.push(this.view(record));
514
+ }
515
+ return out.sort((a, b) => b.createdAt - a.createdAt);
516
+ }
517
+
518
+ /**
519
+ * Read one tree's metadata.
520
+ * @param {string} workspacePath - tree path.
521
+ * @returns {object | null} metadata, or null when unmanaged.
522
+ */
523
+ get(workspacePath) {
524
+ const record = this.trees.get(normalizeKey(workspacePath));
525
+ return record === undefined ? null : this.view(record);
526
+ }
527
+
528
+ /**
529
+ * Recover one original tree after a restart, without creating or changing it.
530
+ * The engine has already verified the caller, task history and Session identity.
531
+ * Here the stored tree identity must also agree with real paths and Git's live
532
+ * registration. A directory name alone is never evidence of a managed tree.
533
+ * @param {object} request - original taskId, sourcePath, workspacePath, state and signal.
534
+ * @returns {Promise<object>} verified metadata, or a refusal.
535
+ */
536
+ async recover(request) {
537
+ const { taskId, sourcePath, workspacePath, signal } = request;
538
+ const refuse = (reason) => new WorktreeError(WORKTREE_CODES.unknownTree,
539
+ 'the original worktree could not be verified after restart', { reason });
540
+ this.throwIfAborted(signal, { taskId, phase: 'recover' });
541
+ if (request.state === WORKTREE_STATES.disposed || safeTaskSegment(taskId) === ''
542
+ || typeof sourcePath !== 'string' || !isAbsolute(sourcePath)
543
+ || typeof workspacePath !== 'string' || !isAbsolute(workspacePath)) {
544
+ throw refuse('invalid recorded tree');
545
+ }
546
+ const present = this.get(workspacePath);
547
+ if (present !== null) return present;
548
+
549
+ const [root, source, workspace] = await Promise.all([
550
+ realpath(this.rootDir), realpath(sourcePath), realpath(workspacePath),
551
+ ]);
552
+ const key = (path) => normalizeKey(resolve(path));
553
+ const prefix = `${safeTaskSegment(taskId)}-`;
554
+ const name = basename(workspace);
555
+ if (key(source) !== key(sourcePath) || key(workspace) !== key(workspacePath)
556
+ || key(dirname(workspace)) !== key(root) || !name.startsWith(prefix)
557
+ || !/^[A-Za-z0-9]{1,12}$/.test(name.slice(prefix.length)) || key(source) === key(workspace)) {
558
+ throw refuse('recorded tree path mismatch');
559
+ }
560
+
561
+ const results = await Promise.all([
562
+ this.deps.runGit(source, ['worktree', 'list', '--porcelain', '-z']),
563
+ this.deps.runGit(source, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
564
+ this.deps.runGit(workspace, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
565
+ this.deps.runGit(workspace, ['rev-parse', '--show-toplevel']),
566
+ ]);
567
+ const [listing, sourceCommon, treeCommon, top] = results.map((result) => requireResult(result, 'recover worktree'));
568
+ if ([listing, sourceCommon, treeCommon, top].some((result) => result.code !== 0)
569
+ || !isAbsolute(sourceCommon.stdout.trim()) || !isAbsolute(treeCommon.stdout.trim())
570
+ || key(sourceCommon.stdout.trim()) !== key(treeCommon.stdout.trim())
571
+ || key(top.stdout.trim()) !== key(workspace)) {
572
+ throw refuse('tree repository mismatch');
573
+ }
574
+ const registrations = listing.stdout.split('\0\0').filter(Boolean).map((block) => block.split('\0'));
575
+ const registration = registrations.find((fields) => fields.some((field) =>
576
+ field.startsWith('worktree ') && key(field.slice(9)) === key(workspace)));
577
+ const head = registration?.find((field) => field.startsWith('HEAD '))?.slice(5) ?? '';
578
+ if (!registration?.includes('detached') || !/^[a-f0-9]{40,64}$/i.test(head)
579
+ || registration.some((field) => field === 'prunable' || field.startsWith('prunable '))) {
580
+ throw refuse('original detached tree is not registered');
581
+ }
582
+ this.throwIfAborted(signal, { taskId, phase: 'recover' });
583
+ // Unknown original timestamps and source dirtiness stay unknown. The next
584
+ // run captures its own audit baseline; recovery never cleans either checkout.
585
+ const record = {
586
+ taskId, workspacePath: workspace, sourcePath: source, baseHead: head,
587
+ isolated: true, detachedVerified: true, state: WORKTREE_STATES.awaitingHostReview,
588
+ createdAt: null, completedAt: null, sourcePreexistingChanges: null,
589
+ };
590
+ this.trees.set(normalizeKey(workspace), record);
591
+ return this.view(record);
592
+ }
593
+
594
+ /**
595
+ * Remove one tree at a host's explicit request.
596
+ *
597
+ * Refuses while the tree is still `active` unless the caller states the tree
598
+ * was reviewed: deleting a tree a run is still using, or one nobody looked at,
599
+ * would destroy the only evidence of what the run changed.
600
+ * @param {string} workspacePath - tree path.
601
+ * @param {object} [options] - `reviewed: true` asserts host review happened.
602
+ * @returns {Promise<object>} metadata of the removed tree.
603
+ */
604
+ async dispose(workspacePath, options = {}) {
605
+ const record = this.requireTree(workspacePath);
606
+ if (record.state === WORKTREE_STATES.disposed) {
607
+ throw new WorktreeError(WORKTREE_CODES.unknownTree, 'the worktree has already been disposed', { workspacePath });
608
+ }
609
+ if (record.state === WORKTREE_STATES.active && options.reviewed !== true) {
610
+ throw new WorktreeError(
611
+ WORKTREE_CODES.notReviewed,
612
+ 'the worktree is still active; mark it complete or state that it was reviewed before removing it',
613
+ { workspacePath, state: record.state },
614
+ );
615
+ }
616
+ const removed = requireResult(
617
+ await this.deps.runGit(record.sourcePath, ['worktree', 'remove', '--force', record.workspacePath]),
618
+ 'worktree remove',
619
+ );
620
+ if (removed.code !== 0) {
621
+ // The directory may already be gone; prune settles the administrative
622
+ // entry before any failure is reported.
623
+ await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
624
+ if (await pathExists(record.workspacePath)) {
625
+ throw gitFailure('worktree remove', removed);
626
+ }
627
+ } else {
628
+ await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
629
+ }
630
+ record.state = WORKTREE_STATES.disposed;
631
+ record.reviewedByHost = options.reviewed === true;
632
+ return this.view(record);
633
+ }
634
+
635
+ /**
636
+ * Resolve a managed record or refuse.
637
+ * @param {string} workspacePath - tree path.
638
+ * @returns {object} record.
639
+ */
640
+ requireTree(workspacePath) {
641
+ const record = this.trees.get(normalizeKey(workspacePath));
642
+ if (record === undefined) {
643
+ throw new WorktreeError(WORKTREE_CODES.unknownTree, 'no such managed worktree', { workspacePath });
644
+ }
645
+ return record;
646
+ }
647
+
648
+ /**
649
+ * Project a record for callers: metadata only, no content, no error text.
650
+ * @param {object} record - internal record.
651
+ * @returns {object} metadata view.
652
+ */
653
+ view(record) {
654
+ return {
655
+ taskId: record.taskId,
656
+ workspacePath: record.workspacePath,
657
+ sourcePath: record.sourcePath,
658
+ baseHead: record.baseHead,
659
+ isolated: record.isolated === true,
660
+ detached: record.detachedVerified === true,
661
+ state: record.state,
662
+ createdAt: record.createdAt,
663
+ completedAt: record.completedAt,
664
+ sourcePreexistingChanges: record.sourcePreexistingChanges,
665
+ disposable: record.state !== WORKTREE_STATES.disposed,
666
+ };
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Normalize a path for use as a registry key. Case-folded on Windows, where the
672
+ * filesystem is case-insensitive.
673
+ * @param {string} workspacePath - path.
674
+ * @returns {string} key.
675
+ */
676
+ function normalizeKey(workspacePath) {
677
+ const normalized = String(workspacePath).replace(/[\\/]+$/, '');
678
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
679
+ }