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