From ae0cc075b65f013e53feae21b514ecdda942e272 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:06:43 -0400 Subject: [PATCH 01/44] docs: prepare HOL Guard before-tool adapter contract --- docs/hol-guard-before-tool.md | 79 +++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/hol-guard-before-tool.md diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md new file mode 100644 index 0000000..c323965 --- /dev/null +++ b/docs/hol-guard-before-tool.md @@ -0,0 +1,79 @@ +# HOL Guard `before_tool` adapter packet + +Status: owned-fork preparation only. This is not an upstream integration or a release artifact. + +## Why this maps cleanly + +Klaat Code sends a JSON object to `before_tool` hooks. For a `run_command` call, the relevant fields are: + +- `event`: `before_tool` +- `project_root`: current project root +- `tool_name`: `run_command` +- `tool_args`: the raw JSON argument string passed to the tool + +Klaat Code blocks a tool call when the hook exits with status `2` or writes a JSON object such as: + +```json +{"decision":"block","reason":"..."} +``` + +HOL Guard already has native pre-tool authority for command decisions. The supported native request is a versioned `PreToolUse` envelope whose `payload.tool_input.command` contains the command string. The Rust runtime owns the security decision. An adapter must transport and render that result, not reimplement Guard policy from Klaat Code. + +## Required adapter behavior + +For `tool_name == "run_command"`: + +1. Parse `tool_args` as JSON. +2. Extract the `command` string. If it is absent or malformed, fail closed for this matched hook rather than guessing. +3. Construct a Guard `PreToolUse` request using the current project as `cwd`. +4. Send the request through HOL Guard's native hook authority. +5. If Guard returns a deny/block/review/reapproval/sandbox-required floor that prevents execution, translate it to Klaat Code's block contract. +6. If Guard returns an allow result, exit successfully without a block response. +7. If Guard cannot produce an authoritative decision, fail closed. Do not silently allow a command because Guard is unavailable. + +Do not use `hol-guard command explain` as the enforcement authority. It is useful for stateless inspection and test assertions, but the live hook decision must remain native-authoritative. + +## Minimum validation cases + +The implementation is not ready for upstream submission until these cases are exercised against the real Guard runtime: + +| Case | Expected result | +| --- | --- | +| `pwd` | Klaat Code command proceeds | +| `git status --short` | Klaat Code command proceeds | +| `rm -rf /` | Klaat Code command is blocked | +| `shred ~/.ssh/id_ed25519` | Klaat Code command is blocked | +| malformed `tool_args` | fail closed | +| Guard runtime unavailable | fail closed | + +The deny-path test must prove that the target command is not executed. + +## Candidate hook configuration + +The adapter should be project-local until there is a stable shipped integration surface: + +```json +{ + "before_tool": [ + { + "matcher": "run_command", + "command": "./scripts/hol-guard-before-tool" + } + ] +} +``` + +The current README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. A real contribution should either ship the referenced helper or replace the example with an existing supported command. + +## Upstream gate + +Before any upstream PR: + +- revalidate the current Klaat Code hook payload and block semantics; +- revalidate HOL Guard's current native hook entry point; +- implement the smallest portable adapter with no duplicated policy logic; +- run Klaat Code typecheck/build plus focused adapter tests; +- prove one allow path and one deny path with the real Guard runtime; +- confirm the contribution still fits current maintainer guidance and Distribution WIP limits. + +Until those gates pass, this packet is preparation only and carries no strict outcome value. From 6788d48f8145eccc116bf96bd1238dade7ce378a Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:49:07 -0400 Subject: [PATCH 02/44] feat: add HOL Guard before-tool adapter --- scripts/hol-guard-before-tool.mjs | 160 ++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 scripts/hol-guard-before-tool.mjs diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs new file mode 100644 index 0000000..ccf814b --- /dev/null +++ b/scripts/hol-guard-before-tool.mjs @@ -0,0 +1,160 @@ +#!/usr/bin/env node +import { spawnSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +import process from 'node:process'; + +const MAX_STDIN_BYTES = 1_000_000; +const GUARD_TIMEOUT_MS = 9_000; + +function block(reason) { + const message = typeof reason === 'string' && reason.trim() + ? reason.trim() + : 'HOL Guard did not return an authoritative allow decision.'; + process.stdout.write(`${JSON.stringify({ decision: 'block', reason: message })}\n`); +} + +export function extractKlaatCommand(payload) { + if (!payload || typeof payload !== 'object') { + throw new Error('invalid Klaat hook payload'); + } + if (payload.event !== 'before_tool' || payload.tool_name !== 'run_command') { + return null; + } + if (typeof payload.tool_args !== 'string') { + throw new Error('run_command tool_args must be a JSON string'); + } + let args; + try { + args = JSON.parse(payload.tool_args); + } catch { + throw new Error('run_command tool_args is not valid JSON'); + } + if (!args || typeof args !== 'object' || typeof args.command !== 'string' || !args.command.trim()) { + throw new Error('run_command command is missing'); + } + return args.command; +} + +export function buildGuardPayload(payload, command) { + const guardPayload = { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command }, + }; + if (typeof payload.session_id === 'string' && payload.session_id) { + guardPayload.session_id = payload.session_id; + } + if (typeof payload.project_root === 'string' && payload.project_root) { + guardPayload.cwd = payload.project_root; + } + return guardPayload; +} + +function parseGuardJson(stdout) { + const text = typeof stdout === 'string' ? stdout.trim() : ''; + if (!text) return null; + try { + return JSON.parse(text); + } catch { + for (const line of text.split(/\r?\n/).reverse()) { + const candidate = line.trim(); + if (!candidate) continue; + try { + const parsed = JSON.parse(candidate); + if (parsed && typeof parsed === 'object') return parsed; + } catch { + // Keep looking for the final JSON response line. + } + } + return null; + } +} + +export function decisionFromGuardResponse(response) { + if (!response || typeof response !== 'object') { + return { allow: false, reason: 'HOL Guard returned an invalid response.' }; + } + const hookSpecific = response.hookSpecificOutput; + const permissionDecision = hookSpecific && typeof hookSpecific === 'object' + ? hookSpecific.permissionDecision + : undefined; + const policyAction = response.policy_action; + const reasonCode = response.reason_code; + + if ( + permissionDecision === 'allow' && + (policyAction === 'allow' || policyAction === 'warn') && + reasonCode !== 'harness_not_managed' + ) { + return { allow: true, reason: '' }; + } + + const reason = + (typeof response.reason === 'string' && response.reason) || + (hookSpecific && typeof hookSpecific === 'object' && + typeof hookSpecific.permissionDecisionReason === 'string' && + hookSpecific.permissionDecisionReason) || + (typeof reasonCode === 'string' && `HOL Guard blocked this command (${reasonCode}).`) || + 'HOL Guard did not return an authoritative allow decision.'; + return { allow: false, reason }; +} + +async function readStdin() { + const chunks = []; + let size = 0; + for await (const chunk of process.stdin) { + size += chunk.length; + if (size > MAX_STDIN_BYTES) throw new Error('Klaat hook payload exceeds the size limit'); + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} + +export async function main() { + let payload; + try { + const input = await readStdin(); + payload = JSON.parse(input); + } catch (error) { + block(error instanceof Error ? error.message : 'invalid Klaat hook payload'); + return; + } + + let command; + try { + command = extractKlaatCommand(payload); + } catch (error) { + block(error instanceof Error ? error.message : 'invalid run_command payload'); + return; + } + if (command === null) return; + + const guardPayload = buildGuardPayload(payload, command); + const args = ['hook', '--harness', 'codex']; + if (typeof payload.project_root === 'string' && payload.project_root) { + args.push('--workspace', payload.project_root); + } + args.push('--json'); + + const result = spawnSync('hol-guard', args, { + input: `${JSON.stringify(guardPayload)}\n`, + encoding: 'utf8', + timeout: GUARD_TIMEOUT_MS, + maxBuffer: MAX_STDIN_BYTES, + windowsHide: true, + }); + + if (result.error || result.status !== 0) { + block('HOL Guard could not complete an authoritative command review.'); + return; + } + + const response = parseGuardJson(result.stdout); + const decision = decisionFromGuardResponse(response); + if (!decision.allow) block(decision.reason); +} + +const invokedPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : ''; +if (import.meta.url === invokedPath) { + await main(); +} From a7958652fba2b27d8782da43d81dc7f27cce625e Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:49:50 -0400 Subject: [PATCH 03/44] test: cover HOL Guard before-tool adapter --- scripts/hol-guard-before-tool.test.mjs | 64 ++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 scripts/hol-guard-before-tool.test.mjs diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs new file mode 100644 index 0000000..80d16c2 --- /dev/null +++ b/scripts/hol-guard-before-tool.test.mjs @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + buildGuardPayload, + decisionFromGuardResponse, + extractKlaatCommand, +} from './hol-guard-before-tool.mjs'; + +test('extracts run_command command from Klaat tool_args', () => { + assert.equal(extractKlaatCommand({ + event: 'before_tool', + tool_name: 'run_command', + tool_args: JSON.stringify({ command: 'git status --short' }), + }), 'git status --short'); +}); + +test('ignores unrelated hook events defensively', () => { + assert.equal(extractKlaatCommand({ event: 'after_tool', tool_name: 'run_command', tool_args: '{}' }), null); +}); + +test('fails closed on malformed run_command input', () => { + assert.throws(() => extractKlaatCommand({ + event: 'before_tool', + tool_name: 'run_command', + tool_args: '{', + })); +}); + +test('builds complete PreToolUse command envelope', () => { + assert.deepEqual( + buildGuardPayload({ session_id: 's1', project_root: '/repo' }, 'pwd'), + { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'pwd' }, + session_id: 's1', + cwd: '/repo', + }, + ); +}); + +test('allows only native allow or warn decisions rendered as allow', () => { + assert.equal(decisionFromGuardResponse({ + policy_action: 'allow', + reason_code: 'native_pre_tool_allow', + hookSpecificOutput: { permissionDecision: 'allow' }, + }).allow, true); + assert.equal(decisionFromGuardResponse({ + policy_action: 'warn', + reason_code: 'native_policy_warning', + hookSpecificOutput: { permissionDecision: 'allow' }, + }).allow, true); +}); + +test('blocks review, block, malformed, and unmanaged passthrough responses', () => { + for (const response of [ + { policy_action: 'review', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'block', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'allow', reason_code: 'harness_not_managed', hookSpecificOutput: { permissionDecision: 'allow' } }, + {}, + ]) { + assert.equal(decisionFromGuardResponse(response).allow, false); + } +}); From f862e5e681ff976666286d7db077ffabbac3fd53 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:50:14 -0400 Subject: [PATCH 04/44] docs: record HOL Guard adapter preparation --- docs/hol-guard-before-tool.md | 59 ++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index c323965..53d4a2d 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -1,6 +1,6 @@ # HOL Guard `before_tool` adapter packet -Status: owned-fork preparation only. This is not an upstream integration or a release artifact. +Status: owned-fork implementation and tests prepared. This is not an upstream integration or a release artifact. ## Why this maps cleanly @@ -17,23 +17,39 @@ Klaat Code blocks a tool call when the hook exits with status `2` or writes a JS {"decision":"block","reason":"..."} ``` -HOL Guard already has native pre-tool authority for command decisions. The supported native request is a versioned `PreToolUse` envelope whose `payload.tool_input.command` contains the command string. The Rust runtime owns the security decision. An adapter must transport and render that result, not reimplement Guard policy from Klaat Code. +HOL Guard already has native pre-tool authority for command decisions. The supported native request is a versioned `PreToolUse` envelope whose `tool_input.command` contains the command string. The Rust runtime owns the security decision. The adapter transports and renders that result rather than reimplementing Guard policy in Klaat Code. -## Required adapter behavior +## Prepared adapter behavior -For `tool_name == "run_command"`: +The owned fork now contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: -1. Parse `tool_args` as JSON. -2. Extract the `command` string. If it is absent or malformed, fail closed for this matched hook rather than guessing. -3. Construct a Guard `PreToolUse` request using the current project as `cwd`. -4. Send the request through HOL Guard's native hook authority. -5. If Guard returns a deny/block/review/reapproval/sandbox-required floor that prevents execution, translate it to Klaat Code's block contract. -6. If Guard returns an allow result, exit successfully without a block response. -7. If Guard cannot produce an authoritative decision, fail closed. Do not silently allow a command because Guard is unavailable. +1. Parses `tool_args` as JSON. +2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. +3. Constructs a Guard `PreToolUse` request with the current project as `cwd`. +4. Sends the complete request through `hol-guard hook --harness codex --json`, with the workspace when available, so Guard's native hook authority remains the decision owner. +5. Allows only a native-rendered `allow` or `warn` result whose hook permission decision is `allow`. +6. Maps review, reapproval, sandbox-required, block, malformed output, unmanaged-harness passthrough, timeout, missing Guard, or any other non-authoritative state to Klaat Code's JSON block contract. -Do not use `hol-guard command explain` as the enforcement authority. It is useful for stateless inspection and test assertions, but the live hook decision must remain native-authoritative. +The adapter does not use `hol-guard command explain` as enforcement authority. -## Minimum validation cases +## Local preparation proof + +`node --check scripts/hol-guard-before-tool.mjs` passed before the owned-fork write. + +`node --test scripts/hol-guard-before-tool.test.mjs` passed six focused unit tests covering: + +- command extraction; +- unrelated hook pass-through; +- malformed `tool_args` fail-closed behavior; +- complete `PreToolUse` envelope construction; +- native allow/warn handling; +- review/block/unmanaged/malformed response rejection. + +A mocked `hol-guard` executable also proved the adapter's process boundary for allow, deny, malformed Klaat input, and unavailable Guard behavior. + +These are preparation checks only. They are not a substitute for real HOL Guard runtime proof. + +## Minimum real-runtime validation cases The implementation is not ready for upstream submission until these cases are exercised against the real Guard runtime: @@ -50,30 +66,29 @@ The deny-path test must prove that the target command is not executed. ## Candidate hook configuration -The adapter should be project-local until there is a stable shipped integration surface: +The adapter should remain project-local until there is a stable shipped integration surface: ```json { "before_tool": [ { "matcher": "run_command", - "command": "./scripts/hol-guard-before-tool" + "command": "node ./scripts/hol-guard-before-tool.mjs" } ] } ``` -The current README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. A real contribution should either ship the referenced helper or replace the example with an existing supported command. +The current upstream README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. This owned-fork candidate supplies the missing executable behavior without changing Klaat's hook semantics. ## Upstream gate Before any upstream PR: -- revalidate the current Klaat Code hook payload and block semantics; +- revalidate the current Klaat Code upstream head, hook payload, block semantics, contribution guidance, and queue ownership; - revalidate HOL Guard's current native hook entry point; -- implement the smallest portable adapter with no duplicated policy logic; -- run Klaat Code typecheck/build plus focused adapter tests; -- prove one allow path and one deny path with the real Guard runtime; -- confirm the contribution still fits current maintainer guidance and Distribution WIP limits. +- run Klaat Code typecheck/build plus the focused adapter tests; +- prove one allow path and one deny path with the real Guard runtime, including target command non-execution on deny; +- confirm the contribution still fits current Distribution WIP and maintainer-conversion gates. -Until those gates pass, this packet is preparation only and carries no strict outcome value. +Until those gates pass, this remains owned-fork preparation and carries no strict outcome value. From ed8d589808ddd5a564bed69d75803ea17e3a6662 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:13:56 -0400 Subject: [PATCH 05/44] fix: fail closed on unavailable Guard decisions --- scripts/hol-guard-before-tool.mjs | 62 +++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index ccf814b..956c626 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -6,6 +6,36 @@ import process from 'node:process'; const MAX_STDIN_BYTES = 1_000_000; const GUARD_TIMEOUT_MS = 9_000; +const NON_AUTHORITATIVE_REASON_CODES = new Set([ + 'native_hook_disabled', + 'native_shadow_diagnostic_disabled', + 'native_policy_not_ready', + 'native_hook_event_unavailable', + 'native_pre_tool_unavailable', + 'native_post_tool_unavailable', + 'native_overloaded', + 'native_hook_worker_unavailable', + 'native_hook_worker_unavailable_before_compatibility', + 'native_hook_worker_unsupported', + 'native_hook_worker_exception', + 'native_hook_compatibility_disabled', + 'native_hook_edge_invalid_response', + 'native_hook_edge_unavailable', + 'python_hook_oracle_unavailable', + 'python_oracle_exception', + 'watch_recording_only', + 'daemon_hook_queue_capacity', + 'daemon_hook_deadline_exhausted', + 'daemon_hook_process_deadline_exhausted', + 'daemon_hook_process_not_ready', + 'daemon_hook_process_failed', + 'daemon_hook_process_invalid_request', + 'daemon_hook_process_guard_home_mismatch', + 'daemon_worker_exception', + 'harness_not_managed', + 'native_degraded_emergency_safe', +]); + function block(reason) { const message = typeof reason === 'string' && reason.trim() ? reason.trim() @@ -79,23 +109,33 @@ export function decisionFromGuardResponse(response) { ? hookSpecific.permissionDecision : undefined; const policyAction = response.policy_action; - const reasonCode = response.reason_code; - - if ( - permissionDecision === 'allow' && - (policyAction === 'allow' || policyAction === 'warn') && - reasonCode !== 'harness_not_managed' - ) { - return { allow: true, reason: '' }; - } - + const reasonCode = typeof response.reason_code === 'string' + ? response.reason_code.trim() + : ''; const reason = (typeof response.reason === 'string' && response.reason) || (hookSpecific && typeof hookSpecific === 'object' && typeof hookSpecific.permissionDecisionReason === 'string' && hookSpecific.permissionDecisionReason) || - (typeof reasonCode === 'string' && `HOL Guard blocked this command (${reasonCode}).`) || + (reasonCode && `HOL Guard blocked this command (${reasonCode}).`) || 'HOL Guard did not return an authoritative allow decision.'; + + if (permissionDecision !== 'allow' || !reasonCode) { + return { allow: false, reason }; + } + + if (NON_AUTHORITATIVE_REASON_CODES.has(reasonCode)) { + return { allow: false, reason }; + } + + if (policyAction === 'allow') { + return { allow: true, reason: '' }; + } + + if (policyAction === 'warn' && reasonCode === 'native_policy_warning') { + return { allow: true, reason: '' }; + } + return { allow: false, reason }; } From e0d553c66fa97d3bba39e0c86962a968ff85300a Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:14:11 -0400 Subject: [PATCH 06/44] test: cover unavailable Guard fail-closed path --- scripts/hol-guard-before-tool.test.mjs | 29 ++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 80d16c2..ed107b3 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -39,10 +39,10 @@ test('builds complete PreToolUse command envelope', () => { ); }); -test('allows only native allow or warn decisions rendered as allow', () => { +test('allows authoritative native allow and policy warning decisions', () => { assert.equal(decisionFromGuardResponse({ policy_action: 'allow', - reason_code: 'native_pre_tool_allow', + reason_code: 'native_exact_safe_command', hookSpecificOutput: { permissionDecision: 'allow' }, }).allow, true); assert.equal(decisionFromGuardResponse({ @@ -52,11 +52,28 @@ test('allows only native allow or warn decisions rendered as allow', () => { }).allow, true); }); -test('blocks review, block, malformed, and unmanaged passthrough responses', () => { +test('fails closed on unavailable and non-authoritative warn decisions', () => { + for (const reason_code of [ + 'native_pre_tool_unavailable', + 'native_policy_not_ready', + 'native_hook_worker_unavailable', + 'harness_not_managed', + 'future_unknown_warning', + ]) { + assert.equal(decisionFromGuardResponse({ + policy_action: 'warn', + reason_code, + reason: 'Guard did not complete an authoritative review.', + hookSpecificOutput: { permissionDecision: 'allow' }, + }).allow, false, reason_code); + } +}); + +test('blocks review, block, malformed, and missing-reason responses', () => { for (const response of [ - { policy_action: 'review', hookSpecificOutput: { permissionDecision: 'deny' } }, - { policy_action: 'block', hookSpecificOutput: { permissionDecision: 'deny' } }, - { policy_action: 'allow', reason_code: 'harness_not_managed', hookSpecificOutput: { permissionDecision: 'allow' } }, + { policy_action: 'review', reason_code: 'native_command_review_required', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'block', reason_code: 'native_destructive_command', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'allow', hookSpecificOutput: { permissionDecision: 'allow' } }, {}, ]) { assert.equal(decisionFromGuardResponse(response).allow, false); From 8eb9859de24febb14bc21bc56e6c3c12eaccc0a1 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:15:51 -0400 Subject: [PATCH 07/44] docs: record real Guard availability test --- docs/hol-guard-before-tool.md | 49 +++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index 53d4a2d..ffcbd0e 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -21,42 +21,49 @@ HOL Guard already has native pre-tool authority for command decisions. The suppo ## Prepared adapter behavior -The owned fork now contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: +The owned fork contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: 1. Parses `tool_args` as JSON. 2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. 3. Constructs a Guard `PreToolUse` request with the current project as `cwd`. 4. Sends the complete request through `hol-guard hook --harness codex --json`, with the workspace when available, so Guard's native hook authority remains the decision owner. -5. Allows only a native-rendered `allow` or `warn` result whose hook permission decision is `allow`. -6. Maps review, reapproval, sandbox-required, block, malformed output, unmanaged-harness passthrough, timeout, missing Guard, or any other non-authoritative state to Klaat Code's JSON block contract. +5. Allows an authoritative native `allow` decision, or the explicit `native_policy_warning` allow-with-warning result. +6. Fails closed when native review is unavailable or not ready, including `native_pre_tool_unavailable`, `native_policy_not_ready`, worker/daemon availability failures, unmanaged-harness passthrough, unknown warning results, malformed output, timeout, missing Guard, review, reapproval, sandbox-required, or block. The adapter does not use `hol-guard command explain` as enforcement authority. -## Local preparation proof +## Validation completed -`node --check scripts/hol-guard-before-tool.mjs` passed before the owned-fork write. +The exact owned branch was downloaded into an independent Linux sandbox and validated with Node 20 and Bun 1.4.2. -`node --test scripts/hol-guard-before-tool.test.mjs` passed six focused unit tests covering: +The following checks pass: -- command extraction; -- unrelated hook pass-through; -- malformed `tool_args` fail-closed behavior; -- complete `PreToolUse` envelope construction; -- native allow/warn handling; -- review/block/unmanaged/malformed response rejection. +- `node --check scripts/hol-guard-before-tool.mjs` +- `node --test scripts/hol-guard-before-tool.test.mjs`, 7/7 focused tests +- `bun install --frozen-lockfile` +- `bun run typecheck` +- `bun run build` -A mocked `hol-guard` executable also proved the adapter's process boundary for allow, deny, malformed Klaat input, and unavailable Guard behavior. +The focused tests cover command extraction, unrelated hook pass-through, malformed `tool_args`, complete `PreToolUse` envelope construction, authoritative allow and policy-warning handling, unavailable native review, unknown warnings, review/block responses, and malformed/missing-reason responses. -These are preparation checks only. They are not a substitute for real HOL Guard runtime proof. +## Real HOL Guard 3.4.2 availability test -## Minimum real-runtime validation cases +A clean isolated Python environment installed the published `hol-guard==3.4.2` package successfully. -The implementation is not ready for upstream submission until these cases are exercised against the real Guard runtime: +With no resident native policy authority initialized, `hol-guard hook --harness codex --json` returned `policy_action: warn`, `permissionDecision: allow`, and `reason_code: native_pre_tool_unavailable` for both a benign command and a destructive command. That response means Guard could not complete the native decision. It is not execution proof. + +The first adapter version treated a generic `warn` plus `permissionDecision: allow` as sufficient and therefore would have allowed that unavailable state. The owned-fork adapter now rejects Guard availability and not-ready reason codes and rejects unknown warning results. Re-running the adapter against the same real 3.4.2 runtime now emits Klaat's block result for both test commands while Guard authority is unavailable. + +This closes the unavailable-runtime fail-open defect. It does not yet prove the final authoritative allow/deny path. + +## Remaining real-runtime gate + +The implementation is not ready for upstream submission until an isolated managed Guard runtime can produce authoritative native decisions for these cases: | Case | Expected result | | --- | --- | -| `pwd` | Klaat Code command proceeds | -| `git status --short` | Klaat Code command proceeds | +| `pwd` | Klaat Code command proceeds after authoritative Guard allow | +| `git status --short` | Klaat Code command proceeds after authoritative Guard allow | | `rm -rf /` | Klaat Code command is blocked | | `shred ~/.ssh/id_ed25519` | Klaat Code command is blocked | | malformed `tool_args` | fail closed | @@ -64,6 +71,8 @@ The implementation is not ready for upstream submission until these cases are ex The deny-path test must prove that the target command is not executed. +An isolated `hol-guard install codex` attempt in the validation sandbox did not establish that authority because Guard rejected the sandbox interpreter as writable by another user. No real user installation was modified. A clean authoritative setup remains required before upstream submission. + ## Candidate hook configuration The adapter should remain project-local until there is a stable shipped integration surface: @@ -87,8 +96,8 @@ Before any upstream PR: - revalidate the current Klaat Code upstream head, hook payload, block semantics, contribution guidance, and queue ownership; - revalidate HOL Guard's current native hook entry point; -- run Klaat Code typecheck/build plus the focused adapter tests; -- prove one allow path and one deny path with the real Guard runtime, including target command non-execution on deny; +- keep Klaat Code typecheck/build plus focused adapter tests green; +- prove one authoritative allow path and one authoritative deny path with the real Guard runtime, including target command non-execution on deny; - confirm the contribution still fits current Distribution WIP and maintainer-conversion gates. Until those gates pass, this remains owned-fork preparation and carries no strict outcome value. From 901bdf4e606e5e0e20c518e2b68fcf2648eb15a7 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:07:01 -0400 Subject: [PATCH 08/44] fix(security): reject mismatched Guard hook and unauthoritative allow reasons --- scripts/hol-guard-before-tool.mjs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 956c626..202ea09 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -101,13 +101,24 @@ function parseGuardJson(stdout) { } export function decisionFromGuardResponse(response) { - if (!response || typeof response !== 'object') { + if (!response || typeof response !== 'object' || Array.isArray(response)) { return { allow: false, reason: 'HOL Guard returned an invalid response.' }; } const hookSpecific = response.hookSpecificOutput; const permissionDecision = hookSpecific && typeof hookSpecific === 'object' ? hookSpecific.permissionDecision : undefined; + // Native hook responses are event-bound; a mismatched or explicitly stopped + // response cannot authorize a Klaat before_tool invocation. Historic local + // fixtures omit hookEventName, so retain their behavior until updated. + if (hookSpecific && typeof hookSpecific === 'object' && + hookSpecific.hookEventName !== undefined && + hookSpecific.hookEventName !== 'PreToolUse') { + return { allow: false, reason: 'HOL Guard returned a different hook event.' }; + } + if (response.continue === false || response.decision === 'deny') { + return { allow: false, reason: 'HOL Guard refused tool continuation.' }; + } const policyAction = response.policy_action; const reasonCode = typeof response.reason_code === 'string' ? response.reason_code.trim() @@ -128,7 +139,11 @@ export function decisionFromGuardResponse(response) { return { allow: false, reason }; } - if (policyAction === 'allow') { + // A superficially allow-shaped response with a destructive/review reason + // must not bypass Guard's native classifier. Unknown reasons fail closed. + const provenAllowReason = reasonCode.startsWith('native_exact_') || + reasonCode === 'native_policy_allow' || reasonCode === 'native_custom_mcp_tool_allow'; + if (policyAction === 'allow' && provenAllowReason) { return { allow: true, reason: '' }; } From 558f61d74d0d9eec909b9fb4a7860b919830ea1a Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:29:59 -0400 Subject: [PATCH 09/44] fix(hol-guard): reject ambiguous and contradictory hook verdicts --- scripts/hol-guard-before-tool.mjs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 202ea09..81ab513 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -80,23 +80,25 @@ export function buildGuardPayload(payload, command) { return guardPayload; } -function parseGuardJson(stdout) { +export function parseGuardJson(stdout) { const text = typeof stdout === 'string' ? stdout.trim() : ''; if (!text) return null; try { - return JSON.parse(text); + const parsed = JSON.parse(text); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; } catch { - for (const line of text.split(/\r?\n/).reverse()) { - const candidate = line.trim(); - if (!candidate) continue; + const verdicts = []; + for (const line of text.split(/\r?\n/)) { try { - const parsed = JSON.parse(candidate); - if (parsed && typeof parsed === 'object') return parsed; + const parsed = JSON.parse(line.trim()); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + verdicts.push(parsed); + } } catch { - // Keep looking for the final JSON response line. + // Plain-text diagnostics are allowed, but ambiguous verdicts are not. } } - return null; + return verdicts.length === 1 ? verdicts[0] : null; } } @@ -116,7 +118,8 @@ export function decisionFromGuardResponse(response) { hookSpecific.hookEventName !== 'PreToolUse') { return { allow: false, reason: 'HOL Guard returned a different hook event.' }; } - if (response.continue === false || response.decision === 'deny') { + if (('continue' in response && response.continue !== true) || + ('decision' in response && response.decision !== 'allow')) { return { allow: false, reason: 'HOL Guard refused tool continuation.' }; } const policyAction = response.policy_action; From 3e133283d2c6386f50bf600495b2855765fb0a42 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:30:23 -0400 Subject: [PATCH 10/44] test(hol-guard): cover ambiguous stdout and explicit stop fields --- scripts/hol-guard-before-tool.test.mjs | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index ed107b3..95ee770 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -4,6 +4,7 @@ import { buildGuardPayload, decisionFromGuardResponse, extractKlaatCommand, + parseGuardJson, } from './hol-guard-before-tool.mjs'; test('extracts run_command command from Klaat tool_args', () => { @@ -79,3 +80,31 @@ test('blocks review, block, malformed, and missing-reason responses', () => { assert.equal(decisionFromGuardResponse(response).allow, false); } }); + +test('rejects multiple machine verdicts even when the final one allows', () => { + const allowed = '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"permissionDecision":"allow"}}'; + const denied = '{"policy_action":"block","reason_code":"policy_block","hookSpecificOutput":{"permissionDecision":"deny"}}'; + assert.equal(parseGuardJson(`log\n${allowed}`)?.policy_action, 'allow'); + for (const output of [`${denied}\n${allowed}`, `${allowed}\n${denied}`, `${allowed}\n${allowed}`]) { + assert.equal(parseGuardJson(output), null); + } +}); + +test('explicit stop fields override otherwise authoritative allows', () => { + const allowed = { + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { permissionDecision: 'allow' }, + }; + for (const stopped of [ + { continue: false }, + { continue: 'false' }, + { continue: 0 }, + { decision: 'deny' }, + { decision: 'review' }, + { decision: 'block' }, + { decision: 0 }, + ]) { + assert.equal(decisionFromGuardResponse({ ...allowed, ...stopped }).allow, false); + } +}); From f7e84127fa0396a4b4fba79274ee1c190335d9dc Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:07:41 -0400 Subject: [PATCH 11/44] fix(hol-guard): whitelist only proven native-exact allow reasons --- scripts/hol-guard-before-tool.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 81ab513..0eb35a8 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -144,7 +144,8 @@ export function decisionFromGuardResponse(response) { // A superficially allow-shaped response with a destructive/review reason // must not bypass Guard's native classifier. Unknown reasons fail closed. - const provenAllowReason = reasonCode.startsWith('native_exact_') || + const provenAllowReason = reasonCode.startsWith('native_exact_safe_') || + reasonCode === 'native_exact_introspection_command' || reasonCode === 'native_policy_allow' || reasonCode === 'native_custom_mcp_tool_allow'; if (policyAction === 'allow' && provenAllowReason) { return { allow: true, reason: '' }; From 894646b87006a1812395dca0220623f0a2b79dd0 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:37:49 -0400 Subject: [PATCH 12/44] docs: align HOL Guard adapter review status with PR #68 --- docs/hol-guard-before-tool.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index ffcbd0e..336fbae 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -1,6 +1,6 @@ # HOL Guard `before_tool` adapter packet -Status: owned-fork implementation and tests prepared. This is not an upstream integration or a release artifact. +Status (updated October 28, 2026): HOL-authored adapter proposed for independent review in [Klaat Code PR #68](https://github.com/KlaatAI/klaatcode/pull/68). The PR is open, not merged or released. This document corrects the earlier pre-submission status; it does not claim third-party approval or adoption. ## Why this maps cleanly @@ -19,9 +19,9 @@ Klaat Code blocks a tool call when the hook exits with status `2` or writes a JS HOL Guard already has native pre-tool authority for command decisions. The supported native request is a versioned `PreToolUse` envelope whose `tool_input.command` contains the command string. The Rust runtime owns the security decision. The adapter transports and renders that result rather than reimplementing Guard policy in Klaat Code. -## Prepared adapter behavior +## Proposed adapter behavior -The owned fork contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: +The proposed PR branch contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: 1. Parses `tool_args` as JSON. 2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. @@ -54,11 +54,11 @@ With no resident native policy authority initialized, `hol-guard hook --harness The first adapter version treated a generic `warn` plus `permissionDecision: allow` as sufficient and therefore would have allowed that unavailable state. The owned-fork adapter now rejects Guard availability and not-ready reason codes and rejects unknown warning results. Re-running the adapter against the same real 3.4.2 runtime now emits Klaat's block result for both test commands while Guard authority is unavailable. -This closes the unavailable-runtime fail-open defect. It does not yet prove the final authoritative allow/deny path. +This closes the unavailable-runtime fail-open defect seen in the initial test. The [PR description](https://github.com/KlaatAI/klaatcode/pull/68) additionally reports a later isolated HOL Guard 3.4.2 native-runtime test with benign allows and a destructive-command block. That later assertion is a contributor report, not an independent maintainer acceptance or a raw test log reproduced in this document. -## Remaining real-runtime gate +## Independent review and real-runtime validation -The implementation is not ready for upstream submission until an isolated managed Guard runtime can produce authoritative native decisions for these cases: +The implementation has already been submitted for independent upstream review in PR #68. A reviewer should reproduce these cases with an isolated managed Guard runtime rather than relying only on contributor-reported results: | Case | Expected result | | --- | --- | @@ -69,9 +69,9 @@ The implementation is not ready for upstream submission until an isolated manage | malformed `tool_args` | fail closed | | Guard runtime unavailable | fail closed | -The deny-path test must prove that the target command is not executed. +The denial test must verify that the target command was not executed. The PR description reports a sentinel test; the exact runtime transcript is not reproduced in this document. -An isolated `hol-guard install codex` attempt in the validation sandbox did not establish that authority because Guard rejected the sandbox interpreter as writable by another user. No real user installation was modified. A clean authoritative setup remains required before upstream submission. +An earlier isolated `hol-guard install codex` attempt did not establish authority because Guard rejected the sandbox interpreter as writable by another user. No real user installation was modified. The PR description reports a later successful managed-runtime test; that proof should be independently replayed before merge. ## Candidate hook configuration @@ -90,14 +90,14 @@ The adapter should remain project-local until there is a stable shipped integrat The current upstream README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. This owned-fork candidate supplies the missing executable behavior without changing Klaat's hook semantics. -## Upstream gate +## Acceptance and release gates -Before any upstream PR: +Before merge or release: - revalidate the current Klaat Code upstream head, hook payload, block semantics, contribution guidance, and queue ownership; - revalidate HOL Guard's current native hook entry point; - keep Klaat Code typecheck/build plus focused adapter tests green; - prove one authoritative allow path and one authoritative deny path with the real Guard runtime, including target command non-execution on deny; -- confirm the contribution still fits current Distribution WIP and maintainer-conversion gates. +- get independent Klaat maintainer review and check the current PR branch against the upstream contribution rules. -Until those gates pass, this remains owned-fork preparation and carries no strict outcome value. +Until independent upstream approval/merge and a separate usable release, PR #68 remains a HOL-authored proposal. It is not an externally authored PR, a tagged extension release, or independently measured nonauthor adoption. From 2d1d8058c2f3f626792e3e6fd68af52f78c4d2ef Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:55:05 -0400 Subject: [PATCH 13/44] fix: block tool calls when HOL Guard adapter cannot launch --- scripts/hol-guard-before-tool.sh | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 scripts/hol-guard-before-tool.sh diff --git a/scripts/hol-guard-before-tool.sh b/scripts/hol-guard-before-tool.sh new file mode 100644 index 0000000..e3e797c --- /dev/null +++ b/scripts/hol-guard-before-tool.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Klaat Code treats exit 2 as a blocking before_tool hook error. A missing +# Node executable or adapter must not silently turn a security hook into allow. +script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd) || { + printf '%s\n' 'HOL Guard adapter directory is unavailable.' >&2 + exit 2 +} +node "$script_dir/hol-guard-before-tool.mjs" +status=$? +if [ "$status" -ne 0 ]; then + printf 'HOL Guard adapter failed (exit %s); blocking tool call.\n' "$status" >&2 + exit 2 +fi From 4b0a78f0e7f314daf933160d016b31795adde4ca Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:56:06 -0400 Subject: [PATCH 14/44] test: verify fail-closed Guard hook launcher --- .../hol-guard-before-tool-wrapper.test.mjs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 scripts/hol-guard-before-tool-wrapper.test.mjs diff --git a/scripts/hol-guard-before-tool-wrapper.test.mjs b/scripts/hol-guard-before-tool-wrapper.test.mjs new file mode 100644 index 0000000..7aeff21 --- /dev/null +++ b/scripts/hol-guard-before-tool-wrapper.test.mjs @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const wrapperPath = join(dirname(fileURLToPath(import.meta.url)), 'hol-guard-before-tool.sh'); + +function runWrapper(fakeAdapter) { + const directory = mkdtempSync(join(tmpdir(), 'klaat-guard-wrapper-')); + try { + const wrapper = join(directory, 'hol-guard-before-tool.sh'); + copyFileSync(wrapperPath, wrapper); + if (fakeAdapter !== null) { + writeFileSync(join(directory, 'hol-guard-before-tool.mjs'), fakeAdapter); + } + return spawnSync('sh', [wrapper], { + encoding: 'utf8', + input: JSON.stringify({ event: 'before_tool', tool_name: 'run_command' }), + timeout: 3000, + }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +const posix = process.platform !== 'win32'; + +test('wrapper preserves authoritative allow with exit 0', { skip: !posix }, () => { + const result = runWrapper('process.exit(0);'); + assert.equal(result.status, 0); + assert.equal(result.stdout.trim(), ''); +}); + +test('wrapper preserves JSON block sent on stdout', { skip: !posix }, () => { + const result = runWrapper('console.log(JSON.stringify({ decision: "block", reason: "denied" }));'); + assert.equal(result.status, 0); + assert.deepEqual(JSON.parse(result.stdout), { decision: 'block', reason: 'denied' }); +}); + +test('wrapper converts adapter runtime failure into Klaat blocking exit 2', { skip: !posix }, () => { + const result = runWrapper('process.exit(7);'); + assert.equal(result.status, 2); + assert.match(result.stderr, /failed \\(exit 7\\)/); +}); + +test('wrapper converts absent adapter into Klaat blocking exit 2', { skip: !posix }, () => { + const result = runWrapper(null); + assert.equal(result.status, 2); + assert.match(result.stderr, /failed \\(exit /); +}); + +// The host's hook timeout must exceed the adapter's own 9-second deadline. +// These tests cover shell exit behavior, not integration with a managed Guard runtime. From 5d4ca20990b054e19c792c4bd26a4a3173cdb54c Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:56:35 -0400 Subject: [PATCH 15/44] test: correct launcher stderr match assertions --- scripts/hol-guard-before-tool-wrapper.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool-wrapper.test.mjs b/scripts/hol-guard-before-tool-wrapper.test.mjs index 7aeff21..ad735af 100644 --- a/scripts/hol-guard-before-tool-wrapper.test.mjs +++ b/scripts/hol-guard-before-tool-wrapper.test.mjs @@ -43,13 +43,13 @@ test('wrapper preserves JSON block sent on stdout', { skip: !posix }, () => { test('wrapper converts adapter runtime failure into Klaat blocking exit 2', { skip: !posix }, () => { const result = runWrapper('process.exit(7);'); assert.equal(result.status, 2); - assert.match(result.stderr, /failed \\(exit 7\\)/); + assert.match(result.stderr, /failed \(exit 7\)/); }); test('wrapper converts absent adapter into Klaat blocking exit 2', { skip: !posix }, () => { const result = runWrapper(null); assert.equal(result.status, 2); - assert.match(result.stderr, /failed \\(exit /); + assert.match(result.stderr, /failed \(exit /); }); // The host's hook timeout must exceed the adapter's own 9-second deadline. From 5e6d7e35510aee7d4bf9803188f2e6b49ded5de5 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:57:03 -0400 Subject: [PATCH 16/44] docs: use verified launcher and describe hook fail-open limits --- docs/hol-guard-before-tool.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index 336fbae..908d13a 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -21,7 +21,7 @@ HOL Guard already has native pre-tool authority for command decisions. The suppo ## Proposed adapter behavior -The proposed PR branch contains `scripts/hol-guard-before-tool.mjs`. For `tool_name == "run_command"` it: +The proposed PR branch contains the JavaScript adapter `scripts/hol-guard-before-tool.mjs` and a POSIX fail-closed launcher `scripts/hol-guard-before-tool.sh`. For `tool_name == "run_command"` it: 1. Parses `tool_args` as JSON. 2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. @@ -40,6 +40,7 @@ The following checks pass: - `node --check scripts/hol-guard-before-tool.mjs` - `node --test scripts/hol-guard-before-tool.test.mjs`, 7/7 focused tests +- `node --test scripts/hol-guard-before-tool-wrapper.test.mjs`, 4/4 isolated POSIX launcher tests (October 28; not upstream CI) - `bun install --frozen-lockfile` - `bun run typecheck` - `bun run build` @@ -75,20 +76,25 @@ An earlier isolated `hol-guard install codex` attempt did not establish authorit ## Candidate hook configuration -The adapter should remain project-local until there is a stable shipped integration surface: +This is an **unreleased, project-local proposal**, not a component shipped by Klaat Code or HOL Guard. Copy **both** `scripts/hol-guard-before-tool.sh` and `scripts/hol-guard-before-tool.mjs` from the reviewed PR branch into your project's `scripts/` directory. Do not assume these scripts are included in the npm package: Klaat's current `package.json` publishes only its built CLI, README, and license. ```json { "before_tool": [ { "matcher": "run_command", - "command": "node ./scripts/hol-guard-before-tool.mjs" + "command": "sh ./scripts/hol-guard-before-tool.sh", + "timeout": 12 } ] } ``` -The current upstream README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. This owned-fork candidate supplies the missing executable behavior without changing Klaat's hook semantics. +Klaat's current hook runner treats exit status **2** or an explicit JSON block as denial, but ignores other failed shell exits and timeouts. The POSIX launcher therefore converts missing Node, missing adapter, and unexpected adapter failures to exit **2** rather than silently allowing the command. The host timeout is set above the adapter's 9-second Guard deadline so the adapter can return its own block verdict first. + +**Limit:** This does not fix a missing `sh` interpreter, a missing *launcher itself*, or a host timeout before the launcher can report a verdict. Klaat currently fails open in those cases. A separate upstream hook-runner change to fail closed on every nonzero exit, start failure, and timeout would be needed before treating this as a general enforcement boundary. Do not represent the PR as a shipped security guarantee. + +The current upstream README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. This PR supplies an opt-in adapter, not a replacement for Klaat's global hook-failure semantics. ## Acceptance and release gates From 78184fbf7baf4bf9e1820d5967fb3ef4023c41de Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:51:58 -0400 Subject: [PATCH 17/44] fix(guard): reject mixed stdout instead of extracting an allow --- scripts/hol-guard-before-tool.mjs | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 0eb35a8..919a2cd 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -87,18 +87,8 @@ export function parseGuardJson(stdout) { const parsed = JSON.parse(text); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; } catch { - const verdicts = []; - for (const line of text.split(/\r?\n/)) { - try { - const parsed = JSON.parse(line.trim()); - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { - verdicts.push(parsed); - } - } catch { - // Plain-text diagnostics are allowed, but ambiguous verdicts are not. - } - } - return verdicts.length === 1 ? verdicts[0] : null; + // A diagnostic line or second verdict cannot authorize execution. + return null; } } From 37e718bdfcefab1b27c4b1423443822bddddb310 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:52:13 -0400 Subject: [PATCH 18/44] test(guard): assert strict one-verdict stdout parsing --- scripts/hol-guard-before-tool.test.mjs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 95ee770..af9dc4b 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -81,11 +81,17 @@ test('blocks review, block, malformed, and missing-reason responses', () => { } }); -test('rejects multiple machine verdicts even when the final one allows', () => { +test('accepts one complete verdict, but never extracts an allow from mixed stdout', () => { const allowed = '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"permissionDecision":"allow"}}'; const denied = '{"policy_action":"block","reason_code":"policy_block","hookSpecificOutput":{"permissionDecision":"deny"}}'; - assert.equal(parseGuardJson(`log\n${allowed}`)?.policy_action, 'allow'); - for (const output of [`${denied}\n${allowed}`, `${allowed}\n${denied}`, `${allowed}\n${allowed}`]) { + assert.equal(parseGuardJson(` \n${allowed}\n `)?.policy_action, 'allow'); + for (const output of [ + `diagnostic\n${allowed}`, + `${allowed}\ndiagnostic`, + `${denied}\n${allowed}`, + `${allowed}\n${denied}`, + `${allowed}\n${allowed}`, + ]) { assert.equal(parseGuardJson(output), null); } }); From 20990b92f0c8d3891785da761d1f714c41d1e9f4 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:52:29 -0400 Subject: [PATCH 19/44] docs(guard): document exact JSON verdict requirement --- docs/hol-guard-before-tool.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index 908d13a..95770f6 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -30,7 +30,7 @@ The proposed PR branch contains the JavaScript adapter `scripts/hol-guard-before 5. Allows an authoritative native `allow` decision, or the explicit `native_policy_warning` allow-with-warning result. 6. Fails closed when native review is unavailable or not ready, including `native_pre_tool_unavailable`, `native_policy_not_ready`, worker/daemon availability failures, unmanaged-harness passthrough, unknown warning results, malformed output, timeout, missing Guard, review, reapproval, sandbox-required, or block. -The adapter does not use `hol-guard command explain` as enforcement authority. +The adapter does not use `hol-guard command explain` as enforcement authority. The `--json` response must be one complete JSON object on stdout; a diagnostic prefix, suffix, or multiple verdicts fails closed instead of letting the adapter extract a possibly misleading allow result. ## Validation completed From 6675a0a1aa41f425674ffc1b1662f9bf3a098dd2 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:47:07 -0400 Subject: [PATCH 20/44] fix(guard): require a bound PreToolUse event before allowing Klaat commands --- scripts/hol-guard-before-tool.mjs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 919a2cd..844008f 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -97,17 +97,13 @@ export function decisionFromGuardResponse(response) { return { allow: false, reason: 'HOL Guard returned an invalid response.' }; } const hookSpecific = response.hookSpecificOutput; - const permissionDecision = hookSpecific && typeof hookSpecific === 'object' - ? hookSpecific.permissionDecision - : undefined; - // Native hook responses are event-bound; a mismatched or explicitly stopped - // response cannot authorize a Klaat before_tool invocation. Historic local - // fixtures omit hookEventName, so retain their behavior until updated. - if (hookSpecific && typeof hookSpecific === 'object' && - hookSpecific.hookEventName !== undefined && - hookSpecific.hookEventName !== 'PreToolUse') { - return { allow: false, reason: 'HOL Guard returned a different hook event.' }; + // Only a concrete PreToolUse verdict is an authorization for this hook. + // A missing event name must fail closed just like a mismatched event. + if (!hookSpecific || typeof hookSpecific !== 'object' || + Array.isArray(hookSpecific) || hookSpecific.hookEventName !== 'PreToolUse') { + return { allow: false, reason: 'HOL Guard returned no matching PreToolUse event.' }; } + const permissionDecision = hookSpecific.permissionDecision; if (('continue' in response && response.continue !== true) || ('decision' in response && response.decision !== 'allow')) { return { allow: false, reason: 'HOL Guard refused tool continuation.' }; From 7d6a254fb83e800d17a9bd9d15d07894f703882a Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:47:23 -0400 Subject: [PATCH 21/44] test(guard): reject missing or mismatched PreToolUse event bindings --- scripts/hol-guard-before-tool.test.mjs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index af9dc4b..1a53b8b 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -44,15 +44,30 @@ test('allows authoritative native allow and policy warning decisions', () => { assert.equal(decisionFromGuardResponse({ policy_action: 'allow', reason_code: 'native_exact_safe_command', - hookSpecificOutput: { permissionDecision: 'allow' }, + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, }).allow, true); assert.equal(decisionFromGuardResponse({ policy_action: 'warn', reason_code: 'native_policy_warning', - hookSpecificOutput: { permissionDecision: 'allow' }, + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, }).allow, true); }); +test('rejects absent, malformed, and mismatched event envelopes', () => { + for (const hookSpecificOutput of [ + { permissionDecision: 'allow' }, + { hookEventName: 'PostToolUse', permissionDecision: 'allow' }, + null, + [], + ]) { + assert.equal(decisionFromGuardResponse({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput, + }).allow, false); + } +}); + test('fails closed on unavailable and non-authoritative warn decisions', () => { for (const reason_code of [ 'native_pre_tool_unavailable', @@ -65,7 +80,7 @@ test('fails closed on unavailable and non-authoritative warn decisions', () => { policy_action: 'warn', reason_code, reason: 'Guard did not complete an authoritative review.', - hookSpecificOutput: { permissionDecision: 'allow' }, + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, }).allow, false, reason_code); } }); @@ -74,7 +89,7 @@ test('blocks review, block, malformed, and missing-reason responses', () => { for (const response of [ { policy_action: 'review', reason_code: 'native_command_review_required', hookSpecificOutput: { permissionDecision: 'deny' } }, { policy_action: 'block', reason_code: 'native_destructive_command', hookSpecificOutput: { permissionDecision: 'deny' } }, - { policy_action: 'allow', hookSpecificOutput: { permissionDecision: 'allow' } }, + { policy_action: 'allow', hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' } }, {}, ]) { assert.equal(decisionFromGuardResponse(response).allow, false); @@ -100,7 +115,7 @@ test('explicit stop fields override otherwise authoritative allows', () => { const allowed = { policy_action: 'allow', reason_code: 'native_policy_allow', - hookSpecificOutput: { permissionDecision: 'allow' }, + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, }; for (const stopped of [ { continue: false }, From 4b4544e61648c06b9107557030b5108446c5ad8f Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:47:59 -0400 Subject: [PATCH 22/44] docs(guard): require event-bound authority for Klaat hook decisions --- docs/hol-guard-before-tool.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md index 95770f6..5f71d94 100644 --- a/docs/hol-guard-before-tool.md +++ b/docs/hol-guard-before-tool.md @@ -27,7 +27,7 @@ The proposed PR branch contains the JavaScript adapter `scripts/hol-guard-before 2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. 3. Constructs a Guard `PreToolUse` request with the current project as `cwd`. 4. Sends the complete request through `hol-guard hook --harness codex --json`, with the workspace when available, so Guard's native hook authority remains the decision owner. -5. Allows an authoritative native `allow` decision, or the explicit `native_policy_warning` allow-with-warning result. +5. Requires `hookSpecificOutput.hookEventName` to be `PreToolUse`, then allows an authoritative native `allow` decision or the explicit `native_policy_warning` allow-with-warning result. Missing or mismatched event binding fails closed. 6. Fails closed when native review is unavailable or not ready, including `native_pre_tool_unavailable`, `native_policy_not_ready`, worker/daemon availability failures, unmanaged-harness passthrough, unknown warning results, malformed output, timeout, missing Guard, review, reapproval, sandbox-required, or block. The adapter does not use `hol-guard command explain` as enforcement authority. The `--json` response must be one complete JSON object on stdout; a diagnostic prefix, suffix, or multiple verdicts fails closed instead of letting the adapter extract a possibly misleading allow result. From 5decf5315b4b44308dac08846e5829de205e04a2 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:57:08 -0400 Subject: [PATCH 23/44] fix: match Guard inspection cwd to run_command workdir --- scripts/hol-guard-before-tool.mjs | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 844008f..92265d3 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import process from 'node:process'; @@ -65,18 +66,38 @@ export function extractKlaatCommand(payload) { return args.command; } +export function resolveKlaatCommandCwd(payload) { + const root = payload?.project_root; + if (typeof root !== 'string' || !root.trim()) { + throw new Error('run_command project_root is missing'); + } + let workdir; + if (typeof payload.tool_args === 'string') { + const parsed = JSON.parse(payload.tool_args); + workdir = parsed?.workdir; + } + if (!workdir) return root; + if (typeof workdir !== 'string') { + throw new Error('run_command workdir must be a string'); + } + // Match Klaat's runCommand/safeResolve logic, including tilde paths. + if (workdir.startsWith('/') || workdir.startsWith('~')) { + return workdir.replace(/^~/, process.env.HOME ?? '~'); + } + return resolve(root, workdir); +} + export function buildGuardPayload(payload, command) { const guardPayload = { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command }, + // Guard must inspect from the same directory as run_command executes. + cwd: resolveKlaatCommandCwd(payload), }; if (typeof payload.session_id === 'string' && payload.session_id) { guardPayload.session_id = payload.session_id; } - if (typeof payload.project_root === 'string' && payload.project_root) { - guardPayload.cwd = payload.project_root; - } return guardPayload; } @@ -166,15 +187,16 @@ export async function main() { } let command; + let guardPayload; try { command = extractKlaatCommand(payload); + if (command !== null) guardPayload = buildGuardPayload(payload, command); } catch (error) { block(error instanceof Error ? error.message : 'invalid run_command payload'); return; } if (command === null) return; - const guardPayload = buildGuardPayload(payload, command); const args = ['hook', '--harness', 'codex']; if (typeof payload.project_root === 'string' && payload.project_root) { args.push('--workspace', payload.project_root); @@ -186,6 +208,7 @@ export async function main() { encoding: 'utf8', timeout: GUARD_TIMEOUT_MS, maxBuffer: MAX_STDIN_BYTES, + cwd: guardPayload.cwd, windowsHide: true, }); From e08918de0a1adf0121f1f6e98bc0ec8c8403b525 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:57:47 -0400 Subject: [PATCH 24/44] test: cover workdir override for Guard command inspection --- scripts/hol-guard-before-tool.test.mjs | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 1a53b8b..70b4cc4 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -1,7 +1,9 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { resolve } from 'node:path'; import { buildGuardPayload, + resolveKlaatCommandCwd, decisionFromGuardResponse, extractKlaatCommand, parseGuardJson, @@ -129,3 +131,35 @@ test('explicit stop fields override otherwise authoritative allows', () => { assert.equal(decisionFromGuardResponse({ ...allowed, ...stopped }).allow, false); } }); + + +test('matches the effective run_command workdir for Guard inspection', () => { + const root = '/repo'; + for (const [workdir, expected] of [ + ['nested', resolve(root, 'nested')], + ['/tmp/other-worktree', '/tmp/other-worktree'], + ['', root], + ]) { + const payload = { + session_id: 's1', + project_root: root, + tool_args: JSON.stringify({ command: 'git status', workdir }), + }; + assert.equal(resolveKlaatCommandCwd(payload), expected); + assert.equal(buildGuardPayload(payload, 'git status').cwd, expected); + } +}); + +test('denies an unknown execution directory instead of inspecting the wrong tree', () => { + assert.throws( + () => resolveKlaatCommandCwd({ tool_args: JSON.stringify({ command: 'git status' }) }), + /project_root/, + ); + assert.throws( + () => resolveKlaatCommandCwd({ + project_root: '/repo', + tool_args: JSON.stringify({ command: 'git status', workdir: ['elsewhere'] }), + }), + /workdir must be a string/, + ); +}); From ae2bb3a3e6656a73054ae6e2a3f4792b1df00fed Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:31:43 -0400 Subject: [PATCH 25/44] fix(hol-guard): reject duplicate authoritative verdict fields --- scripts/hol-guard-before-tool.mjs | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 92265d3..b0f22bf 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -101,10 +101,46 @@ export function buildGuardPayload(payload, command) { return guardPayload; } +// Standard JSON.parse keeps the last repeated field. Refuse duplicate keys +// before an allow-shaped response can erase an earlier deny or review. +function containsDuplicateGuardKeys(raw) { + const frames = []; + for (let i = 0; i < raw.length;) { + const char = raw[i]; + if (char === '"') { + const start = i++; + while (i < raw.length) { + if (raw[i] === "\\") { + i += 2; + continue; + } + if (raw[i++] === '"') break; + } + const frame = frames[frames.length - 1]; + if (frame?.isObject && frame.expectKey) { + const key = JSON.parse(raw.slice(start, i)); + if (frame.keys.has(key)) return true; + frame.keys.add(key); + frame.expectKey = false; + } + continue; + } + if (char === '{') frames.push({ isObject: true, expectKey: true, keys: new Set() }); + else if (char === '[') frames.push({ isObject: false }); + else if (char === '}' || char === ']') frames.pop(); + else if (char === ',' && frames[frames.length - 1]?.isObject) { + frames[frames.length - 1].expectKey = true; + } + i++; + } + return false; +} + export function parseGuardJson(stdout) { const text = typeof stdout === 'string' ? stdout.trim() : ''; if (!text) return null; try { + if (containsDuplicateGuardKeys(text)) return null; const parsed = JSON.parse(text); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; } catch { From 230a8b23627e81b286428a290905fced400d976d Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:32:03 -0400 Subject: [PATCH 26/44] test(hol-guard): fail closed on overwritten native verdicts --- scripts/hol-guard-before-tool.test.mjs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 70b4cc4..7de535c 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -113,6 +113,21 @@ test('accepts one complete verdict, but never extracts an allow from mixed stdou } }); +test('rejects repeated authoritative Guard keys, including escaped duplicates', () => { + const contradictory = [ + '{"policy_action":"block","policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}', + '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecision":"allow"}}', + '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"},"metadata":{"note":"deny","note":"allow"}}', + '{"policy_\\u0061ction":"block","policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}', + ]; + for (const output of contradictory) { + assert.equal(parseGuardJson(output), null); + assert.equal(decisionFromGuardResponse(parseGuardJson(output)).allow, false); + } + const valid = '{"notes":["repeated","repeated"],"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'; + assert.deepEqual(parseGuardJson(valid), JSON.parse(valid)); +}); + test('explicit stop fields override otherwise authoritative allows', () => { const allowed = { policy_action: 'allow', From 36ac361281a04d7e381983356005af7cb8f17682 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:37:23 -0400 Subject: [PATCH 27/44] fix(hol-guard): reject ambiguous nonabsolute execution roots --- scripts/hol-guard-before-tool.mjs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index b0f22bf..78e97c9 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; -import { resolve } from 'node:path'; +import { isAbsolute, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import process from 'node:process'; @@ -68,8 +68,8 @@ export function extractKlaatCommand(payload) { export function resolveKlaatCommandCwd(payload) { const root = payload?.project_root; - if (typeof root !== 'string' || !root.trim()) { - throw new Error('run_command project_root is missing'); + if (typeof root !== 'string' || !root.trim() || !isAbsolute(root)) { + throw new Error('run_command project_root must be an absolute path'); } let workdir; if (typeof payload.tool_args === 'string') { @@ -82,7 +82,11 @@ export function resolveKlaatCommandCwd(payload) { } // Match Klaat's runCommand/safeResolve logic, including tilde paths. if (workdir.startsWith('/') || workdir.startsWith('~')) { - return workdir.replace(/^~/, process.env.HOME ?? '~'); + const expanded = workdir.replace(/^~/, process.env.HOME ?? '~'); + if (!isAbsolute(expanded)) { + throw new Error('run_command effective workdir must be an absolute path'); + } + return expanded; } return resolve(root, workdir); } From 20ebab9fe0a864db132ea5baa4f0426461655ef3 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:37:37 -0400 Subject: [PATCH 28/44] test(hol-guard): fail closed on relative project roots --- scripts/hol-guard-before-tool.test.mjs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 7de535c..6d83e9f 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -178,3 +178,15 @@ test('denies an unknown execution directory instead of inspecting the wrong tree /workdir must be a string/, ); }); + +test('rejects relative project roots before choosing the Guard workspace', () => { + for (const project_root of ['.', 'relative/repo', '']) { + assert.throws( + () => resolveKlaatCommandCwd({ + project_root, + tool_args: JSON.stringify({ command: 'git status' }), + }), + /project_root must be an absolute path/, + ); + } +}); From 46fd38eb464c8e38180110b33706cf84d38f06bb Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:07:10 -0400 Subject: [PATCH 29/44] fix: prevent project-local PATH shadowing of HOL Guard hook --- scripts/hol-guard-before-tool.mjs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 78e97c9..4416efb 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -1,12 +1,22 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; -import { isAbsolute, resolve } from 'node:path'; +import { delimiter, isAbsolute, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import process from 'node:process'; const MAX_STDIN_BYTES = 1_000_000; const GUARD_TIMEOUT_MS = 9_000; +// The hook switches cwd to the tool directory. Relative PATH entries would +// then resolve there and could select a different, project-local hol-guard. +// Only absolute search directories may be used for Guard's executable lookup. +export function trustedGuardPath(pathValue) { + if (typeof pathValue !== 'string') return ''; + return pathValue.split(delimiter) + .filter((entry) => entry && isAbsolute(entry)) + .join(delimiter); +} + const NON_AUTHORITATIVE_REASON_CODES = new Set([ 'native_hook_disabled', 'native_shadow_diagnostic_disabled', @@ -243,12 +253,25 @@ export async function main() { } args.push('--json'); + const guardPathKey = Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH'); + const guardPath = trustedGuardPath(guardPathKey ? process.env[guardPathKey] : ''); + if (!guardPath) { + block('HOL Guard needs an absolute trusted executable search path.'); + return; + } + const guardEnv = { ...process.env }; + for (const key of Object.keys(guardEnv)) { + if (key.toUpperCase() === 'PATH') delete guardEnv[key]; + } + guardEnv.PATH = guardPath; + const result = spawnSync('hol-guard', args, { input: `${JSON.stringify(guardPayload)}\n`, encoding: 'utf8', timeout: GUARD_TIMEOUT_MS, maxBuffer: MAX_STDIN_BYTES, cwd: guardPayload.cwd, + env: guardEnv, windowsHide: true, }); From 82768cfcebcc66a95d66adab9cc518cd2c9d3582 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:08:19 -0400 Subject: [PATCH 30/44] test: block PATH shadowing in Klaat Guard hook --- scripts/hol-guard-before-tool.test.mjs | 62 +++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 6d83e9f..408d73a 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -1,12 +1,17 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { resolve } from 'node:path'; +import { delimiter, join, resolve } from 'node:path'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; import { buildGuardPayload, resolveKlaatCommandCwd, decisionFromGuardResponse, extractKlaatCommand, parseGuardJson, + trustedGuardPath, } from './hol-guard-before-tool.mjs'; test('extracts run_command command from Klaat tool_args', () => { @@ -190,3 +195,58 @@ test('rejects relative project roots before choosing the Guard workspace', () => ); } }); + + +test('Guard executable search excludes relative and empty PATH entries', () => { + const trustedA = resolve('/usr/local/bin'); + const trustedB = resolve('/opt/guard/bin'); + const original = ['.', trustedA, '', './node_modules/.bin', '../other', trustedB].join(delimiter); + assert.equal(trustedGuardPath(original), [trustedA, trustedB].join(delimiter)); + assert.equal(trustedGuardPath('.'), ''); + assert.equal(trustedGuardPath(undefined), ''); +}); + +test('project-local fake hol-guard cannot shadow a trusted PATH executable', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-hol-guard-path-')); + const toolDirectory = join(root, 'tool-workspace'); + const trustedDirectory = join(root, 'trusted-bin'); + mkdirSync(toolDirectory); + mkdirSync(trustedDirectory); + try { + const fakeAllow = JSON.stringify({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }); + const realBlock = JSON.stringify({ + policy_action: 'block', + reason_code: 'native_policy_block', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, + }); + const fakePath = join(toolDirectory, 'hol-guard'); + const trustedPath = join(trustedDirectory, 'hol-guard'); + writeFileSync(fakePath, "#!/bin/sh\\nprintf '%s\\\\n' '" + fakeAllow + "'\\n"); + writeFileSync(trustedPath, "#!/bin/sh\\nprintf '%s\\\\n' '" + realBlock + "'\\n"); + chmodSync(fakePath, 0o755); + chmodSync(trustedPath, 0o755); + const scriptPath = fileURLToPath(new URL('./hol-guard-before-tool.mjs', import.meta.url)); + const result = spawnSync(process.execPath, [scriptPath], { + cwd: root, + env: { ...process.env, PATH: ['.', trustedDirectory, process.env.PATH ?? ''].join(delimiter) }, + input: JSON.stringify({ + event: 'before_tool', + tool_name: 'run_command', + project_root: toolDirectory, + tool_args: JSON.stringify({ command: 'git status' }), + }), + encoding: 'utf8', + timeout: 10_000, + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout.trim()).decision, 'block'); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); From 82b560e6bbb6e427780e3c40a382d7a5609b5e85 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:09:28 -0400 Subject: [PATCH 31/44] test: correct fake Guard script newline fixtures --- scripts/hol-guard-before-tool.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 408d73a..db2d0f0 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -227,8 +227,8 @@ test('project-local fake hol-guard cannot shadow a trusted PATH executable', { }); const fakePath = join(toolDirectory, 'hol-guard'); const trustedPath = join(trustedDirectory, 'hol-guard'); - writeFileSync(fakePath, "#!/bin/sh\\nprintf '%s\\\\n' '" + fakeAllow + "'\\n"); - writeFileSync(trustedPath, "#!/bin/sh\\nprintf '%s\\\\n' '" + realBlock + "'\\n"); + writeFileSync(fakePath, "#!/bin/sh\nprintf '%s\\n' '" + fakeAllow + "'\n"); + writeFileSync(trustedPath, "#!/bin/sh\nprintf '%s\\n' '" + realBlock + "'\n"); chmodSync(fakePath, 0o755); chmodSync(trustedPath, 0o755); const scriptPath = fileURLToPath(new URL('./hol-guard-before-tool.mjs', import.meta.url)); From 36b51bf523eed6b275092a5156ef1122fe5d9358 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:30:40 -0400 Subject: [PATCH 32/44] fix(guard): reject falsey non-string tool workdirs --- scripts/hol-guard-before-tool.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 4416efb..c96307a 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -86,7 +86,7 @@ export function resolveKlaatCommandCwd(payload) { const parsed = JSON.parse(payload.tool_args); workdir = parsed?.workdir; } - if (!workdir) return root; + if (workdir === undefined || workdir === null || workdir === '') return root; if (typeof workdir !== 'string') { throw new Error('run_command workdir must be a string'); } From de406ea9d1919a940992299019e9bb5830dc526e Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:31:20 -0400 Subject: [PATCH 33/44] test(guard): fail closed on false and zero workdirs --- scripts/hol-guard-before-tool.test.mjs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index db2d0f0..15ec433 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -170,6 +170,17 @@ test('matches the effective run_command workdir for Guard inspection', () => { } }); +test('rejects falsey non-string workdirs before Guard inspects a different directory', () => { + for (const workdir of [false, 0]) { + const payload = { + project_root: '/repo', + tool_args: JSON.stringify({ command: 'git status', workdir }), + }; + assert.throws(() => resolveKlaatCommandCwd(payload), /workdir must be a string/); + assert.throws(() => buildGuardPayload(payload, 'git status'), /workdir must be a string/); + } +}); + test('denies an unknown execution directory instead of inspecting the wrong tree', () => { assert.throws( () => resolveKlaatCommandCwd({ tool_args: JSON.stringify({ command: 'git status' }) }), From 94b288dabc3157e9f9261ee44b8526d8248ba525 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:11:03 -0400 Subject: [PATCH 34/44] fix(hol-guard): block malformed Klaat pre-tool identities --- scripts/hol-guard-before-tool.mjs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index c96307a..01d17ac 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -55,12 +55,19 @@ function block(reason) { } export function extractKlaatCommand(payload) { - if (!payload || typeof payload !== 'object') { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { throw new Error('invalid Klaat hook payload'); } - if (payload.event !== 'before_tool' || payload.tool_name !== 'run_command') { - return null; + // An invalid event or unnamed pre-tool action is not proof that the + // pending action is unrelated to run_command. Fail closed before dispatch. + if (typeof payload.event !== 'string' || !payload.event.trim()) { + throw new Error('Klaat hook event is missing'); + } + if (payload.event !== 'before_tool') return null; + if (typeof payload.tool_name !== 'string' || !payload.tool_name.trim()) { + throw new Error('before_tool identity is missing'); } + if (payload.tool_name !== 'run_command') return null; if (typeof payload.tool_args !== 'string') { throw new Error('run_command tool_args must be a JSON string'); } From 75e098c1ae0d68fb584fd10278f4648eec4b47f2 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:11:25 -0400 Subject: [PATCH 35/44] test(hol-guard): cover malformed Klaat tool event fail-closed --- scripts/hol-guard-before-tool.test.mjs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 15ec433..a0c2593 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -26,6 +26,27 @@ test('ignores unrelated hook events defensively', () => { assert.equal(extractKlaatCommand({ event: 'after_tool', tool_name: 'run_command', tool_args: '{}' }), null); }); +test('denies missing event and pre-tool identity instead of bypassing Guard', () => { + for (const payload of [ + null, + [], + {}, + { event: null, tool_name: 'run_command' }, + { event: '', tool_name: 'run_command' }, + { event: 'before_tool' }, + { event: 'before_tool', tool_name: null }, + { event: 'before_tool', tool_name: '' }, + { event: 'before_tool', tool_name: 42 }, + ]) { + assert.throws(() => extractKlaatCommand(payload)); + } + assert.equal(extractKlaatCommand({ + event: 'before_tool', + tool_name: 'read_file', + tool_args: '{}', + }), null); +}); + test('fails closed on malformed run_command input', () => { assert.throws(() => extractKlaatCommand({ event: 'before_tool', From 0bd1a970c3ce7544be4dc271b87be2144431977f Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:14:48 -0400 Subject: [PATCH 36/44] fix(hol-guard): exclude project-controlled absolute PATH executables --- scripts/hol-guard-before-tool.mjs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 01d17ac..c28392c 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; -import { delimiter, isAbsolute, resolve } from 'node:path'; +import { realpathSync } from 'node:fs'; +import { delimiter, isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; import process from 'node:process'; @@ -10,10 +11,26 @@ const GUARD_TIMEOUT_MS = 9_000; // The hook switches cwd to the tool directory. Relative PATH entries would // then resolve there and could select a different, project-local hol-guard. // Only absolute search directories may be used for Guard's executable lookup. -export function trustedGuardPath(pathValue) { +export function trustedGuardPath(pathValue, untrustedRoots = []) { if (typeof pathValue !== 'string') return ''; + // The project can put a forged hol-guard binary on an *absolute* PATH too. + // Resolve links and reject project-owned bin directories before spawning. + const roots = untrustedRoots.filter((root) => typeof root === 'string' && isAbsolute(root)) + .map((root) => { + try { return realpathSync(root); } catch { return resolve(root); } + }); return pathValue.split(delimiter) - .filter((entry) => entry && isAbsolute(entry)) + .filter((entry) => { + if (!entry || !isAbsolute(entry)) return false; + if (!roots.length) return true; + let directory; + try { directory = realpathSync(entry); } catch { return false; } + return roots.every((root) => { + const rel = relative(root, directory); + return rel !== '' && + (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); + }); + }) .join(delimiter); } @@ -261,7 +278,10 @@ export async function main() { args.push('--json'); const guardPathKey = Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH'); - const guardPath = trustedGuardPath(guardPathKey ? process.env[guardPathKey] : ''); + const guardPath = trustedGuardPath( + guardPathKey ? process.env[guardPathKey] : '', + [payload.project_root, guardPayload.cwd], + ); if (!guardPath) { block('HOL Guard needs an absolute trusted executable search path.'); return; From 07e4dabb130d55a6704119634f9a82bf6feeb984 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:15:15 -0400 Subject: [PATCH 37/44] test(hol-guard): reject absolute workspace PATH and symlink shadows --- scripts/hol-guard-before-tool.test.mjs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index a0c2593..7e8e7c7 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { delimiter, join, resolve } from 'node:path'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; @@ -238,6 +238,26 @@ test('Guard executable search excludes relative and empty PATH entries', () => { assert.equal(trustedGuardPath(undefined), ''); }); +test('rejects absolute project PATH entries and symlinks into the project', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-guard-absolute-path-')); + const project = join(root, 'project'); + const projectBin = join(project, 'bin'); + const trustedBin = join(root, 'trusted-bin'); + const linkedProjectBin = join(root, 'linked-project-bin'); + mkdirSync(projectBin, { recursive: true }); + mkdirSync(trustedBin); + symlinkSync(projectBin, linkedProjectBin, 'dir'); + try { + const options = [projectBin, linkedProjectBin, trustedBin].join(delimiter); + assert.equal(trustedGuardPath(options, [project]), trustedBin); + assert.equal(trustedGuardPath(projectBin, [project]), ''); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + test('project-local fake hol-guard cannot shadow a trusted PATH executable', { skip: process.platform === 'win32', }, () => { From a73c056e077308c73023dd52a1768ed78aef0a97 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:32:56 -0400 Subject: [PATCH 38/44] fix(guard): reject worktree PATH aliases and pin canonical dirs --- scripts/hol-guard-before-tool.mjs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index c28392c..274aa77 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -20,17 +20,21 @@ export function trustedGuardPath(pathValue, untrustedRoots = []) { try { return realpathSync(root); } catch { return resolve(root); } }); return pathValue.split(delimiter) - .filter((entry) => { - if (!entry || !isAbsolute(entry)) return false; - if (!roots.length) return true; + .map((entry) => { + if (!entry || !isAbsolute(entry)) return null; + if (!roots.length) return entry; let directory; - try { directory = realpathSync(entry); } catch { return false; } - return roots.every((root) => { - const rel = relative(root, directory); + try { directory = realpathSync(entry); } catch { return null; } + const outsideRoots = (candidate) => roots.every((root) => { + const rel = relative(root, candidate); return rel !== '' && (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); }); + // The alias itself may be project-controlled even if its target is not. + // Launch from canonical dirs so a symlink swap cannot rebind Guard. + return outsideRoots(entry) && outsideRoots(directory) ? directory : null; }) + .filter((entry) => entry !== null) .join(delimiter); } From 03fb10cd1f9fcd2aaae61794e776236e2246b718 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:33:22 -0400 Subject: [PATCH 39/44] test(guard): deny project-owned PATH symlink aliases --- scripts/hol-guard-before-tool.test.mjs | 27 ++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 7e8e7c7..80f71d1 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { delimiter, join, resolve } from 'node:path'; -import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; @@ -251,7 +251,7 @@ test('rejects absolute project PATH entries and symlinks into the project', { symlinkSync(projectBin, linkedProjectBin, 'dir'); try { const options = [projectBin, linkedProjectBin, trustedBin].join(delimiter); - assert.equal(trustedGuardPath(options, [project]), trustedBin); + assert.equal(trustedGuardPath(options, [project]), realpathSync(trustedBin)); assert.equal(trustedGuardPath(projectBin, [project]), ''); } finally { rmSync(root, { recursive: true, force: true }); @@ -302,3 +302,26 @@ test('project-local fake hol-guard cannot shadow a trusted PATH executable', { rmSync(root, { recursive: true, force: true }); } }); + +test('rejects project-controlled PATH link to trusted Guard directory', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-guard-link-spoof-')); + const project = join(root, 'project'); + const trusted = join(root, 'trusted-bin'); + const outsideAlias = join(root, 'trusted-alias'); + const worktreeAlias = join(project, 'guard-bin-alias'); + mkdirSync(project); + mkdirSync(trusted); + symlinkSync(trusted, outsideAlias, 'dir'); + symlinkSync(trusted, worktreeAlias, 'dir'); + try { + assert.equal(trustedGuardPath(worktreeAlias, [project]), ''); + const sanitized = trustedGuardPath([worktreeAlias, outsideAlias].join(delimiter), [project]); + // The project can retarget its own link, while trusted aliases resolve to + // fixed canonical directories before spawn. + assert.equal(sanitized, realpathSync(trusted)); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); From f9670cef574b4b21b7399a13c5633b9670454c90 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:22:39 -0400 Subject: [PATCH 40/44] fix: reject invalid UTF-8 in native Guard verdicts --- scripts/hol-guard-before-tool.mjs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index 274aa77..fc9918e 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; import { realpathSync } from 'node:fs'; +import { TextDecoder } from 'node:util'; import { delimiter, isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; import process from 'node:process'; @@ -191,6 +192,17 @@ export function parseGuardJson(stdout) { } } +// Node's default UTF-8 decoding replaces invalid bytes, which could turn a +// malformed native verdict into valid allow-shaped JSON. Reject the bytes. +export function parseGuardBytes(bytes) { + if (!Buffer.isBuffer(bytes)) return null; + try { + return parseGuardJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + return null; + } +} + export function decisionFromGuardResponse(response) { if (!response || typeof response !== 'object' || Array.isArray(response)) { return { allow: false, reason: 'HOL Guard returned an invalid response.' }; @@ -298,7 +310,6 @@ export async function main() { const result = spawnSync('hol-guard', args, { input: `${JSON.stringify(guardPayload)}\n`, - encoding: 'utf8', timeout: GUARD_TIMEOUT_MS, maxBuffer: MAX_STDIN_BYTES, cwd: guardPayload.cwd, @@ -311,7 +322,7 @@ export async function main() { return; } - const response = parseGuardJson(result.stdout); + const response = parseGuardBytes(result.stdout); const decision = decisionFromGuardResponse(response); if (!decision.allow) block(decision.reason); } From 45c62bafccf9bee469034d0e0071676891fcc65a Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:23:04 -0400 Subject: [PATCH 41/44] test: fail closed on undecodable native Guard output --- scripts/hol-guard-before-tool.test.mjs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 80f71d1..3832ae4 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -11,6 +11,7 @@ import { decisionFromGuardResponse, extractKlaatCommand, parseGuardJson, + parseGuardBytes, trustedGuardPath, } from './hol-guard-before-tool.mjs'; @@ -154,6 +155,29 @@ test('rejects repeated authoritative Guard keys, including escaped duplicates', assert.deepEqual(parseGuardJson(valid), JSON.parse(valid)); }); +test('rejects invalid UTF-8 native Guard bytes even when decoding would look like allow', () => { + const allowed = JSON.stringify({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + diagnostic: 'ok', + }); + const valid = Buffer.from(allowed, 'utf8'); + assert.equal(parseGuardBytes(valid)?.policy_action, 'allow'); + + const marker = allowed.lastIndexOf('ok'); + assert.ok(marker > 0); + const invalid = Buffer.concat([ + Buffer.from(allowed.slice(0, marker), 'utf8'), + Buffer.from([0xff]), + Buffer.from(allowed.slice(marker + 2), 'utf8'), + ]); + // Default Node decoding would replace the invalid byte and still parse an allow. + assert.equal(JSON.parse(invalid.toString('utf8')).policy_action, 'allow'); + assert.equal(parseGuardBytes(invalid), null); + assert.equal(parseGuardBytes(allowed), null); +}); + test('explicit stop fields override otherwise authoritative allows', () => { const allowed = { policy_action: 'allow', From 1cd47781f139f4630ca89795d8a029c1a02ab1e4 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:21:23 -0400 Subject: [PATCH 42/44] fix(guard): reject PATH binaries symlinked into projects --- scripts/hol-guard-before-tool.mjs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs index fc9918e..143208c 100644 --- a/scripts/hol-guard-before-tool.mjs +++ b/scripts/hol-guard-before-tool.mjs @@ -31,9 +31,21 @@ export function trustedGuardPath(pathValue, untrustedRoots = []) { return rel !== '' && (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); }); - // The alias itself may be project-controlled even if its target is not. - // Launch from canonical dirs so a symlink swap cannot rebind Guard. - return outsideRoots(entry) && outsideRoots(directory) ? directory : null; + // Reject a project-owned executable hidden behind a globally located + // PATH symlink. Filtering only directory links would still run the shim. + if (!outsideRoots(entry) || !outsideRoots(directory)) return null; + for (const name of ['hol-guard', 'hol-guard.exe']) { + const executable = resolve(directory, name); + try { + const target = realpathSync(executable); + if (!outsideRoots(executable) || !outsideRoots(target)) return null; + } catch (error) { + // A missing executable lets spawn search later PATH entries. + // Other lookup failures cannot establish a trusted executable. + if (error?.code !== 'ENOENT') return null; + } + } + return directory; }) .filter((entry) => entry !== null) .join(delimiter); From 124764779c0f464f20cc07644e04265ec1325fce Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:21:44 -0400 Subject: [PATCH 43/44] test(guard): cover executable symlinks into project trees --- scripts/hol-guard-before-tool.test.mjs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 3832ae4..9d7f6ee 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -282,6 +282,29 @@ test('rejects absolute project PATH entries and symlinks into the project', { } }); +test('rejects executable symlinks that point into a project', { skip: process.platform === 'win32' }, () => { + const temp = mkdtempSync(join(tmpdir(), 'klaat-guard-executable-link-')); + try { + const project = join(temp, 'project'); + const externalBin = join(temp, 'external-bin'); + mkdirSync(project); + mkdirSync(externalBin); + const projectShim = join(project, 'hol-guard'); + writeFileSync(projectShim, '#!/bin/sh\\nexit 0\\n'); + chmodSync(projectShim, 0o755); + // Directory is outside the repo, but its executable points into it. + symlinkSync(projectShim, join(externalBin, 'hol-guard')); + assert.equal(trustedGuardPath(externalBin, [project]), ''); + // An actual executable outside the project remains eligible. + rmSync(join(externalBin, 'hol-guard')); + writeFileSync(join(externalBin, 'hol-guard'), '#!/bin/sh\\nexit 0\\n'); + chmodSync(join(externalBin, 'hol-guard'), 0o755); + assert.equal(trustedGuardPath(externalBin, [project]), realpathSync(externalBin)); + } finally { + rmSync(temp, { recursive: true, force: true }); + } +}); + test('project-local fake hol-guard cannot shadow a trusted PATH executable', { skip: process.platform === 'win32', }, () => { From 168afe09226b186c0c72c7de18324539f0010011 Mon Sep 17 00:00:00 2001 From: Michael Kantor <6068672+kantorcodes@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:23:14 -0400 Subject: [PATCH 44/44] test(guard): use executable POSIX shell fixtures --- scripts/hol-guard-before-tool.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs index 9d7f6ee..4736f57 100644 --- a/scripts/hol-guard-before-tool.test.mjs +++ b/scripts/hol-guard-before-tool.test.mjs @@ -290,14 +290,14 @@ test('rejects executable symlinks that point into a project', { skip: process.pl mkdirSync(project); mkdirSync(externalBin); const projectShim = join(project, 'hol-guard'); - writeFileSync(projectShim, '#!/bin/sh\\nexit 0\\n'); + writeFileSync(projectShim, '#!/bin/sh\nexit 0\n'); chmodSync(projectShim, 0o755); // Directory is outside the repo, but its executable points into it. symlinkSync(projectShim, join(externalBin, 'hol-guard')); assert.equal(trustedGuardPath(externalBin, [project]), ''); // An actual executable outside the project remains eligible. rmSync(join(externalBin, 'hol-guard')); - writeFileSync(join(externalBin, 'hol-guard'), '#!/bin/sh\\nexit 0\\n'); + writeFileSync(join(externalBin, 'hol-guard'), '#!/bin/sh\nexit 0\n'); chmodSync(join(externalBin, 'hol-guard'), 0o755); assert.equal(trustedGuardPath(externalBin, [project]), realpathSync(externalBin)); } finally {