Skip to content

The agent that grows with you

test(approval): pin CLI prompt hooks to their gateway twin's payload

Teknium6ce6c1aa554c
diff --git a/tests/tools/test_approval_plugin_hooks.py b/tests/tools/test_approval_plugin_hooks.py
index 23e9f4cb074..605306f5cbd 100644
--- a/tests/tools/test_approval_plugin_hooks.py
+++ b/tests/tools/test_approval_plugin_hooks.py
@@ -337,110 +337,65 @@ class TestSmartModeFiresHooks:
]
-class TestProtectedWriteCliPathFiresHooks:
- """CLI protected agent-instruction write prompt: must fire the same observer
- hooks as its gateway twin so notifiers see the human wait (#131876)."""
-
- def test_pre_and_post_fire_with_expected_kwargs(self, monkeypatch):
- monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
- token = set_current_session_key("test:session:protected_write")
- captured = []
-
- def cb(command, description, *, allow_permanent=True, allow_session=True,
- smart_denied=False):
- return "once"
-
- monkeypatch.setattr("tools.terminal_tool._get_approval_callback", lambda: cb)
+def _capture_hooks(run):
+ """Run ``run()`` with the approval hook dispatch captured; drop the per-turn ids
+ every surface adds, so only the prompt payload is compared."""
+ captured = []
+ with patch("hermes_cli.plugins.invoke_hook",
+ side_effect=lambda name, **kw: captured.append((name, kw)) or []):
+ result = run()
+ for _, kw in captured:
+ for key in ("turn_id", "tool_call_id", "session_id"):
+ kw.pop(key, None)
+ return result, captured
+
+
+_PROTECTED_WRITE = (lambda: _request_protected_instruction_approval(["AGENTS.md"]), None, "cli")
+_ELICITATION = (lambda: request_elicitation_consent("Allow server access?", "an MCP server asks",
+ surface="mcp-trust/test-server"),
+ "accept", "mcp-trust/test-server")
+
+
+class TestClassicCliPromptsFireGatewayTwinHooks:
+ """The protected agent-instruction write prompt and MCP/vault consent prompt fire the
+ same pre/post observer hooks in the classic CLI as their gateway twins (#131876)."""
+
+ @pytest.mark.parametrize("run, approved, cli_surface", [_PROTECTED_WRITE, _ELICITATION],
+ ids=["protected_write", "elicitation"])
+ def test_cli_branch_fires_the_gateway_payload(self, isolated_session, monkeypatch,
+ run, approved, cli_surface):
+ from tools.terminal_tool import set_approval_callback
+
+ monkeypatch.setattr(approval_context, "_get_approval_config",
+ lambda: {"mode": "manual", "timeout": 60})
+ # Gateway twin: the notifier answers "once" as soon as the card is sent.
+ monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")
+ approval_module.register_gateway_notify(
+ isolated_session, lambda _data: approval_module.resolve_gateway_approval(isolated_session, "once"))
try:
- with patch("hermes_cli.plugins.invoke_hook",
- side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):
- result = _request_protected_instruction_approval(["AGENTS.md"])
+ result, gateway_hooks = _capture_hooks(run)
finally:
- approval_context._approval_session_key.reset(token)
-
- assert result is None # one-operation grant
- assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]
+ approval_module.unregister_gateway_notify(isolated_session)
+ assert result == approved
- pre_kwargs = captured[0][1]
- assert pre_kwargs["command"] == "<write to AGENTS.md>"
- assert pre_kwargs["pattern_key"] == "protected_instruction_file"
- assert pre_kwargs["pattern_keys"] == ["protected_instruction_file"]
- assert pre_kwargs["surface"] == "cli"
- assert pre_kwargs["session_key"] == "test:session:protected_write"
- assert pre_kwargs["description"]
+ # Classic CLI: the panel callback (protected write) or stdin (consent) answers "once".
+ monkeypatch.delenv("HERMES_GATEWAY_SESSION")
+ monkeypatch.setattr("builtins.input", lambda _prompt="": "o")
+ set_approval_callback(lambda *_a, **_kw: "once")
+ try:
+ result, cli_hooks = _capture_hooks(run)
+ finally:
+ set_approval_callback(None)
- post_kwargs = captured[1][1]
- assert post_kwargs["choice"] == "once"
- assert post_kwargs["surface"] == "cli"
+ assert result == approved
+ assert [name for name, _ in cli_hooks] == ["pre_approval_request", "post_approval_response"]
+ expected = [(name, {**kw, "surface": cli_surface}) for name, kw in gateway_hooks]
+ assert cli_hooks == expected
- def test_no_human_channel_fails_closed_without_hooks(self, monkeypatch):
- """The no-callback branch never waits on a human, so observers must not
- be told a prompt is pending."""
+ def test_protected_write_without_a_human_channel_fires_no_hooks(self, isolated_session, monkeypatch):
+ """Fail-closed with no panel callback: nobody is waiting, so observers hear nothing."""
monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
- token = set_current_session_key("test:session:protected_write")
- captured = []
monkeypatch.setattr("tools.terminal_tool._get_approval_callback", lambda: None)
- try:
- with patch("hermes_cli.plugins.invoke_hook",
- side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):
- result = _request_protected_instruction_approval(["AGENTS.md"])
- finally:
- approval_context._approval_session_key.reset(token)
-
+ result, captured = _capture_hooks(lambda: _request_protected_instruction_approval(["AGENTS.md"]))
assert result is not None and "has NOT consented" in result
assert captured == []
-
-
-class TestElicitationCliPathFiresHooks:
- """CLI MCP/vault consent prompt: must fire the same observer hooks as its
- gateway twin, carrying the caller's surface value (#131876)."""
-
- def test_pre_and_post_fire_with_caller_surface(self, monkeypatch):
- monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
- monkeypatch.delenv("HERMES_EXEC_ASK", raising=False)
- token = set_current_session_key("test:session:elicitation")
- captured = []
- try:
- with patch("tools.approval_prompt.prompt_dangerous_approval", return_value="once"), \
- patch("hermes_cli.plugins.invoke_hook",
- side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):
- verdict = request_elicitation_consent(
- "Allow server access?", "an MCP server asks",
- surface="mcp-elicitation/test-server")
- finally:
- approval_context._approval_session_key.reset(token)
-
- assert verdict == "accept"
- assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]
-
- pre_kwargs = captured[0][1]
- assert pre_kwargs["command"] == "Allow server access?"
- assert pre_kwargs["pattern_key"] == "mcp_elicitation"
- assert pre_kwargs["pattern_keys"] == ["mcp_elicitation"]
- assert pre_kwargs["surface"] == "mcp-elicitation/test-server"
- assert pre_kwargs["session_key"] == "test:session:elicitation"
-
- assert captured[1][1]["choice"] == "once"
-
- def test_prompt_failure_fails_closed_and_settles_observers(self, monkeypatch):
- """A raising panel still maps to "decline" AND settles the wait for
- observers (post hook with choice="cancelled")."""
- monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
- token = set_current_session_key("test:session:elicitation")
- captured = []
- try:
- with patch("tools.approval_prompt.prompt_dangerous_approval",
- side_effect=RuntimeError("panel blew up")), \
- patch("hermes_cli.plugins.invoke_hook",
- side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):
- verdict = request_elicitation_consent(
- "Confirm payment?", "the vault asks", surface="vault-payment")
- finally:
- approval_context._approval_session_key.reset(token)
-
- assert verdict == "decline"
- assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]
- assert captured[1][1]["choice"] == "cancelled"
- assert captured[1][1]["surface"] == "vault-payment"
-
-
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.py
index 357a93e6b5e..bb6915363f8 100644
--- a/tools/approval_prompt.py
+++ b/tools/approval_prompt.py
@@ -327,9 +327,8 @@ def request_elicitation_consent(message: str, description: str, *,
return _consent(decision.get("choice"), "decline")
# allow_permanent=False: elicitation is a per-call confirmation — no pattern to remember.
- # Same observer hooks as the gateway branch, carrying the caller's surface value, so
- # notifiers see this human wait in the classic CLI too; post fires in a finally so the
- # wait always settles for observers even when the prompt raises (#131876).
+ # Same observer payload as the gateway branch (#131876); post fires in a finally so the
+ # wait settles for observers on the early fail-closed return too.
hook_kwargs = dict(command=message, description=description, pattern_key="mcp_elicitation",
pattern_keys=["mcp_elicitation"], session_key=session_key, surface=surface)
_ctx._fire_approval_hook("pre_approval_request", **hook_kwargs)
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index 7666cdcef36..36f4569d3cc 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -319,21 +319,14 @@ def _request_protected_instruction_approval(reasons: list[str], task_id: str = "
# No human channel (script, cron, background thread): fail closed —
# auto-approving here would recreate the persistence vector.
return blocked.format(why=_NO_HUMAN)
- # Observer hooks like the gateway branch above, with the classic-CLI surface
- # every other CLI prompt reports; the post hook fires in a finally so notifiers
- # see the wait settle even when the panel itself raises (#131876).
- hook_kwargs = dict(command=display, description=description,
- pattern_key="protected_instruction_file",
- pattern_keys=["protected_instruction_file"],
- session_key=session_key, surface="cli")
+ # Same observer payload as the gateway branch (#131876), fired like the
+ # dangerous-command CLI prompt in tools/approval.py.
+ hook_kwargs = dict(command=display, description=description, pattern_key="protected_instruction_file",
+ pattern_keys=["protected_instruction_file"], session_key=session_key, surface="cli")
_fire_approval_hook("pre_approval_request", **hook_kwargs)
- hook_choice = "cancelled"
- try:
- choice = prompt_dangerous_approval(
- display, description, allow_permanent=False, allow_session=False, approval_callback=callback)
- hook_choice = choice
- finally:
- _fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)
+ choice = prompt_dangerous_approval(
+ display, description, allow_permanent=False, allow_session=False, approval_callback=callback)
+ _fire_approval_hook("post_approval_response", **hook_kwargs, choice=choice)
if choice == "cancelled":
return blocked.format(why="approval prompt could not be delivered or was not answered "
f"({getattr(choice, 'cause', 'no answer')}).")