@holmes-lab/holmes-kit 0.41.2 → 0.41.3

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 (103) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +28 -5
  3. package/bin/holmes-mcp.js +36 -1
  4. package/dist/.build-id +1 -1
  5. package/dist/holmes/cli/claude-switches.d.ts +9 -0
  6. package/dist/holmes/cli/claude-switches.js +11 -8
  7. package/dist/holmes/cli/doctor.d.ts +7 -1
  8. package/dist/holmes/cli/doctor.js +63 -20
  9. package/dist/holmes/cli/holmes-hook-id.d.ts +9 -0
  10. package/dist/holmes/cli/holmes-hook-id.js +22 -0
  11. package/dist/holmes/cli/hook-failure-posture.d.ts +44 -0
  12. package/dist/holmes/cli/hook-failure-posture.js +65 -0
  13. package/dist/holmes/cli/index.js +3 -1
  14. package/dist/holmes/cli/init.d.ts +6 -0
  15. package/dist/holmes/cli/init.js +151 -3
  16. package/dist/holmes/cli/native-deps.d.ts +10 -4
  17. package/dist/holmes/cli/native-deps.js +30 -29
  18. package/dist/holmes/cli/run-wiring.js +4 -2
  19. package/dist/holmes/cli/runtime-binding.d.ts +24 -0
  20. package/dist/holmes/cli/runtime-binding.js +67 -25
  21. package/dist/holmes/cli/settings-merge.d.ts +3 -2
  22. package/dist/holmes/cli/settings-merge.js +11 -9
  23. package/dist/holmes/config/config.d.ts +6 -0
  24. package/dist/holmes/config/config.js +23 -3
  25. package/dist/holmes/config/judgement-keys.d.ts +20 -0
  26. package/dist/holmes/config/judgement-keys.js +100 -0
  27. package/dist/holmes/config/project-caps.js +3 -2
  28. package/dist/holmes/governance/autonomous-shell.js +1 -1
  29. package/dist/holmes/governance/autonomy.d.ts +27 -1
  30. package/dist/holmes/governance/autonomy.js +126 -6
  31. package/dist/holmes/governance/wiring-receipt.d.ts +7 -0
  32. package/dist/holmes/governance/wiring-receipt.js +84 -0
  33. package/dist/holmes/guardrail/cli-root.d.ts +31 -0
  34. package/dist/holmes/guardrail/cli-root.js +261 -0
  35. package/dist/holmes/guardrail/command-traits.d.ts +2 -0
  36. package/dist/holmes/guardrail/command-traits.js +26 -1
  37. package/dist/holmes/guardrail/impact-gate.d.ts +17 -1
  38. package/dist/holmes/guardrail/impact-gate.js +44 -5
  39. package/dist/holmes/guardrail/outward-acts.js +10 -3
  40. package/dist/holmes/guardrail/package-manager-acts.d.ts +41 -0
  41. package/dist/holmes/guardrail/package-manager-acts.js +1298 -0
  42. package/dist/holmes/guardrail/refusal-codes.js +9 -1
  43. package/dist/holmes/guardrail/shell-syntax.d.ts +3 -0
  44. package/dist/holmes/guardrail/shell-syntax.js +7 -2
  45. package/dist/holmes/guardrail/write-target.d.ts +20 -0
  46. package/dist/holmes/guardrail/write-target.js +168 -2
  47. package/dist/holmes/hooks/pre-tool-use.d.ts +110 -3
  48. package/dist/holmes/hooks/pre-tool-use.js +1208 -60
  49. package/dist/holmes/mcp/evidence-artifact.d.ts +112 -0
  50. package/dist/holmes/mcp/evidence-artifact.js +2 -0
  51. package/dist/holmes/mcp/handlers/maintenance-evidence.d.ts +2 -1
  52. package/dist/holmes/mcp/handlers/maintenance-evidence.js +24 -2
  53. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +1 -1
  54. package/dist/holmes/mcp/handlers/operator-inspection.js +2 -2
  55. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +1 -1
  56. package/dist/holmes/mcp/handlers/requirement-triage.js +3 -2
  57. package/dist/holmes/mcp/handlers/spec-approval.d.ts +1 -1
  58. package/dist/holmes/mcp/handlers/spec-approval.js +6 -6
  59. package/dist/holmes/mcp/handlers/test-execution.d.ts +8 -0
  60. package/dist/holmes/mcp/handlers/test-execution.js +12 -6
  61. package/dist/holmes/mcp/handlers.d.ts +16 -7
  62. package/dist/holmes/mcp/maintenance-evidence.d.ts +11 -82
  63. package/dist/holmes/mcp/maintenance-evidence.js +57 -2
  64. package/dist/holmes/mcp/outcome-replay.d.ts +18 -0
  65. package/dist/holmes/mcp/outcome-replay.js +85 -0
  66. package/dist/holmes/mcp/outcome-windows.d.ts +136 -0
  67. package/dist/holmes/mcp/outcome-windows.js +236 -0
  68. package/dist/holmes/mcp/tool-schemas.js +1 -1
  69. package/dist/holmes/project/hook-specs-arg.d.ts +4 -0
  70. package/dist/holmes/project/hook-specs-arg.js +39 -0
  71. package/dist/holmes/project/install-layout.d.ts +11 -0
  72. package/dist/holmes/project/install-layout.js +109 -0
  73. package/dist/holmes/project/install-scripts-policy.d.ts +4 -1
  74. package/dist/holmes/project/install-scripts-policy.js +6 -3
  75. package/dist/holmes/project/native-recovery.d.ts +29 -0
  76. package/dist/holmes/project/native-recovery.js +62 -0
  77. package/dist/holmes/project/root.d.ts +6 -0
  78. package/dist/holmes/project/root.js +15 -3
  79. package/dist/holmes/project/wiring-receipt-format.d.ts +20 -0
  80. package/dist/holmes/project/wiring-receipt-format.js +42 -0
  81. package/dist/holmes/project/workspace-preflight.d.ts +9 -0
  82. package/dist/holmes/project/workspace-preflight.js +40 -1
  83. package/dist/holmes/review/classification-replay.d.ts +53 -0
  84. package/dist/holmes/review/classification-replay.js +78 -0
  85. package/dist/holmes/review/head-worktree.js +5 -4
  86. package/dist/holmes/review/run-provenance.js +3 -2
  87. package/dist/holmes/review/test-evidence.js +2 -2
  88. package/dist/holmes/review/test-outcomes.js +3 -1
  89. package/dist/holmes/rtm/graph-store.d.ts +5 -0
  90. package/dist/holmes/rtm/graph-store.js +12 -4
  91. package/dist/holmes/rtm/native-driver.d.ts +42 -0
  92. package/dist/holmes/rtm/native-driver.js +147 -0
  93. package/dist/holmes/rtm/rtm-graph.js +11 -2
  94. package/dist/holmes/runtime/dispatch.d.ts +6 -0
  95. package/dist/holmes/runtime/dispatch.js +51 -2
  96. package/dist/holmes/runtime/hook-process.d.ts +6 -0
  97. package/dist/holmes/runtime/hook-process.js +3 -3
  98. package/dist/holmes/update/semver-strict.d.ts +3 -0
  99. package/dist/holmes/update/semver-strict.js +58 -0
  100. package/docs/install-guide.md +8 -1
  101. package/package.json +1 -1
  102. package/playbooks/tdd-slice/PLAYBOOK.md +1 -1
  103. package/release-history.json +36 -1
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.anchorMoveOnly = exports.DEFAULT_SPECS_DIR = void 0;
36
+ exports.anchorMoveOnly = exports.DEFAULT_SPECS_DIR = exports.ROOT_RULE_TARGET = void 0;
37
37
  exports.resolveRmSignals = resolveRmSignals;
38
38
  exports.resolveStagedStore = resolveStagedStore;
39
39
  exports.readApprovalFromEnv = readApprovalFromEnv;
@@ -41,7 +41,13 @@ exports.sedInPlaceFiles = sedInPlaceFiles;
41
41
  exports.gitStoreWrites = gitStoreWrites;
42
42
  exports.referenceInputWrite = referenceInputWrite;
43
43
  exports.referenceInputJudge = referenceInputJudge;
44
+ exports.shellWord = shellWord;
45
+ exports.stripHeredocBodies = stripHeredocBodies;
46
+ exports.shellStages = shellStages;
47
+ exports.lineFlow = lineFlow;
48
+ exports.unreadConstruct = unreadConstruct;
44
49
  exports.governedCliAct = governedCliAct;
50
+ exports.governedCliActs = governedCliActs;
45
51
  exports.commitOrBuildOf = commitOrBuildOf;
46
52
  exports.gitHiddenWriteOf = gitHiddenWriteOf;
47
53
  exports.runsAutonomyWidening = runsAutonomyWidening;
@@ -62,6 +68,7 @@ exports.normalizeHookInput = normalizeHookInput;
62
68
  exports.preEditEvidenceGate = preEditEvidenceGate;
63
69
  exports.decideOnGateError = decideOnGateError;
64
70
  exports.isGovernedProject = isGovernedProject;
71
+ exports.validHookAnswer = validHookAnswer;
65
72
  exports.gateErrorDecision = gateErrorDecision;
66
73
  exports.wiredSpecsDir = wiredSpecsDir;
67
74
  exports.settleVerdict = settleVerdict;
@@ -69,7 +76,7 @@ exports.settleOnMainThread = settleOnMainThread;
69
76
  exports.auditApprovalFor = auditApprovalFor;
70
77
  exports.evaluateHook = evaluateHook;
71
78
  exports.readSpecsSync = readSpecsSync;
72
- // @implements A-SPEC-794.113, A-SPEC-794.97, A-SPEC-794.96, A-SPEC-794.95, A-SPEC-794.91, A-SPEC-794.89, A-SPEC-794.87, A-SPEC-794.86, A-SPEC-794.83, A-SPEC-794.82, A-SPEC-794.72, A-SPEC-794.71, A-SPEC-794.70,A-SPEC-794.69, A-SPEC-578.16, A-SPEC-794.68,A-SPEC-578.15, A-SPEC-333.9, A-SPEC-794.57, A-SPEC-794.55, A-SPEC-794.54, A-SPEC-794.53, A-SPEC-794.52, A-SPEC-794.49, A-SPEC-222.12, A-SPEC-222.13, A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-245.17
79
+ // @implements A-SPEC-772.37, A-SPEC-772.36, A-SPEC-772.35, A-SPEC-772.34, A-SPEC-772.33, A-SPEC-772.32, A-SPEC-772.31, A-SPEC-772.30, A-SPEC-772.28, A-SPEC-772.16, A-SPEC-772.15, A-SPEC-794.134, A-SPEC-728.6, A-SPEC-476.8, A-SPEC-728.5, A-SPEC-728.4, A-SPEC-794.113, A-SPEC-794.97, A-SPEC-794.96, A-SPEC-794.95, A-SPEC-794.91, A-SPEC-794.89, A-SPEC-794.87, A-SPEC-794.86, A-SPEC-794.83, A-SPEC-794.82, A-SPEC-794.72, A-SPEC-794.71, A-SPEC-794.70,A-SPEC-794.69, A-SPEC-578.16, A-SPEC-794.68,A-SPEC-578.15, A-SPEC-333.9, A-SPEC-794.57, A-SPEC-794.55, A-SPEC-794.54, A-SPEC-794.53, A-SPEC-794.52, A-SPEC-794.49, A-SPEC-222.12, A-SPEC-222.13, A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-245.17
73
80
  const powershell_shell_1 = require("../guardrail/powershell-shell");
74
81
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
75
82
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
@@ -116,6 +123,8 @@ const write_target_1 = require("../guardrail/write-target");
116
123
  const dynamic_write_1 = require("../guardrail/dynamic-write");
117
124
  const SHELL_CODE_WRITE_REASON = '[Holmes-Kit] shell write to a project code file bypasses the No-Spec-No-Code gate — use the Write/Edit tools (gated) or supply out-of-band approval';
118
125
  const project_caps_1 = require("../config/project-caps");
126
+ const judgement_keys_1 = require("../config/judgement-keys");
127
+ const package_manager_acts_1 = require("../guardrail/package-manager-acts");
119
128
  const write_target_2 = require("../guardrail/write-target");
120
129
  const shell_syntax_1 = require("../guardrail/shell-syntax");
121
130
  const anchors_1 = require("../guardrail/anchors");
