feat(8141): every gate that stops a tool call is recorded, with what followed

A rule set to enforce or hold, the act checkpoint and the project fence
stopped work and left no record. The hook that makes each stop now reports
it to POST /api/plugin/gate-stop; the hook decides, not the server, because
the per-rule and per-session caps are kept in the plugin.

- gate_stops table (migration 0138): gate, outcome (stopped / let_through /
  asked), rule, where it was reached, tool, target project, call id.
- An open of the rule stamps the stop as cleared (rule-opened). A fenced
  call that then runs stamps ran: grimoire_fence_ran.sh, a PostToolUse on
  the fenced tools, matches the call id the fence left pending. That is
  the operator's yes.
- A hold or checkpoint the spent session budget lets through is reported
  as let_through; the per-rule once is not.
- The readout: by gate and by rule, stops, cleared by a read, misfired
  (rule_misfired after it), let through by the cap, ran. In
  retrieval_telemetry as `gates`, at /api/retrieval/gate-stops, and on the
  Moments settings page ("When a rule stopped the work").
- act_decision carries `at`, the moment the deciding rule was reached at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 14:12:14 -05:00
co-authored by Claude Opus 5.5
parent 706f49a12a
commit 65f1be80b6
24 changed files with 1128 additions and 13 deletions
+196
View File
@@ -0,0 +1,196 @@
"""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"
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