@holmes-lab/holmes-kit 0.40.1 → 0.41.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +11 -3
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-context.js +4 -3
  5. package/dist/holmes/cli/approve.js +22 -12
  6. package/dist/holmes/cli/autonomy.d.ts +21 -0
  7. package/dist/holmes/cli/autonomy.js +35 -5
  8. package/dist/holmes/cli/doctor.js +58 -6
  9. package/dist/holmes/cli/index.js +371 -250
  10. package/dist/holmes/cli/init.js +17 -6
  11. package/dist/holmes/cli/ledger-witness.d.ts +61 -0
  12. package/dist/holmes/cli/ledger-witness.js +212 -0
  13. package/dist/holmes/cli/playbook-skills.d.ts +3 -56
  14. package/dist/holmes/cli/playbook-skills.js +26 -349
  15. package/dist/holmes/config/config.d.ts +4 -0
  16. package/dist/holmes/config/config.js +10 -3
  17. package/dist/holmes/governance/approval-queue.d.ts +65 -1
  18. package/dist/holmes/governance/approval-queue.js +279 -9
  19. package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
  20. package/dist/holmes/governance/autonomous-shell.js +157 -4
  21. package/dist/holmes/governance/autonomy.d.ts +209 -0
  22. package/dist/holmes/governance/autonomy.js +1127 -6
  23. package/dist/holmes/governance/install-manifest.d.ts +7 -4
  24. package/dist/holmes/governance/install-manifest.js +144 -14
  25. package/dist/holmes/governance/ledger-witness.d.ts +63 -0
  26. package/dist/holmes/governance/ledger-witness.js +296 -0
  27. package/dist/holmes/governance/provenance-chain.d.ts +8 -1
  28. package/dist/holmes/governance/provenance-chain.js +23 -4
  29. package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
  30. package/dist/holmes/governance/recorded-pairs.js +25 -1
  31. package/dist/holmes/governance/session-context.d.ts +7 -0
  32. package/dist/holmes/governance/session-context.js +34 -6
  33. package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
  34. package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
  35. package/dist/holmes/guardrail/command-traits.d.ts +102 -0
  36. package/dist/holmes/guardrail/command-traits.js +379 -0
  37. package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
  38. package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
  39. package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
  40. package/dist/holmes/guardrail/outward-acts.js +1102 -0
  41. package/dist/holmes/guardrail/refusal-codes.js +8 -1
  42. package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
  43. package/dist/holmes/guardrail/refusal-templates.js +71 -0
  44. package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
  45. package/dist/holmes/guardrail/risk-classifier.js +12 -118
  46. package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
  47. package/dist/holmes/guardrail/shell-lexer.js +567 -0
  48. package/dist/holmes/guardrail/write-target.js +7 -1
  49. package/dist/holmes/hooks/pre-tool-use.d.ts +60 -0
  50. package/dist/holmes/hooks/pre-tool-use.js +1423 -10
  51. package/dist/holmes/hooks/session-start.js +11 -1
  52. package/dist/holmes/hooks/stop.d.ts +7 -0
  53. package/dist/holmes/hooks/stop.js +39 -2
  54. package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
  55. package/dist/holmes/mcp/elicit-approval.js +5 -2
  56. package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
  57. package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
  58. package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
  59. package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
  60. package/dist/holmes/mcp/handlers/entity-store.js +7 -2
  61. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
  62. package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
  63. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
  64. package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
  65. package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
  66. package/dist/holmes/mcp/handlers/test-execution.js +4 -2
  67. package/dist/holmes/mcp/handlers.d.ts +5 -5
  68. package/dist/holmes/mcp/handlers.js +2 -1
  69. package/dist/holmes/mcp/tool-schemas.js +4 -4
  70. package/dist/holmes/project/playbook-reference.d.ts +50 -0
  71. package/dist/holmes/project/playbook-reference.js +259 -0
  72. package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
  73. package/dist/holmes/project/playbook-skill-states.js +396 -0
  74. package/dist/holmes/project/root.d.ts +9 -1
  75. package/dist/holmes/project/root.js +23 -2
  76. package/dist/holmes/project/running-package.d.ts +15 -0
  77. package/dist/holmes/project/running-package.js +87 -0
  78. package/dist/holmes/review/test-runner.d.ts +2 -0
  79. package/dist/holmes/review/test-runner.js +27 -10
  80. package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
  81. package/dist/holmes/spec/entity-integration-transaction.js +68 -7
  82. package/package.json +5 -2
@@ -37,7 +37,7 @@ exports.isBrokenPipe = void 0;
37
37
  exports.packageRoot = packageRoot;
38
38
  exports.main = main;
39
39
  exports.installPipeGuard = installPipeGuard;
40
- // @implements A-SPEC-552.4, A-SPEC-552.3, A-SPEC-794.59, A-SPEC-794.58, A-SPEC-794.55, A-SPEC-794.43, A-SPEC-794.42, A-SPEC-794.41, A-SPEC-794.36, A-SPEC-792.48, A-SPEC-792.49, A-SPEC-704, A-SPEC-773, A-SPEC-770.11,A-SPEC-709, A-SPEC-734,A-SPEC-751, A-SPEC-752, A-SPEC-772.4, A-SPEC-779, A-SPEC-102.2, A-SPEC-774.20, A-SPEC-102.7, A-SPEC-779.2, A-SPEC-792.3, A-SPEC-102.10, A-SPEC-102.12, A-SPEC-774.34, A-SPEC-794.30, A-SPEC-794.32, A-SPEC-794.33, A-SPEC-102.29, A-SPEC-102.30, A-SPEC-102.31
40
+ // @implements A-SPEC-794.91, A-SPEC-794.83, A-SPEC-552.4, A-SPEC-552.3, A-SPEC-794.59, A-SPEC-794.58, A-SPEC-794.55, A-SPEC-794.43, A-SPEC-794.42, A-SPEC-794.41, A-SPEC-794.36, A-SPEC-792.48, A-SPEC-792.49, A-SPEC-704, A-SPEC-773, A-SPEC-770.11,A-SPEC-709, A-SPEC-734,A-SPEC-751, A-SPEC-752, A-SPEC-772.4, A-SPEC-779, A-SPEC-102.2, A-SPEC-774.20, A-SPEC-102.7, A-SPEC-779.2, A-SPEC-792.3, A-SPEC-102.10, A-SPEC-102.12, A-SPEC-774.34, A-SPEC-794.30, A-SPEC-794.32, A-SPEC-794.33, A-SPEC-102.29, A-SPEC-102.30, A-SPEC-102.31
41
41
  // @implements A-SPEC-549.2
42
42
  // @implements A-SPEC-591, A-SPEC-626
43
43
  const cli_execution_1 = require("./cli-execution");
