handoff-check 0.3.0 → 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/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.0",
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";
@@ -6,11 +6,11 @@ infers rules from a summary.
6
6
 
7
7
  ## Registry installation
8
8
 
9
- After the npm release is published, from the consuming repository root:
9
+ From the consuming repository root:
10
10
 
11
11
  ```sh
12
- npx handoff-check@0.3.0 init --scope staging --agent both --dry-run
13
- npx handoff-check@0.3.0 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:
@@ -23,9 +23,10 @@ Choose `codex`, `claude`, `both` (default), or `none`. Generated integrations:
23
23
  Review and commit generated files. `--dry-run` previews all changes. Existing valid
24
24
  inputs and surrounding instruction text are preserved; conflicts fail before
25
25
  writes. Starters have zero rules: author reviewed constraints and populate handoff
26
- IDs before relying on verification.
26
+ references through a reviewed snapshot before relying on verification. Follow
27
+ [your first real check](first-check.md) for a complete example.
27
28
 
28
- ## Local package before publication
29
+ ## Local contributor package
29
30
 
30
31
  From this source checkout, with Bun installed:
31
32
 
@@ -38,12 +39,12 @@ npm pack
38
39
  From a separate consuming project, substitute the actual absolute tarball path:
39
40
 
40
41
  ```sh
41
- npx --offline --yes --package=/absolute/path/handoff-check-0.3.0.tgz handoff-check init --scope staging --agent both
42
- npx --offline --yes --package=/absolute/path/handoff-check-0.3.0.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
43
44
  ```
44
45
 
45
46
  Bun is not required for these consumer commands. Generated agent commands use the
46
- pinned registry package. Before publication, use the same tarball invocation or
47
+ pinned registry package. To test an unpublished contributor build, use the same tarball invocation or
47
48
  `node /absolute/path/Handoff-Check/dist/cli.js` in your local agent test prompt.
48
49
  A local tarball does not make its npm name available in the public registry.
49
50
 
@@ -63,7 +64,14 @@ At handoff creation, review current rules and run the configured CLI's
63
64
  `snapshot --task "Resume the task" --output handoff.next.json`. Review that file
64
65
  before explicitly promoting it to the configured handoff. On resume, verify the
65
66
  saved baseline first; do not regenerate it to hide a CHANGED finding. Snapshot
66
- 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).
67
75
 
68
76
  Existing v1 inputs are preserved. Review/capture a v2 handoff and explicitly update
69
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.