@@ -253,8 +262,26 @@ function resolveStagedStore(command, projectRoot, specsDir) {
253
262
  * target's post-patch content (no content: the file goes away).
254
263
  */
255
264
  function projectCapsWriteAct(root, input) {
256
- const beforeText = (0, project_caps_1.projectConfigText)(root);
265
+ const { beforeText, after } = projectConfigAfter(root, input);
257
266
  const before = beforeText === undefined ? { ...project_caps_1.NARROWEST_CAPS } : (0, project_caps_1.projectCapsOfText)(beforeText);
267
+ if (after === undefined)
268
+ return (0, project_caps_1.capsAtWidest)(before) ? null : `the result cannot be read, over the semantic search cap ${before.semantic} and the autonomy cap ${before.ceiling}`; // A-SPEC-794.138
269
+ const next = (0, project_caps_1.projectCapsOfText)(after);
270
+ if ((0, project_caps_1.sameCaps)(before, next))
271
+ return null;
272
+ const raised = (0, project_caps_1.raisedCaps)(before, next);
273
+ return raised.length > 0 ? raised.join(', ') : 'lowered';
274
+ }
275
+ /**
276
+ * @implements A-SPEC-476.3, A-SPEC-476.8 — the text of `<root>/ax.config.json` before a file tool's write and after it:
277
+ * the Write content, the Edit or MultiEdit applied to the disk, or a patch target's post-patch content (no content: the
278
+ * file goes away). `undefined` after = the result cannot be computed.
279
+ */
280
+ function projectConfigAfter(root, input) {
281
+ return textAfterWrite((0, project_caps_1.projectConfigText)(root), input);
282
+ }
283
+ /** @implements A-SPEC-794.134 — the same computation for any file whose disk text is `beforeText` (null: absent). */
284
+ function textAfterWrite(beforeText, input) {
258
285
  const ti = input.tool_input;
259
286
  const tool = input.tool_name.toLowerCase();
260
287
  const applyEdit = (text, o, n, all) => {
@@ -278,14 +305,19 @@ function projectCapsWriteAct(root, input) {
278
305
  else if (typeof ti.old_string === 'string') {
279
306
  after = typeof beforeText === 'string' ? applyEdit(beforeText, ti.old_string, ti.new_string, ti.replace_all) : beforeText === null ? null : undefined;
280
307
  }
308
+ return { beforeText, after };
309
+ }
310
+ /**
311
+ * @implements A-SPEC-476.8 — the judgement keys a file tool's write to ax.config.json changes (either direction), or
312
+ * `['(the result cannot be read)']` when the text after the write cannot be computed.
313
+ */
314
+ function projectJudgementWriteAct(root, input) {
315
+ const { beforeText, after } = projectConfigAfter(root, input);
281
316
  if (after === undefined)
282
- return (0, project_caps_1.capsAtWidest)(before) ? null : `the result cannot be read, over semantic.maxTier ${before.semantic} and autonomy.ceiling ${before.ceiling}`;
283
- const next = (0, project_caps_1.projectCapsOfText)(after);
284
- if ((0, project_caps_1.sameCaps)(before, next))
285
- return null;
286
- const raised = (0, project_caps_1.raisedCaps)(before, next);
287
- return raised.length > 0 ? raised.join(', ') : 'lowered';
317
+ return ['(the result cannot be read)'];
318
+ return (0, judgement_keys_1.judgementKeyChanges)(beforeText, after);
288
319
  }
320
+ const OWN_GATE_SETTINGS = 'these are the agent\'s own gate settings — changing one, in either direction, is the owner\'s act';
289
321
  function gitRmSignals(command, cwd, projectRoot, specsDir) {
290
322
  // A-SPEC-728 (round 24): the text as the shell joins it (`r\m -rf .git`, `eval rm\ -rf\ src`).
291
323
  const targets = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_2.joinShellText)(command))])];
