Milestone 639 step 2: typed rules, one delivery order, per-delivery records, triggers, lifecycle #224
@@ -0,0 +1,48 @@
|
||||
"""rule enforcement and salience — what a rule does when it arrives, and how much it outranks
|
||||
|
||||
Revision ID: 0128
|
||||
Revises: 0127
|
||||
Create Date: 2026-11-22
|
||||
|
||||
Two declared columns on a rule, read by the one function that orders what
|
||||
reaches a moment:
|
||||
|
||||
- `enforcement`: `enforce` (the act itself is checked), `hold` (the reply or act
|
||||
waits for one read), `inform` (a line beside the work). Every existing rule
|
||||
starts as `inform`; declaring which ones hold is the author's call.
|
||||
- `salience`: `high`, `normal`, `low` — the author's ranking among rules of
|
||||
the same enforcement.
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0128"
|
||||
down_revision = "0127"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_ENFORCEMENTS = ("enforce", "hold", "inform")
|
||||
_SALIENCES = ("high", "normal", "low")
|
||||
|
||||
|
||||
def _in_list(column: str, values: tuple[str, ...]) -> str:
|
||||
return f"{column} IN ({', '.join(repr(v) for v in values)})"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("rules", sa.Column("enforcement", sa.Text(), nullable=False, server_default="inform"))
|
||||
op.add_column("rules", sa.Column("salience", sa.Text(), nullable=False, server_default="normal"))
|
||||
op.create_check_constraint("ck_rules_enforcement", "rules", _in_list("enforcement", _ENFORCEMENTS))
|
||||
op.create_check_constraint("ck_rules_salience", "rules", _in_list("salience", _SALIENCES))
|
||||
# A preference claims no force: it is how work is liked done, not a bar.
|
||||
op.create_check_constraint(
|
||||
"ck_rules_preference_informs", "rules", "kind <> 'preference' OR enforcement = 'inform'",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_constraint("ck_rules_preference_informs", "rules", type_="check")
|
||||
op.drop_constraint("ck_rules_salience", "rules", type_="check")
|
||||
op.drop_constraint("ck_rules_enforcement", "rules", type_="check")
|
||||
op.drop_column("rules", "salience")
|
||||
op.drop_column("rules", "enforcement")
|
||||
@@ -54,6 +54,15 @@ export interface RulebookTopic {
|
||||
*/
|
||||
export type RuleKind = "rule" | "preference";
|
||||
|
||||
/**
|
||||
* What a rule does when it arrives, declared by its author. `inform` puts a
|
||||
* line beside the work; `hold` makes the reply or act it governs wait for one
|
||||
* read; `enforce` checks the act itself. A preference is always `inform`.
|
||||
*/
|
||||
export type RuleEnforcement = "enforce" | "hold" | "inform";
|
||||
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
|
||||
export type RuleSalience = "high" | "normal" | "low";
|
||||
|
||||
/** A new record opened from somewhere that already knows what it is for —
|
||||
* "Adjust this" on a reply shape opens a preference mounted on that shape's
|
||||
* moment. The editor applies it once, when creating. */
|
||||
@@ -70,6 +79,8 @@ export interface Rule {
|
||||
title: string;
|
||||
statement: string;
|
||||
kind: RuleKind;
|
||||
enforcement: RuleEnforcement;
|
||||
salience: RuleSalience;
|
||||
/** WHEN this rule fires — the trigger, not the instruction. */
|
||||
when_to_apply: string;
|
||||
why: string;
|
||||
@@ -113,6 +124,10 @@ export interface RuleHeader {
|
||||
topic_id: number | null;
|
||||
/** Unconditional on the wire (services.rulebooks.rule_brief). */
|
||||
kind: RuleKind;
|
||||
/** Unconditional on the wire, like `kind`. */
|
||||
enforcement: RuleEnforcement;
|
||||
/** Present only when raised or lowered from `normal`. */
|
||||
salience?: RuleSalience;
|
||||
/** A date (YYYY-MM-DD), not a timestamp. */
|
||||
updated_at: string | null;
|
||||
when_to_apply?: string;
|
||||
@@ -217,6 +232,8 @@ export interface RuleWrite {
|
||||
/** Writable from the editor: a preference is not a lesser rule, it is a
|
||||
* different force, and the person writing it is the one who knows which. */
|
||||
kind: RuleKind;
|
||||
enforcement: RuleEnforcement;
|
||||
salience: RuleSalience;
|
||||
when_to_apply: string;
|
||||
why: string;
|
||||
how_to_apply: string;
|
||||
|
||||
@@ -6,7 +6,10 @@ import { useMomentsStore } from "@/stores/moments";
|
||||
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
|
||||
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks";
|
||||
import {
|
||||
listRulebooks, listTopics,
|
||||
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
|
||||
} from "@/api/rulebooks";
|
||||
|
||||
const props = defineProps<{
|
||||
ruleId: number | null;
|
||||
@@ -26,6 +29,14 @@ const whenToApply = ref("");
|
||||
// followed too faithfully, where a rule mislabelled as a preference is one a
|
||||
// session may quietly rewrite.
|
||||
const kind = ref<RuleKind>("rule");
|
||||
// The server's defaults: a line beside the work, at normal rank.
|
||||
const enforcement = ref<RuleEnforcement>("inform");
|
||||
const salience = ref<RuleSalience>("normal");
|
||||
// A preference carries no force but `inform`, and the server refuses any
|
||||
// other, so switching kind settles it here rather than as a failed save.
|
||||
watch(kind, (k) => {
|
||||
if (k === "preference") enforcement.value = "inform";
|
||||
});
|
||||
const systemIds = ref<number[]>([]);
|
||||
// The moments this rule is mounted on. Catalog moments are
|
||||
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its
|
||||
@@ -123,6 +134,8 @@ async function load() {
|
||||
statement.value = r.statement;
|
||||
whenToApply.value = r.when_to_apply || "";
|
||||
kind.value = r.kind;
|
||||
enforcement.value = r.enforcement ?? "inform";
|
||||
salience.value = r.salience ?? "normal";
|
||||
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
||||
ruleMoments.value = [...(r.moments ?? [])];
|
||||
why.value = r.why || "";
|
||||
@@ -135,6 +148,8 @@ async function load() {
|
||||
statement.value = "";
|
||||
whenToApply.value = props.preset?.whenToApply ?? "";
|
||||
kind.value = props.preset?.kind ?? "rule";
|
||||
enforcement.value = "inform";
|
||||
salience.value = "normal";
|
||||
systemIds.value = [];
|
||||
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
||||
why.value = "";
|
||||
@@ -181,6 +196,8 @@ async function save() {
|
||||
statement: statement.value,
|
||||
when_to_apply: whenToApply.value,
|
||||
kind: kind.value,
|
||||
enforcement: enforcement.value,
|
||||
salience: salience.value,
|
||||
// Always sent, so clearing the last area actually clears it — the server
|
||||
// reads a list as "these ARE the areas now".
|
||||
system_ids: systemIds.value,
|
||||
@@ -271,6 +288,38 @@ watch(() => props.ruleId, load);
|
||||
preference.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset class="kind arrival">
|
||||
<legend>When it arrives</legend>
|
||||
<template v-if="kind === 'rule'">
|
||||
<label class="kind-opt">
|
||||
<input v-model="enforcement" type="radio" value="inform" />
|
||||
<span><strong>Inform</strong> — a line beside the work. Most rules.</span>
|
||||
</label>
|
||||
<label class="kind-opt">
|
||||
<input v-model="enforcement" type="radio" value="hold" />
|
||||
<span>
|
||||
<strong>Hold</strong> — the reply or act it governs waits for one
|
||||
read of it. For a rule whose miss costs a rewrite.
|
||||
</span>
|
||||
</label>
|
||||
<label class="kind-opt">
|
||||
<input v-model="enforcement" type="radio" value="enforce" />
|
||||
<span>
|
||||
<strong>Enforce</strong> — the act itself is checked. For a hard
|
||||
boundary.
|
||||
</span>
|
||||
</label>
|
||||
</template>
|
||||
<p v-else class="field-note">A preference arrives as a line beside the work.</p>
|
||||
<label class="salience">
|
||||
Rank among the rest
|
||||
<select v-model="salience" class="fs-input">
|
||||
<option value="high">High — shown first when a moment is crowded</option>
|
||||
<option value="normal">Normal</option>
|
||||
<option value="low">Low — the first to give way</option>
|
||||
</select>
|
||||
</label>
|
||||
</fieldset>
|
||||
<p v-if="kind === 'preference'" class="kind-drift">
|
||||
Sessions rewrite preferences without asking, which is what makes them
|
||||
stay current. Every rewrite is kept, and
|
||||
|
||||
@@ -27,6 +27,15 @@ const emit = defineEmits<{
|
||||
class="rule-chip rule-chip-preference"
|
||||
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
|
||||
>preference</span>
|
||||
<!-- Marked only when the rule stops the work: a line beside the work
|
||||
is the default, and marking it on every row would mark nothing. -->
|
||||
<span
|
||||
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
|
||||
class="rule-chip"
|
||||
:title="r.enforcement === 'hold'
|
||||
? 'The reply or act it governs waits for one read of it'
|
||||
: 'The act it governs is checked against it'"
|
||||
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
|
||||
<!-- Marked only when something is WRONG: every rule arrives by
|
||||
retrieval now, so "conditional" stopped distinguishing anything.
|
||||
A missing trigger does — it means nothing can retrieve this. -->
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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 "",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, "
|
||||
|
||||
@@ -290,6 +290,9 @@ def fake_rule(**attrs) -> MagicMock:
|
||||
# claim to carry a check and rule_brief would stamp a MagicMock date
|
||||
# onto all of them. Most rules have none — that is the default here.
|
||||
"verify_with": None, "expires_when": None, "verified_at": None,
|
||||
# A MagicMock here would read as a declared enforcement and a raised
|
||||
# salience on every stand-in; the defaults are what a new rule gets.
|
||||
"enforcement": "inform", "salience": "normal",
|
||||
"order_index": 0, "created_at": _now(), "updated_at": _now(),
|
||||
}, attrs)
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Real-Postgres tests for `rules.enforcement` and `rules.salience` (migration 0128).
|
||||
|
||||
The CHECKs are what a mock cannot show: an unknown value refused, a preference
|
||||
refused anything but `inform`, and a row written without either reading back
|
||||
as the defaults every existing rule took on upgrade.
|
||||
"""
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.rulebook import Rule, Rulebook
|
||||
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_enforcement_owner"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def topic_id():
|
||||
# Purged at setup, not teardown: the write path's detached embedding task
|
||||
# would deadlock against a teardown deleting the rulebook.
|
||||
async with async_session() as s:
|
||||
owner = await ensure_user(s, OWNER_USERNAME)
|
||||
uid = owner.id
|
||||
await s.commit()
|
||||
for book in (await s.execute(
|
||||
select(Rulebook).where(Rulebook.owner_user_id == uid)
|
||||
)).scalars().all():
|
||||
await s.delete(book)
|
||||
await s.commit()
|
||||
book = await rulebooks_svc.create_rulebook(uid, "Enforcement fixtures")
|
||||
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
|
||||
return uid, topic.id
|
||||
|
||||
|
||||
async def _write_raw(topic: int, **kw) -> int:
|
||||
"""Straight to the model, around the service's own checks, to reach the CHECKs."""
|
||||
async with async_session() as s:
|
||||
rule = Rule(topic_id=topic, title=kw.pop("title", "t"), statement="s", **kw)
|
||||
s.add(rule)
|
||||
await s.commit()
|
||||
return rule.id
|
||||
|
||||
|
||||
async def _read(rule_id: int) -> Rule:
|
||||
async with async_session() as s:
|
||||
return (await s.execute(select(Rule).where(Rule.id == rule_id))).scalar_one()
|
||||
|
||||
|
||||
async def test_a_rule_written_without_either_reads_back_as_the_defaults(topic_id):
|
||||
_uid, topic = topic_id
|
||||
rule = await _read(await _write_raw(topic))
|
||||
assert (rule.enforcement, rule.salience) == ("inform", "normal")
|
||||
|
||||
|
||||
async def test_an_unknown_enforcement_is_refused_by_the_database(topic_id):
|
||||
_uid, topic = topic_id
|
||||
with pytest.raises(IntegrityError):
|
||||
await _write_raw(topic, enforcement="block")
|
||||
|
||||
|
||||
async def test_an_unknown_salience_is_refused_by_the_database(topic_id):
|
||||
_uid, topic = topic_id
|
||||
with pytest.raises(IntegrityError):
|
||||
await _write_raw(topic, salience="urgent")
|
||||
|
||||
|
||||
async def test_a_preference_that_holds_is_refused_by_the_database(topic_id):
|
||||
_uid, topic = topic_id
|
||||
with pytest.raises(IntegrityError):
|
||||
await _write_raw(topic, kind="preference", enforcement="hold")
|
||||
|
||||
|
||||
async def test_the_service_writes_a_declared_hold_and_reads_it_back(topic_id):
|
||||
uid, topic = topic_id
|
||||
rule = await rulebooks_svc.create_rule(
|
||||
topic, uid, "Holds", "Read before replying", when_to_apply="about to reply",
|
||||
enforcement="hold", salience="high",
|
||||
)
|
||||
back = await _read(rule.id)
|
||||
assert (back.enforcement, back.salience) == ("hold", "high")
|
||||
assert rulebooks_svc.rule_brief(back)["enforcement"] == "hold"
|
||||
assert rulebooks_svc.rule_brief(back)["salience"] == "high"
|
||||
|
||||
|
||||
async def test_the_service_refuses_a_preference_that_holds(topic_id):
|
||||
uid, topic = topic_id
|
||||
with pytest.raises(ValueError, match="always `inform`"):
|
||||
await rulebooks_svc.create_rule(
|
||||
topic, uid, "Pref", "Prefer x", when_to_apply="when x",
|
||||
kind="preference", enforcement="hold",
|
||||
)
|
||||
|
||||
|
||||
async def test_a_rule_turned_into_a_preference_drops_to_inform(topic_id):
|
||||
uid, topic = topic_id
|
||||
rule = await rulebooks_svc.create_rule(
|
||||
topic, uid, "Becomes a preference", "Do x", when_to_apply="when x",
|
||||
enforcement="enforce",
|
||||
)
|
||||
updated = await rulebooks_svc.update_rule(rule.id, uid, kind="preference")
|
||||
assert (updated.kind, updated.enforcement) == ("preference", "inform")
|
||||
|
||||
|
||||
async def test_naming_a_hold_alongside_the_preference_kind_is_refused(topic_id):
|
||||
uid, topic = topic_id
|
||||
rule = await rulebooks_svc.create_rule(
|
||||
topic, uid, "Stays a rule", "Do y", when_to_apply="when y",
|
||||
)
|
||||
with pytest.raises(ValueError, match="always `inform`"):
|
||||
await rulebooks_svc.update_rule(rule.id, uid, kind="preference", enforcement="hold")
|
||||
assert (await _read(rule.id)).kind == "rule"
|
||||
@@ -624,13 +624,15 @@ def test_rule_rows_carry_the_verification_fields():
|
||||
row = SimpleNamespace(
|
||||
id=1, topic_id=2, project_id=None, title="t", statement="s",
|
||||
why="w", how_to_apply="h", order_index=0,
|
||||
when_to_apply="when", kind="rule",
|
||||
when_to_apply="when", kind="rule", enforcement="hold", salience="high",
|
||||
verify_with="cat some/file", expires_when="the file grows a shell",
|
||||
verified_at=checked, arose_from_id=99,
|
||||
created_at=checked, updated_at=checked,
|
||||
)
|
||||
out = backup._rule_rows([row])[0]
|
||||
|
||||
assert (out["enforcement"], out["salience"]) == ("hold", "high")
|
||||
|
||||
assert out["verify_with"] == "cat some/file"
|
||||
assert out["expires_when"] == "the file grows a shell"
|
||||
assert out["verified_at"] == checked.isoformat()
|
||||
@@ -650,7 +652,7 @@ def test_rule_rows_keep_an_unverified_rule_unverified():
|
||||
row = SimpleNamespace(
|
||||
id=1, topic_id=2, project_id=None, title="t", statement="s",
|
||||
why=None, how_to_apply=None, order_index=0,
|
||||
when_to_apply=None, kind="rule",
|
||||
when_to_apply=None, kind="rule", enforcement="inform", salience="normal",
|
||||
verify_with=None, expires_when=None, verified_at=None,
|
||||
arose_from_id=None,
|
||||
created_at=datetime(2026, 8, 27, tzinfo=timezone.utc),
|
||||
@@ -680,7 +682,7 @@ def test_rule_rows_carry_the_kind_so_a_preference_does_not_restore_as_a_rule():
|
||||
row = SimpleNamespace(
|
||||
id=1, topic_id=2, project_id=None, title="t", statement="s",
|
||||
why=None, how_to_apply=None, order_index=0,
|
||||
when_to_apply="when", kind="preference",
|
||||
when_to_apply="when", kind="preference", enforcement="inform", salience="normal",
|
||||
verify_with=None, expires_when=None, verified_at=None,
|
||||
arose_from_id=None, created_at=stamp, updated_at=stamp,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user