handoff-check 0.4.0 → 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.4.0",
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",
@@ -345,10 +345,470 @@ async function loadConfig(cwd, explicit) {
345
345
  return { config: parseConfig(parsed), directory: dirname(path) };
346
346
  }
347
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
+
348
808
  // src/initialize.ts
349
809
  import { constants } from "node:fs";
350
- import { lstat, mkdir, open, readFile as readFile2 } from "node:fs/promises";
351
- 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";
352
812
  var begin = "<!-- handoff-check:begin -->";
353
813
  var end = "<!-- handoff-check:end -->";
354
814
  var instruction = `${begin}
@@ -370,15 +830,15 @@ never refresh the baseline before verifying it when resuming work.
370
830
  ${end}
371
831
  `;
372
832
  async function inspect(root, path) {
373
- const rel = relative(root, path);
374
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
833
+ const rel = relative2(root, path);
834
+ if (!rel || rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel))
375
835
  throw new InputError(`Initialization target must be inside the project: '${path}'`);
376
836
  let current = root;
377
- const parts = rel.split(sep);
837
+ const parts = rel.split(sep2);
378
838
  for (const [index, part] of parts.entries()) {
379
- current = resolve2(current, part);
839
+ current = resolve4(current, part);
380
840
  try {
381
- const info = await lstat(current);
841
+ const info = await lstat2(current);
382
842
  if (info.isSymbolicLink())
383
843
  throw new InputError(`Refusing symlink initialization target: '${current}'`);
384
844
  if (index < parts.length - 1 && !info.isDirectory())
@@ -391,13 +851,13 @@ async function inspect(root, path) {
391
851
  throw error;
392
852
  }
393
853
  }
394
- return readFile2(path, "utf8");
854
+ return readFile3(path, "utf8");
395
855
  }
396
856
  async function initialize(root, options) {
397
857
  if (!["codex", "claude", "both", "none"].includes(options.agent))
398
858
  throw new InputError("--agent: expected codex, claude, both, or none");
399
859
  const plan = [];
400
- const configPath = resolve2(root, ".handoff-check.json");
860
+ const configPath = resolve4(root, ".handoff-check.json");
401
861
  const previous = await inspect(root, configPath);
402
862
  const config = previous === undefined ? { schemaVersion: 1 } : parseConfig(await readJson(configPath));
403
863
  const scope = identifier(options.scope ?? config.scope, "init --scope (or config.scope)");
@@ -437,7 +897,7 @@ async function initialize(root, options) {
437
897
  parseHandoff
438
898
  ]
439
899
  ]) {
440
- const path = resolve2(root, config[key] ?? fallback);
900
+ const path = resolve4(root, config[key] ?? fallback);
441
901
  const old = await inspect(root, path);
442
902
  if (old !== undefined)
443
903
  validate(await readJson(path));
@@ -447,10 +907,10 @@ async function initialize(root, options) {
447
907
  content: old ?? json(starter)
448
908
  });
449
909
  }
450
- 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");
451
911
  const selected = options.agent === "both" ? ["codex", "claude"] : options.agent === "none" ? [] : [options.agent];
452
912
  for (const agent of selected) {
453
- 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");
454
914
  const oldSkill = await inspect(root, skillPath);
455
915
  if (oldSkill !== undefined && oldSkill !== skill)
456
916
  throw new InputError(`Existing skill differs; review it before replacing: '${skillPath}'`);
@@ -459,7 +919,7 @@ async function initialize(root, options) {
459
919
  action: oldSkill === undefined ? "create" : "preserve",
460
920
  content: skill
461
921
  });
462
- const path = resolve2(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
922
+ const path = resolve4(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
463
923
  const before = await inspect(root, path);
464
924
  if (before === undefined)
465
925
  plan.push({ path, action: "create", content: instruction });
@@ -484,7 +944,7 @@ async function initialize(root, options) {
484
944
  }
485
945
  }
486
946
  if (options.ci) {
487
- const path = resolve2(root, ".github/workflows/handoff-check.yml");
947
+ const path = resolve4(root, ".github/workflows/handoff-check.yml");
488
948
  const content = `name: Handoff constraints
489
949
  on: [push, pull_request]
490
950
  permissions:
@@ -513,7 +973,7 @@ jobs:
513
973
  throw new InputError("Initialization paths overlap; use separate config, manifest, handoff and integration files");
514
974
  const written = [];
515
975
  for (const file of plan) {
516
- 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}`)))
517
977
  throw new InputError("Initialization paths overlap as file and directory; choose separate paths");
518
978
  }
