CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 22s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Skipped
Triggers (migration 0130, table rule_triggers): a rule can name the act it applies to, as a tool, a path glob, a command head or a keyword, checked exactly against the act rather than by resemblance. With no moment a trigger delivers its rule on any matching act, even one that reaches no moment; scoped to a moment, it makes the rule's mount there conditional on the act matching. A triggered line ranks above a mounted one in the delivery order and names the trigger that fired. Writable through every MCP and REST rule door, carried by backup (version 29), and edited in the rule editor under "Acts that trigger it". The plugin's catch-all hook is told which tools a trigger can reach. Lifecycle: a rule's life in a session is one full line, one reminder, then silence. A repeat whose latest delivery in the session was already a reminder is left out of both rule arms. A rule that holds stays armed until it is opened, an opened rule keeps its line, and a full delivery (after a compaction or once the ledger ages it out) re-arms it. Read from the delivery records, so it needs no new plugin ledger. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
153 lines
7.0 KiB
Python
153 lines
7.0 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]
|
|
|
|
|
|
def test_triggered_outranks_mounted_in_the_one_order():
|
|
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE
|