test(8249): moment and checkpoint hook guards run the hooks
- test_moment_delivery: the route/hook name check runs the hook with the rule, opened and shape ledgers filled and checks every key it sends is read by the route; "leaves Grimoire's own tools alone" runs it with a listed Grimoire tool and sees no ask. - test_gate_stop_hooks: the action hook run twice on one checkpoint rule holds once, and books the rule on the session ledger after the stop. This replaces two line-window checks in test_pre_act_checkpoint. - The write hook never stopping a write: the two string guards (one per test file) are one, which now also forbids the shared deny helper, the call the old permissionDecision check could not see. - route_query_args (tests/helpers.py) reads the query keys a route takes from its AST, shared by both route/hook contract tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -530,3 +530,21 @@ def forge_tarball(files: dict[str, bytes], top: str = "widget") -> bytes:
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def route_query_args(*fns) -> set[str]:
|
||||
"""Every query-string key the given route functions read with
|
||||
`request.args.get("…")`, from their AST. A hook test runs the hook, takes
|
||||
the keys it actually sent, and checks the route reads each one."""
|
||||
import ast
|
||||
import inspect
|
||||
import textwrap
|
||||
|
||||
keys = set()
|
||||
for fn in fns:
|
||||
for node in ast.walk(ast.parse(textwrap.dedent(inspect.getsource(fn)))):
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr == "get" and ast.unparse(node.func.value) == "request.args"
|
||||
and node.args and isinstance(node.args[0], ast.Constant)):
|
||||
keys.add(node.args[0].value)
|
||||
return keys
|
||||
|
||||
@@ -131,6 +131,22 @@ def test_a_checkpoint_past_the_session_cap_is_reported_as_let_through(tmp_path):
|
||||
assert [(s["gate"], s["outcome"]) for s in _stops(seen)] == [("checkpoint", "let_through")]
|
||||
|
||||
|
||||
def test_a_checkpoint_holds_a_rule_once_and_books_it_as_surfaced_either_way(tmp_path):
|
||||
"""The per-rule cap, end to end: the second command on the same rule goes
|
||||
ahead. And the rule is on the session's rules ledger after the stop,
|
||||
because what the server surfaced happened whichever way the hook rendered
|
||||
it; bookkeeping inside one branch is how two arms' ledgers came to disagree."""
|
||||
with http_sink(by_path=_checkpoint_replies(rule_id=9)) as (port, seen):
|
||||
first = _run(TOOL_RULES, tmp_path, port,
|
||||
_bash_event(call="toolu_a", command="git commit -m x", cwd=str(tmp_path)))
|
||||
second = _run(TOOL_RULES, tmp_path, port,
|
||||
_bash_event(call="toolu_b", command="git commit -m y", cwd=str(tmp_path)))
|
||||
assert _denied(first)
|
||||
assert not second or not _denied(second)
|
||||
ledger = tmp_path / "tmp" / "grimoire-priorart" / "s-gate.rules.ids"
|
||||
assert ledger.read_text().split("\t")[0].strip() == "9"
|
||||
|
||||
|
||||
# ── the project fence ────────────────────────────────────────────────────
|
||||
|
||||
HOME_URL = "https://forge.example/team/home.git"
|
||||
|
||||
@@ -30,7 +30,7 @@ from grimoire.services import moment_actions
|
||||
from grimoire.services import moment_delivery as md
|
||||
from grimoire.services import retrieval_pipeline as rp
|
||||
from grimoire.services import rule_usage, rulebooks
|
||||
from tests.helpers import fake_rule, http_sink, need_tools
|
||||
from tests.helpers import fake_rule, http_sink, need_tools, route_query_args
|
||||
|
||||
# Bound before conftest's autouse stub replaces the module attribute.
|
||||
_REAL_DELIVER = md.deliver_for_act
|
||||
@@ -274,30 +274,6 @@ def test_the_hook_is_registered_on_every_tool():
|
||||
assert any("grimoire_moment.sh" in c for c in entries.get("*", []))
|
||||
|
||||
|
||||
def test_the_hook_and_the_routes_agree_on_every_name():
|
||||
"""Parity across the shell/Python seam: a renamed arg fails silently."""
|
||||
src = HOOK.read_text()
|
||||
assert "/api/plugin/moment-tools" in src and "/api/plugin/moment" in src
|
||||
assert "exclude_rule_ids" in src and "grimoire_held_query" in src
|
||||
assert "grimoire_rules_live" in src and "grimoire_rules_append" in src
|
||||
# The SHARED ledger, not one of its own.
|
||||
assert '"${TMPDIR:-/tmp}/grimoire-priorart"' in src and ".rules.ids" in src
|
||||
for field in (".tools", ".rule_ids", ".context", ".shape_keys"):
|
||||
assert f"'{field}'" in src
|
||||
assert "shapes_seen" in src and "grimoire_shapes_append" in src
|
||||
|
||||
from grimoire.routes import plugin as routes
|
||||
|
||||
route = inspect.getsource(routes.moment)
|
||||
for name in ("exclude_rule_ids", "held_rule_ids", "tool_name", "tool_input",
|
||||
"shapes_seen", "shape_keys"):
|
||||
assert name in route
|
||||
|
||||
|
||||
def test_the_hook_leaves_grimoires_own_tools_to_their_responses():
|
||||
assert "mcp__*grimoire*__*) exit 0" in HOOK.read_text()
|
||||
|
||||
|
||||
def test_the_hook_holds_only_behind_the_session_guard_and_refuses_only_on_enforce():
|
||||
"""Structural, and able to fail: every deny the hook emits is either the
|
||||
`enforce` branch or sits behind `grimoire_checkpoint_allowed`. A hold
|
||||
@@ -355,6 +331,40 @@ def test_an_unlisted_tool_never_leaves_the_machine(tmp_path):
|
||||
assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"]
|
||||
|
||||
|
||||
def test_grimoires_own_tools_are_left_to_their_responses(tmp_path):
|
||||
"""A Grimoire tool attaches its own moment rules in its response, so the
|
||||
hook never asks about one, even when the tool is listed."""
|
||||
with http_sink(by_path={"/api/plugin/moment-tools": b'{"tools":["update_task"]}'}) \
|
||||
as (port, seen):
|
||||
assert _hook(tmp_path, port, tool="mcp__plugin_grimoire_grimoire__update_task") == ""
|
||||
assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"]
|
||||
|
||||
|
||||
def test_the_route_reads_every_name_the_hook_sends(tmp_path):
|
||||
"""Parity across the shell/Python seam, a renamed key fails silently. The
|
||||
hook runs with the shared rule ledger, the opened ledger and the shape
|
||||
ledger all holding something; every query key it sends must be one the
|
||||
route reads, and the body carries the event the route reads."""
|
||||
from grimoire.routes import plugin as routes
|
||||
|
||||
state = tmp_path / "grimoire-priorart"
|
||||
state.mkdir()
|
||||
(state / "s-moment.opened.ids").write_text("7\n")
|
||||
replies = dict(TOOLS)
|
||||
replies["/api/plugin/moment"] = json.dumps(
|
||||
{"context": "a rule", "rule_ids": [5], "moments": ["work.deliver"],
|
||||
"shape_keys": ["asks"]}).encode()
|
||||
with http_sink(by_path=replies) as (port, seen):
|
||||
_hook(tmp_path, port)
|
||||
_hook(tmp_path, port)
|
||||
last = [e for e in seen if e["_path"] == "/api/plugin/moment"][-1]
|
||||
sent = {k for k in last if not k.startswith("_")}
|
||||
assert {"exclude_rule_ids", "held_rule_ids", "shapes_seen"} <= sent, sent
|
||||
read = route_query_args(routes.moment, routes._project_scope)
|
||||
assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}"
|
||||
assert {"tool_name", "tool_input"} <= set(json.loads(last["_body"]))
|
||||
|
||||
|
||||
def test_an_install_with_nothing_mounted_sends_one_request_per_window(tmp_path):
|
||||
with http_sink(by_path={"/api/plugin/moment-tools": b'{"tools":[]}'}) as (port, seen):
|
||||
for _ in range(3):
|
||||
|
||||
@@ -49,7 +49,6 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
HOOKS = ROOT / "plugin" / "hooks"
|
||||
DEFS = HOOKS / "grimoire_defs.sh"
|
||||
ACTION_HOOK = HOOKS / "grimoire_tool_rules.sh"
|
||||
WRITE_HOOK = HOOKS / "grimoire_prior_art.sh"
|
||||
|
||||
WHERE = "this Bash call"
|
||||
TRIGGER = "about to assert in a commit message what CI said"
|
||||
@@ -255,60 +254,5 @@ def test_the_deny_envelope_is_valid_json_carrying_the_reason():
|
||||
|
||||
# ── The boundary that is a recorded decision ──────────────────────────────
|
||||
|
||||
def test_only_the_action_hook_can_hold_an_act():
|
||||
"""THE GUARD ON THE RECORDED DECISION, and the reason it is here rather
|
||||
than left to memory.
|
||||
|
||||
`grimoire_prior_art.sh` runs before every Write and Edit and has never been
|
||||
able to stop one. That is a standing decision — a recall aid may not stand
|
||||
in the way of the work — and `test_hook_never_returns_a_permission_
|
||||
decision` in test_write_path_trigger.py holds the other half of it.
|
||||
|
||||
This milestone has a live argument for extending the checkpoint to writes:
|
||||
three of its seven misses were file edits and none of them are reachable
|
||||
from the command side. That argument is exactly why this assertion exists.
|
||||
A feature with a good reason to spread is the kind that spreads without
|
||||
anyone deciding to, and the decision here is the operator's to revisit.
|
||||
"""
|
||||
assert "grimoire_json_deny" in ACTION_HOOK.read_text()
|
||||
write_code = [
|
||||
ln for ln in WRITE_HOOK.read_text().splitlines()
|
||||
if not ln.lstrip().startswith("#")
|
||||
]
|
||||
assert not any("grimoire_json_deny" in ln for ln in write_code)
|
||||
assert not any("permissionDecision" in ln for ln in write_code)
|
||||
|
||||
|
||||
def test_the_action_hook_caps_every_hold_it_emits():
|
||||
"""Structural, and able to fail: the deny and the ledger call
|
||||
must appear together. A deny emitted outside the guard is a session that
|
||||
can be held by the same rule on every command, which is the one outcome
|
||||
both guards exist to prevent."""
|
||||
text = ACTION_HOOK.read_text()
|
||||
code = [ln for ln in text.splitlines() if not ln.lstrip().startswith("#")]
|
||||
denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln]
|
||||
assert denies, "the action arm no longer emits a hold at all"
|
||||
for i in denies:
|
||||
window = "\n".join(code[max(0, i - 6):i])
|
||||
assert "grimoire_checkpoint_allowed" in window, (
|
||||
"a hold is emitted without passing the per-rule and per-session "
|
||||
"guards first"
|
||||
)
|
||||
|
||||
|
||||
def test_the_action_hook_records_what_was_surfaced_whichever_way_it_renders():
|
||||
"""The ledger append sits BEFORE the checkpoint branch. What the server
|
||||
chose to surface happened whichever way this hook then renders it, and
|
||||
doing the bookkeeping inside one branch is how the two arms' ledgers came
|
||||
to disagree once already."""
|
||||
code = [
|
||||
ln for ln in ACTION_HOOK.read_text().splitlines()
|
||||
if not ln.lstrip().startswith("#")
|
||||
]
|
||||
append = next(i for i, ln in enumerate(code) if "grimoire_rules_append" in ln)
|
||||
deny = next(i for i, ln in enumerate(code) if "grimoire_json_deny" in ln)
|
||||
assert append < deny
|
||||
|
||||
|
||||
def test_the_action_hook_is_still_shell_valid():
|
||||
subprocess.run(["bash", "-n", str(ACTION_HOOK)], check=True)
|
||||
|
||||
@@ -14,7 +14,7 @@ from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from tests.helpers import fake_note, http_sink, writepath_cfg
|
||||
from tests.helpers import fake_note, http_sink, route_query_args, writepath_cfg
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
@@ -936,22 +936,6 @@ def test_prior_art_line_takes_a_search_hit_whose_snippet_is_its_excerpt():
|
||||
|
||||
# --- the route between them --------------------------------------------------
|
||||
|
||||
def _route_args(*fns) -> set[str]:
|
||||
"""Every query key the given route functions read, from their AST."""
|
||||
import ast
|
||||
import inspect
|
||||
import textwrap
|
||||
|
||||
keys = set()
|
||||
for fn in fns:
|
||||
for node in ast.walk(ast.parse(textwrap.dedent(inspect.getsource(fn)))):
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr == "get" and ast.unparse(node.func.value) == "request.args"
|
||||
and node.args and isinstance(node.args[0], ast.Constant)):
|
||||
keys.add(node.args[0].value)
|
||||
return keys
|
||||
|
||||
|
||||
def test_route_reads_every_arg_the_hook_sends(tmp_path):
|
||||
"""The hook's query string and the route's reader are one contract, and
|
||||
the hook is the only caller, so a rename on either side is silent. The
|
||||
@@ -983,7 +967,7 @@ def test_route_reads_every_arg_the_hook_sends(tmp_path):
|
||||
# Every ledger the hook keeps went out, so this run exercised the whole query.
|
||||
assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_sync_ids", "exclude_rule_ids",
|
||||
"exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent
|
||||
read = _route_args(routes.write_path_prior_art, routes._project_scope)
|
||||
read = route_query_args(routes.write_path_prior_art, routes._project_scope)
|
||||
assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}"
|
||||
# project_id is the other scope key the hook can send (from a project marker).
|
||||
assert "project_id" in read
|
||||
@@ -1018,11 +1002,20 @@ def test_hook_is_registered_for_write_and_edit():
|
||||
def test_hook_never_returns_a_permission_decision():
|
||||
"""The load-bearing property: this hook informs a write, it cannot stop one.
|
||||
A permissionDecision of deny/ask would put a recall aid in the way of the
|
||||
operator's work."""
|
||||
operator's work.
|
||||
|
||||
It is a standing decision: a recall aid may not stand in the way of the
|
||||
work, even where a stop would catch a miss. The command-side checkpoint
|
||||
(grimoire_tool_rules.sh) is the only hook that holds an act, and
|
||||
extending it to writes is the operator's call to make.
|
||||
"""
|
||||
src = HOOK.read_text()
|
||||
assert "additionalContext" in src
|
||||
code_lines = [ln for ln in src.splitlines() if not ln.lstrip().startswith("#")]
|
||||
assert not any("permissionDecision" in ln for ln in code_lines)
|
||||
# The shared helper that emits a deny, too: a call to it carries no
|
||||
# permissionDecision text in this file.
|
||||
assert not any("grimoire_json_deny" in ln for ln in code_lines)
|
||||
|
||||
|
||||
def test_hook_is_executable_and_shell_valid():
|
||||
|
||||
Reference in New Issue
Block a user