handoff-check 0.3.1 → 0.5.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
@@ -2,12 +2,12 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { open as open2 } from "node:fs/promises";
5
- import { resolve as resolve3 } from "node:path";
5
+ import { resolve as resolve5 } from "node:path";
6
6
  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.5.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,
@@ -296,10 +345,470 @@ async function loadConfig(cwd, explicit) {
296
345
  return { config: parseConfig(parsed), directory: dirname(path) };
297
346
  }
298
347
 
348
+ // src/doctor.ts
349
+ import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
350
+ import { resolve as resolve3 } from "node:path";
351
+
352
+ // src/lifecycle.ts
353
+ import { realpath, stat } from "node:fs/promises";
354
+ import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
355
+
356
+ // src/verifier.ts
357
+ function compare(a, b) {
358
+ return a < b ? -1 : a > b ? 1 : 0;
359
+ }
360
+ function inactive(rule, scope, time) {
361
+ if (rule.scope !== "global" && rule.scope !== scope)
362
+ return "OUT_OF_SCOPE";
363
+ if (rule.revokedAt !== undefined && time >= Date.parse(rule.revokedAt))
364
+ return "REVOKED";
365
+ if (rule.supersededAt !== undefined && time >= Date.parse(rule.supersededAt))
366
+ return "SUPERSEDED";
367
+ if (rule.expiresAt !== undefined && time >= Date.parse(rule.expiresAt))
368
+ return "EXPIRED";
369
+ return;
370
+ }
371
+ function verify(manifest, handoff, scope, asOf, options = {}) {
372
+ identifier(scope, "scope");
373
+ if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
374
+ throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
375
+ const time = timestamp(asOf, "asOf");
376
+ const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
377
+ const expectedConstraints = manifest.constraints.filter((rule) => inactive(rule, scope, time) === undefined).map((rule) => rule.id).sort(compare);
378
+ const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
379
+ const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
380
+ const reported = new Set(reportedConstraints);
381
+ const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
382
+ const findings = [];
383
+ for (const id of expectedConstraints) {
384
+ if (!reported.has(id))
385
+ findings.push({
386
+ code: "MISSING",
387
+ id,
388
+ message: `Include active constraint: ${byId.get(id)?.description}`
389
+ });
390
+ }
391
+ for (const id of reportedConstraints) {
392
+ const rule = byId.get(id);
393
+ const code = rule ? inactive(rule, scope, time) : "UNKNOWN";
394
+ if (code) {
395
+ const detail = code === "SUPERSEDED" ? `; replaced by '${rule?.replacedBy}'` : "";
396
+ findings.push({
397
+ code,
398
+ id,
399
+ message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
400
+ });
401
+ } else if (rule && handoff.schemaVersion !== 1) {
402
+ const current = reference(rule);
403
+ const previous = refs.get(id);
404
+ if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
405
+ findings.push({
406
+ code: "CHANGED",
407
+ id,
408
+ message: `Review changed constraint: ${rule.description}; handoff revision ${previous.revision}, current revision ${current.revision}${current.contentHash !== previous.contentHash ? "; content hash differs" : ""}`,
409
+ expected: {
410
+ revision: current.revision,
411
+ contentHash: current.contentHash
412
+ },
413
+ reported: {
414
+ revision: previous.revision,
415
+ contentHash: previous.contentHash
416
+ },
417
+ ...retained.has(id) ? {
418
+ changes: fieldChanges(retained.get(id), rule)
419
+ } : {}
420
+ });
421
+ }
422
+ }
423
+ }
424
+ if (options.requireActive && expectedConstraints.length === 0) {
425
+ findings.push({
426
+ code: "NO_ACTIVE_CONSTRAINTS",
427
+ message: "No active constraints apply to the selected scope and time; --require-active requires at least one"
428
+ });
429
+ }
430
+ findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
431
+ return {
432
+ schemaVersion: handoff.schemaVersion,
433
+ ...handoff.schemaVersion !== 1 ? {
434
+ tracking: "content",
435
+ activeConstraintCount: expectedConstraints.length
436
+ } : {},
437
+ status: findings.length ? "mismatch" : "verified",
438
+ scope,
439
+ asOf: new Date(time).toISOString(),
440
+ expectedConstraints,
441
+ reportedConstraints,
442
+ findings
443
+ };
444
+ }
445
+ function snapshot(manifest, task, scope, asOf, options = {}) {
446
+ if (!task.trim())
447
+ throw new InputError("--task: expected a non-empty task");
448
+ const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
449
+ const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
450
+ const base = {
451
+ task,
452
+ scope,
453
+ capturedAt: result.asOf
454
+ };
455
+ const rules = result.expectedConstraints.map((id) => byId.get(id));
456
+ return options.includeContent ? {
457
+ ...base,
458
+ schemaVersion: 3,
459
+ activeConstraints: rules.map((rule) => ({
460
+ ...reference(rule),
461
+ content: retainedContent(rule)
462
+ }))
463
+ } : { ...base, schemaVersion: 2, activeConstraints: rules.map(reference) };
464
+ }
465
+ var fields = [
466
+ "id",
467
+ "scope",
468
+ "description",
469
+ "source",
470
+ "expiresAt",
471
+ "revokedAt",
472
+ "replacedBy",
473
+ "supersededAt",
474
+ "revision"
475
+ ];
476
+ function fieldChanges(previous, current) {
477
+ const before = retainedContent(previous);
478
+ const after = retainedContent(current);
479
+ return fields.filter((field) => before[field] !== after[field]).map((field) => ({
480
+ field,
481
+ before: before[field] ?? null,
482
+ after: after[field] ?? null
483
+ }));
484
+ }
485
+ function explain(manifest, scope, asOf) {
486
+ identifier(scope, "scope");
487
+ const time = timestamp(asOf, "asOf");
488
+ const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
489
+ const decision = inactive(rule, scope, time) ?? "ACTIVE";
490
+ let reason;
491
+ switch (decision) {
492
+ case "ACTIVE":
493
+ reason = `${rule.scope === "global" ? "Global rule" : "Selected scope matches"}; no lifecycle transition is effective`;
494
+ break;
495
+ case "OUT_OF_SCOPE":
496
+ reason = `Rule scope '${rule.scope}' does not match '${scope}' and is not global`;
497
+ break;
498
+ case "REVOKED":
499
+ reason = `Revoked at ${new Date(rule.revokedAt ?? "").toISOString()}`;
500
+ break;
501
+ case "SUPERSEDED":
502
+ reason = `Superseded at ${new Date(rule.supersededAt ?? "").toISOString()}; replaced by '${rule.replacedBy}'`;
503
+ break;
504
+ case "EXPIRED":
505
+ reason = `Expired at ${new Date(rule.expiresAt ?? "").toISOString()}`;
506
+ break;
507
+ }
508
+ return {
509
+ id: rule.id,
510
+ scope: rule.scope,
511
+ description: rule.description,
512
+ source: rule.source,
513
+ decision,
514
+ reason
515
+ };
516
+ });
517
+ return {
518
+ schemaVersion: 1,
519
+ scope,
520
+ asOf: new Date(time).toISOString(),
521
+ activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
522
+ rules
523
+ };
524
+ }
525
+
526
+ // src/lifecycle.ts
527
+ var lifecycleCommand = "node";
528
+ var projectPlaceholder = "$" + "{CLAUDE_PROJECT_DIR}";
529
+ var lifecycleArgs = [
530
+ `${projectPlaceholder}/node_modules/handoff-check/dist/cli.js`,
531
+ "hook",
532
+ "--host",
533
+ "claude",
534
+ "--config",
535
+ `${projectPlaceholder}/.handoff-check.json`
536
+ ];
537
+ var lifecycleMatcher = "^(startup|resume|clear|compact)$";
538
+ function hookConfig(host, requireActive = false) {
539
+ if (host !== "claude")
540
+ throw new InputError("Only the claude lifecycle adapter is supported; see docs/lifecycle.md for host capabilities");
541
+ return {
542
+ hooks: {
543
+ SessionStart: [
544
+ {
545
+ matcher: lifecycleMatcher,
546
+ hooks: [
547
+ {
548
+ type: "command",
549
+ command: lifecycleCommand,
550
+ args: [
551
+ ...lifecycleArgs,
552
+ ...requireActive ? ["--require-active"] : []
553
+ ],
554
+ timeout: 10
555
+ }
556
+ ]
557
+ }
558
+ ]
559
+ }
560
+ };
561
+ }
562
+ async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
563
+ return new Promise((resolveInput, reject) => {
564
+ let size = 0;
565
+ const chunks = [];
566
+ const finish = (error) => {
567
+ clearTimeout(timer);
568
+ input.removeListener("data", data);
569
+ input.removeListener("end", end);
570
+ input.removeListener("error", failure);
571
+ input.removeListener("close", closed);
572
+ if (error) {
573
+ input.pause();
574
+ reject(error);
575
+ }
576
+ };
577
+ const failure = () => finish(new InputError("Cannot read hook event"));
578
+ const closed = () => finish(new InputError("Hook event stream closed before completion"));
579
+ const data = (chunk) => {
580
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
581
+ size += buffer.length;
582
+ if (size > maxBytes)
583
+ finish(new InputError("Hook event exceeds 65536 bytes"));
584
+ else
585
+ chunks.push(buffer);
586
+ };
587
+ const end = () => {
588
+ finish();
589
+ try {
590
+ resolveInput(JSON.parse(Buffer.concat(chunks).toString("utf8")));
591
+ } catch {
592
+ reject(new InputError("Hook event must be valid JSON"));
593
+ }
594
+ };
595
+ const timer = setTimeout(() => finish(new InputError("Timed out waiting for hook event")), timeoutMs);
596
+ input.on("data", data);
597
+ input.once("end", end);
598
+ input.once("error", failure);
599
+ input.once("close", closed);
600
+ });
601
+ }
602
+ async function lifecycleHook(input, configPath, requireActive = false) {
603
+ if (!input || typeof input !== "object" || Array.isArray(input))
604
+ throw new InputError("Hook event must be an object");
605
+ const event = input;
606
+ if (event.hook_event_name !== "SessionStart" || typeof event.source !== "string" || !["startup", "resume", "clear", "compact"].includes(event.source))
607
+ throw new InputError("Expected supported Claude SessionStart source: startup, resume, clear or compact");
608
+ if (typeof event.cwd !== "string" || !isAbsolute(event.cwd) || event.cwd.includes("\x00"))
609
+ throw new InputError("Hook cwd must be an absolute directory path");
610
+ if (!isAbsolute(configPath))
611
+ throw new InputError("hook requires an absolute --config path");
612
+ const root = await realpath(dirname2(configPath));
613
+ const cwd = await realpath(event.cwd);
614
+ if (!(await stat(root)).isDirectory() || !(await stat(cwd)).isDirectory())
615
+ throw new InputError("Hook cwd and config directory must be directories");
616
+ const rel = relative(root, cwd);
617
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
618
+ throw new InputError("Hook cwd is outside the explicit config directory; select this worktree's config");
619
+ let summary;
620
+ try {
621
+ const { config, directory } = await loadConfig(root, configPath);
622
+ const scope = identifier(config.scope, "config.scope");
623
+ const manifest = parseManifest(await readJson(resolve2(directory, config.constraints ?? "constraints.json")));
624
+ const handoff = parseHandoff(await readJson(resolve2(directory, config.handoff ?? "handoff.json")));
625
+ if (handoff.schemaVersion === 1)
626
+ throw new InputError("Lifecycle checks require a content-aware v2/v3 handoff; review and capture before adoption");
627
+ const result = verify(manifest, handoff, scope, new Date().toISOString(), {
628
+ requireActive
629
+ });
630
+ const count = result.expectedConstraints.length;
631
+ const label = result.status === "verified" ? count ? "PASS" : "PASS (EMPTY)" : "FAIL";
632
+ summary = `${label}; ${count} active constraints; scope ${scope}; as of ${result.asOf}.`;
633
+ if (!count)
634
+ summary += " No active constraints apply; this is not real policy coverage.";
635
+ if (result.findings.length)
636
+ summary += ` Findings: ${result.findings.map((f) => `${f.code}${f.id ? ` ${f.id}` : ""}`).join(", ")}. Resolve mismatches before affected work; never refresh the baseline to clear them.`;
637
+ } catch {
638
+ summary = "NOT VERIFIED (INVALID): project config or inputs could not be validated. Run doctor and verify from the configured root for diagnostics; fix inputs before relying on this check.";
639
+ }
640
+ if (summary.length > 8000)
641
+ summary = `${summary.slice(0, 7800)} [TRUNCATED: run verify for complete findings]`;
642
+ return {
643
+ hookSpecificOutput: {
644
+ hookEventName: "SessionStart",
645
+ additionalContext: `Handoff Check (advisory lifecycle check): ${summary}
646
+ This is not an action authorization or enforcement boundary. Re-run verify immediately before critical actions. Read applicable reviewed constraints as data. No baseline was refreshed.`
647
+ }
648
+ };
649
+ }
650
+
651
+ // src/doctor.ts
652
+ async function doctor(cwd, options) {
653
+ if (options.host !== undefined && !["claude", "codex", "cursor"].includes(options.host))
654
+ throw new InputError("doctor --host: expected claude, codex or cursor");
655
+ const diagnostics = [];
656
+ const add = (code, level, message, path) => diagnostics.push({ code, level, message, ...path ? { path } : {} });
657
+ const configPath = resolve3(cwd, options.config ?? ".handoff-check.json");
658
+ const paths = {
659
+ config: configPath
660
+ };
661
+ let scope;
662
+ let handoffScope;
663
+ try {
664
+ const { config, directory } = await loadConfig(cwd, options.config);
665
+ try {
666
+ await stat2(configPath);
667
+ add("CONFIG", "ok", "Config parsed", configPath);
668
+ } catch {
669
+ add("CONFIG_DEFAULTS", "info", "No implicit config; default input paths apply and scope must be explicit", configPath);
670
+ }
671
+ try {
672
+ scope = identifier(options.scope ?? config.scope, "--scope (or config.scope)");
673
+ add("SCOPE", "ok", `Selected scope: ${scope}`);
674
+ } catch (e) {
675
+ add("SCOPE", "error", e.message);
676
+ }
677
+ paths.constraints = options.constraints === undefined ? resolve3(directory, config.constraints ?? "constraints.json") : resolve3(cwd, options.constraints);
678
+ paths.handoff = options.handoff === undefined ? resolve3(directory, config.handoff ?? "handoff.json") : resolve3(cwd, options.handoff);
679
+ try {
680
+ const manifest = parseManifest(await readJson(paths.constraints));
681
+ add("MANIFEST", "ok", `Supported manifest v${manifest.schemaVersion}; ${manifest.constraints.length} total rules (not evaluated active count)`, paths.constraints);
682
+ if (!manifest.constraints.length)
683
+ add("EMPTY_MANIFEST", "warning", "Zero declared rules; author reviewed constraints before relying on policy coverage");
684
+ } catch (e) {
685
+ add("MANIFEST", "error", e.message, paths.constraints);
686
+ }
687
+ try {
688
+ const handoff = parseHandoff(await readJson(paths.handoff));
689
+ if (handoff.schemaVersion !== 1)
690
+ handoffScope = handoff.scope;
691
+ add("HANDOFF", handoff.schemaVersion === 1 ? "warning" : "ok", `Supported handoff v${handoff.schemaVersion}${handoff.schemaVersion === 1 ? "; IDs only, lifecycle adapter requires v2/v3" : "; content-aware"}`, paths.handoff);
692
+ } catch (e) {
693
+ add("HANDOFF", "error", e.message, paths.handoff);
694
+ }
695
+ if (scope && handoffScope && scope !== handoffScope)
696
+ add("SCOPE_MISMATCH", "error", `Saved handoff scope '${handoffScope}' differs from selected '${scope}'`);
697
+ } catch (e) {
698
+ add("CONFIG", "error", e.message, configPath);
699
+ }
700
+ const packagedSkill = await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
701
+ for (const host of ["codex", "claude"]) {
702
+ const skillPath = resolve3(cwd, host === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
703
+ for (const [kind, path] of [
704
+ ["SKILL", skillPath],
705
+ [
706
+ "INSTRUCTIONS",
707
+ resolve3(cwd, host === "codex" ? "AGENTS.md" : "CLAUDE.md")
708
+ ]
709
+ ]) {
710
+ try {
711
+ const text = await readFile2(path, "utf8");
712
+ if (kind === "SKILL")
713
+ add(`${host}_${kind}`, text === packagedSkill ? "ok" : "warning", text === packagedSkill ? "Packaged skill matches" : "Skill differs from this package; review differences explicitly", path);
714
+ else {
715
+ const start = text.indexOf("<!-- handoff-check:begin -->");
716
+ const end = text.indexOf("<!-- handoff-check:end -->");
717
+ if (start < 0 && end < 0)
718
+ add(`${host}_${kind}`, options.host === host ? "warning" : "info", "No managed instruction block; custom prose is not assessed", path);
719
+ else if (start < 0 || end < start || text.split("<!-- handoff-check:begin -->").length !== 2 || text.split("<!-- handoff-check:end -->").length !== 2)
720
+ add(`${host}_${kind}`, "error", "Malformed managed instruction markers; review before init", path);
721
+ else {
722
+ const pins = [
723
+ ...text.slice(start, end).matchAll(/handoff-check@([\w.+-]+)/g)
724
+ ].map((m) => m[1]);
725
+ add(`${host}_${kind}`, pins.length > 0 && pins.every((pin) => pin === package_default.version) ? "ok" : "warning", `Managed package pins: ${pins.join(", ") || "none"}; current ${package_default.version}`, path);
726
+ }
727
+ }
728
+ } catch (e) {
729
+ add(`${host}_${kind}`, e.code === "ENOENT" ? options.host === host ? "warning" : "info" : "error", e.code === "ENOENT" ? "Integration not installed; init can create it after preview" : "Cannot read integration", path);
730
+ }
731
+ }
732
+ }
733
+ const ciPath = resolve3(cwd, ".github/workflows/handoff-check.yml");
734
+ try {
735
+ const ci = await readFile2(ciPath, "utf8");
736
+ const pins = [...ci.matchAll(/handoff-check@([\w.+-]+)/g)].map((m) => m[1]);
737
+ add("CI_PIN", pins.length && pins.every((pin) => pin === package_default.version) ? "ok" : "warning", `Textual CI pins: ${pins.join(", ") || "none"}; workflow execution is not assessed`, ciPath);
738
+ } catch (e) {
739
+ add("CI", e.code === "ENOENT" ? "info" : "error", "CI not inspected; no workflow present or readable", ciPath);
740
+ }
741
+ const settingsPath = resolve3(cwd, ".claude/settings.json");
742
+ let configured = false;
743
+ try {
744
+ const settings = await readJson(settingsPath);
745
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
746
+ throw new Error("Expected settings object");
747
+ if (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== "object" || Array.isArray(settings.hooks)))
748
+ throw new Error("Expected hooks object");
749
+ if (settings.hooks?.SessionStart !== undefined && !Array.isArray(settings.hooks.SessionStart))
750
+ throw new Error("Expected SessionStart array");
751
+ if (settings.disableAllHooks === true)
752
+ add("CLAUDE_HOOK_DISABLED", "warning", "Project settings disable hooks", settingsPath);
753
+ const groups = settings.hooks?.SessionStart;
754
+ if (Array.isArray(groups))
755
+ for (const group of groups) {
756
+ if (group && typeof group === "object" && Array.isArray(group.hooks))
757
+ for (const hook of group.hooks) {
758
+ if (hook?.command === lifecycleCommand && (JSON.stringify(hook.args) === JSON.stringify(lifecycleArgs) || JSON.stringify(hook.args) === JSON.stringify([...lifecycleArgs, "--require-active"]))) {
759
+ configured = true;
760
+ add("CLAUDE_HOOK", group.matcher === lifecycleMatcher && hook.type === "command" && hook.timeout === 10 && hook.async !== true ? "ok" : "warning", "Recognized adapter command; review matcher/type/timeout and host /hooks for actual activation", settingsPath);
761
+ }
762
+ }
763
+ }
764
+ if (!configured)
765
+ add("CLAUDE_HOOK", options.host === "claude" ? "warning" : "info", "No recognized lifecycle adapter; use hook-config --host claude and merge explicitly", settingsPath);
766
+ } catch {
767
+ try {
768
+ await stat2(settingsPath);
769
+ add("CLAUDE_SETTINGS", "error", "Settings unreadable or invalid JSON/shape; no settings were changed", settingsPath);
770
+ } catch {
771
+ add("CLAUDE_HOOK", options.host === "claude" ? "warning" : "info", "No project lifecycle settings inspected; use hook-config --host claude", settingsPath);
772
+ }
773
+ }
774
+ if (configured) {
775
+ const packagePath = resolve3(cwd, "node_modules/handoff-check/package.json");
776
+ try {
777
+ const pkg = await readJson(packagePath);
778
+ await stat2(resolve3(cwd, "node_modules/handoff-check/dist/cli.js"));
779
+ add("LOCAL_ADAPTER", pkg.name === "handoff-check" && pkg.version === package_default.version ? "ok" : "warning", `Local adapter package version ${pkg.version ?? "unknown"}; current ${package_default.version}`, packagePath);
780
+ } catch {
781
+ add("LOCAL_ADAPTER", "error", `Install project-local handoff-check@${package_default.version} before enabling this hook`, packagePath);
782
+ }
783
+ }
784
+ if (options.host === "codex" || options.host === "cursor")
785
+ add("HOST_ADAPTER", "warning", `${options.host} lifecycle adapter is not shipped in this version; use explicit CLI/CI and see docs/lifecycle.md`);
786
+ for (const path of [
787
+ paths.config,
788
+ paths.constraints,
789
+ paths.handoff,
790
+ settingsPath
791
+ ].filter((p) => p !== undefined)) {
792
+ try {
793
+ if ((await lstat(path)).isSymbolicLink())
794
+ add("SYMLINK", "info", "Path is a symlink; input reads follow its target, as verify does", path);
795
+ } catch {}
796
+ }
797
+ return {
798
+ schemaVersion: 1,
799
+ packageVersion: package_default.version,
800
+ status: diagnostics.some((d) => d.level === "warning" || d.level === "error") ? "attention" : "healthy",
801
+ paths,
802
+ ...scope ? { scope } : {},
803
+ diagnostics,
804
+ notice: "Read-only local diagnostics, not handoff verification or proof that host hooks/skills executed. User/global/managed host settings are not inspected."
805
+ };
806
+ }
807
+
299
808
  // src/initialize.ts
