feat(7732): a pass weighs each rule — enforcement, salience and triggers proposed from its text and delivery history, confirmed by the operator
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 2m9s
CI & Build / Build & push image (push) Skipped

Adds rule_field_judgments (migration 0132), the rules_to_weigh / propose_rule_weights / rule_weight_proposals / judge_rule_weights tools, the routes and the Settings › Moments panel that confirms them. A value equal to the rule's own is recorded as agreed; a different one waits; enforce is refused for a rule no act reaches; a direct edit answers a waiting suggestion. Backup v30 carries the judgments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 13:05:38 -05:00
co-authored by Claude Opus 5.5
parent 78c945e7c3
commit 619612732f
20 changed files with 1320 additions and 34 deletions
@@ -0,0 +1,222 @@
"""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",
opened_at=now if opened else None))
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"] == []
+6 -2
View File
@@ -111,12 +111,16 @@ def test_the_tools_are_registered_and_classified():
"list_moments", "list_reply_shapes", "map_action", "unmap_action",
"rules_to_mount", "propose_rule_moments", "rule_moment_proposals",
"judge_rule_moments", "rule_misfired",
"rules_to_weigh", "propose_rule_weights", "rule_weight_proposals",
"judge_rule_weights",
]
assert {"list_moments", "list_reply_shapes",
"rules_to_mount", "rule_moment_proposals"} <= _READ_ONLY_TOOLS
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals"} <= _READ_ONLY_TOOLS
# A confirm mounts a rule, so a read key must not reach it.
assert {"map_action", "unmap_action",
"propose_rule_moments", "judge_rule_moments", "rule_misfired"} <= _WRITE_TOOLS
"propose_rule_moments", "judge_rule_moments", "rule_misfired",
"propose_rule_weights", "judge_rule_weights"} <= _WRITE_TOOLS
def test_both_doors_read_one_catalog():
+2
View File
@@ -46,6 +46,8 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/moments/mappings",
"/api/retrieval/moments/proposals",
"/api/retrieval/moments/proposals/judge",
"/api/retrieval/weights/proposals",
"/api/retrieval/weights/proposals/judge",
"/api/retrieval/reply-shapes",
}
+6 -1
View File
@@ -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 == 29
assert backup.BACKUP_VERSION == 30
def _exportable_note(**over):
@@ -142,6 +142,7 @@ def _column_guard_targets():
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.design_system import DesignSystem, DesignToken
from grimoire.models.milestone import Milestone
from grimoire.models.note import Note
@@ -183,6 +184,7 @@ def _column_guard_targets():
"lesson_rule_links": (LessonRuleLink, backup._lesson_rule_link_rows),
"lesson_no_rule": (LessonNoRule, backup._lesson_no_rule_rows),
"rule_moment_judgments": (RuleMomentJudgment, backup._rule_moment_judgment_rows),
"rule_field_judgments": (RuleFieldJudgment, backup._rule_field_judgment_rows),
"note_usage_events": (NoteUsageEvent, backup._usage_event_rows),
"rule_usage_events": (RuleUsageEvent, backup._rule_usage_event_rows),
"system_usage_events": (SystemUsageEvent, backup._system_usage_event_rows),
@@ -314,6 +316,7 @@ def _import_guard_targets():
"lesson_rule_links": backup._build_lesson_rule_link,
"lesson_no_rule": backup._build_lesson_no_rule,
"rule_moment_judgments": backup._build_rule_moment_judgment,
"rule_field_judgments": backup._build_rule_field_judgment,
"note_usage_events": backup._build_usage_event,
"rule_usage_events": backup._build_rule_usage_event,
"system_usage_events": backup._build_system_usage_event,
@@ -590,6 +593,8 @@ async def test_export_full_backup_contains_every_declared_section():
"rule_moment_judgments",
# v29: the acts that trigger a rule.
"rule_triggers",
# v30: the weighed enforcement, salience and triggers.
"rule_field_judgments",
# v25: family canon.
"platforms", "project_platforms", "family_ideas",
"family_idea_platforms", "family_idea_references",