Files
FabledGrimoire/tests/test_gate_stop_hooks.py
T
bvandeusenandClaude Opus 5.5 82ffd9a235
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m49s
CI & Build / integration (push) Successful in 2m4s
CI & Build / Build & push image (push) Skipped
feat(8141): a rule holding the finished reply is recorded as a gate stop too
The end-of-turn reply hold was the one gate the gate_stops table left out.
The server applies the per-session cap before anything holds and the Stop
hook blocks on every reason it is given, so the hook reports each held rule
after blocking, as the tool-call gates do: gate `reply`, tool `reply`, and
where the rule was reached (`rule_at`, new beside `rule_ids` in the
/reply-rules answer: the moment it is mounted on, or `reply_rule` for the
backstop). A section hold names no rule and stays counted by report_check.
Opening the rule clears the stop, and rule_misfired marks it, unchanged.

The readout, the telemetry docstring and the Settings panel name the new gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:32:46 -05:00

236 lines
11 KiB
Python

"""Every gate that stands in front of a tool call reports it, end to end.
The moment hook (a rule set to enforce or hold), the act checkpoint on a
command and the project fence are run through a real shell against a
stand-in server. Each stop is posted to `/api/plugin/gate-stop` with what
the hook did: `stopped`, `let_through` when the session's stop budget is
spent, or `asked` for the fence. A fenced call that then runs is posted to
`/api/plugin/gate-ran` by grimoire_fence_ran.sh, matched by the call's id.
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
from tests.helpers import http_sink, need_tools
HOOKS = Path(__file__).resolve().parents[1] / "plugin" / "hooks"
MOMENT = HOOKS / "grimoire_moment.sh"
TOOL_RULES = HOOKS / "grimoire_tool_rules.sh"
FENCE = HOOKS / "grimoire_project_fence.sh"
FENCE_RAN = HOOKS / "grimoire_fence_ran.sh"
STOP = "/api/plugin/gate-stop"
RAN = "/api/plugin/gate-ran"
REPLY_CHECK = HOOKS / "grimoire_reply_check.sh"
TOOLS = {"/api/plugin/moment-tools": b'{"tools":["bash"]}'}
def _env(tmp_path, port, **extra):
return {"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}",
"GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path / "tmp"), "HOME": str(tmp_path), **extra}
def _run(hook, tmp_path, port, event, **extra):
need_tools("bash", "curl", "awk")
(tmp_path / "tmp").mkdir(exist_ok=True)
out = subprocess.run(["bash", str(hook)], input=json.dumps(event), capture_output=True,
text=True, env=_env(tmp_path, port, **extra), timeout=30)
assert out.returncode == 0, out.stderr
return out.stdout.strip()
def _bash_event(session="s-gate", call="toolu_1", command="git push origin dev", cwd="."):
return {"session_id": session, "cwd": cwd, "hook_event_name": "PreToolUse",
"tool_name": "Bash", "tool_use_id": call, "tool_input": {"command": command}}
def _stops(seen):
return [json.loads(e["_body"]) for e in seen if e.get("_path") == STOP]
def _denied(out):
return json.loads(out)["hookSpecificOutput"].get("permissionDecision") == "deny"
def _moment_replies(decision):
replies = dict(TOOLS)
replies["/api/plugin/moment"] = json.dumps(
{"context": "", "rule_ids": [], "moments": ["work.deliver"], "decision": decision}).encode()
return replies
# ── the moment hook ──────────────────────────────────────────────────────
def test_an_enforced_refusal_is_reported_every_time_with_where_it_was_reached(tmp_path):
decision = {"kind": "enforce", "rule_ids": [6], "at": "work.deliver", "reason": "Not run: rule 6"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
outs = [_run(MOMENT, tmp_path, port, _bash_event(call=f"toolu_{i}"), CLAUDE_PROJECT_DIR=str(tmp_path))
for i in range(2)]
assert all(_denied(o) for o in outs)
stops = _stops(seen)
assert [s["call_id"] for s in stops] == ["toolu_0", "toolu_1"]
assert stops[0] == {"session_id": "s-gate", "gate": "enforce", "outcome": "stopped",
"tool": "bash", "rule_id": 6, "at": "work.deliver", "call_id": "toolu_0"}
def test_a_hold_is_reported_once_and_its_repeat_is_not_a_cap_let_through(tmp_path):
"""The per-rule once is the hold working as meant, so the second call on
the same rule reports nothing: only a spent session budget is a call the
cap let through."""
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
first = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_a"))
second = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_b"))
assert _denied(first)
assert second == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "stopped", 7)]
def test_a_hold_the_spent_session_budget_lets_through_is_reported_as_such(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
out = _run(MOMENT, tmp_path, port, _bash_event())
assert out == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "let_through", 7)]
def test_a_call_no_gate_stops_reports_nothing(tmp_path):
with http_sink(by_path=_moment_replies({})) as (port, seen):
_run(MOMENT, tmp_path, port, _bash_event())
assert _stops(seen) == []
# ── the act checkpoint ───────────────────────────────────────────────────
def _checkpoint_replies(rule_id=9):
return {"/api/plugin/tool-rules": json.dumps(
{"context": "", "rule_ids": [rule_id],
"checkpoint": {"rule_id": rule_id, "reason": f"Read rule {rule_id} first"}}).encode()}
def test_a_checkpoint_stop_is_reported_with_the_tool_and_the_arm(tmp_path):
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert _denied(out)
assert _stops(seen) == [{"session_id": "s-gate", "gate": "checkpoint", "outcome": "stopped",
"tool": "Bash", "rule_id": 9, "at": "pre_tool_rule", "call_id": "toolu_1"}]
def test_a_checkpoint_past_the_session_cap_is_reported_as_let_through(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert out == ""
assert [(s["gate"], s["outcome"]) for s in _stops(seen)] == [("checkpoint", "let_through")]
# ── the project fence ────────────────────────────────────────────────────
HOME_URL = "https://forge.example/team/home.git"
ASK = json.dumps({"allowed": False, "targets": [{"id": 9, "title": "Other"}], "issue": False,
"reason": "Retire family idea in Other, but this session is working in Home."}).encode()
def _home(tmp_path):
home = tmp_path / "home"
home.mkdir()
subprocess.run(["git", "init", "-q"], cwd=home, check=True)
subprocess.run(["git", "remote", "add", "origin", HOME_URL], cwd=home, check=True)
return home
def _grimoire_write(home, call="toolu_f"):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PreToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188, "why": "x"}}
def _ran(home, call):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PostToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188}, "tool_response": {}}
def test_a_fence_ask_is_reported_and_the_run_after_a_yes_is_matched_to_it(tmp_path):
need_tools("git")
home = _home(tmp_path)
with http_sink(by_path={"/api/plugin/write-scope": ASK}) as (port, seen):
out = _run(FENCE, tmp_path, port, _grimoire_write(home), CLAUDE_PROJECT_DIR=str(home))
assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "ask"
# Another call ran in between: not the one asked about.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_other"))
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
# Matched once; the same id again reports nothing.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
assert _stops(seen) == [{"session_id": "s-gate", "gate": "fence", "outcome": "asked",
"tool": "retire_family_idea", "rule_id": None,
"at": "retire_family_idea", "target": "9", "call_id": "toolu_f"}]
ran = [json.loads(e["_body"]) for e in seen if e["_path"] == RAN]
assert ran == [{"session_id": "s-gate", "call_id": "toolu_f"}]
def test_with_no_ask_pending_the_after_call_hook_sends_nothing(tmp_path):
with http_sink() as (port, seen):
out = _run(FENCE_RAN, tmp_path, port, _ran(tmp_path, "toolu_x"))
assert out == "" and seen == []
def test_the_after_call_hook_is_registered_only_after_calls_and_on_the_fenced_tools():
"""It must never run before a call: it has nothing to decide there, and the
fence itself is what answers a PreToolUse."""
hooks = json.loads((HOOKS / "hooks.json").read_text())["hooks"]
def matchers(event):
return [m.get("matcher") for m in hooks.get(event, [])
for h in m["hooks"] if "grimoire_fence_ran.sh" in h["command"]]
fence_pre = [m.get("matcher") for m in hooks["PreToolUse"]
for h in m["hooks"] if "grimoire_project_fence.sh" in h["command"]]
assert matchers("PreToolUse") == []
assert matchers("PostToolUse") == fence_pre
# ── the reply hold ───────────────────────────────────────────────────────
def _transcript(tmp_path, reply):
lines = [
{"type": "user", "message": {"role": "user", "content": "is it finished?"}},
{"type": "assistant", "message": {"content": [{"type": "text", "text": reply}]}},
]
path = tmp_path / "t.jsonl"
path.write_text("\n".join(json.dumps(x, separators=(",", ":")) for x in lines) + "\n")
return path
def _stop(tmp_path, transcript):
return {"session_id": "s-gate", "transcript_path": str(transcript), "cwd": str(tmp_path),
"hook_event_name": "Stop", "stop_hook_active": False}
def test_each_rule_that_holds_a_reply_is_reported_with_where_it_was_reached(tmp_path):
held = json.dumps({"reason": "Held for one read.", "rule_ids": [11, 40],
"rule_at": ["reply.report", "reply_rule"],
"moments": ["reply.report"]}).encode()
with http_sink(by_path={"/api/plugin/reply-rules": held}) as (port, seen):
out = _run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done.")))
assert json.loads(out)["decision"] == "block"
assert [(s["gate"], s["outcome"], s["tool"], s["rule_id"], s["at"]) for s in _stops(seen)] == [
("reply", "stopped", "reply", 11, "reply.report"),
("reply", "stopped", "reply", 40, "reply_rule"),
]
def test_a_section_hold_names_no_rule_and_reports_no_gate_stop(tmp_path):
"""The completion-section check has its own record (`report_check`)."""
sections = b'{"reason":"Add the sections.","rule_ids":[],"moments":[],"report_check":"blocked"}'
with http_sink(by_path={"/api/plugin/reply-rules": sections}) as (port, seen):
_run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done.")))
assert _stops(seen) == []