300
809
  import { constants } from "node:fs";
301
- import { lstat, mkdir, open, readFile as readFile2 } from "node:fs/promises";
302
- import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
810
+ import { lstat as lstat2, mkdir, open, readFile as readFile3 } from "node:fs/promises";
811
+ import { dirname as dirname3, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
303
812
  var begin = "<!-- handoff-check:begin -->";
304
813
  var end = "<!-- handoff-check:end -->";
305
814
  var instruction = `${begin}
@@ -321,15 +830,15 @@ never refresh the baseline before verifying it when resuming work.
321
830
  ${end}
322
831
  `;
323
832
  async function inspect(root, path) {
324
- const rel = relative(root, path);
325
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
833
+ const rel = relative2(root, path);
834
+ if (!rel || rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel))
326
835
  throw new InputError(`Initialization target must be inside the project: '${path}'`);
327
836
  let current = root;
328
- const parts = rel.split(sep);
837
+ const parts = rel.split(sep2);
329
838
  for (const [index, part] of parts.entries()) {
330
- current = resolve2(current, part);
839
+ current = resolve4(current, part);
331
840
  try {
332
- const info = await lstat(current);
841
+ const info = await lstat2(current);
333
842
  if (info.isSymbolicLink())
334
843
  throw new InputError(`Refusing symlink initialization target: '${current}'`);
335
844
  if (index < parts.length - 1 && !info.isDirectory())
@@ -342,13 +851,13 @@ async function inspect(root, path) {
342
851
  throw error;
343
852
  }
344
853
  }
345
- return readFile2(path, "utf8");
854
+ return readFile3(path, "utf8");
346
855
  }
347
856
  async function initialize(root, options) {
348
857
  if (!["codex", "claude", "both", "none"].includes(options.agent))
349
858
  throw new InputError("--agent: expected codex, claude, both, or none");
350
859
  const plan = [];
351
- const configPath = resolve2(root, ".handoff-check.json");
860
+ const configPath = resolve4(root, ".handoff-check.json");
352
861
  const previous = await inspect(root, configPath);
353
862
  const config = previous === undefined ? { schemaVersion: 1 } : parseConfig(await readJson(configPath));
354
863
  const scope = identifier(options.scope ?? config.scope, "init --scope (or config.scope)");
@@ -388,7 +897,7 @@ async function initialize(root, options) {
388
897
  parseHandoff
389
898
  ]
390
899
  ]) {
391
- const path = resolve2(root, config[key] ?? fallback);
900
+ const path = resolve4(root, config[key] ?? fallback);
392
901
  const old = await inspect(root, path);
393
902
  if (old !== undefined)
394
903
  validate(await readJson(path));
@@ -398,10 +907,10 @@ async function initialize(root, options) {
398
907
  content: old ?? json(starter)
399
908
  });
