dsh-taskbridge 0.0.0-stage → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -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-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -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 +138 -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 +3299 -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 +456 -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 +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,775 @@
1
+ // Git-backed workspace inspection.
2
+ //
3
+ // What a job changed is measured, not reported: this module reads git state
4
+ // before and after the run and records the delta as evidence. It never trusts
5
+ // the agent's summary, and it reads only read-only git subcommands — nothing
6
+ // here can mutate the repository it is auditing.
7
+ //
8
+ // Three invariants make the evidence trustworthy:
9
+ // 1. The comparison point is pinned. `captureBaseline` records the commit the
10
+ // job started from and `captureDiff` compares against *that* commit, never
11
+ // against the mutable `HEAD` the agent may have moved.
12
+ // 2. Filenames are parsed from NUL-delimited output. `-z` is the only git
13
+ // status/diff format that is unambiguous for spaces, quotes, backslashes and
14
+ // non-ASCII bytes; the line format rewrites names and would mis-attribute a
15
+ // change to a file that does not exist.
16
+ // 3. Sensitive paths are filtered *before* the diff is produced. A credential
17
+ // file's name is reported, its content is never read into this process.
18
+ //
19
+ // A capability check is not a formality. If git is unavailable, or git fails
20
+ // where evidence is required, this module refuses rather than reporting an
21
+ // empty diff — "no changes" and "could not tell" must never look alike.
22
+
23
+ import { execFile } from 'node:child_process';
24
+ import { lstat } from 'node:fs/promises';
25
+ import { resolve as resolvePath, win32 } from 'node:path';
26
+
27
+ import { isSensitivePath, redactText } from '../config/redact.js';
28
+ import { isInside } from './locks.js';
29
+
30
+ /** Bounds that keep evidence payloads reviewable and reads finite. */
31
+ export const AUDIT_LIMITS = Object.freeze({
32
+ /** Changed files listed in the evidence. */
33
+ files: 500,
34
+ /** Status records parsed; beyond this the list is truncated, not trusted. */
35
+ statusEntries: 2000,
36
+ /** Patch bytes retained. */
37
+ patchBytes: 64 * 1024,
38
+ /** Untracked files whose content may be rendered into the patch. */
39
+ patchFiles: 50,
40
+ /** Sensitive exclusions handed to one git invocation. */
41
+ sensitivePaths: 100,
42
+ /** numstat rows retained. */
43
+ statLines: 200,
44
+ /** Per-invocation git timeout. */
45
+ gitTimeoutMs: 8000,
46
+ /** Per-invocation stdout/stderr ceiling. */
47
+ gitMaxBytes: 8 * 1024 * 1024,
48
+ /** Stderr bytes quoted in a refusal. */
49
+ stderrBytes: 400,
50
+ /** Paths quoted in a refusal message. */
51
+ samplePaths: 20,
52
+ });
53
+
54
+ /** Audit failure codes, each mapped to an operator-visible explanation. */
55
+ export const AUDIT_CODES = Object.freeze({
56
+ gitUnavailable: 'AUDIT_GIT_UNAVAILABLE',
57
+ notRepository: 'AUDIT_NOT_A_REPOSITORY',
58
+ noCommits: 'AUDIT_NO_COMMITS',
59
+ gitFailed: 'AUDIT_GIT_FAILED',
60
+ baselineInvalid: 'AUDIT_BASELINE_INVALID',
61
+ notRepositoryRoot: 'AUDIT_NOT_A_REPOSITORY_ROOT',
62
+ });
63
+
64
+ /** Raised when the workspace cannot be audited. */
65
+ export class AuditError extends Error {
66
+ /**
67
+ * @param {string} code - stable machine code.
68
+ * @param {string} message - human-readable explanation.
69
+ * @param {object} [details] - bounded details.
70
+ */
71
+ constructor(code, message, details = {}) {
72
+ super(message);
73
+ this.name = 'AuditError';
74
+ this.code = code;
75
+ this.details = details;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Default git runner.
81
+ *
82
+ * `shell: false` with an explicit argv keeps the workspace path out of a shell
83
+ * parse, and a hard timeout keeps a hung git invocation from wedging a job. A
84
+ * sandbox that denies process creation surfaces as `AUDIT_GIT_UNAVAILABLE`,
85
+ * which callers must treat as a refusal, not as "no changes".
86
+ *
87
+ * `stdout` is returned byte-faithfully: the `-z` parsers below depend on NUL
88
+ * delimiters and on the absence of any newline translation.
89
+ * @param {object} [options] - `timeoutMs` override (tests use a shorter bound).
90
+ * @returns {(cwd: string, args: string[]) => Promise<{stdout: string, stderr: string, code: number}>} runner.
91
+ */
92
+ export function createGitRunner(options = {}) {
93
+ const timeout = Number.isSafeInteger(options.timeoutMs) && options.timeoutMs > 0
94
+ ? options.timeoutMs
95
+ : AUDIT_LIMITS.gitTimeoutMs;
96
+ return function runGit(cwd, args) {
97
+ return new Promise((resolvePromise, rejectPromise) => {
98
+ let launched;
99
+ try {
100
+ launched = execFile(
101
+ 'git',
102
+ ['-c', 'core.quotepath=false', ...args],
103
+ {
104
+ cwd,
105
+ encoding: 'utf8',
106
+ timeout,
107
+ maxBuffer: AUDIT_LIMITS.gitMaxBytes,
108
+ shell: false,
109
+ windowsHide: true,
110
+ },
111
+ (error, stdout, stderr) => {
112
+ const out = String(stdout ?? '');
113
+ const err = String(stderr ?? '');
114
+ if (error === null || error === undefined) {
115
+ resolvePromise({ stdout: out, stderr: err, code: 0 });
116
+ return;
117
+ }
118
+ const code = typeof error.code === 'number' ? error.code : null;
119
+ if (code === 0) {
120
+ resolvePromise({ stdout: out, stderr: err, code: 0 });
121
+ return;
122
+ }
123
+ // A sandbox that denies spawning looks like a missing git; both are
124
+ // "git cannot be used here", which is a refusal.
125
+ const denied = denyProcessCreation(error);
126
+ if (denied !== null) {
127
+ rejectPromise(new AuditError(AUDIT_CODES.gitUnavailable, 'git is not executable in this environment', { cause: denied }));
128
+ return;
129
+ }
130
+ if (code !== null) {
131
+ // A git-level failure is data, not an exception: callers inspect it.
132
+ resolvePromise({ stdout: out, stderr: err, code });
133
+ return;
134
+ }
135
+ rejectPromise(new AuditError(AUDIT_CODES.gitFailed, 'git could not be executed', {
136
+ cause: typeof error.code === 'string' ? error.code : null,
137
+ }));
138
+ },
139
+ );
140
+ } catch (error) {
141
+ // Some confined sandboxes deny process creation synchronously
142
+ // (`spawn EPERM`). That is the same refusal, not a crash.
143
+ const denied = denyProcessCreation(error);
144
+ rejectPromise(denied === null
145
+ ? new AuditError(AUDIT_CODES.gitFailed, 'git could not be executed', { cause: typeof error?.code === 'string' ? error.code : null })
146
+ : new AuditError(AUDIT_CODES.gitUnavailable, 'git is not executable in this environment', { cause: denied }));
147
+ return;
148
+ }
149
+ // The child is not needed here; kept for symmetry with execFile's return.
150
+ void launched;
151
+ });
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Classify a spawn-level failure.
157
+ * @param {object} error - execFile error.
158
+ * @returns {string | null} the denied errno, or null when git actually ran.
159
+ */
160
+ function denyProcessCreation(error) {
161
+ const code = typeof error?.code === 'string' ? error.code : '';
162
+ if (code === 'EPERM' || code === 'EACCES' || code === 'ENOENT') return code;
163
+ return null;
164
+ }
165
+
166
+ /**
167
+ * Build a refusal from a failed git invocation.
168
+ *
169
+ * Only bounded, redacted stderr is quoted: a git error message never belongs in
170
+ * a job record in full, and it must not carry file content.
171
+ * @param {string} step - which read failed.
172
+ * @param {object} result - runner result.
173
+ * @returns {AuditError} refusal to throw.
174
+ */
175
+ function gitFailure(step, result) {
176
+ const stderr = redactText(String(result?.stderr ?? '')).trim().slice(0, AUDIT_LIMITS.stderrBytes);
177
+ return new AuditError(AUDIT_CODES.gitFailed, `git ${step} failed`, {
178
+ step,
179
+ exitCode: typeof result?.code === 'number' ? result.code : null,
180
+ stderr,
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Validate that a runner returned the shape this module parses.
186
+ * @param {unknown} result - runner result.
187
+ * @param {string} step - which read produced it.
188
+ * @returns {{stdout: string, stderr: string, code: number}} result.
189
+ */
190
+ function requireResult(result, step) {
191
+ if (result === null || typeof result !== 'object' || typeof result.stdout !== 'string' || typeof result.code !== 'number') {
192
+ throw new AuditError(AUDIT_CODES.gitFailed, `the git runner returned no usable result for ${step}`, { step });
193
+ }
194
+ return { stdout: result.stdout, stderr: typeof result.stderr === 'string' ? result.stderr : '', code: result.code };
195
+ }
196
+
197
+ /**
198
+ * Measure the canonical top level of the repository that contains a path.
199
+ *
200
+ * This is the one read that answers "which directory is this workspace's
201
+ * repository?", and it is deliberately separate from {@link probeRepository}:
202
+ * containment decisions (is this path the repository itself? is a worktree root
203
+ * anywhere inside that repository?) need the top level even when the named path
204
+ * is a subdirectory, and they need it before any write.
205
+ *
206
+ * `--show-toplevel` is read-only and reports an absolute path with symbolic path
207
+ * components resolved, which is why the result is compared against real paths.
208
+ * The value is never returned unless git exited successfully with non-empty
209
+ * output: "could not tell" must not look like "no repository".
210
+ * @param {(cwd: string, args: string[]) => Promise<{stdout: string, code: number}>} runGit - runner.
211
+ * @param {string} workspacePath - resolved workspace path (may be a subdirectory).
212
+ * @returns {Promise<string | null>} real top-level directory, or null when this
213
+ * path is not inside a git work tree.
214
+ */
215
+ export async function readRepositoryTopLevel(runGit, workspacePath) {
216
+ const runner = normalizeRunner(runGit);
217
+ const result = requireResult(
218
+ await runner(workspacePath, ['rev-parse', '--show-toplevel']),
219
+ 'rev-parse --show-toplevel',
220
+ );
221
+ if (result.code !== 0) return null;
222
+ const topLevel = result.stdout.trim();
223
+ return topLevel === '' ? null : topLevel;
224
+ }
225
+
226
+ /**
227
+ * Probe whether a directory is a git work tree with at least one commit.
228
+ *
229
+ * `facts.repository` is true for any directory *inside* a work tree, not only
230
+ * for its root; `facts.workTreeRoot` records whether the named path is itself
231
+ * the top level. Callers that require a repository root — the preflight and the
232
+ * worktree manager both do — must read `workTreeRoot` (or compare against
233
+ * {@link readRepositoryTopLevel}) rather than `repository`.
234
+ *
235
+ * The top-level read is skipped when the path is not a work tree, so a
236
+ * non-repository workspace still costs two invocations and no more.
237
+ * @param {(cwd: string, args: string[]) => Promise<{stdout: string, code: number}>} runGit - runner.
238
+ * @param {string} workspacePath - resolved workspace path.
239
+ * @returns {Promise<{ git: boolean, repository: boolean, workTreeRoot: boolean, topLevel: string | null, hasCommits: boolean, head: string | null }>} facts.
240
+ */
241
+ export async function probeRepository(runGit, workspacePath) {
242
+ const runner = normalizeRunner(runGit);
243
+ const facts = {
244
+ git: false,
245
+ repository: false,
246
+ workTreeRoot: false,
247
+ topLevel: null,
248
+ hasCommits: false,
249
+ head: null,
250
+ };
251
+ const version = requireResult(await runner(workspacePath, ['--version']), '--version');
252
+ facts.git = version.code === 0;
253
+ if (!facts.git) return facts;
254
+ const inside = requireResult(await runner(workspacePath, ['rev-parse', '--is-inside-work-tree']), 'rev-parse');
255
+ // A work tree that is itself a nested repository inside another checkout still
256
+ // answers `true`, and so does any directory inside a work tree. Containment
257
+ // guards therefore use the top level, never this flag alone.
258
+ facts.repository = inside.code === 0 && inside.stdout.trim() === 'true';
259
+ if (!facts.repository) return facts;
260
+ // The canonical top level: what a containment decision must compare against.
261
+ facts.topLevel = await readRepositoryTopLevel(runner, workspacePath);
262
+ const head = requireResult(await runner(workspacePath, ['rev-parse', '--verify', 'HEAD']), 'rev-parse --verify HEAD');
263
+ if (head.code === 0) {
264
+ const sha = head.stdout.trim();
265
+ if (sha !== '') {
266
+ facts.hasCommits = true;
267
+ facts.head = sha;
268
+ }
269
+ }
270
+ // Only a path that resolves to the same directory as the measured top level is
271
+ // a repository root. An unmeasurable top level is never assumed to be the
272
+ // workspace: "could not tell" must not read as "this is the root".
273
+ facts.workTreeRoot = facts.topLevel !== null && samePath(facts.topLevel, workspacePath);
274
+ return facts;
275
+ }
276
+
277
+ /**
278
+ * Whether two paths name the same directory, comparing real paths.
279
+ *
280
+ * Case-folded on Windows, where the filesystem is case-insensitive; both sides
281
+ * are expected to be real paths already (`realpath` / `--show-toplevel`).
282
+ * @param {string} left - absolute path.
283
+ * @param {string} right - absolute path.
284
+ * @returns {boolean} true when they are the same path.
285
+ */
286
+ function samePath(left, right) {
287
+ if (process.platform === 'win32') {
288
+ return win32.normalize(String(left)).toLowerCase() === win32.normalize(String(right)).toLowerCase();
289
+ }
290
+ const trimTrailingSeparators = (value) => String(value).replace(/[\\/]+$/, '');
291
+ return trimTrailingSeparators(left) === trimTrailingSeparators(right);
292
+ }
293
+
294
+ /**
295
+ * Whether a porcelain status code describes a rename or a copy, which is the
296
+ * only case where git emits a second path.
297
+ * @param {string} code - two-character `XY` status.
298
+ * @returns {boolean} true when an original path follows.
299
+ */
300
+ function isRenameOrCopy(code) {
301
+ return code.includes('R') || code.includes('C');
302
+ }
303
+
304
+ /**
305
+ * Map a porcelain status code to a reviewer-facing verb.
306
+ * @param {string} code - `XY` code.
307
+ * @returns {string} verb.
308
+ */
309
+ function describeStatus(code) {
310
+ if (code === '??') return 'added';
311
+ if (code.includes('R')) return 'renamed';
312
+ if (code.includes('C')) return 'copied';
313
+ if (code.includes('D')) return 'deleted';
314
+ if (code.includes('A')) return 'added';
315
+ if (code.includes('M')) return 'modified';
316
+ if (code.includes('U') || code === 'AA' || code === 'DD') return 'conflicted';
317
+ return 'changed';
318
+ }
319
+
320
+ /**
321
+ * Parse `git status --porcelain=v1 -z` output.
322
+ *
323
+ * In `-z` form no path is ever quoted or escaped: records are NUL-terminated and
324
+ * a rename/copy record is followed by one extra NUL-terminated token holding the
325
+ * *original* path (new path first). Both paths are retained because either one
326
+ * can name credential material, and the old path is exactly what a rename-based
327
+ * leak would otherwise hide.
328
+ * @param {string} stdout - raw stdout.
329
+ * @param {number} [limit] - maximum records retained.
330
+ * @returns {{entries: object[], total: number, truncated: boolean}} parsed status.
331
+ */
332
+ export function parseStatusZ(stdout, limit = AUDIT_LIMITS.statusEntries) {
333
+ const text = typeof stdout === 'string' ? stdout : '';
334
+ if (text === '') return { entries: [], total: 0, truncated: false };
335
+ if (!text.includes('\0')) {
336
+ // Without NUL delimiters filenames have been rewritten or quoted; guessing
337
+ // would silently mis-attribute a change, so this is a refusal.
338
+ throw new AuditError(AUDIT_CODES.gitFailed, 'git status did not return the requested NUL-delimited format', {
339
+ step: 'status',
340
+ });
341
+ }
342
+ const tokens = text.split('\0');
343
+ const entries = [];
344
+ let total = 0;
345
+ for (let index = 0; index < tokens.length; index += 1) {
346
+ const token = tokens[index];
347
+ if (token === '') continue;
348
+ if (token.length < 3) continue;
349
+ const code = token.slice(0, 2);
350
+ const path = token[2] === ' ' ? token.slice(3) : token.slice(2);
351
+ if (path === '') continue;
352
+ let from = null;
353
+ if (isRenameOrCopy(code)) {
354
+ const candidate = tokens[index + 1];
355
+ if (typeof candidate === 'string' && candidate !== '') {
356
+ from = candidate;
357
+ index += 1;
358
+ }
359
+ }
360
+ total += 1;
361
+ if (entries.length >= limit) continue;
362
+ entries.push({
363
+ code,
364
+ path,
365
+ from,
366
+ status: describeStatus(code),
367
+ // Either side being sensitive is enough to withhold the rename patch.
368
+ sensitive: isSensitivePath(path) || (from !== null && isSensitivePath(from)),
369
+ });
370
+ }
371
+ return { entries, total, truncated: total > entries.length };
372
+ }
373
+
374
+ /**
375
+ * Read the workspace status in NUL-delimited porcelain v1 format.
376
+ * @param {object} deps - `runGit` runner.
377
+ * @param {string} workspacePath - repository working directory.
378
+ * @param {object} [options] - `limit` records.
379
+ * @returns {Promise<{entries: object[], total: number, truncated: boolean}>} status entries.
380
+ */
381
+ export async function readStatus(deps, workspacePath, options = {}) {
382
+ const runGit = gitRunnerFrom(deps);
383
+ const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : AUDIT_LIMITS.statusEntries;
384
+ const result = requireResult(
385
+ await runGit(workspacePath, ['status', '--porcelain=v1', '-z', '--untracked-files=all']),
386
+ 'status',
387
+ );
388
+ if (result.code !== 0) throw gitFailure('status', result);
389
+ return parseStatusZ(result.stdout, limit);
390
+ }
391
+
392
+ /**
393
+ * Wrap a runner so spawn-level failures are normalised to this module's codes.
394
+ *
395
+ * A runner that throws `EPERM` (a confined sandbox denying process creation) or
396
+ * anything non-`AuditError` must not escape as a generic error: callers switch on
397
+ * `AuditError.code`, and an unclassified throw would be read as an internal bug
398
+ * rather than as "the workspace cannot be audited".
399
+ * @param {(cwd: string, args: string[]) => Promise<object>} runGit - raw runner.
400
+ * @returns {(cwd: string, args: string[]) => Promise<object>} normalising runner.
401
+ */
402
+ function normalizeRunner(runGit) {
403
+ if (typeof runGit !== 'function') {
404
+ throw new AuditError(AUDIT_CODES.gitFailed, 'no git runner is installed', {});
405
+ }
406
+ return async function safeRunGit(cwd, args) {
407
+ try {
408
+ return await runGit(cwd, args);
409
+ } catch (error) {
410
+ if (error instanceof AuditError) throw error;
411
+ throw new AuditError(AUDIT_CODES.gitUnavailable, 'git could not be executed in this environment', {
412
+ cause: typeof error?.code === 'string' ? error.code : null,
413
+ });
414
+ }
415
+ };
416
+ }
417
+
418
+ /**
419
+ * Resolve a normalising runner from a deps object.
420
+ * @param {object} deps - dependency object with `runGit`.
421
+ * @returns {(cwd: string, args: string[]) => Promise<object>} runner.
422
+ */
423
+ export function gitRunnerFrom(deps) {
424
+ return normalizeRunner(deps?.runGit);
425
+ }
426
+
427
+ /**
428
+ * Capture the workspace state a job starts from.
429
+ *
430
+ * `head` is the fixed comparison point for the rest of the job. It is a commit
431
+ * id, not the string `HEAD`, because the agent under audit can move `HEAD`.
432
+ * @param {object} deps - `runGit` runner.
433
+ * @param {string} workspacePath - resolved workspace path.
434
+ * @returns {Promise<object>} baseline snapshot usable by {@link captureDiff}.
435
+ */
436
+ export async function captureBaseline(deps, workspacePath) {
437
+ const facts = await probeRepository(deps.runGit, workspacePath);
438
+ if (!facts.repository || !facts.hasCommits) {
439
+ throw new AuditError(AUDIT_CODES.notRepository, 'the workspace is not a git repository with a commit', {
440
+ repository: facts.repository,
441
+ hasCommits: facts.hasCommits,
442
+ });
443
+ }
444
+ const status = await readStatus(deps, workspacePath);
445
+ return {
446
+ // The pinned commit the diff is measured against.
447
+ head: facts.head,
448
+ dirtyBaseline: status.total > 0,
449
+ // The pre-existing dirty count is kept so a reviewer can tell this job's
450
+ // changes apart from edits that were already there.
451
+ preexistingChanges: status.total,
452
+ // Names only, bounded: a reviewer needs to know the checkout was dirty, not
453
+ // what was already in it.
454
+ preexistingPaths: status.entries.slice(0, AUDIT_LIMITS.samplePaths).map((entry) => entry.path),
455
+ statusTruncated: status.truncated,
456
+ statusFormat: 'porcelain-v1-z',
457
+ capturedAt: Date.now(),
458
+ };
459
+ }
460
+
461
+ /**
462
+ * Collect the paths whose content must be withheld from the patch.
463
+ *
464
+ * Renames contribute both names, so a rename *from* `.env` to `notes.txt` is
465
+ * still recognised as credential material. A path is listed once even when it
466
+ * appears in several status records.
467
+ * @param {object[]} entries - parsed status entries.
468
+ * @returns {{paths: string[], count: number}} sorted unique paths and the total.
469
+ */
470
+ function collectSensitivePaths(entries) {
471
+ const set = new Set();
472
+ for (const entry of entries) {
473
+ if (isSensitivePath(entry.path)) set.add(entry.path);
474
+ if (typeof entry.from === 'string' && isSensitivePath(entry.from)) set.add(entry.from);
475
+ }
476
+ const paths = [...set].sort();
477
+ return { paths, count: paths.length };
478
+ }
479
+
480
+ /**
481
+ * Build literal exclusion pathspecs.
482
+ *
483
+ * `literal` is mandatory: a filename containing `*`, `?` or `[` must be excluded
484
+ * as itself, not as a glob that may match a different sensitive file (or fail to
485
+ * match anything and leak the excluded file back into the patch).
486
+ * @param {string[]} paths - repository-relative paths.
487
+ * @returns {string[]} pathspec arguments.
488
+ */
489
+ function exclusionPathspecs(paths) {
490
+ return paths.map((relPath) => `:(exclude,literal)${relPath}`);
491
+ }
492
+
493
+ /**
494
+ * Parse `git diff --numstat -z` output.
495
+ *
496
+ * A rename row is `add\tdel\t` followed by the old path and the new path as two
497
+ * extra NUL-terminated tokens; a normal row carries the single path in the third
498
+ * field.
499
+ * @param {string} stdout - raw stdout.
500
+ * @param {number} [limit] - maximum rows retained.
501
+ * @returns {{added: string, removed: string, path: string, from: string | null}[]} rows.
502
+ */
503
+ export function parseNumstatZ(stdout, limit = AUDIT_LIMITS.statLines) {
504
+ const text = typeof stdout === 'string' ? stdout : '';
505
+ if (text === '') return [];
506
+ const tokens = text.split('\0');
507
+ const rows = [];
508
+ for (let index = 0; index < tokens.length; index += 1) {
509
+ const token = tokens[index];
510
+ if (token === '') continue;
511
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(token);
512
+ if (match === null) continue;
513
+ const [, added, removed, inline] = match;
514
+ let path = inline;
515
+ let from = null;
516
+ if (inline === '') {
517
+ const oldPath = tokens[index + 1];
518
+ const newPath = tokens[index + 2];
519
+ if (typeof oldPath !== 'string' || typeof newPath !== 'string') continue;
520
+ from = oldPath;
521
+ path = newPath;
522
+ index += 2;
523
+ }
524
+ if (path === '') continue;
525
+ if (rows.length >= limit) continue;
526
+ rows.push({ added, removed, path, from });
527
+ }
528
+ return rows;
529
+ }
530
+
531
+ /**
532
+ * Default file inspector used before an untracked file's content is read.
533
+ *
534
+ * A file is described, never opened: the decision to include it in the patch is
535
+ * made from `lstat` metadata only, so an oversized file, a directory or a
536
+ * symlink is skipped without this process reading anything.
537
+ * @param {string} absolutePath - absolute path to inspect.
538
+ * @returns {Promise<{kind: 'file'|'directory'|'symlink'|'other'|'missing', size: number}>} facts.
539
+ */
540
+ export async function describePath(absolutePath) {
541
+ try {
542
+ const info = await lstat(absolutePath);
543
+ if (info.isSymbolicLink()) return { kind: 'symlink', size: 0 };
544
+ if (info.isFile()) return { kind: 'file', size: info.size };
545
+ if (info.isDirectory()) return { kind: 'directory', size: 0 };
546
+ return { kind: 'other', size: info.size };
547
+ } catch {
548
+ return { kind: 'missing', size: 0 };
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Decide whether one untracked path may be rendered into the patch.
554
+ * @param {string} workspacePath - repository root.
555
+ * @param {string} relPath - repository-relative path.
556
+ * @param {(absolutePath: string) => Promise<object>} statPath - file inspector seam.
557
+ * @returns {Promise<{skip: boolean, note: string | null}>} decision.
558
+ */
559
+ async function inspectUntracked(workspacePath, relPath, statPath) {
560
+ const root = resolvePath(workspacePath);
561
+ const target = resolvePath(root, relPath);
562
+ // A path that escapes the repository is never read; the file list already
563
+ // records it, which is all the evidence a reviewer needs.
564
+ if (!isInside(root, target)) return { skip: true, note: null };
565
+ const facts = await statPath(target);
566
+ if (facts?.kind !== 'file') return { skip: true, note: null };
567
+ const size = typeof facts.size === 'number' ? facts.size : 0;
568
+ if (size > AUDIT_LIMITS.patchBytes) {
569
+ return { skip: true, note: `diff -- omitted ${relPath}: ${size} bytes exceeds the patch budget` };
570
+ }
571
+ return { skip: false, note: null };
572
+ }
573
+
574
+ /**
575
+ * Produce a bounded patch for everything except sensitive paths.
576
+ * @param {Function} runGit - normalising runner.
577
+ * @param {(absolutePath: string) => Promise<object>} statPath - file inspector seam.
578
+ * @param {string} workspacePath - repository root.
579
+ * @param {string} baseHead - pinned commit id.
580
+ * @param {string[]} sensitivePaths - paths to exclude from the patch.
581
+ * @param {string[]} untrackedPaths - non-sensitive untracked files.
582
+ * @returns {Promise<{text: string, truncated: boolean}>} bounded patch.
583
+ */
584
+ async function readBoundedPatch(runGit, statPath, workspacePath, baseHead, sensitivePaths, untrackedPaths) {
585
+ const chunks = [];
586
+ let bytes = 0;
587
+ let truncated = false;
588
+ const add = (text) => {
589
+ if (text === '') return;
590
+ chunks.push(text);
591
+ bytes += Buffer.byteLength(text, 'utf8');
592
+ };
593
+
594
+ // No external diff driver and no textconv filter may run: both are configured
595
+ // in the audited repository and could read or transform withheld content.
596
+ const diffArgs = ['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--unified=3', baseHead];
597
+ const exclusions = exclusionPathspecs(sensitivePaths);
598
+ if (exclusions.length > 0) diffArgs.push('--', ...exclusions);
599
+ const diff = requireResult(await runGit(workspacePath, diffArgs), 'diff');
600
+ if (diff.code !== 0) throw gitFailure('diff', diff);
601
+ add(diff.stdout.trim() === '' ? '' : diff.stdout);
602
+ if (bytes > AUDIT_LIMITS.patchBytes) truncated = true;
603
+
604
+ let rendered = 0;
605
+ for (const relPath of untrackedPaths) {
606
+ if (bytes >= AUDIT_LIMITS.patchBytes) {
607
+ truncated = true;
608
+ break;
609
+ }
610
+ if (rendered >= AUDIT_LIMITS.patchFiles) {
611
+ truncated = true;
612
+ break;
613
+ }
614
+ const decision = await inspectUntracked(workspacePath, relPath, statPath);
615
+ if (decision.skip) {
616
+ if (decision.note !== null) add(decision.note);
617
+ continue;
618
+ }
619
+ rendered += 1;
620
+ // Untracked files have no diff against a commit; render them as additions so
621
+ // a new file cannot silently evade review.
622
+ const shown = requireResult(
623
+ await runGit(workspacePath, [
624
+ 'diff',
625
+ '--no-index',
626
+ '--no-color',
627
+ '--no-ext-diff',
628
+ '--no-textconv',
629
+ '--unified=3',
630
+ '--',
631
+ '/dev/null',
632
+ relPath,
633
+ ]),
634
+ 'diff --no-index',
635
+ );
636
+ // Exit code 1 is `--no-index`'s "differences found", i.e. success here.
637
+ if (shown.code !== 0 && shown.code !== 1) throw gitFailure('diff --no-index', shown);
638
+ add(shown.stdout.trim() === '' ? '' : shown.stdout);
639
+ }
640
+
641
+ const combined = redactText(chunks.join('\n'));
642
+ const payload = Buffer.from(combined, 'utf8');
643
+ if (payload.byteLength <= AUDIT_LIMITS.patchBytes) {
644
+ return { text: combined, truncated };
645
+ }
646
+ // Cut on a byte boundary, then drop the possibly split trailing code point so
647
+ // the retained text stays valid UTF-8 for JSON transport.
648
+ const slice = payload.subarray(0, AUDIT_LIMITS.patchBytes).toString('utf8').replace(/\uFFFD$/, '');
649
+ return { text: `${slice}\n… patch truncated at ${AUDIT_LIMITS.patchBytes} bytes`, truncated: true };
650
+ }
651
+
652
+ /**
653
+ * Explain why a patch was withheld, without quoting any path.
654
+ * @param {number} sensitiveCount - number of sensitive paths seen.
655
+ * @param {boolean} statusTruncated - whether the status list itself was cut.
656
+ * @returns {string} operator-facing reason.
657
+ */
658
+ function withheldAllReason(sensitiveCount, statusTruncated) {
659
+ if (statusTruncated) {
660
+ return `diff withheld: the status list exceeded ${AUDIT_LIMITS.statusEntries} entries, so the sensitive-path set cannot be proven complete`;
661
+ }
662
+ return `diff withheld: ${sensitiveCount} sensitive paths were touched, above the ${AUDIT_LIMITS.sensitivePaths} exclusion bound`;
663
+ }
664
+
665
+ /**
666
+ * Measure what changed since the baseline: status entries plus a bounded patch.
667
+ *
668
+ * Sensitive paths keep their name in the file list — the operator needs to know
669
+ * a credential file was touched — but they are filtered out of the status list
670
+ * *and* the pathspec set before any diff is produced, so their content is never
671
+ * read. If more sensitive paths were touched than the exclusion bound allows,
672
+ * the patch is withheld entirely rather than partially filtered.
673
+ * @param {object} deps - `runGit` runner.
674
+ * @param {string} workspacePath - resolved workspace path.
675
+ * @param {object} baseline - value returned by {@link captureBaseline}.
676
+ * @returns {Promise<object>} bounded, redacted change evidence.
677
+ */
678
+ export async function captureDiff(deps, workspacePath, baseline) {
679
+ const baseHead = typeof baseline?.head === 'string' && baseline.head.trim() !== '' ? baseline.head.trim() : null;
680
+ if (baseHead === null) {
681
+ // Without a pinned commit there is no honest comparison point; comparing to
682
+ // `HEAD` would let the run's own commits disappear from the evidence.
683
+ throw new AuditError(AUDIT_CODES.baselineInvalid, 'the baseline has no pinned head commit', {});
684
+ }
685
+ const runGit = gitRunnerFrom(deps);
686
+ const statPath = typeof deps?.statPath === 'function' ? deps.statPath : describePath;
687
+
688
+ const status = await readStatus(deps, workspacePath);
689
+ const entries = status.entries;
690
+ const sensitive = collectSensitivePaths(entries);
691
+ const files = entries.slice(0, AUDIT_LIMITS.files);
692
+
693
+ // Both tracked and untracked sensitive paths are filtered here, before any
694
+ // diff invocation exists. A truncated status list is treated as "too many":
695
+ // the unparsed tail could hide a credential path, and a patch rendered without
696
+ // excluding it would leak content this module promised not to read.
697
+ const withheldAll = sensitive.count > AUDIT_LIMITS.sensitivePaths || status.truncated;
698
+ const sensitivePaths = sensitive.paths.slice(0, AUDIT_LIMITS.sensitivePaths);
699
+ const untrackedResult = requireResult(
700
+ await runGit(workspacePath, ['ls-files', '--others', '--exclude-standard', '-z']),
701
+ 'ls-files',
702
+ );
703
+ if (untrackedResult.code !== 0) throw gitFailure('ls-files', untrackedResult);
704
+ // Withholding everything also means nothing untracked may be rendered.
705
+ const untrackedPaths = withheldAll
706
+ ? []
707
+ : untrackedResult.stdout
708
+ .split('\0')
709
+ .filter((entry) => entry !== '' && !isSensitivePath(entry))
710
+ .slice(0, AUDIT_LIMITS.files);
711
+
712
+ const numstatArgs = ['diff', '--numstat', '-z', '--no-ext-diff', '--no-textconv', baseHead];
713
+ if (!withheldAll && sensitivePaths.length > 0) numstatArgs.push('--', ...exclusionPathspecs(sensitivePaths));
714
+ // When the patch is withheld no diff is produced at all: a partially filtered
715
+ // diff over an unbounded set of sensitive files is exactly the leak the bound
716
+ // exists to prevent.
717
+ let changes = [];
718
+ if (!withheldAll) {
719
+ const numstat = requireResult(await runGit(workspacePath, numstatArgs), 'diff --numstat');
720
+ if (numstat.code !== 0) throw gitFailure('diff --numstat', numstat);
721
+ changes = parseNumstatZ(numstat.stdout);
722
+ }
723
+
724
+ const patch = withheldAll
725
+ ? {
726
+ text: withheldAllReason(sensitive.count, status.truncated),
727
+ truncated: true,
728
+ }
729
+ : await readBoundedPatch(runGit, statPath, workspacePath, baseHead, sensitivePaths, untrackedPaths);
730
+
731
+ return {
732
+ // Which fixed commit this evidence is measured against.
733
+ head: baseHead,
734
+ baseHead,
735
+ dirtyBaseline: baseline?.dirtyBaseline === true,
736
+ preexistingChanges: baseline?.preexistingChanges ?? 0,
737
+ files,
738
+ fileCount: status.total,
739
+ truncatedFiles: status.truncated || status.total > files.length,
740
+ changes,
741
+ // Paths stay visible; their content was excluded before the diff ran.
742
+ sensitivePaths,
743
+ sensitiveTouchedCount: sensitive.count,
744
+ sensitiveContentWithheld: true,
745
+ patchWithheld: withheldAll,
746
+ patchText: patch.text,
747
+ patchTruncated: patch.truncated,
748
+ patchBytes: Buffer.byteLength(patch.text, 'utf8'),
749
+ capturedAt: Date.now(),
750
+ };
751
+ }
752
+
753
+ /**
754
+ * Verify that a worktree isolation request can be honoured.
755
+ *
756
+ * Worktree isolation needs a committed repository; when that is not the case
757
+ * the request is refused. Silently falling back to shared isolation would
758
+ * execute a job with weaker isolation than the operator asked for.
759
+ * @param {object} deps - `runGit` runner.
760
+ * @param {string} workspacePath - resolved workspace path.
761
+ * @returns {Promise<object>} facts, or a refusal.
762
+ */
763
+ export async function assertWorktreeCapable(deps, workspacePath) {
764
+ const facts = await probeRepository(deps.runGit, workspacePath);
765
+ if (!facts.git) {
766
+ throw new AuditError(AUDIT_CODES.gitUnavailable, 'worktree isolation requires git', {});
767
+ }
768
+ if (!facts.repository) {
769
+ throw new AuditError(AUDIT_CODES.notRepository, 'worktree isolation requires a git work tree', {});
770
+ }
771
+ if (!facts.hasCommits) {
772
+ throw new AuditError(AUDIT_CODES.noCommits, 'worktree isolation requires at least one commit', {});
773
+ }
774
+ return facts;
775
+ }