dsh-taskbridge 0.0.0-stage → 1.3.1
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/CHANGELOG.md +754 -0
- package/LICENSE +21 -0
- package/README.md +624 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-delegate.toml +245 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +32 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +922 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +293 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +220 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +135 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3260 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +454 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3609 -0
- package/src/jobs/history.js +1467 -0
- package/src/mcp/server.js +1820 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1738 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1103 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,613 @@
|
|
|
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 { 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, which is honest — a forgotten tree is still on
|
|
131
|
+
* disk and still reviewable, and the alternative (silently deleting trees at
|
|
132
|
+
* startup) would destroy evidence.
|
|
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
|
+
* Remove one tree at a host's explicit request.
|
|
530
|
+
*
|
|
531
|
+
* Refuses while the tree is still `active` unless the caller states the tree
|
|
532
|
+
* was reviewed: deleting a tree a run is still using, or one nobody looked at,
|
|
533
|
+
* would destroy the only evidence of what the run changed.
|
|
534
|
+
* @param {string} workspacePath - tree path.
|
|
535
|
+
* @param {object} [options] - `reviewed: true` asserts host review happened.
|
|
536
|
+
* @returns {Promise<object>} metadata of the removed tree.
|
|
537
|
+
*/
|
|
538
|
+
async dispose(workspacePath, options = {}) {
|
|
539
|
+
const record = this.requireTree(workspacePath);
|
|
540
|
+
if (record.state === WORKTREE_STATES.disposed) {
|
|
541
|
+
throw new WorktreeError(WORKTREE_CODES.unknownTree, 'the worktree has already been disposed', { workspacePath });
|
|
542
|
+
}
|
|
543
|
+
if (record.state === WORKTREE_STATES.active && options.reviewed !== true) {
|
|
544
|
+
throw new WorktreeError(
|
|
545
|
+
WORKTREE_CODES.notReviewed,
|
|
546
|
+
'the worktree is still active; mark it complete or state that it was reviewed before removing it',
|
|
547
|
+
{ workspacePath, state: record.state },
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
const removed = requireResult(
|
|
551
|
+
await this.deps.runGit(record.sourcePath, ['worktree', 'remove', '--force', record.workspacePath]),
|
|
552
|
+
'worktree remove',
|
|
553
|
+
);
|
|
554
|
+
if (removed.code !== 0) {
|
|
555
|
+
// The directory may already be gone; prune settles the administrative
|
|
556
|
+
// entry before any failure is reported.
|
|
557
|
+
await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
|
|
558
|
+
if (await pathExists(record.workspacePath)) {
|
|
559
|
+
throw gitFailure('worktree remove', removed);
|
|
560
|
+
}
|
|
561
|
+
} else {
|
|
562
|
+
await this.deps.runGit(record.sourcePath, ['worktree', 'prune']).catch(() => {});
|
|
563
|
+
}
|
|
564
|
+
record.state = WORKTREE_STATES.disposed;
|
|
565
|
+
record.reviewedByHost = options.reviewed === true;
|
|
566
|
+
return this.view(record);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Resolve a managed record or refuse.
|
|
571
|
+
* @param {string} workspacePath - tree path.
|
|
572
|
+
* @returns {object} record.
|
|
573
|
+
*/
|
|
574
|
+
requireTree(workspacePath) {
|
|
575
|
+
const record = this.trees.get(normalizeKey(workspacePath));
|
|
576
|
+
if (record === undefined) {
|
|
577
|
+
throw new WorktreeError(WORKTREE_CODES.unknownTree, 'no such managed worktree', { workspacePath });
|
|
578
|
+
}
|
|
579
|
+
return record;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Project a record for callers: metadata only, no content, no error text.
|
|
584
|
+
* @param {object} record - internal record.
|
|
585
|
+
* @returns {object} metadata view.
|
|
586
|
+
*/
|
|
587
|
+
view(record) {
|
|
588
|
+
return {
|
|
589
|
+
taskId: record.taskId,
|
|
590
|
+
workspacePath: record.workspacePath,
|
|
591
|
+
sourcePath: record.sourcePath,
|
|
592
|
+
baseHead: record.baseHead,
|
|
593
|
+
isolated: record.isolated === true,
|
|
594
|
+
detached: record.detachedVerified === true,
|
|
595
|
+
state: record.state,
|
|
596
|
+
createdAt: record.createdAt,
|
|
597
|
+
completedAt: record.completedAt,
|
|
598
|
+
sourcePreexistingChanges: record.sourcePreexistingChanges,
|
|
599
|
+
disposable: record.state !== WORKTREE_STATES.disposed,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Normalize a path for use as a registry key. Case-folded on Windows, where the
|
|
606
|
+
* filesystem is case-insensitive.
|
|
607
|
+
* @param {string} workspacePath - path.
|
|
608
|
+
* @returns {string} key.
|
|
609
|
+
*/
|
|
610
|
+
function normalizeKey(workspacePath) {
|
|
611
|
+
const normalized = String(workspacePath).replace(/[\\/]+$/, '');
|
|
612
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
613
|
+
}
|