400
909
  }
401
- const skill = options.agent === "none" ? "" : await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
910
+ const skill = options.agent === "none" ? "" : await readFile3(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
402
911
  const selected = options.agent === "both" ? ["codex", "claude"] : options.agent === "none" ? [] : [options.agent];
403
912
  for (const agent of selected) {
404
- const skillPath = resolve2(root, agent === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
913
+ const skillPath = resolve4(root, agent === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
405
914
  const oldSkill = await inspect(root, skillPath);
406
915
  if (oldSkill !== undefined && oldSkill !== skill)
407
916
  throw new InputError(`Existing skill differs; review it before replacing: '${skillPath}'`);
@@ -410,7 +919,7 @@ async function initialize(root, options) {
410
919
  action: oldSkill === undefined ? "create" : "preserve",
411
920
  content: skill
412
921
  });
413
- const path = resolve2(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
922
+ const path = resolve4(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
414
923
  const before = await inspect(root, path);
415
924
  if (before === undefined)
416
925
  plan.push({ path, action: "create", content: instruction });
@@ -435,7 +944,7 @@ async function initialize(root, options) {
435
944
  }
436
945
  }
437
946
  if (options.ci) {
438
- const path = resolve2(root, ".github/workflows/handoff-check.yml");
947
+ const path = resolve4(root, ".github/workflows/handoff-check.yml");
439
948
  const content = `name: Handoff constraints
440
949
  on: [push, pull_request]
441
950
  permissions:
@@ -464,7 +973,7 @@ jobs:
464
973
  throw new InputError("Initialization paths overlap; use separate config, manifest, handoff and integration files");
465
974
  const written = [];
466
975
  for (const file of plan) {
467
- if (plan.some((other) => other !== file && pathKey(other.path).startsWith(`${pathKey(file.path)}${sep}`)))
976
+ if (plan.some((other) => other !== file && pathKey(other.path).startsWith(`${pathKey(file.path)}${sep2}`)))
468
977
  throw new InputError("Initialization paths overlap as file and directory; choose separate paths");
469
978
  }
470
979
  if (!options.dryRun) {
@@ -475,7 +984,7 @@ jobs:
475
984
  const current = await inspect(root, file.path);
476
985
  if (file.action === "create" && current !== undefined || file.action === "append" && current !== file.before)
477
986
  throw new InputError("Target changed after planning");
478
- await mkdir(dirname2(file.path), { recursive: true });
987
+ await mkdir(dirname3(file.path), { recursive: true });
479
988
  await inspect(root, file.path);
480
989
  const flags = file.action === "create" ? constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL : constants.O_WRONLY | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0);
481
990
  const handle = await open(file.path, flags, 420);
@@ -484,10 +993,10 @@ jobs:
484
993
  } finally {
485
994
  await handle.close();
486
995
  }
487
- written.push(relative(root, file.path));
996
+ written.push(relative2(root, file.path));
488
997
  } catch (error) {
489
998
  const message = error instanceof Error ? error.message : "write failed";
490
- throw new InputError(`Initialization stopped at '${relative(root, file.path)}': ${message}. Written files: ${written.join(", ") || "none"}. Inspect these paths before retrying; filesystem failures are not transactional.`);
999
+ throw new InputError(`Initialization stopped at '${relative2(root, file.path)}': ${message}. Written files: ${written.join(", ") || "none"}. Inspect these paths before retrying; filesystem failures are not transactional.`);
491
1000
  }
492
1001
  }
493
1002
  }
@@ -496,7 +1005,7 @@ jobs:
496
1005
  status: options.dryRun ? "preview" : "initialized",
497
1006
  scope,
498
1007
  files: plan.map((file) => ({
499
- path: relative(root, file.path),
1008
+ path: relative2(root, file.path),
500
1009
  action: file.action,
501
1010
  ...file.action === "preserve" ? {} : { content: file.content }
502
1011
  })),
@@ -504,124 +1013,77 @@ jobs:
504
1013
  };
505
1014
  }
506
1015
 
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
- };
526
- }
527
-
528
- // src/verifier.ts
529
- function compare(a, b) {
530
- return a < b ? -1 : a > b ? 1 : 0;
1016
+ // src/render.ts
1017
+ function terminalText(value) {
1018
+ return Array.from(value, (character) => {
1019
+ const code = character.codePointAt(0) ?? 0;
1020
+ return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
1021
+ }).join("");
531
1022
  }
532
- function inactive(rule, scope, time) {
533
- if (rule.scope !== "global" && rule.scope !== scope)
534
- return "OUT_OF_SCOPE";
535
- if (rule.revokedAt !== undefined && time >= Date.parse(rule.revokedAt))
536
- return "REVOKED";
537
- if (rule.supersededAt !== undefined && time >= Date.parse(rule.supersededAt))
538
- return "SUPERSEDED";
539
- if (rule.expiresAt !== undefined && time >= Date.parse(rule.expiresAt))
540
- return "EXPIRED";
541
- return;
1023
+ function markdownText(value) {
1024
+ return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
542
1025
  }
543
- function verify(manifest, handoff, scope, asOf, options = {}) {
544
- identifier(scope, "scope");
545
- if (handoff.schemaVersion === 2 && handoff.scope !== scope)
546
- throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
547
- const time = timestamp(asOf, "asOf");
548
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
549
- 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]) : []);
551
- const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
552
- const reported = new Set(reportedConstraints);
553
- const findings = [];
554
- for (const id of expectedConstraints) {
555
- if (!reported.has(id))
556
- findings.push({
557
- code: "MISSING",
558
- id,
559
- message: `Include active constraint: ${byId.get(id)?.description}`
560
- });
561
- }
562
- for (const id of reportedConstraints) {
563
- const rule = byId.get(id);
564
- const code = rule ? inactive(rule, scope, time) : "UNKNOWN";
565
- if (code) {
566
- const detail = code === "SUPERSEDED" ? `; replaced by '${rule?.replacedBy}'` : "";
567
- findings.push({
568
- code,
569
- id,
570
- message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
571
- });
572
- } else if (rule && handoff.schemaVersion === 2) {
573
- const current = reference(rule);
574
- const previous = refs.get(id);
575
- if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
576
- findings.push({
577
- code: "CHANGED",
578
- id,
579
- message: `Review changed constraint: ${rule.description}; handoff revision ${previous.revision}, current revision ${current.revision}${current.contentHash !== previous.contentHash ? "; content hash differs" : ""}`,
580
- expected: {
581
- revision: current.revision,
582
- contentHash: current.contentHash
583
- },
584
- reported: {
585
- revision: previous.revision,
586
- contentHash: previous.contentHash
587
- }
588
- });
589
- }
1026
+ function verificationMarkdown(result, handoff, requireActive, requireContent) {
1027
+ const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
1028
+ const lines = [
1029
+ "# Handoff Check verification",
1030
+ "",
1031
+ `- Result: ${label}`,
1032
+ `- Scope: ${markdownText(result.scope)}`,
1033
+ `- Evaluated at: ${markdownText(result.asOf)}`,
1034
+ `- Active constraints checked: ${result.expectedConstraints.length}`,
1035
+ `- 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"}`,
1036
+ `- Require content-aware handoff: ${requireContent}`,
1037
+ `- Require active constraints: ${requireActive}`,
1038
+ ""
1039
+ ];
1040
+ if (!result.expectedConstraints.length)
1041
+ lines.push("No active constraints apply to this scope and time.", "");
1042
+ lines.push("## Findings", "");
1043
+ if (!result.findings.length)
1044
+ lines.push("No findings.", "");
1045
+ for (const finding of result.findings) {
1046
+ lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
1047
+ if (finding.code === "CHANGED") {
1048
+ if (finding.changes) {
1049
+ lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
1050
+ for (const change of finding.changes)
1051
+ lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
1052
+ lines.push("", "Null means an absent optional field.", "");
1053
+ } else
1054
+ lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
590
1055
  }
591
1056
  }
592
- if (options.requireActive && expectedConstraints.length === 0) {
593
- findings.push({
594
- code: "NO_ACTIVE_CONSTRAINTS",
595
- message: "No active constraints apply to the selected scope and time; --require-active requires at least one"
596
- });
597
- }
598
- findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
599
- return {
600
- schemaVersion: handoff.schemaVersion,
601
- ...handoff.schemaVersion === 2 ? {
602
- tracking: "content",
603
- activeConstraintCount: expectedConstraints.length
604
- } : {},
605
- status: findings.length ? "mismatch" : "verified",
606
- scope,
607
- asOf: new Date(time).toISOString(),
608
- expectedConstraints,
609
- reportedConstraints,
610
- findings
611
- };
1057
+ lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
1058
+ return `${lines.join(`
1059
+ `)}
1060
+ `;
612
1061
  }
613
- function snapshot(manifest, task, scope, asOf) {
614
- if (!task.trim())
615
- throw new InputError("--task: expected a non-empty task");
616
- const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
617
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
618
- return {
619
- schemaVersion: 2,
620
- task,
621
- scope,
622
- capturedAt: result.asOf,
623
- activeConstraints: result.expectedConstraints.map((id) => reference(byId.get(id)))
624
- };
1062
+ function explanationText(result, markdown) {
1063
+ if (markdown) {
1064
+ return [
1065
+ "# Handoff Check explanation",
1066
+ "",
1067
+ `- Scope: ${markdownText(result.scope)}`,
1068
+ `- Evaluated at: ${markdownText(result.asOf)}`,
1069
+ `- Active constraints: ${result.activeConstraintCount}`,
1070
+ "",
1071
+ "| ID | Rule scope | Decision | Reason | Description | Source |",
1072
+ "| --- | --- | --- | --- | --- | --- |",
1073
+ ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
1074
+ "",
1075
+ "Explains manifest applicability only; no handoff was compared.",
1076
+ ""
1077
+ ].join(`
1078
+ `);
1079
+ }
1080
+ return [
1081
+ ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
1082
+ `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}`,
1083
+ "No handoff was compared.",
1084
+ ""
1085
+ ].join(`
1086
+ `);
625
1087
  }
626
1088
 
627
1089
  // src/cli.ts
@@ -630,6 +1092,10 @@ var help = `Handoff Check
630
1092
  Usage: handoff-check verify --scope <scope> [options]
631
1093
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
632
1094
  handoff-check snapshot --task <task> [--output <new-file>] [options]
1095
+ handoff-check explain --scope <scope> [options]
1096
+ handoff-check doctor [--host claude|codex|cursor] [--format text|json]
1097
+ handoff-check hook-config --host claude [--require-active]
1098
+ handoff-check hook --host claude --config <absolute-path> [--require-active]
633
1099
 
634
1100
  Options:
635
1101
  --constraints <path> Manifest file (default: constraints.json)
@@ -637,28 +1103,23 @@ Options:
637
1103
  --scope <scope> Selected scope, including global constraints
638
1104
  --config <path> Project config (default: cwd/.handoff-check.json)
639
1105
  --as-of <UTC time> Fixed evaluation time (default: current time)
640
- --require-content verify: require a v2 content-aware handoff
641
- --require-active verify: fail if no constraints apply to scope/time
1106
+ --require-content verify: require a v2/v3 content-aware handoff
1107
+ --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
642
1108
  --task <task> snapshot: task description (required)
643
1109
  --output <path> snapshot: create a new baseline file, never overwrite
644
- --format text|json Output format (default: text)
1110
+ --include-content snapshot: retain old rule text in a v3 handoff (opt-in)
1111
+ --format text|json|markdown Markdown is verify/explain-only (default: text)
645
1112
  --agent <agent> init: codex, claude, both (default), or none
1113
+ --host <host> doctor: integration target; hook/hook-config: claude
646
1114
  --dry-run init: preview files and instruction changes without writes
647
1115
  --ci init: also create a pinned GitHub Actions check
648
1116
  --version Show package version
649
1117
  --help Show this help
650
1118
 
651
- Exit codes: 0 verified, 1 rule/policy mismatch, 2 invalid input
1119
+ Exit codes: verify 0 verified / 1 mismatch; doctor 0 healthy / 1 attention.
1120
+ Hook 0 means advisory response delivered (may report FAIL/INVALID), not verified.
1121
+ Invalid invocation/input returns 2; explain/init/snapshot/hook-config succeed with 0.
652
1122
  `;
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
1123
  async function main() {
663
1124
  let format = "text";
664
1125
  try {
@@ -680,13 +1141,15 @@ async function main() {
680
1141
  ci: { type: "boolean" },
681
1142
  "require-content": { type: "boolean" },
682
1143
  "require-active": { type: "boolean" },
1144
+ "include-content": { type: "boolean" },
1145
+ host: { type: "string" },
683
1146
  task: { type: "string" },
684
1147
  output: { type: "string" }
685
1148
  }
686
1149
  });
687
1150
  format = values.format;
688
- if (format !== "text" && format !== "json")
689
- throw new InputError("--format: expected text or json");
1151
+ if (!["text", "json", "markdown"].includes(format))
1152
+ throw new InputError("--format: expected text, json or markdown");
690
1153
  if (values.help) {
691
1154
  process.stdout.write(help);
692
1155
  return 0;
@@ -696,9 +1159,87 @@ async function main() {
696
1159
  `);
697
1160
  return 0;
698
1161
  }
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)");
1162
+ if (positionals.length !== 1 || ![
1163
+ "verify",
1164
+ "init",
1165
+ "snapshot",
1166
+ "explain",
1167
+ "doctor",
1168
+ "hook",
1169
+ "hook-config"
1170
+ ].includes(positionals[0] ?? ""))
1171
+ throw new InputError("Expected command: verify, snapshot, explain, init, doctor, hook or hook-config (use --help for usage)");
701
1172
  const cwd = process.cwd();
1173
+ const command = positionals[0];
1174
+ if (["doctor", "hook", "hook-config"].includes(command ?? "")) {
1175
+ const allowed = command === "doctor" ? ["host", "config", "scope", "constraints", "handoff", "format"] : command === "hook" ? ["host", "config", "require-active"] : ["host", "require-active"];
1176
+ for (const key of Object.keys(values)) {
1177
+ if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1178
+ continue;
1179
+ if (!allowed.includes(key))
1180
+ throw new InputError(`--${key} is not supported by ${command}`);
1181
+ }
1182
+ if (command === "doctor") {
1183
+ if (values.scope !== undefined)
1184
+ identifier(values.scope, "--scope");
1185
+ for (const key of ["config", "constraints", "handoff"])
1186
+ if (values[key] !== undefined && !values[key].trim())
1187
+ throw new InputError(`--${key}: expected a non-empty path`);
1188
+ if (format === "markdown")
1189
+ throw new InputError("doctor supports text or json");
1190
+ const result2 = await doctor(cwd, values);
1191
+ if (format === "json")
1192
+ process.stdout.write(`${JSON.stringify(result2, null, 2)}
1193
+ `);
1194
+ else {
1195
+ for (const d of result2.diagnostics)
1196
+ process.stdout.write(`${d.level.toUpperCase()} ${d.code} ${terminalText(d.message)}${d.path ? ` | ${terminalText(d.path)}` : ""}
1197
+ `);
1198
+ process.stdout.write(`DOCTOR ${result2.status.toUpperCase()}
1199
+ ${result2.notice}
1200
+ `);
1201
+ }
1202
+ return result2.status === "healthy" ? 0 : 1;
1203
+ }
1204
+ if (values.host !== "claude")
1205
+ throw new InputError("hook and hook-config require --host claude; other host adapters are not shipped");
1206
+ if (command === "hook-config") {
1207
+ process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false), null, 2)}
1208
+ `);
1209
+ return 0;
1210
+ }
1211
+ if (!values.config)
1212
+ throw new InputError("hook requires --config <absolute-path>");
1213
+ const watchdog = setTimeout(() => {
1214
+ process.stderr.write(`INVALID Hook check exceeded 5 seconds; not verified
1215
+ `);
1216
+ process.exit(2);
1217
+ }, 5000);
1218
+ try {
1219
+ const event = await readHookInput(process.stdin);
1220
+ const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false);
1221
+ process.stdout.write(`${JSON.stringify(result2)}
1222
+ `);
1223
+ return 0;
1224
+ } finally {
1225
+ clearTimeout(watchdog);
1226
+ process.stdin.destroy();
1227
+ }
1228
+ }
1229
+ if (values.host !== undefined)
1230
+ throw new InputError("--host is only supported by doctor, hook and hook-config");
1231
+ if (format === "markdown" && command !== "verify" && command !== "explain")
1232
+ throw new InputError("--format markdown is only supported by verify and explain");
1233
+ if (values["include-content"] !== undefined && command !== "snapshot")
1234
+ throw new InputError("--include-content is only supported by snapshot");
1235
+ if (command === "explain" && [
1236
+ values.handoff,
1237
+ values.task,
1238
+ values.output,
1239
+ values["require-content"],
1240
+ values["require-active"]
1241
+ ].some((value) => value !== undefined))
1242
+ throw new InputError("--handoff, --task, --output and --require-* are not supported by explain");
702
1243
  if (positionals[0] === "init") {
703
1244
  for (const key of [
704
1245
  "constraints",
@@ -750,13 +1291,21 @@ ${result2.notice}
750
1291
  for (const key of ["constraints", "handoff", "config"])
751
1292
  if (values[key] !== undefined && !values[key].trim())
752
1293
  throw new InputError(`--${key}: expected a non-empty path`);
753
- const manifest = parseManifest(await readJson(values.constraints !== undefined ? resolve3(cwd, values.constraints) : resolve3(directory, config.constraints ?? "constraints.json")));
1294
+ const manifest = parseManifest(await readJson(values.constraints !== undefined ? resolve5(cwd, values.constraints) : resolve5(directory, config.constraints ?? "constraints.json")));
1295
+ if (command === "explain") {
1296
+ const result2 = explain(manifest, scope, asOf);
1297
+ process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
1298
+ ` : explanationText(result2, format === "markdown"));
1299
+ return 0;
1300
+ }
754
1301
  if (positionals[0] === "snapshot") {
755
1302
  if (values.handoff !== undefined || values["require-content"] !== undefined || values["require-active"] !== undefined)
756
1303
  throw new InputError("--handoff, --require-content and --require-active are only supported by verify");
757
1304
  if (values.task === undefined)
758
1305
  throw new InputError("snapshot requires --task");
759
- const captured = snapshot(manifest, values.task, scope, asOf);
1306
+ const captured = snapshot(manifest, values.task, scope, asOf, {
1307
+ includeContent: values["include-content"] ?? false
1308
+ });
760
1309
  const content = `${JSON.stringify(captured, null, 2)}
761
1310
  `;
762
1311
  if (values.output === undefined)
@@ -764,7 +1313,7 @@ ${result2.notice}
764
1313
  else {
765
1314
  if (!values.output.trim())
766
1315
  throw new InputError("--output: expected a non-empty path");
767
- const path = resolve3(cwd, values.output);
1316
+ const path = resolve5(cwd, values.output);
768
1317
  let handle;
769
1318
  try {
770
1319
  handle = await open2(path, "wx", 420);
@@ -790,19 +1339,30 @@ ${result2.notice}
790
1339
  }
791
1340
  if (values.task !== undefined || values.output !== undefined)
792
1341
  throw new InputError("--task and --output are only supported by snapshot");
793
- 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");
1342
+ const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve5(cwd, values.handoff) : resolve5(directory, config.handoff ?? "handoff.json")));
1343
+ if (values["require-content"] && handoff.schemaVersion === 1)
1344
+ throw new InputError("Content tracking requires a schemaVersion 2 or 3 handoff; review current rules and capture a snapshot before resuming");
796
1345
  const result = verify(manifest, handoff, scope, asOf, {
797
1346
  requireActive: values["require-active"] ?? false
798
1347
  });
799
1348
  if (format === "json") {
800
1349
  process.stdout.write(`${JSON.stringify(result, null, 2)}
801
1350
  `);
1351
+ } else if (format === "markdown") {
1352
+ process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false));
802
1353
  } else {
803
1354
  for (const finding of result.findings) {
804
1355
  process.stdout.write(`${finding.code.padEnd(12)} ${finding.id === undefined ? "" : `${finding.id} `}${terminalText(finding.message)}
805
1356
  `);
1357
+ if (finding.code === "CHANGED") {
1358
+ if (finding.changes)
1359
+ for (const change of finding.changes)
1360
+ process.stdout.write(` ${change.field}: ${terminalText(JSON.stringify(change.before))} -> ${terminalText(JSON.stringify(change.after))}
1361
+ `);
1362
+ else
1363
+ process.stdout.write(` Previous content unavailable: baseline stores hashes only
1364
+ `);
1365
+ }
806
1366
  }
807
1367
  const count = result.expectedConstraints.length;
808
1368
  const label = result.status === "verified" ? count === 0 ? "PASS (EMPTY)" : "PASS" : "FAIL";