Files
FabledGrimoire/tests/test_rule_triggers.py
T
bvandeusenandClaude Opus 5.5 738bd24d6e
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Plugin hooks (push) Failing after 19s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m31s
CI & Build / integration (push) Successful in 2m18s
CI & Build / Build & push image (push) Canceled after 27s
fix(7733): a rule with triggers holds or refuses only the acts they match
Rules 2, 4, 10 and 153 are set to hold and mounted on work.deliver. A
push to dev therefore stopped four times in a row, once for each of them,
although none of them governs a push to dev: their triggers (git push
origin main, git tag, pytest, pull_request_write) name the acts they do
govern.

A rule that has triggers now stops an act only when one of them matched it.
Reached by its moment alone, it is a line beside the work. A rule with no
triggers still holds wherever it is mounted, because the mount is all that
says where it applies. A mounted rule whose unscoped trigger also matched
now counts as reached by the trigger, so it ranks as triggered and may
stop the act.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:53:36 -05:00

180 lines
8.3 KiB
Python

"""A rule's triggers: what each kind matches, what is refused, and how the
moment arm reads the board they build."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order
from grimoire.services import rule_triggers as rt
from grimoire.services.rule_triggers import Trigger
def T(kind, pattern, moment=""):
return rt.require_trigger({"kind": kind, "pattern": pattern, "moment": moment})
# ── matching, kind by kind ──────────────────────────────────────────────
@pytest.mark.parametrize(("pattern", "path", "hit"), [
("alembic/versions/*.py", "/repo/alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "/repo/alembic/versions/sub/0130.py", False),
("frontend/**/*.vue", "/r/frontend/src/components/A.vue", True),
("frontend/**/*.vue", "/r/frontend/A.vue", True),
("*.md", "/r/docs/README.md", True),
("/etc/*.conf", "/etc/nginx.conf", True),
("/etc/*.conf", "/srv/etc/nginx.conf", False),
("versions/*.py", "/repo/myversions/x.py", False),
])
def test_a_path_glob_matches_from_any_directory_unless_anchored(pattern, path, hit):
assert rt.matches(T("path", pattern), "Write", {"file_path": path}) is hit
def test_a_path_trigger_reads_every_file_field_and_needs_an_act():
trig = T("path", "*.ipynb")
assert rt.matches(trig, "NotebookEdit", {"notebook_path": "/a/b.ipynb"})
assert rt.matches(trig, "Glob", {"path": "/a/b.ipynb"})
assert not rt.matches(trig, None, None, text="b.ipynb")
@pytest.mark.parametrize(("command", "hit"), [
("git push origin dev", True),
("make test && git push", True),
("FOO=1 git push", True),
("git pushx", False),
("echo git push", False),
])
def test_a_command_trigger_matches_the_head_of_any_segment(command, hit):
assert rt.matches(T("command", "git push"), "Bash", {"command": command}) is hit
def test_a_tool_trigger_matches_the_key_with_or_without_a_server_prefix():
assert rt.matches(T("tool", "update_task"), "mcp__plugin_grimoire_grimoire__update_task", {})
assert rt.matches(T("tool", "*_task"), "mcp__x__create_task", {})
assert not rt.matches(T("tool", "update_task"), "mcp__x__get_task", {})
def test_a_keyword_matches_a_whole_word_in_what_the_act_writes_or_the_reply():
trig = T("keyword", "migration")
assert rt.matches(trig, "Edit", {"new_string": "add a Migration for it"})
assert rt.matches(trig, None, None, text="this migration is done")
assert not rt.matches(trig, "Edit", {"new_string": "migrations"})
assert not rt.matches(trig, "Write", {"file_path": "migration.py"})
# ── validation ──────────────────────────────────────────────────────────
def test_validation_normalises_and_refuses_what_could_never_fire():
assert T("tool", "mcp__x__Update_Task") == Trigger("tool", "update_task")
assert T("command", " Git Push ") == Trigger("command", "git push")
assert T("path", "src/**", " Work.Change ") == Trigger("path", "src/**", "work.change")
for bad in ({"kind": "regex", "pattern": "x"}, {"kind": "path", "pattern": " "},
{"kind": "path", "pattern": "x", "moment": "work.finished"}, "path:x"):
with pytest.raises(ValueError):
rt.require_trigger(bad)
def test_a_set_is_deduplicated_capped_and_none_leaves_it_alone():
assert rt.require_triggers(None) is None
assert rt.require_triggers([]) == []
same = {"kind": "path", "pattern": "a/*"}
assert rt.require_triggers([same, same]) == [Trigger("path", "a/*")]
with pytest.raises(ValueError, match="at most"):
rt.require_triggers([{"kind": "keyword", "pattern": f"w{i}"} for i in range(rt.TRIGGERS_MAX + 1)])
def test_each_kind_names_the_tools_the_catch_all_hook_must_forward():
assert rt.tools_for(T("tool", "update_task")) == {"update_task"}
assert rt.tools_for(T("tool", "*_task")) == set()
assert rt.tools_for(T("command", "git push")) == {"bash"}
assert "write" in rt.tools_for(T("path", "a/*")) and "edit" in rt.tools_for(T("path", "a/*"))
# ── the board ───────────────────────────────────────────────────────────
def _r(rid, enforcement="inform"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience="normal")
async def test_the_board_gates_a_conditional_mount_the_act_missed(monkeypatch):
scoped = _r(1)
free = _r(2)
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(scoped, [T("path", "alembic/**", "work.change")]),
(free, [T("command", "git push"), T("keyword", "deploy")]),
]))
edit = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/src/app.py"})
assert edit.gated == {(1, "work.change")} and not edit.matched and not edit.fired
mig = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/alembic/v/1.py"})
assert mig.matched == {(1, "work.change")} and not mig.gated
push = await rt.board(1, 2, tool="Bash", tool_input={"command": "git push"})
assert [(r.id, t.kind) for r, t in push.fired] == [(2, "command")]
# ── the arm reading it ──────────────────────────────────────────────────
CHANGE = [{"moment": "work.change", "tool": "Edit", "match": "", "via": "default"}]
async def _arm(pairs, board, reached=CHANGE, **kw):
return await rp.run_moment_arm(
reached, rp.RuleMoment(user_id=1, query="", project_id=2, **kw),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
board=board,
)
async def test_a_gated_mount_is_not_delivered_and_a_met_one_ranks_as_triggered():
pairs = [(_r(1), "work.change"), (_r(2), "work.change")]
result = await _arm(pairs, rt.Board(gated={(1, "work.change")}))
assert result.shown_rule_ids == [2]
result = await _arm(pairs, rt.Board(matched={(2, "work.change")}))
assert result.shown_rule_ids == [2, 1]
async def test_an_unscoped_trigger_delivers_with_no_moment_reached_and_says_what_fired():
board = rt.Board(fired=[(_r(7), T("path", "alembic/**"))])
result = await _arm([], board, reached=[])
assert result.shown_rule_ids == [7]
assert "path `alembic/**`" in result.lines[0]
async def test_a_rule_both_mounted_and_fired_is_delivered_once():
board = rt.Board(fired=[(_r(1), T("command", "git push"))])
result = await _arm([(_r(1), "work.change")], board)
assert result.shown_rule_ids == [1]
async def test_a_rule_with_triggers_stops_only_the_acts_they_match():
# Rule 2 holds pushes to main; mounted on work.deliver it reaches every
# push, and only its own trigger may make one wait.
guard = _r(2, enforcement="hold")
pairs = [(guard, "work.deliver")]
deliver = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
to_dev = rt.Board(triggered={2})
result = await _arm(pairs, to_dev, reached=deliver)
assert result.decision == {} and result.shown_rule_ids == [2]
to_main = rt.Board(triggered={2}, fired=[(guard, T("command", "git push origin main"))])
result = await _arm(pairs, to_main, reached=deliver)
assert result.decision["kind"] == "hold" and result.decision["rule_ids"] == [2]
# With no trigger of its own, the mount is all that says where it applies.
result = await _arm(pairs, rt.Board(), reached=deliver)
assert result.decision["kind"] == "hold"
async def test_the_board_lists_every_rule_that_has_a_trigger(monkeypatch):
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(_r(1), [T("path", "alembic/**", "work.change")]),
(_r(2), [T("command", "git push origin main")]),
(_r(3), []),
]))
out = await rt.board(1, 2, tool="Bash", tool_input={"command": "ls"})
assert out.triggered == {1, 2}
def test_triggered_outranks_mounted_in_the_one_order():
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE