From 451bb4a38fc50086e1cd6cbc13a09421374517cd Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 15:12:14 +0000 Subject: [PATCH 1/4] fix(events): return 1 on handler timeout and pass SPECKIT_EVENT to handlers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A handler that runs past its timeout exited 2, which agents read from a Stop hook as "don't stop, keep going" — one slow script could keep the agent running when it should stop. Runner failures (timeout or error) now exit 1; a handler's own exit code still passes through unchanged. Handlers also had no way to tell which event fired. Both runners now export the canonical event name as SPECKIT_EVENT. Fixes #5336 --- src/specify_cli/events/__init__.py | 23 +++- tests/specify_cli/events/test_events.py | 175 ++++++++++++++++++++++++ 2 files changed, 192 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 47f86a5cb7..5c6d4d991f 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -289,7 +289,7 @@ def _resolve_argv(template_path, project_root, ext_id): return [str(script_abs), *rest] -def _run_inline(command_name, payload, project_root, timeout, envelope="plain", native_event=""): +def _run_inline(command_name, payload, project_root, timeout, envelope="plain", native_event="", event_name=""): """Resolve and run the event command with stdlib only (no specify_cli).""" template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: @@ -297,6 +297,8 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", argv = _resolve_argv(template_path, project_root, ext_id) if not argv: return 0 + # Tell the handler which event fired (mirrors the full resolver below). + env = {**os.environ, "SPECKIT_EVENT": event_name} if event_name else None try: # ``payload`` is decoded above from the binary buffer with an explicit # ``utf-8``. Without ``encoding=`` here, ``text=True`` re-encodes it @@ -312,6 +314,7 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", encoding="utf-8", timeout=timeout, cwd=str(project_root), + env=env, ) if result.stdout: _emit(result.stdout, envelope, native_event) @@ -322,10 +325,12 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", return 0 except subprocess.TimeoutExpired: print(f"Event {command_name} timed out", file=sys.stderr) - return 2 + # Exit 1, not 2: a runner failure is not the handler's decision, and + # agents read exit 2 from a Stop hook as "don't stop, keep going". + return 1 except Exception as e: print(f"Event {command_name} error: {e}", file=sys.stderr) - return 2 + return 1 def _emit(output, envelope, native_event=""): @@ -438,7 +443,7 @@ def main(): pass # Fallback: self-contained stdlib resolver (one-time/temporary installs). - sys.exit(_run_inline(command_name, payload, project_root, timeout, envelope, native_event)) + sys.exit(_run_inline(command_name, payload, project_root, timeout, envelope, native_event, _event_name)) if __name__ == "__main__": @@ -797,6 +802,9 @@ def resolve_and_run_event_command( if not argv: logger.warning("No script found for event command '%s'", command_name) return 0 + # Tell the handler which event fired so one script can serve several + # events (mirrors the inline fallback in the generated dispatcher). + env = {**os.environ, "SPECKIT_EVENT": event_name} if event_name else None try: # ``payload`` reaches here already decoded from stdin's binary buffer # with an explicit ``utf-8`` (see event_run/dispatcher main()). Without @@ -813,6 +821,7 @@ def resolve_and_run_event_command( encoding="utf-8", timeout=timeout, cwd=str(project_root), + env=env, ) if result.stdout: _emit_event_stdout(result.stdout, envelope, native_event) @@ -823,10 +832,12 @@ def resolve_and_run_event_command( return 0 except subprocess.TimeoutExpired: sys.stderr.write(f"Event command {command_name} timed out\n") - return 2 + # Exit 1, not 2: a runner failure is not the handler's decision, and + # agents read exit 2 from a Stop hook as "don't stop, keep going". + return 1 except Exception as e: sys.stderr.write(f"Event command {command_name} error: {e}\n") - return 2 + return 1 def _emit_event_stdout(output: str, envelope: str, native_event: str = "") -> None: diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index 9c2d07aa6b..feb013226a 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -1614,6 +1614,96 @@ def test_run_command_resolves_and_executes(self, tmp_path): code = resolve_and_run_event_command("speckit.test", "session_start", "{}", tmp_path) assert code == 0 + def _write_sleep_command(self, tmp_path, seconds): + """Create a core command whose script sleeps, then return its name.""" + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + (cmd_dir / "slow.md").write_text( + "---\n" + "description: \"Slow\"\n" + "scripts:\n" + " sh: scripts/slow.sh\n" + "---\n" + "Body\n", + encoding="utf-8", + ) + script_dir = tmp_path / ".specify" / "scripts" + script_dir.mkdir(parents=True) + script_file = script_dir / "slow.sh" + script_file.write_text(f"#!/bin/sh\nsleep {seconds}\nexit 0\n", encoding="utf-8") + script_file.chmod(0o755) + + def test_timeout_returns_1_not_blocking_2(self, tmp_path, capsys): + """A handler that runs past its timeout must not exit 2: Claude Code + reads exit 2 from a Stop hook as "don't stop, keep going", so a slow + script would keep the agent running when it should stop.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_sleep_command(tmp_path, 5) + code = resolve_and_run_event_command( + "speckit.slow", "stop", "{}", tmp_path, timeout=1 + ) + assert code == 1 + assert "timed out" in capsys.readouterr().err + + def test_handler_own_exit_2_still_passes_through(self, tmp_path): + """A handler that deliberately exits 2 keeps that exit code: only a + runner failure (timeout/error) is downgraded to 1, never the + handler's own decision.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + (cmd_dir / "block.md").write_text( + "---\n" + "description: \"Block\"\n" + "scripts:\n" + " sh: scripts/block.sh\n" + "---\n" + "Body\n", + encoding="utf-8", + ) + script_dir = tmp_path / ".specify" / "scripts" + script_dir.mkdir(parents=True) + script_file = script_dir / "block.sh" + script_file.write_text("#!/bin/sh\nexit 2\n", encoding="utf-8") + script_file.chmod(0o755) + + code = resolve_and_run_event_command("speckit.block", "stop", "{}", tmp_path) + assert code == 2 + + def test_event_name_passed_as_speckit_event_env(self, tmp_path): + """The handler sees which event fired via the SPECKIT_EVENT env var.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + (cmd_dir / "which.md").write_text( + "---\n" + "description: \"Which\"\n" + "scripts:\n" + " sh: scripts/which.sh\n" + "---\n" + "Body\n", + encoding="utf-8", + ) + script_dir = tmp_path / ".specify" / "scripts" + script_dir.mkdir(parents=True) + out_file = tmp_path / "event.out" + script_file = script_dir / "which.sh" + script_file.write_text( + f"#!/bin/sh\necho \"$SPECKIT_EVENT\" > {shlex.quote(str(out_file))}\nexit 0\n", + encoding="utf-8", + ) + script_file.chmod(0o755) + + code = resolve_and_run_event_command("speckit.which", "stop", "{}", tmp_path) + assert code == 0 + assert out_file.read_text().strip() == "stop" + def test_py_variant_anchored_under_specify(self, tmp_path): """S2: the py variant resolves scripts/... under .specify/, not the project root, and prepends the resolved interpreter.""" @@ -1897,6 +1987,91 @@ def test_dispatcher_inline_fallback_runs_script(self, tmp_path): assert out_file.exists(), f"inline fallback did not run script; stderr={result.stderr!r} rc={result.returncode}" assert out_file.read_text() == '{"tool_name":"x"}' + def _install_boot_dispatcher(self, tmp_path, script_text, event="session_start"): + """Install a dispatcher for speckit.boot and write its script. + + Returns (dispatcher_path, out_file) — the script writes its output to + out_file when run. Mirrors test_dispatcher_inline_fallback_runs_script. + """ + integration = ClaudeIntegration() + manifest = MagicMock(spec=IntegrationManifest) + manifest.files = {} + manifest.record_file = MagicMock() + manifest.record_existing = MagicMock() + install_integration_events( + integration, tmp_path, manifest, + {event: [{"command": "speckit.boot"}]}, + ) + dispatcher = tmp_path / EVENTS_DISPATCHER_REL + assert dispatcher.is_file() + + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + out_file = tmp_path / "boot.out" + (cmd_dir / "boot.md").write_text( + "---\ndescription: \"Boot\"\nscripts:\n sh: scripts/boot.sh\n---\nBody\n", + encoding="utf-8", + ) + script_dir = tmp_path / ".specify" / "scripts" + script_dir.mkdir(parents=True) + script = script_dir / "boot.sh" + script.write_text(script_text, encoding="utf-8") + script.chmod(0o755) + return dispatcher, out_file + + def _run_dispatcher_inline(self, tmp_path, dispatcher, command, event, timeout): + """Run the generated dispatcher with specify_cli shadowed so the + inline stdlib fallback handles the event. Returns the CompletedProcess.""" + import subprocess as _sp + import sys as _sys + + fake_dir = tmp_path / "_fake" + (fake_dir / "specify_cli").mkdir(parents=True, exist_ok=True) + (fake_dir / "specify_cli" / "__init__.py").write_text("", encoding="utf-8") + env = dict(os.environ) + env["PYTHONPATH"] = str(fake_dir) + return _sp.run( + [_sys.executable, str(dispatcher), command, event, str(timeout)], + input="{}", + capture_output=True, + text=True, + env=env, + cwd=str(tmp_path), + check=False, + ) + + def test_dispatcher_inline_fallback_timeout_returns_1(self, tmp_path): + """The inline fallback must not exit 2 on timeout either: the same + Stop-hook "don't stop" misread applies when specify_cli is absent.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/bin/sh\nsleep 5\nexit 0\n" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "session_start", 1 + ) + assert result.returncode == 1, f"stderr={result.stderr!r}" + assert "timed out" in result.stderr + + def test_dispatcher_inline_fallback_passes_speckit_event(self, tmp_path): + """The inline fallback passes the fired event to the handler via + SPECKIT_EVENT, same as the full resolver.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, out_file = self._install_boot_dispatcher( + tmp_path, + f"#!/bin/sh\necho \"$SPECKIT_EVENT\" > {shlex.quote(str(tmp_path / 'boot.out'))}\nexit 0\n", + event="stop", + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "stop", 60 + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert out_file.read_text().strip() == "stop" + def test_dispatcher_ignores_stale_specify_cli_without_confinement(self, tmp_path): """A generated dispatcher must not delegate to an older specify_cli that lacks EVENT_SCRIPT_PATH_CONFINEMENT (uvx-init plus stale From 3028c707fa3f7c2aaf9e9a0421b983906015c9f9 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 17:21:44 +0000 Subject: [PATCH 2/4] fix(events): keep pre_tool_use runner failures blocking, require runner contract for delegation Runner failures (timeout, handler failing to start) now exit 2 for pre_tool_use so the guard stays blocking, and 1 for every other event. The generated dispatcher requires the new EVENT_RUNNER_CONTRACT marker before delegating to an installed specify_cli, so a stale install with path confinement alone cannot bypass the #5336 runner contract. Regression tests cover per-event timeout and startup-failure codes in both the resolver and the inline fallback, plus a stale package with confinement but no contract marker. --- src/specify_cli/events/__init__.py | 69 ++++++++++-- tests/specify_cli/events/test_events.py | 144 ++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 9 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 5c6d4d991f..79d14c7d81 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -53,6 +53,13 @@ # install) would otherwise run unconfined script tokens. EVENT_SCRIPT_PATH_CONFINEMENT = True +# Generated hook dispatchers refuse to delegate unless this name is True. +# A stale global install that predates the #5336 runner contract (per-event +# runner-failure exit codes, SPECKIT_EVENT propagation) still exposes +# EVENT_SCRIPT_PATH_CONFINEMENT, so confinement alone cannot prove the +# resolver honors the new contract. +EVENT_RUNNER_CONTRACT = True + EVENTS_DISPATCHER_DIR = Path(".specify") EVENTS_DISPATCHER_FILENAME = "events.py" # POSIX-form (forward-slash) relative path so it matches manifest keys, which @@ -84,6 +91,20 @@ "stop", }) +# Events whose handlers act as guards: when a handler cannot run (timeout or +# startup error), the runner failure must keep blocking the agent action. +# Claude Code reads exit 2 from a PreToolUse hook as "block the tool call", +# so a pre_tool_use validation that never ran must still block. Every other +# event fails open with exit 1 so a slow handler cannot keep the agent +# running (#5336). Mirrored inside the generated dispatcher template +# (_runner_failure_exit_code); keep both in sync. +BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use"}) + + +def _runner_failure_exit_code(event_name: str) -> int: + """Exit code for a runner failure (timeout/startup error) for *event_name*.""" + return 2 if event_name in BLOCKING_FAILURE_EVENTS else 1 + # -- Events Dispatcher template --------------------------------------------- _EVENTS_DISPATCHER_TEMPLATE = '''#!/usr/bin/env python3 @@ -289,6 +310,18 @@ def _resolve_argv(template_path, project_root, ext_id): return [str(script_abs), *rest] +# Guard events (pre_tool_use) fail closed: a runner failure (timeout or +# handler failing to start) must keep blocking the action (exit 2). Every +# other event fails open with exit 1. Mirrors BLOCKING_FAILURE_EVENTS / +# _runner_failure_exit_code in the full resolver; keep both in sync. +_BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use"}) + + +def _runner_failure_exit_code(event_name): + """Exit code for a runner failure (timeout/startup error) for *event_name*.""" + return 2 if event_name in _BLOCKING_FAILURE_EVENTS else 1 + + def _run_inline(command_name, payload, project_root, timeout, envelope="plain", native_event="", event_name=""): """Resolve and run the event command with stdlib only (no specify_cli).""" template_path, ext_id = _find_command_template(command_name, project_root) @@ -325,12 +358,16 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", return 0 except subprocess.TimeoutExpired: print(f"Event {command_name} timed out", file=sys.stderr) - # Exit 1, not 2: a runner failure is not the handler's decision, and - # agents read exit 2 from a Stop hook as "don't stop, keep going". - return 1 + # A runner failure is not the handler's decision. For guard events + # (pre_tool_use) the failure must keep blocking (exit 2); for other + # events exit 1, since agents read exit 2 from a Stop hook as + # "don't stop, keep going". + return _runner_failure_exit_code(event_name) except Exception as e: print(f"Event {command_name} error: {e}", file=sys.stderr) - return 1 + # The handler never ran, so its failure cannot be treated as a + # decision: guard events keep blocking (exit 2), others fail open. + return _runner_failure_exit_code(event_name) def _emit(output, envelope, native_event=""): @@ -426,14 +463,19 @@ def main(): # the full resolver, which also handles extension manifests whose file stem # differs from the command name and the project's custom script selection. # Require EVENT_SCRIPT_PATH_CONFINEMENT so a stale global install cannot - # bypass the generated dispatcher's path guard. + # bypass the generated dispatcher's path guard, and EVENT_RUNNER_CONTRACT + # so a stale install that predates the #5336 runner contract (per-event + # runner-failure exit codes, SPECKIT_EVENT) cannot bypass those fixes. try: from specify_cli.events import ( + EVENT_RUNNER_CONTRACT as _contract_ok, EVENT_SCRIPT_PATH_CONFINEMENT as _confine_ok, resolve_and_run_event_command, ) if _confine_ok is not True: raise ImportError("specify_cli.events lacks script path confinement") + if _contract_ok is not True: + raise ImportError("specify_cli.events lacks the event runner contract") sys.exit( resolve_and_run_event_command( command_name, _event_name, payload, project_root, timeout=timeout, envelope=envelope, native_event=native_event @@ -793,6 +835,11 @@ def resolve_and_run_event_command( required inside ``hookSpecificOutput`` by Qwen's hooks spec (and included by the Claude Code hooks spec Gemini/Tabnine/Devin derive from). Only used when *envelope* is ``hookSpecificOutput``. + + A runner failure (timeout, or the handler failing to start) exits 2 for + guard events (``pre_tool_use``) so the action stays blocked, and 1 for + every other event so a slow handler cannot keep the agent running. A + handler's own non-zero exit code always passes through unchanged. """ template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: @@ -832,12 +879,16 @@ def resolve_and_run_event_command( return 0 except subprocess.TimeoutExpired: sys.stderr.write(f"Event command {command_name} timed out\n") - # Exit 1, not 2: a runner failure is not the handler's decision, and - # agents read exit 2 from a Stop hook as "don't stop, keep going". - return 1 + # A runner failure is not the handler's decision. For guard events + # (pre_tool_use) the failure must keep blocking (exit 2); for other + # events exit 1, since agents read exit 2 from a Stop hook as + # "don't stop, keep going". + return _runner_failure_exit_code(event_name) except Exception as e: sys.stderr.write(f"Event command {command_name} error: {e}\n") - return 1 + # The handler never ran, so its failure cannot be treated as a + # decision: guard events keep blocking (exit 2), others fail open. + return _runner_failure_exit_code(event_name) def _emit_event_stdout(output: str, envelope: str, native_event: str = "") -> None: diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index feb013226a..dbf0ab0d04 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -1633,6 +1633,27 @@ def _write_sleep_command(self, tmp_path, seconds): script_file.write_text(f"#!/bin/sh\nsleep {seconds}\nexit 0\n", encoding="utf-8") script_file.chmod(0o755) + def _write_broken_command(self, tmp_path): + """Create a core command whose script cannot start: the file exists + (so argv resolves) but its shebang names a missing interpreter, so + exec fails with a genuine subprocess startup error.""" + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + (cmd_dir / "broken.md").write_text( + "---\n" + "description: \"Broken\"\n" + "scripts:\n" + " sh: scripts/broken.sh\n" + "---\n" + "Body\n", + encoding="utf-8", + ) + script_dir = tmp_path / ".specify" / "scripts" + script_dir.mkdir(parents=True) + script_file = script_dir / "broken.sh" + script_file.write_text("#!/does/not/exist\nexit 0\n", encoding="utf-8") + script_file.chmod(0o755) + def test_timeout_returns_1_not_blocking_2(self, tmp_path, capsys): """A handler that runs past its timeout must not exit 2: Claude Code reads exit 2 from a Stop hook as "don't stop, keep going", so a slow @@ -1647,6 +1668,49 @@ def test_timeout_returns_1_not_blocking_2(self, tmp_path, capsys): assert code == 1 assert "timed out" in capsys.readouterr().err + def test_pre_tool_use_timeout_returns_2_blocking(self, tmp_path, capsys): + """A pre_tool_use handler that runs past its timeout must still exit + 2: Claude Code reads exit 2 from a PreToolUse hook as "block the tool + call", so a guard that never ran must keep the call blocked instead + of failing open like a Stop hook.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_sleep_command(tmp_path, 5) + code = resolve_and_run_event_command( + "speckit.slow", "pre_tool_use", "{}", tmp_path, timeout=1 + ) + assert code == 2 + assert "timed out" in capsys.readouterr().err + + def test_pre_tool_use_startup_failure_returns_2_blocking(self, tmp_path, capsys): + """A pre_tool_use handler that cannot start must still exit 2: the + guard did not validate the tool call, so the call stays blocked.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_broken_command(tmp_path) + code = resolve_and_run_event_command( + "speckit.broken", "pre_tool_use", "{}", tmp_path + ) + assert code == 2 + assert "error:" in capsys.readouterr().err + + def test_startup_failure_returns_1_for_stop(self, tmp_path, capsys): + """A Stop handler that cannot start exits 1 with an error diagnostic: + the runner failure must not read as "don't stop, keep going", and the + generic error branch needs its own coverage so it cannot silently + revert to exit 2.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_broken_command(tmp_path) + code = resolve_and_run_event_command( + "speckit.broken", "stop", "{}", tmp_path + ) + assert code == 1 + assert "error:" in capsys.readouterr().err + def test_handler_own_exit_2_still_passes_through(self, tmp_path): """A handler that deliberately exits 2 keeps that exit code: only a runner failure (timeout/error) is downgraded to 1, never the @@ -1921,6 +1985,9 @@ def test_dispatcher_is_self_contained(self, tmp_path): content = (tmp_path / EVENTS_DISPATCHER_REL).read_text() # Delegates to specify_cli when importable and confinement is present. assert "EVENT_SCRIPT_PATH_CONFINEMENT" in content + # Delegation also requires the #5336 runner contract, so a stale + # install with confinement alone cannot bypass the new runner. + assert "EVENT_RUNNER_CONTRACT" in content assert "from specify_cli.events import" in content assert "resolve_and_run_event_command" in content assert "except (ImportError, TypeError):" in content @@ -2055,6 +2122,83 @@ def test_dispatcher_inline_fallback_timeout_returns_1(self, tmp_path): assert result.returncode == 1, f"stderr={result.stderr!r}" assert "timed out" in result.stderr + def test_dispatcher_inline_fallback_pre_tool_use_timeout_returns_2(self, tmp_path): + """The inline fallback must exit 2 on a pre_tool_use timeout: the + guard never ran, so the tool call stays blocked — same rule as the + full resolver.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/bin/sh\nsleep 5\nexit 0\n", event="pre_tool_use" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "pre_tool_use", 1 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "timed out" in result.stderr + + def test_dispatcher_inline_fallback_startup_failure_returns_1(self, tmp_path): + """The inline fallback must exit 1 with an error diagnostic when a + Stop handler cannot start: the generic error branch needs its own + coverage in the fallback too, so it cannot silently revert to 2.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/does/not/exist\nexit 0\n", event="stop" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "stop", 60 + ) + assert result.returncode == 1, f"stderr={result.stderr!r}" + assert "error:" in result.stderr + + def test_dispatcher_ignores_stale_specify_cli_without_runner_contract(self, tmp_path): + """A generated dispatcher must not delegate to an older specify_cli + that has EVENT_SCRIPT_PATH_CONFINEMENT but predates the #5336 runner + contract (per-event failure exit codes, SPECKIT_EVENT): after a + one-time uvx upgrade, that resolver would still return 2 on timeout + and omit SPECKIT_EVENT. The dispatcher must fall back to its inline + resolver instead.""" + import subprocess as _sp + import sys as _sys + + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, out_file = self._install_boot_dispatcher( + tmp_path, "#!/bin/sh\necho ran > " + shlex.quote(str(tmp_path / "boot.out")) + "\nexit 0\n" + ) + ran = tmp_path / "delegated" + fake_dir = tmp_path / "_stale_pkg" + pkg = fake_dir / "specify_cli" + pkg.mkdir(parents=True) + (pkg / "__init__.py").write_text("", encoding="utf-8") + (pkg / "events.py").write_text( + "EVENT_SCRIPT_PATH_CONFINEMENT = True\n" + "def resolve_and_run_event_command(*_a, **_k):\n" + f" open({str(ran)!r}, 'w').write('delegated')\n" + " return 0\n", + encoding="utf-8", + ) + env = dict(os.environ) + env["PYTHONPATH"] = str(fake_dir) + result = _sp.run( + [_sys.executable, str(dispatcher), "speckit.boot", "session_start", "60"], + input="{}", + capture_output=True, + text=True, + check=False, + env=env, + cwd=str(tmp_path), + ) + assert not ran.exists(), f"stale package ran; stderr={result.stderr!r}" + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert out_file.read_text().strip() == "ran", ( + "inline fallback did not run the script after refusing delegation" + ) + def test_dispatcher_inline_fallback_passes_speckit_event(self, tmp_path): """The inline fallback passes the fired event to the handler via SPECKIT_EVENT, same as the full resolver.""" From c1cbba7ff1ee2b50f8769fadb84da34cf30fdb56 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Tue, 10 Nov 2026 04:49:25 +0000 Subject: [PATCH 3/4] fix(events): keep user_prompt_submit failures blocking, fail closed on unresolved guards Add user_prompt_submit to BLOCKING_FAILURE_EVENTS in both runners: Claude Code reads exit 2 from a UserPromptSubmit hook as "block the prompt, so it never reaches Claude" (Claude Code Hooks reference, "Exit code 2 behavior per event"), so a prompt whose validation never ran must not reach the model. Fix the inline manifest scan: strip trailing '#' comments outside quotes from name:/file: values, and reset the name/file pair on each new list item, so a name can never pair with the next entry's file. Fail closed in the inline fallback: a guard command that cannot be resolved, or resolves to a template with no runnable script, exits 2 with a stderr diagnostic; non-guard events still no-op with 0. Rename the handler env var SPECKIT_EVENT to SPECKIT_EVENT_NAME, establishing SPECKIT_EVENT_* as the namespace for future values. Document the handler contract in docs/integrations/cli.md (stdin JSON payload, UTF-8, 1 MiB cap; SPECKIT_EVENT_NAME; runner-failure exit codes; handler exit codes pass through). Regression tests cover per-event timeout and startup-failure codes for user_prompt_submit in both runners, manifest trailing-comment and cross-pairing resolution, and the fail-closed backstop, each shown red before the fix. --- docs/integrations/cli.md | 30 +++ src/specify_cli/events/__init__.py | 123 +++++++++--- tests/specify_cli/events/test_events.py | 245 +++++++++++++++++++++++- 3 files changed, 367 insertions(+), 31 deletions(-) diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index d67252af5d..6d3837020f 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -464,6 +464,36 @@ Spec Kit hooks rather than merely stopping new hook generation. Agent-specific guides identify native event configuration paths and limitations. These runtime events are distinct from extension command hooks. +### Handler contract + +A handler is a script-backed Spec Kit command. When its event fires, the +runner passes the event JSON payload on stdin (UTF-8, capped at 1 MiB; a +larger payload is rejected with exit 1) and exports the canonical event +name as `SPECKIT_EVENT_NAME` (snake_case: `session_start`, +`pre_tool_use`, `post_tool_use`, `session_end`, `user_prompt_submit`, or +`stop`). `SPECKIT_EVENT_*` is the namespace for future event-related +values, so handlers should read `SPECKIT_EVENT_NAME` and not rely on any +other `SPECKIT_EVENT_*` name yet. + +Exit codes decide what happens next: + +- A handler's own exit code always passes through unchanged. A handler + that deliberately exits 2 still blocks, exactly as the agent reads it. +- A runner failure — the handler timing out, or failing to start — exits + 2 for guard events (`pre_tool_use`, `user_prompt_submit`) and 1 for + every other event. Claude Code reads exit 2 from a `PreToolUse` hook as + "block the tool call" and from a `UserPromptSubmit` hook as "block the + prompt, so it never reaches Claude" (Claude Code Hooks reference, + "Exit code 2 behavior per event"); exit 2 from a `Stop` hook would read + as "don't stop, keep going", so a slow Stop handler must never exit 2. +- A guard handler that cannot be resolved at all — missing command file, + unparsable manifest, disabled extension, or no runnable script — fails + closed: the runner exits 2 with a diagnostic on stderr instead of + letting the action through without validation. Non-guard events still + no-op with exit 0 when no handler resolves. This is deliberate: a + misconfigured guard blocks the action until it is fixed, rather than + silently skipping the validation it was configured to run. + ## Workflow CLI Dispatch The agent guides distinguish IDE setup from workflow CLI support. Some IDE diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 79d14c7d81..ab7fd5ec40 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -55,7 +55,7 @@ # Generated hook dispatchers refuse to delegate unless this name is True. # A stale global install that predates the #5336 runner contract (per-event -# runner-failure exit codes, SPECKIT_EVENT propagation) still exposes +# runner-failure exit codes, SPECKIT_EVENT_NAME propagation) still exposes # EVENT_SCRIPT_PATH_CONFINEMENT, so confinement alone cannot prove the # resolver honors the new contract. EVENT_RUNNER_CONTRACT = True @@ -93,12 +93,15 @@ # Events whose handlers act as guards: when a handler cannot run (timeout or # startup error), the runner failure must keep blocking the agent action. -# Claude Code reads exit 2 from a PreToolUse hook as "block the tool call", -# so a pre_tool_use validation that never ran must still block. Every other +# Claude Code reads exit 2 from a PreToolUse hook as "block the tool call" +# and from a UserPromptSubmit hook as "block the prompt, so it never reaches +# Claude" (Claude Code Hooks reference, "Exit code 2 behavior per event": +# https://code.claude.com/docs/en/hooks.md), so a pre_tool_use or +# user_prompt_submit validation that never ran must still block. Every other # event fails open with exit 1 so a slow handler cannot keep the agent # running (#5336). Mirrored inside the generated dispatcher template # (_runner_failure_exit_code); keep both in sync. -BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use"}) +BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use", "user_prompt_submit"}) def _runner_failure_exit_code(event_name: str) -> int: @@ -145,6 +148,44 @@ def _script_under_base(base, token, project_root): return candidate +def _strip_yaml_comment(value): + """Strip a trailing ``#`` comment outside quotes from a YAML scalar. + + A ``#`` only starts a comment when preceded by whitespace (or at the + start of the value); ``#`` inside single or double quotes is part of + the value. Quoted escapes are honored so a quoted ``#`` never ends the + value early. + """ + in_single = False + in_double = False + i = 0 + while i < len(value): + ch = value[i] + if in_single: + if ch == "'": + if i + 1 < len(value) and value[i + 1] == "'": + i += 2 + continue + in_single = False + elif in_double: + # chr(92) is a backslash: a literal "\\" here would collapse to + # a lone backslash in the generated dispatcher and break its + # string literal, since this helper lives inside the template. + if ch == chr(92): + i += 2 + continue + if ch == '"': + in_double = False + elif ch == "'": + in_single = True + elif ch == '"': + in_double = True + elif ch == "#" and (i == 0 or value[i - 1] in (" ", "\t")): + return value[:i].rstrip() + i += 1 + return value + + def _find_command_template(command_name, project_root): """Locate the command's .md template. Returns (path, ext_id|None).""" exts_dir = project_root / ".specify" / "extensions" @@ -187,10 +228,21 @@ def _find_command_template(command_name, project_root): in_commands = False continue if in_commands: + # A new list item starts a new command entry: + # drop any half-filled pair from the previous + # entry so a name can never pair with the next + # entry's file. + if stripped.startswith("- ") or stripped == "-": + cur_name = None + cur_file = None if "name:" in line: - cur_name = line.split("name:", 1)[1].strip().strip('"').strip("'") + cur_name = _strip_yaml_comment( + line.split("name:", 1)[1].strip() + ).strip('"').strip("'") if "file:" in line: - cur_file = line.split("file:", 1)[1].strip().strip('"').strip("'") + cur_file = _strip_yaml_comment( + line.split("file:", 1)[1].strip() + ).strip('"').strip("'") if cur_name and cur_file: if cur_name == command_name: candidate = ext_dir / cur_file @@ -310,11 +362,15 @@ def _resolve_argv(template_path, project_root, ext_id): return [str(script_abs), *rest] -# Guard events (pre_tool_use) fail closed: a runner failure (timeout or -# handler failing to start) must keep blocking the action (exit 2). Every -# other event fails open with exit 1. Mirrors BLOCKING_FAILURE_EVENTS / -# _runner_failure_exit_code in the full resolver; keep both in sync. -_BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use"}) +# Guard events (pre_tool_use, user_prompt_submit) fail closed: a runner +# failure (timeout or handler failing to start) must keep blocking the +# action (exit 2). Claude Code reads exit 2 from a PreToolUse hook as +# "block the tool call" and from a UserPromptSubmit hook as "block the +# prompt, so it never reaches Claude" (Claude Code Hooks reference, +# "Exit code 2 behavior per event"). Every other event fails open with +# exit 1. Mirrors BLOCKING_FAILURE_EVENTS / _runner_failure_exit_code in +# the full resolver; keep both in sync. +_BLOCKING_FAILURE_EVENTS = frozenset({"pre_tool_use", "user_prompt_submit"}) def _runner_failure_exit_code(event_name): @@ -326,12 +382,32 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", """Resolve and run the event command with stdlib only (no specify_cli).""" template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: + # The guard never ran: a configured guard command that cannot be + # resolved (missing file, unparsable manifest, disabled extension) + # must fail closed for guard events instead of silently letting + # the action through. Non-guard events still no-op with 0. + if event_name in _BLOCKING_FAILURE_EVENTS: + print( + f"Event {command_name} could not be resolved; blocking event " + f"{event_name} fails closed without validation", + file=sys.stderr, + ) + return _runner_failure_exit_code(event_name) return 0 # command not found: fail open (no-op) for lifecycle events argv = _resolve_argv(template_path, project_root, ext_id) if not argv: + # Same fail-closed rule: the template resolved but declares no + # runnable script, so the guard never ran. + if event_name in _BLOCKING_FAILURE_EVENTS: + print( + f"Event {command_name} has no runnable script; blocking event " + f"{event_name} fails closed without validation", + file=sys.stderr, + ) + return _runner_failure_exit_code(event_name) return 0 # Tell the handler which event fired (mirrors the full resolver below). - env = {**os.environ, "SPECKIT_EVENT": event_name} if event_name else None + env = {**os.environ, "SPECKIT_EVENT_NAME": event_name} if event_name else None try: # ``payload`` is decoded above from the binary buffer with an explicit # ``utf-8``. Without ``encoding=`` here, ``text=True`` re-encodes it @@ -359,9 +435,9 @@ def _run_inline(command_name, payload, project_root, timeout, envelope="plain", except subprocess.TimeoutExpired: print(f"Event {command_name} timed out", file=sys.stderr) # A runner failure is not the handler's decision. For guard events - # (pre_tool_use) the failure must keep blocking (exit 2); for other - # events exit 1, since agents read exit 2 from a Stop hook as - # "don't stop, keep going". + # (pre_tool_use, user_prompt_submit) the failure must keep blocking + # (exit 2); for other events exit 1, since agents read exit 2 from + # a Stop hook as "don't stop, keep going". return _runner_failure_exit_code(event_name) except Exception as e: print(f"Event {command_name} error: {e}", file=sys.stderr) @@ -465,7 +541,7 @@ def main(): # Require EVENT_SCRIPT_PATH_CONFINEMENT so a stale global install cannot # bypass the generated dispatcher's path guard, and EVENT_RUNNER_CONTRACT # so a stale install that predates the #5336 runner contract (per-event - # runner-failure exit codes, SPECKIT_EVENT) cannot bypass those fixes. + # runner-failure exit codes, SPECKIT_EVENT_NAME) cannot bypass those fixes. try: from specify_cli.events import ( EVENT_RUNNER_CONTRACT as _contract_ok, @@ -837,9 +913,10 @@ def resolve_and_run_event_command( used when *envelope* is ``hookSpecificOutput``. A runner failure (timeout, or the handler failing to start) exits 2 for - guard events (``pre_tool_use``) so the action stays blocked, and 1 for - every other event so a slow handler cannot keep the agent running. A - handler's own non-zero exit code always passes through unchanged. + guard events (``pre_tool_use``, ``user_prompt_submit``) so the action + stays blocked, and 1 for every other event so a slow handler cannot + keep the agent running. A handler's own non-zero exit code always + passes through unchanged. """ template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: @@ -851,7 +928,7 @@ def resolve_and_run_event_command( return 0 # Tell the handler which event fired so one script can serve several # events (mirrors the inline fallback in the generated dispatcher). - env = {**os.environ, "SPECKIT_EVENT": event_name} if event_name else None + env = {**os.environ, "SPECKIT_EVENT_NAME": event_name} if event_name else None try: # ``payload`` reaches here already decoded from stdin's binary buffer # with an explicit ``utf-8`` (see event_run/dispatcher main()). Without @@ -880,9 +957,9 @@ def resolve_and_run_event_command( except subprocess.TimeoutExpired: sys.stderr.write(f"Event command {command_name} timed out\n") # A runner failure is not the handler's decision. For guard events - # (pre_tool_use) the failure must keep blocking (exit 2); for other - # events exit 1, since agents read exit 2 from a Stop hook as - # "don't stop, keep going". + # (pre_tool_use, user_prompt_submit) the failure must keep blocking + # (exit 2); for other events exit 1, since agents read exit 2 from + # a Stop hook as "don't stop, keep going". return _runner_failure_exit_code(event_name) except Exception as e: sys.stderr.write(f"Event command {command_name} error: {e}\n") diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index dbf0ab0d04..c9bc97734b 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -1696,6 +1696,36 @@ def test_pre_tool_use_startup_failure_returns_2_blocking(self, tmp_path, capsys) assert code == 2 assert "error:" in capsys.readouterr().err + def test_user_prompt_submit_timeout_returns_2_blocking(self, tmp_path, capsys): + """A user_prompt_submit handler that runs past its timeout must still + exit 2: Claude Code reads exit 2 from a UserPromptSubmit hook as + "block the prompt", so a prompt whose validation never ran must not + reach the model (Claude Code Hooks reference, "Exit code 2 behavior + per event": UserPromptSubmit blocks the prompt, so it never reaches + Claude).""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_sleep_command(tmp_path, 5) + code = resolve_and_run_event_command( + "speckit.slow", "user_prompt_submit", "{}", tmp_path, timeout=1 + ) + assert code == 2 + assert "timed out" in capsys.readouterr().err + + def test_user_prompt_submit_startup_failure_returns_2_blocking(self, tmp_path, capsys): + """A user_prompt_submit handler that cannot start must still exit 2: + the prompt was never validated, so it stays blocked.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + self._write_broken_command(tmp_path) + code = resolve_and_run_event_command( + "speckit.broken", "user_prompt_submit", "{}", tmp_path + ) + assert code == 2 + assert "error:" in capsys.readouterr().err + def test_startup_failure_returns_1_for_stop(self, tmp_path, capsys): """A Stop handler that cannot start exits 1 with an error diagnostic: the runner failure must not read as "don't stop, keep going", and the @@ -1738,8 +1768,8 @@ def test_handler_own_exit_2_still_passes_through(self, tmp_path): code = resolve_and_run_event_command("speckit.block", "stop", "{}", tmp_path) assert code == 2 - def test_event_name_passed_as_speckit_event_env(self, tmp_path): - """The handler sees which event fired via the SPECKIT_EVENT env var.""" + def test_event_name_passed_as_speckit_event_name_env(self, tmp_path): + """The handler sees which event fired via the SPECKIT_EVENT_NAME env var.""" if platform.system().lower().startswith("win"): return # sh is POSIX @@ -1759,7 +1789,7 @@ def test_event_name_passed_as_speckit_event_env(self, tmp_path): out_file = tmp_path / "event.out" script_file = script_dir / "which.sh" script_file.write_text( - f"#!/bin/sh\necho \"$SPECKIT_EVENT\" > {shlex.quote(str(out_file))}\nexit 0\n", + f"#!/bin/sh\necho \"$SPECKIT_EVENT_NAME\" > {shlex.quote(str(out_file))}\nexit 0\n", encoding="utf-8", ) script_file.chmod(0o755) @@ -2107,6 +2137,173 @@ def _run_dispatcher_inline(self, tmp_path, dispatcher, command, event, timeout): check=False, ) + def _install_extension_dispatcher( + self, tmp_path, manifest_text, command, event, script_text, + template_name="guard-check.md", script_name="guard.sh", + template_text=None, + ): + """Install a dispatcher for an extension command whose file stem + differs from the command name, so only the manifest path (not the + file-stem scan) can resolve it. Returns (dispatcher, out_file).""" + integration = ClaudeIntegration() + manifest = MagicMock(spec=IntegrationManifest) + manifest.files = {} + manifest.record_file = MagicMock() + manifest.record_existing = MagicMock() + install_integration_events( + integration, tmp_path, manifest, + {event: [{"command": command}]}, + ) + dispatcher = tmp_path / EVENTS_DISPATCHER_REL + assert dispatcher.is_file() + + ext_dir = tmp_path / ".specify" / "extensions" / "guard-ext" + cmds_dir = ext_dir / "commands" + cmds_dir.mkdir(parents=True) + (ext_dir / "extension.yml").write_text(manifest_text, encoding="utf-8") + if template_text is None: + template_text = ( + "---\ndescription: \"Guard\"\nscripts:\n" + f" sh: scripts/{script_name}\n---\nBody\n" + ) + (cmds_dir / template_name).write_text(template_text, encoding="utf-8") + script_dir = ext_dir / "scripts" + script_dir.mkdir(parents=True) + script = script_dir / script_name + script.write_text(script_text, encoding="utf-8") + script.chmod(0o755) + return dispatcher, tmp_path / "guard.out" + + def test_dispatcher_inline_fallback_manifest_trailing_comment_resolves(self, tmp_path): + """The inline manifest scan must ignore a trailing ``#`` comment on + a ``file:`` value: the guard still resolves and runs instead of + silently returning 0 without validation.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + out_file = tmp_path / "guard.out" + dispatcher, _out = self._install_extension_dispatcher( + tmp_path, + "schema_version: '1.0'\n" + "extension:\n" + " id: guard-ext\n" + " name: Guard Ext\n" + " version: 1.0.0\n" + " description: test\n" + "provides:\n" + " commands:\n" + " - name: speckit.guard\n" + " file: commands/guard-check.md # the guard script lives here\n", + "speckit.guard", + "pre_tool_use", + f"#!/bin/sh\necho ran > {shlex.quote(str(out_file))}\nexit 0\n", + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.guard", "pre_tool_use", 60 + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert out_file.read_text().strip() == "ran", ( + "inline fallback did not run the guard; " + f"stderr={result.stderr!r} rc={result.returncode}" + ) + + def test_dispatcher_inline_fallback_manifest_cross_pairing_runs_nothing(self, tmp_path): + """The inline manifest scan must not pair a ``name:`` with the next + entry's ``file:``: a guard entry with no file must not resolve to + another command's script, and the guard event then fails closed.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + out_file = tmp_path / "guard.out" + dispatcher, _out = self._install_extension_dispatcher( + tmp_path, + "schema_version: '1.0'\n" + "extension:\n" + " id: guard-ext\n" + " name: Guard Ext\n" + " version: 1.0.0\n" + " description: test\n" + "provides:\n" + " commands:\n" + " - name: speckit.guard\n" + " - file: commands/other.md\n" + " name: speckit.other\n", + "speckit.guard", + "pre_tool_use", + f"#!/bin/sh\necho ran > {shlex.quote(str(out_file))}\nexit 0\n", + template_name="other.md", + script_name="other.sh", + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.guard", "pre_tool_use", 60 + ) + assert not out_file.exists(), "cross-paired file ran the wrong guard" + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "could not be resolved" in result.stderr + + def test_dispatcher_inline_fallback_unresolved_guard_fails_closed(self, tmp_path): + """A guard command the inline resolver cannot find must fail closed: + pre_tool_use exits 2 with a diagnostic instead of returning 0 + without running the guard; a non-guard event still no-ops with 0.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + integration = ClaudeIntegration() + manifest = MagicMock(spec=IntegrationManifest) + manifest.files = {} + manifest.record_file = MagicMock() + manifest.record_existing = MagicMock() + install_integration_events( + integration, tmp_path, manifest, + { + "pre_tool_use": [{"command": "speckit.missing"}], + "stop": [{"command": "speckit.missing"}], + }, + ) + dispatcher = tmp_path / EVENTS_DISPATCHER_REL + assert dispatcher.is_file() + + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.missing", "pre_tool_use", 60 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "could not be resolved" in result.stderr + + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.missing", "stop", 60 + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + + def test_dispatcher_inline_fallback_guard_without_script_fails_closed(self, tmp_path): + """A guard command that resolves to a template with no runnable + script must fail closed too: the guard never ran, so pre_tool_use + exits 2 instead of silently passing the tool call.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_extension_dispatcher( + tmp_path, + "schema_version: '1.0'\n" + "extension:\n" + " id: guard-ext\n" + " name: Guard Ext\n" + " version: 1.0.0\n" + " description: test\n" + "provides:\n" + " commands:\n" + " - name: speckit.guard\n" + " file: commands/guard-check.md\n", + "speckit.guard", + "pre_tool_use", + "#!/bin/sh\nexit 0\n", + template_text="---\ndescription: \"Guard\"\n---\nBody\n", + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.guard", "pre_tool_use", 60 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "no runnable script" in result.stderr + def test_dispatcher_inline_fallback_timeout_returns_1(self, tmp_path): """The inline fallback must not exit 2 on timeout either: the same Stop-hook "don't stop" misread applies when specify_cli is absent.""" @@ -2138,6 +2335,38 @@ def test_dispatcher_inline_fallback_pre_tool_use_timeout_returns_2(self, tmp_pat assert result.returncode == 2, f"stderr={result.stderr!r}" assert "timed out" in result.stderr + def test_dispatcher_inline_fallback_user_prompt_submit_timeout_returns_2(self, tmp_path): + """The inline fallback must exit 2 on a user_prompt_submit timeout: + Claude Code reads exit 2 from a UserPromptSubmit hook as "block the + prompt", so a prompt whose validation never ran must not reach the + model — same rule as the full resolver.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/bin/sh\nsleep 5\nexit 0\n", event="user_prompt_submit" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "user_prompt_submit", 1 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "timed out" in result.stderr + + def test_dispatcher_inline_fallback_user_prompt_submit_startup_failure_returns_2(self, tmp_path): + """The inline fallback must exit 2 when a user_prompt_submit handler + cannot start: the prompt was never validated, so it stays blocked.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/does/not/exist\nexit 0\n", event="user_prompt_submit" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "user_prompt_submit", 60 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "error:" in result.stderr + def test_dispatcher_inline_fallback_startup_failure_returns_1(self, tmp_path): """The inline fallback must exit 1 with an error diagnostic when a Stop handler cannot start: the generic error branch needs its own @@ -2157,9 +2386,9 @@ def test_dispatcher_inline_fallback_startup_failure_returns_1(self, tmp_path): def test_dispatcher_ignores_stale_specify_cli_without_runner_contract(self, tmp_path): """A generated dispatcher must not delegate to an older specify_cli that has EVENT_SCRIPT_PATH_CONFINEMENT but predates the #5336 runner - contract (per-event failure exit codes, SPECKIT_EVENT): after a + contract (per-event failure exit codes, SPECKIT_EVENT_NAME): after a one-time uvx upgrade, that resolver would still return 2 on timeout - and omit SPECKIT_EVENT. The dispatcher must fall back to its inline + and omit SPECKIT_EVENT_NAME. The dispatcher must fall back to its inline resolver instead.""" import subprocess as _sp import sys as _sys @@ -2199,15 +2428,15 @@ def test_dispatcher_ignores_stale_specify_cli_without_runner_contract(self, tmp_ "inline fallback did not run the script after refusing delegation" ) - def test_dispatcher_inline_fallback_passes_speckit_event(self, tmp_path): + def test_dispatcher_inline_fallback_passes_speckit_event_name(self, tmp_path): """The inline fallback passes the fired event to the handler via - SPECKIT_EVENT, same as the full resolver.""" + SPECKIT_EVENT_NAME, same as the full resolver.""" if platform.system().lower().startswith("win"): return # sh is POSIX dispatcher, out_file = self._install_boot_dispatcher( tmp_path, - f"#!/bin/sh\necho \"$SPECKIT_EVENT\" > {shlex.quote(str(tmp_path / 'boot.out'))}\nexit 0\n", + f"#!/bin/sh\necho \"$SPECKIT_EVENT_NAME\" > {shlex.quote(str(tmp_path / 'boot.out'))}\nexit 0\n", event="stop", ) result = self._run_dispatcher_inline( From ae5a11ea8c901a9a4a9dd69894b3f15417f503b3 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Tue, 10 Nov 2026 06:55:30 +0000 Subject: [PATCH 4/4] fix(events): fail closed on delegated guards, match real manifest keys Copilot round 3 (review 5836931756) on the c1cbba7f head: The delegated resolver returned 0 when a guard command could not be resolved, or resolved to a template with no runnable script, letting the action through without validation. Mirror the inline fallback fail-closed checks: pre_tool_use / user_prompt_submit now exit 2 with a diagnostic; non-guard events still no-op with 0. Fix the inline manifest scan: match real name:/file: keys instead of substrings, so a description mentioning "file:" can no longer select the wrong handler and bypass the guard. A block-style aliases: list between name: and file: reset the entry, so the guard never resolved. Only a dash at the entry's own indent starts a new entry; deeper-indented dashes belong to nested lists. Startup-failure coverage now spans both runners and all three event classes (the inline pre_tool_use case was the missing one). The two carried-over lows needed no change: the handler contract is already documented in docs/integrations/cli.md, and stop startup failures were already covered in both runners. Regression tests for each fix, each shown red before the fix: delegated fail-closed for missing and scriptless guards, description file: text ignored, block aliases keep the command name, inline pre_tool_use startup failure. --- src/specify_cli/events/__init__.py | 52 +++++++-- tests/specify_cli/events/test_events.py | 133 ++++++++++++++++++++++++ 2 files changed, 177 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index ab7fd5ec40..2256d0f152 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -213,6 +213,9 @@ def _find_command_template(command_name, project_root): yml_text = ext_yml.read_text(encoding="utf-8") cur_name = None cur_file = None + # Indent of the dash that started the entry being read; + # a deeper-indented dash belongs to a nested list. + entry_indent = None in_provides = False in_commands = False for line in yml_text.splitlines(): @@ -231,17 +234,31 @@ def _find_command_template(command_name, project_root): # A new list item starts a new command entry: # drop any half-filled pair from the previous # entry so a name can never pair with the next - # entry's file. + # entry's file. Only a dash at (or above) the + # entry's own indent starts a new entry: a + # deeper-indented dash belongs to a nested list + # (e.g. a block-style ``aliases:`` list) and + # must not reset the entry being read. if stripped.startswith("- ") or stripped == "-": - cur_name = None - cur_file = None - if "name:" in line: + indent = len(line) - len(line.lstrip()) + if entry_indent is None or indent <= entry_indent: + cur_name = None + cur_file = None + entry_indent = indent + # Match real ``name:``/``file:`` keys only: a + # substring match mistakes ``file:`` inside a + # description value (or ``file:`` inside + # ``profile:``) for the entry's file, so a + # guard can resolve to the wrong handler. + name_match = re.match(r"^(?:-\\s+)?name\\s*:\\s*(.*)$", stripped) + if name_match: cur_name = _strip_yaml_comment( - line.split("name:", 1)[1].strip() + name_match.group(1).strip() ).strip('"').strip("'") - if "file:" in line: + file_match = re.match(r"^(?:-\\s+)?file\\s*:\\s*(.*)$", stripped) + if file_match: cur_file = _strip_yaml_comment( - line.split("file:", 1)[1].strip() + file_match.group(1).strip() ).strip('"').strip("'") if cur_name and cur_file: if cur_name == command_name: @@ -916,14 +933,33 @@ def resolve_and_run_event_command( guard events (``pre_tool_use``, ``user_prompt_submit``) so the action stays blocked, and 1 for every other event so a slow handler cannot keep the agent running. A handler's own non-zero exit code always - passes through unchanged. + passes through unchanged. A guard command that cannot be resolved, or + resolves to a template with no runnable script, also fails closed + (exit 2) — the guard never ran, so the action must stay blocked; + non-guard events still no-op with 0 when no handler resolves. """ template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: + if event_name in BLOCKING_FAILURE_EVENTS: + logger.warning( + "Event command '%s' could not be resolved; blocking event " + "'%s' fails closed without validation", + command_name, + event_name, + ) + return _runner_failure_exit_code(event_name) logger.warning("Event command '%s' not found", command_name) return 0 argv = _resolve_event_command_argv(template_path, project_root, ext_id) if not argv: + if event_name in BLOCKING_FAILURE_EVENTS: + logger.warning( + "Event command '%s' has no runnable script; blocking event " + "'%s' fails closed without validation", + command_name, + event_name, + ) + return _runner_failure_exit_code(event_name) logger.warning("No script found for event command '%s'", command_name) return 0 # Tell the handler which event fired so one script can serve several diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index c9bc97734b..9ec44ce94c 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -1510,6 +1510,35 @@ def test_run_command_not_found(self, tmp_path): code = resolve_and_run_event_command("nonexistent.command", "session_start", "{}", tmp_path) assert code == 0 # no-ops gracefully + def test_run_command_not_found_fails_closed_for_guard_events(self, tmp_path): + """The delegated resolver must fail closed like the inline fallback: + a guard command that cannot be resolved exits 2 instead of + returning 0 without running the guard (Copilot round 3).""" + for event in ("pre_tool_use", "user_prompt_submit"): + code = resolve_and_run_event_command( + "nonexistent.command", event, "{}", tmp_path + ) + assert code == 2, f"{event} did not fail closed" + + def test_run_command_without_script_fails_closed_for_guard_events(self, tmp_path): + """A guard command that resolves to a template with no runnable + script must fail closed in the delegated resolver too: the guard + never ran, so the action stays blocked (Copilot round 3).""" + cmd_dir = tmp_path / ".specify" / "templates" / "commands" + cmd_dir.mkdir(parents=True) + (cmd_dir / "test.md").write_text( + "---\ndescription: \"Test\"\n---\nBody\n", encoding="utf-8" + ) + for event, expected in ( + ("pre_tool_use", 2), + ("user_prompt_submit", 2), + ("session_start", 0), + ): + code = resolve_and_run_event_command( + "speckit.test", event, "{}", tmp_path + ) + assert code == expected, f"{event} returned {code}, expected {expected}" + def test_extension_command_resolves_when_file_stem_differs(self, tmp_path): """S8: an extension command whose declared file differs from its command name resolves via the manifest, not a file-stem scan.""" @@ -2241,6 +2270,93 @@ def test_dispatcher_inline_fallback_manifest_cross_pairing_runs_nothing(self, tm assert result.returncode == 2, f"stderr={result.stderr!r}" assert "could not be resolved" in result.stderr + def test_dispatcher_inline_fallback_description_file_text_ignored(self, tmp_path): + """The inline manifest scan must match real ``file:`` keys, not the + substring anywhere: a ``description:`` mentioning ``file:`` before + the real ``file:`` entry must not select the mentioned file, or the + guard is bypassed by a handler that exits 0 (Copilot round 3).""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + out_file = tmp_path / "guard.out" + dispatcher, _out = self._install_extension_dispatcher( + tmp_path, + "schema_version: '1.0'\n" + "extension:\n" + " id: guard-ext\n" + " name: Guard Ext\n" + " version: 1.0.0\n" + " description: test\n" + "provides:\n" + " commands:\n" + " - name: speckit.guard\n" + " description: \"Inspect file: commands/allow.md\"\n" + " file: commands/guard-check.md\n", + "speckit.guard", + "pre_tool_use", + f"#!/bin/sh\necho ran > {shlex.quote(str(out_file))}\nexit 0\n", + ) + # The mentioned file exists as a decoy: its script exits 0, so + # selecting it would pass the guard without running the real one. + ext_dir = tmp_path / ".specify" / "extensions" / "guard-ext" + allow_out = tmp_path / "allow.out" + (ext_dir / "commands" / "allow.md").write_text( + "---\ndescription: \"Allow\"\nscripts:\n" + " sh: scripts/allow.sh\n---\nBody\n", + encoding="utf-8", + ) + (ext_dir / "scripts" / "allow.sh").write_text( + f"#!/bin/sh\necho allow > {shlex.quote(str(allow_out))}\nexit 0\n", + encoding="utf-8", + ) + (ext_dir / "scripts" / "allow.sh").chmod(0o755) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.guard", "pre_tool_use", 60 + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert not allow_out.exists(), "description text selected the wrong handler" + assert out_file.read_text().strip() == "ran", ( + "inline fallback did not run the real guard; " + f"stderr={result.stderr!r} rc={result.returncode}" + ) + + def test_dispatcher_inline_fallback_block_aliases_keep_command_name(self, tmp_path): + """A block-style ``aliases:`` list between ``name:`` and ``file:`` + must not reset the command entry: alias items are nested list + items, not sibling commands, so the guard still resolves and runs + (Copilot round 3).""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + out_file = tmp_path / "guard.out" + dispatcher, _out = self._install_extension_dispatcher( + tmp_path, + "schema_version: '1.0'\n" + "extension:\n" + " id: guard-ext\n" + " name: Guard Ext\n" + " version: 1.0.0\n" + " description: test\n" + "provides:\n" + " commands:\n" + " - name: speckit.guard\n" + " aliases:\n" + " - guard-alias\n" + " - other-alias\n" + " file: commands/guard-check.md\n", + "speckit.guard", + "pre_tool_use", + f"#!/bin/sh\necho ran > {shlex.quote(str(out_file))}\nexit 0\n", + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.guard", "pre_tool_use", 60 + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert out_file.read_text().strip() == "ran", ( + "inline fallback did not run the guard after block aliases; " + f"stderr={result.stderr!r} rc={result.returncode}" + ) + def test_dispatcher_inline_fallback_unresolved_guard_fails_closed(self, tmp_path): """A guard command the inline resolver cannot find must fail closed: pre_tool_use exits 2 with a diagnostic instead of returning 0 @@ -2367,6 +2483,23 @@ def test_dispatcher_inline_fallback_user_prompt_submit_startup_failure_returns_2 assert result.returncode == 2, f"stderr={result.stderr!r}" assert "error:" in result.stderr + def test_dispatcher_inline_fallback_pre_tool_use_startup_failure_returns_2(self, tmp_path): + """The inline fallback must exit 2 when a pre_tool_use handler + cannot start: the tool call was never validated, so it stays + blocked. Completes the startup-failure matrix (both runners, all + three event classes) required by the round-1 review.""" + if platform.system().lower().startswith("win"): + return # sh is POSIX + + dispatcher, _out = self._install_boot_dispatcher( + tmp_path, "#!/does/not/exist\nexit 0\n", event="pre_tool_use" + ) + result = self._run_dispatcher_inline( + tmp_path, dispatcher, "speckit.boot", "pre_tool_use", 60 + ) + assert result.returncode == 2, f"stderr={result.stderr!r}" + assert "error:" in result.stderr + def test_dispatcher_inline_fallback_startup_failure_returns_1(self, tmp_path): """The inline fallback must exit 1 with an error diagnostic when a Stop handler cannot start: the generic error branch needs its own