handoff-check 0.6.0 → 0.8.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
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { open as open2 } from "node:fs/promises";
5
- import { resolve as resolve5 } from "node:path";
4
+ import { open as open4 } from "node:fs/promises";
5
+ import { resolve as resolve7 } 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.6.0",
10
+ version: "0.8.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",
@@ -68,7 +68,8 @@ var package_default = {
68
68
 
69
69
  // src/config.ts
70
70
  import { createHash as createHash2 } from "node:crypto";
71
- import { readFile } from "node:fs/promises";
71
+ import { constants } from "node:fs";
72
+ import { open, readFile } from "node:fs/promises";
72
73
  import { dirname, resolve } from "node:path";
73
74
 
74
75
  // src/content.ts
@@ -315,10 +316,22 @@ function selectProfile(config, profile) {
315
316
  function digest(bytes) {
316
317
  return `sha256:${createHash2("sha256").update(bytes).digest("hex")}`;
317
318
  }
318
- async function readJsonRecord(path) {
319
+ async function readBytes(path, regularOnly) {
320
+ if (!regularOnly)
321
+ return readFile(path);
322
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
323
+ try {
324
+ if (!(await handle.stat()).isFile())
325
+ throw new InputError(`Expected a regular input file: '${path}'`);
326
+ return await handle.readFile();
327
+ } finally {
328
+ await handle.close();
329
+ }
330
+ }
331
+ async function readJsonRecord(path, regularOnly = false) {
319
332
  let bytes;
320
333
  try {
321
- bytes = await readFile(path);
334
+ bytes = await readBytes(path, regularOnly);
322
335
  } catch {
323
336
  throw new InputError(`Cannot read input file '${path}'`);
324
337
  }
@@ -330,8 +343,8 @@ async function readJsonRecord(path) {
330
343
  }
331
344
  return { input, path, sha256: digest(bytes) };
332
345
  }
333
- async function readJson(path) {
334
- return (await readJsonRecord(path)).input;
346
+ async function readJson(path, regularOnly = false) {
347
+ return (await readJsonRecord(path, regularOnly)).input;
335
348
  }
336
349
  function parseConfig(input) {
337
350
  if (!input || typeof input !== "object" || Array.isArray(input))
@@ -384,11 +397,11 @@ function parseConfig(input) {
384
397
  }
385
398
  return config;
386
399
  }
387
- async function loadConfig(cwd, explicit) {
400
+ async function loadConfig(cwd, explicit, regularOnly = false) {
388
401
  const path = resolve(cwd, explicit ?? ".handoff-check.json");
389
402
  let input;
390
403
  try {
391
- input = await readFile(path);
404
+ input = await readBytes(path, regularOnly);
392
405
  } catch (error) {
393
406
  if (explicit === undefined && error.code === "ENOENT")
394
407
  return { config: { schemaVersion: 1 }, directory: cwd };
@@ -407,13 +420,80 @@ async function loadConfig(cwd, explicit) {
407
420
  };
408
421
  }
409
422
 
410
- // src/doctor.ts
411
- import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
412
- import { resolve as resolve3 } from "node:path";
413
-
414
- // src/lifecycle.ts
415
- import { realpath, stat } from "node:fs/promises";
416
- import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
423
+ // src/render.ts
424
+ function terminalText(value) {
425
+ return Array.from(value, (character) => {
426
+ const code = character.codePointAt(0) ?? 0;
427
+ return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
428
+ }).join("");
429
+ }
430
+ function markdownText(value) {
431
+ return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
432
+ }
433
+ function verificationMarkdown(result, handoff, requireActive, requireContent) {
434
+ const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
435
+ const lines = [
436
+ "# Handoff Check verification",
437
+ "",
438
+ `- Result: ${label}`,
439
+ `- Scope: ${markdownText(result.scope)}`,
440
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
441
+ `- Evaluated at: ${markdownText(result.asOf)}`,
442
+ `- Active constraints checked: ${result.expectedConstraints.length}`,
443
+ `- Tracking: ${handoff.schemaVersion === 1 ? "IDs only; content changes not checked" : handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? "Content hashes with retained old content" : "Content hashes; old content not retained"}`,
444
+ `- Require content-aware handoff: ${requireContent}`,
445
+ `- Require active constraints: ${requireActive}`,
446
+ ""
447
+ ];
448
+ if (!result.expectedConstraints.length)
449
+ lines.push("No active constraints apply to this scope and time.", "");
450
+ lines.push("## Findings", "");
451
+ if (!result.findings.length)
452
+ lines.push("No findings.", "");
453
+ for (const finding of result.findings) {
454
+ lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
455
+ if (finding.code === "CHANGED") {
456
+ if (finding.changes) {
457
+ lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
458
+ for (const change of finding.changes)
459
+ lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
460
+ lines.push("", "Null means an absent optional field.", "");
461
+ } else
462
+ lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
463
+ }
464
+ }
465
+ lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
466
+ return `${lines.join(`
467
+ `)}
468
+ `;
469
+ }
470
+ function explanationText(result, markdown) {
471
+ if (markdown) {
472
+ return [
473
+ "# Handoff Check explanation",
474
+ "",
475
+ `- Scope: ${markdownText(result.scope)}`,
476
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
477
+ `- Evaluated at: ${markdownText(result.asOf)}`,
478
+ `- Active constraints: ${result.activeConstraintCount}`,
479
+ "",
480
+ "| ID | Rule scope | Decision | Reason | Description | Source |",
481
+ "| --- | --- | --- | --- | --- | --- |",
482
+ ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
483
+ "",
484
+ "Explains manifest applicability only; no handoff was compared.",
485
+ ""
486
+ ].join(`
487
+ `);
488
+ }
489
+ return [
490
+ ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
491
+ `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}${result.projectId === undefined ? "" : ` | project ${result.projectId}`}`,
492
+ "No handoff was compared.",
493
+ ""
494
+ ].join(`
495
+ `);
496
+ }
417
497
 
418
498
  // src/verifier.ts
419
499
  function compare(a, b) {
@@ -624,7 +704,88 @@ function explain(manifest, scope, asOf) {
624
704
  };
625
705
  }
626
706
 
707
+ // src/diff.ts
708
+ function diffSnapshots(before, after) {
709
+ if (before.schemaVersion === 1 || after.schemaVersion === 1)
710
+ throw new InputError("diff requires content-aware v2/v3/v4 snapshots");
711
+ if (before.scope !== after.scope)
712
+ throw new InputError("diff requires snapshots with the same scope");
713
+ const project = before.schemaVersion === 4 ? before.projectId : undefined;
714
+ if (project !== (after.schemaVersion === 4 ? after.projectId : undefined))
715
+ throw new InputError("diff requires matching project binding on both snapshots");
716
+ const previous = new Map(before.activeConstraints.map((r) => [r.id, r]));
717
+ const current = new Map(after.activeConstraints.map((r) => [r.id, r]));
718
+ const ref = (r) => ({
719
+ id: r.id,
720
+ revision: r.revision,
721
+ contentHash: r.contentHash
722
+ });
723
+ const changes = [];
724
+ let unchangedCount = 0;
725
+ for (const id of [
726
+ ...new Set([...previous.keys(), ...current.keys()])
727
+ ].sort()) {
728
+ const a = previous.get(id);
729
+ const b = current.get(id);
730
+ if (a && b && a.revision === b.revision && a.contentHash === b.contentHash) {
731
+ unchangedCount++;
732
+ continue;
733
+ }
734
+ const retained = (r) => ("content" in r);
735
+ changes.push({
736
+ id,
737
+ kind: !a ? "ADDED" : !b ? "REMOVED" : "CHANGED",
738
+ before: a ? ref(a) : null,
739
+ after: b ? ref(b) : null,
740
+ ...a && b && retained(a) && retained(b) ? { fields: fieldChanges(a.content, b.content) } : {}
741
+ });
742
+ }
743
+ return {
744
+ schemaVersion: 1,
745
+ status: changes.length ? "different" : "unchanged",
746
+ scope: before.scope,
747
+ ...project === undefined ? {} : { projectId: project },
748
+ beforeCount: previous.size,
749
+ afterCount: current.size,
750
+ unchangedCount,
751
+ changes,
752
+ notice: "Compares declared rules, not agent behavior or current applicability. Task and capture time are metadata and are not compared. Field details require retained content on both sides; additions/removals do not imply why a rule became active or inactive."
753
+ };
754
+ }
755
+ function diffText(result, markdown) {
756
+ const safe = markdown ? markdownText : terminalText;
757
+ const lines = [
758
+ markdown ? `# Handoff Check snapshot diff
759
+ ` : "SNAPSHOT DIFF",
760
+ `${result.status.toUpperCase()} | scope ${safe(result.scope)}${result.projectId ? ` | project ${safe(result.projectId)}` : ""}`,
761
+ `${result.beforeCount} before | ${result.afterCount} after | ${result.unchangedCount} unchanged`
762
+ ];
763
+ for (const change of result.changes) {
764
+ lines.push(`${change.kind} ${safe(change.id)}`);
765
+ if (change.kind === "CHANGED") {
766
+ if (change.fields) {
767
+ for (const field of change.fields)
768
+ lines.push(` ${field.field}: ${safe(JSON.stringify(field.before))} -> ${safe(JSON.stringify(field.after))}`);
769
+ } else
770
+ lines.push(" Field details unavailable: both snapshots must retain content");
771
+ lines.push(` Before: revision ${change.before?.revision}, ${change.before?.contentHash}`, ` After: revision ${change.after?.revision}, ${change.after?.contentHash}`);
772
+ }
773
+ }
774
+ lines.push(safe(result.notice));
775
+ return `${lines.join(markdown ? `
776
+
777
+ ` : `
778
+ `)}
779
+ `;
780
+ }
781
+
782
+ // src/doctor.ts
783
+ import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
784
+ import { resolve as resolve3 } from "node:path";
785
+
627
786
  // src/lifecycle.ts
787
+ import { realpath, stat } from "node:fs/promises";
788
+ import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
628
789
  var lifecycleCommand = "node";
629
790
  var projectPlaceholder = "$" + "{CLAUDE_PROJECT_DIR}";
630
791
  var lifecycleArgs = [
@@ -969,8 +1130,8 @@ async function doctor(cwd, options) {
969
1130
  }
970
1131
 
971
1132
  // src/initialize.ts
972
- import { constants } from "node:fs";
973
- import { lstat as lstat2, mkdir, open, readFile as readFile3 } from "node:fs/promises";
1133
+ import { constants as constants2 } from "node:fs";
1134
+ import { lstat as lstat2, mkdir, open as open2, readFile as readFile3 } from "node:fs/promises";
974
1135
  import { dirname as dirname3, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
975
1136
  var begin = "<!-- handoff-check:begin -->";
976
1137
  var end = "<!-- handoff-check:end -->";
@@ -1149,8 +1310,8 @@ jobs:
1149
1310
  throw new InputError("Target changed after planning");
1150
1311
  await mkdir(dirname3(file.path), { recursive: true });
1151
1312
  await inspect(root, file.path);
1152
- const flags = file.action === "create" ? constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL : constants.O_WRONLY | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0);
1153
- const handle = await open(file.path, flags, 420);
1313
+ const flags = file.action === "create" ? constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL : constants2.O_WRONLY | constants2.O_APPEND | (constants2.O_NOFOLLOW ?? 0);
1314
+ const handle = await open2(file.path, flags, 420);
1154
1315
  try {
1155
1316
  await handle.writeFile(file.content, "utf8");
1156
1317
  } finally {
@@ -1176,81 +1337,6 @@ jobs:
1176
1337
  };
1177
1338
  }
1178
1339
 
1179
- // src/render.ts
1180
- function terminalText(value) {
1181
- return Array.from(value, (character) => {
1182
- const code = character.codePointAt(0) ?? 0;
1183
- return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
1184
- }).join("");
1185
- }
1186
- function markdownText(value) {
1187
- return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
1188
- }
1189
- function verificationMarkdown(result, handoff, requireActive, requireContent) {
1190
- const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
1191
- const lines = [
1192
- "# Handoff Check verification",
1193
- "",
1194
- `- Result: ${label}`,
1195
- `- Scope: ${markdownText(result.scope)}`,
1196
- ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
1197
- `- Evaluated at: ${markdownText(result.asOf)}`,
1198
- `- Active constraints checked: ${result.expectedConstraints.length}`,
1199
- `- Tracking: ${handoff.schemaVersion === 1 ? "IDs only; content changes not checked" : handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? "Content hashes with retained old content" : "Content hashes; old content not retained"}`,
1200
- `- Require content-aware handoff: ${requireContent}`,
1201
- `- Require active constraints: ${requireActive}`,
1202
- ""
1203
- ];
1204
- if (!result.expectedConstraints.length)
1205
- lines.push("No active constraints apply to this scope and time.", "");
1206
- lines.push("## Findings", "");
1207
- if (!result.findings.length)
1208
- lines.push("No findings.", "");
1209
- for (const finding of result.findings) {
1210
- lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
1211
- if (finding.code === "CHANGED") {
1212
- if (finding.changes) {
1213
- lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
1214
- for (const change of finding.changes)
1215
- lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
1216
- lines.push("", "Null means an absent optional field.", "");
1217
- } else
1218
- lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
1219
- }
1220
- }
1221
- lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
1222
- return `${lines.join(`
1223
- `)}
1224
- `;
1225
- }
1226
- function explanationText(result, markdown) {
1227
- if (markdown) {
1228
- return [
1229
- "# Handoff Check explanation",
1230
- "",
1231
- `- Scope: ${markdownText(result.scope)}`,
1232
- ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
1233
- `- Evaluated at: ${markdownText(result.asOf)}`,
1234
- `- Active constraints: ${result.activeConstraintCount}`,
1235
- "",
1236
- "| ID | Rule scope | Decision | Reason | Description | Source |",
1237
- "| --- | --- | --- | --- | --- | --- |",
1238
- ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
1239
- "",
1240
- "Explains manifest applicability only; no handoff was compared.",
1241
- ""
1242
- ].join(`
1243
- `);
1244
- }
1245
- return [
1246
- ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
1247
- `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}${result.projectId === undefined ? "" : ` | project ${result.projectId}`}`,
1248
- "No handoff was compared.",
1249
- ""
1250
- ].join(`
1251
- `);
1252
- }
1253
-
1254
1340
  // src/report.ts
1255
1341
  import { execFile } from "node:child_process";
1256
1342
  import { promisify } from "node:util";
@@ -1303,10 +1389,268 @@ function reportMarkdown(report) {
1303
1389
  `);
1304
1390
  }
1305
1391
 
1392
+ // src/run.ts
1393
+ import { spawn } from "node:child_process";
1394
+ import { constants as constants3 } from "node:os";
1395
+ import { resolve as resolve5 } from "node:path";
1396
+ async function runVerified(cwd, options, argv) {
1397
+ const executable = argv[0];
1398
+ if (!executable?.trim())
1399
+ throw new InputError("run requires -- <executable> [arguments...]");
1400
+ if (options.profile !== undefined && [options.scope, options.constraints, options.handoff].some((v) => v !== undefined))
1401
+ throw new InputError("--profile cannot be combined with --scope, --constraints or --handoff");
1402
+ for (const key of ["config", "constraints", "handoff"])
1403
+ if (options[key] !== undefined && !options[key].trim())
1404
+ throw new InputError(`--${key}: expected a non-empty path`);
1405
+ let child;
1406
+ const signalCode = (signal) => 128 + (constants3.signals[signal] ?? 1);
1407
+ const forward = (signal) => {
1408
+ if (!child) {
1409
+ process.stderr.write(`RUN CANCELLED before command launch
1410
+ `);
1411
+ process.exit(signalCode(signal));
1412
+ }
1413
+ if (child && child.exitCode === null && child.signalCode === null) {
1414
+ process.stderr.write(`RUN SIGNAL ${signal}: forwarding to direct child
1415
+ `);
1416
+ try {
1417
+ child.kill(signal);
1418
+ } catch {
1419
+ process.stderr.write(`RUN SIGNAL ${signal}: direct-child forwarding failed
1420
+ `);
1421
+ }
1422
+ }
1423
+ };
1424
+ const interrupt = () => forward("SIGINT");
1425
+ const terminate = () => forward("SIGTERM");
1426
+ process.on("SIGINT", interrupt);
1427
+ process.on("SIGTERM", terminate);
1428
+ const deadline = setTimeout(() => {
1429
+ process.stderr.write(`RUN INVALID: preflight exceeded 5 seconds; command not started
1430
+ `);
1431
+ process.exit(2);
1432
+ }, 5000);
1433
+ process.stderr.write(`RUN CHECKING: current-clock content/nonempty preflight
1434
+ `);
1435
+ try {
1436
+ const loaded = await loadConfig(cwd, options.config, true);
1437
+ const config = selectProfile(loaded.config, options.profile);
1438
+ const scope = identifier(options.scope ?? config.scope, "--scope (or config.scope)");
1439
+ const manifest = parseManifest(await readJson(options.constraints !== undefined ? resolve5(cwd, options.constraints) : resolve5(loaded.directory, config.constraints ?? "constraints.json"), true));
1440
+ const handoff = parseHandoff(await readJson(options.handoff !== undefined ? resolve5(cwd, options.handoff) : resolve5(loaded.directory, config.handoff ?? "handoff.json"), true));
1441
+ if (handoff.schemaVersion === 1)
1442
+ throw new InputError("run requires a content-aware v2/v3/v4 handoff; review and capture a baseline explicitly");
1443
+ const result = verify(manifest, handoff, scope, new Date().toISOString(), {
1444
+ requireActive: true,
1445
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
1446
+ });
1447
+ clearTimeout(deadline);
1448
+ if (result.status !== "verified") {
1449
+ for (const finding of result.findings)
1450
+ process.stderr.write(`RUN BLOCKED ${finding.code}${finding.id ? ` ${finding.id}` : ""}
1451
+ `);
1452
+ process.stderr.write(`RUN BLOCKED: command not started | ${result.expectedConstraints.length} active constraints | scope ${scope} | as of ${result.asOf}${result.projectId ? ` | project ${result.projectId}` : ""}${options.profile ? ` | profile ${options.profile}` : ""}
1453
+ `);
1454
+ return 1;
1455
+ }
1456
+ process.stderr.write(`RUN VERIFIED: ${result.expectedConstraints.length} active constraints | content tracked | scope ${scope} | as of ${result.asOf}${result.projectId ? ` | project ${result.projectId}` : ""}${options.profile ? ` | profile ${options.profile}` : ""}
1457
+ `);
1458
+ return await new Promise((done) => {
1459
+ let launchFailed = false;
1460
+ let started = false;
1461
+ try {
1462
+ child = spawn(executable, argv.slice(1), {
1463
+ cwd,
1464
+ env: process.env,
1465
+ shell: false,
1466
+ stdio: "inherit"
1467
+ });
1468
+ } catch {
1469
+ process.stderr.write(`RUN LAUNCH ERROR: command could not be started
1470
+ `);
1471
+ done(2);
1472
+ return;
1473
+ }
1474
+ child.on("error", (error) => {
1475
+ if (started) {
1476
+ process.stderr.write(`RUN PROCESS ERROR: ${terminalText(error.code ?? "UNKNOWN")} | waiting for direct child
1477
+ `);
1478
+ return;
1479
+ }
1480
+ launchFailed = true;
1481
+ process.stderr.write(`RUN LAUNCH ERROR: ${terminalText(error.code ?? "UNKNOWN")} | command could not be started
1482
+ `);
1483
+ done(2);
1484
+ });
1485
+ child.once("spawn", () => {
1486
+ started = true;
1487
+ process.stderr.write(`RUN STARTED: verification passed; waiting for command
1488
+ `);
1489
+ });
1490
+ child.once("close", (code, signal) => {
1491
+ if (launchFailed)
1492
+ return;
1493
+ const exitCode = code ?? (signal ? signalCode(signal) : 2);
1494
+ process.stderr.write(`RUN EXIT: ${exitCode}${signal ? ` | signal ${signal}` : ""}
1495
+ `);
1496
+ done(exitCode);
1497
+ });
1498
+ });
1499
+ } finally {
1500
+ clearTimeout(deadline);
1501
+ process.removeListener("SIGINT", interrupt);
1502
+ process.removeListener("SIGTERM", terminate);
1503
+ }
1504
+ }
1505
+
1506
+ // src/setup.ts
1507
+ import { lstat as lstat3, open as open3, readdir } from "node:fs/promises";
1508
+ import { resolve as resolve6 } from "node:path";
1509
+ import { createInterface } from "node:readline/promises";
1510
+ function setupPlan(answers, asOf) {
1511
+ const projectId = identifier(answers.projectId, "Project ID");
1512
+ const scopes = answers.scopes.map((scope) => identifier(scope, "Environment"));
1513
+ if (!scopes.length || scopes.length > 20 || new Set(scopes).size !== scopes.length || new Set(scopes.map((s) => s.toLowerCase())).size !== scopes.length)
1514
+ throw new InputError("Enter 1 to 20 unique environments (case-insensitive filenames)");
1515
+ const manifest = parseManifest({
1516
+ schemaVersion: 3,
1517
+ projectId,
1518
+ constraints: [
1519
+ {
1520
+ id: identifier(answers.ruleId, "Rule ID"),
1521
+ revision: 1,
1522
+ scope: "global",
1523
+ description: answers.description,
1524
+ source: answers.source
1525
+ }
1526
+ ]
1527
+ });
1528
+ const profiles = Object.fromEntries(scopes.map((scope) => [scope, { scope, handoff: `handoff-${scope}.json` }]));
1529
+ const config = parseConfig({
1530
+ schemaVersion: 2,
1531
+ projectId,
1532
+ constraints: "constraints.json",
1533
+ profiles
1534
+ });
1535
+ const json = (value) => `${JSON.stringify(value, null, 2)}
1536
+ `;
1537
+ return [
1538
+ { path: ".handoff-check.json", content: json(config) },
1539
+ { path: "constraints.json", content: json(manifest) },
1540
+ ...scopes.map((scope) => ({
1541
+ path: `handoff-${scope}.json`,
1542
+ content: json(snapshot(manifest, answers.task, scope, asOf, {
1543
+ includeContent: true,
1544
+ projectId
1545
+ }))
1546
+ }))
1547
+ ];
1548
+ }
1549
+ async function assertSetupTargets(root, files) {
1550
+ const existing = new Set((await readdir(root)).map((name) => name.normalize("NFC").toLowerCase()));
1551
+ for (const file of files) {
1552
+ if (existing.has(file.path.normalize("NFC").toLowerCase()))
1553
+ throw new InputError(`Setup requires new files; target already exists: '${file.path}'.`);
1554
+ try {
1555
+ await lstat3(resolve6(root, file.path));
1556
+ } catch (error) {
1557
+ if (error.code === "ENOENT")
1558
+ continue;
1559
+ throw error;
1560
+ }
1561
+ throw new InputError(`Setup requires new files; target already exists: '${file.path}'. Use init or edit existing configuration explicitly.`);
1562
+ }
1563
+ }
1564
+ async function writeSetup(root, files) {
1565
+ await assertSetupTargets(root, files);
1566
+ const written = [];
1567
+ for (const file of files) {
1568
+ try {
1569
+ const handle = await open3(resolve6(root, file.path), "wx", 420);
1570
+ try {
1571
+ await handle.writeFile(file.content, "utf8");
1572
+ } finally {
1573
+ await handle.close();
1574
+ }
1575
+ written.push(file.path);
1576
+ } catch {
1577
+ throw new InputError(`Setup stopped at '${file.path}'. Written files: ${written.join(", ") || "none"}. Filesystem writes are not transactional; inspect before retrying.`);
1578
+ }
1579
+ }
1580
+ }
1581
+ async function guidedSetup(root, dryRun) {
1582
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
1583
+ throw new InputError("setup requires an interactive terminal; use init --scope <scope> for automation");
1584
+ await assertSetupTargets(root, [
1585
+ { path: ".handoff-check.json" },
1586
+ { path: "constraints.json" }
1587
+ ]);
1588
+ const reader = createInterface({
1589
+ input: process.stdin,
1590
+ output: process.stdout
1591
+ });
1592
+ const abort = new AbortController;
1593
+ reader.on("SIGINT", () => {
1594
+ abort.abort();
1595
+ reader.close();
1596
+ });
1597
+ reader.on("close", () => abort.abort());
1598
+ const ask = async (prompt) => {
1599
+ try {
1600
+ return (await reader.question(prompt, { signal: abort.signal })).trim();
1601
+ } catch {
1602
+ throw new InputError("Setup cancelled before approval; no files written");
1603
+ }
1604
+ };
1605
+ try {
1606
+ process.stdout.write(`Create a project-bound starter with one real rule applying to every environment.
1607
+ No agent settings, hooks, CI, or dependencies will be installed.
1608
+ `);
1609
+ const projectId = await ask("Project ID: ");
1610
+ const scopes = (await ask("Environments (comma-separated, e.g. staging,production): ")).split(",").map((s) => s.trim());
1611
+ const ruleId = await ask("First rule ID: ");
1612
+ const description = await ask("Rule applying to ALL environments: ");
1613
+ const source = await ask("Rule source reference (stored as text, never fetched): ");
1614
+ const task = await ask("Initial handoff task: ");
1615
+ const files = setupPlan({ projectId, scopes, ruleId, description, source, task }, new Date().toISOString());
1616
+ await assertSetupTargets(root, files);
1617
+ process.stdout.write(`
1618
+ Review the exact proposed files and retained rule content:
1619
+ `);
1620
+ for (const file of files)
1621
+ process.stdout.write(`
1622
+ --- ${file.path} ---
1623
+ ${file.content.split(`
1624
+ `).map(terminalText).join(`
1625
+ `)}
1626
+ `);
1627
+ if (dryRun) {
1628
+ process.stdout.write(`PREVIEW ONLY: no files written.
1629
+ `);
1630
+ return;
1631
+ }
1632
+ if (await ask("Adopt these reviewed rules and create these new baselines? Type yes: ") !== "yes") {
1633
+ process.stdout.write(`CANCELLED: no files written.
1634
+ `);
1635
+ return;
1636
+ }
1637
+ await writeSetup(root, files);
1638
+ process.stdout.write(`CREATED ${files.length} files.
1639
+ Next: handoff-check verify --profile ${scopes[0]} --require-content --require-active
1640
+ Edit and review constraints before relying on them. Never refresh a baseline before verifying it on resume.
1641
+ `);
1642
+ } finally {
1643
+ reader.close();
1644
+ }
1645
+ }
1646
+
1306
1647
  // src/cli.ts
1307
1648
  var help = `Handoff Check
1308
1649
 
1309
1650
  Usage: handoff-check verify --scope <scope> [options]
1651
+ handoff-check run [--profile <name> | --scope <scope>] [--config <path>] -- <executable> [args...]
1652
+ handoff-check diff --before <snapshot> --after <snapshot> [--format text|json|markdown]
1653
+ handoff-check setup [--dry-run]
1310
1654
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
1311
1655
  handoff-check snapshot --task <task> [--output <new-file>] [options]
1312
1656
  handoff-check explain --scope <scope> [options]
@@ -1315,6 +1659,8 @@ Usage: handoff-check verify --scope <scope> [options]
1315
1659
  handoff-check hook --host claude --config <absolute-path> [--require-active]
1316
1660
 
1317
1661
  Options:
1662
+ --before <path> diff: saved snapshot before the change
1663
+ --after <path> diff: saved snapshot after the change
1318
1664
  --constraints <path> Manifest file (default: constraints.json)
1319
1665
  --handoff <path> Handoff file (default: handoff.json)
1320
1666
  --scope <scope> Selected scope, including global constraints
@@ -1328,23 +1674,29 @@ Options:
1328
1674
  --task <task> snapshot: task description (required)
1329
1675
  --output <path> snapshot: create a new baseline file, never overwrite
1330
1676
  --include-content snapshot: retain old rule text in unbound v3/bound v4 (opt-in)
1331
- --format text|json|markdown Markdown is verify/explain-only (default: text)
1677
+ --format text|json|markdown Markdown is verify/explain/diff-only (default: text)
1332
1678
  --agent <agent> init: codex, claude, both (default), or none
1333
1679
  --host <host> doctor: integration target; hook/hook-config: claude
1334
- --dry-run init: preview files and instruction changes without writes
1680
+ --dry-run init/setup: preview proposed files without writes
1335
1681
  --ci init: also create a pinned GitHub Actions check
1336
1682
  --version Show package version
1337
1683
  --help Show this help
1338
1684
 
1339
- Exit codes: verify 0 verified / 1 mismatch; doctor 0 healthy / 1 attention.
1685
+ Exit codes: verify 0 verified / 1 mismatch; diff 0 unchanged / 1 different; doctor 0 healthy / 1 attention.
1686
+ Run: mandatory content/nonempty/current-clock preflight; 1 blocked / 2 invalid or launch error.
1687
+ After launch run returns the child exit code (or 128 + signal); diagnostics use stderr.
1340
1688
  Hook 0 means advisory response delivered (may report FAIL/INVALID), not verified.
1341
1689
  Invalid invocation/input returns 2; explain/init/snapshot/hook-config succeed with 0.
1342
1690
  `;
1343
1691
  async function main() {
1344
1692
  let format = "text";
1345
1693
  try {
1694
+ const rawArgs = process.argv.slice(2);
1695
+ const runCommand = rawArgs[0] === "run";
1696
+ const separator = rawArgs.indexOf("--");
1697
+ const wrapperArgs = runCommand && separator >= 0 ? rawArgs.slice(0, separator) : rawArgs;
1346
1698
  const { values, positionals } = parseArgs({
1347
- args: process.argv.slice(2),
1699
+ args: wrapperArgs,
1348
1700
  allowPositionals: true,
1349
1701
  strict: true,
1350
1702
  options: {
@@ -1367,7 +1719,9 @@ async function main() {
1367
1719
  report: { type: "boolean" },
1368
1720
  "git-context": { type: "boolean" },
1369
1721
  task: { type: "string" },
1370
- output: { type: "string" }
1722
+ output: { type: "string" },
1723
+ before: { type: "string" },
1724
+ after: { type: "string" }
1371
1725
  }
1372
1726
  });
1373
1727
  format = values.format;
@@ -1389,11 +1743,49 @@ async function main() {
1389
1743
  "explain",
1390
1744
  "doctor",
1391
1745
  "hook",
1392
- "hook-config"
1746
+ "hook-config",
1747
+ "diff",
1748
+ "setup",
1749
+ "run"
1393
1750
  ].includes(positionals[0] ?? ""))
1394
- throw new InputError("Expected command: verify, snapshot, explain, init, doctor, hook or hook-config (use --help for usage)");
1751
+ throw new InputError("Expected command: verify, snapshot, explain, init, setup, diff, run, doctor, hook or hook-config (use --help for usage)");
1395
1752
  const cwd = process.cwd();
1396
1753
  const command = positionals[0];
1754
+ if (command === "run") {
1755
+ if (!runCommand || separator < 0)
1756
+ throw new InputError("Use run as the first argument and include -- <executable> [arguments...]");
1757
+ const allowed = ["config", "profile", "scope", "constraints", "handoff"];
1758
+ for (const key of Object.keys(values)) {
1759
+ if (key === "format" && !wrapperArgs.some((arg) => arg === "--format" || arg.startsWith("--format=")))
1760
+ continue;
1761
+ if (!allowed.includes(key))
1762
+ throw new InputError(`--${key} is not supported by run; content/nonempty checks and the current clock are mandatory`);
1763
+ }
1764
+ return await runVerified(cwd, values, rawArgs.slice(separator + 1));
1765
+ }
1766
+ if (command === "diff" || command === "setup") {
1767
+ const allowed = command === "diff" ? ["before", "after", "format"] : ["dry-run"];
1768
+ for (const key of Object.keys(values)) {
1769
+ if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1770
+ continue;
1771
+ if (!allowed.includes(key))
1772
+ throw new InputError(`--${key} is not supported by ${command}`);
1773
+ }
1774
+ if (command === "setup") {
1775
+ await guidedSetup(cwd, values["dry-run"] ?? false);
1776
+ return 0;
1777
+ }
1778
+ if (!values.before?.trim() || !values.after?.trim())
1779
+ throw new InputError("diff requires --before <snapshot> and --after <snapshot>");
1780
+ const before = parseHandoff((await readJsonRecord(resolve7(cwd, values.before))).input);
1781
+ const after = parseHandoff((await readJsonRecord(resolve7(cwd, values.after))).input);
1782
+ const result2 = diffSnapshots(before, after);
1783
+ process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
1784
+ ` : diffText(result2, format === "markdown"));
1785
+ return result2.status === "unchanged" ? 0 : 1;
1786
+ }
1787
+ if (values.before !== undefined || values.after !== undefined)
1788
+ throw new InputError("--before and --after are diff-only");
1397
1789
  if (values.profile !== undefined) {
1398
1790
  identifier(values.profile, "--profile");
1399
1791
  if (command === "init")
@@ -1537,7 +1929,7 @@ ${result2.notice}
1537
1929
  for (const key of ["constraints", "handoff", "config"])
1538
1930
  if (values[key] !== undefined && !values[key].trim())
1539
1931
  throw new InputError(`--${key}: expected a non-empty path`);
1540
- const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve5(cwd, values.constraints) : resolve5(directory, config.constraints ?? "constraints.json"));
1932
+ const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve7(cwd, values.constraints) : resolve7(directory, config.constraints ?? "constraints.json"));
1541
1933
  const manifest = parseManifest(manifestRecord.input);
1542
1934
  checkProject(manifest, undefined, config.projectId);
1543
1935
  if (command === "explain") {
@@ -1562,10 +1954,10 @@ ${result2.notice}
1562
1954
  else {
1563
1955
  if (!values.output.trim())
1564
1956
  throw new InputError("--output: expected a non-empty path");
1565
- const path = resolve5(cwd, values.output);
1957
+ const path = resolve7(cwd, values.output);
1566
1958
  let handle;
1567
1959
  try {
1568
- handle = await open2(path, "wx", 420);
1960
+ handle = await open4(path, "wx", 420);
1569
1961
  } catch {
1570
1962
  throw new InputError(`Cannot create snapshot '${path}'; choose a new file with an existing parent directory`);
1571
1963
  }
@@ -1588,7 +1980,7 @@ ${result2.notice}
1588
1980
  }
1589
1981
  if (values.task !== undefined || values.output !== undefined)
1590
1982
  throw new InputError("--task and --output are only supported by snapshot");
1591
- const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve5(cwd, values.handoff) : resolve5(directory, config.handoff ?? "handoff.json"));
1983
+ const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve7(cwd, values.handoff) : resolve7(directory, config.handoff ?? "handoff.json"));
1592
1984
  const handoff = parseHandoff(handoffRecord.input);
1593
1985
  if (values["require-content"] && handoff.schemaVersion === 1)
1594
1986
  throw new InputError("Content tracking requires a schemaVersion 2, 3 or 4 handoff; review current rules and capture a snapshot before resuming");