Files
FabledGrimoire/tests/test_rule_order.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

175 lines
6.7 KiB
Python

"""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
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order as ro
def _r(rid, enforcement="inform", salience="normal"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience=salience)
def _ids(cands):
return [c.rule.id for c in ro.ordered(cands)]
def test_a_rule_that_stops_the_work_outranks_any_line_beside_it():
cands = [ro.Candidate(_r(1), similarity=0.95),
ro.Candidate(_r(2, "hold"), similarity=0.71),
ro.Candidate(_r(3, "enforce"), similarity=0.70)]
assert _ids(cands) == [3, 2, 1]
def test_salience_decides_between_rules_of_the_same_enforcement():
cands = [ro.Candidate(_r(1, salience="low")), ro.Candidate(_r(2)),
ro.Candidate(_r(3, salience="high"))]
assert _ids(cands) == [3, 2, 1]
def test_a_trigger_outranks_a_mount_and_a_mount_outranks_a_resemblance():
cands = [ro.Candidate(_r(1), specificity=ro.BY_RESEMBLANCE, similarity=0.9),
ro.Candidate(_r(2), specificity=ro.BY_MOUNT),
ro.Candidate(_r(3), specificity=ro.BY_TRIGGER)]
assert _ids(cands) == [3, 2, 1]
def test_a_first_mention_outranks_a_reminder_at_the_same_rank():
cands = [ro.Candidate(_r(1), seen=True), ro.Candidate(_r(2))]
assert _ids(cands) == [2, 1]
def test_history_breaks_the_tie_before_similarity_does():
cands = [ro.Candidate(_r(1), opened_rate=0.1, similarity=0.9),
ro.Candidate(_r(2), opened_rate=0.8, similarity=0.7),
ro.Candidate(_r(3), similarity=0.99)]
# Unknown history ranks between them, as an even chance.
assert _ids(cands) == [2, 3, 1]
def test_ties_keep_the_arms_own_order():
cands = [ro.Candidate(_r(i)) for i in (4, 2, 9)]
assert _ids(cands) == [4, 2, 9]
def test_a_rule_with_no_declared_fields_reads_as_inform_normal():
bare = SimpleNamespace(id=1)
assert ro.order_key(ro.Candidate(bare))[:2] == (2, 1)
@pytest.mark.parametrize(("delivered", "opened", "rate"), [(0, 0, 0.5), (1, 1, 2 / 3), (10, 0, 1 / 12)])
def test_the_open_rate_is_smoothed(delivered, opened, rate):
assert ro.opened_rate(delivered, opened) == pytest.approx(rate)
PUSH = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
@pytest.mark.asyncio
async def test_the_moment_arm_delivers_in_that_order_before_its_cap():
pairs = [(_r(i), "work.deliver") for i in range(1, 11)] + [(_r(99, "hold"), "work.deliver")]
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
)
# The holding rule was mounted last and still leads; the cap cut ordinary ones.
assert result.shown_rule_ids[0] == 99
assert len(result.shown_rule_ids) == rp.MOMENT_RULE_LIMIT
@pytest.mark.asyncio
async def test_the_semantic_arm_delivers_in_that_order():
hits = [(0.91, _r(1)), (0.74, _r(2, "hold"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
result = await rp.run_rule_arm(
rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"),
floor=0.5, budget=5, io=io,
)
assert result.shown_rule_ids[:2] == [2, 1]
@pytest.mark.asyncio
async def test_each_line_shown_is_recorded_as_a_delivery_with_its_form():
recorded = MagicMock()
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2, exclude=frozenset({6})),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
record_delivery=recorded),
)
_uid, _sid, source, lines = recorded.call_args.args
assert source == rp.MOMENT_RULE_SOURCE
assert lines == [(5, "work.finish", "full"), (6, "work.finish", "repeat")]
@pytest.mark.asyncio
async def test_history_reorders_rules_of_equal_rank_and_a_failed_read_is_unknown():
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
async def history(_uid, _pairs):
return {6: 0.9, 5: 0.1}
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
history=history),
)
assert result.shown_rule_ids == [6, 5]
async def broken(_uid, _pairs):
raise RuntimeError("no database")
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
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]