"""The command hook runner over generated hooks.json files (robot-docs/hooks.md). The defects: a group run for a subject its matcher does not match, a later block, halt or argument replacement winning over an earlier one, context or notes lost or reordered, a command that crashes, prints nonsense or outlives its timeout failing closed instead of open with a note, plain output from a prompt hook not taken as context, and a block from a PostToolUse or Stop hook not marked as that hook's input. The runner is its own process with the request on stdin, as the hooks extension starts it, so the test starts it the same way; a daemon adds nothing. """ from dataclasses import dataclass import json from pathlib import Path import re import subprocess import sys import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "test")) import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 RUNNER = ROOT / "python" / "albedo_hook_command.py" EVENTS = ["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop"] @dataclass(frozen=True) class Hook: """A command and what the documented rules make of it.""" kind: str n: int @property def command(self) -> str: return { "pass": "exit 0", "block": f"echo NO{self.n} >&2; exit 2", "crash": f"echo CRASH{self.n} >&2; exit 1", "invalid": "echo '{invalid'", "plain": f"echo PLAIN{self.n}", "context": f"""echo '{{"hookSpecificOutput":{{"additionalContext":"C{self.n}"}}}}'""", "rewrite": f"""echo '{{"hookSpecificOutput":{{"updatedInput":{{"k":{self.n}}}}}}}'""", "deny": f"""echo '{{"hookSpecificOutput":{{"permissionDecision":"deny","permissionDecisionReason":"D{self.n}"}}}}'""", "halt": f"""echo '{{"continue":false,"stopReason":"S{self.n}"}}'""", "message": f"""echo '{{"systemMessage":"M{self.n}"}}'""", "slow": "sleep 5", }[self.kind] @property def timeout(self) -> float: return 0.3 if self.kind == "slow" else 10 def expected(self, event: str) -> dict: """The verdict this one hook gives for `event`.""" def failed(why): return {"notes": [f"{event} hook {self.command!r} failed open: {why}"]} def context(text): return {"context": [f"[{event} hook] {text}"]} prompt = event == "UserPromptSubmit" return { "pass": {}, "block": {"block": f"NO{self.n}"}, "crash": failed(f"exited 1: CRASH{self.n}"), "invalid": context("{invalid") if prompt else failed("invalid hook JSON"), "plain": context(f"PLAIN{self.n}") if prompt else failed("invalid hook JSON"), "context": context(f"C{self.n}"), "rewrite": {"arguments": json.dumps({"k": self.n})}, "deny": {"block": f"D{self.n}"}, "halt": {"halt": f"S{self.n}"}, "message": {"notes": [f"M{self.n}"]}, "slow": failed("timed out after 0.3s"), }[self.kind] MATCHERS = ["", "*", "^python$", "^Bash$", "Bas"] groups = st.lists( st.tuples( st.sampled_from(MATCHERS), st.lists( st.builds( Hook, st.sampled_from( [ "pass", "block", "crash", "invalid", "plain", "context", "rewrite", "deny", "halt", "message", "slow", ] ), st.integers(0, 9), ), min_size=1, max_size=3, ), ), max_size=3, ) def run(config: object, event: str, subject: str, cwd: str) -> dict: with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as file: json.dump(config, file) request = { "event": event, "subject": subject, "config": file.name, "input": {"hook_event_name": event, "cwd": cwd, "session_id": "s"}, } try: process = subprocess.Popen( [sys.executable, str(RUNNER)], cwd=ROOT / "python", stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) assert process.stdin is not None and process.stdout is not None # The runner reads one line, then treats the end of stdin as a cancel. process.stdin.write(json.dumps(request).encode() + b"\n") process.stdin.flush() line = process.stdout.readline() process.stdin.close() process.stdout.close() process.wait(timeout=30) return json.loads(line) finally: Path(file.name).unlink() class HookCommandTests(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(40)) @given(groups, st.sampled_from(EVENTS), st.sampled_from(["python", "Bash"])) def test_matching_hooks_merge_in_order_and_fail_open(self, groups, event, subject): config = { "hooks": { event: [ { "matcher": matcher, "hooks": [ { "type": "command", "command": hook.command, "timeout": hook.timeout, } for hook in hooks ], } for matcher, hooks in groups ] } } expected = { "block": None, "halt": None, "arguments": None, "context": [], "notes": [], } for matcher, hooks in groups: if matcher not in ("", "*") and not re.search(matcher, subject): continue for hook in hooks: for key, value in hook.expected(event).items(): if isinstance(value, list): expected[key] += value elif expected[key] is None: expected[key] = value if expected["block"] is not None and event in ("PostToolUse", "Stop"): expected["block"] = f"[{event} hook] {expected['block']}" with tempfile.TemporaryDirectory() as cwd: self.assertEqual(run(config, event, subject, cwd), expected) def test_a_config_without_hooks_fails_open(self): with tempfile.TemporaryDirectory() as cwd: verdict = run([], "Stop", "", cwd) self.assertIsNone(verdict["block"]) self.assertEqual(len(verdict["notes"]), 1) self.assertIn("failed open", verdict["notes"][0]) if __name__ == "__main__": unittest.main()