519
979
  if (!options.dryRun) {
@@ -524,7 +984,7 @@ jobs:
524
984
  const current = await inspect(root, file.path);
525
985
  if (file.action === "create" && current !== undefined || file.action === "append" && current !== file.before)
526
986
  throw new InputError("Target changed after planning");
527
- await mkdir(dirname2(file.path), { recursive: true });
987
+ await mkdir(dirname3(file.path), { recursive: true });
528
988
  await inspect(root, file.path);
529
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);
530
990
  const handle = await open(file.path, flags, 420);
@@ -533,10 +993,10 @@ jobs:
533
993
  } finally {
534
994
  await handle.close();
535
995
  }
536
- written.push(relative(root, file.path));
996
+ written.push(relative2(root, file.path));
537
997
  } catch (error) {
538
998
  const message = error instanceof Error ? error.message : "write failed";
539
- 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.`);
540
1000
  }
541
1001
  }
542
1002
  }
@@ -545,7 +1005,7 @@ jobs:
545
1005
  status: options.dryRun ? "preview" : "initialized",
546
1006
  scope,
547
1007
  files: plan.map((file) => ({
548
- path: relative(root, file.path),
1008
+ path: relative2(root, file.path),
549
1009
  action: file.action,
550
1010
  ...file.action === "preserve" ? {} : { content: file.content }
551
1011
  })),
@@ -626,176 +1086,6 @@ function explanationText(result, markdown) {
626
1086
  `);
627
1087
  }
628
1088
 
629
- // src/verifier.ts
630
- function compare(a, b) {
631
- return a < b ? -1 : a > b ? 1 : 0;
632
- }
633
- function inactive(rule, scope, time) {
634
- if (rule.scope !== "global" && rule.scope !== scope)
635
- return "OUT_OF_SCOPE";
636
- if (rule.revokedAt !== undefined && time >= Date.parse(rule.revokedAt))
637
- return "REVOKED";
638
- if (rule.supersededAt !== undefined && time >= Date.parse(rule.supersededAt))
639
- return "SUPERSEDED";
640
- if (rule.expiresAt !== undefined && time >= Date.parse(rule.expiresAt))
641
- return "EXPIRED";
642
- return;
643
- }
644
- function verify(manifest, handoff, scope, asOf, options = {}) {
645
- identifier(scope, "scope");
646
- if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
647
- throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
648
- const time = timestamp(asOf, "asOf");
649
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
650
- const expectedConstraints = manifest.constraints.filter((rule) => inactive(rule, scope, time) === undefined).map((rule) => rule.id).sort(compare);
651
- const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
652
- const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
653
- const reported = new Set(reportedConstraints);
654
- const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
655
- const findings = [];
656
- for (const id of expectedConstraints) {
657
- if (!reported.has(id))
658
- findings.push({
659
- code: "MISSING",
660
- id,
661
- message: `Include active constraint: ${byId.get(id)?.description}`
662
- });
663
- }
664
- for (const id of reportedConstraints) {
665
- const rule = byId.get(id);
666
- const code = rule ? inactive(rule, scope, time) : "UNKNOWN";
667
- if (code) {
668
- const detail = code === "SUPERSEDED" ? `; replaced by '${rule?.replacedBy}'` : "";
669
- findings.push({
670
- code,
671
- id,
672
- message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
673
- });
674
- } else if (rule && handoff.schemaVersion !== 1) {
675
- const current = reference(rule);
676
- const previous = refs.get(id);
677
- if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
678
- findings.push({
679
- code: "CHANGED",
680
- id,
681
- message: `Review changed constraint: ${rule.description}; handoff revision ${previous.revision}, current revision ${current.revision}${current.contentHash !== previous.contentHash ? "; content hash differs" : ""}`,
682
- expected: {
683
- revision: current.revision,
684
- contentHash: current.contentHash
685
- },
686
- reported: {
687
- revision: previous.revision,
688
- contentHash: previous.contentHash
689
- },
690
- ...retained.has(id) ? {
691
- changes: fieldChanges(retained.get(id), rule)
692
- } : {}
693
- });
694
- }
695
- }
696
- }
697
- if (options.requireActive && expectedConstraints.length === 0) {
698
- findings.push({
699
- code: "NO_ACTIVE_CONSTRAINTS",
700
- message: "No active constraints apply to the selected scope and time; --require-active requires at least one"
701
- });
702
- }
703
- findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
704
- return {
705
- schemaVersion: handoff.schemaVersion,
706
- ...handoff.schemaVersion !== 1 ? {
707
- tracking: "content",
708
- activeConstraintCount: expectedConstraints.length
709
- } : {},
710
- status: findings.length ? "mismatch" : "verified",
711
- scope,
712
- asOf: new Date(time).toISOString(),
713
- expectedConstraints,
714
- reportedConstraints,
715
- findings
716
- };
717
- }
718
- function snapshot(manifest, task, scope, asOf, options = {}) {
719
- if (!task.trim())
720
- throw new InputError("--task: expected a non-empty task");
721
- const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
722
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
723
- const base = {
724
- task,
725
- scope,
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
796
- };
797
- }
798
-
799
1089
  // src/cli.ts
