feat(7728): typed triggers on a rule, and a rule says its piece once per session
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
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>
This commit is contained in:
@@ -273,6 +273,23 @@ def _no_moment_delivery(request):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_rule_triggers(request):
|
||||
"""Stub the database read behind a rule's triggers.
|
||||
|
||||
Every act the moment door sees checks the in-scope triggers, which is a
|
||||
read; stubbed to "no rule carries a trigger" so a unit test of mounts sees
|
||||
mounts only. The matching itself is pure and tested unstubbed in
|
||||
tests/test_rule_triggers.py; the read against Postgres in
|
||||
tests/test_integration_rule_triggers.py, which this skips.
|
||||
"""
|
||||
if request.node.get_closest_marker("integration"):
|
||||
yield
|
||||
return
|
||||
with patch("grimoire.services.rule_triggers._in_scope", AsyncMock(return_value=[])):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_rule_arm():
|
||||
"""Stub the write-path hint's standing-RULES arm.
|
||||
|
||||
+1
-1
@@ -310,7 +310,7 @@ def plain_rule_detail():
|
||||
stubbing the seam slightly differently is a test asserting something
|
||||
slightly different than it appears to.
|
||||
"""
|
||||
async def _detail(_uid, rule, _system_ids=None, _moments=None):
|
||||
async def _detail(_uid, rule, _system_ids=None, _moments=None, **_kw):
|
||||
return rule.to_dict()
|
||||
return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail)
|
||||
|
||||
|
||||
@@ -105,3 +105,23 @@ async def test_old_deliveries_are_pruned():
|
||||
await s.commit()
|
||||
assert await rule_deliveries.prune() >= 1
|
||||
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
|
||||
|
||||
|
||||
async def test_a_rule_retires_after_its_reminder_and_a_full_line_re_arms_it():
|
||||
uid = await _user()
|
||||
rule_deliveries.bind_session("s-life")
|
||||
try:
|
||||
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
|
||||
assert await rule_deliveries.retired(uid, [RULE]) == set()
|
||||
await asyncio.sleep(0.01)
|
||||
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "repeat")])
|
||||
assert await rule_deliveries.retired(uid, [RULE, OTHER]) == {RULE}
|
||||
await asyncio.sleep(0.01)
|
||||
# The ledger forgot it (a compaction): the next line is full, and re-arms it.
|
||||
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
|
||||
assert await rule_deliveries.retired(uid, [RULE]) == set()
|
||||
# Another session's reminder retires nothing here.
|
||||
await _record(uid, "s-other", "moment_rule", [(OTHER, "work.finish", "repeat")])
|
||||
assert await rule_deliveries.retired(uid, [OTHER]) == set()
|
||||
finally:
|
||||
rule_deliveries.bind_session("")
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Real-Postgres tests for `rule_triggers` (migration 0130): stored through the
|
||||
rule's own write path, read back on the record, scoped like every rule read,
|
||||
and checked against an act by the moment door."""
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.rulebook import Rulebook, rule_triggers
|
||||
from grimoire.services import moment_delivery
|
||||
from grimoire.services import rule_triggers as rt
|
||||
from grimoire.services import rulebooks as rulebooks_svc
|
||||
from tests.helpers import ensure_user
|
||||
|
||||
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||
|
||||
OWNER_USERNAME = "rule_trigger_owner"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def topic_id():
|
||||
# Purged at setup, not teardown: the write path's detached embedding task
|
||||
# would deadlock against a teardown deleting the rulebook.
|
||||
async with async_session() as s:
|
||||
owner = await ensure_user(s, OWNER_USERNAME)
|
||||
uid = owner.id
|
||||
await s.commit()
|
||||
for book in (await s.execute(
|
||||
select(Rulebook).where(Rulebook.owner_user_id == uid)
|
||||
)).scalars().all():
|
||||
await s.delete(book)
|
||||
await s.commit()
|
||||
book = await rulebooks_svc.create_rulebook(uid, "Trigger fixtures")
|
||||
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
|
||||
return uid, topic.id
|
||||
|
||||
|
||||
async def _rule(uid, topic, title, triggers, moments=None):
|
||||
rule = await rulebooks_svc.create_rule(
|
||||
topic_id=topic, user_id=uid, title=title, statement="s",
|
||||
when_to_apply="when the fixture's act happens",
|
||||
)
|
||||
return await rulebooks_svc.rule_detail(
|
||||
uid, rule, None, moments, triggers=rt.require_triggers(triggers),
|
||||
)
|
||||
|
||||
|
||||
async def test_triggers_are_stored_with_the_rule_and_replaced_as_a_set(topic_id):
|
||||
uid, topic = topic_id
|
||||
data = await _rule(uid, topic, "Migrations are reviewed", [
|
||||
{"kind": "path", "pattern": "alembic/versions/*.py"},
|
||||
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
|
||||
])
|
||||
assert data["triggers"] == [
|
||||
{"kind": "path", "pattern": "alembic/versions/*.py"},
|
||||
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
|
||||
]
|
||||
rule = await rulebooks_svc.get_rule(data["id"], uid)
|
||||
again = await rulebooks_svc.rule_detail(uid, rule, triggers=[])
|
||||
assert "triggers" not in again
|
||||
# None leaves them alone.
|
||||
await rulebooks_svc.rule_detail(uid, rule, triggers=rt.require_triggers([{"kind": "tool", "pattern": "bash"}]))
|
||||
kept = await rulebooks_svc.rule_detail(uid, rule)
|
||||
assert kept["triggers"] == [{"kind": "tool", "pattern": "bash"}]
|
||||
|
||||
|
||||
async def test_an_unknown_kind_is_refused_by_the_database(topic_id):
|
||||
uid, topic = topic_id
|
||||
data = await _rule(uid, topic, "Raw kind", [])
|
||||
async with async_session() as s:
|
||||
with pytest.raises(IntegrityError):
|
||||
await s.execute(rule_triggers.insert().values(
|
||||
rule_id=data["id"], kind="regex", pattern="x", moment="",
|
||||
))
|
||||
await s.commit()
|
||||
|
||||
|
||||
async def test_an_act_fires_an_unscoped_trigger_with_no_moment_reached(topic_id):
|
||||
uid, topic = topic_id
|
||||
data = await _rule(uid, topic, "Notebooks keep outputs cleared",
|
||||
[{"kind": "path", "pattern": "*.ipynb"}])
|
||||
reached, result = await moment_delivery.deliver_for_act(
|
||||
uid, "Read", {"file_path": "/r/analysis/one.ipynb"},
|
||||
)
|
||||
assert data["id"] in result.shown_rule_ids
|
||||
assert any("path `*.ipynb`" in line for line in result.lines)
|
||||
_, quiet = await moment_delivery.deliver_for_act(uid, "Read", {"file_path": "/r/a.py"})
|
||||
assert data["id"] not in quiet.shown_rule_ids
|
||||
|
||||
|
||||
async def test_a_conditional_mount_arrives_only_when_the_act_meets_it(topic_id):
|
||||
uid, topic = topic_id
|
||||
data = await _rule(uid, topic, "Schema changes get a migration",
|
||||
[{"kind": "path", "pattern": "models/*.py", "moment": "work.change"}],
|
||||
moments=["work.change"])
|
||||
_, missed = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/views/a.py"})
|
||||
assert data["id"] not in missed.shown_rule_ids
|
||||
_, met = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/models/a.py"})
|
||||
assert data["id"] in met.shown_rule_ids
|
||||
|
||||
|
||||
async def test_the_reachable_tools_include_what_a_trigger_can_match(topic_id):
|
||||
uid, topic = topic_id
|
||||
await _rule(uid, topic, "Task closes carry a report",
|
||||
[{"kind": "tool", "pattern": "update_task"}])
|
||||
assert "update_task" in await moment_delivery.reachable_tools(uid)
|
||||
@@ -103,7 +103,7 @@ async def test_an_unknown_moment_is_refused_before_anything_is_written():
|
||||
async def test_the_door_hands_rule_detail_the_normalised_moments():
|
||||
seen = {}
|
||||
|
||||
async def detail(_uid, rule, _system_ids=None, moments=None):
|
||||
async def detail(_uid, rule, _system_ids=None, moments=None, **_kw):
|
||||
seen["moments"] = moments
|
||||
return rule.to_dict()
|
||||
|
||||
@@ -119,7 +119,7 @@ async def test_the_door_hands_rule_detail_the_normalised_moments():
|
||||
async def test_omitting_moments_leaves_the_mounts_alone():
|
||||
seen = {}
|
||||
|
||||
async def detail(_uid, rule, _system_ids=None, moments="unset"):
|
||||
async def detail(_uid, rule, _system_ids=None, moments="unset", **_kw):
|
||||
seen["moments"] = moments
|
||||
return rule.to_dict()
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""The one delivery order, key by key, and both rule arms reading it."""
|
||||
import dataclasses
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -129,3 +130,45 @@ async def test_history_reorders_rules_of_equal_rank_and_a_failed_read_is_unknown
|
||||
history=broken),
|
||||
)
|
||||
assert result.shown_rule_ids == [5, 6]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_repeat_already_reminded_once_is_retired_unless_it_holds_or_was_opened():
|
||||
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish"), (_r(7, "hold"), "work.finish"),
|
||||
(_r(8), "work.finish")]
|
||||
asked = {}
|
||||
|
||||
async def retired(_uid, ids):
|
||||
asked["ids"] = sorted(ids)
|
||||
return set(ids)
|
||||
|
||||
result = await rp.run_moment_arm(
|
||||
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2,
|
||||
exclude=frozenset({6, 7, 8}), held=frozenset({8})),
|
||||
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
|
||||
retired=retired),
|
||||
)
|
||||
# Only the unopened, non-holding repeat is asked about, and only it goes.
|
||||
assert asked["ids"] == [6]
|
||||
assert sorted(result.shown_rule_ids) == [5, 7, 8]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_semantic_arm_retires_the_same_way_and_a_failed_read_retires_nothing():
|
||||
hits = [(0.91, _r(1)), (0.80, _r(2))]
|
||||
|
||||
async def retired(_uid, ids):
|
||||
return {2}
|
||||
|
||||
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
|
||||
record_rule_surfaced=MagicMock(), retired=retired)
|
||||
moment = rp.RuleMoment(user_id=1, query="q", project_id=2, where="here", exclude=frozenset({2}))
|
||||
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
|
||||
assert result.shown_rule_ids == [1]
|
||||
|
||||
async def broken(_uid, ids):
|
||||
raise RuntimeError("no database")
|
||||
|
||||
io = dataclasses.replace(io, retired=broken)
|
||||
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
|
||||
assert sorted(result.shown_rule_ids) == [1, 2]
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""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
|
||||
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
|
||||
"""The bump is the point of the test — a payload section added without
|
||||
moving the version produces backups that are structurally different and
|
||||
indistinguishable by inspection."""
|
||||
assert backup.BACKUP_VERSION == 28
|
||||
assert backup.BACKUP_VERSION == 29
|
||||
|
||||
|
||||
def _exportable_note(**over):
|
||||
@@ -483,7 +483,7 @@ def test_the_column_guard_covers_every_table_with_a_row_helper():
|
||||
# REAL table names, as _BACKED_UP holds them — not the shorter keys the
|
||||
# payload uses for the same sections. Getting this wrong is what the guard
|
||||
# caught on its own first run.
|
||||
join_tables = {"rule_systems", "rule_moments"}
|
||||
join_tables = {"rule_systems", "rule_moments", "rule_triggers"}
|
||||
covered = set(_column_guard_targets()) | join_tables
|
||||
assert set(backup._BACKED_UP) - covered == set()
|
||||
# And no stale entries: every declaration must name a real target.
|
||||
|
||||
Reference in New Issue
Block a user