handoff-check 0.8.0 → 0.10.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 open4 } from "node:fs/promises";
5
- import { resolve as resolve7 } from "node:path";
4
+ import { open as open7 } from "node:fs/promises";
5
+ import { resolve as resolve10 } 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.8.0",
10
+ version: "0.10.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",
@@ -1389,10 +1389,230 @@ function reportMarkdown(report) {
1389
1389
  `);
1390
1390
  }
1391
1391
 
1392
+ // src/review-cli.ts
1393
+ import { open as open3 } from "node:fs/promises";
1394
+ import { resolve as resolve5 } from "node:path";
1395
+
1396
+ // src/review.ts
1397
+ function object2(input, allowed, path) {
1398
+ if (!input || typeof input !== "object" || Array.isArray(input))
1399
+ throw new InputError(`${path}: expected an object`);
1400
+ const value = input;
1401
+ for (const key of Object.keys(value).sort())
1402
+ if (!allowed.includes(key))
1403
+ throw new InputError(`${path}: unknown field '${key}'`);
1404
+ return value;
1405
+ }
1406
+ function text(input, path) {
1407
+ if (typeof input !== "string" || !input.trim())
1408
+ throw new InputError(`${path}: expected a non-empty string`);
1409
+ return input;
1410
+ }
1411
+ function parseReviewRegistry(input) {
1412
+ const root = object2(input, ["schemaVersion", "projectId", "rules"], "review registry");
1413
+ if (root.schemaVersion !== 1)
1414
+ throw new InputError("review registry.schemaVersion: expected 1");
1415
+ const projectId = Object.hasOwn(root, "projectId") ? identifier(root.projectId, "review registry.projectId") : undefined;
1416
+ if (!Array.isArray(root.rules))
1417
+ throw new InputError("review registry.rules: expected an array");
1418
+ const seen = new Set;
1419
+ const rules = root.rules.map((input2, index) => {
1420
+ const path = `review registry.rules[${index}]`;
1421
+ const entry = object2(input2, ["id", "revision", "contentHash", "owner", "reviewedAt", "reviewBy"], path);
1422
+ const id = identifier(entry.id, `${path}.id`);
1423
+ if (seen.has(id))
1424
+ throw new InputError(`${path}: duplicate ID '${id}'`);
1425
+ seen.add(id);
1426
+ if (!Number.isSafeInteger(entry.revision) || entry.revision < 1)
1427
+ throw new InputError(`${path}.revision: expected a positive safe integer`);
1428
+ const contentHash = text(entry.contentHash, `${path}.contentHash`);
1429
+ if (!/^sha256:[a-f0-9]{64}(?![\s\S])/.test(contentHash))
1430
+ throw new InputError(`${path}.contentHash: expected canonical sha256 reference`);
1431
+ const reviewedAt = timestamp(entry.reviewedAt, `${path}.reviewedAt`);
1432
+ const reviewBy = timestamp(entry.reviewBy, `${path}.reviewBy`);
1433
+ if (reviewBy <= reviewedAt)
1434
+ throw new InputError(`${path}: reviewBy must be later than reviewedAt`);
1435
+ return {
1436
+ id,
1437
+ revision: entry.revision,
1438
+ contentHash,
1439
+ owner: text(entry.owner, `${path}.owner`),
1440
+ reviewedAt: new Date(reviewedAt).toISOString(),
1441
+ reviewBy: new Date(reviewBy).toISOString()
1442
+ };
1443
+ });
1444
+ return {
1445
+ schemaVersion: 1,
1446
+ ...projectId === undefined ? {} : { projectId },
1447
+ rules
1448
+ };
1449
+ }
1450
+ function recordReview(manifest, scope, asOf, owner, reviewBy) {
1451
+ text(owner, "--owner");
1452
+ const explanation = explain(manifest, scope, asOf);
1453
+ const active = new Set(explanation.rules.filter((r) => r.decision === "ACTIVE").map((r) => r.id));
1454
+ if (!active.size)
1455
+ throw new InputError("review-record requires at least one active constraint; no review record created");
1456
+ return parseReviewRegistry({
1457
+ schemaVersion: 1,
1458
+ ...manifest.projectId === undefined ? {} : { projectId: manifest.projectId },
1459
+ rules: manifest.constraints.filter((r) => active.has(r.id)).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((rule) => ({
1460
+ ...reference(rule),
1461
+ owner,
1462
+ reviewedAt: explanation.asOf,
1463
+ reviewBy
1464
+ }))
1465
+ });
1466
+ }
1467
+ function reviewRules(manifest, registry, scope, asOf) {
1468
+ const projectId = checkProject(manifest);
1469
+ if (projectId !== registry.projectId)
1470
+ throw new InputError("Review registry and manifest must have matching project binding (both bound or both unbound)");
1471
+ const explanation = explain(manifest, scope, asOf);
1472
+ const time = timestamp(explanation.asOf, "asOf");
1473
+ const active = new Set(explanation.rules.filter((r) => r.decision === "ACTIVE").map((r) => r.id));
1474
+ const known = new Set(manifest.constraints.map((r) => r.id));
1475
+ const entries = new Map(registry.rules.map((r) => [r.id, r]));
1476
+ const rules = manifest.constraints.filter((r) => active.has(r.id)).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((rule) => {
1477
+ const expected = reference(rule);
1478
+ const entry = entries.get(rule.id);
1479
+ let status;
1480
+ if (!entry)
1481
+ status = "MISSING_REVIEW";
1482
+ else if (entry.revision !== expected.revision || entry.contentHash !== expected.contentHash)
1483
+ status = "STALE_REVIEW";
1484
+ else if (timestamp(entry.reviewedAt, "reviewedAt") > time)
1485
+ status = "FUTURE_REVIEW";
1486
+ else if (timestamp(entry.reviewBy, "reviewBy") <= time)
1487
+ status = "OVERDUE_REVIEW";
1488
+ else
1489
+ status = "CURRENT";
1490
+ return {
1491
+ id: rule.id,
1492
+ status,
1493
+ expected,
1494
+ ...entry ? {
1495
+ recorded: {
1496
+ id: entry.id,
1497
+ revision: entry.revision,
1498
+ contentHash: entry.contentHash
1499
+ },
1500
+ owner: entry.owner,
1501
+ reviewedAt: entry.reviewedAt,
1502
+ reviewBy: entry.reviewBy
1503
+ } : {}
1504
+ };
1505
+ });
1506
+ const findings = [];
1507
+ if (!active.size)
1508
+ findings.push({ code: "NO_ACTIVE_CONSTRAINTS" });
1509
+ for (const rule of rules)
1510
+ if (rule.status !== "CURRENT")
1511
+ findings.push({ code: rule.status, id: rule.id });
1512
+ for (const entry of registry.rules)
1513
+ if (!known.has(entry.id))
1514
+ findings.push({ code: "UNKNOWN_RULE", id: entry.id });
1515
+ findings.sort((a, b) => (a.id ?? "") < (b.id ?? "") ? -1 : (a.id ?? "") > (b.id ?? "") ? 1 : 0);
1516
+ return {
1517
+ schemaVersion: 1,
1518
+ kind: "rule-review",
1519
+ status: findings.length ? "attention" : "current",
1520
+ ...projectId === undefined ? {} : { projectId },
1521
+ scope,
1522
+ asOf: explanation.asOf,
1523
+ activeConstraintCount: active.size,
1524
+ currentReviewCount: rules.filter((r) => r.status === "CURRENT").length,
1525
+ registryEntryCount: registry.rules.length,
1526
+ ignoredEntryCount: registry.rules.filter((r) => known.has(r.id) && !active.has(r.id)).length,
1527
+ rules,
1528
+ findings,
1529
+ notice: "Local maintenance record, not authenticated review or permission. Review deadlines never deactivate constraints or change verify/run results. Known inactive rules are ignored; orphan registry IDs require attention. Record only after reviewing the current rules; never refresh merely to clear findings."
1530
+ };
1531
+ }
1532
+ function reviewText(result, markdown) {
1533
+ const safe = markdown ? markdownText : terminalText;
1534
+ const lines = [
1535
+ markdown ? `# Handoff Check rule review
1536
+ ` : "RULE REVIEW",
1537
+ `${result.status.toUpperCase()} | ${result.currentReviewCount}/${result.activeConstraintCount} active rules have current review | scope ${safe(result.scope)} | as of ${safe(result.asOf)}${result.projectId ? ` | project ${safe(result.projectId)}` : ""}`,
1538
+ `${result.registryEntryCount} registry entries | ${result.ignoredEntryCount} known inactive entries ignored`
1539
+ ];
1540
+ for (const rule of result.rules) {
1541
+ lines.push(`${rule.status} ${safe(rule.id)}${rule.owner === undefined ? "" : ` | owner ${safe(rule.owner)} | reviewed ${safe(rule.reviewedAt ?? "")} | review by ${safe(rule.reviewBy ?? "")}`}`);
1542
+ if (rule.status === "MISSING_REVIEW" || rule.status === "STALE_REVIEW")
1543
+ lines.push(` Current reference: revision ${rule.expected.revision} ${rule.expected.contentHash}`);
1544
+ }
1545
+ for (const finding of result.findings)
1546
+ if (!finding.id || finding.code === "UNKNOWN_RULE")
1547
+ lines.push(`${finding.code}${finding.id ? ` ${safe(finding.id)}` : ""}`);
1548
+ lines.push(safe(result.notice));
1549
+ return `${lines.join(markdown ? `
1550
+
1551
+ ` : `
1552
+ `)}
1553
+ `;
1554
+ }
1555
+
1556
+ // src/review-cli.ts
1557
+ async function reviewCommand(cwd, command, options) {
1558
+ if (options.profile !== undefined && [options.scope, options.constraints].some((v) => v !== undefined))
1559
+ throw new InputError("--profile cannot be combined with --scope or --constraints");
1560
+ for (const key of ["config", "constraints", "registry", "output"])
1561
+ if (options[key] !== undefined && !options[key].trim())
1562
+ throw new InputError(`--${key}: expected a non-empty path`);
1563
+ if (command === "review" && options.registry === undefined)
1564
+ throw new InputError("review requires --registry <review-file>; no review file is discovered implicitly");
1565
+ if (command === "review-record" && (options.owner === undefined || options["review-by"] === undefined))
1566
+ throw new InputError("review-record requires --owner and --review-by after reviewing the current rules");
1567
+ if (command === "review-record" && options.format === "markdown")
1568
+ throw new InputError("review-record supports text or json acknowledgement; its record is always JSON");
1569
+ const loaded = await loadConfig(cwd, options.config, true);
1570
+ const config = selectProfile(loaded.config, options.profile);
1571
+ const scope = identifier(options.scope ?? config.scope, "--scope (or config.scope)");
1572
+ const manifest = parseManifest(await readJson(options.constraints !== undefined ? resolve5(cwd, options.constraints) : resolve5(loaded.directory, config.constraints ?? "constraints.json"), true));
1573
+ checkProject(manifest, undefined, config.projectId);
1574
+ if (command === "review") {
1575
+ const registry = parseReviewRegistry(await readJson(resolve5(cwd, options.registry), true));
1576
+ const asOf2 = options["as-of"] ?? new Date().toISOString();
1577
+ timestamp(asOf2, "--as-of");
1578
+ const result = reviewRules(manifest, registry, scope, asOf2);
1579
+ process.stdout.write(options.format === "json" ? `${JSON.stringify(result, null, 2)}
1580
+ ` : reviewText(result, options.format === "markdown"));
1581
+ return result.status === "current" ? 0 : 1;
1582
+ }
1583
+ const asOf = options["as-of"] ?? new Date().toISOString();
1584
+ timestamp(asOf, "--as-of");
1585
+ const record = recordReview(manifest, scope, asOf, options.owner, options["review-by"]);
1586
+ const content = `${JSON.stringify(record, null, 2)}
1587
+ `;
1588
+ if (options.output === undefined)
1589
+ process.stdout.write(content);
1590
+ else {
1591
+ const path = resolve5(cwd, options.output);
1592
+ let handle;
1593
+ try {
1594
+ handle = await open3(path, "wx", 420);
1595
+ } catch {
1596
+ throw new InputError(`Cannot create review record '${path}'; choose a new file with an existing parent directory`);
1597
+ }
1598
+ try {
1599
+ await handle.writeFile(content, "utf8");
1600
+ } catch {
1601
+ throw new InputError(`Cannot finish review record '${path}'; the new file may be partial. Inspect it before retrying.`);
1602
+ } finally {
1603
+ await handle.close();
1604
+ }
1605
+ process.stdout.write(options.format === "json" ? `${JSON.stringify({ schemaVersion: 1, status: "recorded", path, entries: record.rules.length })}
1606
+ ` : `RECORDED ${terminalText(path)} | ${record.rules.length} reviewed rule references
1607
+ `);
1608
+ }
1609
+ return 0;
1610
+ }
1611
+
1392
1612
  // src/run.ts
1393
1613
  import { spawn } from "node:child_process";
1394
1614
  import { constants as constants3 } from "node:os";
1395
- import { resolve as resolve5 } from "node:path";
1615
+ import { resolve as resolve6 } from "node:path";
1396
1616
  async function runVerified(cwd, options, argv) {
1397
1617
  const executable = argv[0];
1398
1618
  if (!executable?.trim())
@@ -1436,8 +1656,8 @@ async function runVerified(cwd, options, argv) {
1436
1656
  const loaded = await loadConfig(cwd, options.config, true);
1437
1657
  const config = selectProfile(loaded.config, options.profile);
1438
1658
  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));
1659
+ const manifest = parseManifest(await readJson(options.constraints !== undefined ? resolve6(cwd, options.constraints) : resolve6(loaded.directory, config.constraints ?? "constraints.json"), true));
1660
+ const handoff = parseHandoff(await readJson(options.handoff !== undefined ? resolve6(cwd, options.handoff) : resolve6(loaded.directory, config.handoff ?? "handoff.json"), true));
1441
1661
  if (handoff.schemaVersion === 1)
1442
1662
  throw new InputError("run requires a content-aware v2/v3/v4 handoff; review and capture a baseline explicitly");
1443
1663
  const result = verify(manifest, handoff, scope, new Date().toISOString(), {
@@ -1504,8 +1724,8 @@ async function runVerified(cwd, options, argv) {
1504
1724
  }
1505
1725
 
1506
1726
  // src/setup.ts
1507
- import { lstat as lstat3, open as open3, readdir } from "node:fs/promises";
1508
- import { resolve as resolve6 } from "node:path";
1727
+ import { lstat as lstat3, open as open4, readdir } from "node:fs/promises";
1728
+ import { resolve as resolve7 } from "node:path";
1509
1729
  import { createInterface } from "node:readline/promises";
1510
1730
  function setupPlan(answers, asOf) {
1511
1731
  const projectId = identifier(answers.projectId, "Project ID");
@@ -1552,7 +1772,7 @@ async function assertSetupTargets(root, files) {
1552
1772
  if (existing.has(file.path.normalize("NFC").toLowerCase()))
1553
1773
  throw new InputError(`Setup requires new files; target already exists: '${file.path}'.`);
1554
1774
  try {
1555
- await lstat3(resolve6(root, file.path));
1775
+ await lstat3(resolve7(root, file.path));
1556
1776
  } catch (error) {
1557
1777
  if (error.code === "ENOENT")
1558
1778
  continue;
@@ -1566,7 +1786,7 @@ async function writeSetup(root, files) {
1566
1786
  const written = [];
1567
1787
  for (const file of files) {
1568
1788
  try {
1569
- const handle = await open3(resolve6(root, file.path), "wx", 420);
1789
+ const handle = await open4(resolve7(root, file.path), "wx", 420);
1570
1790
  try {
1571
1791
  await handle.writeFile(file.content, "utf8");
1572
1792
  } finally {
@@ -1644,10 +1864,390 @@ Edit and review constraints before relying on them. Never refresh a baseline bef
1644
1864
  }
1645
1865
  }
1646
1866
 
1867
+ // src/source-cli.ts
1868
+ import { open as open6 } from "node:fs/promises";
1869
+ import { resolve as resolve9 } from "node:path";
1870
+
1871
+ // src/source-files.ts
1872
+ import { createHash as createHash3 } from "node:crypto";
1873
+ import { constants as constants4 } from "node:fs";
1874
+ import { lstat as lstat4, open as open5, realpath as realpath2, stat as stat3 } from "node:fs/promises";
1875
+ import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
1876
+
1877
+ // src/sources.ts
1878
+ var sourceLimit = 10 * 1024 * 1024;
1879
+ var bindingLimit = 256;
1880
+ function object3(input, allowed, path) {
1881
+ if (!input || typeof input !== "object" || Array.isArray(input))
1882
+ throw new InputError(`${path}: expected an object`);
1883
+ const value = input;
1884
+ for (const key of Object.keys(value).sort())
1885
+ if (!allowed.includes(key))
1886
+ throw new InputError(`${path}: unknown field '${key}'`);
1887
+ return value;
1888
+ }
1889
+ function hash(input, path) {
1890
+ if (typeof input !== "string" || !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(input))
1891
+ throw new InputError(`${path}: expected canonical sha256 reference`);
1892
+ return input;
1893
+ }
1894
+ function sourcePath(input, path = "source path") {
1895
+ if (typeof input !== "string" || !input || Array.from(input).length > 1024)
1896
+ throw new InputError(`${path}: expected a relative portable path of 1 to 1024 characters`);
1897
+ const parts = input.split("/");
1898
+ if (parts.some((part) => !part || part === "." || part === ".." || Array.from(part).length > 255 || /[\\:*?"<>|\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)))
1899
+ throw new InputError(`${path}: use a portable relative file path without traversal, URLs, reserved names or control characters`);
1900
+ return input;
1901
+ }
1902
+ function root(input, field) {
1903
+ const value = object3(input, [
1904
+ "schemaVersion",
1905
+ "projectId",
1906
+ field,
1907
+ ...field === "sources" ? ["capturedAt"] : []
1908
+ ], "source registry");
1909
+ if (value.schemaVersion !== 1)
1910
+ throw new InputError("source registry.schemaVersion: expected 1");
1911
+ if (!Array.isArray(value[field]) || value[field].length > bindingLimit)
1912
+ throw new InputError(`source registry.${field}: expected an array with at most ${bindingLimit} entries`);
1913
+ const projectId = Object.hasOwn(value, "projectId") ? identifier(value.projectId, "source registry.projectId") : undefined;
1914
+ return { value, ...projectId === undefined ? {} : { projectId } };
1915
+ }
1916
+ function entries(value, retained) {
1917
+ const seen = new Set;
1918
+ return value.map((input, index) => {
1919
+ const path = `source entries[${index}]`;
1920
+ const entry = object3(input, [
1921
+ "id",
1922
+ "path",
1923
+ ...retained ? ["revision", "contentHash", "fileHash"] : []
1924
+ ], path);
1925
+ const id = identifier(entry.id, `${path}.id`);
1926
+ if (seen.has(id))
1927
+ throw new InputError(`${path}: duplicate ID '${id}'`);
1928
+ seen.add(id);
1929
+ return { entry, id, path: sourcePath(entry.path, `${path}.path`) };
1930
+ });
1931
+ }
1932
+ function parseSourcePlan(input) {
1933
+ const { value, projectId } = root(input, "bindings");
1934
+ return {
1935
+ schemaVersion: 1,
1936
+ ...projectId === undefined ? {} : { projectId },
1937
+ bindings: entries(value.bindings, false).map(({ id, path }) => ({ id, path }))
1938
+ };
1939
+ }
1940
+ function parseSourceRegistry(input) {
1941
+ const { value, projectId } = root(input, "sources");
1942
+ const capturedAt = new Date(timestamp(value.capturedAt, "source registry.capturedAt")).toISOString();
1943
+ const sources = entries(value.sources, true).map(({ entry, id, path }) => {
1944
+ if (!Number.isSafeInteger(entry.revision) || entry.revision < 1)
1945
+ throw new InputError(`source '${id}': expected a positive safe revision`);
1946
+ return {
1947
+ id,
1948
+ path,
1949
+ revision: entry.revision,
1950
+ contentHash: hash(entry.contentHash, "contentHash"),
1951
+ fileHash: hash(entry.fileHash, "fileHash")
1952
+ };
1953
+ });
1954
+ return {
1955
+ schemaVersion: 1,
1956
+ ...projectId === undefined ? {} : { projectId },
1957
+ capturedAt,
1958
+ sources
1959
+ };
1960
+ }
1961
+ function selection(manifest, projectId, scope, asOf) {
1962
+ if (checkProject(manifest) !== projectId)
1963
+ throw new InputError("Source metadata and manifest must have matching project binding (both bound or both unbound)");
1964
+ const explanation = explain(manifest, scope, asOf);
1965
+ const active = new Set(explanation.rules.filter((r) => r.decision === "ACTIVE").map((r) => r.id));
1966
+ return {
1967
+ explanation,
1968
+ active,
1969
+ rules: manifest.constraints.filter((r) => active.has(r.id)).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
1970
+ };
1971
+ }
1972
+ function recordSourceTargets(manifest, plan, scope, asOf) {
1973
+ const selected = selection(manifest, plan.projectId, scope, asOf);
1974
+ const known = new Set(manifest.constraints.map((r) => r.id));
1975
+ for (const binding of plan.bindings)
1976
+ if (!known.has(binding.id))
1977
+ throw new InputError(`Source binding '${binding.id}' does not exist in the manifest`);
1978
+ if (!selected.rules.length)
1979
+ throw new InputError("source-record requires at least one active constraint");
1980
+ const paths = new Map(plan.bindings.map((b) => [b.id, b.path]));
1981
+ return selected.rules.map((rule) => {
1982
+ const path = paths.get(rule.id);
1983
+ if (path === undefined)
1984
+ throw new InputError(`Missing explicit source binding for active rule '${rule.id}'`);
1985
+ return { ...reference(rule), path };
1986
+ });
1987
+ }
1988
+ function sourceCheckTargets(manifest, registry, scope, asOf) {
1989
+ const selected = selection(manifest, registry.projectId, scope, asOf);
1990
+ const byId = new Map(registry.sources.map((r) => [r.id, r]));
1991
+ return selected.rules.flatMap((rule) => {
1992
+ const entry = byId.get(rule.id);
1993
+ const expected = reference(rule);
1994
+ return entry && entry.revision === expected.revision && entry.contentHash === expected.contentHash ? [entry] : [];
1995
+ });
1996
+ }
1997
+ function checkSources(manifest, registry, scope, asOf, observed) {
1998
+ const selected = selection(manifest, registry.projectId, scope, asOf);
1999
+ const byId = new Map(registry.sources.map((r) => [r.id, r]));
2000
+ const known = new Set(manifest.constraints.map((r) => r.id));
2001
+ const rules = selected.rules.map((rule) => {
2002
+ const expected = reference(rule);
2003
+ const entry = byId.get(rule.id);
2004
+ if (!entry)
2005
+ return { id: rule.id, expected, status: "MISSING_BINDING" };
2006
+ const base = {
2007
+ id: rule.id,
2008
+ expected,
2009
+ recorded: {
2010
+ id: entry.id,
2011
+ revision: entry.revision,
2012
+ contentHash: entry.contentHash
2013
+ },
2014
+ path: entry.path,
2015
+ expectedFileHash: entry.fileHash
2016
+ };
2017
+ if (entry.revision !== expected.revision || entry.contentHash !== expected.contentHash)
2018
+ return { ...base, status: "STALE_BINDING" };
2019
+ const observation = observed.get(entry.path);
2020
+ if (!observation)
2021
+ throw new InputError(`Missing source observation for '${rule.id}'`);
2022
+ if (observation.status !== "READ")
2023
+ return { ...base, status: observation.status };
2024
+ return {
2025
+ ...base,
2026
+ status: observation.fileHash === entry.fileHash ? "UNCHANGED" : "SOURCE_CHANGED",
2027
+ observedFileHash: observation.fileHash,
2028
+ observedBytes: observation.bytes
2029
+ };
2030
+ });
2031
+ const findings = [];
2032
+ if (!rules.length)
2033
+ findings.push({ code: "NO_ACTIVE_CONSTRAINTS" });
2034
+ for (const rule of rules)
2035
+ if (rule.status !== "UNCHANGED")
2036
+ findings.push({ id: rule.id, code: rule.status });
2037
+ for (const entry of registry.sources)
2038
+ if (!known.has(entry.id))
2039
+ findings.push({ id: entry.id, code: "UNKNOWN_RULE" });
2040
+ findings.sort((a, b) => (a.id ?? "") < (b.id ?? "") ? -1 : (a.id ?? "") > (b.id ?? "") ? 1 : 0);
2041
+ return {
2042
+ schemaVersion: 1,
2043
+ kind: "source-check",
2044
+ status: findings.length ? "attention" : "unchanged",
2045
+ ...manifest.projectId === undefined ? {} : { projectId: manifest.projectId },
2046
+ scope,
2047
+ asOf: selected.explanation.asOf,
2048
+ activeConstraintCount: rules.length,
2049
+ unchangedSourceCount: rules.filter((r) => r.status === "UNCHANGED").length,
2050
+ registryEntryCount: registry.sources.length,
2051
+ ignoredEntryCount: registry.sources.filter((r) => known.has(r.id) && !selected.active.has(r.id)).length,
2052
+ rules,
2053
+ findings,
2054
+ notice: "Explicit local whole-file byte comparison, not semantic policy validation, authenticated history or authorization. File changes signal review needed; no constraints or baselines are refreshed. Known inactive/stale bindings are not read. Other verification commands do not load this registry. Reads and filesystem checks are not an atomic sandbox against concurrent changes."
2055
+ };
2056
+ }
2057
+ function sourceText(result, markdown) {
2058
+ const safe = markdown ? markdownText : terminalText;
2059
+ const lines = [
2060
+ markdown ? `# Handoff Check local sources
2061
+ ` : "SOURCE CHECK",
2062
+ `${result.status.toUpperCase()} | ${result.unchangedSourceCount}/${result.activeConstraintCount} active rule sources unchanged | scope ${safe(result.scope)} | as of ${safe(result.asOf)}${result.projectId ? ` | project ${safe(result.projectId)}` : ""}`,
2063
+ `${result.registryEntryCount} registry entries | ${result.ignoredEntryCount} known inactive entries ignored`
2064
+ ];
2065
+ for (const rule of result.rules)
2066
+ lines.push(`${rule.status} ${safe(rule.id)}${rule.path ? ` | ${safe(rule.path)}` : ""}${rule.observedFileHash ? ` | ${rule.observedFileHash}` : ""}`);
2067
+ for (const finding of result.findings)
2068
+ if (!finding.id || finding.code === "UNKNOWN_RULE")
2069
+ lines.push(`${finding.code}${finding.id ? ` ${safe(finding.id)}` : ""}`);
2070
+ lines.push(safe(result.notice));
2071
+ return `${lines.join(markdown ? `
2072
+
2073
+ ` : `
2074
+ `)}
2075
+ `;
2076
+ }
2077
+
2078
+ // src/source-files.ts
2079
+ async function sourceRoot(directory) {
2080
+ try {
2081
+ const root2 = await realpath2(directory);
2082
+ if (!(await stat3(root2)).isDirectory())
2083
+ throw new Error("not directory");
2084
+ return root2;
2085
+ } catch {
2086
+ throw new InputError("Cannot resolve source project directory");
2087
+ }
2088
+ }
2089
+ function inside(root2, path) {
2090
+ const value = relative3(root2, path);
2091
+ return value !== "" && value !== ".." && !value.startsWith(`..${sep3}`) && !isAbsolute3(value);
2092
+ }
2093
+ async function readSourceFile(root2, path) {
2094
+ try {
2095
+ sourcePath(path);
2096
+ } catch {
2097
+ return { status: "SOURCE_UNSAFE" };
2098
+ }
2099
+ let handle;
2100
+ const observation = await (async () => {
2101
+ try {
2102
+ let current = root2;
2103
+ const parts = path.split("/");
2104
+ let before;
2105
+ for (const [index, part] of parts.entries()) {
2106
+ current = resolve8(current, part);
2107
+ if (!inside(root2, current))
2108
+ return { status: "SOURCE_UNSAFE" };
2109
+ const info2 = await lstat4(current);
2110
+ if (info2.isSymbolicLink() || (index < parts.length - 1 ? !info2.isDirectory() : !info2.isFile()))
2111
+ return { status: "SOURCE_UNSAFE" };
2112
+ before = info2;
2113
+ }
2114
+ const resolved = await realpath2(current);
2115
+ if (!inside(root2, resolved))
2116
+ return { status: "SOURCE_UNSAFE" };
2117
+ handle = await open5(current, constants4.O_RDONLY | (constants4.O_NONBLOCK ?? 0) | (constants4.O_NOFOLLOW ?? 0));
2118
+ const info = await handle.stat();
2119
+ if (!info.isFile() || !before || info.dev !== before.dev || info.ino !== before.ino)
2120
+ return { status: "SOURCE_UNSAFE" };
2121
+ if (info.size > sourceLimit)
2122
+ return { status: "SOURCE_TOO_LARGE" };
2123
+ const hash2 = createHash3("sha256");
2124
+ const buffer = Buffer.alloc(64 * 1024);
2125
+ let bytes = 0;
2126
+ while (true) {
2127
+ const read = await handle.read(buffer, 0, Math.min(buffer.length, sourceLimit - bytes + 1), bytes);
2128
+ if (!read.bytesRead)
2129
+ break;
2130
+ bytes += read.bytesRead;
2131
+ if (bytes > sourceLimit)
2132
+ return { status: "SOURCE_TOO_LARGE" };
2133
+ hash2.update(buffer.subarray(0, read.bytesRead));
2134
+ }
2135
+ return {
2136
+ status: "READ",
2137
+ fileHash: `sha256:${hash2.digest("hex")}`,
2138
+ bytes
2139
+ };
2140
+ } catch (error) {
2141
+ const code = error.code;
2142
+ return {
2143
+ status: code === "ENOENT" ? "SOURCE_MISSING" : code === "ELOOP" || code === "ENOTDIR" ? "SOURCE_UNSAFE" : "SOURCE_UNREADABLE"
2144
+ };
2145
+ }
2146
+ })();
2147
+ if (handle) {
2148
+ try {
2149
+ await handle.close();
2150
+ } catch {
2151
+ return { status: "SOURCE_UNREADABLE" };
2152
+ }
2153
+ }
2154
+ return observation;
2155
+ }
2156
+ async function readSourceTargets(directory, targets) {
2157
+ const result = new Map;
2158
+ if (!targets.length)
2159
+ return result;
2160
+ const root2 = await sourceRoot(directory);
2161
+ for (const target of targets)
2162
+ if (!result.has(target.path))
2163
+ result.set(target.path, await readSourceFile(root2, target.path));
2164
+ return result;
2165
+ }
2166
+
2167
+ // src/source-cli.ts
2168
+ async function sourceCommand(cwd, command, options) {
2169
+ if (options.profile !== undefined && [options.scope, options.constraints].some((v) => v !== undefined))
2170
+ throw new InputError("--profile cannot be combined with --scope or --constraints");
2171
+ for (const key of [
2172
+ "config",
2173
+ "constraints",
2174
+ "bindings",
2175
+ "sources",
2176
+ "output"
2177
+ ])
2178
+ if (options[key] !== undefined && !options[key].trim())
2179
+ throw new InputError(`--${key}: expected a non-empty path`);
2180
+ const input = command === "source-check" ? options.sources : options.bindings;
2181
+ if (input === undefined)
2182
+ throw new InputError(command === "source-check" ? "source-check requires --sources <registry-file>" : "source-record requires --bindings <binding-plan> after reviewing the explicit local files");
2183
+ if (command === "source-record" && options.format === "markdown")
2184
+ throw new InputError("source-record supports text or json acknowledgement; its record is always JSON");
2185
+ const loaded = await loadConfig(cwd, options.config, true);
2186
+ const config = selectProfile(loaded.config, options.profile);
2187
+ const scope = identifier(options.scope ?? config.scope, "--scope (or config.scope)");
2188
+ const manifest = parseManifest(await readJson(options.constraints === undefined ? resolve9(loaded.directory, config.constraints ?? "constraints.json") : resolve9(cwd, options.constraints), true));
2189
+ checkProject(manifest, undefined, config.projectId);
2190
+ const metadata = await readJson(resolve9(cwd, input), true);
2191
+ const asOf = options["as-of"] ?? new Date().toISOString();
2192
+ timestamp(asOf, "--as-of");
2193
+ if (command === "source-check") {
2194
+ const registry2 = parseSourceRegistry(metadata);
2195
+ const targets2 = sourceCheckTargets(manifest, registry2, scope, asOf);
2196
+ const observed2 = await readSourceTargets(loaded.directory, targets2);
2197
+ const result = checkSources(manifest, registry2, scope, asOf, observed2);
2198
+ process.stdout.write(options.format === "json" ? `${JSON.stringify(result, null, 2)}
2199
+ ` : sourceText(result, options.format === "markdown"));
2200
+ return result.status === "unchanged" ? 0 : 1;
2201
+ }
2202
+ const plan = parseSourcePlan(metadata);
2203
+ const targets = recordSourceTargets(manifest, plan, scope, asOf);
2204
+ const observed = await readSourceTargets(loaded.directory, targets);
2205
+ const sources = targets.map((target) => {
2206
+ const observation = observed.get(target.path);
2207
+ if (observation?.status !== "READ")
2208
+ throw new InputError(`Cannot record source for '${target.id}': ${observation?.status ?? "SOURCE_UNREADABLE"}; no record created`);
2209
+ return { ...target, fileHash: observation.fileHash };
2210
+ });
2211
+ const registry = parseSourceRegistry({
2212
+ schemaVersion: 1,
2213
+ ...manifest.projectId === undefined ? {} : { projectId: manifest.projectId },
2214
+ capturedAt: asOf,
2215
+ sources
2216
+ });
2217
+ const content = `${JSON.stringify(registry, null, 2)}
2218
+ `;
2219
+ if (options.output === undefined)
2220
+ process.stdout.write(content);
2221
+ else {
2222
+ const path = resolve9(cwd, options.output);
2223
+ let handle;
2224
+ try {
2225
+ handle = await open6(path, "wx", 420);
2226
+ } catch {
2227
+ throw new InputError(`Cannot create source record '${path}'; choose a new file with an existing parent directory`);
2228
+ }
2229
+ try {
2230
+ await handle.writeFile(content, "utf8");
2231
+ } catch {
2232
+ throw new InputError(`Cannot finish source record '${path}'; the new file may be partial. Inspect it before retrying.`);
2233
+ } finally {
2234
+ await handle.close();
2235
+ }
2236
+ process.stdout.write(options.format === "json" ? `${JSON.stringify({ schemaVersion: 1, status: "recorded", path, entries: registry.sources.length })}
2237
+ ` : `RECORDED ${terminalText(path)} | ${registry.sources.length} local source references
2238
+ `);
2239
+ }
2240
+ return 0;
2241
+ }
2242
+
1647
2243
  // src/cli.ts
1648
2244
  var help = `Handoff Check
1649
2245
 
1650
2246
  Usage: handoff-check verify --scope <scope> [options]
2247
+ handoff-check source-check --sources <source-registry> [options]
2248
+ handoff-check source-record --bindings <binding-plan> [--output <new-file>] [options]
2249
+ handoff-check review --registry <review-file> [--profile <name>] [--format text|json|markdown]
2250
+ handoff-check review-record --owner <owner> --review-by <UTC time> [--output <new-file>] [options]
1651
2251
  handoff-check run [--profile <name> | --scope <scope>] [--config <path>] -- <executable> [args...]
1652
2252
  handoff-check diff --before <snapshot> --after <snapshot> [--format text|json|markdown]
1653
2253
  handoff-check setup [--dry-run]
@@ -1659,6 +2259,11 @@ Usage: handoff-check verify --scope <scope> [options]
1659
2259
  handoff-check hook --host claude --config <absolute-path> [--require-active]
1660
2260
 
1661
2261
  Options:
2262
+ --sources <path> source-check: explicit local-source registry (cwd relative)
2263
+ --bindings <path> source-record: explicit rule/path binding plan (cwd relative)
2264
+ --registry <path> review: explicit review registry (resolved from cwd)
2265
+ --owner <owner> review-record: owner of explicitly reviewed active rules
2266
+ --review-by <UTC> review-record: review deadline, later than capture time
1662
2267
  --before <path> diff: saved snapshot before the change
1663
2268
  --after <path> diff: saved snapshot after the change
1664
2269
  --constraints <path> Manifest file (default: constraints.json)
@@ -1672,9 +2277,9 @@ Options:
1672
2277
  --require-content verify: require a v2/v3/v4 content-aware handoff
1673
2278
  --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
1674
2279
  --task <task> snapshot: task description (required)
1675
- --output <path> snapshot: create a new baseline file, never overwrite
2280
+ --output <path> snapshot/review-record/source-record: new file, never overwrite
1676
2281
  --include-content snapshot: retain old rule text in unbound v3/bound v4 (opt-in)
1677
- --format text|json|markdown Markdown is verify/explain/diff-only (default: text)
2282
+ --format text|json|markdown Markdown: verify/explain/diff/review/source-check (default: text)
1678
2283
  --agent <agent> init: codex, claude, both (default), or none
1679
2284
  --host <host> doctor: integration target; hook/hook-config: claude
1680
2285
  --dry-run init/setup: preview proposed files without writes
@@ -1683,6 +2288,8 @@ Options:
1683
2288
  --help Show this help
1684
2289
 
1685
2290
  Exit codes: verify 0 verified / 1 mismatch; diff 0 unchanged / 1 different; doctor 0 healthy / 1 attention.
2291
+ Review: 0 current maintenance / 1 attention (including zero active); never changes verify/run policy.
2292
+ Source-check: 0 unchanged / 1 attention (including zero active); no implicit source reads by verify/run.
1686
2293
  Run: mandatory content/nonempty/current-clock preflight; 1 blocked / 2 invalid or launch error.
1687
2294
  After launch run returns the child exit code (or 128 + signal); diagnostics use stderr.
1688
2295
  Hook 0 means advisory response delivered (may report FAIL/INVALID), not verified.
@@ -1721,7 +2328,12 @@ async function main() {
1721
2328
  task: { type: "string" },
1722
2329
  output: { type: "string" },
1723
2330
  before: { type: "string" },
1724
- after: { type: "string" }
2331
+ after: { type: "string" },
2332
+ registry: { type: "string" },
2333
+ owner: { type: "string" },
2334
+ "review-by": { type: "string" },
2335
+ sources: { type: "string" },
2336
+ bindings: { type: "string" }
1725
2337
  }
1726
2338
  });
