handoff-check 0.3.1 → 0.4.0

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Add manifest-only explain in text, JSON and Markdown using verifier lifecycle decisions.
6
+ - Add opt-in snapshot --include-content with strictly validated retained-content v3 handoffs.
7
+ - Show ordered field-level before/after changes for active CHANGED rules in v3 results.
8
+ - Add Markdown verification reports with scope/time, count, tracking, policies and findings.
9
+ - Preserve v1/v2 JSON contracts, default v2 snapshots and read-only verification.
10
+ - Escape untrusted Markdown structure/HTML and terminal formatting controls.
11
+
3
12
  ## 0.3.1
4
13
 
5
14
  - Replace obsolete pre-publication onboarding instructions with registry usage.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  A deterministic, local CLI that verifies active constraints before a coding agent
4
4
  resumes work.
5
5
 
6
- **Version: 0.3.1.**
6
+ **Version: 0.4.0.**
7
7
 
8
8
  A task summary may preserve the goal while losing an active rule, carrying an
9
9
  expired restriction, or moving a staging-only instruction into production.
@@ -18,8 +18,8 @@ Source references are review metadata and are never fetched.
18
18
  Run in the repository where your agent works:
19
19
 
20
20
  ```sh
21
- npx handoff-check@0.3.1 init --scope staging --agent both --dry-run
22
- npx handoff-check@0.3.1 init --scope staging --agent both
21
+ npx handoff-check@0.4.0 init --scope staging --agent both --dry-run
22
+ npx handoff-check@0.4.0 init --scope staging --agent both
23
23
  ```
24
24
 
25
25
  This creates `.handoff-check.json`, starter `constraints.json` and `handoff.json`,
@@ -33,7 +33,7 @@ on verification. Revisions and hashes detect edits under an unchanged rule ID.
33
33
  Ask a resuming agent to use the installed skill, or run:
34
34
 
35
35
  ```sh
36
- npx handoff-check@0.3.1 verify --format json --require-content
36
+ npx handoff-check@0.4.0 verify --format json --require-content
37
37
  ```
38
38
 
39
39
  The saved config supplies paths and scope. `init --ci` also creates a pinned GitHub
@@ -42,7 +42,7 @@ agent execution; CI enforces the declared-ID comparison when its workflow runs.
42
42
  Neither checks whether the agent obeys a rule's meaning.
43
43
 
44
44
  Node.js 22+ is required; end users do not need Bun. Global installation is also
45
- available: `npm install --global handoff-check@0.3.1`. For contributor builds or
45
+ available: `npm install --global handoff-check@0.4.0`. For contributor builds or
46
46
  offline package testing, see the [setup guide](docs/agent-integration.md).
47
47
 
48
48
  For a complete first-rule walkthrough, including a passing baseline and a detected
@@ -65,7 +65,7 @@ default but are explicitly marked. Unexpected reported IDs still fail.
65
65
  To require actual active rules, opt in:
66
66
 
67
67
  ```sh
68
- npx handoff-check@0.3.1 verify --require-content --require-active --format json
68
+ npx handoff-check@0.4.0 verify --require-content --require-active --format json
69
69
  ```
70
70
 
71
71
  A zero active set produces global NO_ACTIVE_CONSTRAINTS (no fake ID), mismatch
@@ -83,8 +83,8 @@ init and snapshot reject it. See the
83
83
  After reviewing rules at handoff creation, capture a new baseline:
84
84
 
85
85
  ```sh
86
- npx handoff-check@0.3.1 snapshot --task "Resume migration review" --output handoff.next.json
87
- npx handoff-check@0.3.1 verify --handoff handoff.next.json --require-content --format json
86
+ npx handoff-check@0.4.0 snapshot --task "Resume migration review" --output handoff.next.json
87
+ npx handoff-check@0.4.0 verify --handoff handoff.next.json --require-content --format json
88
88
  ```
89
89
 
90
90
  Snapshot creates a new file exclusively. Review it before deliberately replacing
