feat(7728): one delivery order for rules, and each delivery recorded with whether it was opened
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 1m59s
CI & Build / Build & push image (push) Skipped

Every rule arm now ranks what it delivers with one function
(services/rule_order.py): enforcement, then salience, then how narrowly
the rule was reached, then first mention before reminder, then the
rule's own open rate at that moment, then similarity. A crowded moment
drops the same rules whichever arm brought them, and a rule that holds
is never cut for a line beside it.

The open rate comes from a new table, rule_deliveries (migration 0129):
one row per rule line a plugin session is shown, full or repeat, with the
open stamped on the latest delivery it followed. The plugin routes bind
the session per request; the prompt, pre-tool and write-path hooks now
send it, and the opened hook reports every open, with its acts only when
no hook had just named the rule. Rows are pruned daily after 180 days.

Also fixes the TypeScript check: the store's list row now carries the
new enforcement field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:13:16 -05:00
co-authored by Claude Opus 5.5
parent 61077752b9
commit 61873b184b
20 changed files with 759 additions and 23 deletions
+107
View File
@@ -0,0 +1,107 @@
"""Real-Postgres tests for `rule_deliveries`: a delivery recorded against a
session, the open stamped on the one it followed, and the history read back."""
import asyncio
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.services import background, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_100_001
OTHER = 9_100_002
async def _user() -> int:
async with async_session() as s:
user = await ensure_user(s, "rule_delivery_owner")
uid = user.id
await s.commit()
await s.execute(delete(RuleDelivery).where(RuleDelivery.user_id == uid))
await s.commit()
return uid
async def _rows(uid: int) -> list[RuleDelivery]:
async with async_session() as s:
return list((await s.execute(
select(RuleDelivery).where(RuleDelivery.user_id == uid).order_by(RuleDelivery.id)
)).scalars().all())
async def _record(uid, sid, source, lines):
rule_deliveries.record(uid, sid, source, lines)
await background.drain()
async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")])
await asyncio.sleep(0.01)
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "repeat")])
await _record(uid, "s-2", "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
rows = await _rows(uid)
opened = [(r.session_id, r.form) for r in rows if r.opened_at is not None]
assert opened == [("s-1", "repeat")]
# A second open with nothing left unopened in the session stamps the earlier one.
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is False
async def test_an_open_with_no_delivery_behind_it_stamps_nothing():
uid = await _user()
assert await rule_deliveries.mark_opened(uid, "s-1", OTHER) is False
assert await rule_deliveries.mark_opened(uid, "", RULE) is False
async def test_without_a_session_nothing_is_recorded():
uid = await _user()
rule_deliveries.bind_session("")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
assert await _rows(uid) == []
async def test_a_bound_session_is_the_one_recorded():
uid = await _user()
rule_deliveries.bind_session("bound s/3")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
# The plugin's filename-safe form, so the raw and safe ids agree.
assert [r.session_id for r in await _rows(uid)] == ["bound_s_3"]
rule_deliveries.bind_session("")
async def test_history_is_the_smoothed_open_rate_at_each_place():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")] * 3
+ [(RULE, "work.deliver", "full"), (OTHER, "work.finish", "full")])
await rule_deliveries.mark_opened(uid, "s-1", RULE) # one of the five RULE rows
history = await rule_deliveries.history(uid, [(RULE, "work.finish"), (OTHER, "work.finish")])
rows = await _rows(uid)
stamped_at = next(r.at for r in rows if r.opened_at is not None)
finish_opened = 1 if stamped_at == "work.finish" else 0
assert history[RULE] == pytest.approx((finish_opened + 1) / (3 + 2))
assert history[OTHER] == pytest.approx(1 / 3)
# A place with no delivery is unknown, not zero.
assert await rule_deliveries.history(uid, [(RULE, "reply.report")]) == {}
async def test_old_deliveries_are_pruned():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")])
async with async_session() as s:
await s.execute(
update(RuleDelivery)
.where(RuleDelivery.user_id == uid, RuleDelivery.rule_id == RULE)
.values(delivered_at=datetime.now(timezone.utc) - timedelta(days=rule_deliveries.RETAIN_DAYS + 1))
)
await s.commit()
assert await rule_deliveries.prune() >= 1
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
+6 -4
View File
@@ -166,7 +166,9 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env)
assert out.stdout == ""
assert not (tmp / "curl.log").exists()
# The open is reported for the delivery record, with no acts to count.
assert json.loads((tmp / "curl.body").read_text()) == {
"rule_id": 11, "session_id": "s1", "acts": []}
# The open itself is still recorded.
assert (named / "s1.opened.ids").read_text().startswith("11\t")
# A rule no hook named is still reported.
@@ -176,7 +178,7 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
assert json.loads((tmp / "curl.body").read_text())["rule_id"] == 1
def test_an_open_with_nothing_in_the_window_sends_nothing(sandbox):
def test_an_open_with_nothing_in_the_window_sends_only_the_open(sandbox):
tmp, env = sandbox
ledger = tmp / "grimoire-moment"
ledger.mkdir()
@@ -185,9 +187,9 @@ def test_an_open_with_nothing_in_the_window_sends_nothing(sandbox):
)
out = _run("grimoire_record_opened.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env)
"tool_input": {"rule_id": 11}}, env, FAKE_CURL_REPLY='{"moments":[],"context":""}')
assert out.stdout == ""
assert not (tmp / "curl.log").exists()
assert json.loads((tmp / "curl.body").read_text())["acts"] == []
def test_session_end_removes_the_sessions_moment_files_and_no_others(sandbox):
+131
View File
@@ -0,0 +1,131 @@
"""The one delivery order, key by key, and both rule arms reading it."""
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]