800
1090
  var help = `Handoff Check
801
1091
 
@@ -803,6 +1093,9 @@ Usage: handoff-check verify --scope <scope> [options]
803
1093
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
804
1094
  handoff-check snapshot --task <task> [--output <new-file>] [options]
805
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]
806
1099
 
807
1100
  Options:
808
1101
  --constraints <path> Manifest file (default: constraints.json)
@@ -811,18 +1104,21 @@ Options:
811
1104
  --config <path> Project config (default: cwd/.handoff-check.json)
812
1105
  --as-of <UTC time> Fixed evaluation time (default: current time)
813
1106
  --require-content verify: require a v2/v3 content-aware handoff
814
- --require-active verify: fail if no constraints apply to scope/time
1107
+ --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
815
1108
  --task <task> snapshot: task description (required)
816
1109
  --output <path> snapshot: create a new baseline file, never overwrite
817
1110
  --include-content snapshot: retain old rule text in a v3 handoff (opt-in)
818
1111
  --format text|json|markdown Markdown is verify/explain-only (default: text)
819
1112
  --agent <agent> init: codex, claude, both (default), or none
1113
+ --host <host> doctor: integration target; hook/hook-config: claude
820
1114
  --dry-run init: preview files and instruction changes without writes
821
1115
  --ci init: also create a pinned GitHub Actions check
822
1116
  --version Show package version
823
1117
  --help Show this help
824
1118
 
825
- Exit codes: 0 verified/explained/captured/initialized, 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.
826
1122
  `;
827
1123
  async function main() {
828
1124
  let format = "text";
@@ -846,6 +1142,7 @@ async function main() {
846
1142
  "require-content": { type: "boolean" },
847
1143
  "require-active": { type: "boolean" },
848
1144
  "include-content": { type: "boolean" },
1145
+ host: { type: "string" },
849
1146
  task: { type: "string" },
850
1147
  output: { type: "string" }
851
1148
  }
@@ -862,10 +1159,75 @@ async function main() {
862
1159
  `);
863
1160
  return 0;
864
1161
  }
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)");
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)");
867
1172
  const cwd = process.cwd();
868
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");
869
1231
  if (format === "markdown" && command !== "verify" && command !== "explain")
870
1232
  throw new InputError("--format markdown is only supported by verify and explain");
871
1233
  if (values["include-content"] !== undefined && command !== "snapshot")
@@ -929,7 +1291,7 @@ ${result2.notice}
929
1291
  for (const key of ["constraints", "handoff", "config"])
930
1292
  if (values[key] !== undefined && !values[key].trim())
931
1293
  throw new InputError(`--${key}: expected a non-empty path`);
932
- 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")));
933
1295
  if (command === "explain") {
934
1296
  const result2 = explain(manifest, scope, asOf);
935
1297
  process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
@@ -951,7 +1313,7 @@ ${result2.notice}
951
1313
  else {
952
1314
  if (!values.output.trim())
953
1315
  throw new InputError("--output: expected a non-empty path");
954
- const path = resolve3(cwd, values.output);
1316
+ const path = resolve5(cwd, values.output);
955
1317
  let handle;
956
1318
  try {
957
1319
  handle = await open2(path, "wx", 420);
@@ -977,7 +1339,7 @@ ${result2.notice}
977
1339
  }
978
1340
  if (values.task !== undefined || values.output !== undefined)
979
1341
  throw new InputError("--task and --output are only supported by snapshot");
980
- const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve3(cwd, values.handoff) : resolve3(directory, config.handoff ?? "handoff.json")));
1342
+ const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve5(cwd, values.handoff) : resolve5(directory, config.handoff ?? "handoff.json")));
981
1343
  if (values["require-content"] && handoff.schemaVersion === 1)
982
1344
  throw new InputError("Content tracking requires a schemaVersion 2 or 3 handoff; review current rules and capture a snapshot before resuming");
983
1345
  const result = verify(manifest, handoff, scope, asOf, {