1727
2339
  format = values.format;
@@ -1746,11 +2358,49 @@ async function main() {
1746
2358
  "hook-config",
1747
2359
  "diff",
1748
2360
  "setup",
1749
- "run"
2361
+ "run",
2362
+ "review",
2363
+ "review-record",
2364
+ "source-check",
2365
+ "source-record"
1750
2366
  ].includes(positionals[0] ?? ""))
1751
- throw new InputError("Expected command: verify, snapshot, explain, init, setup, diff, run, doctor, hook or hook-config (use --help for usage)");
2367
+ throw new InputError("Expected command: verify, snapshot, explain, init, setup, diff, run, review, review-record, source-check, source-record, doctor, hook or hook-config (use --help for usage)");
1752
2368
  const cwd = process.cwd();
1753
2369
  const command = positionals[0];
2370
+ if (command === "source-check" || command === "source-record") {
2371
+ const allowed = [
2372
+ "config",
2373
+ "profile",
2374
+ "scope",
2375
+ "constraints",
2376
+ "as-of",
2377
+ "format",
2378
+ ...command === "source-check" ? ["sources"] : ["bindings", "output"]
2379
+ ];
2380
+ for (const key of Object.keys(values))
2381
+ if (!allowed.includes(key))
2382
+ throw new InputError(`--${key} is not supported by ${command}`);
2383
+ return await sourceCommand(cwd, command, values);
2384
+ }
2385
+ if (values.sources !== undefined || values.bindings !== undefined)
2386
+ throw new InputError("--sources and --bindings are source-check/source-record-only");
2387
+ if (command === "review" || command === "review-record") {
2388
+ const allowed = [
2389
+ "config",
2390
+ "profile",
2391
+ "scope",
2392
+ "constraints",
2393
+ "as-of",
2394
+ "format",
2395
+ ...command === "review" ? ["registry"] : ["owner", "review-by", "output"]
2396
+ ];
2397
+ for (const key of Object.keys(values))
2398
+ if (!allowed.includes(key))
2399
+ throw new InputError(`--${key} is not supported by ${command}`);
2400
+ return await reviewCommand(cwd, command, values);
2401
+ }
2402
+ if (values.registry !== undefined || values.owner !== undefined || values["review-by"] !== undefined)
2403
+ throw new InputError("--registry, --owner and --review-by are review/review-record-only");
1754
2404
  if (command === "run") {
1755
2405
  if (!runCommand || separator < 0)
1756
2406
  throw new InputError("Use run as the first argument and include -- <executable> [arguments...]");
@@ -1777,8 +2427,8 @@ async function main() {
1777
2427
  }
1778
2428
  if (!values.before?.trim() || !values.after?.trim())
1779
2429
  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);
