dsh-taskbridge 1.7.1 → 1.8.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 (84) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -21
  3. package/README.md +733 -877
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +32 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +181 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +122 -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/conversation-placement.md +7 -6
  17. package/docs/plugin-market.md +30 -30
  18. package/docs/redaction-contract.md +170 -170
  19. package/docs/releases/1.7.0.zh.md +11 -11
  20. package/docs/releases/1.8.0.zh.md +16 -0
  21. package/docs/releases/1.8.1.zh.md +24 -0
  22. package/docs/runtime-compatibility.md +1 -1
  23. package/docs/taskbridge-upgrade.md +28 -28
  24. package/docs/taskdispatch-upgrade.md +25 -25
  25. package/docs/workspace-contract.md +538 -538
  26. package/docs/workspace-grouping.md +126 -126
  27. package/icon.svg +1 -1
  28. package/lib/client.d.ts +804 -699
  29. package/lib/client.js +7 -7
  30. package/locale/en.json +1 -1
  31. package/locale/zh.json +1 -1
  32. package/package.json +150 -144
  33. package/src/antigravity/installer.js +1068 -0
  34. package/src/antigravity/seam.js +142 -0
  35. package/src/auth/fence.js +361 -361
  36. package/src/auth/grants.js +789 -789
  37. package/src/client/api.js +266 -3
  38. package/src/client/index.jsx +224 -11
  39. package/src/client/sidebar.jsx +862 -862
  40. package/src/client/styles.js +624 -624
  41. package/src/client/task-cleanup.js +429 -304
  42. package/src/client/task-records-table.jsx +217 -217
  43. package/src/client/task-view.js +307 -307
  44. package/src/client/workspace-groups.js +482 -482
  45. package/src/client/workspaces-browser.jsx +770 -770
  46. package/src/codex/agent-ownership.js +270 -270
  47. package/src/codex/installer.js +6 -0
  48. package/src/codex/toml.js +784 -784
  49. package/src/config/defaults.js +11 -15
  50. package/src/config/redact.js +245 -245
  51. package/src/config/store.js +186 -186
  52. package/src/credentials/seam.js +202 -202
  53. package/src/http/respond.js +6 -5
  54. package/src/http/user-plane.js +83 -1
  55. package/src/index.js +25 -0
  56. package/src/jobs/diagnostics.js +15 -15
  57. package/src/jobs/engine.js +1 -0
  58. package/src/jobs/history.js +1 -1
  59. package/src/jobs/plan-store.js +1103 -1020
  60. package/src/jobs/record-cleanup.js +452 -7
  61. package/src/jobs/review-note.js +63 -63
  62. package/src/jobs/task-descriptions.js +82 -82
  63. package/src/jobs/task-display.js +73 -73
  64. package/src/jobs/task-tree.js +786 -786
  65. package/src/jobs/title.js +134 -134
  66. package/src/mcp/continuation.js +317 -317
  67. package/src/mcp/server.js +34 -27
  68. package/src/mcp/wait.js +34 -15
  69. package/src/model/connectivity.js +371 -371
  70. package/src/model/discovery.js +582 -582
  71. package/src/model/native-catalog.js +68 -68
  72. package/src/model/openai-adapter.js +671 -671
  73. package/src/model/probe.js +264 -264
  74. package/src/model/providers.js +756 -756
  75. package/src/model/routing.js +321 -321
  76. package/src/runtime/agent-runner.js +1 -0
  77. package/src/runtime/permissions.js +1619 -1619
  78. package/src/runtime/question-call.js +162 -162
  79. package/src/runtime/questions.js +909 -909
  80. package/src/runtime/session-placement.js +36 -1
  81. package/src/runtime/worker-prompt.js +61 -55
  82. package/src/workspace/audit.js +775 -775
  83. package/src/workspace/preflight.js +424 -424
  84. package/src/workspace/worktrees.js +833 -679
@@ -1,424 +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 };
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 };