@@ -541,11 +573,57 @@ function readApprovalFromEnv() {
541
573
  // measured false denial), and a command word that is a path ending in holmes-mcp is a start
542
574
  // (`./bin/holmes-mcp.js`, `node_modules/.bin/holmes-mcp` — measured bypass).
543
575
  const HOLMES_SERVER_TAIL = /\bholmes-mcp\b|dist[\\/]+holmes[\\/]+mcp[\\/]+(?:server|handlers)(?:\.js)?(?![\w.-])/;
576
+ /**
577
+ * @implements A-SPEC-794.139 (Behavior 5) — a program run (`node`, `bun`, `deno`, `tsx`, `ts-node`) starts the server only
578
+ * when its FIRST script argument is the entry (the package path, `holmes-mcp`, the mcp server or handlers module), or its
579
+ * `-e`/`-p` program names one (round 6: `require('@holmes-lab/holmes-kit')`). A name or path given as a later argument
580
+ * (`bun test P`, `node scripts/check.js P`, a grep pattern) is not a start. Linear: one split, one pass per segment.
581
+ */
582
+ const ENTRY_SCRIPT = /(?:^|\/)@holmes-lab\/holmes-kit(?:\/(?:bin\/holmes-mcp(?:\.js)?|dist\/holmes\/mcp\/(?:server|handlers)(?:\.js)?))?\/?$/;
583
+ const PROGRAM_HEAD = /^(?:.*\/)?(?:node|nodejs|bun|deno|tsx|ts-node)$/;
584
+ const PROGRAM_VALUE_OPTIONS = new Set(['-r', '--require', '--import', '--loader', '--experimental-loader', '--cwd', '--conditions', '-C']);
585
+ const firstScriptStartsServer = {
586
+ test(command) {
587
+ for (const seg of command.split(/[;&|\n]/)) {
588
+ const t = seg.trim().replace(/^\(\s*/, '').split(/\s+/).filter((x) => x !== '');
589
+ let i = 0;
590
+ while (i < t.length && (t[i] === 'exec' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(t[i])))
591
+ i++;
592
+ if (i >= t.length || !PROGRAM_HEAD.test(t[i]))
593
+ continue;
594
+ const bun = /(?:^|\/)bun$/.test(t[i]);
595
+ for (i++; i < t.length; i++) {
596
+ const w = t[i].replace(/^["']|["']$/g, '');
597
+ if (/^(?:-e|--eval|-p|--print)$/.test(w)) {
598
+ // round 6's reading: the package or its entry by name, not a file inside it (`P/package.json` is a read)
599
+ if (/@holmes-lab\/holmes-kit(?:\/(?:bin\/holmes-mcp(?:\.js)?|dist\/holmes\/mcp\/(?:server|handlers)(?:\.js)?))?(?![\w.-]|\/[\w.-])|holmes-mcp|dist[\\/]+holmes[\\/]+mcp/.test(t.slice(i + 1).join(' ')))
600
+ return true;
601
+ break;
602
+ }
603
+ if (w.startsWith('-')) {
604
+ if (PROGRAM_VALUE_OPTIONS.has(w)) {
605
+ if (ENTRY_SCRIPT.test((t[i + 1] ?? '').replace(/^["']|["']$/g, '')))
606
+ return true;
607
+ i++;
608
+ }
609
+ continue;
610
+ }
611
+ if (bun && w === 'run')
612
+ continue;
613
+ if (ENTRY_SCRIPT.test(w))
614
+ return true;
615
+ break; // the first script argument is something else
616
+ }
617
+ }
618
+ return false;
619
+ },
620
+ };
544
621
  const SERVER_RUNNERS = [
622
+ // the server MODULE or bin by path stays judged anywhere after a program word (a loader may run it: A-SPEC-753)
545
623
  (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:exec\s+)?(?:node|nodejs|bun|deno|tsx|ts-node)\b/, /[;&|\n]/, HOLMES_SERVER_TAIL),
546
- (0, linear_match_1.headThenTail)(/\b(?:npx|pnpx|bunx|npm\s+(?:exec|x)|pnpm\s+(?:exec|dlx)|yarn\s+dlx)\b/, /[;&|\n]/, /\bholmes-mcp\b/),
547
- // Round 6: the package itself, by name (`node node_modules/@holmes-lab/holmes-kit`, `require('@holmes-lab/holmes-kit')`).
548
- (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:exec\s+)?(?:node|nodejs|bun|deno|tsx|ts-node)\b/, /[;&|\n]/, /@holmes-lab\/holmes-kit(?:\/(?:bin\/holmes-mcp(?:\.js)?|dist\/holmes\/mcp\/(?:server|handlers)(?:\.js)?))?(?![\w.-]|\/[\w.-])/),
624
+ // the PACKAGE by name only as the first script argument (or a -r/-e value): A-SPEC-794.139 Behavior 5
625
+ firstScriptStartsServer,
626
+ (0, linear_match_1.headThenTail)(/\b(?:npx|pnpx|bunx|bun\s+x|npm\s+(?:exec|x)|pnpm\s+(?:exec|dlx)|yarn\s+dlx)\b/, /[;&|\n]/, /\bholmes-mcp\b/),
549
627
  // Round 5 (measured): `yarn holmes-mcp`, `pnpm run holmes-mcp` — package-manager script runners.
550
628
  (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:yarn|pnpm|npm\s+run)\b/, /[;&|\n]/, /^\s*(?:run\s+)?holmes-mcp(?=$|[\s;&|)])/),
551
629
  (0, linear_match_1.headThenTail)(/(?:^|[;&|(])\s*/, /[;&|\n]/, /^(?:exec\s+)?(?:[^\s;&|()]*[\\/])?holmes-mcp(?:\.js)?(?=$|[\s;&|)])/),
@@ -983,57 +1061,898 @@ const referenceInputDeny = (shown, what) => ({ permissionDecision: 'deny', refus
983
1061
  const GOVERNED_CLI = [
984
1062
  { head: 'runtime-binding', ops: new Set(['setup', 'remove']), act: 'runtime-binding setup/remove changes which Holmes build governs a workspace (governance wiring)', preview: '--dry-run' },
985
1063
  { head: 'ledger', ops: new Set(['rechain']), act: 'ledger rechain rewrites the provenance chain wholesale (it re-chains and records the result)', preview: '--dry-run' },
1064
+ // @implements A-SPEC-772.15 — `init` options that change what the gate sees (or strip it, or widen approvals) are the
1065
+ // owner's; so is any option not on the allow-list (a new option is the owner's until it is read). Plain init, another
1066
+ // harness, the mode and the MCP launcher stay free: they repair or add, they do not weaken (measured 2026-11-16:
1067
+ // `init --matcher Nothing` and `--specs-dir <empty>` switched the gate off without approval).
1068
+ { head: 'init', ops: new Set(['--remove', '--force', '--matcher', '--specs-dir', '--settings', '--autonomy']),
1069
+ act: 'init with --remove, --force, --matcher, --specs-dir, --settings or --autonomy changes what the gate sees or approves (governance wiring)',
1070
+ preview: '--dry-run',
1071
+ allowed: new Set(['--help', '-h', '--dry-run', '--target', '--mode', '--agent', '--mcp-launcher', '--no-mcp', '--no-autonomy']) },
986
1072
  ];
1073
+ /** `--name=value` read as `--name` (A-SPEC-772.15). */
1074
+ const optionName = (t) => (t.startsWith('--') && t.includes('=') ? t.slice(0, t.indexOf('=')) : t);
1075
+ // A-SPEC-772.16: compared without case (`Holmes-Kit` runs the same file on a case-insensitive file system)
987
1076
  const isCliWord = (text) => {
988
- const base = (text.replace(/\\/g, '/').split('/').pop() ?? '').replace(/\.(?:js|cjs|mjs|cmd|exe|ps1)$/i, '');
989
- return base === 'holmes-kit' || /^@holmes-lab\/holmes-kit(?:@[^\s]*)?$/.test(text);
1077
+ const base = (text.replace(/\\/g, '/').split('/').pop() ?? '').replace(/\.(?:js|cjs|mjs|cmd|exe|ps1)$/i, '').toLowerCase();
1078
+ return base === 'holmes-kit' || /^@holmes-lab\/holmes-kit(?:@[^\s]*)?$/i.test(text);
1079
+ };
1080
+ /** @implements A-SPEC-772.16 — the programs that run the word after them (the CLI word counts only as the command or after one). */
1081
+ const CLI_RUNNERS = /^(?:npx|bunx|pnpm|pnpx|yarn|npm|node|exec|sudo|env|nohup|command|time|doas|bun|deno)$/;
1082
+ /** The governed acts' words: the head's index in the window (its first non-option word), or -1. */
1083
+ const firstWordAt = (window) => window.findIndex((x) => !x.text.startsWith('-'));
1084
+ /**
1085
+ * @implements A-SPEC-772.23 — the heads that write a workspace's gate wiring from the copy that runs them. Run from any
1086
+ * holmes-kit package other than the one governing the session, they re-wire the gate to that copy (review A: an old copy
1087
+ * re-pointed the gate, and labels are cheap to change — the copy is compared by real path, never by version).
1088
+ */
1089
+ const ROOT_BOUND_HEADS = new Set(['init', 'upgrade']);
1090
+ /** @implements A-SPEC-772.28 (review A M3) — one set of governed heads for every guard (upgrade was missing from three). */
1091
+ const GOVERNED_HEADS = [...GOVERNED_CLI.map((g) => g.head), ...ROOT_BOUND_HEADS];
1092
+ /** @implements A-SPEC-772.28 (low 4) — one test of "writes nothing" for both rules: help anywhere, or the head's preview. */
1093
+ const writesNothing = (rest, preview) => rest.some((x) => x === '--help' || x === '-h' || (preview !== undefined && x === preview));
1094
+ /**
1095
+ * @implements A-SPEC-772.30 — a word for the shell the Bash tool runs (sh; Git Bash on Windows): bare when it holds only
1096
+ * characters no shell reads specially, else single-quoted with each `'` as `'\''`. One function for every word of the
1097
+ * self-recovery command — a root with a space, a `C:\…` root (backslashes kept inside single quotes) and an argument that
1098
+ * held quotes come back as the same words (review of 772.28, H-2: the recovery command broke on each).
1099
+ */
1100
+ function shellWord(word) {
1101
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
1102
+ }
1103
+ /** @implements A-SPEC-772.33, A-SPEC-772.34 — the runners the CLI-root resolver reads, and the wrappers it reads in front of them. */
1104
+ const READ_RUNNERS = new Set(['npx', 'bunx', 'pnpm', 'pnpx', 'yarn', 'npm', 'node', 'bun', 'deno']);
1105
+ const NPX_LIKE_RUNNERS = new Set(['npx', 'bunx', 'pnpm', 'pnpx', 'yarn', 'npm']);
1106
+ const READ_WRAPPERS = new Set(['time', 'nohup', 'exec', 'command', 'env', 'sudo', 'doas']);
1107
+ /** A-SPEC-772.34 — package-manager acts the package reader (A-SPEC-794.134) reads: understood on a governed line. */
1108
+ const PACKAGE_ACTS = new Set(['install', 'i', 'add', 'remove', 'rm', 'uninstall', 'un', 'update', 'up', 'upgrade', 'link', 'ln', 'unlink', 'ci']);
1109
+ /**
1110
+ * A-SPEC-772.34 §6 — programs that run nothing they are given. Writers are not here (a copy into `.bin` before an npx on
1111
+ * the same line changes what runs), nor pagers (`less`, `more`, `man` run preprocessors).
1112
+ */
1113
+ const DATA_PROGRAMS = new Set(['echo', 'printf', 'grep', 'egrep', 'fgrep', 'cat', 'head', 'tail', 'wc', 'which', 'type', 'whatis', 'jq',
1114
+ 'ls', 'sort', 'uniq', 'cut', 'tr', 'diff', 'cmp', 'stat', 'file', 'du', 'df', 'basename', 'dirname', 'realpath', 'readlink', 'date',
1115
+ 'sleep', 'test', '[', 'true', 'false', 'pwd', 'nl', 'od', 'base64', 'shasum', 'sha256sum', 'md5', 'column', 'comm', 'paste', 'fold',
1116
+ 'rev', 'seq', 'uname', 'whoami', 'id', 'hostname', 'tree']);
1117
+ /** git's built-in subcommands that run no command they are given (`config`, `submodule`, `difftool`, aliases are not). */
1118
+ const GIT_DATA = new Set(['status', 'log', 'diff', 'show', 'add', 'commit', 'push', 'fetch', 'pull', 'checkout', 'switch', 'branch', 'tag',
1119
+ 'rev-parse', 'ls-files', 'mv', 'rm', 'restore', 'reset', 'stash', 'merge', 'rebase', 'cherry-pick', 'revert', 'blame', 'grep', 'remote',
1120
+ 'describe', 'shortlog', 'cat-file', 'ls-tree', 'rev-list', 'merge-base', 'worktree', 'init', 'clone', 'apply', 'am', 'format-patch',
1121
+ 'notes', 'reflog', 'show-ref', 'symbolic-ref', 'check-ignore', 'for-each-ref', 'update-index', 'hash-object', 'write-tree',
1122
+ 'count-objects', 'diff-tree', 'diff-index', 'range-diff', 'version']);
1123
+ const GH_DATA = new Set(['pr', 'issue', 'api', 'repo', 'release', 'run', 'workflow', 'search', 'browse', 'label']);
1124
+ const CD_WORDS = /^(?:cd|pushd|popd|chdir)$/;
1125
+ const SHELL_WORDS = /^(?:sh|bash|zsh|dash|ksh)$/;
1126
+ const GRAMMAR_WORDS = /^(?:\{|\}|!|if|then|else|elif|fi|while|until|do|done|for|in|case|esac|select|function|coproc|\[\[|eval|builtin|source|\.)$/;
1127
+ const progName = (t) => t.replace(/^.*[/\\]/, '').toLowerCase();
1128
+ const namesCli = (t) => /holmes-kit/i.test(t.replace(/['"\\]/g, ''));
1129
+ const namesHead = (t) => t.split(/[^A-Za-z0-9_.@/\\-]+/).some((x) => GOVERNED_HEADS.includes(x));
1130
+ const afterAssignments = (words) => {
1131
+ let at = 0;
1132
+ while (at < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[at].text))
1133
+ at++;
1134
+ return words.slice(at);
990
1135
  };
991
- function governedCliAct(command, depth = 0) {
992
- // the cheap look first, over the text with quoting removed (`holmes-k''it` is the CLI word to the shell — measured)
993
- const bare = command.replace(/['"\\]/g, '');
994
- if (depth > 4 || !/holmes-kit/.test(bare) || !GOVERNED_CLI.some((g) => bare.includes(g.head)))
1136
+ function stripHeredocBodies(command) {
1137
+ const out = [];
1138
+ const bodies = [];
1139
+ const pending = [];
1140
+ const done = (p) => { bodies.push({ opener: p.opener, body: p.body.join('\n'), receiver: p.receiver, expands: p.expands, tag: p.tag, at: p.at }); };
1141
+ let offset = 0; // A-SPEC-772.37: where the kept line starts in the returned text
1142
+ let q = '';
1143
+ // A-SPEC-772.35 §3: a `$(` inside double quotes opens a fresh quoting context — Claude Code's own commit and PR form
1144
+ // (`-m "$(cat <<'EOF' … EOF\n)"`) holds its heredoc there; the outer quotes come back at the matching `)`.
1145
+ // A-SPEC-772.36: an unquoted `$(` opens one too, and each context keeps where its current command starts, so the
1146
+ // command that receives a `<<` is known (`OUT="$(bash <<'EOF' …)"` — the line's own commands hold only `OUT=`)
1147
+ const outer = [];
1148
+ let depth = 0;
1149
+ for (const line of command.split('\n')) {
1150
+ if (pending.length > 0) {
1151
+ const p = pending[0];
1152
+ if ((p.dash ? line.replace(/^\t+/, '') : line) === p.tag) {
1153
+ done(p);
1154
+ pending.shift();
1155
+ }
1156
+ else
1157
+ p.body.push(line);
1158
+ continue;
1159
+ }
1160
+ out.push(line);
1161
+ const lineAt = offset;
1162
+ offset += line.length + 1;
1163
+ let start = 0;
1164
+ for (let i = 0; i < line.length; i++) {
1165
+ const c = line[i];
1166
+ if (q !== "'" && c === '\\') {
1167
+ i++;
1168
+ continue;
1169
+ }
1170
+ if (q !== "'" && c === '$' && line[i + 1] === '(' && line[i + 2] !== '(') {
1171
+ outer.push({ q, depth, start });
1172
+ q = '';
1173
+ depth = 0;
1174
+ start = i + 2;
1175
+ i++;
1176
+ continue;
1177
+ }
1178
+ if (q === '' && outer.length > 0 && c === '(') {
1179
+ depth++;
1180
+ continue;
1181
+ }
1182
+ if (q === '' && outer.length > 0 && c === ')') {
1183
+ if (depth > 0)
1184
+ depth--;
1185
+ else {
1186
+ const o = outer.pop();
1187
+ q = o.q;
1188
+ depth = o.depth;
1189
+ start = o.start;
1190
+ }
1191
+ continue;
1192
+ }
1193
+ if (q === '' && (c === "'" || c === '"')) {
1194
+ q = c;
1195
+ continue;
1196
+ }
1197
+ if (q !== '' && c === q) {
1198
+ q = '';
1199
+ continue;
1200
+ }
1201
+ // A-SPEC-772.37 (A-L1): the `&` of `>&2`, `&>` and `2>&1` is a redirection, not a command boundary
1202
+ if (q === '' && c === '&' && (line[i - 1] === '>' || line[i - 1] === '<' || line[i + 1] === '>'))
1203
+ continue;
1204
+ if (q === '' && (c === ';' || c === '|' || c === '&')) {
1205
+ start = i + 1;
1206
+ continue;
1207
+ }
1208
+ if (q === '' && c === '<' && line[i + 1] === '<' && line[i + 2] !== '<' && line[i - 1] !== '<') {
1209
+ // A-SPEC-772.37: `<<WORD`, `<<'WORD'`, `<<"WORD"` and `<<\WORD`, a word holding `-` too (`<<'END-X'`)
1210
+ const m = /^<<(-?)\s*(?:(['"])([^'"\n]+)\2|\\([A-Za-z0-9_.-]+)|([A-Za-z_][A-Za-z0-9_.-]*))/.exec(line.slice(i));
1211
+ if (m !== null) {
1212
+ const tag = m[3] ?? m[4] ?? m[5];
1213
+ pending.push({ tag, dash: m[1] === '-', opener: line, receiver: line.slice(start, i), expands: m[5] !== undefined, at: lineAt + i, body: [] });
1214
+ i += m[0].length - 1;
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ for (const p of pending)
1220
+ done(p); // unterminated: to the end
1221
+ return { text: out.join('\n'), bodies };
1222
+ }
1223
+ /** @implements A-SPEC-772.34 §6 — a data program with no option that makes it run something. */
1224
+ function dataProgram(words) {
1225
+ const w0 = words[0];
1226
+ if (w0 === undefined || !w0.known || (w0.glob && w0.text !== '['))
1227
+ return false;
1228
+ const name = progName(w0.text);
1229
+ if (name === 'rg' || name === 'ag')
1230
+ return !words.some((w) => /^--pre(?:-glob)?(?:=|$)/.test(w.text));
1231
+ if (name === 'gh') {
1232
+ const sub = words.slice(1).find((w) => !w.text.startsWith('-'));
1233
+ return sub !== undefined && sub.known && GH_DATA.has(sub.text);
1234
+ }
1235
+ if (name === 'git') {
1236
+ let k = 1;
1237
+ while (k < words.length && words[k].text.startsWith('-')) {
1238
+ const t = words[k].text;
1239
+ if (t === '-c' || /^--(?:config-env|exec-path)/.test(t))
1240
+ return false;
1241
+ if (t === '-C' || t === '--git-dir' || t === '--work-tree' || t === '--namespace')
1242
+ k++;
1243
+ k++;
1244
+ }
1245
+ const sub = words[k];
1246
+ if (sub === undefined || !sub.known || !GIT_DATA.has(sub.text))
1247
+ return false;
1248
+ if (sub.text === 'rebase' && words.slice(k + 1).some((w) => /^(?:--exec(?:=.*)?|-x)$/.test(w.text)))
1249
+ return false;
1250
+ if (sub.text === 'grep' && words.slice(k + 1).some((w) => /^(?:-O.*|--open-files-in-pager(?:=.*)?)$/.test(w.text)))
1251
+ return false;
1252
+ return true;
1253
+ }
1254
+ return DATA_PROGRAMS.has(name);
1255
+ }
1256
+ function shellStages(src) {
1257
+ const stages = [];
1258
+ // each stage's own text: a nested context is one computed word (`$H`), so a 120 KB nest is read once, not per level
1259
+ const holes = [];
1260
+ let pipes = 0;
1261
+ const open = (start, parent, pipe, idx) => {
1262
+ stages.push({ start, end: src.length, text: '', pipe, idx, parent });
1263
+ holes.push([]);
1264
+ return stages.length - 1;
1265
+ };
1266
+ const close = (k, end) => {
1267
+ stages[k].end = end;
1268
+ let t = '', at = stages[k].start;
1269
+ for (const [a, b] of holes[k]) {
1270
+ if (a < at)
1271
+ continue;
1272
+ t += src.slice(at, a) + '$H';
1273
+ at = Math.min(b, end);
1274
+ }
1275
+ stages[k].text = t + src.slice(at, end);
1276
+ };
1277
+ const hole = (k, from, to) => { holes[k].push([from, to]); };
1278
+ let q = '';
1279
+ let depth = 0;
1280
+ let cur = open(0, -1, pipes++, 0);
1281
+ const stack = [];
1282
+ const next = (i, skip) => { close(cur, i); cur = open(i + skip, stages[cur].parent, pipes++, 0); };
1283
+ for (let i = 0; i < src.length; i++) {
1284
+ const c = src[i];
1285
+ if (q !== "'" && c === '\\') {
1286
+ i++;
1287
+ continue;
1288
+ }
1289
+ if (q !== "'" && c === '$' && src[i + 1] === '(' && src[i + 2] === '(') { // arithmetic: to its `))`
1290
+ let d = 0, j = i + 1;
1291
+ for (; j < src.length; j++) {
1292
+ if (src[j] === '(')
1293
+ d++;
1294
+ else if (src[j] === ')' && --d === 0)
1295
+ break;
1296
+ }
1297
+ i = j;
1298
+ continue;
1299
+ }
1300
+ const tickTop = stack.length > 0 && stack[stack.length - 1].tick;
1301
+ if (q !== "'" && c === '`') {
1302
+ if (tickTop) {
1303
+ close(cur, i);
1304
+ const o = stack.pop();
1305
+ q = o.q;
1306
+ depth = o.depth;
1307
+ cur = o.cur;
1308
+ hole(cur, o.from, i + 1);
1309
+ }
1310
+ else {
1311
+ stack.push({ q, depth, cur, tick: true, from: i });
1312
+ q = '';
1313
+ depth = 0;
1314
+ cur = open(i + 1, cur, pipes++, 0);
1315
+ }
1316
+ continue;
1317
+ }
1318
+ if ((q !== "'" && c === '$' || q === '' && (c === '<' || c === '>')) && src[i + 1] === '(') {
1319
+ stack.push({ q, depth, cur, tick: false, from: i });
1320
+ q = '';
1321
+ depth = 0;
1322
+ cur = open(i + 2, cur, pipes++, 0);
1323
+ i++;
1324
+ continue;
1325
+ }
1326
+ if (q === '' && c === '(') {
1327
+ depth++;
1328
+ continue;
1329
+ }
1330
+ if (q === '' && c === ')') {
1331
+ if (depth > 0) {
1332
+ depth--;
1333
+ continue;
1334
+ }
1335
+ if (stack.length > 0 && !tickTop) {
1336
+ close(cur, i);
1337
+ const o = stack.pop();
1338
+ q = o.q;
1339
+ depth = o.depth;
1340
+ cur = o.cur;
1341
+ hole(cur, o.from, i + 1);
1342
+ }
1343
+ continue;
1344
+ }
1345
+ if (q === '' && (c === "'" || c === '"')) {
1346
+ q = c;
1347
+ continue;
1348
+ }
1349
+ if (q !== '' && c === q) {
1350
+ q = '';
1351
+ continue;
1352
+ }
1353
+ if (q !== '')
1354
+ continue;
1355
+ if (c === '\n' || c === ';') {
1356
+ next(i, 1);
1357
+ continue;
1358
+ }
1359
+ if (c === '&') {
1360
+ if (src[i + 1] === '&') {
1361
+ next(i, 2);
1362
+ i++;
1363
+ continue;
1364
+ }
1365
+ if (src[i - 1] === '>' || src[i - 1] === '<' || src[i + 1] === '>')
1366
+ continue; // `>&2`, `&>`, `2>&1`
1367
+ next(i, 1);
1368
+ continue;
1369
+ }
1370
+ if (c === '|') {
1371
+ if (src[i + 1] === '|') {
1372
+ next(i, 2);
1373
+ i++;
1374
+ continue;
1375
+ }
1376
+ if (src[i - 1] === '>')
1377
+ continue; // `>|`
1378
+ const amp = src[i + 1] === '&' ? 1 : 0;
1379
+ const s = stages[cur];
1380
+ close(cur, i);
1381
+ cur = open(i + 1 + amp, s.parent, s.pipe, s.idx + 1);
1382
+ i += amp;
1383
+ }
1384
+ }
1385
+ close(cur, src.length);
1386
+ for (const o of stack.reverse()) {
1387
+ hole(o.cur, o.from, src.length);
1388
+ close(o.cur, src.length);
1389
+ }
1390
+ return stages;
1391
+ }
1392
+ /** @implements A-SPEC-772.37 §2 — the programs that read code from their arguments or input (after `commandOf`). */
1393
+ const CODE_READERS = /^(?:sh|bash|zsh|dash|ksh|eval|source|\.|node|bun|deno|tsx|ts-node|python|python3|perl|ruby)$/;
1394
+ /** @implements A-SPEC-772.37 §4 — the command substitutions an unquoted tag's body runs (`$(…)` not `$((`, backticks). */
1395
+ function bodyRuns(body) {
1396
+ const runs = [];
1397
+ for (let i = 0; i < body.length; i++) {
1398
+ const c = body[i];
1399
+ if (c === '\\') {
1400
+ i++;
1401
+ continue;
1402
+ }
1403
+ if (c === '$' && body[i + 1] === '(') {
1404
+ let d = 0, j = i + 1;
1405
+ for (; j < body.length; j++) {
1406
+ if (body[j] === '(')
1407
+ d++;
1408
+ else if (body[j] === ')' && --d === 0)
1409
+ break;
1410
+ }
1411
+ if (body[i + 2] !== '(')
1412
+ runs.push(body.slice(i + 2, j));
1413
+ i = j;
1414
+ continue;
1415
+ }
1416
+ if (c === '`') {
1417
+ const j = body.indexOf('`', i + 1);
1418
+ runs.push(body.slice(i + 1, j < 0 ? body.length : j));
1419
+ i = j < 0 ? body.length : j;
1420
+ }
1421
+ }
1422
+ return runs;
1423
+ }
1424
+ function lineFlow(text, bodies) {
1425
+ const stages = shellStages(text);
1426
+ const parsedOf = stages.map((s) => { try {
1427
+ return (0, shell_syntax_1.shellWords)(s.text, {}, undefined, null, true);
1428
+ }
1429
+ catch {
995
1430
  return null;
996
- const parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, null, true);
997
- if (parsed.overflow || parsed.subs.length > 0)
998
- return { unjudged: 'it names holmes-kit and a governed subcommand, and holds a substitution or more than the gate reads' };
1431
+ } });
1432
+ const wordsOf = (k) => afterAssignments(parsedOf[k]?.commands[0]?.words ?? []);
1433
+ // linear in the stages (a 120 KB line holds thousands — A-SPEC-728's whole-hook bound): each reader name once, each
1434
+ // pipeline's later reader found from its end
1435
+ const names = stages.map((_, k) => {
1436
+ const w = wordsOf(k);
1437
+ if (w.length === 0)
1438
+ return null;
1439
+ let real = w;
1440
+ try {
1441
+ real = (0, shell_syntax_1.commandOf)(w);
1442
+ }
1443
+ catch {
1444
+ return null;
1445
+ }
1446
+ const n = progName(real[0]?.text ?? '');
1447
+ return CODE_READERS.test(n) ? n : null;
1448
+ });
1449
+ const readerName = (k) => names[k];
1450
+ const byPipe = new Map();
1451
+ stages.forEach((s, k) => { const l = byPipe.get(s.pipe); if (l)
1452
+ l.push(k);
1453
+ else
1454
+ byPipe.set(s.pipe, [k]); });
1455
+ const laterReader = new Map(); // stage → a reader later in its pipeline
1456
+ for (const ks of byPipe.values()) {
1457
+ ks.sort((a, b) => stages[a].idx - stages[b].idx);
1458
+ let after = null;
1459
+ for (let j = ks.length - 1; j >= 0; j--) {
1460
+ laterReader.set(ks[j], after);
1461
+ after = after ?? names[ks[j]];
1462
+ }
1463
+ }
1464
+ // one pass in stage order: a parent stage is opened before its child (no recursion 40,000 levels deep)
1465
+ const reach = [];
1466
+ stages.forEach((s, k) => { reach[k] = readerName(k) ?? laterReader.get(k) ?? (s.parent >= 0 ? reach[s.parent] : null); });
1467
+ const reaches = (k) => reach[k];
1468
+ const stageAt = (at) => {
1469
+ let best = -1;
1470
+ for (let k = 0; k < stages.length; k++)
1471
+ if (stages[k].start <= at && at < stages[k].end && (best < 0 || stages[k].start >= stages[best].start))
1472
+ best = k;
1473
+ return best;
1474
+ };
1475
+ // a variable assigned from a heredoc's text and read by a reader on the line (`X="$(cat <<'EOF' …)"; eval "$X"`)
1476
+ const viaVariable = (k) => {
1477
+ let root = k;
1478
+ while (stages[root].parent >= 0)
1479
+ root = stages[root].parent;
1480
+ if (root === k)
1481
+ return null;
1482
+ const v = /^\s*([A-Za-z_][A-Za-z0-9_]*)=/.exec(stages[root].text)?.[1];
1483
+ if (v === undefined)
1484
+ return null;
1485
+ const read = new RegExp(`\\$\\{?${v}(?![A-Za-z0-9_])`);
1486
+ for (let j = 0; j < stages.length; j++)
1487
+ if (j !== root && read.test(stages[j].text)) {
1488
+ const r = reaches(j);
1489
+ if (r !== null)
1490
+ return r;
1491
+ }
1492
+ return null;
1493
+ };
1494
+ const readerOf = (b) => { const k = stageAt(b.at); return k < 0 ? null : reaches(k) ?? viaVariable(k); };
1495
+ const textBody = (b) => {
1496
+ const k = stageAt(b.at);
1497
+ if (k < 0 || reaches(k) !== null || viaVariable(k) !== null)
1498
+ return false;
1499
+ const w = wordsOf(k);
1500
+ return w.length > 0 && dataProgram(w);
1501
+ };
1502
+ // a reaching stage's own text: the shell reader keeps no here-string or heredoc redirect words (`bash <<< '…'`)
1503
+ const readerWords = stages.filter((_, k) => reaches(k) !== null).map((s) => s.text);
1504
+ const runs = bodies.filter((b) => b.expands && textBody(b)).flatMap((b) => bodyRuns(b.body));
1505
+ return { textBody, readerOf, readerWords, bodyRuns: runs };
1506
+ }
1507
+ /**
1508
+ * @implements A-SPEC-772.34 §4 — whether the line is the contract's: (a) words that run (not a data program's arguments,
1509
+ * plus every substitution and every non-data heredoc body) name the CLI, and any word names a governed head; (b) a
1510
+ * non-data command holds a runner, shell, cd or CLI word and a computed or glob word; (c) a command word is computed.
1511
+ */
1512
+ function contractScope(parsed, bodies, text, flow) {
1513
+ let cli = false, head = false;
1514
+ // A-SPEC-772.37 §3 — what a code reader receives, in every context and pipe stage (`echo '…' | sudo sh`,
1515
+ // `$(cat <<'EOF' | bash …)`, `bash -c "$(cat <<'EOF' …)"`): the reaching stages' words; never the whole text
1516
+ for (const w of flow.readerWords) {
1517
+ if (namesCli(w))
1518
+ cli = true;
1519
+ if (namesHead(w.replace(/['"\\]/g, ' ')))
1520
+ head = true;
1521
+ }
1522
+ for (const r of flow.bodyRuns) {
1523
+ if (namesCli(r))
1524
+ cli = true;
1525
+ if (namesHead(r))
1526
+ head = true;
1527
+ }
1528
+ // A-SPEC-772.34 (supervisor's decision on the corpus, option 2): a computed command word or a computed program to run
1529
+ // brings the line in only when the CLI or a governed head is spelled somewhere on it — a line that spells neither shows
1530
+ // nothing of holmes-kit, which is outside the string judgement's boundary (the 0.41.4 after-the-fact check's)
1531
+ const headSpelled = namesHead(text.replace(/['"\\]/g, ' '));
1532
+ const cliSpelled = namesCli(text);
1533
+ // a computed program counts when a governed head is spelled, or the CLI is spelled and the subcommand after the
1534
+ // computed word is not seen (`$C $SUB`); a visible other subcommand is that subcommand's (`$H lock recover` — 245.19)
1535
+ const spelledFor = (rest) => {
1536
+ if (headSpelled)
1537
+ return true;
1538
+ if (!cliSpelled)
1539
+ return false;
1540
+ const sub = rest.find((w) => !w.text.startsWith('-'));
1541
+ return sub === undefined || !sub.known || sub.glob;
1542
+ };
1543
+ for (const one of parsed.commands) {
1544
+ const words = afterAssignments(one.words);
1545
+ const w0 = words[0];
1546
+ if (w0 === undefined)
1547
+ continue;
1548
+ if (!w0.known || (w0.glob && w0.text !== '[')) {
1549
+ if (spelledFor(words.slice(1)))
1550
+ return true;
1551
+ continue;
1552
+ } // (`[` is the test program)
1553
+ if (words.some((w) => namesHead(w.text)))
1554
+ head = true;
1555
+ if (dataProgram(words))
1556
+ continue;
1557
+ const unread = (w) => w !== undefined && (!w.known || w.glob);
1558
+ if (words.some((w) => namesCli(w.text))) {
1559
+ cli = true;
1560
+ // the subcommand computed on a command that names the CLI (`… holmes-kit.js ini${U:-t}`); other computed words
1561
+ // there are the subcommand's arguments (`holmes-kit doctor --target $D` — census of 794.113)
1562
+ const at = words.findIndex((w) => isCliWord(w.text));
1563
+ if (at >= 0 && unread(words.slice(at + 1).find((w) => !w.text.startsWith('-'))))
1564
+ return true;
1565
+ }
1566
+ // (b) a computed or glob word where the program to run is named: a runner's script or package, a shell's string or
1567
+ // script (`node <old>/bin/holmes-ki?.js`, `node …/$V.js`, `sh -c "$S"`, `npx $P`) — not any argument (measured on
1568
+ // 25,611 agent commands: any computed word on a runner refused 5.95% of them)
1569
+ let real = words;
1570
+ try {
1571
+ real = (0, shell_syntax_1.commandOf)(words);
1572
+ }
1573
+ catch {
1574
+ return true;
1575
+ }
1576
+ const n = progName(real[0]?.text ?? '');
1577
+ const at = real.findIndex((w, k) => k > 0 && !w.text.startsWith('-'));
1578
+ const op = at > 0 ? real[at] : undefined;
1579
+ if (unread(op) && (/^(?:node|bun|deno|tsx|ts-node)$/.test(n) || NPX_LIKE_RUNNERS.has(n) || SHELL_WORDS.test(n)) && spelledFor(real.slice(at + 1)))
1580
+ return true;
1581
+ }
1582
+ for (const s of parsed.subs) {
1583
+ if (namesCli(s))
1584
+ cli = true;
1585
+ if (namesHead(s))
1586
+ head = true;
1587
+ }
1588
+ for (const b of bodies)
1589
+ if (!flow.textBody(b)) {
1590
+ if (namesCli(b.body))
1591
+ cli = true;
1592
+ if (namesHead(b.body))
1593
+ head = true;
1594
+ }
1595
+ return cli && head;
1596
+ }
1597
+ /** @implements A-SPEC-772.34 §5 — a command that runs the CLI as the resolver reads it, or why it is not one. */
1598
+ function cliCommandProblem(words) {
1599
+ if (words[0].text === 'env' && words.slice(1).some((w) => w.text.startsWith('-')))
1600
+ return '`env` with an option (`env -C`, `env -S` …)';
1601
+ let real;
1602
+ try {
1603
+ real = (0, shell_syntax_1.commandOf)(words);
1604
+ }
1605
+ catch {
1606
+ return 'wrappers nested deeper than the gate reads';
1607
+ }
1608
+ const r0 = real[0];
1609
+ if (r0 === undefined)
1610
+ return `\`${words[0].text}\` with nothing to run`;
1611
+ // only the wrappers the resolver reads may stand in front (`timeout`, `nice`, `stdbuf`, `busybox` … are not read)
1612
+ if (r0 !== words[0] && !words.slice(0, words.indexOf(r0)).every((w) => READ_WRAPPERS.has(w.text) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w.text) || w.text.startsWith('-'))) {
1613
+ return `\`${words[0].text}\` in front of \`${r0.text}\``;
1614
+ }
1615
+ if (isCliWord(r0.text))
1616
+ return null;
1617
+ const name = progName(r0.text);
1618
+ if (SHELL_WORDS.test(name)) {
1619
+ const c = real.findIndex((w, k) => k > 0 && /^-\w*c\w*$/.test(w.text));
1620
+ return c > 0 && real[c + 1] !== undefined && real.slice(1, c).every((w) => /^-\w+$/.test(w.text)) ? null : `\`${r0.text}\` reading a script or its input`;
1621
+ }
1622
+ if (name === 'node' || name === 'deno' || (name === 'bun' && real[1]?.text !== 'x')) {
1623
+ return real[1] !== undefined && isCliWord(real[1].text) ? null : `\`${r0.text}\` given something other than the holmes-kit file first`;
1624
+ }
1625
+ if (NPX_LIKE_RUNNERS.has(name.replace(/\.cmd$/, '')) || name === 'bun') {
1626
+ const from = name === 'bun' ? 2 : 1;
1627
+ if (from === 1 && real[1] !== undefined && PACKAGE_ACTS.has(real[1].text))
1628
+ return null; // the package reader's (A-SPEC-794.134)
1629
+ // a runner that names the holmes-kit package in any form (`dlx`, `-p` pairs, `--package=`, `-p@…`) is read whole by the
1630
+ // package reader (A-SPEC-794.134–794.139), which keeps the owner's approval route for it
1631
+ if (real.slice(1).some((w) => /@holmes-lab\/holmes-kit/i.test(w.text)))
1632
+ return null;
1633
+ const { SAFE_RUNNER_WORDS } = require('../guardrail/cli-root');
1634
+ for (let k = from; k < real.length; k++) {
1635
+ const t = real[k].text;
1636
+ if (isCliWord(t))
1637
+ return null;
1638
+ // `dlx` is read by the resolver as a runner it cannot resolve: it refuses with the self-recovery command (772.30)
1639
+ if (SAFE_RUNNER_WORDS.has(t) || t === 'dlx')
1640
+ continue;
1641
+ if ((t === '-p' || t === '--package') && /^@holmes-lab\/holmes-kit(?:@.*)?$/i.test(real[k + 1]?.text ?? '')) {
1642
+ k++;
1643
+ continue;
1644
+ }
1645
+ if (/^--package=@holmes-lab\/holmes-kit(?:@.*)?$/i.test(t))
1646
+ continue;
1647
+ return `the runner word \`${t}\` the gate does not read`;
1648
+ }
1649
+ return `\`${r0.text}\` running something other than holmes-kit`;
1650
+ }
1651
+ return `\`${r0.text}\`, a program the gate does not read`;
1652
+ }
1653
+ /**
1654
+ * @implements A-SPEC-772.33 — the governed CLI line contract (owner decision 11/17, after the same defect recurred in
1655
+ * 772.30, 772.31 and 772.32): null when the reader understood the whole line — every simple command starts with a word
1656
+ * the allow list names (A-SPEC-772.33 §3) and the text holds no construct the reader drops — else the construct's name.
1657
+ */
1658
+ function unreadConstruct(command, parsed, bodies = [], flow = lineFlow(command, bodies)) {
1659
+ // A-SPEC-772.34 §7 — the text outside quotes (heredoc bodies are already out): an unquoted `(` that is not `$(`, `<(`,
1660
+ // `>(` or the second of `$((`, a `${…}` whose body runs a command, `$'…'`, and the names below. Inside quotes they are text.
1661
+ let q = '';
1662
+ let unquoted = '';
1663
+ for (let i = 0; i < command.length; i++) {
1664
+ const c = command[i];
1665
+ if (q !== "'" && c === '\\') {
1666
+ unquoted += q === '' ? ' ' : '';
1667
+ i++;
1668
+ continue;
1669
+ }
1670
+ if (q === '' && c === '$' && command[i + 1] === "'")
1671
+ return "an ANSI-C quoted string `$'…'`";
1672
+ if (q === '' && (c === "'" || c === '"')) {
1673
+ q = c;
1674
+ unquoted += ' ';
1675
+ continue;
1676
+ }
1677
+ if (q !== '' && c === q) {
1678
+ q = '';
1679
+ unquoted += ' ';
1680
+ continue;
1681
+ }
1682
+ if (q === '' && c === '(' && !/[$<>]/.test(command[i - 1] ?? '') && !(command[i - 1] === '(' && command[i - 2] === '$'))
1683
+ return 'a subshell or group `( … )`';
1684
+ if (q !== "'" && c === '$' && command[i + 1] === '{') {
1685
+ const close = command.indexOf('}', i + 2);
1686
+ const body = command.slice(i + 2, close < 0 ? command.length : close);
1687
+ if (close < 0 || /\$\(|`|\$\{/.test(body))
1688
+ return 'a parameter expansion that runs a command `${…$(…)}`';
1689
+ }
1690
+ unquoted += q === '' ? c : ' ';
1691
+ }
1692
+ if (/CDPATH/.test(unquoted))
1693
+ return '`CDPATH`';
1694
+ if (/LESS(?:OPEN|CLOSE)/.test(unquoted))
1695
+ return '`LESSOPEN`';
1696
+ if (/(?:^|[^A-Za-z0-9_])(?:HOME|CODEX_HOME|PWD|OLDPWD|GIT_[A-Z_]+)=/.test(unquoted))
1697
+ return 'a reassigned HOME, CODEX_HOME, PWD or GIT_* variable';
1698
+ // A-SPEC-772.37 §5 — a body that is not text first, naming its tag and the reader its text reaches (772.36 put this
1699
+ // after the commands, so `cat <<'EOF' | sudo bash` named only `bash` and not the heredoc)
1700
+ for (const b of bodies) {
1701
+ if (flow.textBody(b))
1702
+ continue;
1703
+ const reader = flow.readerOf(b);
1704
+ if (reader !== null)
1705
+ return `a heredoc (<<${b.tag}) whose text reaches \`${reader}\``;
1706
+ const fed = b.receiver.trim().split(/\s+/).find((w) => w !== '' && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) ?? '';
1707
+ return fed === '' ? `a heredoc (<<${b.tag}) whose receiver the gate does not read` : `a heredoc (<<${b.tag}) fed to \`${fed}\``;
1708
+ }
1709
+ for (const one of parsed.commands) {
1710
+ const words = afterAssignments(one.words);
1711
+ const w0 = words[0];
1712
+ if (w0 === undefined)
1713
+ continue;
1714
+ if (!w0.known || (w0.glob && w0.text !== '['))
1715
+ return 'a command name computed at run time';
1716
+ if (dataProgram(words))
1717
+ continue; // its arguments are text
1718
+ // A-SPEC-772.34 §5 — every word of a non-data command is literal
1719
+ if (words.some((w) => !w.known || w.glob))
1720
+ return `a word computed at run time or a glob in \`${w0.text} …\``;
1721
+ if (GRAMMAR_WORDS.test(w0.text))
1722
+ return `\`${w0.text}\``;
1723
+ if (CD_WORDS.test(w0.text)) {
1724
+ if (/^~[^/\\]/.test(words[1]?.text ?? ''))
1725
+ return '`cd ~user`';
1726
+ continue;
1727
+ }
1728
+ const problem = cliCommandProblem(words);
1729
+ if (problem !== null)
1730
+ return problem;
1731
+ }
1732
+ return null;
1733
+ }
1734
+ /** @implements A-SPEC-772.34 §8 — the refusal: the construct, the rule, and the way out, once. */
1735
+ const contractRefusal = (construct) => `the line holds ${construct}; only a line the gate reads whole is judged when it runs holmes-kit (A-SPEC-772.33, owner decision 2026-11-17). `
1736
+ + 'Run the holmes-kit call as a plain line of its own; put text that only mentions holmes-kit in a file (`git commit -F <file>`, `gh pr create --body-file <file>`)';
1737
+ /** The first verdict, as before 772.30 (callers that judge one verdict at a time). */
1738
+ function governedCliAct(command, depth = 0, ctx) {
1739
+ return governedCliActs(command, depth, ctx)[0] ?? null;
1740
+ }
1741
+ /**
1742
+ * @implements A-SPEC-772.30 — every verdict on the line, in order (review of 772.28, H-1: the first verdict alone let a
1743
+ * root-rule approval for `node <old>/bin/holmes-kit.js init --force` lift the 772.15 option rule too; the hook combines
1744
+ * them, and an approval lifts root verdicts only).
1745
+ */
1746
+ function governedCliActs(command, depth = 0, ctx) {
1747
+ const out = [];
1748
+ // the cheap look first, over the text with quoting removed (`holmes-k''it` is the CLI word to the shell — measured).
1749
+ // A-SPEC-772.34 — a computed or glob word reaches the contract even when the CLI's spelling is not in the text
1750
+ const whole = command.replace(/['"\\]/g, '');
1751
+ if (depth > 4 || (!/holmes-kit/i.test(whole) && !GOVERNED_HEADS.some((h) => whole.includes(h)) && !/[$`*?[]/.test(command)))
1752
+ return out;
1753
+ // A-SPEC-772.34 §3 — heredoc bodies out of the text the reader parses (it read their lines as commands)
1754
+ const split = stripHeredocBodies(command);
1755
+ const bare = split.text.replace(/['"\\]/g, '');
1756
+ const parsed = (0, shell_syntax_1.shellWords)(split.text, process.env, undefined, null, true);
1757
+ // the head the text names, so init's refusal still waits for the package reader (`echo $(npx …@0.40.0 init)`)
1758
+ const named = () => GOVERNED_HEADS.find((h) => new RegExp(`\\b${h}\\b`).test(bare)) ?? '';
1759
+ if (parsed.overflow) {
1760
+ if (!/holmes-kit/i.test(whole) || !GOVERNED_HEADS.some((h) => whole.includes(h)))
1761
+ return out;
1762
+ return [{ unjudged: 'it names holmes-kit and a governed subcommand, and holds more than the gate reads', head: named(), rule: 'line' }];
1763
+ }
1764
+ // @implements A-SPEC-772.33, A-SPEC-772.34 — the contract: a line in its scope is judged only when the reader understood
1765
+ // all of it (owner decision 11/17); otherwise refused at once, with no recovery command and no approval to ask
1766
+ const flow = lineFlow(split.text, split.bodies);
1767
+ if (contractScope(parsed, split.bodies, command, flow)) {
1768
+ const unread = unreadConstruct(split.text, parsed, split.bodies, flow);
1769
+ if (unread !== null)
1770
+ return [{ unjudged: contractRefusal(unread), head: named(), rule: 'line', contract: true }];
1771
+ }
1772
+ // A-SPEC-772.37 §4: what an unquoted tag's body runs is on the line too
1773
+ const runText = [bare, ...flow.bodyRuns].join('\n');
1774
+ if (!/holmes-kit/i.test(runText) || !GOVERNED_HEADS.some((h) => runText.includes(h)))
1775
+ return out;
1776
+ // @implements A-SPEC-772.21 — a substitution no longer decides the whole line: 772.16's dry-run exemption was a regex over
1777
+ // the line's text and freed every command on it (`init --dry-run --target "$(…)"; holmes-kit ledger rechain` passed —
1778
+ // review A, measured). Each substitution is judged as a command of its own, then each command by the loop below, where
1779
+ // a dry-run init with a computed value frees that command only.
1780
+ // @implements A-SPEC-772.32 — the reader keeps no order between substitutions and commands: on a line with a cd, each
1781
+ // substitution is judged as after a computed cd (`cd <old> && echo $(npx holmes-kit init …)` had no verdict — measured)
1782
+ const lineCds = parsed.commands.some((c) => {
1783
+ let k = 0;
1784
+ while (k < c.words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(c.words[k].text))
1785
+ k++;
1786
+ return /^(?:cd|pushd|popd|chdir)$/.test(c.words[k]?.text ?? '');
1787
+ });
1788
+ const subCtx = ctx !== undefined && lineCds ? { ...ctx, cdBefore: true, cdUnknown: true } : ctx;
1789
+ // A-SPEC-772.37 §4 — what an unquoted tag's body runs is judged as a substitution
1790
+ for (const sub of [...parsed.subs, ...flow.bodyRuns]) {
1791
+ out.push(...governedCliActs(sub, depth + 1, subCtx));
1792
+ // a substitution the reader cannot judge as a command at the depth limit stays the owner's
1793
+ if (depth + 1 > 4 && /holmes-kit/i.test(sub.replace(/['"\\]/g, '')))
1794
+ out.push({ unjudged: 'a substitution nests deeper than the gate reads', head: named(), rule: 'line' });
1795
+ }
1796
+ // A-SPEC-772.23: a cd earlier on the line moves where a later CLI word resolves. A-SPEC-772.30 (M-2): where it moved to,
1797
+ // when the cd names a literal directory (null when computed), so the recovery command names the same target.
1798
+ let cdBefore = false;
1799
+ let cdTo = ctx?.cdUnknown === true ? null : (ctx?.cwd ?? null);
999
1800
  for (const one of parsed.commands) {
1000
1801
  let at = 0;
1001
1802
  while (at < one.words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(one.words[at].text))
1002
1803
  at++;
1804
+ const pathAssigned = one.words.slice(0, at).some((w) => /^(?:PATH|NODE_PATH|Path)=/.test(w.text));
1805
+ const cdHere = /^(?:cd|pushd|popd|chdir)$/.test(one.words[at]?.text ?? '');
1806
+ if (cdHere) {
1807
+ const arg = one.words[at + 1];
1808
+ cdTo = cdTo !== null && arg !== undefined && arg.known && !arg.glob && !arg.text.startsWith('-')
1809
+ ? path.resolve(cdTo, arg.text.replace(/^~(?=[/\\]|$)/, os.homedir())) : null;
1810
+ }
1003
1811
  // a program that only prints or searches runs nothing it names (`echo holmes-kit runtime-binding setup` was refused
1004
1812
  // by the first build of this rule — measured by the installer suite); what it pipes into a shell is the CLI's guard
1005
1813
  if (/^(?:echo|printf|grep|egrep|fgrep|rg|ag|cat|head|tail|less|more|wc|man|which|type|whatis)$/.test((one.words[at]?.text ?? '').replace(/^.*\//, '')))
1006
1814
  continue;
1007
1815
  const words = one.words.slice(at);
1008
1816
  const shellish = /^(?:sh|bash|zsh|dash|ksh|eval)$/.test((words[0]?.text ?? '').replace(/^.*\//, ''));
1817
+ // @implements A-SPEC-772.16 — a computed command word before a governed head (`H=holmes-kit; $H init …`) is unread
1818
+ if (words.length > 1 && (!words[0].known || words[0].glob)) {
1819
+ const first = firstWordAt(words.slice(1));
1820
+ const w1 = first >= 0 ? words[1 + first] : undefined;
1821
+ const g = w1 !== undefined && w1.known ? GOVERNED_HEADS.find((x) => x === w1.text) : undefined;
1822
+ if (g !== undefined) {
1823
+ out.push({ unjudged: `the command word before \`${g}\` is computed at run time`, head: g, rule: 'line' });
1824
+ continue;
1825
+ }
1826
+ }
1827
+ const runnerLed = CLI_RUNNERS.test((words[0]?.text ?? '').replace(/^.*[/\\]/, '').toLowerCase());
1009
1828
  for (let i = 0; i < words.length; i++) {
1010
1829
  const w = words[i];
1011
1830
  // a program string: after a `-c`-like option, or any word of a shell or eval
1012
1831
  if (/\s/.test(w.text) && (shellish || /^-\w*c$|^--call(?:=|$)/.test(words[i - 1]?.text ?? ''))) {
1013
- const inner = governedCliAct(w.text, depth + 1);
1014
- if (inner !== null)
1015
- return inner;
1832
+ // A-SPEC-772.28 (review A M3): the cd and PATH assignment before it reach the nested command
1833
+ out.push(...governedCliActs(w.text, depth + 1, ctx === undefined ? undefined
1834
+ : { ...ctx, cwd: cdTo ?? ctx.cwd, cdBefore: cdBefore || ctx.cdBefore === true, pathAssigned: pathAssigned || ctx.pathAssigned === true,
1835
+ // A-SPEC-772.31 (review of 772.30, A-M1): a computed cd is carried in, so the nested command names no place
1836
+ cdUnknown: cdTo === null || ctx.cdUnknown === true }));
1837
+ continue;
1838
+ }
1839
+ // A-SPEC-772.16: the CLI word counts as the command, or behind a runner (`git -C ../holmes-kit init` is git's)
1840
+ if (!isCliWord(w.text) || (i > 0 && !runnerLed))
1841
+ continue;
1842
+ const after = words.slice(i + 1);
1843
+ const window = after.slice(0, 64);
1844
+ // A-SPEC-772.16: the head is the first non-option word; a computed one is unread
1845
+ const h = firstWordAt(window);
1846
+ if (h < 0)
1847
+ continue;
1848
+ const headWord = window[h];
1849
+ if (!headWord.known || headWord.glob) {
1850
+ if (GOVERNED_HEADS.some((x) => bare.includes(x)))
1851
+ out.push({ unjudged: 'the holmes-kit subcommand is computed at run time', head: '', rule: 'line' });
1016
1852
  continue;
1017
1853
  }
1018
- if (!isCliWord(w.text))
1854
+ // @implements A-SPEC-772.31 (review of 772.30, A-M2) — init or upgrade with more words than the gate reads: refused
1855
+ // (upgrade has no option rule, so past the window it had no verdict at all)
1856
+ if (ROOT_BOUND_HEADS.has(headWord.text) && after.length > window.length) {
1857
+ out.push({ unjudged: `more than ${window.length} words follow \`holmes-kit ${headWord.text}\``, head: headWord.text, rule: 'line' });
1019
1858
  continue;
1020
- const window = words.slice(i + 1, i + 65);
1859
+ }
1860
+ // @implements A-SPEC-772.23 — init or upgrade from another copy than the governing one re-wires the gate to it; a
1861
+ // copy the gate cannot resolve is unread. Help and dry runs write nothing.
1862
+ // (a line past the window keeps 772.16's reason — the loop below reports it)
1863
+ // @implements A-SPEC-772.28 — a package name is resolved too (review A H1: with an old copy in the project,
1864
+ // `npx -y @holmes-lab/holmes-kit init` ran it); only a name no local copy answers goes to the package reader
1865
+ // (an empty governing root exists only where a suite replaces the running-package module)
1866
+ if (ctx !== undefined && ctx.governingRoot !== '' && ROOT_BOUND_HEADS.has(headWord.text) && after.length <= window.length) {
1867
+ const rest = window.slice(h + 1).map((x) => optionName(x.text));
1868
+ if (!writesNothing(rest, '--dry-run')) {
1869
+ const { resolveCliRoot } = require('../guardrail/cli-root');
1870
+ const r = resolveCliRoot(w.text, { cwd: ctx.cwd, env: ctx.env, runner: i > 0 ? words[0].text : undefined,
1871
+ between: words.slice(1, i).map((x) => x.text), pathAssigned: pathAssigned || ctx.pathAssigned === true, cdBefore: cdBefore || ctx.cdBefore === true });
1872
+ // A-SPEC-772.28 (review A H3): the reason names the command that runs the governing install, so the agent recovers
1873
+ // without a person. A-SPEC-772.30: every word through shellWord (H-2), and after a cd the target it moved to (M-2)
1874
+ const recovery = recoveryCommand(ctx.governingRoot, headWord.text, window.slice(h + 1).map((x) => x.text), cdBefore || ctx.cdBefore === true ? cdTo : undefined);
1875
+ if ('unresolved' in r)
1876
+ out.push({ unjudged: `the holmes-kit that would run \`${headWord.text}\` cannot be resolved — ${r.unresolved}`, head: headWord.text, rule: 'root', root: true, recovery });
1877
+ else if ('root' in r) {
1878
+ const real = (() => { try {
1879
+ return fs.realpathSync.native(r.root);
1880
+ }
1881
+ catch {
1882
+ return r.root;
1883
+ } })();
1884
+ if (real !== ctx.governingRoot) {
1885
+ out.push({ act: `${headWord.text} run from another holmes-kit copy (${real}) than the one governing this session (${ctx.governingRoot}) re-wires the gate (governance wiring)`, head: headWord.text, rule: 'root', root: true, recovery });
1886
+ }
1887
+ }
1888
+ }
1889
+ }
1021
1890
  for (const g of GOVERNED_CLI) {
1022
- const h = window.findIndex((x) => x.text === g.head);
1023
- if (h < 0)
1891
+ if (headWord.text !== g.head)
1892
+ continue;
1893
+ // A-SPEC-772.16: options pushed past the window are not read — the owner's
1894
+ if (after.length > window.length) {
1895
+ out.push({ unjudged: `more than ${window.length} words follow \`holmes-kit ${g.head}\``, head: g.head, rule: 'option' });
1024
1896
  continue;
1897
+ }
1025
1898
  const rest = window.slice(h + 1);
1026
- if (rest.some((x) => !x.known || x.glob))
1027
- return { unjudged: `a word after \`holmes-kit ${g.head}\` is computed at run time` };
1028
- if (!rest.some((x) => g.ops.has(x.text)))
1899
+ const ownerOp = rest.some((x) => x.known && g.ops.has(optionName(x.text)));
1900
+ const preview = writesNothing(rest.map((x) => x.text), g.preview);
1901
+ if (rest.some((x) => !x.known || x.glob)) {
1902
+ // A-SPEC-772.16: a preview with no owner option is free even with a computed value (`--dry-run --target "$PWD"`)
1903
+ if (preview && !ownerOp)
1904
+ continue;
1905
+ out.push({ unjudged: `a word after \`holmes-kit ${g.head}\` is computed at run time`, head: g.head, rule: 'option' });
1906
+ continue;
1907
+ }
1908
+ // A-SPEC-772.15: an option the allow-list does not name is the owner's too (when the entry has a list)
1909
+ const unlisted = g.allowed !== undefined && rest.some((x) => x.text.startsWith('-') && x.text !== '-' && !g.allowed.has(optionName(x.text)));
1910
+ if (!unlisted && !ownerOp)
1029
1911
  continue;
1030
- if (g.preview !== undefined && rest.some((x) => x.text === g.preview))
1912
+ if (preview)
1031
1913
  continue;
1032
- return { act: g.act };
1914
+ out.push({ act: g.act, head: g.head, rule: 'option' });
1033
1915
  }
1034
1916
  }
1917
+ if (cdHere)
1918
+ cdBefore = true;
1035
1919
  }
1036
- return null;
1920
+ return out;
1921
+ }
1922
+ /**
1923
+ * @implements A-SPEC-772.30 — the command that runs `head` from the governing install, every word serialized for sh. After
1924
+ * a cd, `dir` is where it moved: init's `--target` is named absolute — added when absent, a relative one made absolute
1925
+ * against `dir`; a null `dir` (a cd to a computed place) leaves no recovery command. Without a cd (`undefined`) the words
1926
+ * are kept as given (the recovery runs where the refused command would have).
1927
+ */
1928
+ /** @implements A-SPEC-772.32 — the approval target of the root rule: a request of its own, apart from the command's. */
1929
+ const ROOT_RULE_TARGET = (command) => `holmes-kit root rule: ${command}`;
1930
+ exports.ROOT_RULE_TARGET = ROOT_RULE_TARGET;
1931
+ function recoveryCommand(governingRoot, head, args, dir) {
1932
+ if (dir === null)
1933
+ return null;
1934
+ // A-SPEC-772.31 (review low): a `~` the shell would have expanded is expanded before quoting (quoted, it stays `~`)
1935
+ const home = (p) => p.replace(/^~(?=[/\\]|$)/, os.homedir());
1936
+ const words = args.map((w, i) => (args[i - 1] === '--target' ? home(w) : w.startsWith('--target=~') ? `--target=${home(w.slice('--target='.length))}` : w));
1937
+ if (head === 'init' && dir !== undefined) {
1938
+ const at = words.findIndex((w) => w === '--target' || w.startsWith('--target='));
1939
+ if (at < 0)
1940
+ words.push('--target', dir);
1941
+ else if (words[at] === '--target' && words[at + 1] !== undefined)
1942
+ words[at + 1] = path.resolve(dir, words[at + 1]);
1943
+ else if (words[at].startsWith('--target='))
1944
+ words[at] = `--target=${path.resolve(dir, words[at].slice('--target='.length))}`;
1945
+ }
1946
+ const run = ['node', path.join(governingRoot, 'bin', 'holmes-kit.js'), head, ...words].map(shellWord).join(' ');
1947
+ // A-SPEC-772.31 (review low): upgrade works in the directory it runs in — after a cd, the recovery goes there first
1948
+ return head !== 'init' && dir !== undefined ? `cd ${shellWord(dir)} && ${run}` : run;
1949
+ }
1950
+ /**
1951
+ * @implements A-SPEC-772.23 — the package root this gate runs from (real path): the one fact principle 7 already reads
1952
+ * (A-SPEC-794.111, fixed by the module's location, no setter), not a second computation of it.
1953
+ */
1954
+ function governingRoot() {
1955
+ return require('../project/running-package').RUNNING_PACKAGE_ROOT;
1037
1956
  }
1038
1957
  /**
1039
1958
  * @implements A-SPEC-794.91 (N2), 794.95, 794.96 — the principle 7 write rule for the file tools: judged where the write
@@ -1910,6 +2829,26 @@ function lockRecoverTextRuns(command) {
1910
2829
  return false;
1911
2830
  return interpreterSpawns(command) || SHELL_FED.test(command) || RUNTIME_COMMAND_WORD.test(command);
1912
2831
  }
2832
+ /** @implements A-SPEC-794.139 — the governing holmes-kit's version: this build's own package.json (src and dist alike). */
2833
+ let governingVersionMemo = null;
2834
+ function governingVersion() {
2835
+ if (governingVersionMemo !== null)
2836
+ return governingVersionMemo;
2837
+ try {
2838
+ // A-SPEC-772.28 (review A low 2): the governing root's package.json — one computation of the root, not a second one
2839
+ const root = governingRoot();
2840
+ if (typeof root !== 'string' || root === '') {
2841
+ governingVersionMemo = undefined;
2842
+ return undefined;
2843
+ }
2844
+ const v = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;
2845
+ governingVersionMemo = typeof v === 'string' ? v : undefined;
2846
+ }
2847
+ catch {
2848
+ governingVersionMemo = undefined;
2849
+ }
2850
+ return governingVersionMemo;
2851
+ }
1913
2852
  function startsHolmesServer(command) {
1914
2853
  command = (0, shell_argument_roles_1.shellArgumentRoles)(command).serverText;
1915
2854
  if (SERVER_RUNNERS.some((t) => t.test(command)))
@@ -3266,10 +4205,35 @@ function isGovernedProject(specsDir, opts = {}) {
3266
4205
  return false;
3267
4206
  }
3268
4207
  }
4208
+ /**
4209
+ * @implements A-SPEC-728.4 — whether `stdout` with exit `code` is one valid PreToolUse answer: one JSON object whose
4210
+ * hookSpecificOutput names PreToolUse, a decision that is absent or allow/deny/ask, and a code that is 2 exactly for a
4211
+ * deny. Measured 2026-11-15 (Claude Code 2.1.325): a malformed answer with exit 0 passes the call, onFailure or not.
4212
+ */
4213
+ function validHookAnswer(stdout, code) {
4214
+ let parsed;
4215
+ try {
4216
+ parsed = JSON.parse(stdout);
4217
+ }
4218
+ catch {
4219
+ return false;
4220
+ }
4221
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
4222
+ return false;
4223
+ const h = parsed.hookSpecificOutput;
4224
+ if (h === null || typeof h !== 'object' || Array.isArray(h))
4225
+ return false;
4226
+ const { hookEventName, permissionDecision } = h;
4227
+ if (hookEventName !== 'PreToolUse')
4228
+ return false;
4229
+ if (permissionDecision !== undefined && permissionDecision !== 'allow' && permissionDecision !== 'deny' && permissionDecision !== 'ask')
4230
+ return false;
4231
+ return (permissionDecision === 'deny') === (code === 2) && (code === 0 || code === 2);
4232
+ }
3269
4233
  /**
3270
4234
  * The whole error-path decision, assembled from an environment.
3271
4235
  *
3272
- * @implements A-SPEC-144
4236
+ * @implements A-SPEC-144, A-SPEC-728.5 (the head line restored here)
3273
4237
  * Exported and env-injected so the WIRING is tested rather than trusted. Mutation testing found the
3274
4238
  * gap: hardcoding `bypass: true` and inverting the governance check both left every test green,
3275
4239
  * because the tests exercised the pure helpers directly and nothing exercised the code that reads
@@ -3307,8 +4271,9 @@ function gateErrorDecision(message, env = process.env, argv = process.argv, proj
3307
4271
  * argv > env > default: the wiring is more specific than an ambient variable.
3308
4272
  */
3309
4273
  function wiredSpecsDir(argv, env) {
3310
- const i = argv.indexOf('--specs');
3311
- const fromArgv = i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
4274
+ // A-SPEC-772.16: one reader with init (project/hook-specs-arg)
4275
+ const named = require('../project/hook-specs-arg').specsArgOf(argv);
4276
+ const fromArgv = named === 'unreadable' ? undefined : named;
3312
4277
  return fromArgv ?? (env.HOLMES_SPECS || undefined) ?? exports.DEFAULT_SPECS_DIR;
3313
4278
  }
3314
4279
  /** Default spec root. Used to tell "never governed" apart from an explicitly configured HOLMES_SPECS. */
@@ -3616,6 +4581,10 @@ function judgeHook(input, specsDir, opts) {
3616
4581
  // it is not spent again and files no request. Every other approval resolves as before, against the text judged.
3617
4582
  const carried = opts.carriedApprovals?.reading === command ? opts.carriedApprovals : undefined;
3618
4583
  const resolveForCommand = (kind) => {
4584
+ // @implements A-SPEC-772.33 — the root rule's target namespace is reserved: a command spelled with its prefix takes
4585
+ // no config-write grant (review B of 772.32: its own target equalled the root target of the line after the prefix)
4586
+ if (kind === 'config-write' && command.trimStart().startsWith((0, exports.ROOT_RULE_TARGET)('')))
4587
+ return undefined;
3619
4588
  const held = carried?.approvals.find((a) => (0, risk_gate_1.approvalCovers)(a, { kind, target: carried.command }, nowTs));
3620
4589
  return held !== undefined ? { approval: held, source: 'carried' }
3621
4590
  : (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind, target: command }, nowTs);
@@ -4056,14 +5025,119 @@ function judgeHook(input, specsDir, opts) {
4056
5025
  }
4057
5026
  // @implements A-SPEC-794.113 — the same subcommands behind any runner (the installer rule below reads the CLI as the
4058
5027
  // first word only), and `ledger rechain`
5028
+ // A-SPEC-772.15: held until the package reader has judged — running another holmes-kit version (`npx …@0.40.0 init
5029
+ // --force`) keeps its own, more specific reason; either way the command is refused
5030
+ let governedRefusal = null;
4059
5031
  if (!legacySessionApproval && (0, shell_argument_roles_1.installerInvocationOf)(command) === null && (0, shell_argument_roles_1.installerApplyIn)(command) === null) {
4060
- const governed = governedCliAct(command);
4061
- if (governed !== null) {
4062
- return 'act' in governed
4063
- ? { permissionDecision: 'deny', refusal: 'launch.refused', permissionDecisionReason: `[Holmes-Kit] ${governed.act}; it requires operator approval — the operator runs it from their own terminal, not the session (A-SPEC-794.113). Its --dry-run form shows what it would do.` }
4064
- : { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: `[Holmes-Kit] the gate cannot read the holmes-kit words of this command — ${governed.unjudged} — so it is refused rather than judged (A-SPEC-794.113). Write the holmes-kit command out literally, or have the operator run it.` };
5032
+ // A-SPEC-772.23: with the facts the root rule needs — where the command runs and which package governs
5033
+ // A-SPEC-772.30 (H-1): every verdict on the line — an approval lifts root verdicts only; any other verdict refuses
5034
+ const verdicts = governedCliActs(command, 0, { cwd: input.cwd ?? opts.projectRoot, governingRoot: governingRoot(), env: process.env });
5035
+ // @implements A-SPEC-772.34 §8 — a contract refusal is returned before any rule files an approval request (the
5036
+ // package reader's request could never lift it)
5037
+ const contracted = verdicts.find((v) => v.contract === true);
5038
+ if (contracted !== undefined && 'unjudged' in contracted) {
5039
+ return { permissionDecision: 'deny', refusal: 'line.unread', permissionDecisionReason: `[Holmes-Kit] ${contracted.unjudged}` }; // A-SPEC-772.35 §4
5040
+ }
5041
+ const rootOnes = verdicts.filter((v) => v.rule === 'root');
5042
+ const rootText = rootOnes.map((v) => {
5043
+ const what = 'act' in v ? v.act : `the holmes-kit that would run \`${v.head}\` cannot be told — ${v.unjudged}`;
5044
+ return v.recovery ? `${what}. To run it from the install that governs this session: ${v.recovery}` : `${what}. Write a cd before it out literally to get the command that runs the governing install`;
5045
+ }).join('; ');
5046
+ const governed = verdicts.find((v) => v.rule !== 'root') ?? null;
5047
+ if (governed === null && rootOnes.length > 0) {
5048
+ // @implements A-SPEC-772.28 (review A M1) — the root rule's refusal is a config-write act (it changes which
5049
+ // holmes-kit governs); its reason names the self-recovery command.
5050
+ // @implements A-SPEC-772.32 — under a target of its own: the package reader asks for the command itself, and a
5051
+ // shared target let one grant, filed with one reason, lift both verdicts
5052
+ const rootTarget = (0, exports.ROOT_RULE_TARGET)(command);
5053
+ const carriedRoot = carried?.approvals.find((a) => (0, risk_gate_1.approvalCovers)(a, { kind: 'config-write', target: (0, exports.ROOT_RULE_TARGET)(carried.command) }, nowTs));
5054
+ const held = carriedRoot !== undefined ? { approval: carriedRoot, source: 'carried' }
5055
+ : (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'config-write', target: rootTarget }, nowTs);
5056
+ if (held !== undefined)
5057
+ pendingApprovals.push(held);
5058
+ else {
5059
+ governedRefusal = { permissionDecision: 'deny', refusal: routeCode('approval.required'),
5060
+ permissionDecisionReason: `[Holmes-Kit] ${rootText} (A-SPEC-772.28, A-SPEC-772.30). Otherwise it requires operator approval (A-SPEC-772.23)`
5061
+ + hintOrRoute({ kind: 'config-write', target: rootTarget, why: rootOnes.map((v) => `${v.head} from a holmes-kit copy other than the governing one`).join('; ') }) };
5062
+ }
5063
+ }
5064
+ else if (governed !== null) {
5065
+ // A-SPEC-772.30: a root verdict on the same line is named too — an approval would not lift this refusal.
5066
+ // A-SPEC-772.31 (review low): and every other non-root verdict, not the first alone
5067
+ const rest = verdicts.filter((v) => v.rule !== 'root' && v !== governed).map((v) => ('act' in v ? v.act : v.unjudged));
5068
+ const also = (rest.length > 0 ? ` Also: ${rest.join('; ')}.` : '') + (rootOnes.length > 0 ? ` Also: ${rootText}.` : '');
5069
+ governedRefusal = 'act' in governed
5070
+ ? { permissionDecision: 'deny', refusal: 'launch.refused', permissionDecisionReason: `[Holmes-Kit] ${governed.act}; it requires operator approval — the operator runs it from their own terminal, not the session (A-SPEC-794.113). Its --dry-run form shows what it would do.${also}` }
5071
+ : { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: `[Holmes-Kit] the gate cannot read the holmes-kit words of this command — ${governed.unjudged} — so it is refused rather than judged (A-SPEC-794.113). Write the holmes-kit command out literally, or have the operator run it.${also}` };
5072
+ // A-SPEC-772.16: only init's refusal waits for the package reader; the others no approval lifts, so they are
5073
+ // returned now (a pinned `runtime-binding setup` said approval.required, then launch.refused after the grant)
5074
+ // A-SPEC-772.23: upgrade's waits too (the reader names a pinned old version more precisely)
5075
+ if (governed.head !== 'init' && governed.head !== 'upgrade')
5076
+ return governedRefusal;
4065
5077
  }
4066
5078
  }
5079
+ // @implements A-SPEC-794.134 — a package-manager act that swaps the holmes-kit governing this session (install,
5080
+ // remove, update, link, or run a version named in the command) is the owner's; before the server-start rule, whose
5081
+ // wording misread `bun add -g` as a server start
5082
+ {
5083
+ // @implements A-SPEC-794.136, A-SPEC-794.137 — only a command that points at holmes-kit is judged, against a closed allow list. A shell
5084
+ // write over a manifest or lockfile naming holmes-kit is the same act, its file read in the segment's own directory
5085
+ // (after `cd`); a segment whose directory is not known is read in every directory it may run in.
5086
+ const readIn = (bases) => (w) => {
5087
+ const texts = bases.map((b) => { try {
5088
+ return fs.readFileSync(path.resolve(b, w), 'utf8');
5089
+ }
5090
+ catch {
5091
+ return null;
5092
+ } }).filter((t) => t !== null);
5093
+ return texts.length === 0 ? null : texts.join('\n');
5094
+ };
5095
+ // A-SPEC-794.139: the reader gets the directory reads (a package.json's name, in the command's directory) and the
5096
+ // governing version (a named version strictly higher stays free)
5097
+ const pkgBase = shellBase ?? opts.projectRoot;
5098
+ const nameAt = (d) => {
5099
+ try {
5100
+ const p = path.resolve(pkgBase, d.replace(/^~(?=\/|$)/, os.homedir()));
5101
+ const file = /\.(?:tgz|tar\.gz|tar)$/i.test(p) ? null : path.join(p, 'package.json');
5102
+ if (file === null)
5103
+ return null;
5104
+ const n = JSON.parse(fs.readFileSync(file, 'utf8')).name;
5105
+ return typeof n === 'string' ? n : null;
5106
+ }
5107
+ catch {
5108
+ return null;
5109
+ }
5110
+ };
5111
+ // A-SPEC-794.142 (item 6): the manifest a pkg set rewrites, so its value is judged against the entry it replaces
5112
+ const readManifest = (d) => { try {
5113
+ return fs.readFileSync(path.join(path.resolve(pkgBase, d), 'package.json'), 'utf8');
5114
+ }
5115
+ catch {
5116
+ return null;
5117
+ } };
5118
+ let pkgAct = (0, package_manager_acts_1.holmesPackageAct)(command, { nameAt, current: governingVersion(), readManifest });
5119
+ for (const seg of segmentsOnce) {
5120
+ if (pkgAct !== null)
5121
+ break;
5122
+ if (seg.data)
5123
+ continue;
5124
+ const bases = seg.base !== null ? [seg.base] : [...(seg.maybe ?? []), shellBase ?? opts.projectRoot];
5125
+ pkgAct = (0, package_manager_acts_1.shellManifestWrite)(seg.text, readIn(bases));
5126
+ }
5127
+ if (pkgAct !== null) {
5128
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
5129
+ return { permissionDecision: 'deny', refusal: 'cap.run-fixed', permissionDecisionReason: `[Holmes-Kit] a run cannot change a project cap or the holmes-kit that governs this session (${pkgAct}) — it stays fixed for the run (A-SPEC-794.134)` };
5130
+ }
5131
+ const r = resolveForCommand('config-write');
5132
+ if (r === undefined) {
5133
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), permissionDecisionReason: `[Holmes-Kit] requires operator approval — ${pkgAct}: this changes the holmes-kit that governs this session, and an agent does not swap its own gate. A person installs, upgrades or removes it in their own terminal (A-SPEC-794.134)`
5134
+ + hintOrRoute({ kind: 'config-write', target: command, why: `changing the governing holmes-kit (${pkgAct})` }) };
5135
+ }
5136
+ pendingApprovals.push(r);
5137
+ }
5138
+ }
5139
+ if (governedRefusal !== null)
5140
+ return governedRefusal; // A-SPEC-772.15: after the package reader
4067
5141
  const installerExact = legacySessionApproval ? null : (0, shell_argument_roles_1.installerInvocationOf)(command);
4068
5142
  const installerApply = legacySessionApproval ? null
4069
5143
  : installerExact === 'apply' ? command
@@ -4326,22 +5400,41 @@ function judgeHook(input, specsDir, opts) {
4326
5400
  // ways in one adversarial round. Data heredoc bodies are not commands and are not judged.
4327
5401
  if (!hardHitlCovered && !configWriteLifted) {
4328
5402
  // Every segment, heredoc bodies included (round 2: a `<<` in quotes hid the lines after it).
5403
+ // @implements A-SPEC-476.9 — `ln`/`link` of a protected file makes another name a later write goes through (review A1)
5404
+ {
5405
+ const lnKind = (0, write_target_1.linkMakingProtected)(opts.projectRoot, shellBase ?? opts.projectRoot, command); // A-SPEC-794.136
5406
+ if (lnKind !== null) {
5407
+ const refusal = liftByConfigWrite(`ln makes another name for ${lnKind} — a write through that name writes it, so linking it is a config write`);
5408
+ if (refusal)
5409
+ return refusal;
5410
+ }
5411
+ }
4329
5412
  let act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
5413
+ // @implements A-SPEC-476.9 (B3) — the wiring act first: when the first act is ax.config.json, any other wiring act in
5414
+ // the command is judged and named before the caps act (476.7's property, which 476.8 had stopped exercising)
5415
+ if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
5416
+ const other = (0, write_target_1.withoutProjectCaps)(() => (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase));
5417
+ if (other)
5418
+ act = other;
5419
+ }
4330
5420
  // @implements A-SPEC-476.3 — a shell write to ax.config.json cannot be read, so it asks only where a cap could rise
4331
5421
  // (the disk sets one below its widest value); in a run it is refused outright, with no approval to lift it.
4332
5422
  if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
4333
5423
  const onDisk = (0, project_caps_1.readProjectCaps)(opts.projectRoot);
4334
5424
  if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
4335
- return { permissionDecision: 'deny', refusal: 'cap.run-fixed', permissionDecisionReason: `[Holmes-Kit] ${act}: a run cannot change a project cap in ax.config.json, and a shell write to it cannot be read — the caps are the owner's and stay fixed for the run (A-SPEC-476.3)` };
5425
+ return { permissionDecision: 'deny', refusal: 'cap.run-fixed', permissionDecisionReason: `[Holmes-Kit] ${act}: a run cannot change a project cap or gate setting in ax.config.json, and a shell write to it cannot be read — they are the owner's and stay fixed for the run (A-SPEC-476.3, A-SPEC-476.8)` };
4336
5426
  }
4337
- if (!(0, project_caps_1.capsAtWidest)(onDisk)) {
4338
- const refusal = liftByConfigWrite(`${act}: ax.config.json sets a project cap (semantic.maxTier ${onDisk.semantic}, autonomy.ceiling ${onDisk.ceiling}) and a shell write to it cannot be read — raising or removing a cap is the owner's act (A-SPEC-476.3)`);
4339
- if (refusal)
4340
- return refusal;
4341
- }
4342
- // @implements A-SPEC-476.7 — the cap act is settled; the rest of the command is judged with the caps file out of the
4343
- // wiring set (the scan stops at its first act, and an allowed cap write hid an unlink of the hook wiring after it).
4344
- act = (0, write_target_1.withoutProjectCaps)(() => (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase));
5427
+ // @implements A-SPEC-476.8 — a shell write cannot be read, so it may change any judgement key: always the owner's
5428
+ // act (before, it asked only when a cap was set below its widest)
5429
+ // A-SPEC-476.9 — "sets a project cap" only when one is set below its widest value
5430
+ const holds = (0, project_caps_1.capsAtWidest)(onDisk) ? 'requires operator approval — ax.config.json holds the gate settings'
5431
+ : `ax.config.json sets a project cap (semantic search ${onDisk.semantic}, autonomy ${onDisk.ceiling}) and the gate settings`; // A-SPEC-794.138
5432
+ const refusal = liftByConfigWrite(`${act}: ${holds}, and a shell write to it cannot be read — ${OWN_GATE_SETTINGS}; use Edit or Write for a change that keeps them (A-SPEC-476.3, A-SPEC-476.8)`);
5433
+ if (refusal)
5434
+ return refusal;
5435
+ // @implements A-SPEC-476.7, A-SPEC-794.136 (B-L2) — the cap act is settled; any other wiring act was judged first
5436
+ // (476.9's wiring-first rescan), so nothing is left to re-scan here
5437
+ act = null;
4345
5438
  }
4346
5439
  if (act) {
4347
5440
  // @implements A-SPEC-728 (round 9) — `.ax` is named for what it is: the spec store and ledger.
@@ -4891,7 +5984,8 @@ function judgeHook(input, specsDir, opts) {
4891
5984
  if (canonical === null) {
4892
5985
  // @implements A-SPEC-728 — outside the project is free, EXCEPT the user-level harness config
4893
5986
  // that loads this session's gate (`~/.claude/settings*.json`, Codex `config.toml`/`hooks.json`).
4894
- const userKind = (0, write_target_2.userHarnessConfigKindOf)(norm, projectRoot);
5987
+ // @implements A-SPEC-476.9 — and a hard link out here to a protected file of the project is that file
5988
+ const userKind = (0, write_target_2.userHarnessConfigKindOf)(norm, projectRoot) ?? (0, write_target_1.hardLinkKindOf)(projectRoot, path.resolve(projectRoot, norm));
4895
5989
  if (userKind === null)
4896
5990
  return { permissionDecision: 'allow' };
4897
5991
  const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
@@ -4954,7 +6048,9 @@ function judgeHook(input, specsDir, opts) {
4954
6048
  }
4955
6049
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
4956
6050
  // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
4957
- const configKind = (0, write_target_2.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_2.userHarnessConfigKindOf)(norm, opts.projectRoot);
6051
+ // @implements A-SPEC-476.9 — a hard link to a protected file is that file (dev+ino): a config write
6052
+ const configKind = (0, write_target_2.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_2.userHarnessConfigKindOf)(norm, opts.projectRoot)
6053
+ ?? (0, write_target_1.hardLinkKindOf)(opts.projectRoot, path.resolve(opts.projectRoot, norm));
4958
6054
  // @implements A-SPEC-163 — identity, not spelling. Measured: `.ax//ledger//p.jsonl`,
4959
6055
  // `.ax/./ledger/p.jsonl` and `.AX/roles/policy.yaml` all reached the protected file while the
4960
6056
  // regex saw a different string. Adding `//` to the pattern would only move the next variant.
@@ -4974,6 +6070,36 @@ function judgeHook(input, specsDir, opts) {
4974
6070
  }
4975
6071
  // @implements A-SPEC-476.3 — the owner's caps in ax.config.json narrow this agent: raising or removing one is the owner's
4976
6072
  // act (owner decision 2026-10-19), lowering stays free, and in a run no write changes one.
6073
+ // @implements A-SPEC-794.134 — a manifest or lockfile edit of the holmes-kit entry is the first step of swapping the
6074
+ // governing install (edit, then a plain `npm install`): the owner's, in every mode
6075
+ const manifestName = path.basename(norm).toLowerCase();
6076
+ // A-SPEC-794.137: .npmrc no longer judged — it does not point at holmes-kit (evasion resistance is out of scope)
6077
+ if ((0, package_manager_acts_1.isManifestName)(manifestName)) { // A-SPEC-794.136 (B-M3): the one lockfile list
6078
+ // only a manifest or lockfile is read: every other write skips this (a large Write must not be read or copied here)
6079
+ const abs = path.resolve(opts.projectRoot, norm);
6080
+ let disk;
6081
+ try {
6082
+ disk = fs.readFileSync(abs, 'utf8');
6083
+ }
6084
+ catch (e) {
6085
+ disk = e.code === 'ENOENT' ? null : undefined;
6086
+ }
6087
+ const { after } = textAfterWrite(disk, input);
6088
+ const name = manifestName;
6089
+ // a result that cannot be computed counts as a change when either side names the package
6090
+ const changes = after === undefined || disk === undefined
6091
+ ? (disk ?? '').includes('@holmes-lab/holmes-kit') || JSON.stringify(input.tool_input).includes('@holmes-lab/holmes-kit')
6092
+ : (0, package_manager_acts_1.manifestHolmesChange)(name, disk, after, governingVersion()); // A-SPEC-794.140 (item 3): adds against the governing version
6093
+ if (changes) {
6094
+ const r = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
6095
+ if (r === undefined) {
6096
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), permissionDecisionReason: `[Holmes-Kit] requires operator approval — this write changes the @holmes-lab/holmes-kit entry of ${name}: that is the holmes-kit that governs this session, and an agent does not swap its own gate. A person changes it in their own terminal (A-SPEC-794.134)`
6097
+ + hintOrRoute({ kind: 'config-write', target: norm, why: `changing the governing holmes-kit in ${name}` }) };
6098
+ }
6099
+ if (r.source === 'grant' && r.approval.nonce)
6100
+ opts.settlement?.hold(opts.projectRoot, r.approval.nonce, r.approval); // A-SPEC-245.2
6101
+ }
6102
+ }
4977
6103
  if ((0, write_target_1.isProjectConfigTarget)(opts.projectRoot, norm)) {
4978
6104
  const capsAct = projectCapsWriteAct(opts.projectRoot, input);
4979
6105
  if (capsAct !== null) {
@@ -4990,6 +6116,20 @@ function judgeHook(input, specsDir, opts) {
4990
6116
  opts.settlement?.hold(opts.projectRoot, capsResolved.approval.nonce, capsResolved.approval); // A-SPEC-245.2
4991
6117
  }
4992
6118
  }
6119
+ // @implements A-SPEC-476.8 — a judgement key changed, either direction, is the agent's own gate: the owner's act
6120
+ const keys = projectJudgementWriteAct(opts.projectRoot, input);
6121
+ if (keys.length > 0) {
6122
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
6123
+ return { permissionDecision: 'deny', refusal: 'cap.run-fixed', permissionDecisionReason: `[Holmes-Kit] a run cannot change a project cap or gate setting in ax.config.json (${keys.join(', ')}) — ${OWN_GATE_SETTINGS} and stays fixed for the run (A-SPEC-476.8)` };
6124
+ }
6125
+ const judgeResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
6126
+ if (judgeResolved === undefined) {
6127
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), permissionDecisionReason: `[Holmes-Kit] requires operator approval — this write changes ${keys.join(', ')} in ax.config.json; ${OWN_GATE_SETTINGS}, like a write that raises or removes a project cap: an out-of-band approval that includes config-write (A-SPEC-476.8)`
6128
+ + hintOrRoute({ kind: 'config-write', target: norm, why: `changing a gate setting (${keys.join(', ')})` }) };
6129
+ }
6130
+ if (judgeResolved.source === 'grant' && judgeResolved.approval.nonce)
6131
+ opts.settlement?.hold(opts.projectRoot, judgeResolved.approval.nonce, judgeResolved.approval); // A-SPEC-245.2
6132
+ }
4993
6133
  }
4994
6134
  // Spec-file edit → graph-aware blast-radius risk (Tier-2 push-feed): a change to a widely-depended-on
4995
6135
  // or foundational (REQ) spec ripples across the graph, so its risk is assessed from the spec
@@ -6161,11 +7301,14 @@ if (require.main === module) {
6161
7301
  const code = runHookProcess(buf, { out: (t) => { stdout += t; }, err: (t) => { stderr += t; } });
6162
7302
  return { stdout, stderr, code };
6163
7303
  };
7304
+ // @implements A-SPEC-728.4 — only a valid PreToolUse answer reaches the harness; anything else is the gate-error decision
6164
7305
  const emit = (r) => {
6165
- process.stdout.write(r.stdout);
6166
- if (r.stderr)
6167
- process.stderr.write(r.stderr);
6168
- process.exit(r.code);
7306
+ const out = validHookAnswer(r.stdout, r.code) ? r
7307
+ : (() => { const g = gateErrorOutcome('the gate produced an answer that is not a valid hook decision'); return { ...g, stderr: `${r.stderr}${g.stderr}` }; })();
7308
+ process.stdout.write(out.stdout);
7309
+ if (out.stderr)
7310
+ process.stderr.write(out.stderr);
7311
+ process.exit(out.code);
6169
7312
  };
6170
7313
  if (!isMainThread) {
6171
7314
  // @implements A-SPEC-245.9 (1b-2) — a final allow's spends cross to the main thread; the worker waits for its answer
@@ -6192,14 +7335,19 @@ if (require.main === module) {
6192
7335
  return;
6193
7336
  settled = true;
6194
7337
  clearTimeout(timer);
6195
- emit(r);
7338
+ // A-SPEC-728.4: one turn of the loop first, so worker stdout already sent is forwarded to stderr before exit
7339
+ setImmediate(() => emit(r));
6196
7340
  };
6197
7341
  let worker;
6198
7342
  try {
6199
- worker = new Worker(__filename, { workerData: { buf }, argv: process.argv.slice(2), resourceLimits: { maxOldGenerationSizeMb: 2048 } });
7343
+ // @implements A-SPEC-728.4 — the worker's stdout is captured, never piped into the answer the harness reads
7344
+ worker = new Worker(__filename, { workerData: { buf }, argv: process.argv.slice(2), resourceLimits: { maxOldGenerationSizeMb: 2048 }, stdout: true });
7345
+ // @implements A-SPEC-728.6 — a diagnostic label, not a `[Holmes-Kit …]` refusal head
7346
+ worker.stdout.on('data', (d) => { process.stderr.write(`holmes-kit hook (diagnostic): worker stdout: ${String(d)}`); });
6200
7347
  }
6201
7348
  catch (e) {
6202
- // No worker available: judge inline rather than not at all.
7349
+ // No worker available: judge inline rather than not at all. A-SPEC-728.5 (named limit): on this path a module that
7350
+ // prints writes to the real stdout before the answer — emit still validates the answer, it cannot take back text.
6203
7351
  emit(collect(buf));
6204
7352
  return;
6205
7353
  }