2430
+ const before = parseHandoff((await readJsonRecord(resolve10(cwd, values.before))).input);
2431
+ const after = parseHandoff((await readJsonRecord(resolve10(cwd, values.after))).input);
1782
2432
  const result2 = diffSnapshots(before, after);
1783
2433
  process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
1784
2434
  ` : diffText(result2, format === "markdown"));
@@ -1929,7 +2579,7 @@ ${result2.notice}
1929
2579
  for (const key of ["constraints", "handoff", "config"])
1930
2580
  if (values[key] !== undefined && !values[key].trim())
1931
2581
  throw new InputError(`--${key}: expected a non-empty path`);
1932
- const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve7(cwd, values.constraints) : resolve7(directory, config.constraints ?? "constraints.json"));
2582
+ const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve10(cwd, values.constraints) : resolve10(directory, config.constraints ?? "constraints.json"));
1933
2583
  const manifest = parseManifest(manifestRecord.input);
1934
2584
  checkProject(manifest, undefined, config.projectId);
1935
2585
  if (command === "explain") {
@@ -1954,10 +2604,10 @@ ${result2.notice}
1954
2604
  else {
1955
2605
  if (!values.output.trim())
1956
2606
  throw new InputError("--output: expected a non-empty path");
1957
- const path = resolve7(cwd, values.output);
2607
+ const path = resolve10(cwd, values.output);
1958
2608
  let handle;
1959
2609
  try {
1960
- handle = await open4(path, "wx", 420);
2610
+ handle = await open7(path, "wx", 420);
1961
2611
  } catch {
1962
2612
  throw new InputError(`Cannot create snapshot '${path}'; choose a new file with an existing parent directory`);
1963
2613
  }
@@ -1980,7 +2630,7 @@ ${result2.notice}
1980
2630
  }
1981
2631
  if (values.task !== undefined || values.output !== undefined)
1982
2632
  throw new InputError("--task and --output are only supported by snapshot");
1983
- const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve7(cwd, values.handoff) : resolve7(directory, config.handoff ?? "handoff.json"));
2633
+ const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve10(cwd, values.handoff) : resolve10(directory, config.handoff ?? "handoff.json"));
1984
2634
  const handoff = parseHandoff(handoffRecord.input);
1985
2635
  if (values["require-content"] && handoff.schemaVersion === 1)
1986
2636
  throw new InputError("Content tracking requires a schemaVersion 2, 3 or 4 handoff; review current rules and capture a snapshot before resuming");