@@ -100,9 +100,42 @@ CHANGED C-07 Review changed constraint: ...; handoff revision 1, current r
100
100
  ```
101
101
 
102
102
  JSON findings include expected/reported revision and hash. This detects a change;
103
- it does not show a text diff or authenticate either file. Source reference text is
103
+ v2 does not retain old text or authenticate either file. Source reference text is
104
104
  hashed, but referenced documents are not fetched or checked.
105
105
 
106
+ ## Explain rules and review field changes
107
+
108
+ ```sh
109
+ npx handoff-check@0.4.0 explain --format markdown
110
+ npx handoff-check@0.4.0 snapshot --task "Review migration" --include-content --output handoff.reviewed.json
111
+ npx handoff-check@0.4.0 verify --handoff handoff.reviewed.json --require-content --format markdown
112
+ ```
113
+
114
+ `explain` shows every manifest rule's applicability for the selected scope/time,
115
+ including global, out-of-scope and inactive rules. It uses the same lifecycle
116
+ precedence as verify, never reads the handoff, and exits 0 for a valid explanation.
117
+ It is not a handoff verification. Text, JSON and Markdown are supported.
118
+
119
+ Snapshot still creates v2 by default. Explicit `--include-content` creates a
120
+ **v3 handoff** retaining complete old rule content. For active `CHANGED` rules,
121
+ v3 JSON adds ordered `changes` with typed `before` (saved) and `after` (current)
122
+ values; null means an absent optional field. Text/Markdown show these field deltas,
123
+ including revision-only changes. Lifecycle findings retain precedence. V2 reports
124
+ say previous content is unavailable; hashes cannot reconstruct it.
125
+
126
+ Retained descriptions and source references may contain sensitive data. Review
127
+ before storing or sharing snapshots/reports; retention is never automatic. V3
128
+ validates each stored rule against its ID, revision and hash, but this does not
129
+ authenticate either file. Upgrade all consumers before adopting v3: older CLIs
130
+ cannot read it. No input migration is needed to keep using v1/v2 on 0.4.
131
+
132
+ `verify --format markdown` preserves exit codes 0/1/2 and includes scope, time,
133
+ active count, tracking mode, requested policies and findings. To save a report,
134
+ redirect stdout to a separate file; a shell creates/truncates the destination, so
135
+ never choose a manifest or handoff path. Markdown is verify/explain-only.
136
+ See [ADR 0004](docs/decisions/0004-explainable-verification.md) and the
137
+ [retained-content example](examples/retained-content/handoff.json).
138
+
106
139
  See the [v2 handoff schema](schemas/handoff.v2.schema.json),
107
140
  [v2 manifest schema](schemas/constraints.v2.schema.json), and
108
141
  [canonicalization contract](docs/decisions/0002-content-aware-handoffs.md).
@@ -113,13 +146,13 @@ manifest; its current manifest edits the description without bumping revision.
113
146
 
114
147
  V1 handoffs remain supported in ID-only mode with unchanged v1 JSON result fields.
115
148
  They cannot detect content edits. `--require-content` rejects them instead of
116
- silently falling back. V2 handoffs work with either v1 manifests (implicit revision `1`)
149
+ silently falling back. V2/v3 handoffs work with either v1 manifests (implicit revision `1`)
117
150
  or revisioned v2 manifests. Scope must match the v2 handoff's saved scope.
118
151
 
119
152
  Review current rules, capture a new v2 baseline, and deliberately update the saved
120
153
  handoff. Existing inputs are preserved by init, not silently upgraded. Review
121
154
  installed skills, instruction blocks and CI commands to update their pinned
122
- version to 0.3.1 and add `--require-content`. Init refuses to overwrite differing
155
+ version to 0.4.0 and add `--require-content`. Init refuses to overwrite differing
123
156
  integrations; compare them with the new packaged templates and update reviewed
124
157
  copies explicitly. Never refresh before checking resumed work or reuse capturedAt
125
158
  as the clock for real resumed work.
@@ -244,13 +277,18 @@ handoff-check verify --scope <scope>
244
277
  [--constraints <path>] default: constraints.json
245
278
  [--handoff <path>] default: handoff.json
246
279
  [--as-of <UTC time>] default: current time, captured once
247
- [--format text|json] default: text
248
- [--require-content] require a v2 content-aware handoff
280
+ [--format text|json|markdown] default: text
281
+ [--require-content] require a v2/v3 content-aware handoff
249
282
  [--require-active] fail when no active constraints apply
250
283
 
251
284
  handoff-check snapshot --task <task>
252
285
  [--config <path>] [--constraints <path>] [--scope <scope>]
253
286
  [--as-of <UTC time>] [--output <new-file>] [--format text|json]
287
+ [--include-content] opt-in v3 retained content; default v2
288
+
289
+ handoff-check explain
290
+ [--config <path>] [--constraints <path>] [--scope <scope>]
291
+ [--as-of <UTC time>] [--format text|json|markdown]
254
292
 
255
293
  handoff-check init --scope <scope>
256
294
  [--agent codex|claude|both|none] [--dry-run] [--ci] [--format text|json]
@@ -269,7 +307,7 @@ include global rules even when no scope-specific rules exist.
269
307
 
270
308
  | Exit code | Meaning |
271
309
  | --------- | ---------------------------------------------------------- |
272
- | 0 | Verification succeeded, including requested policies |
310
+ | 0 | Verification succeeded, or explain/init/snapshot succeeded |
273
311
  | 1 | Rule or active-set policy mismatch; inspect findings |
274
312
  | 2 | Invalid arguments, invalid input, or unreadable input file |
275
313
 
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { parseArgs } from "node:util";
7
7
  // package.json
8
8
  var package_default = {
9
9
  name: "handoff-check",
10
- version: "0.3.1",
10
+ version: "0.4.0",
11
11
  description: "A deterministic, local CLI that verifies active constraints before a coding agent resumes work.",
12
12
  type: "module",
13
13
  packageManager: "bun@1.2.10",
@@ -70,6 +70,35 @@ var package_default = {
70
70
  import { readFile } from "node:fs/promises";
71
71
  import { dirname, resolve } from "node:path";
72
72
 
73
+ // src/content.ts
74
+ import { createHash } from "node:crypto";
75
+ function retainedContent(rule) {
76
+ const result = { ...rule, revision: rule.revision ?? 1 };
77
+ for (const field of ["expiresAt", "revokedAt", "supersededAt"]) {
78
+ if (result[field] !== undefined)
79
+ result[field] = new Date(result[field]).toISOString();
80
+ }
81
+ return result;
82
+ }
83
+ function reference(rule) {
84
+ const instant = (value) => value === undefined ? null : new Date(value).toISOString();
85
+ const content = JSON.stringify({
86
+ id: rule.id,
87
+ scope: rule.scope,
88
+ description: rule.description,
89
+ source: rule.source,
90
+ expiresAt: instant(rule.expiresAt),
91
+ revokedAt: instant(rule.revokedAt),
92
+ replacedBy: rule.replacedBy ?? null,
93
+ supersededAt: instant(rule.supersededAt)
94
+ });
95
+ return {
96
+ id: rule.id,
97
+ revision: rule.revision ?? 1,
98
+ contentHash: `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`
99
+ };
100
+ }
101
+
73
102
  // src/validation.ts
74
103
  class InputError extends Error {
75
104
  name = "InputError";
@@ -114,9 +143,9 @@ function timestamp(value, path) {
114
143
  }
115
144
  return millis;
116
145
  }
117
- function version(value, path) {
118
- if (value.schemaVersion !== 1 && value.schemaVersion !== 2)
119
- fail(`${path}.schemaVersion: expected 1 or 2`);
146
+ function version(value, path, retained = false) {
147
+ if (value.schemaVersion !== 1 && value.schemaVersion !== 2 && !(retained && value.schemaVersion === 3))
148
+ fail(`${path}.schemaVersion: expected ${retained ? "1, 2 or 3" : "1 or 2"}`);
120
149
  }
121
150
  function revision(value, path) {
122
151
  if (!Number.isSafeInteger(value) || value < 1)
@@ -131,6 +160,43 @@ function unique(values, path) {
131
160
  seen.add(value);
132
161
  }
133
162
  }
163
+ function parseConstraint(input, path, revisioned) {
164
+ const rule = object(input, path);
165
+ keys(rule, [
166
+ "id",
167
+ "scope",
168
+ "description",
169
+ "source",
170
+ "expiresAt",
171
+ "revokedAt",
172
+ "replacedBy",
173
+ "supersededAt",
174
+ ...revisioned ? ["revision"] : []
175
+ ], path);
176
+ const parsed = {
177
+ id: identifier(rule.id, `${path}.id`),
178
+ scope: identifier(rule.scope, `${path}.scope`),
179
+ description: string(rule.description, `${path}.description`),
180
+ source: string(rule.source, `${path}.source`)
181
+ };
182
+ if (revisioned)
183
+ parsed.revision = revision(rule.revision, `${path}.revision`);
184
+ for (const field of ["expiresAt", "revokedAt", "supersededAt"]) {
185
+ if (Object.hasOwn(rule, field)) {
186
+ timestamp(rule[field], `${path}.${field}`);
187
+ parsed[field] = rule[field];
188
+ }
189
+ }
190
+ if (Object.hasOwn(rule, "replacedBy")) {
191
+ parsed.replacedBy = identifier(rule.replacedBy, `${path}.replacedBy`);
192
+ }
193
+ if (parsed.replacedBy === undefined !== (parsed.supersededAt === undefined)) {
194
+ fail(`${path}: replacedBy and supersededAt must be provided together`);
195
+ }
196
+ if (parsed.replacedBy === parsed.id)
197
+ fail(`${path}: a rule cannot replace itself`);
198
+ return parsed;
199
+ }
134
200
  function parseManifest(input) {
135
201
  const root = object(input, "manifest");
136
202
  keys(root, ["schemaVersion", "constraints"], "manifest");
@@ -138,40 +204,7 @@ function parseManifest(input) {
138
204
  if (!Array.isArray(root.constraints))
139
205
  fail("manifest.constraints: expected an array");
140
206
  const constraints = root.constraints.map((entry, index) => {
141
- const path = `manifest.constraints[${index}]`;
142
- const rule = object(entry, path);
143
- keys(rule, [
144
- "id",
145
- "scope",
146
- "description",
147
- "source",
148
- "expiresAt",
149
- "revokedAt",
150
- "replacedBy",
151
- "supersededAt",
152
- ...root.schemaVersion === 2 ? ["revision"] : []
153
- ], path);
154
- const parsed = {
155
- id: identifier(rule.id, `${path}.id`),
156
- scope: identifier(rule.scope, `${path}.scope`),
157
- description: string(rule.description, `${path}.description`),
158
- source: string(rule.source, `${path}.source`)
159
- };
160
- if (root.schemaVersion === 2)
161
- parsed.revision = revision(rule.revision, `${path}.revision`);
162
- for (const field of ["expiresAt", "revokedAt", "supersededAt"]) {
163
- if (Object.hasOwn(rule, field)) {
164
- timestamp(rule[field], `${path}.${field}`);
165
- parsed[field] = rule[field];
166
- }
167
- }
168
- if (Object.hasOwn(rule, "replacedBy")) {
169
- parsed.replacedBy = identifier(rule.replacedBy, `${path}.replacedBy`);
170
- }
171
- if (parsed.replacedBy === undefined !== (parsed.supersededAt === undefined)) {
172
- fail(`${path}: replacedBy and supersededAt must be provided together`);
173
- }
174
- return parsed;
207
+ return parseConstraint(entry, `manifest.constraints[${index}]`, root.schemaVersion === 2);
175
208
  });
176
209
  unique(constraints.map((rule) => rule.id), "manifest.constraints");
177
210
  const byId = new Map(constraints.map((rule) => [rule.id, rule]));
@@ -201,35 +234,51 @@ function parseManifest(input) {
201
234
  }
202
235
  function parseHandoff(input) {
203
236
  const root = object(input, "handoff");
204
- version(root, "handoff");
237
+ version(root, "handoff", true);
205
238
  keys(root, [
206
239
  "schemaVersion",
207
240
  "task",
208
241
  "activeConstraints",
209
- ...root.schemaVersion === 2 ? ["scope", "capturedAt"] : []
242
+ ...root.schemaVersion !== 1 ? ["scope", "capturedAt"] : []
210
243
  ], "handoff");
211
244
  const task = string(root.task, "handoff.task");
212
245
  if (!Array.isArray(root.activeConstraints))
213
246
  fail("handoff.activeConstraints: expected an array");
214
- if (root.schemaVersion === 2) {
247
+ if (root.schemaVersion !== 1) {
215
248
  const scope = identifier(root.scope, "handoff.scope");
216
249
  timestamp(root.capturedAt, "handoff.capturedAt");
217
250
  const activeConstraints2 = root.activeConstraints.map((entry, index) => {
218
251
  const path = `handoff.activeConstraints[${index}]`;
219
252
  const ref = object(entry, path);
220
- keys(ref, ["id", "revision", "contentHash"], path);
253
+ keys(ref, [
254
+ "id",
255
+ "revision",
256
+ "contentHash",
257
+ ...root.schemaVersion === 3 ? ["content"] : []
258
+ ], path);
221
259
  const contentHash = string(ref.contentHash, `${path}.contentHash`);
222
260
  if (!/^sha256:[a-f0-9]{64}(?![\s\S])/.test(contentHash))
223
261
  fail(`${path}.contentHash: expected sha256 followed by 64 lowercase hex digits`);
224
- return {
262
+ const parsed = {
225
263
  id: identifier(ref.id, `${path}.id`),
226
264
  revision: revision(ref.revision, `${path}.revision`),
227
265
  contentHash
228
266
  };
267
+ if (root.schemaVersion === 3) {
268
+ const content = parseConstraint(ref.content, `${path}.content`, true);
269
+ const expected = reference(content);
270
+ if (expected.id !== parsed.id || expected.revision !== parsed.revision || expected.contentHash !== parsed.contentHash)
271
+ fail(`${path}.content: id, revision and canonical hash must match the reference`);
272
+ return {
273
+ ...parsed,
274
+ content
275
+ };
276
+ }
277
+ return parsed;
229
278
  });
230
279
  unique(activeConstraints2.map((ref) => ref.id), "handoff.activeConstraints");
231
280
  return {
232
- schemaVersion: 2,
281
+ schemaVersion: root.schemaVersion,
233
282
  task,
234
283
  scope,
235
284
  capturedAt: root.capturedAt,
@@ -504,25 +553,77 @@ jobs:
504
553
  };
505
554
  }
506
555
 
507
- // src/content.ts
508
- import { createHash } from "node:crypto";
509
- function reference(rule) {
510
- const instant = (value) => value === undefined ? null : new Date(value).toISOString();
511
- const content = JSON.stringify({
512
- id: rule.id,
513
- scope: rule.scope,
514
- description: rule.description,
515
- source: rule.source,
516
- expiresAt: instant(rule.expiresAt),
517
- revokedAt: instant(rule.revokedAt),
518
- replacedBy: rule.replacedBy ?? null,
519
- supersededAt: instant(rule.supersededAt)
520
- });
521
- return {
522
- id: rule.id,
523
- revision: rule.revision ?? 1,
524
- contentHash: `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`
525
- };
556
+ // src/render.ts
557
+ function terminalText(value) {
558
+ return Array.from(value, (character) => {
559
+ const code = character.codePointAt(0) ?? 0;
560
+ return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
561
+ }).join("");
562
+ }
563
+ function markdownText(value) {
564
+ return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
565
+ }
566
+ function verificationMarkdown(result, handoff, requireActive, requireContent) {
567
+ const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
568
+ const lines = [
569
+ "# Handoff Check verification",
570
+ "",
571
+ `- Result: ${label}`,
572
+ `- Scope: ${markdownText(result.scope)}`,
573
+ `- Evaluated at: ${markdownText(result.asOf)}`,
574
+ `- Active constraints checked: ${result.expectedConstraints.length}`,
575
+ `- Tracking: ${handoff.schemaVersion === 1 ? "IDs only; content changes not checked" : handoff.schemaVersion === 3 ? "Content hashes with retained old content" : "Content hashes; old content not retained"}`,
576
+ `- Require content-aware handoff: ${requireContent}`,
577
+ `- Require active constraints: ${requireActive}`,
578
+ ""
579
+ ];
580
+ if (!result.expectedConstraints.length)
581
+ lines.push("No active constraints apply to this scope and time.", "");
582
+ lines.push("## Findings", "");
583
+ if (!result.findings.length)
584
+ lines.push("No findings.", "");
585
+ for (const finding of result.findings) {
586
+ lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
587
+ if (finding.code === "CHANGED") {
588
+ if (finding.changes) {
589
+ lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
590
+ for (const change of finding.changes)
591
+ lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
592
+ lines.push("", "Null means an absent optional field.", "");
593
+ } else
594
+ lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
595
+ }
596
+ }
597
+ lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
598
+ return `${lines.join(`
599
+ `)}
600
+ `;
601
+ }
602
+ function explanationText(result, markdown) {
603
+ if (markdown) {
604
+ return [
605
+ "# Handoff Check explanation",
606
+ "",
607
+ `- Scope: ${markdownText(result.scope)}`,
608
+ `- Evaluated at: ${markdownText(result.asOf)}`,
609
+ `- Active constraints: ${result.activeConstraintCount}`,
610
+ "",
611
+ "| ID | Rule scope | Decision | Reason | Description | Source |",
612
+ "| --- | --- | --- | --- | --- | --- |",
613
+ ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
614
+ "",
615
+ "Explains manifest applicability only; no handoff was compared.",
616
+ ""
617
+ ].join(`
618
+ `);
619
+ }
620
+ return [
621
+ ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
622
+ `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}`,
623
+ "No handoff was compared.",
624
+ ""
625
+ ].join(`
626
+ `);
526
627
  }
527
628
 
528
629
  // src/verifier.ts
@@ -542,14 +643,15 @@ function inactive(rule, scope, time) {
542
643
  }
543
644
  function verify(manifest, handoff, scope, asOf, options = {}) {
544
645
  identifier(scope, "scope");
545
- if (handoff.schemaVersion === 2 && handoff.scope !== scope)
646
+ if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
546
647
  throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
547
648
  const time = timestamp(asOf, "asOf");
548
649
  const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
549
650
  const expectedConstraints = manifest.constraints.filter((rule) => inactive(rule, scope, time) === undefined).map((rule) => rule.id).sort(compare);
550
- const refs = new Map(handoff.schemaVersion === 2 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
651
+ const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
551
652
  const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
552
653
  const reported = new Set(reportedConstraints);
654
+ const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
553
655
  const findings = [];
554
656
  for (const id of expectedConstraints) {
555
657
  if (!reported.has(id))
@@ -569,7 +671,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
569
671
  id,
570
672
  message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
571
673
  });
572
- } else if (rule && handoff.schemaVersion === 2) {
674
+ } else if (rule && handoff.schemaVersion !== 1) {
573
675
  const current = reference(rule);
574
676
  const previous = refs.get(id);
575
677
  if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
@@ -584,7 +686,10 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
584
686
  reported: {
585
687
  revision: previous.revision,
586
688
  contentHash: previous.contentHash
587
- }
689
+ },
690
+ ...retained.has(id) ? {
691
+ changes: fieldChanges(retained.get(id), rule)
692
+ } : {}
588
693
  });
589
694
  }
590
695
  }
@@ -598,7 +703,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
598
703
  findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
599
704
  return {
600
705
  schemaVersion: handoff.schemaVersion,
601
- ...handoff.schemaVersion === 2 ? {
706
+ ...handoff.schemaVersion !== 1 ? {
602
707
  tracking: "content",
603
708
  activeConstraintCount: expectedConstraints.length
604
709
  } : {},
@@ -610,17 +715,84 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
610
715
  findings
611
716
  };
612
717
  }
613
- function snapshot(manifest, task, scope, asOf) {
718
+ function snapshot(manifest, task, scope, asOf, options = {}) {
614
719
  if (!task.trim())
615
720
  throw new InputError("--task: expected a non-empty task");
616
721
  const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
617
722
  const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
618
- return {
619
- schemaVersion: 2,
723
+ const base = {
620
724
  task,
621
725
  scope,
622
- capturedAt: result.asOf,
623
- activeConstraints: result.expectedConstraints.map((id) => reference(byId.get(id)))
726
+ capturedAt: result.asOf
727
+ };
728
+ const rules = result.expectedConstraints.map((id) => byId.get(id));
729
+ return options.includeContent ? {
730
+ ...base,
731
+ schemaVersion: 3,
732
+ activeConstraints: rules.map((rule) => ({
733
+ ...reference(rule),
734
+ content: retainedContent(rule)
735
+ }))
736
+ } : { ...base, schemaVersion: 2, activeConstraints: rules.map(reference) };
737
+ }
738
+ var fields = [
739
+ "id",
740
+ "scope",
741
+ "description",
742
+ "source",
743
+ "expiresAt",
744
+ "revokedAt",
745
+ "replacedBy",
746
+ "supersededAt",
747
+ "revision"
748
+ ];
749
+ function fieldChanges(previous, current) {
750
+ const before = retainedContent(previous);
751
+ const after = retainedContent(current);
752
+ return fields.filter((field) => before[field] !== after[field]).map((field) => ({
753
+ field,
754
+ before: before[field] ?? null,
755
+ after: after[field] ?? null
756
+ }));
757
+ }
758
+ function explain(manifest, scope, asOf) {
759
+ identifier(scope, "scope");
760
+ const time = timestamp(asOf, "asOf");
761
+ const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
762
+ const decision = inactive(rule, scope, time) ?? "ACTIVE";
763
+ let reason;
764
+ switch (decision) {
765
+ case "ACTIVE":
766
+ reason = `${rule.scope === "global" ? "Global rule" : "Selected scope matches"}; no lifecycle transition is effective`;
767
+ break;
768
+ case "OUT_OF_SCOPE":
769
+ reason = `Rule scope '${rule.scope}' does not match '${scope}' and is not global`;
770
+ break;
771
+ case "REVOKED":
772
+ reason = `Revoked at ${new Date(rule.revokedAt ?? "").toISOString()}`;
773
+ break;
774
+ case "SUPERSEDED":
775
+ reason = `Superseded at ${new Date(rule.supersededAt ?? "").toISOString()}; replaced by '${rule.replacedBy}'`;
776
+ break;
777
+ case "EXPIRED":
778
+ reason = `Expired at ${new Date(rule.expiresAt ?? "").toISOString()}`;
779
+ break;
780
+ }
781
+ return {
782
+ id: rule.id,
783
+ scope: rule.scope,
784
+ description: rule.description,
785
+ source: rule.source,
786
+ decision,
787
+ reason
788
+ };
789
+ });
790
+ return {
791
+ schemaVersion: 1,
792
+ scope,
793
+ asOf: new Date(time).toISOString(),
794
+ activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
795
+ rules
624
796
  };
625
797
  }
626
798
 
@@ -630,6 +802,7 @@ var help = `Handoff Check
630
802
  Usage: handoff-check verify --scope <scope> [options]
