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.
Files changed (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,167 @@
1
+ // Workspace coordination: mutual exclusion per workspace and an audit trail of
2
+ // what a job actually changed on disk.
3
+ //
4
+ // Two guarantees, both enforced here rather than trusted from the agent:
5
+ // 1. At most one job mutates a given workspace at a time. The lock is
6
+ // in-process, nonce-fenced and lease-bounded, so a stuck job cannot hold it
7
+ // forever and a stale release cannot free another job's lock.
8
+ // 2. What a job changed is measured by reading git state before and after, not
9
+ // by believing the agent's own summary.
10
+
11
+ import { randomUUID } from 'node:crypto';
12
+ import { realpath } from 'node:fs/promises';
13
+ import { resolve, sep } from 'node:path';
14
+
15
+ /** Lock refusal codes. */
16
+ export const LOCK_CODES = Object.freeze({
17
+ busy: 'WORKSPACE_BUSY',
18
+ invalid: 'WORKSPACE_INVALID',
19
+ });
20
+
21
+ /** An operation refused because the workspace is unavailable for it. */
22
+ export class WorkspaceError extends Error {
23
+ /**
24
+ * @param {string} code - stable machine code.
25
+ * @param {string} message - human-readable explanation.
26
+ * @param {object} [details] - bounded details.
27
+ */
28
+ constructor(code, message, details = {}) {
29
+ super(message);
30
+ this.name = 'WorkspaceError';
31
+ this.code = code;
32
+ this.details = details;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Resolve a workspace path to its real absolute path.
38
+ *
39
+ * Refuses rather than guesses: a path that does not resolve is a refusal, and
40
+ * the resolved value is what later boundary checks compare against so a symlink
41
+ * cannot be used to escape the workspace.
42
+ * @param {string} candidate - absolute workspace path.
43
+ * @returns {Promise<string>} resolved real path.
44
+ */
45
+ export async function resolveWorkspacePath(candidate) {
46
+ if (typeof candidate !== 'string' || candidate.trim() === '') {
47
+ throw new WorkspaceError(LOCK_CODES.invalid, 'a workspace path is required', {});
48
+ }
49
+ const absolute = candidate.trim();
50
+ if (!(absolute.startsWith('/') || /^[A-Za-z]:[\\/]/.test(absolute) || absolute.startsWith('\\\\'))) {
51
+ throw new WorkspaceError(LOCK_CODES.invalid, 'workspace path must be absolute', {});
52
+ }
53
+ try {
54
+ return await realpath(resolve(absolute));
55
+ } catch (error) {
56
+ throw new WorkspaceError(LOCK_CODES.invalid, 'workspace path could not be resolved', {
57
+ cause: error?.code ?? null,
58
+ });
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Whether `target` is inside `root`. Case-folded on Windows where paths are
64
+ * compared case-insensitively.
65
+ * @param {string} root - resolved workspace root.
66
+ * @param {string} target - resolved candidate path.
67
+ * @returns {boolean} true when contained (or equal).
68
+ */
69
+ export function isInside(root, target) {
70
+ const normalize = (value) => (process.platform === 'win32' ? value.toLowerCase() : value);
71
+ const base = normalize(root).replace(/[\\/]+$/, '');
72
+ const candidate = normalize(target);
73
+ if (candidate === base) return true;
74
+ const withSep = base.endsWith(sep) ? base : `${base}${sep}`;
75
+ return candidate.startsWith(withSep);
76
+ }
77
+
78
+ /**
79
+ * In-process workspace lock registry.
80
+ *
81
+ * The lock is not a file: two DSH processes would still be able to race. That
82
+ * limitation is documented in docs/native-integration-audit.md rather than
83
+ * papered over with a lockfile that looks stronger than it is.
84
+ */
85
+ export class WorkspaceLocks {
86
+ /**
87
+ * @param {object} [options] - `now` clock override and `maxHoldMs` lease.
88
+ */
89
+ constructor(options = {}) {
90
+ this.now = options.now ?? (() => Date.now());
91
+ this.maxHoldMs = options.maxHoldMs ?? 150 * 60 * 1000;
92
+ /** @type {Map<string, object>} */
93
+ this.held = new Map();
94
+ }
95
+
96
+ /**
97
+ * Acquire the lock for a workspace without waiting.
98
+ * @param {string} workspacePath - resolved absolute workspace path.
99
+ * @param {object} input - `taskId` and optional `sessionId` for diagnostics.
100
+ * @returns {object} the lease, including its nonce.
101
+ */
102
+ acquire(workspacePath, input = {}) {
103
+ const key = lockKey(workspacePath);
104
+ const existing = this.held.get(key);
105
+ if (existing !== undefined && this.now() < existing.expiresAt) {
106
+ throw new WorkspaceError(LOCK_CODES.busy, 'another job is already running in this workspace', {
107
+ taskId: existing.taskId,
108
+ since: existing.acquiredAt,
109
+ });
110
+ }
111
+ const lease = {
112
+ nonce: randomUUID(),
113
+ workspacePath,
114
+ taskId: typeof input.taskId === 'string' ? input.taskId : null,
115
+ acquiredAt: this.now(),
116
+ expiresAt: this.now() + this.maxHoldMs,
117
+ };
118
+ this.held.set(key, lease);
119
+ return { ...lease };
120
+ }
121
+
122
+ /**
123
+ * Release a lease. A release with the wrong nonce is a no-op, so one job can
124
+ * never release another job's lock.
125
+ * @param {string} workspacePath - locked workspace.
126
+ * @param {string} nonce - lease nonce returned by {@link acquire}.
127
+ * @returns {boolean} true when this call actually released the lock.
128
+ */
129
+ release(workspacePath, nonce) {
130
+ const key = lockKey(workspacePath);
131
+ const existing = this.held.get(key);
132
+ if (existing === undefined || existing.nonce !== nonce) return false;
133
+ this.held.delete(key);
134
+ return true;
135
+ }
136
+
137
+ /**
138
+ * Whether a workspace is currently locked by a live lease.
139
+ * @param {string} workspacePath - workspace to test.
140
+ * @returns {boolean} true when locked.
141
+ */
142
+ isLocked(workspacePath) {
143
+ const existing = this.held.get(lockKey(workspacePath));
144
+ if (existing === undefined) return false;
145
+ if (this.now() >= existing.expiresAt) {
146
+ this.held.delete(lockKey(workspacePath));
147
+ return false;
148
+ }
149
+ return true;
150
+ }
151
+
152
+ /**
153
+ * Drop every lease. Used on dispose: a shutdown must not leave a workspace
154
+ * unacquirable in the next process.
155
+ * @returns {number} number of leases dropped.
156
+ */
157
+ releaseAll() {
158
+ const count = this.held.size;
159
+ this.held.clear();
160
+ return count;
161
+ }
162
+ }
163
+
164
+ function lockKey(workspacePath) {
165
+ const normalized = String(workspacePath).replace(/[\\/]+$/, '');
166
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
167
+ }
@@ -0,0 +1,424 @@
1
+ // Read-only workspace preflight: the facts a dispatcher needs *before* work is
2
+ // submitted, and the isolation it should therefore ask the plugin for.
3
+ //
4
+ // Why this module exists
5
+ // ----------------------
6
+ // The isolation setting is a property of the *job*, not of the workspace, so the
7
+ // first thing that used to discover an unusable workspace was the job itself:
8
+ // `WORKTREE_SOURCE_DIRTY` arrived after a task id was allocated, a grant was
9
+ // consumed and a queue slot was taken. The dispatcher (Codex) then had to explain
10
+ // a failure whose cause it could have measured in advance — and the natural
11
+ // remedy, silently switching the job to shared isolation, is exactly the
12
+ // downgrade `docs/workspace-contract.md` forbids.
13
+ //
14
+ // So the same facts are now measurable up front, by a tool that has no side
15
+ // effects: this module runs only read-only git subcommands through the audit
16
+ // seam, and returns a *recommendation* rather than an action. It never creates a
17
+ // commit, a stash, a branch, a worktree or a task, and it is not authorization:
18
+ // the switch, the grants and the engine remain the only things that decide
19
+ // whether work runs.
20
+ //
21
+ // The decision table is deliberately small, stable and exhaustive. Every answer
22
+ // carries a `reason` code from {@link PREFLIGHT_REASONS} so a caller (and a test)
23
+ // can branch on the cause, never on human prose:
24
+ //
25
+ // git unavailable / not a repository / no commit → block
26
+ // a directory inside a work tree that is not its
27
+ // top level (a subdirectory) → block (its own stable
28
+ // reason: "this path is inside
29
+ // a repository but is not its
30
+ // root", which is why naming
31
+ // it would put a tree inside
32
+ // the user's checkout)
33
+ // clean → worktree
34
+ // dirty, `allowShared` NOT given → block (the caller must decide)
35
+ // dirty, `allowShared: true` → shared (explicit, recorded)
36
+ //
37
+ // `allowShared` is a request parameter, not a configuration default: the operator
38
+ // and the dispatcher decide per dispatch, the plugin never decides for them, and
39
+ // the answer says which of the two happened (`sharedExplicit: true`).
40
+
41
+ import { relative } from 'node:path';
42
+
43
+ import { AUDIT_CODES, AUDIT_LIMITS, createGitRunner, probeRepository, readStatus } from './audit.js';
44
+ import { LOCK_CODES, WorkspaceError, resolveWorkspacePath } from './locks.js';
45
+
46
+ /** The three isolation decisions this module can recommend. */
47
+ export const PREFLIGHT_ISOLATIONS = Object.freeze(['worktree', 'shared', 'block']);
48
+
49
+ /**
50
+ * Stable reason codes. The set is closed: a caller may switch on it, and a
51
+ * decision always names exactly one of these.
52
+ */
53
+ export const PREFLIGHT_REASONS = Object.freeze({
54
+ /** Not busy, git present, repository root, at least one commit, no changes. */
55
+ cleanRepository: 'PREFLIGHT_CLEAN_REPOSITORY',
56
+ /** The repository root can be checked out from a commit, but it has uncommitted changes. */
57
+ dirtyRepository: 'PREFLIGHT_DIRTY_REPOSITORY',
58
+ /** No `allowShared` request was made for a dirty repository, so shared is not implied. */
59
+ dirtyNeedsDecision: 'PREFLIGHT_DIRTY_NEEDS_DECISION',
60
+ /** A dirty repository was explicitly allowed to run in place. */
61
+ dirtySharedExplicit: 'PREFLIGHT_DIRTY_SHARED_EXPLICIT',
62
+ /** git could not be executed here, so no fact about the workspace could be measured. */
63
+ gitUnavailable: 'PREFLIGHT_GIT_UNAVAILABLE',
64
+ /** The path exists but is not inside a git work tree at all. */
65
+ notRepository: 'PREFLIGHT_NOT_A_REPOSITORY',
66
+ /**
67
+ * The path is inside a git work tree but is not that repository's top level.
68
+ * Naming it as the workspace would make an isolated tree land inside the user's
69
+ * checkout, so it is refused rather than recommended worktree or shared.
70
+ */
71
+ notRepositoryRoot: 'PREFLIGHT_NOT_A_REPOSITORY_ROOT',
72
+ /** The repository has no commit; a worktree can only be created from one. */
73
+ noCommits: 'PREFLIGHT_NO_COMMITS',
74
+ /** A read-only git invocation failed, so the state is unknown. */
75
+ gitFailed: 'PREFLIGHT_GIT_FAILED',
76
+ /** The path is relative, empty or cannot be resolved to a real directory. */
77
+ workspaceInvalid: 'PREFLIGHT_WORKSPACE_INVALID',
78
+ /** The path is a file rather than a directory. */
79
+ notDirectory: 'PREFLIGHT_NOT_A_DIRECTORY',
80
+ });
81
+
82
+ /** Bounds on the facts this module reports. Paths are names, never content. */
83
+ export const PREFLIGHT_LIMITS = Object.freeze({
84
+ /** Paths listed in `changedPaths`. */
85
+ changedPaths: 50,
86
+ /** Bytes of one changed path retained (a pathological filename cannot bloat a result). */
87
+ pathChars: 400,
88
+ });
89
+
90
+ /**
91
+ * One decision, as it is published.
92
+ *
93
+ * The shape is fixed here so the module, the MCP tool and the document cannot
94
+ * drift: `isolation` is the recommendation, `reason` the stable cause, `facts`
95
+ * what was measured, and the flags state **how** the recommendation was reached
96
+ * rather than only what it was.
97
+ * @param {object} options - decision inputs.
98
+ * @returns {object} published decision.
99
+ */
100
+ function decision(options) {
101
+ return {
102
+ ok: true,
103
+ // Read-only by construction: this module has no code path that writes.
104
+ readOnly: true,
105
+ workspacePath: options.workspacePath ?? null,
106
+ isolation: options.isolation,
107
+ reason: options.reason,
108
+ // Whether the recommendation came from an explicit request instead of the
109
+ // repository being clean. A caller can therefore tell "worktree because clean"
110
+ // from "shared because I said so", which are different audit stories.
111
+ sharedExplicit: options.sharedExplicit === true,
112
+ // True when shared isolation is genuinely usable for a dirty checkout AND the
113
+ // caller has to say so. False when there is nothing to decide.
114
+ decisionRequired: options.decisionRequired === true,
115
+ facts: {
116
+ gitAvailable: options.facts?.gitAvailable === true,
117
+ repository: options.facts?.repository === true,
118
+ hasCommits: options.facts?.hasCommits === true,
119
+ clean: typeof options.facts?.clean === 'boolean' ? options.facts.clean : null,
120
+ head: typeof options.facts?.head === 'string' ? options.facts.head : null,
121
+ changedFiles: Number.isSafeInteger(options.facts?.changedFiles) ? options.facts.changedFiles : 0,
122
+ changedPaths: Array.isArray(options.facts?.changedPaths) ? options.facts.changedPaths : [],
123
+ changedPathsTruncated: options.facts?.changedPathsTruncated === true,
124
+ // Sensitive names are reported by name only — the operator must know a
125
+ // credential file was touched — and their content is never read.
126
+ sensitivePaths: Array.isArray(options.facts?.sensitivePaths) ? options.facts.sensitivePaths : [],
127
+ },
128
+ // What the caller must do next, in one sentence. Never a route override.
129
+ guidance: options.guidance ?? null,
130
+ checkedAt: options.now,
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Classify one failure into the reason code and the facts that are still known.
136
+ *
137
+ * A failed probe is not an empty probe: `gitAvailable`/`repository`/`hasCommits`
138
+ * stay false, `clean` stays `null` (unknown, not "true"), and every caller of
139
+ * {@link preflightWorkspace} gets the same shape.
140
+ * @param {unknown} error - the thrown audit/workspace error.
141
+ * @returns {{ reason: string, message: string }} normalized failure.
142
+ */
143
+ function classify(error) {
144
+ const code = typeof error?.code === 'string' ? error.code : '';
145
+ if (code === AUDIT_CODES.gitUnavailable) {
146
+ return {
147
+ reason: PREFLIGHT_REASONS.gitUnavailable,
148
+ message: 'git is not executable in this environment, so the workspace cannot be inspected',
149
+ };
150
+ }
151
+ if (code === AUDIT_CODES.notRepositoryRoot) {
152
+ return { reason: PREFLIGHT_REASONS.notRepositoryRoot, message: notRootMessage(error) };
153
+ }
154
+ if (code === AUDIT_CODES.notRepository) {
155
+ return { reason: PREFLIGHT_REASONS.notRepository, message: 'the workspace is not inside a git repository' };
156
+ }
157
+ if (code === AUDIT_CODES.noCommits) {
158
+ return { reason: PREFLIGHT_REASONS.noCommits, message: 'the repository has no commit yet' };
159
+ }
160
+ if (code === AUDIT_CODES.gitFailed) {
161
+ return { reason: PREFLIGHT_REASONS.gitFailed, message: 'a read-only git invocation failed while inspecting the workspace' };
162
+ }
163
+ if (code === LOCK_CODES.invalid) {
164
+ return { reason: PREFLIGHT_REASONS.workspaceInvalid, message: 'the workspace path could not be resolved to a real directory' };
165
+ }
166
+ return {
167
+ reason: PREFLIGHT_REASONS.gitFailed,
168
+ message: 'the workspace could not be inspected',
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Guidance for a path that is inside a repository but is not its top level.
174
+ *
175
+ * The message must not suggest worktree or shared isolation, because neither is
176
+ * safe for such a path: both would place agent writes somewhere under the user's
177
+ * checkout. Only naming the repository root is a remedy, so only that is said.
178
+ * @param {unknown} error - the audit error carrying `details.topLevel`.
179
+ * @returns {string} one operator-facing sentence.
180
+ */
181
+ function notRootMessage(error) {
182
+ const topLevel = typeof error?.details?.topLevel === 'string' ? error.details.topLevel : '';
183
+ const base = 'the workspace path is inside a git repository but is not its root';
184
+ return topLevel === '' ? base : `${base}; name the repository root ${topLevel} instead`;
185
+ }
186
+
187
+ /**
188
+ * Bound one reported path.
189
+ * @param {string} value - repository-relative path.
190
+ * @returns {string} bounded path.
191
+ */
192
+ function boundPath(value) {
193
+ const text = String(value ?? '');
194
+ if (text.length <= PREFLIGHT_LIMITS.pathChars) return text;
195
+ return `${text.slice(0, PREFLIGHT_LIMITS.pathChars)}…`;
196
+ }
197
+
198
+ /**
199
+ * Inspect one workspace read-only and recommend an isolation.
200
+ *
201
+ * Nothing in this function writes: no commit, no stash, no worktree, no task, no
202
+ * lock, no settings change. The runs are the read-only subcommands
203
+ * `git --version`, `git rev-parse --is-inside-work-tree`, `git rev-parse
204
+ * --show-toplevel`, `git rev-parse --verify HEAD` and `git status
205
+ * --porcelain=v1 -z --untracked-files=all`, all issued through the audit seam's
206
+ * argv runner with `shell: false`. The top-level read is what distinguishes the
207
+ * repository root (which may be inspected) from a subdirectory inside it (which
208
+ * is refused).
209
+ * @param {object} [deps] - dependency object; `runGit` defaults to the audit runner.
210
+ * Tests inject a failing runner to prove the refusal paths.
211
+ * @param {object} request - `workspacePath` (absolute), optional `allowShared`.
212
+ * @returns {Promise<object>} the decision described by {@link PREFLIGHT_REASONS}.
213
+ */
214
+ export async function preflightWorkspace(deps = {}, request = {}) {
215
+ const now = Date.now();
216
+ const runGit = typeof deps?.runGit === 'function' ? deps.runGit : createGitRunner();
217
+ const allowShared = request?.allowShared === true;
218
+
219
+ // The absolute-path, resolution and directory checks are the ones the engine
220
+ // applies (`resolveWorkspacePath`), so a preflight that answers `worktree` can
221
+ // never be rejected by the job for naming a path the engine cannot use.
222
+ let workspacePath;
223
+ try {
224
+ workspacePath = await resolveWorkspacePath(request?.workspacePath);
225
+ } catch (error) {
226
+ const failure = classify(error);
227
+ return decision({
228
+ workspacePath: null,
229
+ isolation: 'block',
230
+ reason: failure.reason,
231
+ facts: { gitAvailable: false, repository: false, hasCommits: false, clean: null, changedFiles: 0 },
232
+ guidance: `${failure.message}; name an absolute path to an existing workspace directory`,
233
+ now,
234
+ });
235
+ }
236
+
237
+ // A file is not a directory. `probeRepository` would answer "not a repository"
238
+ // for it, which is true but hides the actual mistake, so it is distinguished.
239
+ const kind = await describeStart(workspacePath);
240
+ if (kind !== 'directory') {
241
+ return decision({
242
+ workspacePath,
243
+ isolation: 'block',
244
+ reason: PREFLIGHT_REASONS.notDirectory,
245
+ facts: { gitAvailable: false, repository: false, hasCommits: false, clean: null, changedFiles: 0 },
246
+ guidance: 'the workspace path is not a directory',
247
+ now,
248
+ });
249
+ }
250
+
251
+ let facts;
252
+ try {
253
+ facts = await probeRepository(runGit, workspacePath);
254
+ } catch (error) {
255
+ const failure = classify(error);
256
+ return blockFor(workspacePath, failure, now);
257
+ }
258
+
259
+ if (!facts.git) {
260
+ return blockFor(workspacePath, classify({ code: AUDIT_CODES.gitUnavailable }), now);
261
+ }
262
+ if (!facts.repository) {
263
+ return blockFor(workspacePath, classify({ code: AUDIT_CODES.notRepository }), now, {
264
+ gitAvailable: true,
265
+ });
266
+ }
267
+ // A path inside a work tree is not the same workspace as that work tree. The
268
+ // engine creates an isolated tree *for the supplied path*, so a subdirectory
269
+ // would put the agent's checkout inside the user's repository — the exact
270
+ // placement `WorktreeManager` refuses. The canonical top level is measured by
271
+ // `git rev-parse --show-toplevel`, so this is decided from git, not from string
272
+ // comparison against the supplied path.
273
+ if (!facts.workTreeRoot) {
274
+ return blockFor(
275
+ workspacePath,
276
+ classify({ code: AUDIT_CODES.notRepositoryRoot, details: { topLevel: facts.topLevel ?? null } }),
277
+ now,
278
+ { gitAvailable: true, repository: true },
279
+ );
280
+ }
281
+ if (!facts.hasCommits) {
282
+ return blockFor(workspacePath, classify({ code: AUDIT_CODES.noCommits }), now, {
283
+ gitAvailable: true,
284
+ repository: true,
285
+ });
286
+ }
287
+
288
+ let status;
289
+ try {
290
+ status = await readStatus({ runGit }, workspacePath, { limit: PREFLIGHT_LIMITS.changedPaths });
291
+ } catch (error) {
292
+ const failure = classify(error);
293
+ return blockFor(workspacePath, failure, now, {
294
+ gitAvailable: true,
295
+ repository: true,
296
+ hasCommits: true,
297
+ head: facts.head,
298
+ });
299
+ }
300
+
301
+ const changedPaths = status.entries.slice(0, PREFLIGHT_LIMITS.changedPaths).map((entry) => boundPath(entry.path));
302
+ const sensitivePaths = uniqSorted(status.entries.flatMap((entry) => {
303
+ const names = [];
304
+ if (entry.sensitive === true) names.push(entry.path);
305
+ return names;
306
+ })).map(boundPath).slice(0, PREFLIGHT_LIMITS.changedPaths);
307
+ const measured = {
308
+ gitAvailable: true,
309
+ repository: true,
310
+ hasCommits: true,
311
+ head: typeof facts.head === 'string' ? facts.head : null,
312
+ changedFiles: status.total,
313
+ changedPaths,
314
+ // A path list shorter than the count is stated as truncated, never implied
315
+ // complete: "this list is short" must not read as "this list was short".
316
+ changedPathsTruncated: status.total > changedPaths.length,
317
+ sensitivePaths,
318
+ };
319
+
320
+ if (status.total === 0) {
321
+ // A dirty source is refused by the worktree manager, so only a clean one may
322
+ // take that route. This is the same condition, measured earlier.
323
+ return decision({
324
+ workspacePath,
325
+ isolation: 'worktree',
326
+ reason: PREFLIGHT_REASONS.cleanRepository,
327
+ facts: { ...measured, clean: true },
328
+ guidance: 'the repository is clean; worktree isolation can be prepared from its current commit',
329
+ now,
330
+ });
331
+ }
332
+
333
+ if (allowShared !== true) {
334
+ // No implicit downgrade: a dirty checkout blocks until a human or the
335
+ // coordinator decides that running in place is acceptable for this dispatch.
336
+ return decision({
337
+ workspacePath,
338
+ isolation: 'block',
339
+ reason: PREFLIGHT_REASONS.dirtyNeedsDecision,
340
+ decisionRequired: true,
341
+ facts: { ...measured, clean: false },
342
+ guidance: 'the repository has uncommitted changes, so worktree isolation would fail; '
343
+ + 'commit them, or make the shared-isolation decision explicitly (allowShared) and record why',
344
+ now,
345
+ });
346
+ }
347
+
348
+ return decision({
349
+ workspacePath,
350
+ isolation: 'shared',
351
+ reason: PREFLIGHT_REASONS.dirtySharedExplicit,
352
+ sharedExplicit: true,
353
+ facts: { ...measured, clean: false },
354
+ guidance: 'the repository has uncommitted changes and shared isolation was explicitly allowed; '
355
+ + 'the delegated run will mutate this checkout in place, and unrelated changes must be preserved',
356
+ now,
357
+ });
358
+ }
359
+
360
+ /**
361
+ * Build a `block` decision from a normalized failure.
362
+ * @param {string} workspacePath - resolved workspace path.
363
+ * @param {{reason: string, message: string}} failure - normalized failure.
364
+ * @param {number} now - timestamp.
365
+ * @param {object} [known] - facts that were already established.
366
+ * @returns {object} decision.
367
+ */
368
+ function blockFor(workspacePath, failure, now, known = {}) {
369
+ return decision({
370
+ workspacePath,
371
+ isolation: 'block',
372
+ reason: failure.reason,
373
+ facts: {
374
+ gitAvailable: known.gitAvailable === true,
375
+ repository: known.repository === true,
376
+ hasCommits: known.hasCommits === true,
377
+ clean: null,
378
+ head: typeof known.head === 'string' ? known.head : null,
379
+ changedFiles: 0,
380
+ },
381
+ guidance: failure.message,
382
+ now,
383
+ });
384
+ }
385
+
386
+ /**
387
+ * Whether one resolved path is a directory or something else.
388
+ * @param {string} target - resolved absolute path.
389
+ * @returns {Promise<'directory' | 'other'>} the kind of entry found.
390
+ */
391
+ async function describeStart(target) {
392
+ // The audit module's inspector is not exported for this purpose and the check
393
+ // here is one `lstat`; it is done locally so the preflight stays dependency-light.
394
+ const { lstat } = await import('node:fs/promises');
395
+ try {
396
+ const info = await lstat(target);
397
+ return info.isDirectory() ? 'directory' : 'other';
398
+ } catch {
399
+ return 'other';
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Sorted unique copy of a list of strings.
405
+ * @param {string[]} values - values.
406
+ * @returns {string[]} sorted unique values.
407
+ */
408
+ function uniqSorted(values) {
409
+ return [...new Set(values)].sort();
410
+ }
411
+
412
+ /**
413
+ * The repository-relative path of a workspace, for a caller that wants to key
414
+ * something by it. Exported so the MCP tool does not re-implement containment.
415
+ * @param {string} root - repository root.
416
+ * @param {string} target - candidate path.
417
+ * @returns {string} relative path, or `''` when they are the same directory.
418
+ */
419
+ export function relativeTo(root, target) {
420
+ return relative(root, target);
421
+ }
422
+
423
+ /** Re-exported so a caller can report the same bound the audit layer uses. */
424
+ export { AUDIT_LIMITS };