"""Real-Postgres tests for weighing rules: proposed and judged enforcement, salience and triggers. What the feature promises, against the real tables: - the pass reads each rule beside its delivery history, and any answer takes the rule off the pass; - a value equal to the rule's own is recorded as agreed and changes nothing; a different one waits, changes nothing, and a confirm sets it; - a rejected value is never proposed again, and a newer suggestion for a field replaces an older one; - `enforce` needs an act to refuse, and a preference never holds; - a direct edit answers a waiting suggestion; - only the owner can propose or judge. """ from datetime import datetime, timezone import pytest import pytest_asyncio from sqlalchemy import select from grimoire.models import async_session from grimoire.models.rule_delivery import RuleDelivery from grimoire.models.rule_field_judgment import RuleFieldJudgment from grimoire.models.rule_usage import RuleUsageEvent from grimoire.models.rulebook import Rule, Rulebook from grimoire.models.user import User from grimoire.services import rule_field_judgments as weights_svc from grimoire.services import rule_triggers 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_weights_owner" STRANGER_USERNAME = "rule_weights_stranger" async def _purge_books(username: str) -> None: async with async_session() as s: for user in (await s.execute( select(User).where(User.username == username) )).scalars().all(): for book in (await s.execute( select(Rulebook).where(Rulebook.owner_user_id == user.id) )).scalars().all(): await s.delete(book) await s.commit() @pytest_asyncio.fixture async def world(): for name in (OWNER_USERNAME, STRANGER_USERNAME): await _purge_books(name) async with async_session() as s: owner = await ensure_user(s, OWNER_USERNAME) stranger = await ensure_user(s, STRANGER_USERNAME) await s.commit() uid, sid = owner.id, stranger.id book = await rulebooks_svc.create_rulebook(uid, "Weight fixtures") topic = await rulebooks_svc.create_topic(book.id, uid, "delivery") push = await rulebooks_svc.create_rule( topic.id, uid, "Push to main only when asked", "Never push to main unless the operator asked for it in this conversation.", when_to_apply="about to push a branch", ) dates = await rulebooks_svc.create_rule( topic.id, uid, "Dates are written day first", "Every date shown to a person is written day, month, year.", when_to_apply="formatting a date for display", ) terse = await rulebooks_svc.create_rule( topic.id, uid, "Replies stay short", "Lead with the answer and stop.", when_to_apply="writing a reply", kind="preference", ) return {"uid": uid, "sid": sid, "push": push, "dates": dates, "terse": terse} def _item(rule, enforcement="inform", salience="normal", why="read from the rule", **extra): return {"rule_id": rule.id, "enforcement": enforcement, "salience": salience, "why": why, **extra} async def _rule(rule_id: int) -> Rule: async with async_session() as s: return await s.get(Rule, rule_id) async def _unweighed_ids(uid: int) -> set[int]: return {r["id"] for r in (await weights_svc.unweighed_rules(uid, limit=100))["rules"]} async def _pending(uid: int) -> dict[int, list[tuple[str, str]]]: out = (await weights_svc.pending(uid))["rules"] return {r["id"]: [(p["field"], p["value"]) for p in r["proposals"]] for r in out} async def test_agreeing_marks_a_rule_weighed_and_changes_nothing(world): uid, dates = world["uid"], world["dates"] assert dates.id in await _unweighed_ids(uid) out = await weights_svc.propose(uid, [_item(dates)]) assert out == {"suggested": 0, "agreed": 2, "skipped": [], "refused": []} assert dates.id not in await _unweighed_ids(uid) assert dates.id not in await _pending(uid) rule = await _rule(dates.id) assert (rule.enforcement, rule.salience) == ("inform", "normal") async def test_a_suggestion_changes_nothing_until_a_confirm_sets_it(world): uid, push = world["uid"], world["push"] out = await weights_svc.propose(uid, [_item( push, "hold", "high", why="sessions pushed past it twice", )]) assert out["suggested"] == 2 and not out["refused"] assert (await _rule(push.id)).enforcement == "inform" assert sorted((await _pending(uid))[push.id]) == [("enforcement", "hold"), ("salience", "high")] judged = await weights_svc.judge(uid, [ {"rule_id": push.id, "field": "enforcement", "value": "hold", "verdict": "confirm"}, {"rule_id": push.id, "field": "salience", "value": "high", "verdict": "confirm"}, ]) assert not judged["refused"] and len(judged["judged"]) == 2 rule = await _rule(push.id) assert (rule.enforcement, rule.salience) == ("hold", "high") assert push.id not in await _pending(uid) async def test_a_rejected_value_is_never_proposed_again(world): uid, push = world["uid"], world["push"] await weights_svc.propose(uid, [_item(push, "hold")]) await weights_svc.judge(uid, [{"rule_id": push.id, "field": "enforcement", "value": "hold", "verdict": "reject", "note": "too loud"}]) again = await weights_svc.propose(uid, [_item(push, "hold")]) assert again["suggested"] == 0 assert again["skipped"][0]["field"] == "enforcement" assert "too loud" in again["skipped"][0]["why"] assert (await _rule(push.id)).enforcement == "inform" async def test_a_newer_suggestion_for_a_field_replaces_the_older(world): uid, dates = world["uid"], world["dates"] await weights_svc.propose(uid, [_item(dates, salience="high")]) await weights_svc.propose(uid, [_item(dates, salience="low")]) assert (await _pending(uid))[dates.id] == [("salience", "low")] async def test_enforce_needs_an_act_to_refuse(world): uid, push = world["uid"], world["push"] alone = await weights_svc.propose(uid, [_item(push, "enforce")]) assert alone["refused"] and "nothing routes an act" in alone["refused"][0]["error"] assert push.id in await _unweighed_ids(uid) trigger = {"kind": "command", "pattern": "git push"} routed = await weights_svc.propose(uid, [_item(push, "enforce", triggers=[trigger])]) assert not routed["refused"] and routed["suggested"] == 2 pending = (await weights_svc.pending(uid))["rules"][0]["proposals"] proposed = next(p for p in pending if p["field"] == "trigger") assert proposed["trigger"] == {"kind": "command", "pattern": "git push"} await weights_svc.judge(uid, [{"rule_id": push.id, "field": "trigger", "value": trigger, "verdict": "confirm"}]) have = (await rule_triggers.list_rule_triggers([push.id]))[push.id] assert have == [{"kind": "command", "pattern": "git push"}] async def test_a_preference_never_holds(world): uid, terse = world["uid"], world["terse"] out = await weights_svc.propose(uid, [_item(terse, "hold")]) assert out["refused"] and "preference" in out["refused"][0]["error"] ok = await weights_svc.propose(uid, [_item(terse, "inform", "low")]) assert not ok["refused"] and ok["agreed"] == 1 and ok["suggested"] == 1 async def test_a_direct_edit_answers_a_waiting_suggestion(world): uid, push = world["uid"], world["push"] await weights_svc.propose(uid, [_item(push, "hold")]) await rulebooks_svc.update_rule(push.id, uid, enforcement="inform", salience="high") # Enforcement did not change, so the suggestion still waits; salience did, # and is recorded as the edit's judgment. assert (await _pending(uid))[push.id] == [("enforcement", "hold")] await rulebooks_svc.update_rule(push.id, uid, enforcement="hold") assert push.id not in await _pending(uid) async with async_session() as s: states = {(r.field, r.value): (r.state, r.source) for r in (await s.execute( select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id == push.id) )).scalars().all()} assert states[("salience", "high")] == ("confirmed", "edit") assert states[("enforcement", "hold")][0] == "confirmed" async def test_the_pass_reads_each_rule_with_its_history(world): uid, push = world["uid"], world["push"] now = datetime.now(timezone.utc) async with async_session() as s: for i, (at, opened) in enumerate([("work.deliver", True), ("work.deliver", False), ("pre_tool_rule", False)]): s.add(RuleDelivery(user_id=uid, session_id=f"s{i}", rule_id=push.id, source="hook", at=at, form="full", plugin="2026.11.23.2100", opened_at=now if opened else None)) # From a plugin that does not report opens: not part of the history. s.add(RuleDelivery(user_id=uid, session_id="s-old", rule_id=push.id, source="hook", at="work.deliver", form="full")) s.add(RuleUsageEvent(user_id=uid, rule_id=push.id, event="departed", source="mcp_rule_outcome", detail="the operator asked")) await s.commit() page = await weights_svc.unweighed_rules(uid, limit=100) h = next(r for r in page["rules"] if r["id"] == push.id)["history"] assert (h["delivered"], h["opened"], h["departed"]) == (3, 1, 1) assert h["places"][0] == {"at": "work.deliver", "delivered": 2, "opened": 1} await weights_svc.propose(uid, [_item(push, "hold")]) evidence = (await weights_svc.pending(uid))["rules"][0]["proposals"][0]["evidence"] assert evidence["delivered"] == 3 async def test_only_the_owner_can_propose_or_judge(world): uid, sid, push = world["uid"], world["sid"], world["push"] out = await weights_svc.propose(sid, [_item(push, "hold")]) assert out["refused"][0]["error"] == "not a rule you own" await weights_svc.propose(uid, [_item(push, "hold")]) judged = await weights_svc.judge(sid, [{"rule_id": push.id, "field": "enforcement", "value": "hold", "verdict": "confirm"}]) assert judged["refused"] and not judged["judged"] assert (await _rule(push.id)).enforcement == "inform" assert (await weights_svc.pending(sid))["rules"] == []