CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
A rule is in force at a moment of a session when it was delivered there. Each (session, rule, place) now carries at most one verdict (rule_adherence, migration 0134): followed, departed, broken or not applicable, with where it came from: - an enforce rule refusing the act: followed, recorded by the moment arm, and never replaced; - the session's own rule_outcome (applied, departed) and rule_misfired calls, which the plugin's outcome hook now also posts with the session id (/api/plugin/rule-verdict) onto the delivery being answered; - a transcript review: adherence_to_judge lists what has no verdict yet, by session, and judge_adherence records verdicts with their evidence. rule_adherence (MCP) and /api/retrieval/adherence give the readout: sessions in force, opened and each verdict per rule and per place. Settings > Moments shows it in a "Were they followed" panel, beside each moment's delivered and opened counts, and per rule inside each moment. Verdicts are pruned with their deliveries and left out of backups like them. Plugin 2026.11.23.2227. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
206 lines
9.6 KiB
Python
206 lines
9.6 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_a_refused_act_is_recorded_as_the_rule_kept_there():
|
|
# An enforce rule that refuses the act kept the rule at that moment by
|
|
# construction; a hold, which lets the act go on after a read, does not.
|
|
refusals = MagicMock()
|
|
guard = _r(2, enforcement="enforce")
|
|
note = _r(3, enforcement="hold")
|
|
deliver = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
|
|
result = await rp.run_moment_arm(
|
|
deliver, rp.RuleMoment(user_id=1, query="", project_id=2),
|
|
io=rp.MomentIO(lookup=AsyncMock(return_value=[(guard, "work.deliver"), (note, "work.deliver")]),
|
|
record_rule_surfaced=MagicMock(), record_refusal=refusals),
|
|
board=rt.Board(),
|
|
)
|
|
assert result.decision["kind"] == "enforce"
|
|
refusals.assert_called_once_with(1, [(2, "work.deliver", "at work.deliver, reached by `git push`")])
|
|
|
|
refusals.reset_mock()
|
|
await rp.run_moment_arm(
|
|
deliver, rp.RuleMoment(user_id=1, query="", project_id=2),
|
|
io=rp.MomentIO(lookup=AsyncMock(return_value=[(note, "work.deliver")]),
|
|
record_rule_surfaced=MagicMock(), record_refusal=refusals),
|
|
board=rt.Board(),
|
|
)
|
|
refusals.assert_not_called()
|
|
|
|
|
|
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
|