diffpact 0.0.0-stage → 0.4.3

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 (51) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/LICENSE +21 -0
  3. package/README.md +223 -2
  4. package/bin/diffpact.mjs +15 -0
  5. package/dist/adapters/claude-code.d.ts +21 -0
  6. package/dist/adapters/claude-code.js +191 -0
  7. package/dist/adapters/codex.d.ts +31 -0
  8. package/dist/adapters/codex.js +348 -0
  9. package/dist/adapters/gemini-agy.d.ts +26 -0
  10. package/dist/adapters/gemini-agy.js +429 -0
  11. package/dist/adapters/vercel-board.d.ts +30 -0
  12. package/dist/adapters/vercel-board.js +138 -0
  13. package/dist/amend.d.ts +46 -0
  14. package/dist/amend.js +476 -0
  15. package/dist/boundaries.d.ts +43 -0
  16. package/dist/boundaries.js +309 -0
  17. package/dist/canonical-json.d.ts +6 -0
  18. package/dist/canonical-json.js +63 -0
  19. package/dist/cli.d.ts +1 -0
  20. package/dist/cli.js +1704 -0
  21. package/dist/delegate.d.ts +22 -0
  22. package/dist/delegate.js +140 -0
  23. package/dist/doctor.d.ts +36 -0
  24. package/dist/doctor.js +293 -0
  25. package/dist/git.d.ts +27 -0
  26. package/dist/git.js +234 -0
  27. package/dist/index.d.ts +19 -0
  28. package/dist/index.js +19 -0
  29. package/dist/merge-verify.d.ts +31 -0
  30. package/dist/merge-verify.js +721 -0
  31. package/dist/report.d.ts +25 -0
  32. package/dist/report.js +220 -0
  33. package/dist/review.d.ts +46 -0
  34. package/dist/review.js +527 -0
  35. package/dist/runner.d.ts +45 -0
  36. package/dist/runner.js +213 -0
  37. package/dist/schema.d.ts +6 -0
  38. package/dist/schema.js +424 -0
  39. package/dist/types.d.ts +190 -0
  40. package/dist/types.js +220 -0
  41. package/dist/verify.d.ts +45 -0
  42. package/dist/verify.js +952 -0
  43. package/dist/worktree.d.ts +82 -0
  44. package/dist/worktree.js +717 -0
  45. package/examples/harnesses/README.md +63 -0
  46. package/examples/quickstart/README.md +17 -0
  47. package/examples/quickstart/run.mjs +247 -0
  48. package/package.json +62 -4
  49. package/schemas/contract.schema.json +148 -0
  50. package/schemas/receipt.schema.json +49 -0
  51. package/schemas/review.schema.json +48 -0
package/dist/cli.js ADDED
@@ -0,0 +1,1704 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { canonicalSha256, sha256Hex } from './canonical-json.js';
4
+ import { amendContract, readAmendmentHistory } from './amend.js';
5
+ import { createDelegatedSubcontract } from './delegate.js';
6
+ import { installHarnessHooks, runDoctor } from './doctor.js';
7
+ import { appendLedgerEvent, generateTaskReport } from './report.js';
8
+ import {
9
+ buildHarnessCommand,
10
+ spawnCommandWithHeartbeat,
11
+
12
+ } from './runner.js';
13
+ import { createManagedWorktree, inspectDirtyTreeDiagnostics, removeManagedWorktree } from './worktree.js';
14
+ import {
15
+ collectRepoChanges,
16
+ commitExists,
17
+ ensureGitInfoExclude,
18
+ isAncestor,
19
+ resolveCommitSha,
20
+ resolveCurrentBranch,
21
+ resolveHeadSha,
22
+ resolveRepoRoot,
23
+ runGitText
24
+ } from './git.js';
25
+ import { runMergeVerify } from './merge-verify.js';
26
+ import { checkStatus, runReview } from './review.js';
27
+ import { validateContract, validateSessionIdentity } from './schema.js';
28
+ import {
29
+ EXIT_INCOMPLETE,
30
+ EXIT_PASS,
31
+ EXIT_STALE,
32
+ EXIT_VIOLATION,
33
+
34
+
35
+
36
+
37
+ } from './types.js';
38
+ import { runVerify, runVerifyAsync } from './verify.js';
39
+ import { generateClaudeCodeConfig, handleClaudeCodeHook } from './adapters/claude-code.js';
40
+ import {
41
+ generateCodexConfig,
42
+ handleCodexHook,
43
+ handleCodexNotify,
44
+ runWrappedCodexReview
45
+ } from './adapters/codex.js';
46
+ import {
47
+ generateAgyConfig,
48
+ generateGeminiCliConfig,
49
+ handleAgyHook,
50
+ handleGeminiCliHook,
51
+ verifyAgyWorkerPatch
52
+ } from './adapters/gemini-agy.js';
53
+ import { boardCompleteGate, boardPostContract } from './adapters/vercel-board.js';
54
+
55
+ const ZSH_IDENTITY_HINT =
56
+ 'Tip for zsh users: wrap variables in braces or single quotes (e.g. "codex:s-${n}:codex" or \'codex:s-1:codex\') so zsh does not treat "$n:c" as a parameter modifier.';
57
+
58
+ function parseSessionSpec(spec , ctx ) {
59
+ const parts = spec.split(':');
60
+ if (parts.length < 3) {
61
+ throw new Error(`${ctx} must be formatted as "<agent_id>:<session_id>:<harness>" (got "${spec}"). ${ZSH_IDENTITY_HINT}`);
62
+ }
63
+ const agent_id = parts[0] ;
64
+ const harness = parts[parts.length - 1] ;
65
+ const session_id = parts.slice(1, -1).join(':');
66
+ try {
67
+ return validateSessionIdentity({ agent_id, session_id, harness }, ctx);
68
+ } catch (err) {
69
+ const msg = (err ).message;
70
+ if (msg.includes('.harness invalid')) {
71
+ throw new Error(`${msg}. ${ZSH_IDENTITY_HINT}`);
72
+ }
73
+ throw err;
74
+ }
75
+ }
76
+
77
+ function readStdinUtf8() {
78
+ try {
79
+ return fs.readFileSync(0, 'utf8');
80
+ } catch {
81
+ return '';
82
+ }
83
+ }
84
+
85
+ function printHelp() {
86
+ const text = `diffpact v0.4.3 — Stateless Git task contracts & cross-harness review gates
87
+
88
+ Usage:
89
+ diffpact [--cwd <dir>] [--contract <path>] [--json] <command> [options]
90
+ diffpact <command> --help | diffpact help <command>
91
+
92
+ Global Options:
93
+ --cwd <dir>, -C <dir> Run command against target repo/worktree directory (default: current directory)
94
+ --contract <path> Path to contract.json relative to cwd (default: .diffpact/contract.json)
95
+ --json Emit machine-readable JSON output
96
+ -h, --help Show global or per-command help
97
+
98
+ Commands:
99
+ init Create .diffpact/contract.json pinned to starting_sha
100
+ amend Record hash-chained scope or starting_sha amendment with reason
101
+ exec [--resume] -- <cmd...> Pre-flight check -> run worker -> post-flight verify (alias: wrap)
102
+ run --harness <id> Harness-aware launcher (claude | codex | crush | agy | gemini) with pre/post gate
103
+ verify Recompute Git diff boundaries, pinned versions, and run checks
104
+ merge-verify Post-merge gate across 2+ merged contracts/archives (runs union of checks)
105
+ diff Print primary raw Git diff + raw_diff_sha256 token for independent review
106
+ review Record non-self-certified review attestation bound to candidate_sha & diff
107
+ status Fast read-only gate check against live Git HEAD (+ review visibility)
108
+ report Emit Markdown PR card, JSON bundle, or SARIF 2.1.0 report
109
+ worktree <create|remove> Manage linked Git worktrees (+ archiving & subdir node_modules)
110
+ delegate Create monotonically narrowed child subcontract conserving max_budget_usd
111
+ doctor Probe Git, worktree state, root/sandbox warnings, and installed CLIs
112
+ install-hooks Merge diffpact hooks safely into claude-code | codex | gemini | agy
113
+ hook <target> Protocol hook for claude-code | codex | codex-notify | gemini | agy | auto
114
+ board <subcommand> @vercel/board adapter: post-contract <id> | complete <id>
115
+ agy-verify-patch Verify unattended agy-worker --diff patch before git apply
116
+ print-config <kind> Emit drop-in config for claude-code | codex | gemini | agy
117
+
118
+ Deterministic Exit Codes:
119
+ 0 = PASS All boundaries, checks, and required reviews verified
120
+ 1 = VIOLATION Path/shell boundary breached, self-certification, or check failed
121
+ 2 = INCOMPLETE Missing contract/receipt/review or skipped tests (No Silent Zero)
122
+ 3 = STALE Git HEAD or contract drifted after receipt/review
123
+ `;
124
+ process.stdout.write(text);
125
+ }
126
+
127
+ const COMMAND_HELP = {
128
+ init: `Usage: diffpact [--contract <path>] [--json] init [options]
129
+
130
+ Create a SHA-pinned task contract (.diffpact/contract.json) and exclude .diffpact/ in .git/info/exclude.
131
+
132
+ Options:
133
+ --task-id <id> Task identifier (default: task-001)
134
+ --type <coding|research> Task type; research enforces empty allowed_paths (default: coding)
135
+ --mission <text> Human-readable task description
136
+ --starting-sha <sha|ref> Pin starting commit (full SHA, short SHA, or Git ref; stored as 40-char SHA; default: HEAD)
137
+ --branch <name> Pin expected Git branch (default: current branch)
138
+ --implementer <a:s:h> Implementer identity "<agent_id>:<session_id>:<harness>"
139
+ Harnesses: claude-code | codex | crush | gemini-cli | agy | vercel-board | manual | other
140
+ (zsh tip: use "codex:s-\${n}:codex" or single quotes so "$n:c" is not parsed as a modifier)
141
+ --allow <glob> Allowed repo-relative file glob (repeatable)
142
+ --read-only <glob> Read-only file glob (repeatable)
143
+ --forbid <glob> Forbidden file glob (repeatable; overrides allow)
144
+ --check <id>=<cmd> Blocking verification command (repeatable; also accepts bare <cmd>)
145
+ --advisory-check <id>=<cmd> Non-blocking visibility check recorded in receipt/report (repeatable)
146
+ --check-timeout <id>=<sec> Per-check timeout in seconds (default: 300)
147
+ --max-budget <usd> Optional USD budget ceiling for delegated subcontracts
148
+ --lockfile <path> Pin external interface lockfile SHA-256 (e.g. interfacedelta.lock.json)
149
+ --allow-no-checks Explicitly allow empty required_checks (otherwise exit 2 No Silent Zero)
150
+ --allow-no-commit Explicitly allow HEAD === starting_sha for coding contracts
151
+ `,
152
+ amend: `Usage: diffpact [--contract <path>] [--json] amend [options]
153
+
154
+ Record a hash-chained scope or starting_sha amendment in .diffpact/amendments.jsonl.
155
+
156
+ Options:
157
+ --authorized-by <id> Orchestrator or human authorizing the amendment (required)
158
+ --reason <text> Why scope or base SHA changed (required)
159
+ --add-allow <glob> Append allowed path glob (repeatable)
160
+ --add-read-only <glob> Append read-only path glob (repeatable)
161
+ --add-forbid <glob> Append forbidden path glob (repeatable)
162
+ --update-starting-sha <sha> Re-pin starting_sha after rebasing onto updated main
163
+ --history Print and validate the amendment hash chain
164
+ `,
165
+ exec: `Usage: diffpact [--contract <path>] exec [--resume] [--heartbeat-sec <n>] -- <cmd...>
166
+
167
+ Pre-flight clean/ancestry check -> run bounded worker command -> detect contract tampering -> post-flight verify.
168
+ (Alias: diffpact wrap)
169
+
170
+ Options:
171
+ --resume Accept dirty/untracked files strictly inside allowed_paths (alias: --allow-in-scope-dirty)
172
+ --heartbeat-sec <n> Emit stderr progress heartbeat every N seconds (default: 30 non-TTY, 0 TTY)
173
+ `,
174
+ wrap: `Alias for "diffpact exec". Run "diffpact exec --help" for full options.
175
+ `,
176
+ run: `Usage: diffpact [--contract <path>] [--json] run --harness <id> (--prompt <text> | --prompt-file <path>) [options]
177
+
178
+ Harness-aware launcher with pre-flight boundary guard, live heartbeats, and host post-flight verification.
179
+
180
+ Options:
181
+ --harness <id> Target CLI: claude (claude-code) | codex | crush | agy | gemini (gemini-cli)
182
+ --prompt <text> Inline task prompt
183
+ --prompt-file <path> Read task prompt from file
184
+ --model <name> Optional model identifier forwarded to the harness
185
+ --reasoning-effort <level> Optional reasoning effort (used by crush: low | medium | high)
186
+ --data-dir <dir> Custom Crush state dir (default: isolated /var/tmp/diffpact-crush-*)
187
+ --resume Resume interrupted session if dirty files are strictly inside allowed_paths
188
+ --heartbeat-sec <n> Stderr heartbeat interval in seconds (default: 30 non-TTY, 0 TTY)
189
+ --dry-run Print resolved harness binary and flags without executing
190
+ `,
191
+ verify: `Usage: diffpact [--contract <path>] [--json] verify [--heartbeat-sec <n>]
192
+
193
+ Recompute Git diff boundaries, symlinks/submodules, version assertions, lockfile pins, and checks,
194
+ writing a canonical SHA-256 signed receipt to .diffpact/receipt.json.
195
+
196
+ Options:
197
+ --heartbeat-sec <n> Stderr heartbeat interval for long-running checks (default: 30 non-TTY, 0 TTY)
198
+ `,
199
+ 'merge-verify': `Usage: diffpact [--json] merge-verify --from <path> [--from <path> ...] [options]
200
+
201
+ Post-merge verification gate across 2+ merged contracts or archived worktree evidence bundles.
202
+ Checks that every changed file since base SHA is authorized by at least one participating contract,
203
+ runs the deduplicated UNION of all contracts' required_checks & version pins, and writes a signed
204
+ merge receipt under .diffpact/merges/.
205
+
206
+ Recommended order:
207
+ 1. Merge or squash-merge verified branches onto main.
208
+ 2. Run "diffpact merge-verify --from <archive-a> --from <archive-b>" BEFORE any manual orchestrator fixes.
209
+ 3. If orchestrator integration glue edits were needed on main, pass "--allow-integration <glob> --reason '...'"
210
+ (recorded in merge-receipt.json; global forbidden paths across all contracts remain strictly blocked).
211
+
212
+ Options:
213
+ --from <path> Path to contract.json, .diffpact/ dir, worktree root, or .diffpact/archive/<bundle> (repeatable)
214
+ --base <sha|ref> Base commit before merge (default: common merge-base of contracts' starting_sha)
215
+ --allow-integration <glob> Explicitly authorize orchestrator integration glue files on main (repeatable; cannot override global forbidden_paths)
216
+ --reason <text> Optional audit reason recorded alongside --allow-integration in merge-receipt.json
217
+ --allow-untracked Ignore pre-existing untracked files on main (alias: --committed-only); still fails on dirty tracked files and records ignored paths in receipt
218
+ --heartbeat-sec <n> Stderr heartbeat interval in seconds (default: 30 non-TTY, 0 TTY)
219
+ --write-receipt <path> Custom path for merge-receipt.json
220
+ --no-write Skip writing merge-receipt.json to disk
221
+ `,
222
+ diff: `Usage: diffpact [--contract <path>] [--json] diff
223
+
224
+ Print the primary raw Git diff (starting_sha..HEAD) plus untracked files and the canonical
225
+ raw_diff_sha256 token for use with "diffpact review --diff-sha <sha>".
226
+ `,
227
+ review: `Usage: diffpact [--cwd <dir>] [--contract <path>] [--json] review --reviewer <a:s:h> --verdict <approve|reject> (--diff-sha <sha> | --inspected-raw-diff) [options]
228
+
229
+ Record a non-self-certified review attestation bound to contract_sha256, receipt_sha256, candidate_sha, and raw_diff_sha256.
230
+ Set DIFFPACT_REVIEWER_SECRET in the orchestrator environment (automatically stripped from diffpact exec/run workers)
231
+ to HMAC-SHA256 sign and verify reviews so workers cannot forge reviewer attestations.
232
+
233
+ Options:
234
+ --reviewer <a:s:h> Reviewer identity "<agent_id>:<session_id>:<harness>" (must differ from implementer)
235
+ --verdict <approve|reject> Review verdict (required; no default)
236
+ --summary <text> Concise review summary
237
+ --finding <text> Specific finding line (repeatable)
238
+ --diff-sha <sha> Bind review cryptographically to raw_diff_sha256 from "diffpact diff" (recommended; >=12 hex chars)
239
+ --inspected-raw-diff Explicitly attest that you inspected the primary raw Git diff
240
+ --summary-only Mark inspected_raw_diff=false (fails closed when require_raw_diff_inspection is true)
241
+ --lineage <id> Custom evidence lineage identifier for multi-reviewer independence
242
+ --adapter codex -- <cmd...> Run read-only Codex reviewer wrapper and parse thread_id + JSONL verdict
243
+ `,
244
+ status: `Usage: diffpact [--contract <path>] [--json] status [--require-review] [--integrator <agent_id>]
245
+
246
+ Fast stateless read-only gate check against live Git HEAD, receipt, and review attestations.
247
+ Without --require-review, checks verification receipt AND prints explicit review status (missing/approved/stale/rejected).
248
+
249
+ Options:
250
+ --require-review Fail closed (exit 2/3/1) unless required independent review(s) pass for current HEAD
251
+ --integrator <agent_id> Enforce canonical_integrator_agent_id / role_substitution policy
252
+ `,
253
+ report: `Usage: diffpact [--contract <path>] [--json] report [--format <markdown|json|sarif>]
254
+
255
+ Render persisted contract, verification receipt, advisory checks, amendments, and reviews.
256
+
257
+ Options:
258
+ --format <markdown|json|sarif> Output format (default: markdown, or json when --json is set)
259
+ `,
260
+ worktree: `Usage: diffpact [--contract <path>] [--json] worktree <create|remove> <dir> [options]
261
+
262
+ Manage linked Git worktrees cleanly with automatic .diffpact/ exclusion, dependency sharing, and evidence archiving.
263
+
264
+ Subcommand "create":
265
+ diffpact worktree create <dir> --branch <name> [--from <ref>] [--share-node-modules] [--node-modules-dir <subdir>]
266
+ --branch <name> New branch name to create (required)
267
+ --from <ref> Starting ref/SHA (default: HEAD)
268
+ --share-node-modules Share node_modules cleanly (workspace-aware overlay for npm/pnpm monorepos;
269
+ auto-discovers depth 1-2 package subdirs like site/node_modules if no root node_modules)
270
+ --node-modules-dir <subdir> Explicit package subdir containing node_modules (repeatable; e.g. site)
271
+
272
+ Subcommand "remove":
273
+ diffpact worktree remove <dir> [--require-verified] [--delete-branch | --force-delete-branch] [--archive-dir <dir>] [--no-archive] [--force]
274
+ --require-verified Block removal unless "diffpact status --require-review" passes (exit 0);
275
+ automatically uses "git branch -D" with --delete-branch for squash-merged branches
276
+ --delete-branch Delete worktree branch (uses -D if --require-verified or --force; never deletes main/master)
277
+ --force-delete-branch Delete worktree branch via "git branch -D" (never deletes main/master)
278
+ --archive-dir <dir> Custom archive destination (default: <main>/.diffpact/archive/<timestamp>-<task>-<sha>/)
279
+ --no-archive Skip archiving .diffpact/ evidence before removing worktree
280
+ --force Force worktree removal even if unverified or dirty
281
+ `,
282
+ delegate: `Usage: diffpact [--contract <path>] [--json] delegate --subtask-id <id> --implementer <a:s:h> --allow <glob> [options]
283
+
284
+ Create a monotonically narrowed child subcontract under .diffpact/subcontracts/ conserving parent max_budget_usd.
285
+
286
+ Options:
287
+ --subtask-id <id> Child task identifier (required)
288
+ --mission <text> Child mission statement
289
+ --implementer <a:s:h> Child implementer identity (required)
290
+ --allow <glob> Narrowed allowed path glob (repeatable; must stay inside parent scope)
291
+ --budget <usd> Reserved USD budget (sum across subcontracts <= parent max_budget_usd)
292
+ --branch <name> Optional pinned branch
293
+ --worktree <path> Optional pinned worktree path
294
+ `,
295
+ doctor: `Usage: diffpact [--json] doctor
296
+
297
+ Probe Node, Git, repository status, .git/info/exclude, installed agent CLIs (claude, codex, crush, agy, gemini, vercel),
298
+ and emit proactive warnings (root Claude permissions, Codex sandbox nesting, Crush .crush/ isolation).
299
+ `,
300
+ 'install-hooks': `Usage: diffpact [--contract <path>] [--json] install-hooks <claude-code|codex|gemini|agy> [--exclude]
301
+
302
+ Idempotently merge diffpact guard hooks into the target harness config file without clobbering user hooks.
303
+
304
+ Options:
305
+ --exclude Add generated config path and .diffpact/ to .git/info/exclude
306
+ `,
307
+ hook: `Usage: diffpact [--contract <path>] hook [claude-code|codex|codex-notify|gemini|agy|auto] [json-payload]
308
+
309
+ Process a harness hook event from stdin (or positional JSON argument) and enforce diffpact boundaries.
310
+ `,
311
+ gate: `Alias for "diffpact hook". Run "diffpact hook --help" for details.
312
+ `,
313
+ board: `Usage: diffpact [--contract <path>] [--json] board <post-contract|complete> <task-id> [options]
314
+
315
+ @vercel/board integration: post pinned contract hashes or gate task completion behind diffpact status.
316
+
317
+ Options:
318
+ --vb-bin <path> Custom @vercel/board executable path
319
+ --no-require-review Skip --require-review check on board complete
320
+ --message <text> Optional summary message
321
+ `,
322
+ 'agy-verify-patch': `Usage: diffpact [--contract <path>] [--json] agy-verify-patch <patch-file> [--allow-empty]
323
+
324
+ Verify an unattended agy-worker unified diff patch against contract boundaries before running git apply.
325
+ `,
326
+ 'print-config': `Usage: diffpact [--contract <path>] print-config <claude-code|codex|gemini|agy>
327
+
328
+ Print drop-in JSON hook configuration for the target harness to stdout.
329
+ `
330
+ };
331
+
332
+ function printCommandHelp(cmd ) {
333
+ const entry = COMMAND_HELP[cmd];
334
+ if (!entry) return false;
335
+ process.stdout.write(entry);
336
+ return true;
337
+ }
338
+
339
+ function failCliArg(cmd , message , jsonOut ) {
340
+ const full = cmd ? `diffpact ${cmd}: ${message}` : `diffpact: ${message}`;
341
+ if (jsonOut) {
342
+ process.stdout.write(JSON.stringify({ exit_code: EXIT_INCOMPLETE, error: full }, null, 2) + '\n');
343
+ } else {
344
+ process.stderr.write(`${full}\n`);
345
+ }
346
+ return EXIT_INCOMPLETE;
347
+ }
348
+
349
+ function failUnknownFlag(cmd , flag , jsonOut , extraHint ) {
350
+ const hint = extraHint ? ` ${extraHint}` : '';
351
+ return failCliArg(
352
+ cmd,
353
+ `Unknown option "${flag}". Run "diffpact ${cmd} --help" for valid options.${hint}`,
354
+ jsonOut
355
+ );
356
+ }
357
+
358
+ async function executeBoundedWorkerCommand(options
359
+
360
+
361
+
362
+
363
+
364
+
365
+ ) {
366
+ const { contractPath, cwd, childCmd, resume, heartbeatSec, label } = options;
367
+ const contractAbs = path.resolve(cwd, contractPath);
368
+ if (!fs.existsSync(contractAbs)) {
369
+ process.stderr.write(`Missing contract at "${contractAbs}"\n`);
370
+ return EXIT_INCOMPLETE;
371
+ }
372
+
373
+ let contract ;
374
+ try {
375
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
376
+ } catch (err) {
377
+ process.stderr.write(`Invalid contract: ${(err ).message}\n`);
378
+ return EXIT_INCOMPLETE;
379
+ }
380
+
381
+ const repoRoot = resolveRepoRoot(cwd);
382
+ const headBefore = resolveHeadSha(repoRoot);
383
+ if (!commitExists(repoRoot, contract.starting_sha)) {
384
+ process.stderr.write(`starting_sha ${contract.starting_sha} missing\n`);
385
+ return EXIT_STALE;
386
+ }
387
+ if (!isAncestor(repoRoot, contract.starting_sha, headBefore)) {
388
+ process.stderr.write(`starting_sha ${contract.starting_sha} is not an ancestor of HEAD ${headBefore}\n`);
389
+ return EXIT_STALE;
390
+ }
391
+
392
+ if (contract.worktree.require_clean_start !== false) {
393
+ const diag = inspectDirtyTreeDiagnostics(repoRoot, contract);
394
+ if (!diag.clean) {
395
+ if (resume) {
396
+ if (diag.outOfBoundsViolations.length > 0) {
397
+ process.stderr.write(
398
+ 'diffpact exec --resume pre-flight failed: dirty/untracked files exist outside allowed_paths:\n'
399
+ );
400
+ for (const v of diag.outOfBoundsViolations) {
401
+ process.stderr.write(` - [${v.code}] ${v.message}${v.path ? ` (${v.path})` : ''}\n`);
402
+ }
403
+ for (const hint of diag.symlinkGitignoreHints) {
404
+ process.stderr.write(` hint: ${hint}\n`);
405
+ }
406
+ return EXIT_VIOLATION;
407
+ }
408
+ process.stderr.write(
409
+ `[diffpact] --resume accepted ${diag.dirtyEntries.length} in-scope dirty file(s): ${diag.dirtyEntries.map((d) => `${d.status} ${d.path}`).join(', ')}\n`
410
+ );
411
+ } else {
412
+ const listed = diag.dirtyEntries.map((d) => `${d.status} ${d.path}`).join(', ');
413
+ process.stderr.write(
414
+ `diffpact exec pre-flight failed: working tree is not clean at start\n Dirty paths: ${listed}\n`
415
+ );
416
+ for (const hint of diag.symlinkGitignoreHints) {
417
+ process.stderr.write(` hint: ${hint}\n`);
418
+ }
419
+ if (diag.outOfBoundsViolations.length === 0) {
420
+ process.stderr.write(
421
+ ' hint: All dirty files are inside allowed_paths; pass `--resume` (or `--allow-in-scope-dirty`) to continue an interrupted session.\n'
422
+ );
423
+ }
424
+ return EXIT_VIOLATION;
425
+ }
426
+ }
427
+ }
428
+
429
+ const contractRawBefore = fs.readFileSync(contractAbs, 'utf8');
430
+ const contractSha = canonicalSha256('diffpact/contract/v0.1', contract);
431
+ const [bin, ...args] = childCmd;
432
+ const workerEnv = {
433
+ ...process.env,
434
+ DIFFPACT_CONTRACT: contractAbs,
435
+ DIFFPACT_CONTRACT_SHA256: contractSha,
436
+ DIFFPACT_STARTING_SHA: contract.starting_sha
437
+ };
438
+ // Never leak orchestrator review signing secret into bounded worker subprocesses
439
+ delete workerEnv.DIFFPACT_REVIEWER_SECRET;
440
+
441
+ const child = await spawnCommandWithHeartbeat({
442
+ bin: bin ,
443
+ args,
444
+ cwd: repoRoot,
445
+ env: workerEnv,
446
+ heartbeatSec,
447
+ label
448
+ });
449
+
450
+ if (child.error) {
451
+ const errCode = (child.error ).code ?? 'SPAWN_ERROR';
452
+ process.stderr.write(`diffpact exec failed to spawn "${bin}" (${errCode}): ${child.error.message}\n`);
453
+ return EXIT_VIOLATION;
454
+ }
455
+
456
+ // Guard against untrusted worker mutating or deleting contract.json during exec
457
+ let contractTampered = false;
458
+ if (!fs.existsSync(contractAbs)) {
459
+ contractTampered = true;
460
+ } else {
461
+ try {
462
+ const afterParsed = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
463
+ if (canonicalSha256('diffpact/contract/v0.1', afterParsed) !== contractSha) {
464
+ contractTampered = true;
465
+ }
466
+ } catch {
467
+ contractTampered = true;
468
+ }
469
+ }
470
+ if (contractTampered) {
471
+ fs.mkdirSync(path.dirname(contractAbs), { recursive: true });
472
+ fs.writeFileSync(contractAbs, contractRawBefore);
473
+ process.stderr.write('diffpact exec VIOLATION: worker attempted to modify or delete contract.json (restored original)\n');
474
+ runVerify({ contractPath: contractAbs, cwd: repoRoot, writeReceipt: true });
475
+ return EXIT_VIOLATION;
476
+ }
477
+
478
+ const post = await runVerifyAsync({
479
+ contractPath: contractAbs,
480
+ cwd: repoRoot,
481
+ writeReceipt: true,
482
+ heartbeatSec
483
+ });
484
+ if (child.status !== 0 && post.exitCode === 0) {
485
+ return EXIT_VIOLATION;
486
+ }
487
+ return post.exitCode;
488
+ }
489
+
490
+ export async function runCli(argv ) {
491
+ let contractPath = process.env.DIFFPACT_CONTRACT ?? '.diffpact/contract.json';
492
+ let cwdArg ;
493
+ let jsonOut = false;
494
+ let helpRequested = false;
495
+ let missingGlobalValueFlag ;
496
+
497
+ const rest = [];
498
+ for (let i = 0; i < argv.length; i++) {
499
+ const arg = argv[i] ;
500
+ if (arg === '--') {
501
+ rest.push('--', ...argv.slice(i + 1));
502
+ break;
503
+ }
504
+ if (arg === '--contract') {
505
+ if (!argv[i + 1]) {
506
+ missingGlobalValueFlag = '--contract';
507
+ } else {
508
+ contractPath = argv[++i] ;
509
+ }
510
+ } else if (arg === '--cwd' || arg === '-C') {
511
+ if (!argv[i + 1]) {
512
+ missingGlobalValueFlag = arg;
513
+ } else {
514
+ cwdArg = argv[++i] ;
515
+ }
516
+ } else if (arg === '--json') {
517
+ jsonOut = true;
518
+ } else if (arg === '-h' || arg === '--help') {
519
+ helpRequested = true;
520
+ } else {
521
+ rest.push(arg);
522
+ }
523
+ }
524
+
525
+ const cmd = rest[0];
526
+ if (cmd === 'help') {
527
+ const topic = rest[1];
528
+ if (topic && printCommandHelp(topic)) return 0;
529
+ printHelp();
530
+ return 0;
531
+ }
532
+ if (helpRequested) {
533
+ if (cmd && printCommandHelp(cmd)) return 0;
534
+ printHelp();
535
+ return 0;
536
+ }
537
+ if (missingGlobalValueFlag) {
538
+ return failCliArg(cmd ?? '', `Option "${missingGlobalValueFlag}" requires a value`, jsonOut);
539
+ }
540
+ if (!cmd) {
541
+ printHelp();
542
+ return EXIT_INCOMPLETE;
543
+ }
544
+
545
+ const workCwd = cwdArg ? path.resolve(process.cwd(), cwdArg) : process.cwd();
546
+ if (cwdArg) {
547
+ if (!fs.existsSync(workCwd) || !fs.statSync(workCwd).isDirectory()) {
548
+ return failCliArg(cmd, `Directory not found for --cwd: "${cwdArg}"`, jsonOut);
549
+ }
550
+ }
551
+
552
+ const subArgs = rest.slice(1);
553
+
554
+ if (cmd === 'print-config') {
555
+ const badFlag = subArgs.find((a) => a.startsWith('-'));
556
+ if (badFlag) return failUnknownFlag('print-config', badFlag, jsonOut);
557
+ const kind = subArgs[0];
558
+ if (kind === 'claude-code') process.stdout.write(generateClaudeCodeConfig(contractPath) + '\n');
559
+ else if (kind === 'codex') process.stdout.write(generateCodexConfig(contractPath) + '\n');
560
+ else if (kind === 'gemini') process.stdout.write(generateGeminiCliConfig(contractPath) + '\n');
561
+ else if (kind === 'agy') process.stdout.write(generateAgyConfig(contractPath) + '\n');
562
+ else {
563
+ process.stderr.write(`Unknown config target "${String(kind)}". Expected claude-code|codex|gemini|agy.\n`);
564
+ return EXIT_INCOMPLETE;
565
+ }
566
+ return EXIT_PASS;
567
+ }
568
+
569
+ if (cmd === 'init') {
570
+ let taskId = 'task-001';
571
+ let taskType = 'coding';
572
+ let mission = 'Bounded implementation task';
573
+ let startingSha = '';
574
+ let branch = '';
575
+ let implementerSpec = 'worker:session-1:manual';
576
+ let maxBudgetUsd ;
577
+ let lockfilePath ;
578
+ let allowNoChecks = false;
579
+ let allowNoCommit = false;
580
+ const allowedPaths = [];
581
+ const readOnlyPaths = [];
582
+ const forbiddenPaths = [];
583
+ const checks = [];
584
+ const advisoryChecks = [];
585
+ const checkTimeouts = new Map ();
586
+
587
+ for (let i = 0; i < subArgs.length; i++) {
588
+ const a = subArgs[i] ;
589
+ if (a === '--task-id') {
590
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--task-id" requires a value', jsonOut);
591
+ taskId = subArgs[++i] ;
592
+ } else if (a === '--type') {
593
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--type" requires a value', jsonOut);
594
+ taskType = subArgs[++i] ;
595
+ } else if (a === '--mission') {
596
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--mission" requires a value', jsonOut);
597
+ mission = subArgs[++i] ;
598
+ } else if (a === '--starting-sha') {
599
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--starting-sha" requires a value', jsonOut);
600
+ startingSha = subArgs[++i] ;
601
+ } else if (a === '--branch') {
602
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--branch" requires a value', jsonOut);
603
+ branch = subArgs[++i] ;
604
+ } else if (a === '--implementer') {
605
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--implementer" requires a value', jsonOut);
606
+ implementerSpec = subArgs[++i] ;
607
+ } else if (a === '--allow') {
608
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--allow" requires a value', jsonOut);
609
+ allowedPaths.push(subArgs[++i] );
610
+ } else if (a === '--read-only') {
611
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--read-only" requires a value', jsonOut);
612
+ readOnlyPaths.push(subArgs[++i] );
613
+ } else if (a === '--forbid') {
614
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--forbid" requires a value', jsonOut);
615
+ forbiddenPaths.push(subArgs[++i] );
616
+ } else if (a === '--max-budget') {
617
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--max-budget" requires a value', jsonOut);
618
+ maxBudgetUsd = Number(subArgs[++i] );
619
+ } else if (a === '--lockfile') {
620
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--lockfile" requires a value', jsonOut);
621
+ lockfilePath = subArgs[++i] ;
622
+ } else if (a === '--allow-no-checks') {
623
+ allowNoChecks = true;
624
+ } else if (a === '--allow-no-commit') {
625
+ allowNoCommit = true;
626
+ } else if (a === '--check') {
627
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--check" requires a value', jsonOut);
628
+ const rawChk = subArgs[++i] ;
629
+ const eq = rawChk.indexOf('=');
630
+ if (eq === -1) {
631
+ checks.push({ id: `check-${checks.length + 1}`, command: rawChk, forbid_skipped: true });
632
+ } else {
633
+ checks.push({
634
+ id: rawChk.slice(0, eq),
635
+ command: rawChk.slice(eq + 1),
636
+ forbid_skipped: true
637
+ });
638
+ }
639
+ } else if (a === '--advisory-check') {
640
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--advisory-check" requires a value', jsonOut);
641
+ const rawChk = subArgs[++i] ;
642
+ const eq = rawChk.indexOf('=');
643
+ if (eq === -1) {
644
+ advisoryChecks.push({ id: `advisory-${advisoryChecks.length + 1}`, command: rawChk, forbid_skipped: false });
645
+ } else {
646
+ advisoryChecks.push({
647
+ id: rawChk.slice(0, eq),
648
+ command: rawChk.slice(eq + 1),
649
+ forbid_skipped: false
650
+ });
651
+ }
652
+ } else if (a === '--check-timeout') {
653
+ if (!subArgs[i + 1]) return failCliArg('init', 'Option "--check-timeout" requires a value', jsonOut);
654
+ const rawTo = subArgs[++i] ;
655
+ const eq = rawTo.indexOf('=');
656
+ if (eq > 0) {
657
+ const sec = Number(rawTo.slice(eq + 1));
658
+ if (Number.isFinite(sec) && sec > 0) {
659
+ checkTimeouts.set(rawTo.slice(0, eq), sec);
660
+ }
661
+ }
662
+ } else {
663
+ return failUnknownFlag('init', a, jsonOut);
664
+ }
665
+ }
666
+
667
+ for (const c of [...checks, ...advisoryChecks]) {
668
+ const customSec = checkTimeouts.get(c.id);
669
+ if (customSec !== undefined) c.timeout_sec = customSec;
670
+ }
671
+
672
+ try {
673
+ const repoRoot = resolveRepoRoot(workCwd);
674
+ let resolvedSha ;
675
+ if (startingSha) {
676
+ const canonical = resolveCommitSha(repoRoot, startingSha);
677
+ if (!canonical || !commitExists(repoRoot, canonical)) {
678
+ process.stderr.write(`starting_sha "${startingSha}" does not resolve to a commit\n`);
679
+ return EXIT_STALE;
680
+ }
681
+ resolvedSha = canonical;
682
+ } else {
683
+ resolvedSha = resolveHeadSha(repoRoot);
684
+ }
685
+ const resolvedBranch = branch || resolveCurrentBranch(repoRoot);
686
+ const implementer = parseSessionSpec(implementerSpec, '--implementer');
687
+
688
+ let lockfilePin = undefined;
689
+ if (lockfilePath) {
690
+ const lfAbs = path.resolve(repoRoot, lockfilePath);
691
+ if (!fs.existsSync(lfAbs)) {
692
+ process.stderr.write(`Lockfile "${lockfilePath}" not found\n`);
693
+ return EXIT_INCOMPLETE;
694
+ }
695
+ lockfilePin = {
696
+ path: lockfilePath,
697
+ sha256: sha256Hex(fs.readFileSync(lfAbs)),
698
+ must_remain_unmodified: true
699
+ };
700
+ }
701
+
702
+ const contract = validateContract({
703
+ schema_version: 'diffpact-contract-v0.1',
704
+ task_id: taskId,
705
+ task_type: taskType,
706
+ mission,
707
+ starting_sha: resolvedSha,
708
+ worktree: {
709
+ branch: resolvedBranch,
710
+ path: repoRoot,
711
+ require_clean_start: true,
712
+ require_clean_end: true
713
+ },
714
+ allowed_paths: allowedPaths,
715
+ ...(readOnlyPaths.length > 0 ? { read_only_paths: readOnlyPaths } : {}),
716
+ forbidden_paths: forbiddenPaths,
717
+ ...(lockfilePin ? { interfacedelta_lockfile: lockfilePin } : {}),
718
+ ...(maxBudgetUsd !== undefined
719
+ ? { budget: { max_budget_usd: maxBudgetUsd, max_delegation_depth: 1 } }
720
+ : {}),
721
+ required_checks: checks,
722
+ ...(advisoryChecks.length > 0 ? { advisory_checks: advisoryChecks } : {}),
723
+ ...(allowNoChecks ? { allow_no_checks: true } : {}),
724
+ ...(allowNoCommit ? { allow_no_commit: true } : {}),
725
+ implementer_session: implementer,
726
+ review_policy: {
727
+ required_reviews: 1,
728
+ require_non_self_certified: true,
729
+ require_raw_diff_inspection: true
730
+ }
731
+ });
732
+
733
+ const outAbs = path.resolve(workCwd, contractPath);
734
+ fs.mkdirSync(path.dirname(outAbs), { recursive: true });
735
+ fs.writeFileSync(outAbs, JSON.stringify(contract, null, 2) + '\n');
736
+ if (contractPath === '.diffpact/contract.json' || contractPath.startsWith('.diffpact/')) {
737
+ ensureGitInfoExclude(repoRoot, '.diffpact/');
738
+ }
739
+ const contractSha = canonicalSha256('diffpact/contract/v0.1', contract);
740
+ if (jsonOut) {
741
+ process.stdout.write(JSON.stringify({ contract_path: outAbs, contract_sha256: contractSha }) + '\n');
742
+ } else {
743
+ process.stdout.write(`Initialized ${outAbs} (sha256=${contractSha.slice(0, 16)}…)\n`);
744
+ }
745
+ return EXIT_PASS;
746
+ } catch (err) {
747
+ process.stderr.write(`diffpact init failed: ${(err ).message}\n`);
748
+ return EXIT_INCOMPLETE;
749
+ }
750
+ }
751
+
752
+ if (cmd === 'verify') {
753
+ let heartbeatSec = process.stderr.isTTY ? 0 : 30;
754
+ for (let i = 0; i < subArgs.length; i++) {
755
+ const a = subArgs[i] ;
756
+ if (a === '--heartbeat-sec') {
757
+ if (!subArgs[i + 1]) return failCliArg('verify', 'Option "--heartbeat-sec" requires a value', jsonOut);
758
+ const parsed = Number(subArgs[++i] );
759
+ if (Number.isFinite(parsed) && parsed >= 0) heartbeatSec = parsed;
760
+ } else {
761
+ return failUnknownFlag('verify', a, jsonOut);
762
+ }
763
+ }
764
+ const res =
765
+ heartbeatSec > 0
766
+ ? await runVerifyAsync({ contractPath, cwd: workCwd, heartbeatSec })
767
+ : runVerify({ contractPath, cwd: workCwd });
768
+ if (jsonOut) {
769
+ process.stdout.write(JSON.stringify(res.receipt ?? { exit_code: res.exitCode, error: res.error }, null, 2) + '\n');
770
+ } else if (res.receipt) {
771
+ process.stdout.write(
772
+ `diffpact verify: ${res.receipt.status.toUpperCase()} (exit ${res.exitCode}) | candidate=${res.receipt.candidate_sha.slice(0, 8)} | receipt=${res.receipt.receipt_sha256.slice(0, 12)}\n`
773
+ );
774
+ for (const v of res.receipt.violations) {
775
+ process.stderr.write(` - [${v.code}] ${v.message}\n`);
776
+ }
777
+ for (const adv of res.receipt.advisory_checks ?? []) {
778
+ if (adv.exit_code !== 0 || adv.skipped_count > 0) {
779
+ process.stderr.write(
780
+ ` - [ADVISORY:${adv.id}] non-blocking exit=${adv.exit_code} skipped=${adv.skipped_count} (${adv.duration_ms}ms)\n`
781
+ );
782
+ }
783
+ }
784
+ } else {
785
+ process.stderr.write(`diffpact verify: ${res.error}\n`);
786
+ }
787
+ return res.exitCode;
788
+ }
789
+
790
+ if (cmd === 'diff') {
791
+ if (subArgs.length > 0) {
792
+ return failUnknownFlag('diff', subArgs[0] , jsonOut);
793
+ }
794
+ const contractAbs = path.resolve(workCwd, contractPath);
795
+ if (!fs.existsSync(contractAbs)) {
796
+ process.stderr.write(`Missing contract at "${contractAbs}"\n`);
797
+ return EXIT_INCOMPLETE;
798
+ }
799
+ try {
800
+ const contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
801
+ const repoRoot = resolveRepoRoot(workCwd);
802
+ const headSha = resolveHeadSha(repoRoot);
803
+ const snap = collectRepoChanges(repoRoot, contract.starting_sha, headSha);
804
+ const patchText = runGitText(repoRoot, ['diff', '--binary', '-M', contract.starting_sha, headSha]);
805
+ if (jsonOut) {
806
+ process.stdout.write(
807
+ JSON.stringify(
808
+ {
809
+ task_id: contract.task_id,
810
+ starting_sha: contract.starting_sha,
811
+ candidate_sha: headSha,
812
+ raw_diff_sha256: snap.rawDiffSha256,
813
+ changed_files: snap.changedFiles,
814
+ untracked_files: snap.untrackedFiles,
815
+ diff: patchText
816
+ },
817
+ null,
818
+ 2
819
+ ) + '\n'
820
+ );
821
+ } else {
822
+ process.stdout.write(patchText);
823
+ if (patchText && !patchText.endsWith('\n')) process.stdout.write('\n');
824
+ process.stdout.write(
825
+ `\n# diffpact diff | task=${contract.task_id} | ${contract.starting_sha.slice(0, 8)}..${headSha.slice(0, 8)} | raw_diff_sha256=${snap.rawDiffSha256}\n`
826
+ );
827
+ process.stdout.write(
828
+ `# Review with: diffpact review --reviewer <agent:session:harness> --verdict approve --diff-sha ${snap.rawDiffSha256.slice(0, 16)} --summary "..."\n`
829
+ );
830
+ }
831
+ return EXIT_PASS;
832
+ } catch (err) {
833
+ process.stderr.write(`diffpact diff failed: ${(err ).message}\n`);
834
+ return EXIT_INCOMPLETE;
835
+ }
836
+ }
837
+
838
+ if (cmd === 'merge-verify') {
839
+ const fromPaths = [];
840
+ const allowIntegrationPaths = [];
841
+ let integrationReason ;
842
+ let allowUntracked = false;
843
+ let baseSha ;
844
+ let receiptPath ;
845
+ let writeReceipt = true;
846
+ let heartbeatSec = process.stderr.isTTY ? 0 : 30;
847
+
848
+ for (let i = 0; i < subArgs.length; i++) {
849
+ const a = subArgs[i] ;
850
+ if (a === '--from') {
851
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--from" requires a value', jsonOut);
852
+ fromPaths.push(subArgs[++i] );
853
+ } else if (a === '--base') {
854
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--base" requires a value', jsonOut);
855
+ baseSha = subArgs[++i] ;
856
+ } else if (a === '--allow-integration') {
857
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--allow-integration" requires a value', jsonOut);
858
+ allowIntegrationPaths.push(subArgs[++i] );
859
+ } else if (a === '--reason') {
860
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--reason" requires a value', jsonOut);
861
+ integrationReason = subArgs[++i] ;
862
+ } else if (a === '--allow-untracked' || a === '--committed-only') {
863
+ allowUntracked = true;
864
+ } else if (a === '--write-receipt') {
865
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--write-receipt" requires a value', jsonOut);
866
+ receiptPath = subArgs[++i] ;
867
+ } else if (a === '--no-write') {
868
+ writeReceipt = false;
869
+ } else if (a === '--heartbeat-sec') {
870
+ if (!subArgs[i + 1]) return failCliArg('merge-verify', 'Option "--heartbeat-sec" requires a value', jsonOut);
871
+ const parsed = Number(subArgs[++i] );
872
+ if (Number.isFinite(parsed) && parsed >= 0) heartbeatSec = parsed;
873
+ } else if (a.startsWith('-')) {
874
+ return failUnknownFlag('merge-verify', a, jsonOut);
875
+ } else {
876
+ fromPaths.push(a);
877
+ }
878
+ }
879
+
880
+ if (fromPaths.length === 0) {
881
+ process.stderr.write(
882
+ 'Usage: diffpact merge-verify --from <contract-or-archive-dir> [--from <path> ...] [--base <sha>] [--allow-integration <glob>] [--reason <text>] [--allow-untracked] [--heartbeat-sec <n>]\n'
883
+ );
884
+ return EXIT_INCOMPLETE;
885
+ }
886
+
887
+ const res = await runMergeVerify({
888
+ fromPaths,
889
+ cwd: workCwd,
890
+ baseSha,
891
+ ...(allowIntegrationPaths.length > 0 ? { allowIntegrationPaths } : {}),
892
+ ...(integrationReason ? { integrationReason } : {}),
893
+ ...(allowUntracked ? { allowUntracked } : {}),
894
+ writeReceipt,
895
+ receiptPath,
896
+ heartbeatSec
897
+ });
898
+ if (jsonOut) {
899
+ process.stdout.write(
900
+ JSON.stringify(
901
+ res.receipt ? { ...res.receipt, ...(res.receiptPath ? { receipt_path: res.receiptPath } : {}) } : { exit_code: res.exitCode, error: res.error },
902
+ null,
903
+ 2
904
+ ) + '\n'
905
+ );
906
+ } else if (res.receipt) {
907
+ process.stdout.write(
908
+ `diffpact merge-verify: ${res.receipt.status.toUpperCase()} (exit ${res.exitCode}) | contracts=${res.receipt.source_contracts.length} | checks=${res.receipt.checks.length} | merged=${res.receipt.merged_sha.slice(0, 8)} | receipt=${res.receipt.merge_receipt_sha256.slice(0, 12)}${res.receiptPath ? ` (${res.receiptPath})` : ''}\n`
909
+ );
910
+ for (const v of res.receipt.violations) {
911
+ process.stderr.write(` - [${v.code}] ${v.message}\n`);
912
+ }
913
+ if (
914
+ !allowUntracked &&
915
+ res.receipt.diff_summary.untracked_files.length > 0 &&
916
+ res.receipt.violations.some((v) => v.code === 'DIRTY_WORKING_TREE' && v.message.includes('untracked file(s)'))
917
+ ) {
918
+ process.stderr.write(
919
+ ' hint: Pre-existing untracked files on main tripped DIRTY_WORKING_TREE; stash/gitignore them or pass `--allow-untracked` (alias `--committed-only`) to verify only the committed merge diff (base..HEAD) while still blocking dirty tracked files.\n'
920
+ );
921
+ }
922
+ if (
923
+ allowIntegrationPaths.length === 0 &&
924
+ res.receipt.violations.some((v) => v.code === 'OUTSIDE_ALLOWED_PATHS')
925
+ ) {
926
+ process.stderr.write(
927
+ ' hint: Run `diffpact merge-verify` immediately after merging before manual orchestrator fixes, or pass `--allow-integration <glob> --reason "..."` to explicitly authorize integration glue files in merge-receipt.json.\n'
928
+ );
929
+ }
930
+ for (const adv of res.receipt.advisory_checks ?? []) {
931
+ if (adv.exit_code !== 0 || adv.skipped_count > 0) {
932
+ process.stderr.write(
933
+ ` - [ADVISORY:${adv.id}] non-blocking exit=${adv.exit_code} skipped=${adv.skipped_count} (${adv.duration_ms}ms)\n`
934
+ );
935
+ }
936
+ }
937
+ } else {
938
+ process.stderr.write(`diffpact merge-verify: ${res.error}\n`);
939
+ }
940
+ return res.exitCode;
941
+ }
942
+
943
+ if (cmd === 'exec' || cmd === 'wrap') {
944
+ const dashIdx = subArgs.indexOf('--');
945
+ const preFlags = dashIdx >= 0 ? subArgs.slice(0, dashIdx) : [];
946
+ const childCmd = dashIdx >= 0 ? subArgs.slice(dashIdx + 1) : subArgs;
947
+ if (childCmd.length === 0) {
948
+ process.stderr.write('diffpact exec requires a command after "--"\n');
949
+ return EXIT_INCOMPLETE;
950
+ }
951
+
952
+ let resume = false;
953
+ let heartbeatSec = process.stderr.isTTY ? 0 : 30;
954
+ for (let i = 0; i < preFlags.length; i++) {
955
+ const a = preFlags[i] ;
956
+ if (a === '--resume' || a === '--allow-in-scope-dirty') {
957
+ resume = true;
958
+ } else if (a === '--heartbeat-sec') {
959
+ if (!preFlags[i + 1]) return failCliArg(cmd, 'Option "--heartbeat-sec" requires a value', jsonOut);
960
+ const parsed = Number(preFlags[++i] );
961
+ if (Number.isFinite(parsed) && parsed >= 0) heartbeatSec = parsed;
962
+ } else {
963
+ return failUnknownFlag(cmd, a, jsonOut);
964
+ }
965
+ }
966
+
967
+ return executeBoundedWorkerCommand({
968
+ contractPath,
969
+ cwd: workCwd,
970
+ childCmd,
971
+ resume,
972
+ heartbeatSec,
973
+ label: `exec "${childCmd[0]}"`
974
+ });
975
+ }
976
+
977
+ if (cmd === 'run') {
978
+ let harnessRaw = '';
979
+ let model ;
980
+ let reasoningEffort ;
981
+ let dataDir ;
982
+ let prompt = '';
983
+ let promptFile = '';
984
+ let resume = false;
985
+ let dryRun = false;
986
+ let heartbeatSec = process.stderr.isTTY ? 0 : 30;
987
+
988
+ for (let i = 0; i < subArgs.length; i++) {
989
+ const a = subArgs[i] ;
990
+ if (a === '--harness') {
991
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--harness" requires a value', jsonOut);
992
+ harnessRaw = subArgs[++i] ;
993
+ } else if (a === '--model') {
994
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--model" requires a value', jsonOut);
995
+ model = subArgs[++i] ;
996
+ } else if (a === '--reasoning-effort') {
997
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--reasoning-effort" requires a value', jsonOut);
998
+ reasoningEffort = subArgs[++i] ;
999
+ } else if (a === '--data-dir') {
1000
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--data-dir" requires a value', jsonOut);
1001
+ dataDir = subArgs[++i] ;
1002
+ } else if (a === '--prompt') {
1003
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--prompt" requires a value', jsonOut);
1004
+ prompt = subArgs[++i] ;
1005
+ } else if (a === '--prompt-file') {
1006
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--prompt-file" requires a value', jsonOut);
1007
+ promptFile = subArgs[++i] ;
1008
+ } else if (a === '--resume' || a === '--allow-in-scope-dirty') {
1009
+ resume = true;
1010
+ } else if (a === '--dry-run') {
1011
+ dryRun = true;
1012
+ } else if (a === '--heartbeat-sec') {
1013
+ if (!subArgs[i + 1]) return failCliArg('run', 'Option "--heartbeat-sec" requires a value', jsonOut);
1014
+ const parsed = Number(subArgs[++i] );
1015
+ if (Number.isFinite(parsed) && parsed >= 0) heartbeatSec = parsed;
1016
+ } else {
1017
+ return failUnknownFlag('run', a, jsonOut);
1018
+ }
1019
+ }
1020
+
1021
+ const harnessMap = {
1022
+ claude: 'claude',
1023
+ 'claude-code': 'claude',
1024
+ codex: 'codex',
1025
+ crush: 'crush',
1026
+ agy: 'agy',
1027
+ 'agy-worker': 'agy',
1028
+ gemini: 'gemini',
1029
+ 'gemini-cli': 'gemini'
1030
+ };
1031
+ const harness = harnessMap[harnessRaw];
1032
+ if (!harness) {
1033
+ process.stderr.write(
1034
+ 'Usage: diffpact run --harness <claude|codex|crush|agy|gemini> (--prompt <text> | --prompt-file <path>) [--model <m>] [--reasoning-effort <lvl>] [--data-dir <dir>] [--resume] [--heartbeat-sec <n>] [--dry-run]\n'
1035
+ );
1036
+ return EXIT_INCOMPLETE;
1037
+ }
1038
+
1039
+ if (promptFile) {
1040
+ const absPrompt = path.resolve(workCwd, promptFile);
1041
+ if (!fs.existsSync(absPrompt)) {
1042
+ process.stderr.write(`Prompt file not found: "${absPrompt}"\n`);
1043
+ return EXIT_INCOMPLETE;
1044
+ }
1045
+ prompt = fs.readFileSync(absPrompt, 'utf8').trim();
1046
+ }
1047
+ if (!prompt) {
1048
+ process.stderr.write('diffpact run requires --prompt <text> or --prompt-file <path>\n');
1049
+ return EXIT_INCOMPLETE;
1050
+ }
1051
+
1052
+ const repoRoot = resolveRepoRoot(workCwd);
1053
+ const built = buildHarnessCommand({ harness, repoRoot, prompt, model, reasoningEffort, dataDir });
1054
+ if (dryRun) {
1055
+ if (jsonOut) {
1056
+ process.stdout.write(JSON.stringify(built, null, 2) + '\n');
1057
+ } else {
1058
+ process.stdout.write(`${built.bin} ${built.args.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(' ')}\n`);
1059
+ for (const n of built.notes) process.stderr.write(`note: ${n}\n`);
1060
+ }
1061
+ return EXIT_PASS;
1062
+ }
1063
+
1064
+ if (built.dataDir) {
1065
+ fs.mkdirSync(built.dataDir, { recursive: true });
1066
+ }
1067
+ for (const n of built.notes) {
1068
+ process.stderr.write(`[diffpact run] ${n}\n`);
1069
+ }
1070
+ return executeBoundedWorkerCommand({
1071
+ contractPath,
1072
+ cwd: workCwd,
1073
+ childCmd: [built.bin, ...built.args],
1074
+ resume,
1075
+ heartbeatSec,
1076
+ label: `harness "${harness}"`
1077
+ });
1078
+ }
1079
+
1080
+ if (cmd === 'worktree') {
1081
+ const action = subArgs[0];
1082
+ if (action === 'create') {
1083
+ let dir = '';
1084
+ let branch = '';
1085
+ let fromRef ;
1086
+ let shareNodeModules = false;
1087
+ const nodeModulesDirs = [];
1088
+ for (let i = 1; i < subArgs.length; i++) {
1089
+ const a = subArgs[i] ;
1090
+ if (a === '--branch') {
1091
+ if (!subArgs[i + 1]) return failCliArg('worktree', 'Option "--branch" requires a value', jsonOut);
1092
+ branch = subArgs[++i] ;
1093
+ } else if (a === '--from') {
1094
+ if (!subArgs[i + 1]) return failCliArg('worktree', 'Option "--from" requires a value', jsonOut);
1095
+ fromRef = subArgs[++i] ;
1096
+ } else if (a === '--share-node-modules') {
1097
+ shareNodeModules = true;
1098
+ } else if (a === '--node-modules-dir') {
1099
+ if (!subArgs[i + 1]) return failCliArg('worktree', 'Option "--node-modules-dir" requires a value', jsonOut);
1100
+ nodeModulesDirs.push(subArgs[++i] );
1101
+ } else if (a.startsWith('-')) {
1102
+ return failUnknownFlag('worktree', a, jsonOut);
1103
+ } else if (!dir) {
1104
+ dir = a;
1105
+ } else {
1106
+ return failCliArg('worktree', `Unexpected extra positional argument "${a}"`, jsonOut);
1107
+ }
1108
+ }
1109
+ if (!dir || !branch) {
1110
+ process.stderr.write(
1111
+ 'Usage: diffpact worktree create <dir> --branch <name> [--from <ref>] [--share-node-modules] [--node-modules-dir <subdir>]\n'
1112
+ );
1113
+ return EXIT_INCOMPLETE;
1114
+ }
1115
+ try {
1116
+ const res = createManagedWorktree({
1117
+ cwd: workCwd,
1118
+ dir,
1119
+ branch,
1120
+ fromRef,
1121
+ shareNodeModules,
1122
+ ...(nodeModulesDirs.length > 0 ? { nodeModulesDirs } : {})
1123
+ });
1124
+ if (jsonOut) {
1125
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
1126
+ } else {
1127
+ const pathsLabel = res.sharedNodeModulesPaths?.join(', ') ?? 'node_modules';
1128
+ const nmSummary = res.sharedNodeModules
1129
+ ? res.workspaceMode === 'workspace-overlay'
1130
+ ? `, workspace-aware ${pathsLabel} (${res.workspacePackagesLinked?.length ?? 0} local workspace package(s) linked)`
1131
+ : `, shared ${pathsLabel} excluded cleanly`
1132
+ : '';
1133
+ process.stdout.write(`Created worktree ${res.worktreePath} (branch=${res.branch}${nmSummary})\n`);
1134
+ if (res.nodeModulesNote) {
1135
+ process.stderr.write(`warning: ${res.nodeModulesNote}\n`);
1136
+ }
1137
+ }
1138
+ return EXIT_PASS;
1139
+ } catch (err) {
1140
+ process.stderr.write(`diffpact worktree create failed: ${(err ).message}\n`);
1141
+ return EXIT_VIOLATION;
1142
+ }
1143
+ }
1144
+
1145
+ if (action === 'remove') {
1146
+ let dir = '';
1147
+ let deleteBranch = false;
1148
+ let forceDeleteBranch = false;
1149
+ let force = false;
1150
+ let requireVerified = false;
1151
+ let archiveDir ;
1152
+ let noArchive = false;
1153
+ for (let i = 1; i < subArgs.length; i++) {
1154
+ const a = subArgs[i] ;
1155
+ if (a === '--delete-branch') deleteBranch = true;
1156
+ else if (a === '--force-delete-branch') forceDeleteBranch = true;
1157
+ else if (a === '--force') force = true;
1158
+ else if (a === '--require-verified') requireVerified = true;
1159
+ else if (a === '--archive-dir') {
1160
+ if (!subArgs[i + 1]) return failCliArg('worktree', 'Option "--archive-dir" requires a value', jsonOut);
1161
+ archiveDir = subArgs[++i] ;
1162
+ } else if (a === '--no-archive') noArchive = true;
1163
+ else if (a.startsWith('-')) return failUnknownFlag('worktree', a, jsonOut);
1164
+ else if (!dir) dir = a;
1165
+ else return failCliArg('worktree', `Unexpected extra positional argument "${a}"`, jsonOut);
1166
+ }
1167
+ if (!dir) {
1168
+ process.stderr.write(
1169
+ 'Usage: diffpact worktree remove <dir> [--delete-branch] [--force-delete-branch] [--force] [--require-verified] [--archive-dir <dir>] [--no-archive]\n'
1170
+ );
1171
+ return EXIT_INCOMPLETE;
1172
+ }
1173
+ const res = removeManagedWorktree({
1174
+ cwd: workCwd,
1175
+ dir,
1176
+ deleteBranch,
1177
+ forceDeleteBranch,
1178
+ force,
1179
+ requireVerified,
1180
+ contractPath,
1181
+ archiveDir,
1182
+ noArchive
1183
+ });
1184
+ if (jsonOut) {
1185
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
1186
+ } else if (res.ok) {
1187
+ const branchMsg = res.branchDeleted && res.branch ? ` (deleted branch ${res.branch} via ${res.branchDeleteMode ?? '-d'})` : '';
1188
+ const archiveMsg = res.archivedTo ? ` (archived evidence to ${res.archivedTo})` : '';
1189
+ process.stdout.write(`Removed worktree ${res.worktreePath}${branchMsg}${archiveMsg}\n`);
1190
+ } else {
1191
+ process.stderr.write(`diffpact worktree remove failed: ${res.error}\n`);
1192
+ }
1193
+ return res.exitCode;
1194
+ }
1195
+
1196
+ process.stderr.write(
1197
+ 'Usage: diffpact worktree <create|remove> <dir> [options]\n'
1198
+ );
1199
+ return EXIT_INCOMPLETE;
1200
+ }
1201
+
1202
+ if (cmd === 'review') {
1203
+ let reviewerSpec = '';
1204
+ let verdictRaw ;
1205
+ let summary = 'Independent diff review completed';
1206
+ let adapter = '';
1207
+ let explicitInspectedRawDiff = false;
1208
+ let summaryOnly = false;
1209
+ let diffSha ;
1210
+ let lineageId ;
1211
+ const findings = [];
1212
+
1213
+ const dashIdx = subArgs.indexOf('--');
1214
+ const flagArgs = dashIdx >= 0 ? subArgs.slice(0, dashIdx) : subArgs;
1215
+ const wrappedArgs = dashIdx >= 0 ? subArgs.slice(dashIdx + 1) : [];
1216
+
1217
+ for (let i = 0; i < flagArgs.length; i++) {
1218
+ const a = flagArgs[i] ;
1219
+ if (a === '--reviewer') {
1220
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--reviewer" requires a value', jsonOut);
1221
+ reviewerSpec = flagArgs[++i] ;
1222
+ } else if (a === '--verdict') {
1223
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--verdict" requires a value ("approve" or "reject")', jsonOut);
1224
+ verdictRaw = flagArgs[++i] ;
1225
+ } else if (a === '--summary') {
1226
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--summary" requires a value', jsonOut);
1227
+ summary = flagArgs[++i] ;
1228
+ } else if (a === '--finding') {
1229
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--finding" requires a value', jsonOut);
1230
+ findings.push(flagArgs[++i] );
1231
+ } else if (a === '--adapter') {
1232
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--adapter" requires a value', jsonOut);
1233
+ adapter = flagArgs[++i] ;
1234
+ } else if (a === '--lineage') {
1235
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--lineage" requires a value', jsonOut);
1236
+ lineageId = flagArgs[++i] ;
1237
+ } else if (a === '--diff-sha') {
1238
+ if (!flagArgs[i + 1]) return failCliArg('review', 'Option "--diff-sha" requires a value', jsonOut);
1239
+ diffSha = flagArgs[++i] ;
1240
+ } else if (a === '--inspected-raw-diff') {
1241
+ explicitInspectedRawDiff = true;
1242
+ } else if (a === '--summary-only') {
1243
+ summaryOnly = true;
1244
+ } else {
1245
+ const hint =
1246
+ a === '--decision' || a === '--status' || a === '--result'
1247
+ ? 'Use --verdict <approve|reject>.'
1248
+ : undefined;
1249
+ return failUnknownFlag('review', a, jsonOut, hint);
1250
+ }
1251
+ }
1252
+
1253
+ if (adapter === 'codex' && wrappedArgs.length > 0) {
1254
+ const reviewerAgentId = reviewerSpec.split(':')[0] || 'codex-reviewer';
1255
+ const res = runWrappedCodexReview({
1256
+ contractPath,
1257
+ cwd: workCwd,
1258
+ reviewerAgentId,
1259
+ commandArgs: wrappedArgs,
1260
+ inspectedRawDiff: !summaryOnly,
1261
+ evidenceLineageId: lineageId
1262
+ });
1263
+ if (jsonOut) {
1264
+ process.stdout.write(
1265
+ JSON.stringify({ exit_code: res.exitCode, review_sha256: res.reviewSha256, ...(res.error ? { error: res.error } : {}) }) + '\n'
1266
+ );
1267
+ } else if (res.error) {
1268
+ process.stderr.write(`diffpact review [codex]: ${res.error}\n`);
1269
+ }
1270
+ return res.exitCode;
1271
+ }
1272
+
1273
+ if (!verdictRaw) {
1274
+ return failCliArg(
1275
+ 'review',
1276
+ 'Missing required --verdict <approve|reject> option (verdict never defaults to approve).',
1277
+ jsonOut
1278
+ );
1279
+ }
1280
+ if (verdictRaw !== 'approve' && verdictRaw !== 'reject') {
1281
+ return failCliArg(
1282
+ 'review',
1283
+ `Invalid --verdict "${verdictRaw}". Expected "approve" or "reject".`,
1284
+ jsonOut
1285
+ );
1286
+ }
1287
+ const verdict = verdictRaw;
1288
+
1289
+ // On CLI, raw-diff inspection is NEVER silently assumed true; reviewer must pass --diff-sha <sha> or --inspected-raw-diff
1290
+ const inspectedRawDiff = !summaryOnly && (explicitInspectedRawDiff || Boolean(diffSha));
1291
+ if (!inspectedRawDiff && !summaryOnly) {
1292
+ const msg =
1293
+ 'Raw-diff inspection must be explicitly attested: run `diffpact diff` to inspect the primary Git diff, then pass `--diff-sha <sha>` (recommended) or `--inspected-raw-diff` (or `--summary-only` if contract disables raw-diff inspection).';
1294
+ if (jsonOut) {
1295
+ process.stdout.write(JSON.stringify({ exit_code: EXIT_INCOMPLETE, error: msg }, null, 2) + '\n');
1296
+ } else {
1297
+ process.stderr.write(`diffpact review: ${msg}\n`);
1298
+ }
1299
+ return EXIT_INCOMPLETE;
1300
+ }
1301
+
1302
+ try {
1303
+ const reviewer = parseSessionSpec(reviewerSpec, '--reviewer');
1304
+ const res = runReview({
1305
+ contractPath,
1306
+ cwd: workCwd,
1307
+ reviewer,
1308
+ verdict,
1309
+ summary,
1310
+ findings,
1311
+ inspectedRawDiff,
1312
+ expectedRawDiffSha256: diffSha,
1313
+ attestationMode: diffSha ? 'diff-sha-bound' : 'cli-explicit',
1314
+ evidenceLineageId: lineageId
1315
+ });
1316
+ if (jsonOut) {
1317
+ process.stdout.write(JSON.stringify(res.review ?? { exit_code: res.exitCode, error: res.error }, null, 2) + '\n');
1318
+ } else if (res.error) {
1319
+ process.stderr.write(`diffpact review: ${res.error}\n`);
1320
+ } else if (res.review) {
1321
+ const modeTag = res.review.attestation_hmac_sha256
1322
+ ? `${res.review.attestation_mode}+hmac`
1323
+ : (res.review.attestation_mode ?? 'cli-explicit');
1324
+ process.stdout.write(
1325
+ `diffpact review: ${res.review.verdict.toUpperCase()} | reviewer=${reviewer.agent_id} | mode=${modeTag} | review=${res.review.review_sha256.slice(0, 12)}\n`
1326
+ );
1327
+ }
1328
+ return res.exitCode;
1329
+ } catch (err) {
1330
+ process.stderr.write(`diffpact review error: ${(err ).message}\n`);
1331
+ return EXIT_INCOMPLETE;
1332
+ }
1333
+ }
1334
+
1335
+ if (cmd === 'status') {
1336
+ let requireReview = false;
1337
+ let integratorAgentId ;
1338
+ for (let i = 0; i < subArgs.length; i++) {
1339
+ const a = subArgs[i] ;
1340
+ if (a === '--require-review') {
1341
+ requireReview = true;
1342
+ } else if (a === '--integrator') {
1343
+ if (!subArgs[i + 1]) return failCliArg('status', 'Option "--integrator" requires a value', jsonOut);
1344
+ integratorAgentId = subArgs[++i] ;
1345
+ } else {
1346
+ return failUnknownFlag('status', a, jsonOut);
1347
+ }
1348
+ }
1349
+ const st = checkStatus({ contractPath, cwd: workCwd, requireReview, integratorAgentId });
1350
+ if (jsonOut) {
1351
+ process.stdout.write(JSON.stringify(st, null, 2) + '\n');
1352
+ } else {
1353
+ process.stdout.write(`diffpact status: ${st.status.toUpperCase()} (exit ${st.exit_code}) — ${st.reason}\n`);
1354
+ }
1355
+ return st.exit_code;
1356
+ }
1357
+
1358
+ if (cmd === 'delegate') {
1359
+ let subtaskId = '';
1360
+ let mission = 'Delegated subtask';
1361
+ let implementerSpec = '';
1362
+ let budgetUsd ;
1363
+ let branch ;
1364
+ let worktreePath ;
1365
+ const allowedPaths = [];
1366
+
1367
+ for (let i = 0; i < subArgs.length; i++) {
1368
+ const a = subArgs[i] ;
1369
+ if (a === '--subtask-id') {
1370
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--subtask-id" requires a value', jsonOut);
1371
+ subtaskId = subArgs[++i] ;
1372
+ } else if (a === '--mission') {
1373
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--mission" requires a value', jsonOut);
1374
+ mission = subArgs[++i] ;
1375
+ } else if (a === '--implementer') {
1376
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--implementer" requires a value', jsonOut);
1377
+ implementerSpec = subArgs[++i] ;
1378
+ } else if (a === '--allow') {
1379
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--allow" requires a value', jsonOut);
1380
+ allowedPaths.push(subArgs[++i] );
1381
+ } else if (a === '--budget') {
1382
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--budget" requires a value', jsonOut);
1383
+ budgetUsd = Number(subArgs[++i] );
1384
+ } else if (a === '--branch') {
1385
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--branch" requires a value', jsonOut);
1386
+ branch = subArgs[++i] ;
1387
+ } else if (a === '--worktree') {
1388
+ if (!subArgs[i + 1]) return failCliArg('delegate', 'Option "--worktree" requires a value', jsonOut);
1389
+ worktreePath = subArgs[++i] ;
1390
+ } else {
1391
+ return failUnknownFlag('delegate', a, jsonOut);
1392
+ }
1393
+ }
1394
+
1395
+ try {
1396
+ const implementer = parseSessionSpec(implementerSpec, '--implementer');
1397
+ const res = createDelegatedSubcontract({
1398
+ parentContractPath: contractPath,
1399
+ cwd: workCwd,
1400
+ subtaskId,
1401
+ mission,
1402
+ allowedPaths,
1403
+ reservedBudgetUsd: budgetUsd,
1404
+ implementer,
1405
+ branch,
1406
+ worktreePath
1407
+ });
1408
+ if (res.error) {
1409
+ process.stderr.write(`diffpact delegate: ${res.error}\n`);
1410
+ } else if (jsonOut) {
1411
+ process.stdout.write(JSON.stringify({ subcontract_path: res.subcontractPath }) + '\n');
1412
+ } else {
1413
+ process.stdout.write(`Created delegated subcontract ${res.subcontractPath}\n`);
1414
+ }
1415
+ return res.exitCode;
1416
+ } catch (err) {
1417
+ process.stderr.write(`diffpact delegate error: ${(err ).message}\n`);
1418
+ return EXIT_INCOMPLETE;
1419
+ }
1420
+ }
1421
+
1422
+ if (cmd === 'hook' || cmd === 'gate') {
1423
+ const firstArgIsJson = Boolean(subArgs[0]?.trim().startsWith('{'));
1424
+ const target = firstArgIsJson ? 'auto' : (subArgs[0] ?? 'auto');
1425
+ if (target.startsWith('-')) {
1426
+ return failUnknownFlag(cmd, target, jsonOut);
1427
+ }
1428
+ const rawArgPayload = firstArgIsJson ? subArgs[0] : subArgs[1];
1429
+ const stdinText = rawArgPayload ?? readStdinUtf8();
1430
+ const resolvedContractPath = cwdArg ? path.resolve(workCwd, contractPath) : contractPath;
1431
+
1432
+ let payload = {};
1433
+ if (stdinText.trim()) {
1434
+ try {
1435
+ payload = JSON.parse(stdinText) ;
1436
+ } catch (err) {
1437
+ process.stderr.write(`diffpact hook: invalid JSON payload: ${(err ).message}\n`);
1438
+ return 2;
1439
+ }
1440
+ }
1441
+
1442
+ let resolvedTarget = target;
1443
+ if (target === 'auto') {
1444
+ if ('hookEventName' in payload || 'toolCall' in payload) resolvedTarget = 'agy';
1445
+ else if (payload.type === 'agent-turn-complete') resolvedTarget = 'codex-notify';
1446
+ else if (
1447
+ payload.hook_event_name === 'BeforeTool' ||
1448
+ payload.hook_event_name === 'AfterTool' ||
1449
+ payload.hook_event_name === 'AfterAgent'
1450
+ ) {
1451
+ resolvedTarget = 'gemini';
1452
+ } else if (payload.tool_name === 'apply_patch') resolvedTarget = 'codex';
1453
+ else resolvedTarget = 'claude-code';
1454
+ }
1455
+
1456
+ let res;
1457
+ if (resolvedTarget === 'claude-code') res = handleClaudeCodeHook(payload, resolvedContractPath);
1458
+ else if (resolvedTarget === 'codex') res = handleCodexHook(payload, resolvedContractPath);
1459
+ else if (resolvedTarget === 'codex-notify') res = handleCodexNotify(payload, resolvedContractPath);
1460
+ else if (resolvedTarget === 'gemini') res = handleGeminiCliHook(payload, resolvedContractPath);
1461
+ else if (resolvedTarget === 'agy') res = handleAgyHook(payload, resolvedContractPath);
1462
+ else {
1463
+ process.stderr.write(`Unknown hook target "${resolvedTarget}"\n`);
1464
+ return 2;
1465
+ }
1466
+
1467
+ if (res.stderr) process.stderr.write(res.stderr + '\n');
1468
+ if (res.stdout) process.stdout.write(res.stdout + '\n');
1469
+ return res.exitCode;
1470
+ }
1471
+
1472
+ if (cmd === 'board') {
1473
+ let vbBin ;
1474
+ let requireReview = true;
1475
+ let summaryMessage ;
1476
+ const positionals = [];
1477
+ for (let i = 0; i < subArgs.length; i++) {
1478
+ const a = subArgs[i] ;
1479
+ if (a === '--vb-bin') {
1480
+ if (!subArgs[i + 1]) return failCliArg('board', 'Option "--vb-bin" requires a value', jsonOut);
1481
+ vbBin = subArgs[++i] ;
1482
+ } else if (a === '--no-require-review') {
1483
+ requireReview = false;
1484
+ } else if (a === '--message') {
1485
+ if (!subArgs[i + 1]) return failCliArg('board', 'Option "--message" requires a value', jsonOut);
1486
+ summaryMessage = subArgs[++i] ;
1487
+ } else if (a.startsWith('-')) {
1488
+ return failUnknownFlag('board', a, jsonOut);
1489
+ } else {
1490
+ positionals.push(a);
1491
+ }
1492
+ }
1493
+ const action = positionals[0];
1494
+ const taskId = positionals[1];
1495
+ if (!action || !taskId) {
1496
+ process.stderr.write('Usage: diffpact board <post-contract|complete> <task-id> [--vb-bin <path>] [--no-require-review]\n');
1497
+ return EXIT_INCOMPLETE;
1498
+ }
1499
+
1500
+ if (action === 'post-contract') {
1501
+ const r = boardPostContract({ contractPath, cwd: workCwd, taskId, vbBin });
1502
+ if (jsonOut) process.stdout.write(JSON.stringify(r) + '\n');
1503
+ else process.stdout.write(r.message + '\n');
1504
+ return r.exitCode;
1505
+ }
1506
+ if (action === 'complete') {
1507
+ const r = boardCompleteGate({
1508
+ contractPath,
1509
+ cwd: workCwd,
1510
+ taskId,
1511
+ vbBin,
1512
+ requireReview,
1513
+ summaryMessage
1514
+ });
1515
+ if (jsonOut) process.stdout.write(JSON.stringify(r) + '\n');
1516
+ else process.stdout.write(`${r.action.toUpperCase()}: ${r.detail}\n`);
1517
+ return r.exitCode;
1518
+ }
1519
+ process.stderr.write(`Unknown board subcommand "${action}"\n`);
1520
+ return EXIT_INCOMPLETE;
1521
+ }
1522
+
1523
+ if (cmd === 'agy-verify-patch') {
1524
+ let allowEmpty = false;
1525
+ const positionals = [];
1526
+ for (const a of subArgs) {
1527
+ if (a === '--allow-empty') allowEmpty = true;
1528
+ else if (a.startsWith('-')) return failUnknownFlag('agy-verify-patch', a, jsonOut);
1529
+ else positionals.push(a);
1530
+ }
1531
+ const patchPath = positionals[0];
1532
+ if (!patchPath) {
1533
+ process.stderr.write('Usage: diffpact agy-verify-patch <patch-file> [--allow-empty]\n');
1534
+ return EXIT_INCOMPLETE;
1535
+ }
1536
+ const r = verifyAgyWorkerPatch({ contractPath, cwd: workCwd, patchPath, allowEmpty });
1537
+ if (jsonOut) {
1538
+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');
1539
+ } else if (r.exitCode === 0) {
1540
+ process.stdout.write(`agy-verify-patch PASS (${r.paths.length} file(s) within contract boundaries)\n`);
1541
+ } else {
1542
+ process.stderr.write(`agy-verify-patch BLOCKED (exit ${r.exitCode}):\n - ${r.violations.join('\n - ')}\n`);
1543
+ }
1544
+ return r.exitCode;
1545
+ }
1546
+
1547
+ if (cmd === 'amend') {
1548
+ let showHistory = false;
1549
+ let authorizedBy = '';
1550
+ let reason = '';
1551
+ let updateStartingSha ;
1552
+ const addAllowedPaths = [];
1553
+ const addReadOnlyPaths = [];
1554
+ const addForbiddenPaths = [];
1555
+ for (let i = 0; i < subArgs.length; i++) {
1556
+ const a = subArgs[i] ;
1557
+ if (a === '--history') {
1558
+ showHistory = true;
1559
+ } else if (a === '--authorized-by') {
1560
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--authorized-by" requires a value', jsonOut);
1561
+ authorizedBy = subArgs[++i] ;
1562
+ } else if (a === '--reason') {
1563
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--reason" requires a value', jsonOut);
1564
+ reason = subArgs[++i] ;
1565
+ } else if (a === '--add-allow') {
1566
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--add-allow" requires a value', jsonOut);
1567
+ addAllowedPaths.push(subArgs[++i] );
1568
+ } else if (a === '--add-read-only') {
1569
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--add-read-only" requires a value', jsonOut);
1570
+ addReadOnlyPaths.push(subArgs[++i] );
1571
+ } else if (a === '--add-forbid') {
1572
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--add-forbid" requires a value', jsonOut);
1573
+ addForbiddenPaths.push(subArgs[++i] );
1574
+ } else if (a === '--update-starting-sha') {
1575
+ if (!subArgs[i + 1]) return failCliArg('amend', 'Option "--update-starting-sha" requires a value', jsonOut);
1576
+ updateStartingSha = subArgs[++i] ;
1577
+ } else {
1578
+ return failUnknownFlag('amend', a, jsonOut);
1579
+ }
1580
+ }
1581
+ if (showHistory) {
1582
+ const hist = readAmendmentHistory(contractPath, workCwd);
1583
+ if (jsonOut) process.stdout.write(JSON.stringify(hist, null, 2) + '\n');
1584
+ else process.stdout.write(`Amendments: ${hist.entries.length} (valid=${hist.valid})\n`);
1585
+ return hist.valid ? EXIT_PASS : EXIT_VIOLATION;
1586
+ }
1587
+ const res = amendContract({
1588
+ contractPath,
1589
+ cwd: workCwd,
1590
+ authorizedBy,
1591
+ reason,
1592
+ addAllowedPaths,
1593
+ addReadOnlyPaths,
1594
+ addForbiddenPaths,
1595
+ updateStartingSha
1596
+ });
1597
+ if (res.exitCode === 0 && res.entry) {
1598
+ try {
1599
+ const contractAbs = path.resolve(workCwd, contractPath);
1600
+ const parsed = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
1601
+ appendLedgerEvent(contractAbs, {
1602
+ kind: 'amend',
1603
+ task_id: parsed.task_id,
1604
+ exit_code: 0,
1605
+ summary: `Amendment #${res.amendmentCount} by ${authorizedBy}: ${reason}`,
1606
+ artifact_sha256: res.entry.entry_sha256
1607
+ });
1608
+ } catch {
1609
+ // ignore ledger error
1610
+ }
1611
+ }
1612
+ if (jsonOut) {
1613
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
1614
+ } else if (res.exitCode === 0) {
1615
+ process.stdout.write(
1616
+ `Amended ${contractPath} (amendment #${res.amendmentCount}, sha256=${res.contractSha256?.slice(0, 16)}…)\n`
1617
+ );
1618
+ } else {
1619
+ process.stderr.write(`diffpact amend failed (exit ${res.exitCode}): ${res.error}\n`);
1620
+ }
1621
+ return res.exitCode;
1622
+ }
1623
+
1624
+ if (cmd === 'doctor') {
1625
+ if (subArgs.length > 0) {
1626
+ return failUnknownFlag('doctor', subArgs[0] , jsonOut);
1627
+ }
1628
+ const doc = runDoctor({ cwd: workCwd });
1629
+ if (jsonOut) {
1630
+ process.stdout.write(JSON.stringify(doc, null, 2) + '\n');
1631
+ } else {
1632
+ process.stdout.write(
1633
+ `diffpact doctor: node=${doc.nodeVersion} git=${doc.gitAvailable} repo=${doc.insideGitRepo} exclude=${doc.diffpactExcludedInGit ?? false}\n`
1634
+ );
1635
+ for (const h of doc.harnesses) {
1636
+ process.stdout.write(
1637
+ ` [${h.installed ? 'FOUND' : ' - '}] ${h.id.padEnd(14)} ${h.resolvedPath ?? h.binary}${h.version ? ` (${h.version})` : ''}\n`
1638
+ );
1639
+ }
1640
+ if (doc.warnings.length > 0) {
1641
+ process.stdout.write('Warnings:\n');
1642
+ for (const w of doc.warnings) {
1643
+ process.stdout.write(` ! ${w}\n`);
1644
+ }
1645
+ }
1646
+ }
1647
+ return doc.ok ? EXIT_PASS : EXIT_INCOMPLETE;
1648
+ }
1649
+
1650
+ if (cmd === 'install-hooks') {
1651
+ let target ;
1652
+ let excludeInGitInfo = false;
1653
+ for (let i = 0; i < subArgs.length; i++) {
1654
+ const a = subArgs[i] ;
1655
+ if (a === '--exclude') {
1656
+ excludeInGitInfo = true;
1657
+ } else if (a === '--harness') {
1658
+ if (!subArgs[i + 1]) return failCliArg('install-hooks', 'Option "--harness" requires a value', jsonOut);
1659
+ target = subArgs[++i] ;
1660
+ } else if (a.startsWith('-')) {
1661
+ return failUnknownFlag('install-hooks', a, jsonOut);
1662
+ } else if (!target) {
1663
+ target = a ;
1664
+ } else {
1665
+ return failCliArg('install-hooks', `Unexpected extra argument "${a}"`, jsonOut);
1666
+ }
1667
+ }
1668
+ if (!target || !['claude-code', 'codex', 'gemini', 'agy'].includes(target)) {
1669
+ process.stderr.write('Usage: diffpact install-hooks <claude-code|codex|gemini|agy> [--exclude]\n');
1670
+ return EXIT_INCOMPLETE;
1671
+ }
1672
+ const r = installHarnessHooks({ target, cwd: workCwd, contractPath, excludeInGitInfo });
1673
+ if (jsonOut) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
1674
+ else process.stdout.write(`${r.created ? 'Created' : 'Merged'} hooks in ${r.configPath}\n`);
1675
+ return EXIT_PASS;
1676
+ }
1677
+
1678
+ if (cmd === 'report') {
1679
+ let format = jsonOut ? 'json' : 'markdown';
1680
+ for (let i = 0; i < subArgs.length; i++) {
1681
+ const a = subArgs[i] ;
1682
+ if (a === '--format') {
1683
+ if (!subArgs[i + 1]) return failCliArg('report', 'Option "--format" requires a value', jsonOut);
1684
+ const f = subArgs[++i] ;
1685
+ if (f !== 'markdown' && f !== 'json' && f !== 'sarif') {
1686
+ return failCliArg('report', `Invalid --format "${f}". Expected markdown|json|sarif.`, jsonOut);
1687
+ }
1688
+ format = f;
1689
+ } else {
1690
+ return failUnknownFlag('report', a, jsonOut);
1691
+ }
1692
+ }
1693
+ const r = generateTaskReport({ contractPath, cwd: workCwd, format });
1694
+ if (r.error) {
1695
+ process.stderr.write(`diffpact report error: ${r.error}\n`);
1696
+ return r.exitCode;
1697
+ }
1698
+ process.stdout.write(r.output);
1699
+ return EXIT_PASS;
1700
+ }
1701
+
1702
+ process.stderr.write(`Unknown command "${cmd}"\n`);
1703
+ return EXIT_INCOMPLETE;
1704
+ }