@@ -161,7 +161,8 @@ const USAGE = `holmes-kit — deterministic ASE governance for a project
161
161
  HOLMES_SKIP_MODEL_INSTALL=1 in the environment: skip the automatic BGE-M3 download init starts
162
162
  (offline or CI); holmes-kit semantic-setup prepares it later
163
163
 
164
- holmes-kit ledger rechain re-chain forked ledger files against the committed mainline
164
+ holmes-kit ledger rechain re-chain forked ledger files against the committed mainline (a person approves the plan; --dry-run is free)
165
+ holmes-kit ledger witness vouch for this repository's provenance chain as it is (a person decides it in the session's approval form)
165
166
  --target <dir> project to repair (default: cwd)
166
167
  --ref <git-ref> mainline ref (default: HEAD; walks first-parent to the first
167
168
  verifying committed version)
@@ -327,7 +328,7 @@ async function main(argv, deps = {}) {
327
328
  }
328
329
  // Positionals these commands do not take are refused, not dropped: `skills refresh <dir>`
329
330
  // silently wrote into CWD while the named target stayed stale (round-3 HIGH).
330
- const expected = cmd === 'runtime-binding' ? ['setup', 'status', 'remove'] : cmd === 'guidance' ? ['check', 'refresh'] : cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain']
331
+ const expected = cmd === 'runtime-binding' ? ['setup', 'status', 'remove'] : cmd === 'guidance' ? ['check', 'refresh'] : cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain', 'witness'] // A-SPEC-794.114: witness
331
332
  : cmd === 'semantic-key' ? ['set', 'unset', 'status']
332
333
  : cmd === 'autonomy' ? ['status', 'on', 'off', 'delegate', 'revoke-delegation', 'full'] // @implements A-SPEC-771.1, A-SPEC-792.3
333
334
  : cmd === 'roles' ? ['migrate'] // @implements A-SPEC-774.10
@@ -477,7 +478,16 @@ async function main(argv, deps = {}) {
477
478
  const { resolveApproval } = require('../governance/approval-grants');
478
479
  const { enqueueApprovalRequest } = require('../governance/approval-queue');
479
480
  const askRoot = askingRoot(); // A-SPEC-102.31 — through actRoot, the one decision
480
- const v = fullProfileGate({ scope, askRoot, flags: fullFlags, now, envApproval: approval }, {
481
+ // A-SPEC-794.83 — the profile covering the scope now, so the form names what this request changes
482
+ const { readFullProfile } = require('../governance/full-autonomy');
483
+ const covering = (() => { try {
484
+ const s = readFullProfile(home, scope);
485
+ return s.active ? s.entry.flags : null;
486
+ }
487
+ catch {
488
+ return null;
489
+ } })();
490
+ const v = fullProfileGate({ scope, askRoot, flags: fullFlags, now, envApproval: approval, current: covering }, {
481
491
  // A-SPEC-102.30 — the union of what the profile covers: the scope's project, the working directory's, every
482
492
  // project under the scope (a scope above a project skipped its additions); a search it cannot finish refuses
483
493
  guard: () => {
@@ -563,14 +573,14 @@ async function main(argv, deps = {}) {
563
573
  spend = { root: askRoot, nonce: v.spend };
564
574
  }
565
575
  else if (sub === 'delegate') {
566
- const { approvalCovers } = require('../guardrail/risk-gate');
567
- if (!approvalCovers(approval, { kind: 'autonomy-grant', target: root }, now)) {
568
- const why = operatorActGuard('issuing a run delegation', root); // A-SPEC-102.29 — the project it delegates
569
- if (why !== null) {
570
- process.stderr.write(`${withRefusalLine(why, 'grant.operator-only')}\n`);
571
- return 2;
572
- } // A-SPEC-245.25
573
- }
576
+ // @implements A-SPEC-794.91 — the operator guard first, whatever approval the environment carries (an environment
577
+ // approval let an agent ancestor issue a 7-day delegation)
578
+ const { autonomyWideningGate } = require('./autonomy');
579
+ const w = autonomyWideningGate({ kind: 'autonomy-delegate', envApproval: approval }, { guard: () => operatorActGuard('issuing a run delegation', root) }); // A-SPEC-102.29 — the project it delegates
580
+ if (!w.proceed) {
581
+ process.stderr.write(`${withRefusalLine(w.why ?? 'issuing a run delegation is the operator\'s', 'grant.operator-only')}\n`);
582
+ return 2;
583
+ } // A-SPEC-245.25
574
584
  }
575
585
  // @implements A-SPEC-245.4 — the act runs inside the grant's claim: committed when it succeeds, returned otherwise
576
586
  const { claimGrant, spendGrantApprovals, GrantSpendRefusal } = require('../governance/approval-grants');
@@ -816,6 +826,37 @@ async function main(argv, deps = {}) {
816
826
  // @implements A-SPEC-256.1 — re-chain forked ledgers against an EXPLICIT mainline (a named git
817
827
  // ref, default HEAD). Greedy mainline selection is the measured trap this command refuses to be.
818
828
  if (cmd === 'ledger') {
829
+ const { withRefusalLine } = require('../guardrail/refusal-codes');
830
+ // @implements A-SPEC-794.114 — a person vouches for this repository's provenance chain as it is (cli/ledger-witness.ts)
831
+ if (positionals[0] === 'witness') {
832
+ const root = typeof flags.target === 'string' ? path.resolve(flags.target) : process.cwd();
833
+ const lw = require('./ledger-witness');
834
+ const { resolveApproval } = require('../governance/approval-grants');
835
+ const { enqueueApprovalRequest } = require('../governance/approval-queue');
836
+ const { operatorActGuard } = require('../guardrail/operator-person');
837
+ const w = require('../governance/ledger-witness');
838
+ const { writerChainFile } = require('../governance/ledger-store');
839
+ const now = new Date().toISOString();
840
+ const facts = lw.ledgerWitnessFacts(root);
841
+ const v = lw.ledgerWitnessGate({ root, askRoot: root, now }, {
842
+ guard: () => operatorActGuard('vouching for the provenance chain', root),
843
+ resolve: (r, env, action, n) => resolveApproval(r, env, action, n),
844
+ enqueue: (r, req) => { enqueueApprovalRequest(r, req); },
845
+ });
846
+ if (!v.proceed) {
847
+ process.stderr.write(`${facts.text}\n\n${withRefusalLine(v.message, 'grant.operator-only')}\n`);
848
+ return 2;
849
+ }
850
+ try {
851
+ const head = lw.underGrant(root, v, `ledger witness ${root}`, () => w.vouch(writerChainFile(path.join(root, '.ax', 'ledger')), { sha256: facts.subject.slice('head='.length) }));
852
+ process.stdout.write(`${facts.text}\n\nvouched: this repository's chain is the one it wrote, at row ${head.seq + 1} (sha256 ${head.sha256.slice(0, 16)}…)\n`);
853
+ return 0;
854
+ }
855
+ catch (e) {
856
+ process.stderr.write(`[Holmes-Kit] ${e.message}\n`);
857
+ return 1;
858
+ }
859
+ }
819
860
  if (positionals[0] !== 'rechain') {
820
861
  process.stderr.write(`unknown ledger subcommand\n\n${USAGE}`);
821
862
  return 2;
@@ -873,278 +914,345 @@ async function main(argv, deps = {}) {
873
914
  process.stdout.write('no ledger files — nothing to rechain.\n');
874
915
  return 0;
875
916
  }
876
- // STRICT parse (round-9): a torn TAIL is tolerated, but mid-file corruption or a non-object line
877
- // throws — the repair tool must not drop a line and then 'fix' the seq gap, making the loss
878
- // permanent and invisible to verify().
879
- const parse = (raw, file) => parseLedgerLines(raw, file, { throwOnCorruption: true });
880
- // The first-parent commit list is the SAME for every file (one ref), so resolve it ONCE outside
881
- // the loop (round-9: it was re-run per file).
882
- const WALK_LIMIT = 64;
883
- let walkCommits = [];
884
- try {
885
- walkCommits = execFileSync('git', ['-C', root, 'rev-list', '--first-parent', '-n', String(WALK_LIMIT), ref], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] })
886
- .split('\n').map((l) => l.trim()).filter(Boolean);
887
- }
888
- catch (e) {
889
- // A rev-list failure (the ref was already rev-parse-verified) is a real git error, not an
890
- // empty history — surface it rather than degrading every file to a false 'no mainline'
891
- // (round-12).
892
- process.stderr.write(`git rev-list failed — cannot enumerate history: ${e.message.split('\n')[0]}\n`);
893
- return 1;
917
+ // @implements A-SPEC-794.114 — a rechain rewrites the chain wholesale: it applies only to a plan a person approved in
918
+ // the session form (or at their own terminal). The plan is the resolved ref and each chain file's digest now, so a
919
+ // grant for one state of the ledger covers no other. --dry-run needs no approval.
920
+ let rechainGrant = null;
921
+ if (!dry) {
922
+ const lw = require('./ledger-witness');
923
+ const w = require('../governance/ledger-witness');
924
+ const { resolveApproval } = require('../governance/approval-grants');
925
+ const { enqueueApprovalRequest } = require('../governance/approval-queue');
926
+ const { operatorActGuard } = require('../guardrail/operator-person');
927
+ let resolved = ref;
928
+ try {
929
+ resolved = execFileSync('git', ['-C', root, 'rev-parse', '--verify', `${ref}^{commit}`], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
930
+ }
931
+ catch { /* verified above */ }
932
+ const plan = `sha256:${require('node:crypto').createHash('sha256').update(JSON.stringify([resolved, files.map((n) => [n, w.chainDigest(path.join(ledgerDir, n))])])).digest('hex')}`;
933
+ rechainGrant = lw.rechainGate({ root, askRoot: root, now: new Date().toISOString(), plan }, {
934
+ guard: () => operatorActGuard('rechaining the provenance ledger', root),
935
+ resolve: (r, env, action, n) => resolveApproval(r, env, action, n),
936
+ enqueue: (r, req) => { enqueueApprovalRequest(r, req); },
937
+ });
938
+ if (!rechainGrant.proceed) {
939
+ process.stderr.write(`${withRefusalLine(rechainGrant.message, 'grant.operator-only')}\n`);
940
+ return 2;
941
+ }
894
942
  }
895
- // Resolve the SYMBOLIC ref once (round-13): 'HEAD' is ephemeral, so the audit event records the
896
- // branch name too, making the trail self-describing later. Falls back to the raw ref.
897
- let refLabel = ref;
898
- try {
899
- refLabel = execFileSync('git', ['-C', root, 'rev-parse', '--abbrev-ref', ref], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] }).trim() || ref;
943
+ // the grant is claimed before anything is rewritten (A-SPEC-245.4's order)
944
+ const { claimGrant: claimRechain, spendGrantApprovals: spendRechain } = require('../governance/approval-grants');
945
+ const rechainClaim = rechainGrant !== null && rechainGrant.proceed && rechainGrant.spend !== undefined ? claimRechain(root, rechainGrant.spend) : undefined;
946
+ if (rechainClaim === null) {
947
+ process.stderr.write('the approval grant for this rechain is in use by another act — nothing was rewritten; retry\n');
948
+ return 2;
900
949
  }
901
- catch { /* keep raw ref */ }
902
- const planRechain = (mainline, input, mainlineAt) => {
903
- const r = rechainLedger(mainline, input, key);
904
- if ('refused' in r)
905
- return { refused: r.refused };
906
- if (r.alreadyVerified)
907
- return { audited: r.events, orphanCount: 0, alreadyVerified: true, mainlineLen: mainline.length, mainlineAt };
908
- const audited = [...r.events];
909
- audited.push(chainNext(audited, {
910
- ts: new Date().toISOString(), actor: 'holmes-kit', kind: 'ledger-rechained',
911
- summary: `rechained against ${refLabel}@${mainlineAt.slice(0, 8)} — mainline ${mainline.length} + orphans ${r.orphanCount}`,
912
- inputs: [refLabel, mainlineAt, String(r.orphanCount)], rationale: 'ledger rechain repair', authorization: '',
913
- }, key));
914
- // Verify the AUDITED chain (round-8: never claim "verified" without verifying; round-16: verify
915
- // the chain we will actually write, WITH its keyed audit tail, not the pre-audit prefix).
916
- const v = verifyChain(audited, key);
917
- if (!v.ok)
918
- return { refused: `the rechained output does not verify (brokenAt=${v.brokenAt ?? '?'}: ${v.detail ?? ''}) — check the canonical ref (--ref) or the key setting.` };
919
- return { audited, orphanCount: r.orphanCount, alreadyVerified: false, mainlineLen: mainline.length, mainlineAt };
950
+ let rewrote = 0;
951
+ // @implements A-SPEC-794.116 — one place settles the claim, on every path after it was taken (an early return, an
952
+ // exception, a failure, success): spent when a file was rewritten, released otherwise. The rechain does NOT move the
953
+ // ledger witness (it moved it, unconditionally, and a taken-back chain approved as a "rechain" became the witnessed
954
+ // one — the supervisor's review, H1): the one act that moves it is a person's `holmes-kit ledger witness`.
955
+ const settleRechain = () => {
956
+ if (dry || rechainGrant === null || !rechainGrant.proceed)
957
+ return;
958
+ try {
959
+ if (rechainClaim !== undefined) {
960
+ if (rewrote > 0 && rechainGrant.approval !== undefined) {
961
+ spendRechain(root, [rechainGrant.approval], `ledger rechain ${root}`);
962
+ rechainClaim.commit();
963
+ }
964
+ else
965
+ rechainClaim.release();
966
+ }
967
+ }
968
+ catch (e) {
969
+ rechainClaim?.release();
970
+ process.stderr.write(`[Holmes-Kit] the grant could not be settled after the rechain: ${e.message}\n`);
971
+ }
972
+ process.stdout.write('The ledger witness was not moved: if this writer\'s chain is now not the one the witness holds, the judgement stays closed until a person vouches for it — run `holmes-kit ledger witness` (a person decides it in the session\'s approval form).\n');
920
973
  };
921
- // "Is this committed version VALIDLY KEYED under the current key?" — the load-bearing distinction
922
- // of the two-phase walk: a keyed mainline is terminal, and a keyed ancestor is the only rollback
923
- // evidence (round-18). Named once so the `key !== undefined` narrowing is not copy-pasted.
924
- const isValidlyKeyed = (c) => c.some((e) => key !== undefined && keyedSelfConsistent(e, key));
925
- let failed = 0;
926
- for (const name of files) {
927
- const abs = path.join(ledgerDir, name);
928
- const rel = path.relative(root, abs).split(path.sep).join('/');
929
- let working;
974
+ const runRechain = () => {
975
+ // STRICT parse (round-9): a torn TAIL is tolerated, but mid-file corruption or a non-object line
976
+ // throws — the repair tool must not drop a line and then 'fix' the seq gap, making the loss
977
+ // permanent and invisible to verify().
978
+ const parse = (raw, file) => parseLedgerLines(raw, file, { throwOnCorruption: true });
979
+ // The first-parent commit list is the SAME for every file (one ref), so resolve it ONCE outside
980
+ // the loop (round-9: it was re-run per file).
981
+ const WALK_LIMIT = 64;
982
+ let walkCommits = [];
930
983
  try {
931
- working = parse(fs.readFileSync(abs, 'utf8'), name);
984
+ walkCommits = execFileSync('git', ['-C', root, 'rev-list', '--first-parent', '-n', String(WALK_LIMIT), ref], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] })
985
+ .split('\n').map((l) => l.trim()).filter(Boolean);
932
986
  }
933
987
  catch (e) {
934
- process.stdout.write(`✗ ${name}: ${e.message} — investigate and repair the corrupt line, then re-run.\n`);
935
- failed++;
936
- continue;
988
+ // A rev-list failure (the ref was already rev-parse-verified) is a real git error, not an
989
+ // empty history — surface it rather than degrading every file to a false 'no mainline'
990
+ // (round-12).
991
+ process.stderr.write(`git rev-list failed — cannot enumerate history: ${e.message.split('\n')[0]}\n`);
992
+ return 1;
937
993
  }
938
- // Refuse to re-sign what this entry point cannot verify (a keyless run rewriting an intact
939
- // keyed ledger as keyless is the exact attack signature the HMAC detector exists for,
940
- // manufactured by the repair tool).
941
- if (!key && hasKeyedLookingEvents(working)) {
942
- process.stdout.write(`✗ ${name}: there is a non-self-consistent line — either keyed (HMAC) or content-tampered, and without the key the two cannot be told apart. If keyed, set HOLMES_LEDGER_KEY; if tampered, investigate. rechain only repairs forks and does not re-sign this line.\n`);
943
- failed++;
944
- continue;
994
+ // Resolve the SYMBOLIC ref once (round-13): 'HEAD' is ephemeral, so the audit event records the
995
+ // branch name too, making the trail self-describing later. Falls back to the raw ref.
996
+ let refLabel = ref;
997
+ try {
998
+ refLabel = execFileSync('git', ['-C', root, 'rev-parse', '--abbrev-ref', ref], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] }).trim() || ref;
945
999
  }
946
- // Mainline = the FIRST VERIFYING committed version, walking first-parent from the ref. A
947
- // union-merge commit's own HEAD carries the seam, so "the ref, verbatim" strands the operator
948
- // right after the scenario this command exists for. The walk selects the last healthy
949
- // COMMITTED state; every line outside it is preserved as an orphan.
950
- let mainline = null;
951
- let mainlineAt = '';
952
- let presentAnywhere = false;
953
- let presentButCorrupt = false; // a committed version existed but strict-parse rejected it
954
- let keyedBlocked = false; // a keyed-looking committed version the current mode can't verify
955
- let sawKeyedCommitted = false; // any committed version in the walk carried keyed-looking events
956
- for (const at of walkCommits) {
957
- let cand;
958
- // `:./` pins the pathspec to -C's cwd: a bare `<ref>:<rel>` is repo-TOPLEVEL-relative, so a
959
- // governed subdirectory of a monorepo would adopt the PARENT repo's same-named ledger. A
960
- // show failure means "absent at THIS commit" and the walk CONTINUES; stderr is piped. A
961
- // committed candidate that is CORRUPT (strict-parse throws) is skipped like an absent one.
962
- let raw;
1000
+ catch { /* keep raw ref */ }
1001
+ const planRechain = (mainline, input, mainlineAt) => {
1002
+ const r = rechainLedger(mainline, input, key);
1003
+ if ('refused' in r)
1004
+ return { refused: r.refused };
1005
+ if (r.alreadyVerified)
1006
+ return { audited: r.events, orphanCount: 0, alreadyVerified: true, mainlineLen: mainline.length, mainlineAt };
1007
+ const audited = [...r.events];
1008
+ audited.push(chainNext(audited, {
1009
+ ts: new Date().toISOString(), actor: 'holmes-kit', kind: 'ledger-rechained',
1010
+ summary: `rechained against ${refLabel}@${mainlineAt.slice(0, 8)} — mainline ${mainline.length} + orphans ${r.orphanCount}`,
1011
+ inputs: [refLabel, mainlineAt, String(r.orphanCount)], rationale: 'ledger rechain repair', authorization: '',
1012
+ }, key));
1013
+ // Verify the AUDITED chain (round-8: never claim "verified" without verifying; round-16: verify
1014
+ // the chain we will actually write, WITH its keyed audit tail, not the pre-audit prefix).
1015
+ const v = verifyChain(audited, key);
1016
+ if (!v.ok)
1017
+ return { refused: `the rechained output does not verify (brokenAt=${v.brokenAt ?? '?'}: ${v.detail ?? ''}) — check the canonical ref (--ref) or the key setting.` };
1018
+ return { audited, orphanCount: r.orphanCount, alreadyVerified: false, mainlineLen: mainline.length, mainlineAt };
1019
+ };
1020
+ // "Is this committed version VALIDLY KEYED under the current key?" — the load-bearing distinction
1021
+ // of the two-phase walk: a keyed mainline is terminal, and a keyed ancestor is the only rollback
1022
+ // evidence (round-18). Named once so the `key !== undefined` narrowing is not copy-pasted.
1023
+ const isValidlyKeyed = (c) => c.some((e) => key !== undefined && keyedSelfConsistent(e, key));
1024
+ let failed = 0;
1025
+ for (const name of files) {
1026
+ const abs = path.join(ledgerDir, name);
1027
+ const rel = path.relative(root, abs).split(path.sep).join('/');
1028
+ let working;
963
1029
  try {
964
- raw = execFileSync('git', ['-C', root, 'show', `${at}:./${rel}`], { timeout: bounded_io_1.GIT_TIMEOUT_MS, encoding: 'utf8', maxBuffer: 1 << 28, env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] });
1030
+ working = parse(fs.readFileSync(abs, 'utf8'), name);
965
1031
  }
966
- catch {
1032
+ catch (e) {
1033
+ process.stdout.write(`✗ ${name}: ${e.message} — investigate and repair the corrupt line, then re-run.\n`);
1034
+ failed++;
967
1035
  continue;
968
- } // absent at THIS commit — walk continues
969
- presentAnywhere = true;
970
- // Present but CORRUPT is distinct from absent (round-14): remember it so the final message
971
- // names corruption, not 'absent from history'.
972
- try {
973
- cand = parse(raw, `${at}:${rel}`);
974
1036
  }
975
- catch {
976
- presentButCorrupt = true;
1037
+ // Refuse to re-sign what this entry point cannot verify (a keyless run rewriting an intact
1038
+ // keyed ledger as keyless is the exact attack signature the HMAC detector exists for,
1039
+ // manufactured by the repair tool).
1040
+ if (!key && hasKeyedLookingEvents(working)) {
1041
+ process.stdout.write(`✗ ${name}: there is a non-self-consistent line — either keyed (HMAC) or content-tampered, and without the key the two cannot be told apart. If keyed, set HOLMES_LEDGER_KEY; if tampered, investigate. rechain only repairs forks and does not re-sign this line.\n`);
1042
+ failed++;
977
1043
  continue;
978
1044
  }
979
- // Two DISTINCT phases (round-18): MAINLINE SELECTION while `mainline === null`, then, only
980
- // for a keyless mainline chosen under a set key, a ROLLBACK SCAN of older commits. Keeping
981
- // them separate stops an older corrupt ancestor — reachable only because the scan walks past
982
- // the chosen mainline — from hijacking selection-phase logic (keyedBlocked) or being counted
983
- // as a keyed ancestor.
984
- if (mainline === null) {
985
- // Stop only at an UNACCOUNTABLE candidate — one carrying a line this mode can explain
986
- // neither as keyless-self-consistent NOR (key present) as validly keyed under the current
987
- // key. That is wrong-key / tamper (round-12), and for a keyless run any keyed-looking line
988
- // (round-5 V2). A union-merge SEAM of a keyed ledger is NOT unaccountable: its lines ARE
989
- // keyed-self-consistent (signed correctly, only linkage broken), so the walk continues past
990
- // it to the healthy keyed ancestor and rechain repairs the seam (round-14 regression).
991
- const unaccountable = cand.some((e) => !keylessSelfConsistent(e) && !(key !== undefined && keyedSelfConsistent(e, key)));
992
- if (unaccountable) {
993
- keyedBlocked = true;
994
- break;
1045
+ // Mainline = the FIRST VERIFYING committed version, walking first-parent from the ref. A
1046
+ // union-merge commit's own HEAD carries the seam, so "the ref, verbatim" strands the operator
1047
+ // right after the scenario this command exists for. The walk selects the last healthy
1048
+ // COMMITTED state; every line outside it is preserved as an orphan.
1049
+ let mainline = null;
1050
+ let mainlineAt = '';
1051
+ let presentAnywhere = false;
1052
+ let presentButCorrupt = false; // a committed version existed but strict-parse rejected it
1053
+ let keyedBlocked = false; // a keyed-looking committed version the current mode can't verify
1054
+ let sawKeyedCommitted = false; // any committed version in the walk carried keyed-looking events
1055
+ for (const at of walkCommits) {
1056
+ let cand;
1057
+ // `:./` pins the pathspec to -C's cwd: a bare `<ref>:<rel>` is repo-TOPLEVEL-relative, so a
1058
+ // governed subdirectory of a monorepo would adopt the PARENT repo's same-named ledger. A
1059
+ // show failure means "absent at THIS commit" and the walk CONTINUES; stderr is piped. A
1060
+ // committed candidate that is CORRUPT (strict-parse throws) is skipped like an absent one.
1061
+ let raw;
1062
+ try {
1063
+ raw = execFileSync('git', ['-C', root, 'show', `${at}:./${rel}`], { timeout: bounded_io_1.GIT_TIMEOUT_MS, encoding: 'utf8', maxBuffer: 1 << 28, env: gitEnv, stdio: ['ignore', 'pipe', 'pipe'] });
995
1064
  }
996
- // An empty committed ledger is trivially "valid" but adopting it re-chains the whole working
997
- // file from genesis, discarding its relation to real history — walk past it (round-14).
998
- if (cand.length === 0)
1065
+ catch {
999
1066
  continue;
1000
- if (!acceptsAsMainline(cand, key))
1067
+ } // absent at THIS commit — walk continues
1068
+ presentAnywhere = true;
1069
+ // Present but CORRUPT is distinct from absent (round-14): remember it so the final message
1070
+ // names corruption, not 'absent from history'.
1071
+ try {
1072
+ cand = parse(raw, `${at}:${rel}`);
1073
+ }
1074
+ catch {
1075
+ presentButCorrupt = true;
1001
1076
  continue;
1002
- mainline = cand;
1003
- mainlineAt = at;
1004
- // A KEYED mainline (or a keyless run) is terminal — the walk goes newest→oldest, so nothing
1005
- // older can override the newest verifying state. Only a KEYLESS mainline under a SET key
1006
- // enters the rollback scan: KEY ADOPTION IS MONOTONIC (round-17), so it must confirm no
1007
- // OLDER committed version was validly keyed under this key (which would make this keyless
1008
- // mainline a rollback). Legit first-adoption has no such ancestor and the mainline stands.
1009
- if (!key || isValidlyKeyed(cand))
1010
- break;
1011
- }
1012
- else {
1013
- // ROLLBACK SCAN: only a version VALIDLY KEYED UNDER THE CURRENT KEY is rollback evidence
1014
- // (round-18). A merely keyed-LOOKING older commit — content-tampered, garbage-hash, or
1015
- // signed under a foreign key — is NOT: counting it would misdiagnose corruption as a
1016
- // key-rollback and block a healthy first-key adoption over an unrelated older corrupt commit.
1017
- if (isValidlyKeyed(cand)) {
1018
- sawKeyedCommitted = true;
1019
- break;
1077
+ }
1078
+ // Two DISTINCT phases (round-18): MAINLINE SELECTION while `mainline === null`, then, only
1079
+ // for a keyless mainline chosen under a set key, a ROLLBACK SCAN of older commits. Keeping
1080
+ // them separate stops an older corrupt ancestor — reachable only because the scan walks past
1081
+ // the chosen mainline — from hijacking selection-phase logic (keyedBlocked) or being counted
1082
+ // as a keyed ancestor.
1083
+ if (mainline === null) {
1084
+ // Stop only at an UNACCOUNTABLE candidate — one carrying a line this mode can explain
1085
+ // neither as keyless-self-consistent NOR (key present) as validly keyed under the current
1086
+ // key. That is wrong-key / tamper (round-12), and for a keyless run any keyed-looking line
1087
+ // (round-5 V2). A union-merge SEAM of a keyed ledger is NOT unaccountable: its lines ARE
1088
+ // keyed-self-consistent (signed correctly, only linkage broken), so the walk continues past
1089
+ // it to the healthy keyed ancestor and rechain repairs the seam (round-14 regression).
1090
+ const unaccountable = cand.some((e) => !keylessSelfConsistent(e) && !(key !== undefined && keyedSelfConsistent(e, key)));
1091
+ if (unaccountable) {
1092
+ keyedBlocked = true;
1093
+ break;
1094
+ }
1095
+ // An empty committed ledger is trivially "valid" but adopting it re-chains the whole working
1096
+ // file from genesis, discarding its relation to real history — walk past it (round-14).
1097
+ if (cand.length === 0)
1098
+ continue;
1099
+ if (!acceptsAsMainline(cand, key))
1100
+ continue;
1101
+ mainline = cand;
1102
+ mainlineAt = at;
1103
+ // A KEYED mainline (or a keyless run) is terminal — the walk goes newest→oldest, so nothing
1104
+ // older can override the newest verifying state. Only a KEYLESS mainline under a SET key
1105
+ // enters the rollback scan: KEY ADOPTION IS MONOTONIC (round-17), so it must confirm no
1106
+ // OLDER committed version was validly keyed under this key (which would make this keyless
1107
+ // mainline a rollback). Legit first-adoption has no such ancestor and the mainline stands.
1108
+ if (!key || isValidlyKeyed(cand))
1109
+ break;
1110
+ }
1111
+ else {
1112
+ // ROLLBACK SCAN: only a version VALIDLY KEYED UNDER THE CURRENT KEY is rollback evidence
1113
+ // (round-18). A merely keyed-LOOKING older commit — content-tampered, garbage-hash, or
1114
+ // signed under a foreign key — is NOT: counting it would misdiagnose corruption as a
1115
+ // key-rollback and block a healthy first-key adoption over an unrelated older corrupt commit.
1116
+ if (isValidlyKeyed(cand)) {
1117
+ sawKeyedCommitted = true;
1118
+ break;
1119
+ }
1020
1120
  }
1021
1121
  }
1022
- }
1023
- // A keyless mainline was selected under a set key atop a genuinely-keyed ancestor: a keyless-
1024
- // rollback of a formerly-keyed ledger (round-17). Refuse — do not launder. (Legit first-adoption
1025
- // never reaches here: sawKeyedCommitted stays false. A keyed union-merge seam repair selects a
1026
- // KEYED mainline, so it never enters the rollback scan.) Note: a full first-parent history
1027
- // rewrite that erases every keyed commit within WALK_LIMIT (rebase/squash) defeats this
1028
- // git-anchored check — the fundamental limitation named in provenance-chain.ts and spec §22.
1029
- if (mainline !== null && key && sawKeyedCommitted) {
1030
- process.stdout.write(`✗ ${name}: the committed history was keyed (HMAC) but the current mainline candidate is keyless — adopting a key is irreversible (keyless-rollback). This rewrite would discard the keyed history and re-sign the keyless content with the key, laundering a forgery. verify already flags this as tampering. Point --ref at a healthy keyed canonical, or investigate the tampering.\n`);
1031
- failed++;
1032
- continue;
1033
- }
1034
- if (keyedBlocked) {
1035
- process.stdout.write(key
1036
- ? `✗ ${name}: the committed mainline does not verify under the current HOLMES_LEDGER_KEY — either the key is wrong or the history was tampered with. Rechaining past this would re-sign a keyed history with the wrong key. Confirm the correct key.\n`
1037
- : `✗ ${name}: the committed mainline has a non-self-consistent line — it is keyed (HMAC) or content-tampered. If keyed, set HOLMES_LEDGER_KEY; if tampered, investigate. Not rechaining past it.\n`);
1038
- failed++;
1039
- continue;
1040
- }
1041
- if (mainline === null) {
1042
- // With no verifying committed mainline nothing can arbitrate. A verifying working file
1043
- // needs no arbitration; a broken one is refused, not guessed at.
1044
- if (verifyChain(working, key).ok) {
1045
- process.stdout.write(`· ${name}: no verifying copy in the committed history, working copy verifies — no change\n`);
1122
+ // A keyless mainline was selected under a set key atop a genuinely-keyed ancestor: a keyless-
1123
+ // rollback of a formerly-keyed ledger (round-17). Refuse — do not launder. (Legit first-adoption
1124
+ // never reaches here: sawKeyedCommitted stays false. A keyed union-merge seam repair selects a
1125
+ // KEYED mainline, so it never enters the rollback scan.) Note: a full first-parent history
1126
+ // rewrite that erases every keyed commit within WALK_LIMIT (rebase/squash) defeats this
1127
+ // git-anchored check — the fundamental limitation named in provenance-chain.ts and spec §22.
1128
+ if (mainline !== null && key && sawKeyedCommitted) {
1129
+ process.stdout.write(`✗ ${name}: the committed history was keyed (HMAC) but the current mainline candidate is keyless — adopting a key is irreversible (keyless-rollback). This rewrite would discard the keyed history and re-sign the keyless content with the key, laundering a forgery. verify already flags this as tampering. Point --ref at a healthy keyed canonical, or investigate the tampering.\n`);
1130
+ failed++;
1046
1131
  continue;
1047
1132
  }
1048
- process.stdout.write(presentButCorrupt
1049
- ? `✗ ${name}: the committed ledger copy is corrupt and the working copy fails to verify — repair the corrupt committed copy or point --ref at a healthy canonical\n`
1050
- : presentAnywhere
1051
- ? `✗ ${name}: no verifying committed copy within the first-parent ${WALK_LIMIT} commits and the working copy fails to verify — point --ref at a canonical\n`
1052
- : `✗ ${name}: not in the ${ref} history and the working copy fails to verify — point --ref at a canonical\n`);
1053
- failed++;
1054
- continue;
1055
- }
1056
- // Read-rechain-write runs under the ledger lock: an unlocked wholesale rewrite would erase any
1057
- // append landing between the snapshot and the write. The working file is RE-READ inside the
1058
- // hold; the git walk stayed outside (it never touches the file).
1059
- const fixedMainline = mainline;
1060
- // --dry-run is READ-ONLY (round-10): it takes NO write lock (the lock's stale-break recorder
1061
- // would append a lock-broken event, and lock contention would fail the CI gate on drift it
1062
- // never checked) and opens nothing for write — it judges the snapshot `working` and returns an
1063
- // exit code only. The write path (lock, audit event, atomic rewrite) is for the real run only.
1064
- if (dry) {
1065
- const rd = planRechain(fixedMainline, working, mainlineAt);
1066
- if ('refused' in rd) {
1067
- process.stdout.write(`✗ ${name}: ${rd.refused}\n`);
1133
+ if (keyedBlocked) {
1134
+ process.stdout.write(key
1135
+ ? `✗ ${name}: the committed mainline does not verify under the current HOLMES_LEDGER_KEY — either the key is wrong or the history was tampered with. Rechaining past this would re-sign a keyed history with the wrong key. Confirm the correct key.\n`
1136
+ : `✗ ${name}: the committed mainline has a non-self-consistent line — it is keyed (HMAC) or content-tampered. If keyed, set HOLMES_LEDGER_KEY; if tampered, investigate. Not rechaining past it.\n`);
1068
1137
  failed++;
1069
1138
  continue;
1070
1139
  }
1071
- if (rd.alreadyVerified) {
1072
- process.stdout.write(`· ${name}: already verifies — no change\n`);
1140
+ if (mainline === null) {
1141
+ // With no verifying committed mainline nothing can arbitrate. A verifying working file
1142
+ // needs no arbitration; a broken one is refused, not guessed at.
1143
+ if (verifyChain(working, key).ok) {
1144
+ process.stdout.write(`· ${name}: no verifying copy in the committed history, working copy verifies — no change\n`);
1145
+ continue;
1146
+ }
1147
+ process.stdout.write(presentButCorrupt
1148
+ ? `✗ ${name}: the committed ledger copy is corrupt and the working copy fails to verify — repair the corrupt committed copy or point --ref at a healthy canonical\n`
1149
+ : presentAnywhere
1150
+ ? `✗ ${name}: no verifying committed copy within the first-parent ${WALK_LIMIT} commits and the working copy fails to verify — point --ref at a canonical\n`
1151
+ : `✗ ${name}: not in the ${ref} history and the working copy fails to verify — point --ref at a canonical\n`);
1152
+ failed++;
1073
1153
  continue;
1074
1154
  }
1075
- process.stdout.write(`○ ${name}: would rechain — ${rd.orphanCount} orphan(s) (dry-run, not written)\n`);
1076
- failed++;
1077
- continue; // drift detected → CI gate fails
1078
- }
1079
- let verdict;
1080
- try {
1081
- verdict = withLedgerLock(abs, () => {
1082
- // Corruption appearing between the outer read and the lock throws here; catch it as a
1083
- // per-file ✗ (round-14: an uncaught strict-parse throw crashed the whole multi-file run).
1084
- let fresh;
1085
- try {
1086
- fresh = parse(fs.readFileSync(abs, 'utf8'), name);
1087
- } // read inside the lock (round-8)
1088
- catch (e) {
1089
- return { line: `✗ ${name}: ${e.message} — investigate and repair the corrupt line, then re-run.`, fail: true };
1090
- }
1091
- // Re-checked INSIDE the hold (TOCTOU): a non-self-consistent line appearing between the
1092
- // snapshot and the lock is either keyed or content-tampered — honest either way (round-8).
1093
- if (!key && hasKeyedLookingEvents(fresh)) {
1094
- return { line: `✗ ${name}: a non-self-consistent line appeared while acquiring the lock — it is keyed (set HOLMES_LEDGER_KEY) or tampered. Not re-signing.`, fail: true };
1155
+ // Read-rechain-write runs under the ledger lock: an unlocked wholesale rewrite would erase any
1156
+ // append landing between the snapshot and the write. The working file is RE-READ inside the
1157
+ // hold; the git walk stayed outside (it never touches the file).
1158
+ const fixedMainline = mainline;
1159
+ // --dry-run is READ-ONLY (round-10): it takes NO write lock (the lock's stale-break recorder
1160
+ // would append a lock-broken event, and lock contention would fail the CI gate on drift it
1161
+ // never checked) and opens nothing for write — it judges the snapshot `working` and returns an
1162
+ // exit code only. The write path (lock, audit event, atomic rewrite) is for the real run only.
1163
+ if (dry) {
1164
+ const rd = planRechain(fixedMainline, working, mainlineAt);
1165
+ if ('refused' in rd) {
1166
+ process.stdout.write(`✗ ${name}: ${rd.refused}\n`);
1167
+ failed++;
1168
+ continue;
1095
1169
  }
1096
- // ONE judgment (round-16): rechain, chain the KEYED audit event onto the tail (the ledger's
1097
- // own doctrine — the audit trail must not silently change; the `ledger-rechained` event
1098
- // attributes the regeneration to this tool, the mainline ref/sha, and the orphan count, is
1099
- // keyed iff a key is present, and is idempotent), then verify the WHOLE audited chain. The
1100
- // SAME function the dry-run advisory used, so the two can never disagree.
1101
- const plan = planRechain(fixedMainline, fresh, mainlineAt);
1102
- if ('refused' in plan)
1103
- return { line: `✗ ${name}: ${plan.refused}`, fail: true };
1104
- if (plan.alreadyVerified)
1105
- return { line: `· ${name}: already verifies — no change` };
1106
- const audited = plan.audited;
1107
- // ATOMIC rewrite: a crash mid-write must leave the old file, never a verifying prefix that
1108
- // the rerun's no-change guard silently accepts.
1109
- const serialized = audited.map((e) => JSON.stringify(e)).join('\n') + '\n';
1110
- const tmp = abs + '.rechain-tmp';
1111
- fs.writeFileSync(tmp, serialized);
1112
- fs.renameSync(tmp, abs);
1113
- // Confirm the ON-DISK result matches what we verified (round-15): the success line must
1114
- // reflect the file, not just the in-memory array — a torn/short write is reported, not
1115
- // silently blessed as 'verified'.
1116
- if (fs.readFileSync(abs, 'utf8') !== serialized) {
1117
- return { line: `✗ ${name}: the rewritten file differs from what was verified (disk fault?) — re-run.`, fail: true };
1170
+ if (rd.alreadyVerified) {
1171
+ process.stdout.write(`· ${name}: already verifies — no change\n`);
1172
+ continue;
1118
1173
  }
1119
- return { line: `✓ ${name}: rechained — mainline ${fixedMainline.length}(${mainlineAt.slice(0, 8)}) + orphans ${plan.orphanCount}, audit event recorded, chain verifies` };
1120
- }, { onStaleBreak: new ProvenanceChain(abs).staleBreakRecorder() });
1121
- }
1122
- catch (e) {
1123
- // Lock contention is a per-file refusal, not a crash.
1124
- if (e instanceof LedgerLockError) {
1125
- process.stdout.write(`✗ ${name}: could not acquire the ledger lock (another writer is active) — retry shortly.\n`);
1174
+ process.stdout.write(`○ ${name}: would rechain — ${rd.orphanCount} orphan(s) (dry-run, not written)\n`);
1126
1175
  failed++;
1127
- continue;
1176
+ continue; // drift detected → CI gate fails
1128
1177
  }
1129
- // Any OTHER fault — a raw I/O error on the atomic write (ENOSPC/EACCES/EIO), etc. — is a
1130
- // per-file ✗, NOT an abort of the whole run: one replica's disk failure must not abandon its
1131
- // siblings, consistent with every other per-file fault (corruption, lock, refusal). The
1132
- // message is printed (never swallowed) so the failure stays visible and the exit is nonzero.
1133
- // The atomic tmp is left only on a mid-write crash and is ignored by isLedgerFilename; still,
1134
- // best-effort remove it so a retry starts clean.
1178
+ let verdict;
1135
1179
  try {
1136
- fs.rmSync(abs + '.rechain-tmp', { force: true });
1180
+ verdict = withLedgerLock(abs, () => {
1181
+ // Corruption appearing between the outer read and the lock throws here; catch it as a
1182
+ // per-file ✗ (round-14: an uncaught strict-parse throw crashed the whole multi-file run).
1183
+ let fresh;
1184
+ try {
1185
+ fresh = parse(fs.readFileSync(abs, 'utf8'), name);
1186
+ } // read inside the lock (round-8)
1187
+ catch (e) {
1188
+ return { line: `✗ ${name}: ${e.message} — investigate and repair the corrupt line, then re-run.`, fail: true };
1189
+ }
1190
+ // Re-checked INSIDE the hold (TOCTOU): a non-self-consistent line appearing between the
1191
+ // snapshot and the lock is either keyed or content-tampered — honest either way (round-8).
1192
+ if (!key && hasKeyedLookingEvents(fresh)) {
1193
+ return { line: `✗ ${name}: a non-self-consistent line appeared while acquiring the lock — it is keyed (set HOLMES_LEDGER_KEY) or tampered. Not re-signing.`, fail: true };
1194
+ }
1195
+ // ONE judgment (round-16): rechain, chain the KEYED audit event onto the tail (the ledger's
1196
+ // own doctrine — the audit trail must not silently change; the `ledger-rechained` event
1197
+ // attributes the regeneration to this tool, the mainline ref/sha, and the orphan count, is
1198
+ // keyed iff a key is present, and is idempotent), then verify the WHOLE audited chain. The
1199
+ // SAME function the dry-run advisory used, so the two can never disagree.
1200
+ const plan = planRechain(fixedMainline, fresh, mainlineAt);
1201
+ if ('refused' in plan)
1202
+ return { line: `✗ ${name}: ${plan.refused}`, fail: true };
1203
+ if (plan.alreadyVerified)
1204
+ return { line: `· ${name}: already verifies — no change` };
1205
+ const audited = plan.audited;
1206
+ // ATOMIC rewrite: a crash mid-write must leave the old file, never a verifying prefix that
1207
+ // the rerun's no-change guard silently accepts.
1208
+ const serialized = audited.map((e) => JSON.stringify(e)).join('\n') + '\n';
1209
+ const tmp = abs + '.rechain-tmp';
1210
+ fs.writeFileSync(tmp, serialized);
1211
+ fs.renameSync(tmp, abs);
1212
+ // Confirm the ON-DISK result matches what we verified (round-15): the success line must
1213
+ // reflect the file, not just the in-memory array — a torn/short write is reported, not
1214
+ // silently blessed as 'verified'.
1215
+ if (fs.readFileSync(abs, 'utf8') !== serialized) {
1216
+ return { line: `✗ ${name}: the rewritten file differs from what was verified (disk fault?) — re-run.`, fail: true };
1217
+ }
1218
+ return { line: `✓ ${name}: rechained — mainline ${fixedMainline.length}(${mainlineAt.slice(0, 8)}) + orphans ${plan.orphanCount}, audit event recorded, chain verifies` };
1219
+ }, { onStaleBreak: new ProvenanceChain(abs).staleBreakRecorder() });
1137
1220
  }
1138
- catch { /* best-effort */ }
1139
- process.stdout.write(`✗ ${name}: error during rewrite — ${e.message.split('\n')[0]}. This file is skipped (others continue). Investigate the cause, then re-run.\n`);
1140
- failed++;
1141
- continue;
1221
+ catch (e) {
1222
+ // Lock contention is a per-file refusal, not a crash.
1223
+ if (e instanceof LedgerLockError) {
1224
+ process.stdout.write(`✗ ${name}: could not acquire the ledger lock (another writer is active) — retry shortly.\n`);
1225
+ failed++;
1226
+ continue;
1227
+ }
1228
+ // Any OTHER fault — a raw I/O error on the atomic write (ENOSPC/EACCES/EIO), etc. — is a
1229
+ // per-file ✗, NOT an abort of the whole run: one replica's disk failure must not abandon its
1230
+ // siblings, consistent with every other per-file fault (corruption, lock, refusal). The
1231
+ // message is printed (never swallowed) so the failure stays visible and the exit is nonzero.
1232
+ // The atomic tmp is left only on a mid-write crash and is ignored by isLedgerFilename; still,
1233
+ // best-effort remove it so a retry starts clean.
1234
+ try {
1235
+ fs.rmSync(abs + '.rechain-tmp', { force: true });
1236
+ }
1237
+ catch { /* best-effort */ }
1238
+ process.stdout.write(`✗ ${name}: error during rewrite — ${e.message.split('\n')[0]}. This file is skipped (others continue). Investigate the cause, then re-run.\n`);
1239
+ failed++;
1240
+ continue;
1241
+ }
1242
+ process.stdout.write(verdict.line + '\n');
1243
+ if (verdict.fail)
1244
+ failed++;
1245
+ else if (verdict.line.startsWith('✓'))
1246
+ rewrote++;
1142
1247
  }
1143
- process.stdout.write(verdict.line + '\n');
1144
- if (verdict.fail)
1145
- failed++;
1248
+ return failed === 0 ? 0 : 1;
1249
+ };
1250
+ try {
1251
+ return runRechain();
1252
+ }
1253
+ finally {
1254
+ settleRechain();
1146
1255
  }
1147
- return failed === 0 ? 0 : 1;
1148
1256
  }
1149
1257
  // @implements A-SPEC-215, A-SPEC-262.2 — the approve dispatch lives in approve-cli.ts (A-SPEC-794.30: this file stays under its 1,500-line ceiling)
1150
1258
  if (cmd === 'approve')
@@ -1281,6 +1389,19 @@ async function main(argv, deps = {}) {
1281
1389
  const { resolveInitAutonomy, terminalAutonomyIO } = require('./interactive-prompt');
1282
1390
  const autonomyTarget = path.resolve(typeof flags.target === 'string' ? flags.target : process.cwd());
1283
1391
  const { autonomy, interactive: autonomyInteractive } = await resolveInitAutonomy(flags, autonomyTarget, terminalAutonomyIO(autonomyTarget));
1392
+ // @implements A-SPEC-794.91 — `init --autonomy` widens autonomy: the operator guard first, whatever approval the
1393
+ // environment carries (review A of 98c58e31: init took an environment approval without it)
1394
+ // (without an environment approval, runInit's own refusal stands as before)
1395
+ if (autonomy === true && !autonomyInteractive && readApproval() !== undefined) {
1396
+ const { operatorActGuard } = require('../guardrail/operator-person');
1397
+ const { autonomyWideningGate } = require('./autonomy');
1398
+ const { withRefusalLine } = require('../guardrail/refusal-codes');
1399
+ const w = autonomyWideningGate({ kind: 'init-autonomy', envApproval: readApproval() }, { guard: () => operatorActGuard('enabling autonomous spec approval through init', autonomyTarget) });
1400
+ if (!w.proceed) {
1401
+ process.stderr.write(`${withRefusalLine(w.why ?? 'enabling autonomous spec approval is the operator\'s', 'grant.operator-only')}\n`);
1402
+ return 2;
1403
+ }
1404
+ }
1284
1405
  // @implements A-SPEC-552.4 — with no .mcp.json written, --no-autonomy cannot change the posture; say so
1285
1406
  if (flags['no-autonomy'] === true && flags['no-mcp'] === true) {
1286
1407
  process.stderr.write('note: --no-autonomy has no effect with --no-mcp — no .mcp.json is written, so the autonomy posture is unchanged\n');