feat(7728): a rule declares its enforcement and salience
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Failing after 21s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Skipped

A rule now carries what it does when it arrives, declared by its author
rather than guessed from a score: enforce (the act is checked), hold (the
reply or act waits for one read) or inform (a line beside the work, the
default). And a salience, high, normal or low, for ranking among rules of
the same enforcement at a crowded moment. A preference is always inform.

Migration 0128 adds both with CHECKs. Every door carries them: the
service, the MCP create and update tools, REST, backup and restore, and
the rule editor, which also marks holding and enforced rules in the list.
Unknown values are refused rather than mapped. Nothing reads them yet
beyond the record; the ordering function and the lifecycle come next in
this step, and step 5 decides who holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:05:45 -05:00
co-authored by Claude Opus 5.5
parent da7c43aa8a
commit 61077752b9
12 changed files with 402 additions and 10 deletions
+46 -1
View File
@@ -342,6 +342,7 @@ async def create_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
) -> dict:
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
@@ -530,6 +531,14 @@ async def create_rule(
constraint expires when the ground under it moves, not on a
schedule. Pairs with verify_with; both empty is the normal case.
order_index: Display order within the topic (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule
already in this topic BLOCKS creation and returns its id so you update
it instead. Set true only for a genuinely distinct rule. A rule or
@@ -553,6 +562,7 @@ async def create_rule(
arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
@@ -565,6 +575,7 @@ async def create_project_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
) -> dict:
"""Create a rule scoped to a single project (no rulebook needed).
@@ -640,6 +651,14 @@ async def create_project_rule(
expires_when: The state under which the rule stops being true — see
create_rule. A state, not a date.
order_index: Display order within the project's rule list (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule
already on this project BLOCKS creation and returns its id so you
update it instead. Set true only for a genuinely distinct rule. An
@@ -662,6 +681,7 @@ async def create_project_rule(
arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
@@ -675,6 +695,7 @@ async def update_rule(
moments: list[str] | None = None, arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "",
clear_fields: list[str] | None = None,
enforcement: str = "", salience: str = "",
) -> dict:
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
@@ -735,6 +756,15 @@ async def update_rule(
expires_when: The state under which the rule stops being true. A
state, not a date. See create_rule.
clear_fields: Names of fields to empty, as above.
enforcement: What this rule does when it arrives. `inform` (the
default for a new rule) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit either to leave it unchanged.
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
@@ -759,6 +789,10 @@ async def update_rule(
fields["expires_when"] = expires_when
if order_index >= 0:
fields["order_index"] = order_index
if enforcement:
fields["enforcement"] = enforcement
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields,
)
@@ -786,7 +820,7 @@ async def create_preference(
arose_from_id: int, why: str = "", how_to_apply: str = "",
order_index: int = 0, system_ids: list[int] | None = None,
moments: list[str] | None = None,
force: bool = False,
force: bool = False, salience: str = "normal",
) -> dict:
"""Record how the operator wants work done. No approval loop — write it.
@@ -860,6 +894,9 @@ async def create_preference(
done rather than what it is about: a rule on when work counts as
finished belongs at work.finish and reply.report, where nothing
said resembles it. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. For a genuinely distinct
preference, not for one that is "mostly" different — a mostly
different preference is an update. A RULE that already answers
@@ -893,6 +930,7 @@ async def create_preference(
title=title, statement=statement, when_to_apply=when_to_apply,
kind="preference", arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "preference"))
@@ -905,6 +943,7 @@ async def update_preference(
how_to_apply: str = "", order_index: int = -1,
system_ids: list[int] | None = None,
moments: list[str] | None = None, clear_fields: list[str] | None = None,
salience: str = "",
) -> dict:
"""Bring a preference up to date. Doing this mid-work is expected.
@@ -959,6 +998,10 @@ async def update_preference(
moments: Replaces the moments this preference arrives at (see
create_preference); omit to leave them alone.
when_to_apply: The moment it applies, in session vocabulary. See above.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit to leave it unchanged.
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
@@ -981,6 +1024,8 @@ async def update_preference(
fields["how_to_apply"] = how_to_apply
if order_index >= 0:
fields["order_index"] = order_index
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields,
)
+11
View File
@@ -116,6 +116,15 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# Defaults to `rule` so nothing changes force on upgrade.
# CHECK ck_rules_kind (migration 0098).
kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule")
# WHAT THE RULE DOES WHEN IT ARRIVES, declared by its author rather than
# guessed from a score. `enforce`: the act it governs is checked. `hold`:
# the reply or act waits for one read of it. `inform`: a line beside the
# work, and never a stop. A preference is always `inform` (CHECK
# ck_rules_preference_informs). CHECK ck_rules_enforcement (migration 0128).
enforcement: Mapped[str] = mapped_column(Text, default="inform", server_default="inform")
# How this rule ranks among rules of the same enforcement when a moment has more
# to say than fits: `high`, `normal`, `low`. CHECK ck_rules_salience.
salience: Mapped[str] = mapped_column(Text, default="normal", server_default="normal")
why: Mapped[str | None] = mapped_column(Text, nullable=True)
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
# The three fields that tell a CONSTRAINT apart from a NORM (milestone
@@ -161,6 +170,8 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# codebase keeps re-encountering. Twenty bytes buys an answer that
# cannot be misread.
"kind": self.kind or "rule",
"enforcement": self.enforcement or "inform",
"salience": self.salience or "normal",
"why": self.why or "",
"how_to_apply": self.how_to_apply or "",
"verify_with": self.verify_with or "",
+27 -2
View File
@@ -18,6 +18,18 @@ from grimoire.services.rule_usage import (
rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api")
def _declared_or_refusal(data: dict):
"""The request's enforcement and salience, validated before any write, so
a bad value is a 400 naming the choices rather than a half-made rule."""
try:
return (
rulebooks_svc.require_enforcement(data.get("enforcement"), data.get("kind")),
rulebooks_svc.require_salience(data.get("salience")),
), None
except ValueError as exc:
return None, (jsonify({"error": str(exc)}), 400)
def _moments_or_refusal(data: dict):
"""The request's `moments`, validated BEFORE any write — so an unknown
name is a 400 and not a rule created without the mounts it asked for.
@@ -184,6 +196,10 @@ async def create_rule(topic_id: int):
moments, refused = _moments_or_refusal(data)
if refused:
return refused
declared, refused = _declared_or_refusal(data)
if refused:
return refused
enforcement, salience = declared
try:
rule = await rulebooks_svc.create_rule(
topic_id=topic_id,
@@ -202,6 +218,7 @@ async def create_rule(topic_id: int):
arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""),
enforcement=enforcement, salience=salience,
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
@@ -234,7 +251,7 @@ async def update_rule(rule_id: int):
k: v for k, v in data.items()
if k in ("title", "statement", "why", "how_to_apply", "order_index",
"when_to_apply", "kind", "arose_from_id",
"verify_with", "expires_when")
"verify_with", "expires_when", "enforcement", "salience")
}
# No clear_fields here: a form sends "" for an emptied input, and the
# service normalises "" to NULL for every nullable text column. The MCP
@@ -243,7 +260,10 @@ async def update_rule(rule_id: int):
moments, refused = _moments_or_refusal(data)
if refused:
return refused
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
try:
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if rule is None:
return jsonify({"error": "rule not found"}), 404
return jsonify(await rulebooks_svc.rule_detail(
@@ -425,6 +445,10 @@ async def create_project_rule(project_id: int):
moments, refused = _moments_or_refusal(data)
if refused:
return refused
declared, refused = _declared_or_refusal(data)
if refused:
return refused
enforcement, salience = declared
try:
rule = await rulebooks_svc.create_project_rule(
project_id=project_id,
@@ -443,6 +467,7 @@ async def create_project_rule(project_id: int):
arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""),
enforcement=enforcement, salience=salience,
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
+10
View File
@@ -959,6 +959,7 @@ def _rule_rows(rows) -> list[dict]:
"title": r.title, "statement": r.statement, "why": r.why,
"how_to_apply": r.how_to_apply, "order_index": r.order_index,
"when_to_apply": r.when_to_apply, "kind": r.kind,
"enforcement": r.enforcement, "salience": r.salience,
"verify_with": r.verify_with, "expires_when": r.expires_when,
"verified_at": r.verified_at.isoformat() if r.verified_at else None,
"arose_from_id": r.arose_from_id,
@@ -1717,6 +1718,15 @@ def _build_rule(row: dict, maps: _Maps) -> Rule | None:
# way would restore an old backup with things that had always bound
# quietly not binding.
kind=row.get("kind") or "rule",
# An archive from before these columns restores every rule as it
# behaved then: a line beside the work, at normal rank. A preference
# is always `inform`, whatever the archive says, since the CHECK would
# refuse anything else and take the whole restore down with it.
enforcement=(
"inform" if (row.get("kind") or "rule") == "preference"
else (row.get("enforcement") if row.get("enforcement") in ("enforce", "hold", "inform") else "inform")
),
salience=row.get("salience") if row.get("salience") in ("high", "normal", "low") else "normal",
verify_with=row.get("verify_with") or None,
expires_when=row.get("expires_when") or None,
# Restored as-is, NOT reset to null. `verified_at` records when someone
+60 -3
View File
@@ -273,6 +273,38 @@ RELATION_KINDS = ("co_surfaces", "overrides", "elaborates")
# Migration 0098's CHECK. `rule` binds; `preference` is how the operator
# wants work done — see the model comment for why both live on one table.
KINDS = ("rule", "preference")
# Migration 0128's CHECKs, strongest first — the order the ordering function
# ranks them in (services/rule_order.py).
ENFORCEMENTS = ("enforce", "hold", "inform")
SALIENCES = ("high", "normal", "low")
def require_enforcement(enforcement: str | None, kind: str | None) -> str:
"""The enforcement a rule of this kind may carry, or a refusal naming the choices.
Unlike `kind`, an unknown enforcement is refused rather than mapped: there is no
safe direction to fall in. Mapped up, a typo turns a line into a stop;
mapped down, it turns a stop into a line. A preference is always `inform`
— it says how work is liked done, and a stop would claim a force it does
not have.
"""
clean = (enforcement or "inform").strip().lower()
if clean not in ENFORCEMENTS:
raise ValueError(f"enforcement must be one of {', '.join(ENFORCEMENTS)}, got {enforcement!r}")
if (kind or "rule") == "preference" and clean != "inform":
raise ValueError(
"a preference's enforcement is always `inform`: it says how work is liked "
"done, and holding or enforcing it would make it a rule. Record it "
"as a rule if it must stop the work."
)
return clean
def require_salience(salience: str | None) -> str:
clean = (salience or "normal").strip().lower()
if clean not in SALIENCES:
raise ValueError(f"salience must be one of {', '.join(SALIENCES)}, got {salience!r}")
return clean
# The rule columns that are nullable, and therefore the ones where EMPTY has
@@ -339,8 +371,14 @@ def rule_brief(rule: Rule, **extra) -> dict:
# one, and the assumption it would reach for — "this binds" — is the
# expensive one to get wrong in the other direction. Say it outright.
"kind": rule.kind or "rule",
# Unconditional for the same reason as `kind`: whether a rule stops
# the work is never something a reader should have to assume.
"enforcement": rule.enforcement or "inform",
"updated_at": rule.updated_at.date().isoformat() if rule.updated_at else None,
}
# Salience is attached only when the author raised or lowered it.
if (rule.salience or "normal") != "normal":
out["salience"] = rule.salience
# Attached only when present: never a null key that reads as a
# capability the record doesn't have.
if rule.when_to_apply:
@@ -506,8 +544,12 @@ async def create_rule(
why: str = "", how_to_apply: str = "", order_index: int = 0,
when_to_apply: str = "", arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "rule",
enforcement: str = "inform", salience: str = "normal",
) -> Rule:
_require_trigger(when_to_apply)
kind = _valid_kind(kind)
enforcement = require_enforcement(enforcement, kind)
salience = require_salience(salience)
async with async_session() as session:
await _assert_topic_owned(session, topic_id, user_id)
rule = Rule(
@@ -515,7 +557,7 @@ async def create_rule(
title=title,
statement=statement,
when_to_apply=when_to_apply or None,
kind=_valid_kind(kind),
kind=kind, enforcement=enforcement, salience=salience,
why=why or None,
how_to_apply=how_to_apply or None,
verify_with=verify_with or None,
@@ -535,6 +577,7 @@ async def create_project_rule(
why: str = "", how_to_apply: str = "", order_index: int = 0,
when_to_apply: str = "", arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "rule",
enforcement: str = "inform", salience: str = "normal",
) -> Rule:
"""Create a rule scoped to a single project (no rulebook ceremony).
@@ -544,6 +587,9 @@ async def create_project_rule(
constraint enforces exactly-one of (topic_id, project_id).
"""
_require_trigger(when_to_apply)
kind = _valid_kind(kind)
enforcement = require_enforcement(enforcement, kind)
salience = require_salience(salience)
async with async_session() as session:
await _assert_project_owned(session, project_id, user_id)
rule = Rule(
@@ -551,7 +597,7 @@ async def create_project_rule(
title=title,
statement=statement,
when_to_apply=when_to_apply or None,
kind=_valid_kind(kind),
kind=kind, enforcement=enforcement, salience=salience,
why=why or None,
how_to_apply=how_to_apply or None,
verify_with=verify_with or None,
@@ -691,7 +737,7 @@ async def update_rule(
allowed = {
"title", "statement", "why", "how_to_apply", "order_index",
"when_to_apply", "kind", "arose_from_id",
"verify_with", "expires_when",
"verify_with", "expires_when", "enforcement", "salience",
}
check_before = rule.verify_with
# A create-time guard is worth nothing if an edit can undo it, and
@@ -719,6 +765,11 @@ async def update_rule(
continue
if key == "kind":
value = _valid_kind(value)
elif key == "salience":
value = require_salience(value)
elif key == "enforcement":
# Checked against the kind after the loop, which may change it.
value = (value or "").strip().lower() or "inform"
elif key in NULLABLE_RULE_TEXT:
value = value or None
elif key == "arose_from_id":
@@ -731,6 +782,12 @@ async def update_rule(
# rule wrongly vouched for costs the thing the sweep exists to catch.
if rule.verify_with != check_before:
rule.verified_at = None
# A rule turned into a preference without naming an enforcement drops to
# `inform`, since a preference carries no other. Named explicitly
# alongside the new kind, a stronger enforcement is refused instead.
if rule.kind == "preference" and "enforcement" not in fields:
rule.enforcement = "inform"
rule.enforcement = require_enforcement(rule.enforcement, rule.kind)
if trigger_before and not (rule.when_to_apply or "").strip():
raise ValueError(
"when_to_apply cannot be cleared: it is how this rule arrives, "