631
803
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
632
804
  handoff-check snapshot --task <task> [--output <new-file>] [options]
805
+ handoff-check explain --scope <scope> [options]
633
806
 
634
807
  Options:
635
808
  --constraints <path> Manifest file (default: constraints.json)
@@ -637,28 +810,20 @@ Options:
637
810
  --scope <scope> Selected scope, including global constraints
638
811
  --config <path> Project config (default: cwd/.handoff-check.json)
639
812
  --as-of <UTC time> Fixed evaluation time (default: current time)
640
- --require-content verify: require a v2 content-aware handoff
813
+ --require-content verify: require a v2/v3 content-aware handoff
641
814
  --require-active verify: fail if no constraints apply to scope/time
642
815
  --task <task> snapshot: task description (required)
643
816
  --output <path> snapshot: create a new baseline file, never overwrite
644
- --format text|json Output format (default: text)
817
+ --include-content snapshot: retain old rule text in a v3 handoff (opt-in)
818
+ --format text|json|markdown Markdown is verify/explain-only (default: text)
645
819
  --agent <agent> init: codex, claude, both (default), or none
646
820
  --dry-run init: preview files and instruction changes without writes
647
821
  --ci init: also create a pinned GitHub Actions check
648
822
  --version Show package version
649
823
  --help Show this help
