feat(7731): enforced rules refuse the act, only hold rules hold, and the shape question rides the next prompt
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m45s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Skipped

- A rule set to enforce, reached by a mount or a trigger, refuses the tool
  call in its own words every time (`act_decision`, `/moment` returns
  `decision`, grimoire_moment.sh denies). Opening it does not lift it.
- A rule set to hold denies the call once until read, under the act
  checkpoint's per-rule and per-session guard; file writes are never held.
- The reply hold, the reply backstop and the act checkpoint hold only on rules
  declared hold or enforce (`rule_order.holds`). An inform rule is a line
  beside the work.
- The prompt arm leaves rules that arrive at an act (mounted on a non-reply
  moment, or with a tool/path/command trigger) to that act.
- The end-of-turn shape check no longer blocks: its note is kept for the next
  prompt, carried as `carry` into the one fitted payload, and the stop after
  that prompt records whether the lines were judged (noted /
  judged_after_note / left_after_note).
- Rule editor and list copy say what hold and enforce now do. Plugin
  2026.11.23.0005.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 00:22:56 -05:00
co-authored by Claude Opus 5.5
parent 6b4c24e336
commit 7d46ce0229
23 changed files with 644 additions and 170 deletions
+136 -5
View File
@@ -7,6 +7,8 @@ tests/test_integration_rule_moments.py. These pin what is decided above it:
- a rule the session was already shown is cited, not repeated, and only the
fresh ones are recorded, each with its moment;
- every door fails open;
- a rule set to enforce refuses the act every time, one set to hold holds it
once for a read (never a write), and an `inform` rule only sits beside it;
- the plugin is told which tools can reach anything, and nothing more;
- every Grimoire tool the shipped mappings name carries the attach, and the
hook and the route agree on every name between them.
@@ -238,7 +240,7 @@ async def test_the_route_reads_the_event_and_the_ledger():
resp = await routes.moment.__wrapped__()
body = await resp.get_json()
assert body == {"context": "a line", "rule_ids": [5], "moments": ["work.deliver"],
"shape_keys": []}
"shape_keys": [], "decision": {}}
args, kw = deliver.await_args
assert args == (7, "Bash", {"command": "git push"})
assert kw == {"project_id": 3, "exclude": frozenset({9}), "held": frozenset({4})}
@@ -252,7 +254,7 @@ async def test_the_route_answers_an_empty_event_with_nothing():
g.user = SimpleNamespace(id=7)
resp = await routes.moment.__wrapped__()
assert await resp.get_json() == {"context": "", "rule_ids": [], "moments": [],
"shape_keys": []}
"shape_keys": [], "decision": {}}
def test_both_routes_are_on_the_app():
@@ -296,10 +298,18 @@ def test_the_hook_leaves_grimoires_own_tools_to_their_responses():
assert "mcp__*grimoire*__*) exit 0" in HOOK.read_text()
def test_the_hook_never_returns_a_permission_decision():
"""A mount is a recall aid: it informs the act and never holds it."""
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
emitted outside the guard is a session the same rule can stop on every
call."""
code = [ln for ln in HOOK.read_text().splitlines() if not ln.lstrip().startswith("#")]
assert not any("permissionDecision" in ln or "grimoire_json_deny" in ln for ln in code)
denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln]
assert len(denies) == 2, "one deny for enforce, one for hold"
enforce, hold = denies
assert "enforce)" in "\n".join(code[max(0, enforce - 3):enforce])
assert "grimoire_checkpoint_allowed" in "\n".join(code[max(0, hold - 4):hold])
assert "permissionDecision" not in "\n".join(code), "decisions go through grimoire_json_deny"
def _hook(tmp_path, port, tool="Bash", command="git push origin dev", session="s-moment"):
@@ -496,3 +506,124 @@ def test_the_hook_carries_the_shape_ledger_between_calls(tmp_path):
assert "shapes_seen" not in moment_calls[0]
assert moment_calls[1]["shapes_seen"] == ["asks"]
# ── what the act itself is told ─────────────────────────────────────────
def _forced(rid, enforcement, kind="rule"):
return fake_rule(id=rid, title=f"rule {rid}", kind=kind, enforcement=enforcement,
statement=f"The words of rule {rid}.", when_to_apply="when it applies")
async def _arm(pairs, **moment):
io = rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock())
return await rp.run_moment_arm(PUSH, _moment(**moment), io=io)
async def test_a_rule_set_to_enforce_refuses_the_act_in_its_own_words():
result = await _arm([(_forced(5, "inform"), "work.deliver"),
(_forced(6, "enforce"), "work.deliver")])
d = result.decision
assert d["kind"] == "enforce" and d["rule_ids"] == [6]
assert "The words of rule 6." in d["reason"]
assert "at work.deliver, reached by `git push`" in d["reason"]
assert 'rule_misfired(6, "work.deliver", why)' in d["reason"]
# The lines still go out beside it, for a door that shows them.
assert result.lines
async def test_opening_an_enforced_rule_does_not_lift_it():
result = await _arm([(_forced(6, "enforce"), "work.deliver")], held=frozenset({6}),
exclude=frozenset({6}))
assert result.decision["kind"] == "enforce"
async def test_a_rule_set_to_hold_holds_until_the_session_opens_it():
pairs = [(_forced(7, "hold"), "work.deliver")]
held = (await _arm(pairs)).decision
assert held["kind"] == "hold" and held["rule_ids"] == [7]
assert "get_rule(7)" in held["reason"] and "re-submit" in held["reason"]
assert (await _arm(pairs, held=frozenset({7}))).decision == {}
async def test_an_inform_rule_and_a_preference_never_stop_the_act():
pairs = [(_forced(8, "inform"), "work.deliver"),
(_forced(9, "enforce", kind="preference"), "work.deliver")]
assert (await _arm(pairs)).decision == {}
async def _deliver_for(tool, decision):
from grimoire.services import moment_actions as ma
with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \
patch.object(md, "_board", AsyncMock(return_value=None)), \
patch.object(md, "deliver_moments",
AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))):
_reached, result = await _REAL_DELIVER(1, tool, {})
return result.decision
async def test_a_write_is_refused_by_an_enforced_rule_but_never_held():
hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"}
enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"}
assert await _deliver_for("Edit", hold) == {}
assert await _deliver_for("Bash", hold) == hold
assert await _deliver_for("Write", enforce) == enforce
def _decided(tmp_path, decision, session="s-decide"):
replies = dict(TOOLS)
replies["/api/plugin/moment"] = json.dumps(
{"context": "a line beside it", "rule_ids": [], "moments": ["work.deliver"],
"decision": decision}).encode()
with http_sink(by_path=replies) as (port, _seen):
return [_hook(tmp_path, port, session=session) for _ in range(2)]
def test_the_hook_refuses_an_enforced_act_every_time(tmp_path):
outs = _decided(tmp_path, {"kind": "enforce", "rule_ids": [6], "reason": "Not run: rule 6"})
for out in outs:
body = json.loads(out)["hookSpecificOutput"]
assert body["permissionDecision"] == "deny"
assert body["permissionDecisionReason"] == "Not run: rule 6"
def test_the_hook_holds_an_act_once_then_lets_it_through_with_its_lines(tmp_path):
first, second = _decided(tmp_path, {"kind": "hold", "rule_ids": [7], "reason": "Read rule 7"})
assert json.loads(first)["hookSpecificOutput"]["permissionDecision"] == "deny"
after = json.loads(second)["hookSpecificOutput"]
assert "permissionDecision" not in after
assert after["additionalContext"] == "a line beside it"
# ── reminders wait for the act ──────────────────────────────────────────
async def test_the_prompt_arm_leaves_a_rule_that_arrives_at_an_act_to_the_act():
hits = [(0.9, _forced(21, "inform")), (0.89, _forced(22, "inform"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
moment = rp.RuleMoment(user_id=1, query="merge it", project_id=2, where="to this request",
elsewhere=frozenset({21}))
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert result.shown_rule_ids == [22]
async def test_a_rule_arrives_at_an_act_by_a_mount_off_the_reply_or_an_act_trigger():
from grimoire.services import rule_triggers
lookup = AsyncMock(return_value=[(_forced(31, "inform"), "work.deliver")])
scoped = [
(_forced(32, "inform"), [rule_triggers.Trigger("path", "alembic/**")]),
(_forced(33, "inform"), [rule_triggers.Trigger("keyword", "let me know")]),
(_forced(34, "inform"), [rule_triggers.Trigger("command", "git push", "work.deliver")]),
]
with patch.object(moment_actions, "list_mappings", AsyncMock(return_value=[])), \
patch.object(rulebooks, "rules_on_moments", lookup), \
patch.object(rule_triggers, "_in_scope", AsyncMock(return_value=scoped)):
routed = await md.routed_to_acts(1, 2)
# A keyword can match a reply; a trigger scoped to a moment is that moment's mount.
assert routed == frozenset({31, 32})
moments = lookup.await_args.args[1]
assert moments and not any(m.startswith("reply.") for m in moments)