Files
FabledGrimoire/tests/test_integration_rule_triggers.py
T
bvandeusenandClaude Opus 5.5 c9e64450ba
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
feat(7728): typed triggers on a rule, and a rule says its piece once per session
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>
2026-11-22 18:24:39 -05:00

108 lines
4.5 KiB
Python

"""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)