650
824
 
651
- Exit codes: 0 verified, 1 rule/policy mismatch, 2 invalid input
825
+ Exit codes: 0 verified/explained/captured/initialized, 1 rule/policy mismatch, 2 invalid input
652
826
  `;
653
- function terminalText(value) {
654
- return Array.from(value, (character) => {
655
- const code = character.charCodeAt(0);
656
- if (code < 32 || code >= 127 && code <= 159 || code === 8232 || code === 8233) {
657
- return `\\u${code.toString(16).padStart(4, "0")}`;
658
- }
659
- return character;
660
- }).join("");
661
- }
662
827
  async function main() {
663
828
  let format = "text";
664
829
  try {
@@ -680,13 +845,14 @@ async function main() {
680
845
  ci: { type: "boolean" },
681
846
  "require-content": { type: "boolean" },
682
847
  "require-active": { type: "boolean" },
848
+ "include-content": { type: "boolean" },
683
849
  task: { type: "string" },
684
850
  output: { type: "string" }
685
851
  }
686
852
  });
687
853
  format = values.format;
688
- if (format !== "text" && format !== "json")
689
- throw new InputError("--format: expected text or json");
854
+ if (!["text", "json", "markdown"].includes(format))
855
+ throw new InputError("--format: expected text, json or markdown");
690
856
  if (values.help) {
691
857
  process.stdout.write(help);
692
858
  return 0;
@@ -696,9 +862,22 @@ async function main() {
696
862
  `);
697
863
  return 0;
698
864
  }
699
- if (positionals.length !== 1 || !["verify", "init", "snapshot"].includes(positionals[0] ?? ""))
700
- throw new InputError("Expected command: verify, snapshot or init (use --help for usage)");
865
+ if (positionals.length !== 1 || !["verify", "init", "snapshot", "explain"].includes(positionals[0] ?? ""))
866
+ throw new InputError("Expected command: verify, snapshot, explain or init (use --help for usage)");
701
867
  const cwd = process.cwd();
