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 ADDED
@@ -0,0 +1,126 @@
1
+ # Changelog
2
+
3
+ All notable changes to **`diffpact`** are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ---
8
+
9
+ ## [0.4.2] — 2026-11-30
10
+
11
+ ### Added
12
+ - **Committed-Only Post-Merge Verification (`merge-verify --allow-untracked` / `--committed-only`):** Allows `diffpact merge-verify` to ignore pre-existing untracked scratch files on `main` while **still failing closed** (`DIRTY_WORKING_TREE`) on any uncommitted modifications to tracked files.
13
+ - Records `merged_policy.allow_untracked: true` and `diff_summary.ignored_untracked_files` inside the canonical SHA-256 signed `merge-receipt.json` for full auditability.
14
+ - Default `merge-verify` remains strict clean-tree, now listing the exact untracked file paths in `DIRTY_WORKING_TREE` and printing an actionable hint pointing to `--allow-untracked` / `--committed-only` when only untracked files are dirty.
15
+
16
+ ### Changed
17
+ - Added `trackedTreeClean` to `RepoChangeSnapshot` in `git.ts` and updated SARIF 2.1.0 driver version to `0.4.2`.
18
+
19
+ ---
20
+
21
+ ## [0.4.1] — 2026-11-30
22
+
23
+ ### Added
24
+ - **Orchestrator Post-Merge Integration Scope (`merge-verify --allow-integration <glob> --reason <text>`):** Supports both the recommended post-merge order (running `diffpact merge-verify` right after merging before any manual orchestrator fixes) and explicit, auditable post-merge integration glue edits on `main`:
25
+ - `--allow-integration <glob>` (repeatable) and `--reason <text>` authorize specified repo-relative integration glue files and record them inside the signed `merge-receipt.json` (`merged_policy.integration_allowed_paths` / `integration_reason`).
26
+ - Global `forbidden_paths` shared by all merged contracts (plus `.git/` metadata, symlinks, and submodules) remain strictly blocked even when `--allow-integration` is set.
27
+ - When `merge-verify` fails with `OUTSIDE_ALLOWED_PATHS`, stderr now prints an explicit workflow hint explaining both the merge-first order and `--allow-integration`.
28
+ - **`zsh` Identity-String Modifier Warning (`$n:c`):**
29
+ - Updated `parseSessionSpec` error messages (`diffpact init --implementer`, `diffpact review --reviewer`, `diffpact delegate --implementer`) with an explicit `zsh` hint when colons are mangled or a harness name is invalid (e.g., `"codex:s-$n:codex"` expanding `$n:c` as a `zsh` modifier → use `"codex:s-${n}:codex"` or single quotes).
30
+ - Documented the `zsh` quoting rule in `README.md` and `diffpact init --help`.
31
+
32
+ ### Changed
33
+ - Updated SARIF 2.1.0 driver version to `0.4.1`.
34
+
35
+ ---
36
+
37
+ ## [0.4.0] — 2026-11-30
38
+
39
+ ### Added
40
+ - **Durable Evidence Archiving on Worktree Cleanup (`worktree remove`):** Before removing a linked Git worktree, `diffpact worktree remove` now automatically archives `.diffpact/` (`contract.json`, `receipt.json`, `reviews/`, `amendments.jsonl`, `ledger.jsonl`, and `subcontracts/`) **plus** generated `report.md` and `report.json` to `<main>/.diffpact/archive/<timestamp>-<task>-<sha>/` and excludes `.diffpact/` in the main repository's `.git/info/exclude`. Added `--archive-dir <dir>` and `--no-archive` flags.
41
+ - **Post-Merge Multi-Contract Gate (`diffpact merge-verify`):** Added `diffpact merge-verify --from <path> --from <path> [--base <sha>] [--heartbeat-sec <n>] [--write-receipt <path>]` to verify merged branches on `main`:
42
+ - Resolves source contracts from `contract.json`, `.diffpact/`, worktree roots, or archived bundles under `.diffpact/archive/`.
43
+ - Verifies that every changed file since `base_sha` is authorized by at least one participating contract (catching unauthorized edits introduced during manual conflict resolution).
44
+ - Runs the deduplicated **union** of all participating contracts' `required_checks`, `advisory_checks`, `version_assertions`, and `interfacedelta_lockfile` pins, and writes a canonical SHA-256 signed `merge-receipt.json` under `.diffpact/merges/`.
45
+ - **Primary Diff Viewer (`diffpact diff`):** Prints the exact `git diff <starting_sha>..<HEAD>` alongside the canonical `raw_diff_sha256` token for independent reviewers.
46
+ - **Cryptographic Diff-SHA & Orchestrator HMAC Review Binding:**
47
+ - Added `--diff-sha <sha>` on `diffpact review` (verified against live `raw_diff_sha256`, recording `attestation_mode: "diff-sha-bound"`).
48
+ - Added optional `DIFFPACT_REVIEWER_SECRET` HMAC-SHA256 signing and verification (`attestation_hmac_sha256`) on review attestations; `diffpact exec` and `diffpact run` automatically strip `DIFFPACT_REVIEWER_SECRET` from worker subprocesses so workers cannot forge reviews.
49
+ - **Per-Command CLI Help:** Added dedicated help text for every subcommand via `diffpact <command> --help` / `-h` and `diffpact help <command>`.
50
+ - **Subdirectory `node_modules` Auto-Discovery:** `diffpact worktree create --share-node-modules` now automatically discovers depth 1–2 package subdirectories containing `package.json` and `node_modules` (such as `site/node_modules`) when no root `node_modules` exists, adds `--node-modules-dir <subdir>`, and prints an explicit stderr warning if no `node_modules` directory is found.
51
+ - **Install & `PATH` Setup Documentation:** Overhauled `README.md` to `v0.4.0` with local `PATH` installation (`npm link`, `npm install -g`, direct symlink), complete quickstart, and command reference.
52
+
53
+ ### Changed
54
+ - **Explicit Review Attestation Required on CLI (`diffpact review`):** CLI `diffpact review` no longer silently assumes `inspected_raw_diff: true`. Reviewers must explicitly pass `--diff-sha <sha>` (recommended) or `--inspected-raw-diff` (or `--summary-only` when the contract disables `require_raw_diff_inspection`), failing closed with exit `2` otherwise.
55
+ - **Unambiguous `diffpact status` Review Visibility:** Even without `--require-review`, `diffpact status` now always evaluates existing reviews and reports `review_status` (`missing`, `approved`, `stale`, `rejected`, `incomplete`, `invalid`) in both human-readable and `--json` output (e.g., `Checks verified; review: missing (0/1 — run \`diffpact status --require-review\` before merge)`).
56
+ - Updated SARIF 2.1.0 driver version to `0.4.0` and extended `schemas/review.schema.json` with optional `attestation_mode` and `attestation_hmac_sha256`.
57
+
58
+ ---
59
+
60
+ ## [0.3.2] — 2026-11-29
61
+
62
+ ### Added
63
+ - **Monorepo Workspace-Aware `--share-node-modules`:** When `package.json` defines `workspaces` (array or `{ packages }`) or `pnpm-workspace.yaml` exists, `diffpact worktree create --share-node-modules` now creates a real `<worktree>/node_modules/` overlay that symlinks third-party dependencies (and `.bin`) from the main checkout while symlinking every local workspace package (including splitting scoped namespaces like `@org/*`) to the worktree's own directories—preventing cross-package edits from importing stale main-checkout code while keeping `git status` clean.
64
+ - **First-Class `crush` Harness Support:**
65
+ - Added `'crush'` to `HarnessKind`, `VALID_HARNESSES`, `schemas/contract.schema.json`, and `diffpact doctor` probes (with a proactive `.crush/` isolation warning).
66
+ - Added `diffpact run --harness crush [--model <m>] [--reasoning-effort <level>] [--data-dir <dir>]`, isolating Crush state outside the worktree via `--data-dir /var/tmp/diffpact-crush-...` and `--quiet` so `.crush/` never dirties Git.
67
+ - **Squash-Merge Branch Cleanup (`worktree remove`):** Added `--force-delete-branch` and automatically switched `--delete-branch` to `git branch -D` when `--require-verified` has already passed (preventing false "branch not fully merged" errors after `git merge --squash` while still protecting unverified branches and refusing to delete `main`/`master`).
68
+
69
+ ### Fixed
70
+ - Upgraded `diffpact doctor` binary version parsing to skip ASCII-art banners (such as `crush --version`) and display the real version line cleanly.
71
+
72
+ ---
73
+
74
+ ## [0.3.1] — 2026-11-29
75
+
76
+ ### Added
77
+ - **Companion Worktree Teardown (`diffpact worktree remove`):** Added `diffpact worktree remove <dir> [--require-verified] [--delete-branch] [--force]` to verify `diffpact status --require-review`, remove linked Git worktrees cleanly, prune stale Git worktree metadata, and optionally delete feature branches (never deleting `main` or `master`).
78
+
79
+ ### Fixed
80
+ - **Linked Git Worktree Commits Inside Codex Sandboxes:** `diffpact run --harness codex` now resolves `git rev-parse --git-dir` and `git rev-parse --git-common-dir` via `resolveExternalGitAddDirs` and passes `--add-dir` for both when they live outside the worktree root, allowing `git add && git commit` to write `index.lock`, objects, and branch refs cleanly inside Codex's `-s workspace-write` sandbox.
81
+
82
+ ---
83
+
84
+ ## [0.3.0] — 2026-11-29
85
+
86
+ *Field-driven upgrades from live multi-agent production sprints across parallel Codex and Claude Code worktrees.*
87
+
88
+ ### Added
89
+ - **Safe Mid-Task Resume (`diffpact exec --resume` / `--allow-in-scope-dirty`):** Allows resuming interrupted worker sessions when dirty/untracked files exist **strictly** inside `allowed_paths`, while still blocking immediately on any forbidden, read-only, or out-of-bounds dirty path.
90
+ - **Managed Worktree Setup (`diffpact worktree create`):** Added `diffpact worktree create <dir> --branch <name> [--from <ref>] [--share-node-modules]` with automatic `.diffpact/` and `node_modules` registration in `.git/info/exclude`.
91
+ - **Harness-Aware Launcher (`diffpact run --harness <claude|codex|agy|gemini>`):** Automatically emits known-good non-interactive flags (root-safe `--permission-mode acceptEdits --allowedTools ... -- <prompt>` for Claude Code; modern `exec -s workspace-write --add-dir ... --ephemeral` for Codex `0.172+`), supports `--prompt` / `--prompt-file` / `--model` / `--resume` / `--dry-run`, and runs host post-flight verification.
92
+ - **Live Progress Heartbeats & Per-Check Timeouts:** Added async check/worker execution with `--heartbeat-sec <n>` (default `30s` non-TTY) and `--check-timeout <id>=<sec>` on `diffpact init`.
93
+ - **Non-Blocking Advisory Checks (`--advisory-check`):** Added optional `advisory_checks` on contracts and receipts so cross-repo or baseline tests are executed and rendered in Markdown/JSON reports for reviewer visibility without blocking `exit 0`.
94
+ - **Proactive `doctor` Warnings:** Added root/Claude and Codex sandbox nesting diagnostics to `diffpact doctor`.
95
+
96
+ ### Fixed
97
+ - **Honest Spawn vs. Timeout Classification (`classifyCheckProcessOutcome`):** Stopped masking child process spawn errors (`EPERM`, `EACCES`, `ENOENT`) as exit code `124` (timeout). Real timeouts emit `124` (`REQUIRED_CHECK_TIMEOUT`, `timed_out: true`); spawn failures emit `126`/`127` with `CHECK_SPAWN_ERROR`, `spawn_error_code`, and `spawn_error_message`.
98
+ - **Actionable Dirty-Tree Diagnostics:** `diffpact exec` pre-flight failures now list exact dirty paths and detect untracked symlinks colliding with trailing-slash `.gitignore` patterns (e.g., `node_modules/`).
99
+
100
+ ---
101
+
102
+ ## [0.2.0] — 2026-11-27
103
+
104
+ ### Added
105
+ - **Hash-Chained Scope & Base Amendments (`diffpact amend`):** Record auditable mid-task scope enlargements (`--add-allow`, `--add-read-only`, `--add-forbid`) or post-rebase `--update-starting-sha` updates in `.diffpact/amendments.jsonl` with `--authorized-by`, `--reason`, SHA-256 chain integrity verification (`--history`), and automatic stale-receipt invalidation.
106
+ - **Environment Diagnostics & Idempotent Hook Installer (`diffpact doctor`, `diffpact install-hooks`):** Probe Node, Git, worktree cleanliness, `.git/info/exclude`, and installed harness CLIs; idempotently merge `diffpact` guard hooks into `.claude/settings.json`, `.codex/hooks.json`, `.gemini/settings.json`, or `.agents/hooks.json` without erasing existing user hooks.
107
+ - **Multi-Format Reporting & Event Ledger (`diffpact report`):** Generate Markdown PR cards, deterministic canonical JSON bundles, and **SARIF 2.1.0** security/compliance reports, plus append-only `.diffpact/ledger.jsonl` event logging.
108
+
109
+ ---
110
+
111
+ ## [0.1.0] — 2026-11-27
112
+
113
+ ### Added
114
+ - **Core Stateless Git Verification Engine (`init`, `exec`/`wrap`, `verify`, `review`, `status`, `delegate`):**
115
+ - RFC 8785 canonical JSON hashing (`canonicalSha256`) and JSON Schemas (`contract.schema.json`, `receipt.schema.json`, `review.schema.json`).
116
+ - Strict boundary precedence (`.git` metadata deny > `forbidden_paths` > `read_only_paths` > `allowed_paths`), symlink (`120000`) and submodule (`160000`) rejection, rename-aware `git diff -M -z`, path traversal protection, and contract tamper detection during `exec`.
117
+ - **No Silent Zero:** Missing contracts/receipts, zero candidate commits, empty `required_checks`, or skipped test suites (Vitest, `node --test`/TAP, Jest, Pytest) return exit `2` (`INCOMPLETE`).
118
+ - **Version Assertions & External Interface Lockfile Pinning:** `sha256`, `json_pointer`, and `regex_exact` pins plus `interfacedelta.lock.json` drift detection.
119
+ - **Non-Self-Certified Review & Monotonic Delegation:** Distinct implementer/reviewer identity enforcement, multi-reviewer echo-chamber lineage guard, `role_substitution` / `canonical_integrator_agent_id` checks, automatic `exit 3` (`STALE`) invalidation on `HEAD` drift, and monotonically narrowed child subcontracts conserving `max_budget_usd`.
120
+ - **Deterministic Exit Codes:** `0` (`PASS`), `1` (`VIOLATION`), `2` (`INCOMPLETE`), `3` (`STALE`).
121
+ - **Four Cross-Harness Adapters (`hook`, `board`, `agy-verify-patch`, `print-config`):**
122
+ - `@vercel/board` (`post-contract` / `complete` gate)
123
+ - Claude Code (`PreToolUse` / `PostToolUse` / `Stop` hooks with shell/inline-interpreter guards and loop cap)
124
+ - OpenAI Codex CLI (`apply_patch` / `Bash` hook guard + wrapped read-only JSONL reviewer + `notify` hook)
125
+ - Google Gemini CLI & Antigravity (`agy` hooks + unattended `agy-worker --diff` pre-apply patch verifier)
126
+ - **Zero Runtime Dependencies:** Pure Node.js (`>= 22.6.0`) TypeScript implementation under the MIT License.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 InterfaceDelta, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,215 @@
1
- # Temporary Holding Version
1
+ # diffpact (`v0.4.2`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Local, stateless Git task contracts, deterministic diff boundaries, post-merge verification, and cross-harness review gates for multi-agent coding workflows.**
4
+
5
+ Built by [InterfaceDelta](https://interfacedelta.com) · MIT License · Zero runtime dependencies · Node `>= 22.6` · [Changelog](./CHANGELOG.md) · [![CI](https://github.com/interface-delta/diffpact/actions/workflows/ci.yml/badge.svg)](https://github.com/interface-delta/diffpact/actions/workflows/ci.yml)
6
+
7
+ ---
8
+
9
+ ## Install & Put `diffpact` on Your `PATH`
10
+
11
+ Choose one installation method (zero runtime dependencies, Node `>= 22.6`):
12
+
13
+ **Option A (Recommended right now): Clone from GitHub and symlink globally** *(runs `npm run build` automatically)*
14
+
15
+ ```bash
16
+ git clone https://github.com/interface-delta/diffpact.git
17
+ cd diffpact && npm link
18
+ ```
19
+
20
+ **Option B: Install globally from a local checkout**
21
+
22
+ ```bash
23
+ npm install -g /path/to/diffpact
24
+ ```
25
+
26
+ **Option C: Run or install from npm** *(coming soon — once published to npm)*
27
+
28
+ ```bash
29
+ npx diffpact doctor
30
+ npm install -g diffpact
31
+ ```
32
+
33
+ **Verify your environment and try the 30-second self-contained quickstart demo:**
34
+
35
+ ```bash
36
+ diffpact doctor
37
+ npm run quickstart
38
+ ```
39
+
40
+ See [examples/quickstart/](./examples/quickstart/) for the interactive walkthrough and [examples/harnesses/](./examples/harnesses/) for drop-in Claude Code, Codex CLI, Crush, Gemini/Antigravity, and `@vercel/board` configs.
41
+
42
+ Every command supports per-command help:
43
+
44
+ ```bash
45
+ diffpact <command> --help
46
+ diffpact help <command>
47
+ ```
48
+
49
+ ---
50
+
51
+ ## Why `diffpact`?
52
+
53
+ Shared message boards (`@vercel/board`) and subagent harnesses let multiple coding agents claim tasks in parallel—but ticket locks alone do not stop agents from editing forbidden files, skipping test suites while exiting `0`, silently altering pinned constants, introducing regressions when two parallel branches are merged, or rubber-stamping their own commits.
54
+
55
+ `diffpact` enforces explicit, SHA-pinned **Task Contracts** directly against Git:
56
+
57
+ - **100% Local & Stateless:** No daemon, no database, no sign-up. Truth is recomputed directly from Git (`HEAD`, `git diff -M -z`, untracked files, and symlink checks) plus RFC 8785 canonical SHA-256 receipts.
58
+ - **Boundary Precedence (`.git` deny > `forbidden` > `read_only` > `allowed`):** Unconditionally blocks `.git/` metadata/hook tampering, symlinks (`120000`), submodules (`160000`), unauthorized edits/renames (`-M -z`), and destructive shell or inline interpreter commands (`Bash`, `python -c`, `node -e`) *before* and *after* execution.
59
+ - **No Silent Zero:** Empty check lists, skipped test suites (`vitest` / `node --test` / `jest` skipped counts), or missing commits return exit code `2` (`INCOMPLETE`), never `0`.
60
+ - **Non-Self-Certified, Diff-Bound Review:** Enforces distinct implementer vs. reviewer identities, explicit raw-diff attestation (`--diff-sha <sha>` from `diffpact diff` or `--inspected-raw-diff`), optional orchestrator HMAC signing (`DIFFPACT_REVIEWER_SECRET`, automatically stripped from worker subprocesses), and automatic invalidation (`exit 3`) if `HEAD` moves.
61
+ - **Worktree Lifecycle & Durable Evidence Archiving:** `diffpact worktree create --share-node-modules` handles standard repos, npm/pnpm monorepo workspace overlays, and subdirectory apps (`site/node_modules`). `diffpact worktree remove` automatically archives `.diffpact/` evidence (`contract.json`, `receipt.json`, `reviews/`, `report.md`, `report.json`) to `<main>/.diffpact/archive/` before removing the worktree.
62
+ - **Post-Merge Integration Gate (`diffpact merge-verify`):** After joining 2+ parallel branches onto `main`, runs the deduplicated union of all participating contracts' checks and path boundaries on the merged tree and writes a signed `merge-receipt.json`.
63
+ - **Cross-Harness Support:** Ready out of the box for **Claude Code**, **OpenAI Codex CLI**, **Crush**, **Google Gemini CLI / Antigravity (`agy` & `agy-worker`)**, and **`@vercel/board`**.
64
+
65
+ ---
66
+
67
+ ## Real-World Trajectory: Why Passing Tests Aren't Enough
68
+
69
+ In a typical single-agent workflow, the moment `npm run typecheck` and `npm test` exit `0`, the branch looks ready to merge. Here is an actual generalized trajectory from a 7-package TypeScript monorepo running `diffpact v0.4.x` with two separate models (Author Agent A and Independent Reviewer Agent B):
70
+
71
+ ```text
72
+ worktree create --share-node-modules (7 local workspace packages linked, ~10s)
73
+ └─▶ Author Agent A implements feature + tests ──▶ diffpact verify: PASS (exit 0)
74
+ └─▶ diffpact status --require-review ──▶ HOLD (exit 2: review missing)
75
+ └─▶ Reviewer Agent B runs `diffpact diff` (~90s raw-diff audit)
76
+ └─▶ REQUEST_CHANGES: 6 real bugs caught before merge!
77
+ 1. Async cancellation race (queue cleared, active fetch unguarded)
78
+ 2. Missing DOM data-attribute breaking replay buttons on one variant
79
+ 3. Background audio volume left un-ducked during modal transition
80
+ 4. Test file silently swallowing a ReferenceError inside try/catch
81
+ 5. Missing profile metadata in peer-to-peer rendering path
82
+ 6. Automated system notices unintentionally triggering TTS playback
83
+ └─▶ Orchestrator runs `diffpact amend --add-allow packages/core/src/index.ts`
84
+ (hash-chained scope expansion required for bug #5; old receipt invalidated)
85
+ └─▶ Author fixes all 6 bugs ──▶ diffpact verify: PASS (exit 0)
86
+ └─▶ Reviewer B signs `diffpact review --diff-sha <sha> --verdict approve` (mode=diff-sha-bound)
87
+ └─▶ diffpact status --require-review ──▶ PASS (exit 0, review: approved 1/1)
88
+ └─▶ diffpact worktree remove --require-verified --delete-branch
89
+ (archived contract, receipt, amendment chain, reviews & reports to .diffpact/archive/)
90
+ ```
91
+
92
+ **Measured overhead:** ~25 seconds for worktree setup, contract pinning, and archiving + ~90 seconds for independent raw-diff review — **6 subtle production bugs stopped before a single line touched `main`**, including a broken test that had exited `0`.
93
+
94
+ ---
95
+
96
+ ## End-to-End Quickstart
97
+
98
+ ```bash
99
+ # 0. Inspect environment, Git setup, and installed agent CLIs (with root/sandbox warnings)
100
+ diffpact doctor
101
+
102
+ # 1. Create an isolated linked worktree with clean dependency sharing
103
+ # (monorepo workspace-aware; auto-discovers subdir apps like site/node_modules or use --node-modules-dir)
104
+ diffpact worktree create /var/tmp/wt-normalizer --branch feat/normalizer --share-node-modules
105
+ cd /var/tmp/wt-normalizer
106
+
107
+ # 2. Initialize a SHA-pinned task contract (with blocking + advisory checks and timeouts)
108
+ diffpact init \
109
+ --task-id "feat-normalizer-01" \
110
+ --mission "Implement normalizer slice without touching migrations" \
111
+ --allow "src/normalizer/**" \
112
+ --allow "test/normalizer/**" \
113
+ --read-only "src/common/**" \
114
+ --forbid "migrations/**" \
115
+ --forbid "package.json" \
116
+ --check "typecheck=npm run typecheck" \
117
+ --check "unit=npm test" \
118
+ --check-timeout "unit=60" \
119
+ --advisory-check "baseline=npm run test:baseline" \
120
+ --implementer "codex-worker:sess-01:codex"
121
+
122
+ # Tip for zsh users: wrap shell variables inside colon-delimited identity strings in braces
123
+ # (e.g. "codex:s-${n}:codex") or single quotes ('codex:s-1:codex'), because zsh parses
124
+ # unbraced "$n:c" in "codex:s-$n:codex" as a `:c` parameter expansion modifier.
125
+
126
+ # 3. Run any supported harness (claude | codex | crush | agy | gemini) with pre/post gate & live heartbeats
127
+ diffpact run --harness codex --model gpt-6-astra --prompt "Implement .diffpact/contract.json" --heartbeat-sec 30
128
+ # (Or wrap any custom worker command: diffpact exec [--resume] -- <cmd...>)
129
+
130
+ # 4. Check status (explicitly shows whether review is still missing)
131
+ diffpact status
132
+ # -> diffpact status: PASS (exit 0) — Checks verified; review: missing (0/1 — run `diffpact status --require-review` before merge)
133
+
134
+ # 5. Inspect the primary raw Git diff & record an independent, diff-SHA-bound review
135
+ diffpact diff
136
+ diffpact review \
137
+ --reviewer "claude-rev:sess-99:claude-code" \
138
+ --verdict approve \
139
+ --diff-sha <raw_diff_sha256_prefix> \
140
+ --summary "Verified raw diff and edge cases"
141
+
142
+ # 6. Gate merge (fails closed until verified + independently reviewed)
143
+ diffpact status --require-review
144
+ diffpact report --format markdown
145
+
146
+ # 7. Merge into main, then clean up worktree (auto-archives .diffpact/ evidence to <main>/.diffpact/archive/)
147
+ cd /path/to/main-repo
148
+ git merge --squash feat/normalizer && git commit -m "feat: normalizer"
149
+ diffpact worktree remove /var/tmp/wt-normalizer --require-verified --delete-branch
150
+
151
+ # 8. Post-merge verification across 2+ merged contracts / archived bundles
152
+ # Recommended order: run merge-verify right after merging BEFORE any manual follow-up fixes on main.
153
+ diffpact merge-verify \
154
+ --from .diffpact/archive/<bundle-branch-a> \
155
+ --from .diffpact/archive/<bundle-branch-b>
156
+
157
+ # If the orchestrator had to make small post-merge integration glue fixes on main, either:
158
+ # (a) declare those files explicitly (recorded in merge-receipt.json; global forbidden paths stay blocked):
159
+ diffpact merge-verify \
160
+ --from .diffpact/archive/<bundle-branch-a> \
161
+ --from .diffpact/archive/<bundle-branch-b> \
162
+ --allow-integration "src/index.ts" \
163
+ --reason "Wire exported routes from both merged slices"
164
+ # or (b) pass a lightweight follow-up contract via an extra `--from <contract.json>`.
165
+ # If unrelated local untracked scratch notes sit on main, pass `--allow-untracked`
166
+ # (alias `--committed-only`) to verify only the committed merge diff while still blocking dirty tracked files.
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Command Reference
172
+
173
+ Run `diffpact <command> --help` for full flags and examples on any command.
174
+
175
+ | Command | Purpose |
176
+ |---|---|
177
+ | `diffpact doctor` | Probe Node, Git, `.git/info/exclude`, installed agent CLIs (`claude`, `codex`, `crush`, `agy`, `gemini`, `vercel`), and root/sandbox warnings |
178
+ | `diffpact worktree create` | Create linked Git worktree with `.diffpact/` pre-excluded + workspace/subdir-aware `--share-node-modules` |
179
+ | `diffpact worktree remove` | Auto-archive `.diffpact/` evidence + reports to `<main>/.diffpact/archive/`, gate via `--require-verified`, and delete merged/squashed branch |
180
+ | `diffpact init` | Create `.diffpact/contract.json` pinned to `starting_sha`, path boundaries, checks, timeouts, and advisory checks |
181
+ | `diffpact amend` | Record hash-chained scope or `starting_sha` amendment in `.diffpact/amendments.jsonl` |
182
+ | `diffpact run` | Harness-aware launcher (`claude`, `codex`, `crush`, `agy`, `gemini`) with linked-worktree Codex `--add-dir`, root-safe Claude flags, isolated Crush `--data-dir`, heartbeats, and host `verify` |
183
+ | `diffpact exec` (`wrap`) | Wrap any worker command with pre-flight boundary check (`--resume` for in-scope dirty trees), tamper guard, and post-flight `verify` |
184
+ | `diffpact verify` | Recompute Git diff boundaries, version pins, lockfiles, and run required + advisory checks (`receipt.json`) |
185
+ | `diffpact merge-verify` | Post-merge gate across 2+ merged contracts/archives: verifies combined path boundaries and runs the union of all checks (`merge-receipt.json`) |
186
+ | `diffpact diff` | Print primary raw Git diff (`starting_sha..HEAD`) and canonical `raw_diff_sha256` token for independent review |
187
+ | `diffpact review` | Record non-self-certified review attestation (`--diff-sha` or `--inspected-raw-diff`; optional `DIFFPACT_REVIEWER_SECRET` HMAC) |
188
+ | `diffpact status` | Fast read-only gate check against live Git `HEAD` (shows explicit `review: missing/approved/stale` even without `--require-review`) |
189
+ | `diffpact report` | Emit Markdown PR card, canonical JSON bundle, or SARIF 2.1.0 report |
190
+ | `diffpact delegate` | Create monotonically narrowed child subcontract conserving parent `max_budget_usd` |
191
+ | `diffpact install-hooks` | Idempotently merge `diffpact` hooks into `claude-code`, `codex`, `gemini`, or `agy` configs |
192
+ | `diffpact print-config` | Print drop-in hook JSON config for `claude-code`, `codex`, `gemini`, or `agy` |
193
+ | `diffpact board` | `@vercel/board` adapter (`post-contract` / `complete` gate) |
194
+ | `diffpact agy-verify-patch` | Verify unattended `agy-worker --diff` unified patch before `git apply` |
195
+
196
+ ---
197
+
198
+ ## Strengthening Reviewer Integrity (`DIFFPACT_REVIEWER_SECRET`)
199
+
200
+ Because a local CLI has no central identity server, a plain `--reviewer` flag is self-declared unless bound by your orchestrator. `diffpact` supports three escalating levels of review assurance:
201
+
202
+ 1. **Diff-SHA Binding (`--diff-sha <sha>`):** Reviewer runs `diffpact diff` and passes the exact `raw_diff_sha256` prefix (`>= 12` hex chars), proving the review targets the exact inspected diff bytes.
203
+ 2. **Orchestrator HMAC Signing (`DIFFPACT_REVIEWER_SECRET`):** Export `DIFFPACT_REVIEWER_SECRET` in your orchestrator shell. `diffpact exec` and `diffpact run` automatically **strip** `DIFFPACT_REVIEWER_SECRET` from worker subprocesses, so a worker agent cannot forge a valid `diffpact review` attestation—only processes holding the orchestrator's secret pass `diffpact status --require-review`.
204
+ 3. **Wrapped Read-Only Reviewer (`--adapter codex -- <cmd...>`):** Spawns an independent read-only Codex session, extracts its real `thread_id`, and rejects any mutation of the working tree.
205
+
206
+ ---
207
+
208
+ ## Exit Codes
209
+
210
+ | Exit Code | Status | Meaning |
211
+ |:---:|---|---|
212
+ | `0` | `PASS` | Boundaries, version pins, checks, and (when required) independent reviews verified against `HEAD` |
213
+ | `1` | `VIOLATION` | Path/symlink/shell boundary breached, self-certification or forged HMAC, diff-SHA mismatch, budget exceeded, or check failed |
214
+ | `2` | `INCOMPLETE` | Missing contract/receipt/review, unattested raw-diff inspection, zero commits, or skipped tests (*No Silent Zero*) |
215
+ | `3` | `STALE` | Git `HEAD` or `contract.json` moved after receipt or review was issued |
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+
4
+ const distEntry = new URL('../dist/cli.js', import.meta.url);
5
+ const { runCli } = fs.existsSync(distEntry)
6
+ ? await import('../dist/cli.js')
7
+ : await import('../src/cli.ts');
8
+
9
+ const code = await runCli(process.argv.slice(2));
10
+ process.exitCode = code;
@@ -0,0 +1,191 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { evaluatePathBoundary, evaluateShellCommand } from '../boundaries.js';
4
+ import { resolveRepoRoot } from '../git.js';
5
+ import { validateContract } from '../schema.js';
6
+ import { runVerify } from '../verify.js';
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+ export function readStopCount(pactDir , sessionId ) {
15
+ const stateFile = path.join(pactDir, 'hook-stop-state.json');
16
+ try {
17
+ const data = JSON.parse(fs.readFileSync(stateFile, 'utf8')) ;
18
+ return data[sessionId] ?? 0;
19
+ } catch {
20
+ return 0;
21
+ }
22
+ }
23
+
24
+ export function writeStopCount(pactDir , sessionId , count ) {
25
+ const stateFile = path.join(pactDir, 'hook-stop-state.json');
26
+ let data = {};
27
+ try {
28
+ data = JSON.parse(fs.readFileSync(stateFile, 'utf8')) ;
29
+ } catch {
30
+ // ignore
31
+ }
32
+ data[sessionId] = count;
33
+ fs.mkdirSync(pactDir, { recursive: true });
34
+ fs.writeFileSync(stateFile, JSON.stringify(data, null, 2) + '\n');
35
+ }
36
+
37
+ export function evaluateBoundedStopGate(options
38
+
39
+
40
+
41
+
42
+
43
+ ) {
44
+ const pactDir = path.dirname(options.contractAbs);
45
+ const maxBlocks = options.maxStopBlocks ?? 3;
46
+ const prev = options.isContinuation ? readStopCount(pactDir, options.sessionId) : 0;
47
+
48
+ if (options.isContinuation && prev >= maxBlocks) {
49
+ writeStopCount(pactDir, options.sessionId, 0);
50
+ return { action: 'capped', exitCode: 0, maxBlocks };
51
+ }
52
+
53
+ const res = runVerify({ contractPath: options.contractAbs, cwd: options.repoRoot, writeReceipt: true });
54
+ if (res.exitCode === 0) {
55
+ writeStopCount(pactDir, options.sessionId, 0);
56
+ return { action: 'pass', exitCode: 0, maxBlocks };
57
+ }
58
+
59
+ writeStopCount(pactDir, options.sessionId, prev + 1);
60
+ const details =
61
+ res.receipt?.violations.map((v) => `[${v.code}] ${v.message}`).join('; ') ??
62
+ res.error ??
63
+ 'verification failed';
64
+ return { action: 'block', exitCode: res.exitCode, details, maxBlocks };
65
+ }
66
+
67
+ export function handleClaudeCodeHook(
68
+ payload ,
69
+ contractPath ,
70
+ cwdOverride
71
+ ) {
72
+ const cwd = cwdOverride ?? (typeof payload.cwd === 'string' ? payload.cwd : process.cwd());
73
+ const contractAbs = path.resolve(cwd, contractPath);
74
+ if (!fs.existsSync(contractAbs)) {
75
+ return {
76
+ exitCode: 2,
77
+ stderr: `diffpact [claude-code]: missing contract at "${contractAbs}"`
78
+ };
79
+ }
80
+
81
+ let contract;
82
+ try {
83
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
84
+ } catch (err) {
85
+ return { exitCode: 2, stderr: `diffpact [claude-code]: ${(err ).message}` };
86
+ }
87
+
88
+ const repoRoot = resolveRepoRoot(cwd);
89
+ const eventName = String(payload.hook_event_name ?? '');
90
+ const toolName = String(payload.tool_name ?? '');
91
+ const toolInput =
92
+ typeof payload.tool_input === 'object' && payload.tool_input !== null
93
+ ? (payload.tool_input )
94
+ : {};
95
+
96
+ if (eventName === 'PreToolUse') {
97
+ if (
98
+ toolName === 'Write' ||
99
+ toolName === 'Edit' ||
100
+ toolName === 'MultiEdit' ||
101
+ toolName === 'NotebookEdit'
102
+ ) {
103
+ const candidatePaths = [];
104
+ if (typeof toolInput.file_path === 'string') candidatePaths.push(toolInput.file_path);
105
+ if (typeof toolInput.path === 'string') candidatePaths.push(toolInput.path);
106
+ if (typeof toolInput.notebook_path === 'string') candidatePaths.push(toolInput.notebook_path);
107
+ if (candidatePaths.length === 0) {
108
+ return { exitCode: 2, stderr: `diffpact [claude-code]: ${toolName} missing target file path` };
109
+ }
110
+ for (const p of candidatePaths) {
111
+ const v = evaluatePathBoundary(p, repoRoot, contract);
112
+ if (v) {
113
+ return {
114
+ exitCode: 2,
115
+ stderr: `diffpact BLOCKED ${toolName} (${v.code}): ${v.message}`
116
+ };
117
+ }
118
+ }
119
+ return { exitCode: 0 };
120
+ }
121
+
122
+ if (toolName === 'Bash') {
123
+ const cmd = typeof toolInput.command === 'string' ? toolInput.command : '';
124
+ const v = evaluateShellCommand(cmd, contract);
125
+ if (v) {
126
+ return {
127
+ exitCode: 2,
128
+ stderr: `diffpact BLOCKED Bash (${v.code}): ${v.message}`
129
+ };
130
+ }
131
+ return { exitCode: 0 };
132
+ }
133
+
134
+ return { exitCode: 0 };
135
+ }
136
+
137
+ if (eventName === 'PostToolUse') {
138
+ return { exitCode: 0 };
139
+ }
140
+
141
+ if (eventName === 'Stop' || eventName === 'SubagentStop') {
142
+ const sessionId = typeof payload.session_id === 'string' ? payload.session_id : 'default';
143
+ const gate = evaluateBoundedStopGate({
144
+ contractAbs,
145
+ repoRoot,
146
+ sessionId,
147
+ isContinuation: payload.stop_hook_active === true
148
+ });
149
+ if (gate.action === 'pass') {
150
+ return { exitCode: 0 };
151
+ }
152
+ if (gate.action === 'capped') {
153
+ return {
154
+ exitCode: 0,
155
+ stderr: `diffpact WARNING: Stop hook block cap (${gate.maxBlocks}) reached; allowing turn exit without passing receipt.`
156
+ };
157
+ }
158
+ return {
159
+ exitCode: 2,
160
+ stderr: `diffpact Stop gate failed (exit ${gate.exitCode}): ${gate.details}. Fix violations and commit/clean before finishing.`
161
+ };
162
+ }
163
+
164
+ return { exitCode: 0 };
165
+ }
166
+
167
+ export function generateClaudeCodeConfig(contractPath = '.diffpact/contract.json') {
168
+ const cmd = `diffpact --contract ${contractPath} hook claude-code`;
169
+ return JSON.stringify(
170
+ {
171
+ hooks: {
172
+ PreToolUse: [
173
+ {
174
+ matcher: 'Write|Edit|MultiEdit|NotebookEdit|Bash',
175
+ hooks: [{ type: 'command', command: cmd, timeout: 15 }]
176
+ }
177
+ ],
178
+ PostToolUse: [
179
+ {
180
+ matcher: 'Write|Edit|MultiEdit|NotebookEdit|Bash',
181
+ hooks: [{ type: 'command', command: cmd, timeout: 15 }]
182
+ }
183
+ ],
184
+ Stop: [{ hooks: [{ type: 'command', command: cmd, timeout: 180 }] }],
185
+ SubagentStop: [{ hooks: [{ type: 'command', command: cmd, timeout: 180 }] }]
186
+ }
187
+ },
188
+ null,
189
+ 2
190
+ );
191
+ }