+ Suggested from each rule's text and what happened when it reached sessions. Inform is a
+ line beside the work; hold makes the act or reply wait until the rule has been read once
+ (file edits are never held); enforce refuses the act it governs. A trigger reaches the
+ rule exactly, by the tool, path, command or word the act carries.
+
+
+
+
+
+
+
+
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index baafb305..e2710971 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
- "version": "2026.11.23.0005",
+ "version": "2026.11.23.1802",
"author": {
"name": "Bryan Van Deusen"
},
diff --git a/plugin/skills/using-grimoire/moments.md b/plugin/skills/using-grimoire/moments.md
index e9c9bd6b..33159385 100644
--- a/plugin/skills/using-grimoire/moments.md
+++ b/plugin/skills/using-grimoire/moments.md
@@ -89,3 +89,10 @@ The same tool answers proposals from a pass over the rules
proposes, and only the operator's yes mounts. Writing a NEW rule is different
— its moments are part of writing it, and the
skill's guide to writing records says how.
+
+A second pass weighs each rule: how strongly it arrives once reached
+(`enforcement`: inform, hold or enforce; `salience`), and which typed
+triggers reach it exactly (`rules_to_weigh`, `propose_rule_weights`,
+`rule_weight_proposals`, `judge_rule_weights`). It reads each rule beside its
+delivery history and proposes; the operator confirms each change, in the
+session or under Settings › Moments.
diff --git a/src/grimoire/mcp/server.py b/src/grimoire/mcp/server.py
index bf1e8495..c76bf7a4 100644
--- a/src/grimoire/mcp/server.py
+++ b/src/grimoire/mcp/server.py
@@ -168,6 +168,7 @@ _READ_ONLY_TOOLS = frozenset({
# rules are unjudged and which proposals wait. Reads of the caller's own
# rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals",
+ "rules_to_weigh", "rule_weight_proposals",
})
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
@@ -229,6 +230,9 @@ _WRITE_TOOLS = frozenset({
# Proposing moments for a rule writes a judgment row; judging one mounts
# or unmounts the rule.
"propose_rule_moments", "judge_rule_moments",
+ # Proposing a rule's enforcement, salience or triggers writes a judgment
+ # row; judging one changes how the rule arrives.
+ "propose_rule_weights", "judge_rule_weights",
# A misfire report writes a counted row that can become an unmount
# proposal.
"rule_misfired",
diff --git a/src/grimoire/mcp/tools/moments.py b/src/grimoire/mcp/tools/moments.py
index 4e247678..2b164f29 100644
--- a/src/grimoire/mcp/tools/moments.py
+++ b/src/grimoire/mcp/tools/moments.py
@@ -16,6 +16,7 @@ from grimoire.mcp._context import current_user_id
from grimoire.services import moment_actions as actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
+from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
@@ -232,6 +233,90 @@ async def rule_misfired(rule_id: int, moment: str, why: str,
)
+async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
+ """The rules nobody has weighed, each with what happened when it reached a session — a page at a time.
+
+ Weighing a rule is deciding how strongly it arrives once the work reaches
+ it, and what reaches it exactly:
+
+ - `enforcement`: `inform` is a line beside the work, and is right for
+ most rules. `hold` makes the act or reply wait until the rule has been
+ read once in the session (file edits are never held). `enforce` refuses
+ the act the rule governs, in the rule's own words, every time — for a
+ rule whose breach an act commits and that must never be crossed without
+ the operator (pushing to a protected branch, a destructive command). A
+ preference is always `inform`.
+ - `salience`: `high`, `normal` or `low` — how it ranks beside rules of the
+ same enforcement when a moment has more to say than fits.
+ - `triggers`: typed predicates on the act (`tool`, `path`, `command`,
+ `keyword`, optionally scoped to a moment) that reach the rule exactly.
+ Propose one when the rule names the act it governs; an `enforce` rule
+ needs one, or a mount on an act's moment, to have an act to refuse.
+
+ Each rule carries its current `enforcement`, `salience`, `mounted` and
+ `triggers`, and `history` over the last 90 days: `delivered` and `opened`
+ in total and at each place (`places`), `pulled`, `applied`, `departed`
+ and `misfire_days`. Read the history as evidence about the rule's
+ weight, not as the decision: a rule delivered often and rarely opened is
+ either reaching the wrong work (a trigger fixes that) or arriving too
+ loudly for what it asks (lower salience); a rule sessions keep departing
+ from or breaching may need `hold`.
+
+ Record the answer with `propose_rule_weights`. A rule leaves this list as
+ soon as an answer is recorded, so the next call returns the next rules.
+ Returns `rules`, `total_unweighed` and `offset`.
+ """
+ return await weights_svc.unweighed_rules(current_user_id(), limit=limit, offset=offset)
+
+
+async def propose_rule_weights(proposals: list[dict]) -> dict:
+ """Propose rules' enforcement, salience and triggers — for the operator to confirm; nothing changes on this call.
+
+ Each item is
+ `{"rule_id": N, "enforcement": "inform"|"hold"|"enforce",
+ "salience": "high"|"normal"|"low", "triggers": [{"kind": "command",
+ "pattern": "git push", "moment": ""}], "why": "…"}`.
+
+ Give both enforcement and salience for every rule, even where they match
+ what it has: a value equal to the rule's own is recorded as agreed, which
+ is what marks the rule as weighed. A different value waits as a
+ suggestion. `triggers` lists only triggers to add; omit it when none fits.
+ `why` is shown to the operator beside each suggestion: say what in the
+ rule and its history led to it, so they can say yes or no without opening
+ the rule.
+
+ Refused alone, under `refused`, with why: an unknown value, a preference
+ proposed to hold or enforce, and `enforce` on a rule no act reaches.
+ A value the operator already rejected is listed under `skipped`. Then show
+ the operator what is waiting (`rule_weight_proposals`) and let them
+ decide.
+ """
+ return await weights_svc.propose(current_user_id(), proposals)
+
+
+async def rule_weight_proposals(rule_id: int = 0) -> dict:
+ """The enforcement, salience and trigger suggestions waiting on the operator, grouped by rule.
+
+ Each rule carries its current enforcement, salience, mounts and triggers
+ beside its `proposals`: each a `field`, the suggested `value` (a trigger
+ also as `trigger`), `why`, and the delivery history the proposer read
+ (`evidence`). `rule_id` narrows to one rule.
+ """
+ return await weights_svc.pending(current_user_id(), rule_id=rule_id or None)
+
+
+async def judge_rule_weights(judgments: list[dict]) -> dict:
+ """Confirm or reject weight suggestions — on the operator's word, since a confirm changes how the rule arrives.
+
+ Each item is `{"rule_id": N, "field": "enforcement"|"salience"|"trigger",
+ "value": "hold" (or the trigger object), "verdict": "confirm"|"reject",
+ "note": "why"}`. Confirm sets the field on the rule (a trigger is added
+ beside the rule's others); reject records that the value is wrong for this
+ rule, so it is never proposed again. Put the operator's reason in `note`.
+ """
+ return await weights_svc.judge(current_user_id(), judgments)
+
+
def register(mcp) -> None:
mcp.tool(name="list_moments")(list_moments)
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
@@ -242,3 +327,7 @@ def register(mcp) -> None:
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
mcp.tool(name="judge_rule_moments")(judge_rule_moments)
mcp.tool(name="rule_misfired")(rule_misfired)
+ mcp.tool(name="rules_to_weigh")(rules_to_weigh)
+ mcp.tool(name="propose_rule_weights")(propose_rule_weights)
+ mcp.tool(name="rule_weight_proposals")(rule_weight_proposals)
+ mcp.tool(name="judge_rule_weights")(judge_rule_weights)
diff --git a/src/grimoire/models/__init__.py b/src/grimoire/models/__init__.py
index 71ae222c..4cda1e35 100644
--- a/src/grimoire/models/__init__.py
+++ b/src/grimoire/models/__init__.py
@@ -84,6 +84,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
# After rules: it foreign-keys them.
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
+from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
diff --git a/src/grimoire/models/rule_field_judgment.py b/src/grimoire/models/rule_field_judgment.py
new file mode 100644
index 00000000..c8f0ae06
--- /dev/null
+++ b/src/grimoire/models/rule_field_judgment.py
@@ -0,0 +1,73 @@
+from datetime import datetime
+
+from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
+from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.orm import Mapped, mapped_column
+
+from grimoire.models import Base
+from grimoire.models.base import CreatedAtMixin, iso
+from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
+
+__all__ = [
+ "CONFIRMED", "ENFORCEMENT", "FIELDS", "REJECTED", "SALIENCE", "SUGGESTED",
+ "TRIGGER", "RuleFieldJudgment",
+]
+
+# The fields of a rule that decide how it arrives once it is reached: what it
+# does (`enforcement`), how it ranks beside rules of the same force
+# (`salience`), and the typed predicates that reach it (`trigger`).
+ENFORCEMENT, SALIENCE, TRIGGER = "enforcement", "salience", "trigger"
+FIELDS = (ENFORCEMENT, SALIENCE, TRIGGER)
+
+
+class RuleFieldJudgment(Base, CreatedAtMixin):
+ """A proposed or judged value for one of a rule's delivery fields.
+
+ The rule row holds the current value; this holds the reasoning behind it
+ and the values that were turned down. One row per (rule, field, value):
+
+ - ``suggested`` — a pass read the rule and its delivery history and
+ proposed this value. Changes nothing until a person confirms it.
+ - ``confirmed`` — the value was judged right. For a proposal equal to
+ what the rule already carries, the pass's agreement is recorded this way,
+ so a rule that was looked at and left alone does not read as one nobody
+ looked at.
+ - ``rejected`` — judged wrong, kept with its reason so it is never
+ proposed again.
+
+ `value` is the enforcement or salience name, or for a trigger
+ `kindpatternmoment` — one string, so the pair is unique.
+ `evidence` is the delivery history the proposer read, as it stood then.
+ """
+
+ __tablename__ = "rule_field_judgments"
+
+ id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
+ rule_id: Mapped[int] = mapped_column(
+ BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), index=True,
+ )
+ field: Mapped[str] = mapped_column(Text)
+ value: Mapped[str] = mapped_column(Text)
+ state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
+ # `pass` — an agent proposed it; `edit` — a person set the field directly.
+ source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
+ note: Mapped[str | None] = mapped_column(Text, nullable=True)
+ evidence: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
+ judged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+
+ __table_args__ = (
+ UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
+ )
+
+ def to_dict(self) -> dict:
+ return {
+ "rule_id": self.rule_id,
+ "field": self.field,
+ "value": self.value,
+ "state": self.state,
+ "source": self.source,
+ "note": self.note or "",
+ "evidence": self.evidence or {},
+ "judged_at": iso(self.judged_at),
+ "created_at": iso(self.created_at),
+ }
diff --git a/src/grimoire/routes/retrieval.py b/src/grimoire/routes/retrieval.py
index 716161f7..7276668d 100644
--- a/src/grimoire/routes/retrieval.py
+++ b/src/grimoire/routes/retrieval.py
@@ -21,6 +21,7 @@ from grimoire.auth import get_current_user_id, login_required
from grimoire.services import moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
+from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services.retrieval_telemetry import moment_usage
@@ -238,3 +239,28 @@ async def judge_moment_proposals_route():
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
+
+
+@retrieval_bp.route("/weights/proposals", methods=["GET"])
+@login_required
+async def weight_proposals_route():
+ """The enforcement, salience and trigger suggestions waiting on a judgment
+ — `rule_weight_proposals`' payload, from the same service. `?rule_id=`
+ narrows to one rule."""
+ try:
+ rule_id = int(request.args.get("rule_id") or 0)
+ except ValueError:
+ return jsonify({"error": "rule_id must be a whole number"}), 400
+ return jsonify(await weights_svc.pending(get_current_user_id(), rule_id=rule_id or None))
+
+
+@retrieval_bp.route("/weights/proposals/judge", methods=["POST"])
+@login_required
+async def judge_weight_proposals_route():
+ """Confirm or reject suggestions: `{"judgments": [{rule_id, field, value,
+ verdict, note}]}` — `judge_rule_weights` from the browser. A confirm
+ changes the rule."""
+ data = await request.get_json(silent=True)
+ if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
+ return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
+ return jsonify(await weights_svc.judge(get_current_user_id(), data["judgments"]))
diff --git a/src/grimoire/services/backup.py b/src/grimoire/services/backup.py
index a29f8a4a..9d739a9b 100644
--- a/src/grimoire/services/backup.py
+++ b/src/grimoire/services/backup.py
@@ -26,6 +26,7 @@ from grimoire.models.rulebook import (
rule_triggers as rule_triggers_t,
)
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
+from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.project import Project
@@ -116,7 +117,10 @@ logger = logging.getLogger(__name__)
# from. A live instance rolls back only to a backup with its own id.
# v29 rule_triggers: the typed predicates on the act that deliver a rule or
# make its mount conditional. Nothing in the rule's text records them.
-BACKUP_VERSION = 29
+# v30 rule_field_judgments: suggested, agreed and rejected values for a rule's
+# enforcement, salience and triggers. Lose them and a weighed corpus reads
+# as unweighed, and every rejected value is proposed again.
+BACKUP_VERSION = 30
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
# below, these two lists must together account for the entire schema — which is
@@ -162,6 +166,7 @@ _BACKED_UP = [
"rule_moments",
"rule_moment_judgments",
"rule_triggers",
+ "rule_field_judgments",
# Family canon. `platforms` is global like
# canonical_systems and rides every export for the same reason: the rows
# below name platforms by slug, and a partial catalog restores partial
@@ -269,6 +274,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"lesson_rule_links": {"id"},
# The same shape: the (rule, moment) pair is the row.
"rule_moment_judgments": {"id"},
+ # And again: the (rule, field, value) triple is the row.
+ "rule_field_judgments": {"id"},
# Keyed by the lesson itself; nothing to exclude, every column travels.
"lesson_no_rule": set(),
"note_usage_events": {"id"},
@@ -376,6 +383,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"rule_relations": {"id", "created_at"},
"lesson_rule_links": {"id"},
"rule_moment_judgments": {"id"},
+ "rule_field_judgments": {"id"},
"lesson_no_rule": set(),
"note_usage_events": {"id"},
"rule_usage_events": {"id"},
@@ -830,6 +838,21 @@ def _rule_moment_judgment_rows(rows) -> list[dict]:
]
+def _rule_field_judgment_rows(rows) -> list[dict]:
+ """Suggested, agreed and rejected values for a rule's enforcement,
+ salience and triggers (v30). The rule id is a SOURCE id, remapped at
+ restore."""
+ return [
+ {
+ "rule_id": r.rule_id, "field": r.field, "value": r.value, "state": r.state,
+ "source": r.source, "note": r.note, "evidence": r.evidence,
+ "judged_at": r.judged_at.isoformat() if r.judged_at else None,
+ "created_at": r.created_at.isoformat() if r.created_at else None,
+ }
+ for r in rows
+ ]
+
+
def _rule_system_rows(rows) -> list[dict]:
"""A rule's area tags, carried by canonical SLUG for the same reason the
Systems are: the catalog is global and its ids are per-install."""
@@ -1042,6 +1065,9 @@ async def export_full_backup() -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
)).scalars().all()
+ rule_field_judgments = (await session.execute(
+ select(RuleFieldJudgment).order_by(RuleFieldJudgment.id)
+ )).scalars().all()
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all()
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all()
lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all()
@@ -1133,6 +1159,7 @@ async def export_full_backup() -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
+ "rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
@@ -1301,6 +1328,10 @@ async def export_user_backup(user_id: int) -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
)).scalars().all() if _rule_ids else []
+ rule_field_judgments = (await session.execute(
+ select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(_rule_ids))
+ .order_by(RuleFieldJudgment.id)
+ )).scalars().all() if _rule_ids else []
# Scoped through the RULE, not the version's user_id. That column is
# the ACTOR, so filtering on it would carry the
# versions this user wrote on someone ELSE's rule and drop the ones
@@ -1426,6 +1457,7 @@ async def export_user_backup(user_id: int) -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
+ "rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
@@ -1857,6 +1889,25 @@ def _build_rule_moment_judgment(row: dict, maps: _Maps) -> RuleMomentJudgment |
)
+def _build_rule_field_judgment(row: dict, maps: _Maps) -> RuleFieldJudgment | None:
+ """Skipped when its rule did not restore, for the reason a moment
+ judgment is."""
+ rule = maps.rules.get(row.get("rule_id", 0))
+ if rule is None or not row.get("field") or row.get("value") is None:
+ return None
+ return RuleFieldJudgment(
+ rule_id=rule,
+ field=row["field"],
+ value=row["value"],
+ state=row.get("state") or "suggested",
+ source=row.get("source") or "pass",
+ note=row.get("note") or None,
+ evidence=row.get("evidence"),
+ judged_at=_dt_or_none(row.get("judged_at")),
+ created_at=_dt(row.get("created_at")),
+ )
+
+
def _build_platform(row: dict, maps: _Maps) -> Platform | None:
"""Matched on SLUG, like a canonical system: this install seeded the
standard platforms from its migrations, so the common case creates nothing
@@ -2447,7 +2498,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
- "rule_triggers": 0,
+ "rule_triggers": 0, "rule_field_judgments": 0,
"rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0,
@@ -2666,6 +2717,15 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
session.add(judgment)
stats["rule_moment_judgments"] += 1
+ # Weighed values for each rule (v30); archives before v30 carry none, and
+ # every rule restores unweighed.
+ for rf in data.get("rule_field_judgments", []):
+ weighed = _build_rule_field_judgment(rf, maps)
+ if weighed is None:
+ continue
+ session.add(weighed)
+ stats["rule_field_judgments"] += 1
+
for rr in data.get("rule_relations", []):
relation = _build_rule_relation(rr, maps)
if relation is None:
diff --git a/src/grimoire/services/rule_field_judgments.py b/src/grimoire/services/rule_field_judgments.py
new file mode 100644
index 00000000..04b302b3
--- /dev/null
+++ b/src/grimoire/services/rule_field_judgments.py
@@ -0,0 +1,501 @@
+"""How strongly each rule arrives, and what reaches it — proposals and judgments.
+
+A rule carries three fields that decide what happens once the work reaches it:
+
+- `enforcement` — `inform` (a line beside the work), `hold` (the act or reply
+ waits for one read of the rule) or `enforce` (the act it governs is refused,
+ in the rule's own words, every time). A preference is always `inform`.
+- `salience` — `high`, `normal` or `low`: how it ranks beside rules of the same
+ enforcement when a moment has more to say than fits.
+- `trigger` — typed predicates on the act (tool, path, command, keyword) that
+ reach the rule exactly, with no resemblance involved.
+
+Every rule written before these fields existed carries the defaults, which
+say nothing about whether anyone judged them. This service records that
+judgment the way moment mounts are recorded (`rule_moment_judgments`):
+
+- THE PASS. An agent reads each rule nobody has weighed, with its delivery
+ history — how often it reached a session, at which places, how often it was
+ opened there, how often sessions said it applied or departed from it — and
+ proposes its enforcement and salience, and any triggers it should have
+ (`propose`). A value equal to what the rule already has is recorded as the
+ pass's agreement; a different one waits as a suggestion and changes nothing.
+- THE JUDGMENT. A person confirms or rejects each suggestion (`judge`). A
+ confirm writes the field through the one rule write path; a reject is kept
+ so the value is never proposed again.
+
+A person setting a rule's enforcement or salience directly is judging it too
+(`record_edit`, called from `rulebooks.update_rule`), so a suggestion that an
+edit already answered does not wait in the list.
+
+ACL: rules are owner-scoped; every read and write goes through
+`rulebooks._owned_rules_clause`.
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from sqlalchemy import case, exists, func, not_, select
+
+from grimoire.models import async_session
+from grimoire.models.rule_delivery import RuleDelivery
+from grimoire.models.rule_field_judgment import (
+ CONFIRMED, ENFORCEMENT, FIELDS, REJECTED, SALIENCE, SUGGESTED, TRIGGER,
+ RuleFieldJudgment,
+)
+from grimoire.models.rule_moment_judgment import RuleMomentJudgment
+from grimoire.models.rule_usage import RuleUsageEvent
+from grimoire.models.rulebook import Rule
+from grimoire.services import lesson_rules, rule_order
+from grimoire.services import rule_triggers as triggers_svc
+from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned
+from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES
+
+VERDICTS = {"confirm": CONFIRMED, "reject": REJECTED}
+
+# Rules per pass page: enough to batch the reading, few enough that each rule
+# and its history is actually read.
+PASS_PAGE = 25
+# The delivery history a pass reads. Matches what the delivery order reads
+# (`rule_deliveries.HISTORY_DAYS`), so a proposal and the ranking it changes
+# look at the same window.
+HISTORY_DAYS = 90
+# Places listed per rule in its history, busiest first. Past this the counts
+# stop changing what the proposer would say.
+_PLACES = 8
+_WHY_CHARS = 600
+
+_EDIT_NOTE = "set by an edit"
+
+
+def _text(v) -> str:
+ return v.strip() if isinstance(v, str) else ""
+
+
+def trigger_value(trigger: triggers_svc.Trigger) -> str:
+ """A trigger as one string, so (rule, field, value) is unique."""
+ return f"{trigger.kind}\t{trigger.pattern}\t{trigger.moment}"
+
+
+def parse_trigger_value(value: str) -> triggers_svc.Trigger:
+ kind, pattern, moment = (value.split("\t", 2) + ["", ""])[:3]
+ return triggers_svc.Trigger(kind, pattern, moment)
+
+
+def current_value(rule: Rule, field: str) -> str:
+ if field == ENFORCEMENT:
+ return rule_order.force(rule)
+ return rule.salience or "normal"
+
+
+def _act_routed(mounts: set[str], triggers: list) -> bool:
+ """Whether some act can reach the rule — what `enforce` refuses.
+
+ A trigger is matched against an act; a mount reaches an act unless it is
+ on the reply. A rule reached only at the reply has no act to refuse, so
+ enforcing it would hold the reply and claim more than it does.
+ """
+ return bool(triggers) or any(not m.startswith("reply.") for m in mounts)
+
+
+# ── reading ───────────────────────────────────────────────────────────────
+
+
+async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
+ """What happened when each rule reached a session, over HISTORY_DAYS.
+
+ `delivered` / `opened` in total and at each place it was delivered
+ (`at`: a moment, or the arm that found it), busiest first; `pulled`,
+ `applied` and `departed` from the usage events; `misfire_days`, the days
+ sessions reported a mount of it arriving where it did not apply.
+ """
+ ids = sorted({int(r) for r in rule_ids or []})
+ out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [],
+ "pulled": 0, "applied": 0, "departed": 0, "misfire_days": 0}
+ for rid in ids}
+ if not ids:
+ return out
+ since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
+ rows = (await session.execute(
+ select(
+ RuleDelivery.rule_id, RuleDelivery.at, func.count(RuleDelivery.id),
+ func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
+ )
+ .where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
+ RuleDelivery.rule_id.in_(ids))
+ .group_by(RuleDelivery.rule_id, RuleDelivery.at)
+ )).all()
+ for rid, at, delivered, opened in rows:
+ h = out[int(rid)]
+ h["delivered"] += int(delivered)
+ h["opened"] += int(opened or 0)
+ h["places"].append({"at": at, "delivered": int(delivered), "opened": int(opened or 0)})
+ for h in out.values():
+ h["places"] = sorted(h["places"], key=lambda p: (-p["delivered"], p["at"]))[:_PLACES]
+ events = (await session.execute(
+ select(RuleUsageEvent.rule_id, RuleUsageEvent.event, func.count())
+ .where(RuleUsageEvent.user_id == user_id, RuleUsageEvent.created_at >= since,
+ RuleUsageEvent.rule_id.in_(ids),
+ RuleUsageEvent.event.in_(("pulled", "applied", "departed")))
+ .group_by(RuleUsageEvent.rule_id, RuleUsageEvent.event)
+ )).all()
+ for rid, event, n in events:
+ out[int(rid)][event] = int(n)
+ misfires = (await session.execute(
+ select(RuleMomentJudgment.rule_id, RuleMomentJudgment.misfire)
+ .where(RuleMomentJudgment.rule_id.in_(ids), RuleMomentJudgment.misfire.isnot(None))
+ )).all()
+ for rid, mf in misfires:
+ out[int(rid)]["misfire_days"] += lesson_rules.evidence_summary(mf)["situations"]
+ return out
+
+
+def _brief(rule: Rule, mounts: set[str], triggers: list[dict]) -> dict:
+ return {
+ "id": rule.id,
+ "title": rule.title,
+ "kind": rule.kind or "rule",
+ "statement": rule.statement,
+ "when_to_apply": rule.when_to_apply or "",
+ "home": "project" if rule.project_id else "global",
+ "enforcement": current_value(rule, ENFORCEMENT),
+ "salience": current_value(rule, SALIENCE),
+ "mounted": sorted(mounts),
+ "triggers": triggers,
+ }
+
+
+def _unweighed_clause():
+ """No enforcement or salience judgment of any kind — a rule nobody weighed."""
+ return not_(exists().where(
+ RuleFieldJudgment.rule_id == Rule.id,
+ RuleFieldJudgment.field.in_((ENFORCEMENT, SALIENCE)),
+ ))
+
+
+async def unweighed_rules(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> dict:
+ """The caller's rules nobody has weighed, a page at a time, each with its history.
+
+ A rule leaves this list once its enforcement and salience have any answer
+ — a proposal, the pass's agreement, or a direct edit — so a pass run in
+ pieces does not read a rule twice.
+ """
+ from grimoire.services.rulebooks import _owned_rules_clause
+
+ limit = max(1, min(int(limit or PASS_PAGE), 100))
+ offset = max(0, int(offset or 0))
+ clauses = (_owned_rules_clause(user_id), _unweighed_clause())
+ async with async_session() as session:
+ total = (await session.execute(
+ select(func.count()).select_from(Rule).where(*clauses)
+ )).scalar_one()
+ rules = (await session.execute(
+ select(Rule).where(*clauses).order_by(Rule.id).limit(limit).offset(offset)
+ )).scalars().all()
+ ids = [r.id for r in rules]
+ mounts = await _mounts(session, ids)
+ hist = await history(session, user_id, ids)
+ triggers = await triggers_svc.list_rule_triggers(ids)
+ return {
+ "rules": [{**_brief(r, mounts.get(r.id, set()), triggers.get(r.id, [])),
+ "history": hist[r.id]} for r in rules],
+ "total_unweighed": int(total),
+ "offset": offset,
+ }
+
+
+# ── the pass ──────────────────────────────────────────────────────────────
+
+
+async def _rows(session, rule_ids) -> dict[tuple[int, str, str], RuleFieldJudgment]:
+ if not rule_ids:
+ return {}
+ rows = (await session.execute(
+ select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(list(rule_ids)))
+ )).scalars().all()
+ return {(r.rule_id, r.field, r.value): r for r in rows}
+
+
+async def propose(user_id: int, proposals: list[dict]) -> dict:
+ """Record a pass's proposals for rules' enforcement, salience and triggers.
+
+ Each item is `{rule_id, enforcement, salience, triggers?: [...], why}`.
+ Enforcement and salience are both required: they are the answer to "how
+ strongly does this rule arrive", and answering one leaves the rule half
+ weighed. A value equal to the rule's own is recorded as agreed and changes
+ nothing; a different one lands `suggested`, replacing any earlier
+ suggestion for that field. A trigger the rule does not have lands
+ `suggested`. A value already rejected is skipped and said so.
+
+ Refused alone, with why: a rule the caller does not own, an unknown value,
+ a preference proposed to hold or enforce, and `enforce` on a rule no act
+ can reach (no trigger, none proposed, and mounted only at the reply).
+ """
+ now = datetime.now(timezone.utc)
+ suggested = agreed = 0
+ skipped: list[dict] = []
+ refused: list[dict] = []
+ items = [p for p in proposals or [] if isinstance(p, dict)]
+ refused += [{"item": p, "error": "each proposal is an object"}
+ for p in proposals or [] if not isinstance(p, dict)]
+ async with async_session() as session:
+ owned = await _owned(session, user_id, [p.get("rule_id") for p in items])
+ mounts = await _mounts(session, list(owned))
+ hist = await history(session, user_id, list(owned))
+ existing = await _rows(session, list(owned))
+ have = await triggers_svc.list_rule_triggers(list(owned))
+ for item in items:
+ rid = _int(item.get("rule_id"))
+ rule = owned.get(rid) if rid else None
+ if rule is None:
+ refused.append({"rule_id": item.get("rule_id"), "error": "not a rule you own"})
+ continue
+ enforcement = _text(item.get("enforcement")).lower()
+ salience = _text(item.get("salience")).lower()
+ why = _text(item.get("why"))[:_WHY_CHARS]
+ if enforcement not in ENFORCEMENTS or salience not in SALIENCES:
+ refused.append({"rule_id": rid, "error": (
+ f"give both enforcement (one of {', '.join(ENFORCEMENTS)}) and salience "
+ f"(one of {', '.join(SALIENCES)})")})
+ continue
+ if not why:
+ refused.append({"rule_id": rid, "error": (
+ "why is required: it is what the operator reads to say yes or no "
+ "without opening the rule")})
+ continue
+ if rule.kind == "preference" and enforcement != "inform":
+ refused.append({"rule_id": rid, "error": (
+ "a preference is always `inform`: it says how work is liked, and "
+ "claims no force that could stop it. Propose it as a rule's "
+ "enforcement only after it is made a rule")})
+ continue
+ try:
+ wanted = triggers_svc.require_triggers(item.get("triggers") or []) or []
+ except ValueError as exc:
+ refused.append({"rule_id": rid, "error": str(exc)})
+ continue
+ current_triggers = {trigger_value(triggers_svc.require_trigger(t))
+ for t in have.get(rid, [])}
+ new_triggers = [t for t in wanted if trigger_value(t) not in current_triggers]
+ if enforcement == "enforce" and not _act_routed(mounts.get(rid, set()),
+ have.get(rid, []) + new_triggers):
+ refused.append({"rule_id": rid, "error": (
+ "`enforce` refuses the act a rule governs, and nothing routes an act "
+ "to this one: it has no trigger and is mounted only at the reply, if "
+ "anywhere. Propose the trigger that names the act (a command, a path, "
+ "a tool) with it, or propose `hold`")})
+ continue
+ evidence = hist[rid]
+
+ def put(field: str, value: str, state: str) -> None:
+ row = existing.get((rid, field, value))
+ if row is None:
+ row = RuleFieldJudgment(rule_id=rid, field=field, value=value, source="pass")
+ session.add(row)
+ existing[(rid, field, value)] = row
+ row.state, row.note, row.evidence = state, why, evidence
+ if state != SUGGESTED:
+ row.judged_at = now
+
+ for field, value in ((ENFORCEMENT, enforcement), (SALIENCE, salience)):
+ row = existing.get((rid, field, value))
+ if value == current_value(rule, field):
+ if row is None or row.state == SUGGESTED:
+ put(field, value, CONFIRMED)
+ agreed += 1
+ continue
+ if row is not None and row.state == REJECTED:
+ skipped.append({"rule_id": rid, "field": field, "value": value,
+ "why": "already rejected" + (f": {row.note}" if row.note else "")})
+ continue
+ # One open suggestion per field: a newer reading replaces an older one.
+ for key, other in list(existing.items()):
+ if key[0] == rid and key[1] == field and key[2] != value and other.state == SUGGESTED:
+ await session.delete(other)
+ existing.pop(key)
+ put(field, value, SUGGESTED)
+ suggested += 1
+ for trigger in new_triggers:
+ value = trigger_value(trigger)
+ row = existing.get((rid, TRIGGER, value))
+ if row is not None and row.state != SUGGESTED:
+ skipped.append({"rule_id": rid, "field": TRIGGER, "value": trigger.to_dict(),
+ "why": f"already {row.state}" + (f": {row.note}" if row.note else "")})
+ continue
+ put(TRIGGER, value, SUGGESTED)
+ suggested += 1
+ await session.commit()
+ return {"suggested": suggested, "agreed": agreed, "skipped": skipped, "refused": refused}
+
+
+# ── waiting on a person ───────────────────────────────────────────────────
+
+
+def _proposal_item(row: RuleFieldJudgment) -> dict:
+ out = {"field": row.field, "value": row.value, "why": row.note or "",
+ "source": row.source, "evidence": row.evidence or {},
+ "created_at": row.created_at.isoformat() if row.created_at else None}
+ if row.field == TRIGGER:
+ out["trigger"] = parse_trigger_value(row.value).to_dict()
+ return out
+
+
+async def pending(user_id: int, rule_id: int | None = None, limit: int = 200) -> dict:
+ """The suggestions waiting on a judgment, grouped by rule.
+
+ Each rule carries its current enforcement, salience, mounts and triggers,
+ so a suggestion is read beside what it would change. A suggestion the rule
+ already carries — set by an edit since, or a trigger added by hand — is
+ left out: there is nothing left to decide.
+ """
+ from grimoire.services.rulebooks import _owned_rules_clause
+
+ limit = max(1, min(int(limit or 200), 500))
+ async with async_session() as session:
+ stmt = (
+ select(RuleFieldJudgment, Rule)
+ .join(Rule, Rule.id == RuleFieldJudgment.rule_id)
+ .where(RuleFieldJudgment.state == SUGGESTED, _owned_rules_clause(user_id))
+ )
+ if rule_id:
+ stmt = stmt.where(Rule.id == int(rule_id))
+ rows = (await session.execute(
+ stmt.order_by(Rule.id, RuleFieldJudgment.field, RuleFieldJudgment.value).limit(limit)
+ )).all()
+ ids = sorted({r.id for _, r in rows})
+ mounts = await _mounts(session, ids)
+ triggers = await triggers_svc.list_rule_triggers(ids)
+ order = {f: i for i, f in enumerate(FIELDS)}
+ grouped: dict[int, dict] = {}
+ for row, rule in rows:
+ have = triggers.get(rule.id, [])
+ if row.field == TRIGGER:
+ if parse_trigger_value(row.value).to_dict() in have:
+ continue
+ elif row.value == current_value(rule, row.field):
+ continue
+ entry = grouped.setdefault(rule.id, {
+ **_brief(rule, mounts.get(rule.id, set()), have), "proposals": [],
+ })
+ entry["proposals"].append(_proposal_item(row))
+ for entry in grouped.values():
+ entry["proposals"].sort(key=lambda p: (order.get(p["field"], 9), p["value"]))
+ rules = sorted(grouped.values(), key=lambda r: r["id"])
+ return {"rules": rules, "total": sum(len(r["proposals"]) for r in rules)}
+
+
+# ── judging ───────────────────────────────────────────────────────────────
+
+
+def _judged_value(field: str, raw) -> str:
+ """The value a judgment names, normalised the way proposals store it."""
+ if field == TRIGGER:
+ trigger = raw if isinstance(raw, dict) else None
+ if trigger is None and isinstance(raw, str) and "\t" in raw:
+ return trigger_value(parse_trigger_value(raw))
+ return trigger_value(triggers_svc.require_trigger(trigger))
+ value = _text(raw).lower()
+ allowed = ENFORCEMENTS if field == ENFORCEMENT else SALIENCES
+ if value not in allowed:
+ raise ValueError(f"{field} must be one of {', '.join(allowed)}")
+ return value
+
+
+async def judge(user_id: int, judgments: list[dict]) -> dict:
+ """Confirm or reject suggestions — on a person's word, since a confirm changes the rule.
+
+ Each item is `{rule_id, field, value, verdict, note?}`; for a trigger,
+ `value` is the trigger `{kind, pattern, moment?}`. Confirm writes the
+ field through `rulebooks.update_rule` (enforcement, salience) or adds the
+ trigger beside the rule's others; reject records that the value is wrong
+ here, so it is never proposed again. A bad item is refused alone.
+ """
+ from grimoire.services.rulebooks import update_rule
+
+ done: list[dict] = []
+ refused: list[dict] = []
+ for item in judgments or []:
+ if not isinstance(item, dict):
+ refused.append({"item": item, "error": "each judgment is an object"})
+ continue
+ rid = _int(item.get("rule_id"))
+ field = _text(item.get("field")).lower()
+ state = VERDICTS.get(_text(item.get("verdict")).lower())
+ if rid is None or field not in FIELDS or state is None:
+ refused.append({"rule_id": item.get("rule_id"), "field": item.get("field"), "error": (
+ f"needs rule_id, a field (one of {', '.join(FIELDS)}) and a verdict "
+ f"(one of {', '.join(sorted(VERDICTS))})")})
+ continue
+ try:
+ value = _judged_value(field, item.get("value"))
+ except ValueError as exc:
+ refused.append({"rule_id": rid, "field": field, "error": str(exc)})
+ continue
+ note = _text(item.get("note"))[:_WHY_CHARS]
+ async with async_session() as session:
+ if not await _owned(session, user_id, [rid]):
+ refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
+ continue
+ if state == CONFIRMED:
+ try:
+ if field == TRIGGER:
+ await _add_trigger(rid, parse_trigger_value(value))
+ elif await update_rule(rid, user_id, **{field: value}) is None:
+ refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
+ continue
+ except ValueError as exc:
+ refused.append({"rule_id": rid, "field": field, "error": str(exc)})
+ continue
+ await _record(rid, field, value, state, note)
+ done.append({"rule_id": rid, "field": field, "value": value, "state": state})
+ return {"judged": done, "refused": refused}
+
+
+async def _add_trigger(rule_id: int, trigger: triggers_svc.Trigger) -> None:
+ have = (await triggers_svc.list_rule_triggers([rule_id])).get(rule_id, [])
+ triggers = triggers_svc.require_triggers(have + [trigger.to_dict()]) or []
+ await triggers_svc.set_rule_triggers(rule_id, triggers)
+
+
+async def _record(rule_id: int, field: str, value: str, state: str, note: str) -> None:
+ now = datetime.now(timezone.utc)
+ async with async_session() as session:
+ row = (await session.execute(
+ select(RuleFieldJudgment).where(
+ RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field,
+ RuleFieldJudgment.value == value)
+ )).scalar_one_or_none()
+ if row is None:
+ row = RuleFieldJudgment(rule_id=rule_id, field=field, value=value, source="edit")
+ session.add(row)
+ row.state, row.judged_at = state, now
+ row.note = note or row.note
+ await session.commit()
+
+
+async def record_edit(session, rule_id: int, field: str, before: str, after: str) -> None:
+ """Record a direct change of enforcement or salience, in the caller's session.
+
+ The new value is confirmed; a suggestion for any other value of that field
+ is rejected — the edit answered it. A rule edited this way has been
+ weighed, so the pass does not read it again.
+ """
+ if field not in (ENFORCEMENT, SALIENCE) or before == after:
+ return
+ now = datetime.now(timezone.utc)
+ rows = (await session.execute(
+ select(RuleFieldJudgment).where(
+ RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field)
+ )).scalars().all()
+ by_value = {r.value: r for r in rows}
+ row = by_value.get(after)
+ if row is None:
+ row = RuleFieldJudgment(rule_id=rule_id, field=field, value=after,
+ source="edit", note=_EDIT_NOTE)
+ session.add(row)
+ row.state, row.judged_at = CONFIRMED, now
+ for value, other in by_value.items():
+ if value != after and other.state == SUGGESTED:
+ other.state, other.judged_at = REJECTED, now
+ other.note = f"{field} set to {after} by an edit"
+
diff --git a/src/grimoire/services/rulebooks.py b/src/grimoire/services/rulebooks.py
index 611516df..94c92085 100644
--- a/src/grimoire/services/rulebooks.py
+++ b/src/grimoire/services/rulebooks.py
@@ -763,6 +763,8 @@ async def update_rule(
# to survive the mutation below. A rule's history is the only record
# of what it used to say; the edit itself destroys that.
text_before = rule_versions.snapshot(rule)
+ weight_before = {"enforcement": rule.enforcement or "inform",
+ "salience": rule.salience or "normal"}
for key in clear:
if key in allowed and key in NULLABLE_RULE_TEXT:
setattr(rule, key, None)
@@ -808,6 +810,12 @@ async def update_rule(
# wording was written — which is why it is taken before the loop and
# not here.
rule_versions.record_if_changed(session, rule, user_id, text_before)
+ # Setting how strongly a rule arrives is a judgment of it: recorded
+ # beside the pass's suggestions, so one this edit answered stops waiting.
+ from grimoire.services import rule_field_judgments
+ for field, before in weight_before.items():
+ await rule_field_judgments.record_edit(
+ session, rule.id, field, before, getattr(rule, field) or before)
await session.commit()
await session.refresh(rule)
_refresh_rule_embedding(rule)
diff --git a/tests/test_integration_rule_field_judgments.py b/tests/test_integration_rule_field_judgments.py
new file mode 100644
index 00000000..cf263aa2
--- /dev/null
+++ b/tests/test_integration_rule_field_judgments.py
@@ -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"] == []
diff --git a/tests/test_moments.py b/tests/test_moments.py
index 0e4c88ab..afc213f5 100644
--- a/tests/test_moments.py
+++ b/tests/test_moments.py
@@ -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():
diff --git a/tests/test_routes_retrieval_tuning.py b/tests/test_routes_retrieval_tuning.py
index e3605908..c94c92b5 100644
--- a/tests/test_routes_retrieval_tuning.py
+++ b/tests/test_routes_retrieval_tuning.py
@@ -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",
}
diff --git a/tests/test_services_backup.py b/tests/test_services_backup.py
index 0a1dfdfb..6ac614bb 100644
--- a/tests/test_services_backup.py
+++ b/tests/test_services_backup.py
@@ -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",