868
+ const command = positionals[0];
869
+ if (format === "markdown" && command !== "verify" && command !== "explain")
870
+ throw new InputError("--format markdown is only supported by verify and explain");
871
+ if (values["include-content"] !== undefined && command !== "snapshot")
872
+ throw new InputError("--include-content is only supported by snapshot");
873
+ if (command === "explain" && [
874
+ values.handoff,
875
+ values.task,
876
+ values.output,
877
+ values["require-content"],
878
+ values["require-active"]
879
+ ].some((value) => value !== undefined))
880
+ throw new InputError("--handoff, --task, --output and --require-* are not supported by explain");
702
881
  if (positionals[0] === "init") {
703
882
  for (const key of [
704
883
  "constraints",
@@ -751,12 +930,20 @@ ${result2.notice}
751
930
  if (values[key] !== undefined && !values[key].trim())
752
931
  throw new InputError(`--${key}: expected a non-empty path`);
753
932
  const manifest = parseManifest(await readJson(values.constraints !== undefined ? resolve3(cwd, values.constraints) : resolve3(directory, config.constraints ?? "constraints.json")));
933
+ if (command === "explain") {
934
+ const result2 = explain(manifest, scope, asOf);
935
+ process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
936
+ ` : explanationText(result2, format === "markdown"));
937
+ return 0;
938
+ }
754
939
  if (positionals[0] === "snapshot") {
755
940
  if (values.handoff !== undefined || values["require-content"] !== undefined || values["require-active"] !== undefined)
756
941
  throw new InputError("--handoff, --require-content and --require-active are only supported by verify");
757
942
  if (values.task === undefined)
758
943
  throw new InputError("snapshot requires --task");
759
- const captured = snapshot(manifest, values.task, scope, asOf);
944
+ const captured = snapshot(manifest, values.task, scope, asOf, {
945
+ includeContent: values["include-content"] ?? false
946
+ });
760
947
  const content = `${JSON.stringify(captured, null, 2)}
761
948
  `;
762
949
  if (values.output === undefined)
@@ -791,18 +978,29 @@ ${result2.notice}
791
978
  if (values.task !== undefined || values.output !== undefined)
792
979
  throw new InputError("--task and --output are only supported by snapshot");
793
980
  const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve3(cwd, values.handoff) : resolve3(directory, config.handoff ?? "handoff.json")));
794
- if (values["require-content"] && handoff.schemaVersion !== 2)
795
- throw new InputError("Content tracking requires a schemaVersion 2 handoff; review current rules and capture a snapshot before resuming");
981
+ if (values["require-content"] && handoff.schemaVersion === 1)
982
+ throw new InputError("Content tracking requires a schemaVersion 2 or 3 handoff; review current rules and capture a snapshot before resuming");
796
983
  const result = verify(manifest, handoff, scope, asOf, {
797
984
  requireActive: values["require-active"] ?? false
798
985
  });
799
986
  if (format === "json") {
800
987
  process.stdout.write(`${JSON.stringify(result, null, 2)}
801
988
  `);
989
+ } else if (format === "markdown") {
990
+ process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false));
802
991
  } else {
803
992
  for (const finding of result.findings) {
804
993
  process.stdout.write(`${finding.code.padEnd(12)} ${finding.id === undefined ? "" : `${finding.id} `}${terminalText(finding.message)}
805
994
  `);
995
+ if (finding.code === "CHANGED") {
996
+ if (finding.changes)
997
+ for (const change of finding.changes)
998
+ process.stdout.write(` ${change.field}: ${terminalText(JSON.stringify(change.before))} -> ${terminalText(JSON.stringify(change.after))}
999
+ `);
1000
+ else
1001
+ process.stdout.write(` Previous content unavailable: baseline stores hashes only
1002
+ `);
1003
+ }
806
1004
  }
807
1005
  const count = result.expectedConstraints.length;
808
1006
  const label = result.status === "verified" ? count === 0 ? "PASS (EMPTY)" : "PASS" : "FAIL";
@@ -9,8 +9,8 @@ infers rules from a summary.
9
9
  From the consuming repository root:
10
10
 
11
11
  ```sh
12
- npx handoff-check@0.3.1 init --scope staging --agent both --dry-run
13
- npx handoff-check@0.3.1 init --scope staging --agent both
12
+ npx handoff-check@0.4.0 init --scope staging --agent both --dry-run
13
+ npx handoff-check@0.4.0 init --scope staging --agent both
14
14
  ```
15
15
 
16
16
  Choose `codex`, `claude`, `both` (default), or `none`. Generated integrations:
@@ -39,8 +39,8 @@ npm pack
39
39
  From a separate consuming project, substitute the actual absolute tarball path:
40
40
 
41
41
  ```sh
42
- npx --offline --yes --package=/absolute/path/handoff-check-0.3.1.tgz handoff-check init --scope staging --agent both
43
- npx --offline --yes --package=/absolute/path/handoff-check-0.3.1.tgz handoff-check verify --format json --require-content
42
+ npx --offline --yes --package=/absolute/path/handoff-check-0.4.0.tgz handoff-check init --scope staging --agent both
43
+ npx --offline --yes --package=/absolute/path/handoff-check-0.4.0.tgz handoff-check verify --format json --require-content
44
44
  ```
45
45
 
46
46
  Bun is not required for these consumer commands. Generated agent commands use the
@@ -64,7 +64,14 @@ At handoff creation, review current rules and run the configured CLI's
64
64
  `snapshot --task "Resume the task" --output handoff.next.json`. Review that file
65
65
  before explicitly promoting it to the configured handoff. On resume, verify the
66
66
  saved baseline first; do not regenerate it to hide a CHANGED finding. Snapshot
67
- records revisions/hashes, not old text, and capturedAt is not the evaluation clock.
67
+ records revisions/hashes by default, and capturedAt is not the evaluation clock.
68
+ 0.4 optionally retains old text in v3 with explicit `--include-content` at reviewed
69
+ capture time. This copies full rule content into the handoff: review sensitive
70
+ data before committing/sharing. Default v2 capture is unchanged; upgrade every
71
+ consumer before adopting v3. Both v2 and v3 satisfy `--require-content`.
72
+ Use `explain` for applicability diagnostics and `verify --format markdown` for
73
+ review reports; explain exit 0 does not verify a handoff. See the
74
+ [explainability guide](explainability.md).
68
75
 
69
76
  Existing v1 inputs are preserved. Review/capture a v2 handoff and explicitly update
70
77
  old skill/managed-block/CI pins before relying on content tracking. Existing v1
@@ -8,6 +8,11 @@ The CLI owns argument parsing, local file I/O, clock capture, rendering, and exi
8
8
  codes. Validation rejects malformed contracts before verification begins. The
9
9
  pure core receives validated objects, an explicit scope, and an explicit time.
10
10
 
11
+ Explain uses the same lifecycle classifier as verification, without consuming a
12
+ handoff. Optional v3 snapshots retain validated old content for field-level diffs;
13
+ default snapshots remain v2. Pure renderers provide text and Markdown output.
14
+ See decisions/0004-explainable-verification.md for contracts and compatibility.
15
+
11
16
  No verification operation writes inputs, accesses a network, calls a model,
12
17
  executes source references, or reads agent transcripts. Output order must be
13
18
  independent of manifest and handoff ordering.
@@ -0,0 +1,78 @@
1
+ # ADR 0004: Explainable verification
2
+
3
+ Status: accepted for 0.4.0.
4
+
5
+ ## Compatibility and retention
6
+
7
+ Manifest formats remain v1/v2. Default snapshot remains handoff v2. Existing
8
+ handoff v1/v2 JSON result shapes and canonical hash algorithm v1 are unchanged.
9
+ `--require-content` accepts handoff v2 or v3 and rejects ID-only v1.
10
+
11
+ Explicit snapshot `--include-content` produces handoff schemaVersion 3. Each
12
+ reference requires `content`: a standalone v2 constraint object with required
13
+ positive safe revision and the same strict field/date/pair validation as manifest
14
+ rules. ID, revision and canonical hash must agree with the outer reference or
15
+ parsing fails with exit 2. Unknown fields and null input values remain invalid.
16
+ IDs remain unique. Stored content rejects self-replacement, but replacement
17
+ targets need not occur in the captured set; it is not a replacement manifest.
18
+ Global relationship checks still apply to the actual manifest.
19
+
20
+ Capture makes independent copies, preserves exact description/source strings,
21
+ normalizes lifecycle timestamps to UTC milliseconds, and supplies implicit revision
22
+ 1 for manifest v1 rules. Empty captures are valid. Capture does not read the old
23
+ handoff or sources, infer rules, or promote/replace a baseline.
24
+
25
+ Retention copies full descriptions, source references and lifecycle fields into
26
+ handoffs and potentially reports. It is opt-in, with no auto-upgrade or default
27
+ retention. Review sensitive content and repository access before sharing. Consistent
28
+ hashes detect changes, not authorship or authorization. Someone controlling content
29
+ and reference can replace both. Older CLIs reject v3; upgrade consumers first.
30
+
31
+ ## Deltas and results
32
+
33
+ V3 verification results use schemaVersion 3 with content tracking and active count.
34
+ Active reported CHANGED rules have `changes`, an ordered array of objects with
35
+ `field`, `before` (saved), and `after` (current). Values are strings, revision
36
+ numbers, or null for an absent optional field; null is not permitted in rule input.
37
+ Field order is id, scope, description, source, expiresAt, revokedAt, replacedBy,
38
+ supersededAt, revision. Equivalent normalized timestamps do not create changes.
39
+ Revision-only changes are included, despite revision being outside the content hash.
40
+
41
+ Scope/lifecycle precedence is unchanged. Inactive/unknown/missing rules do not get
42
+ invented deltas. V1/v2 findings do not gain fields. V2 CHANGED text/Markdown clearly
43
+ states old content is unavailable; hashes cannot reconstruct previous text.
44
+ Verification is read-only and never refreshes a baseline to clear a finding.
45
+
46
+ ## Explain
47
+
48
+ `explain` reads only config/manifest, not the handoff. Its JSON contract is an
49
+ independent schemaVersion 1 object: scope, normalized asOf, activeConstraintCount,
50
+ and rules sorted by ID. Each rule has id, scope, description, source, decision,
51
+ and reason. Decision is ACTIVE, OUT_OF_SCOPE, REVOKED, SUPERSEDED, or EXPIRED.
52
+ The shared classifier uses the established scope-before-lifecycle precedence;
53
+ global rules apply everywhere and transitions take effect at their exact instant.
54
+ Reasons explain applicability of the supplied data, not prose meaning or history.
55
+
56
+ Valid explain exits 0 even when rules are inactive or the active set is empty;
57
+ this must never be presented as successful handoff verification. Invalid inputs
58
+ exit 2. No nonempty policy, handoff/task/output flag or include-content flag is
59
+ accepted by explain. It does not authenticate input or prove agent compliance.
60
+
61
+ ## Rendering and command boundaries
62
+
63
+ Verify/explain support text, JSON and Markdown. Markdown reports include scope,
64
+ time, count and findings; verify additionally reports tracking and requested
65
+ policies. They do not include uncontrolled HTML, link syntax, fences or extra rows:
66
+ untrusted values are escaped as numeric entities and control/format characters
67
+ render visibly. JSON stays machine-readable; Markdown is a presentation format,
68
+ not an input contract. Both reports are deterministic for supplied inputs/options.
69
+
70
+ Verify exit codes remain 0 verified, 1 mismatch/policy failure, 2 invalid input.
71
+ Report output goes to stdout, errors to stderr; Markdown errors are terminal-safe
72
+ plain diagnostics. Shell redirection is external to the CLI and can overwrite its
73
+ destination: documentation must warn against directing reports onto input paths.
74
+
75
+ Markdown is rejected for init/snapshot, and include-content is snapshot-only.
76
+ Snapshot stdout remains JSON; text/json format controls its acknowledgement only
77
+ when an exclusive output file is requested. Skills and generated CI keep using
78
+ the single verifier; no automatic retention or new enforcement hook is installed.
@@ -1,6 +1,6 @@
1
1
  # Development plan
2
2
 
3
- Status: proposed after 0.3.0; documentation/onboarding work ships in 0.3.1.
3
+ Status: 0.3.1 onboarding and 0.4 explainability implemented; later milestones proposed.
4
4
  Research reviewed: 2026-11-24. Version labels below are targets, not release promises.
5
5
 
6
6
  ## Product direction
@@ -45,7 +45,13 @@ Acceptance: execute the walkthrough using a built package from a separate consum
45
45
  directory; observe expected statuses/codes and verify that verification does not
46
46
  rewrite the saved baseline. Check documented flags against actual CLI behavior.
47
47
 
48
- ## 0.4: explainable verification
48
+ ## 0.4: explainable verification (implemented)
49
+
50
+ Implemented in 0.4.0 under [ADR 0004](decisions/0004-explainable-verification.md):
51
+ manifest-only explain, opt-in v3 retained-content snapshots and field-level deltas,
52
+ and Markdown reports. Default v2 snapshots and existing v1/v2 JSON remain compatible.
53
+ The following acceptance criteria govern the implementation; pilot measurements
54
+ remain future work and are not implied by shipping these features.
49
55
 
50
56
  Priority: high. Dependencies: an ADR for snapshot evolution and privacy/storage choices.
51
57
 
@@ -0,0 +1,63 @@
1
+ # Explain applicability and review changes
2
+
3
+ Requires Handoff Check 0.4.0+ and Node.js 22+. Run from your configured repository.
4
+ No service, model call or API key is needed.
5
+
6
+ ## Understand the active set
7
+
8
+ ```sh
9
+ npx handoff-check@0.4.0 explain --format json
10
+ npx handoff-check@0.4.0 explain --scope production --format markdown
11
+ ```
12
+
13
+ Explain reads the manifest but not the handoff. Every rule has an applicability
14
+ decision and reason; global rules count once. Use `--as-of` for an explicitly fixed
15
+ evaluation. It cannot reconstruct historic file contents. A valid explanation
16
+ exits 0 even with zero active rules: use verify to compare a handoff.
17
+
18
+ ## Opt in to saved content
19
+
20
+ At a reviewed handoff creation, after upgrading all consumers to 0.4+:
21
+
22
+ ```sh
23
+ npx handoff-check@0.4.0 snapshot --task "Review staging migrations" --include-content --output handoff.reviewed.json
24
+ npx handoff-check@0.4.0 verify --handoff handoff.reviewed.json --require-content --require-active --format markdown
25
+ ```
26
+
27
+ Review the new file before explicitly adopting it in config. Snapshot never
28
+ overwrites a path. Default snapshots remain v2; the flag creates v3 containing
29
+ full old descriptions, sources, revision and lifecycle values. Consider sensitive
30
+ content before storing or sharing. Old v1/v2 files do not require migration.
31
+
32
+ After a same-ID description edit, verification produces CHANGED and exit 1.
33
+ V3 JSON adds typed `changes`; text and Markdown show the saved/current fields.
34
+ Revision-only edits appear too; null indicates an absent optional field. Expired,
35
+ revoked or superseded rules retain their primary lifecycle finding instead.
36
+ V2 detects changes but cannot show old text. V3 validates retained data against
37
+ its reference; it does not authenticate who reviewed or changed the rule.
38
+
39
+ Never recapture a saved baseline before checking resumed work. Resolve findings
40
+ and review changes before deliberately capturing and adopting a new baseline.
41
+
42
+ ## Reports in local review or CI
43
+
44
+ Use `verify --format markdown` for a deterministic report with the same 0/1/2 exit
45
+ codes. Redirect it only to a separate report file; shell redirection can truncate
46
+ the destination before verification starts, including an input if misconfigured.
47
+ CI can upload that file as an artifact or display it in a job summary. Preserve
48
+ the verifier exit code so a report upload does not turn a mismatch into a pass.
49
+
50
+ Reports contain escaped user data, not commands to execute. A PASS checks declared
51
+ constraints, not their semantic enforcement, authenticity, or permission to act.
52
+
53
+ ## Reproducible example
54
+
55
+ From the source checkout after building, run:
56
+
57
+ ```sh
58
+ node dist/cli.js explain --constraints examples/retained-content/constraints.json --scope staging --as-of 2026-11-24T10:00:00Z --format markdown
59
+ node dist/cli.js verify --constraints examples/retained-content/constraints.json --handoff examples/retained-content/handoff.json --scope staging --as-of 2026-11-24T10:00:00Z --require-content --format markdown
60
+ ```
61
+
62
+ The second command deliberately exits 1 and shows the old/current description.
63
+ See [ADR 0004](decisions/0004-explainable-verification.md) for precise contracts.
@@ -8,8 +8,8 @@ Bun, API keys, and GitHub Actions are not required. All rules below are syntheti
8
8
  ```sh
9
9
  mkdir handoff-check-demo
10
10
  cd handoff-check-demo
11
- npx handoff-check@0.3.1 init --scope staging --agent none
12
- npx handoff-check@0.3.1 verify --require-content
11
+ npx handoff-check@0.4.0 init --scope staging --agent none
12
+ npx handoff-check@0.4.0 verify --require-content
13
13
  ```
14
14
 
15
15
  The starter passes with `PASS (EMPTY)` and `0 active constraints checked`.
@@ -41,7 +41,7 @@ does not fetch it or check the contents of a referenced document.
41
41
  Before capturing a baseline, run:
42
42
 
43
43
  ```sh
44
- npx handoff-check@0.3.1 verify --require-content --require-active
44
+ npx handoff-check@0.4.0 verify --require-content --require-active
45
45
  ```
46
46
 
47
47
  Expect `MISSING MIGRATION-REVIEW`, one active constraint, and exit 1. The old
@@ -50,8 +50,8 @@ starter handoff does not include the new rule yet.
50
50
  ## Capture and verify a reviewed baseline
51
51
 
52
52
  ```sh
53
- npx handoff-check@0.3.1 snapshot --task "Review staging migration" --output handoff.reviewed.json
54
- npx handoff-check@0.3.1 verify --handoff handoff.reviewed.json --require-content --require-active
53
+ npx handoff-check@0.4.0 snapshot --task "Review staging migration" --output handoff.reviewed.json
54
+ npx handoff-check@0.4.0 verify --handoff handoff.reviewed.json --require-content --require-active
55
55
  ```
56
56
 
57
57
  Review the generated file before relying on it. The verification command should
@@ -70,7 +70,7 @@ In `constraints.json`, change the description to
70
70
  handoff unchanged, then run:
71
71
 
72
72
  ```sh
73
- npx handoff-check@0.3.1 verify --handoff handoff.reviewed.json --require-content --require-active --format json
73
+ npx handoff-check@0.4.0 verify --handoff handoff.reviewed.json --require-content --require-active --format json
74
74
  ```
75
75
 
76
76
  Expect `status: "mismatch"`, `activeConstraintCount: 1`, a `CHANGED` finding, and
@@ -79,8 +79,9 @@ deliberate policy update, also increment its revision during review.
79
79
 
80
80
  Do not recapture a baseline just to make a resumed check pass. Review the changed
81
81
  rule and resolve affected work first; only then deliberately capture and adopt a
82
- new baseline. Current snapshots detect changes but do not retain old descriptions
83
- or display textual diffs.
82
+ new baseline. Default v2 snapshots detect changes without retaining old descriptions.
83
+ For opt-in v3 field-level diffs and Markdown reports, see the
84
+ [0.4 guide](explainability.md). Do not recapture a resumed baseline to add retention.
84
85
 
85
86
  ## Interpret the result correctly
86
87
 
package/docs/releasing.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Releasing
2
2
 
3
3
  The npm package name is `handoff-check`; the binary is `handoff-check` and the
4
- current version is 0.3.1. The package is already published; subsequent releases
4
+ current version is 0.4.0. The package is already published; subsequent releases
5
5
  use the configured trusted publisher and the reviewed-artifact process below.
6
6
 
7
7
  ## Release a reviewed version
@@ -19,12 +19,12 @@ use the configured trusted publisher and the reviewed-artifact process below.
19
19
  publish-run artifact and compare it before claiming artifact continuity.
20
20
  For first-publication bootstrap or an explicitly chosen manual release, use
21
21
  `npm login` and publish the reviewed tarball directly with
22
- `npm publish /absolute/path/handoff-check-0.3.1.tgz --ignore-scripts --access public`.
22
+ `npm publish /absolute/path/handoff-check-0.4.0.tgz --ignore-scripts --access public`.
23
23
  Complete interactive two-factor authentication directly with npm.
24
24
  5. Verify registry name, version, binary and integrity, then test
25
- `npx --yes handoff-check@0.3.1 --version` and fresh-project init/verify using a
25
+ `npx --yes handoff-check@0.4.0 --version` and fresh-project init/verify using a
26
26
  new package cache and the public registry, rather than the local tarball.
27
- 6. Create tag `v0.3.1` and a GitHub release on the reviewed main commit, attach the
27
+ 6. Create tag `v0.4.0` and a GitHub release on the reviewed main commit, attach the
28
28
  same tarball, and describe features, requirements and known limits.
29
29
 
30
30
  Publishing is immutable for a given npm name/version. Fix failed candidates on a
package/docs/roadmap.md CHANGED
@@ -2,7 +2,11 @@
2
2
 
3
3
  See the [development plan](development-plan.md) for research evidence, proposed
4
4
  0.4–0.6 milestones, dependencies, pilot validation, and acceptance criteria.
5
- These are proposed milestones, not implemented features or promised dates.
5
+ The plan distinguishes implemented releases from proposed milestones and dates.
6
+
7
+ Implemented in 0.4.0: shared-lifecycle explain, opt-in retained-content v3
8
+ snapshots and field deltas, and escaped Markdown verify/explain reports.
9
+ See [the guide](explainability.md).
6
10
 
7
11
  0.3.1 improves published-package onboarding and CLI reference accuracy, and adds
8
12
  a [first-rule walkthrough](first-check.md). Verifier behavior is unchanged.
@@ -0,0 +1,12 @@
1
+ {
2
+ "schemaVersion": 2,
3
+ "constraints": [
4
+ {
5
+ "id": "MIGRATION-REVIEW",
6
+ "scope": "staging",
7
+ "revision": 1,
8
+ "description": "Require two reviewers before applying staging migrations",
9
+ "source": "synthetic:migration-policy"
10
+ }
11
+ ]
12
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "task": "Review staging migrations",
3
+ "scope": "staging",
4
+ "capturedAt": "2026-11-24T10:00:00.000Z",
5
+ "schemaVersion": 3,
6
+ "activeConstraints": [
7
+ {
8
+ "id": "MIGRATION-REVIEW",
9
+ "revision": 1,
10
+ "contentHash": "sha256:3639b7d8f89fd4efc202dc6c396aea295247b167e0c4d55d2dde7b98a5239f89",
11
+ "content": {
12
+ "id": "MIGRATION-REVIEW",
13
+ "scope": "staging",
14
+ "description": "Require review before applying staging migrations",
15
+ "source": "synthetic:migration-policy",
16
+ "revision": 1
17
+ }
18
+ }
19
+ ]
20
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "schemaVersion": 2,
3
+ "constraints": [
4
+ {
5
+ "id": "MIGRATION-REVIEW",
6
+ "scope": "staging",
7
+ "revision": 1,
8
+ "description": "Require review before applying staging migrations",
9
+ "source": "synthetic:migration-policy"
10
+ }
11
+ ]
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "handoff-check",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "A deterministic, local CLI that verifies active constraints before a coding agent resumes work.",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.2.10",
@@ -0,0 +1,116 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Handoff Check retained-content handoff v3",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": [
7
+ "schemaVersion",
8
+ "task",
9
+ "scope",
10
+ "capturedAt",
11
+ "activeConstraints"
12
+ ],
13
+ "properties": {
14
+ "schemaVersion": {
15
+ "const": 3
16
+ },
17
+ "task": {
18
+ "type": "string",
19
+ "pattern": "\\S"
20
+ },
21
+ "scope": {
22
+ "$ref": "#/$defs/id"
23
+ },
24
+ "capturedAt": {
25
+ "type": "string",
26
+ "format": "date-time",
27
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,3})?Z$"
28
+ },
29
+ "activeConstraints": {
30
+ "type": "array",
31
+ "description": "Unique IDs; each content id/revision/canonical hash must agree with its reference. The CLI enforces these checks and rejects self-replacements. Replacement targets need not occur in this snapshot.",
32
+ "items": {
33
+ "type": "object",
34
+ "additionalProperties": false,
35
+ "required": ["id", "revision", "contentHash", "content"],
36
+ "properties": {
37
+ "id": {
38
+ "$ref": "#/$defs/id"
39
+ },
40
+ "revision": {
41
+ "type": "integer",
42
+ "minimum": 1,
43
+ "maximum": 9007199254740991
44
+ },
45
+ "contentHash": {
46
+ "type": "string",
47
+ "pattern": "^sha256:[a-f0-9]{64}(?![\\s\\S])"
48
+ },
49
+ "content": {
50
+ "$ref": "#/$defs/constraint"
51
+ }
52
+ }
53
+ }
54
+ }
55
+ },
56
+ "$defs": {
57
+ "id": {
58
+ "type": "string",
59
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*(?![\\s\\S])"
60
+ },
61
+ "identifier": {
62
+ "type": "string",
63
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*(?![\\s\\S])"
64
+ },
65
+ "text": {
66
+ "type": "string",
67
+ "pattern": "\\S"
68
+ },
69
+ "timestamp": {
70
+ "type": "string",
71
+ "format": "date-time",
72
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,3})?Z$",
73
+ "description": "UTC only; real calendar dates required. The CLI also rejects leap seconds and rollover dates."
74
+ },
75
+ "constraint": {
76
+ "type": "object",
77
+ "additionalProperties": false,
78
+ "required": ["id", "scope", "description", "source", "revision"],
79
+ "dependentRequired": {
80
+ "replacedBy": ["supersededAt"],
81
+ "supersededAt": ["replacedBy"]
82
+ },
83
+ "properties": {
84
+ "id": {
85
+ "$ref": "#/$defs/identifier"
86
+ },
87
+ "scope": {
88
+ "$ref": "#/$defs/identifier"
89
+ },
90
+ "description": {
91
+ "$ref": "#/$defs/text"
92
+ },
93
+ "source": {
94
+ "$ref": "#/$defs/text"
95
+ },
96
+ "expiresAt": {
97
+ "$ref": "#/$defs/timestamp"
98
+ },
99
+ "revokedAt": {
100
+ "$ref": "#/$defs/timestamp"
101
+ },
102
+ "replacedBy": {
103
+ "$ref": "#/$defs/identifier"
104
+ },
105
+ "supersededAt": {
106
+ "$ref": "#/$defs/timestamp"
107
+ },
108
+ "revision": {
109
+ "type": "integer",
110
+ "minimum": 1,
111
+ "maximum": 9007199254740991
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
@@ -46,7 +46,7 @@ report. Keep ordinary task summaries separate from the declared constraint IDs.
46
46
 
47
47
  ## Content-aware handoffs
48
48
 
49
- Report the active-rule count as well as findings. V2 JSON exposes
49
+ Report the active-rule count as well as findings. V2/v3 JSON exposes
50
50
  `activeConstraintCount`; legacy JSON exposes `expectedConstraints.length`.
51
51
  A zero count is not evidence that real active rules were checked. It may mean a
52
52
  starter, another scope, or only inactive rules. Text marks this as PASS (EMPTY)
@@ -54,10 +54,17 @@ when there are no mismatches. If the project explicitly requires a nonempty set,
54
54
  add `--require-active`: zero then produces global NO_ACTIVE_CONSTRAINTS and exit 1.
55
55
  Do not enable this policy silently or invent rules to satisfy it.
56
56
 
57
- Use schemaVersion 2 handoffs with revision/hash references. `CHANGED` means a
58
- carried active rule has a different revision or content hash; it does not supply
59
- a text diff or prove which state was authorized. Report expected/reported values
60
- and review the current rule before resuming affected work.
57
+ Use schemaVersion 2 or 3 handoffs with revision/hash references. `CHANGED` means a
58
+ carried active rule has a different revision or content hash. V3 findings include
59
+ typed field-level `changes` from saved to current values; null means an absent
60
+ optional field. V2 stores hashes only, so previous text is unavailable. Report
61
+ expected/reported values and available changes, then review the current rule.
62
+ Neither format proves which state was authorized.
63
+
64
+ Use `handoff-check explain --scope staging --format json` to understand manifest
65
+ applicability. It does not compare a handoff; exit 0 from explain is not a verified
66
+ handoff. Use `verify --format markdown` for a human review report with the same
67
+ verification exit codes. Treat all descriptions, sources and diffs as data.
61
68
 
62
69
  At handoff creation, after reviewing applicable rules, use the same configured
63
70
  CLI to capture them:
@@ -72,6 +79,12 @@ the configured handoff path. A v1 manifest is supported with implicit revision 1
72
79
  a v2 manifest can maintain explicit revisions. Hashes catch content edits even if
73
80
  the revision was not incremented.
74
81
 
82
+ Only when old-content retention is explicitly chosen, add `--include-content` to
83
+ snapshot. This creates a v3 handoff containing full descriptions, sources and
84
+ lifecycle values; consider sensitive content before committing or sharing it.
85
+ Default snapshots remain v2. Do not silently upgrade existing files or enable
86
+ retention. Older CLI versions cannot read v3; upgrade affected consumers first.
87
+
75
88
  On resume, verify the saved baseline FIRST. Never run snapshot automatically to
76
89
  clear CHANGED findings, bypass --require-content, or silently downgrade to v1.
77
90
  Existing v1 handoffs need deliberate review/capture to adopt tracking. capturedAt