feat(7731): enforced rules refuse the act, only hold rules hold, and the shape question rides the next prompt
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m45s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Skipped

- A rule set to enforce, reached by a mount or a trigger, refuses the tool
  call in its own words every time (`act_decision`, `/moment` returns
  `decision`, grimoire_moment.sh denies). Opening it does not lift it.
- A rule set to hold denies the call once until read, under the act
  checkpoint's per-rule and per-session guard; file writes are never held.
- The reply hold, the reply backstop and the act checkpoint hold only on rules
  declared hold or enforce (`rule_order.holds`). An inform rule is a line
  beside the work.
- The prompt arm leaves rules that arrive at an act (mounted on a non-reply
  moment, or with a tool/path/command trigger) to that act.
- The end-of-turn shape check no longer blocks: its note is kept for the next
  prompt, carried as `carry` into the one fitted payload, and the stop after
  that prompt records whether the lines were judged (noted /
  judged_after_note / left_after_note).
- Rule editor and list copy say what hold and enforce now do. Plugin
  2026.11.23.0005.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 00:22:56 -05:00
co-authored by Claude Opus 5.5
parent 6b4c24e336
commit 7d46ce0229
23 changed files with 644 additions and 170 deletions
+43 -7
View File
@@ -16,7 +16,7 @@ from __future__ import annotations
import logging
from grimoire.services import hook_payload, moment_actions, reply_shapes
from grimoire.services import hook_payload, moment_actions, reply_shapes, rule_order
from grimoire.services import retrieval_pipeline as rp
logger = logging.getLogger(__name__)
@@ -121,9 +121,43 @@ async def deliver_for_act(
result = await deliver_moments(
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
)
# A write is never held for a read: a recall aid does not stand in the
# way of the work. A rule set to enforce still refuses one — that is a
# boundary the operator drew, not a reminder.
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
result.decision = {}
return reached, result
# The file-writing tools, as tool keys: a `hold` rule never holds these.
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
async def routed_to_acts(user_id: int, project_id: int | None = None) -> frozenset[int]:
"""The rules that arrive at an act, so the prompt arm leaves them there.
A rule mounted on a moment some action is mapped to (every moment but the
reply moments), or carrying a `tool`, `path` or `command` trigger, reaches
the session at the call it governs. Delivered at the prompt too, it would
arrive twice, and the first time beside a request it competes with. A
keyword trigger can also match a reply, so it does not count.
"""
from grimoire.services import rule_triggers, rulebooks
mappings = await moment_actions.list_mappings(user_id)
act_moments = sorted({
action.moment for action, _via in moment_actions.effective_actions(mappings)
if not action.moment.startswith("reply.")
})
out = {rule.id for rule, _at in await rulebooks.rules_on_moments(
user_id, act_moments, project_id or None,
)} if act_moments else set()
for rule, triggers in await rule_triggers._in_scope(user_id, project_id or None):
if any(t.kind in ("tool", "path", "command") and not t.moment for t in triggers):
out.add(rule.id)
return frozenset(out)
def shapes_for_act(reached: list[dict], seen: frozenset[str] = frozenset()) -> tuple[list[str], dict[str, str]]:
"""The default reply shapes riding the moments this act reached.
@@ -238,8 +272,8 @@ async def attach_moment_rules(
# your end" gets said — so it is checked twice over: the rules MOUNTED on the
# reply moments (deterministic, somebody said they belong here), and the
# reply text against every rule's trigger (the backstop for whatever the
# earlier arms missed). An unopened rule from either half HOLDS the reply for
# one read, in these words; the hook never holds the rewrite.
# earlier arms missed). An unopened rule set to hold, from either half, HOLDS
# the reply for one read, in these words; the hook never holds the rewrite.
# The reply's head and tail. The embedder reads ~512 tokens, and the part of
# a report that asks something of the reader — "let me know if it works" —
@@ -339,13 +373,15 @@ async def reply_hold(
room = pc.CHECKPOINT_SESSION_CAP - len(stopped)
out: list[dict] = []
# The mounted half: deterministic, so every unopened RULE on these
# moments holds. A preference claims no such force. A mount
# conditional on a trigger holds only when the reply meets it.
# The mounted half: deterministic, so every unopened rule on these
# moments that is declared to hold (`hold` or `enforce`) holds. An
# `inform` rule was put in front of the turn before the reply was
# written, and a preference claims no force. A mount conditional on
# a trigger holds only when the reply meets it.
board = await _board(user_id, project_id, text=reply)
gated = board.gated if board is not None else set()
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
if rule.id in skip or rule.kind == "preference" or (rule.id, at) in gated:
if rule.id in skip or not rule_order.holds(rule) or (rule.id, at) in gated:
continue
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
"trigger": (rule.when_to_apply or "").strip()})
+14
View File
@@ -985,6 +985,7 @@ async def build_prompt_rule_hint(
# the bound project's own. An unbound session (project_id 0) gets
# global rules only — this surface speaks unasked, and a whole-rulebook
# answer is only right for someone who asked the whole rulebook.
# A rule that reaches the session at an act is left for that act.
result = await _rule_moment(
rp.PROMPT_RULE,
rp.RuleMoment(
@@ -992,6 +993,7 @@ async def build_prompt_rule_hint(
where="to this request",
exclude=frozenset(exclude_rule_ids or []),
held=frozenset(held_rule_ids or []),
elsewhere=await _routed_for(user_id, project_id),
),
floor=await floor_for(user_id, "prompt_rule"),
budget=await budget_for(user_id, "prompt_rule"),
@@ -1011,6 +1013,18 @@ async def build_prompt_rule_hint(
return out
async def _routed_for(user_id: int, project_id: int) -> frozenset[int]:
"""The rules that arrive at an act (`moment_delivery.routed_to_acts`);
empty when they cannot be read, so the prompt arm delivers as before."""
from grimoire.services import moment_delivery
try:
return await moment_delivery.routed_to_acts(user_id, project_id or None)
except Exception: # noqa: BLE001 - a recall aid never breaks the prompt
logger.debug("act-routed rules unreadable", exc_info=True)
return frozenset()
def _rule_io() -> rp.RuleIO:
"""The ranker and recorders the rule arms report to, read at call time.
+101 -8
View File
@@ -105,12 +105,11 @@ def checkpoint_for(
floor; only a hit the corpus is confident about is allowed to stop
anything.
2. IT IS A RULE, NEVER A PREFERENCE. A preference says how something has
been done before and following it is what keeps work consistent; a rule
says what happens if you do not. Stopping an act over a preference
would assert a force the record explicitly does not claim, and
`_rule_hint_line` already keeps that distinction in the one word that
names it.
2. IT IS A RULE DECLARED TO HOLD (`rule_order.holds`): `hold` or
`enforce`, never `inform`, never a preference. A preference says how
something has been done before; an `inform` rule asked to be put beside
the work. Stopping an act over either would assert a force the record
does not claim.
3. THE SESSION HAS NOT OPENED IT. `held` is observable — a PostToolUse
hook watches for the `get_rule` call — so this is a recorded
@@ -134,7 +133,7 @@ def checkpoint_for(
score, rule = kept[0]
if score < floor:
return {}
if getattr(rule, "kind", "") == "preference":
if not rule_order.holds(rule):
return {}
if rule.id in held:
return {}
@@ -545,6 +544,12 @@ class RuleMoment:
held: frozenset[int] = frozenset()
"""Rules the session has OPENED."""
elsewhere: frozenset[int] = frozenset()
"""Rules that arrive at an act — mounted on a moment a tool call reaches,
or triggered by a tool, path or command — and so are not delivered here
by resemblance. A reminder read at the act is the one acted on; the same
line at the prompt competes with the request it came beside."""
@dataclass
class RuleResult:
@@ -563,6 +568,11 @@ class RuleResult:
checkpoint: dict = field(default_factory=dict)
decision: dict = field(default_factory=dict)
"""The moment arm's answer for the act itself, empty when the act goes
ahead: `{"kind": "enforce" | "hold", "rule_ids", "reason"}`. See
`act_decision`."""
line_rule_ids: list[int] = field(default_factory=list)
"""The rule behind each of `lines`, in order, when a caller added lines
of its own after the arm's; empty means `shown_rule_ids` lines up."""
@@ -644,6 +654,8 @@ async def _ranked(
# this done" asserts a force the record does not have.
hits = [(score, rule) for score, rule in hits
if getattr(rule, "kind", None) == kind]
if moment.elsewhere:
hits = [(score, rule) for score, rule in hits if rule.id not in moment.elsewhere]
kept = _rule_band(hits) if band else hits
# The gate is part of the cut, like the band: what it turns away is not
# shown, so it is not in the row's results either.
@@ -1749,11 +1761,16 @@ async def run_moment_arm(
taken.add(rule.id)
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
rule_order.BY_TRIGGER))
# Read before retirement: a rule that enforces does so on every act it
# reaches, however often this session has been shown it.
decision = act_decision(
[(rule, at, where) for rule, at, where, _s in cands], held=moment.held,
)
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
if gone:
cands = [c for c in cands if c[0].id not in gone]
if not cands:
return RuleResult()
return RuleResult(decision=decision)
# The one delivery order (services/rule_order.py), then the cap — so
# what a crowded moment drops is the lowest-ranked, not the last
# mounted. Ties keep catalog order.
@@ -1798,7 +1815,83 @@ async def run_moment_arm(
lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for rule, _at, _where in shown],
shown=[(None, rule) for rule, _at, _where in shown],
decision=decision,
)
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
return RuleResult()
def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) -> dict:
"""What the act itself is told, from the rules its moments and triggers reached.
`reached` is `(rule, at, where)` for every rule the act reached, in any
order. Sync and pure, so it can be read against a fixed list.
- A rule declared `enforce` REFUSES the act, every time it is reached:
`{"kind": "enforce", ...}` with the rules' own words as the reason. It
is a boundary the operator drew, and the act is the place it is drawn —
reaching it by mount or trigger is a structural fact, never a
resemblance. Opening the rule does not lift it; changing the rule does.
- Otherwise the first rule declared `hold` that the session has not
opened HOLDS the act for one read: `{"kind": "hold", ...}`. The client
holds a rule once per session and caps holds per session, as at the act
checkpoint.
- Otherwise `{}`: the act goes ahead, with any lines beside it.
A preference never refuses or holds (`rule_order.force`).
"""
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
if enforced:
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
"reason": enforce_reason(enforced)}
for rule, at, where in reached:
if rule_order.force(rule) == "hold" and rule.id not in held:
return {"kind": "hold", "rule_ids": [rule.id],
"reason": hold_reason(rule, at=at, where=where)}
return {}
def enforce_reason(enforced: list[tuple]) -> str:
"""The text the agent reads instead of the act running, for an `enforce` rule.
Says which rule drew the line and where, gives its own words, and names
who can move it: the operator, by changing the rule. A rule reached by
the wrong act is a misfire the reader can record in one call.
"""
parts = []
for rule, at, where in enforced:
statement = _statement_excerpt(rule)
parts.append(
f"“{rule.title}” (Rule {rule.id}, {where})"
+ (f": {statement}" if statement else "")
)
first_rule, first_at, _w = enforced[0]
noun = "a rule" if len(enforced) == 1 else "rules"
return (
f"Not run: this act reaches {noun} the operator set to enforce. "
+ " · ".join(parts)
+ ". An enforced rule stops the act rather than sitting beside it, and "
"opening it does not lift it. If the operator has asked for this act, "
"tell them which rule stopped it: they lift it by changing the rule's "
"enforcement or its trigger. If the rule has nothing to do with this "
f"act, rule_misfired({first_rule.id}, \"{first_at}\", why) records that."
)
def hold_reason(rule, *, at: str, where: str) -> str:
"""The text the agent reads instead of the act running, for a `hold` rule.
A practice on the act checkpoint's model: one read, then the act may be
re-submitted unchanged.
"""
trigger = (getattr(rule, "when_to_apply", "") or "").strip()
return (
f"Held for one read. “{rule.title}” (Rule {rule.id}, {where}) is set to "
f"hold the work it governs, and this session has not opened it"
+ (f" — it applies when {trigger}" if trigger else "")
+ f". Read it with get_rule({rule.id}), then re-submit this call — "
"unchanged if the rule does not apply, which is a judgement only you "
"can make. If it has nothing to do with this act, "
f"rule_misfired({rule.id}, \"{at}\", why) records that."
)
+23
View File
@@ -32,6 +32,29 @@ from typing import Any
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
def force(rule: Any) -> str:
"""What this rule does when it arrives: `enforce`, `hold` or `inform`.
A preference is always `inform`, whatever the field says: it records how
work is liked, and claims no force that could stop it.
"""
if getattr(rule, "kind", None) == "preference":
return "inform"
value = getattr(rule, "enforcement", None)
return value if value in ENFORCEMENT_RANK else "inform"
def holds(rule: Any) -> bool:
"""Whether this rule may make a reply or an act wait for one read.
Only a rule declared `hold` or `enforce` may. Every other rule is a line
beside the work: holding the work on a rule nobody declared as one that
holds made each reply after a write cost a rewrite, for rules that asked
only to be read.
"""
return force(rule) in ("enforce", "hold")
# How narrowly a rule was reached, larger is narrower.
BY_RESEMBLANCE = 0
BY_MOUNT = 1
+31 -24
View File
@@ -33,15 +33,21 @@ from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.app_log import AppLog
# check — the turn's first stop: block if anything is unjudged.
# after — the stop that follows a block: never block again, only record
# whether the agent answered.
# check — a turn's stop: note what is unjudged, for the next prompt.
# after — the stop after the note was read: record whether the agent
# answered it.
PHASES = ("check", "after")
OUTCOMES = ("passed", "blocked", "judged_after_block", "left_after_block")
# `blocked` and its two answers are the outcomes of the end-of-turn hold this
# check once was; they stay readable so a window spanning both still sums.
OUTCOMES = ("passed", "noted", "judged_after_note", "left_after_note",
"blocked", "judged_after_block", "left_after_block")
ASKED = ("noted", "blocked")
LEFT = ("left_after_note", "left_after_block")
# How many shapes the reason names before "+N more". Enough to judge a normal
# turn in one call; a turn that wrote more than this generated something.
_LISTED = 25
# How many shapes the note names before "+N more". It rides the next prompt
# inside the payload budget, so it names the first few and the call that
# lists the rest.
_LISTED = 8
def _evidence_note(evidence: dict) -> str:
@@ -62,8 +68,9 @@ def _evidence_note(evidence: dict) -> str:
return f" ({'; '.join(parts)})" if parts else ""
def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
"""What the agent is told at the end of a turn that wrote unjudged shapes.
def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str:
"""What the agent reads at the start of the turn after one that wrote
unjudged shapes.
Phrased as a practice: what to decide and the one
call that records it, not a prohibition. The reusing-code skill owns the
@@ -81,10 +88,10 @@ def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)")
repo_arg = f', repo="{repo}"' if repo else ""
return (
f"This turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
"that nobody has judged yet. You built them, so you know what each one is — "
"record it now, while that is still true, so the next session starts from your "
"answer instead of rebuilding it:\n"
"record it alongside this turn's work, while that is still true, so the next "
"session starts from your answer instead of rebuilding it:\n"
+ "\n".join(lines)
+ "\n\nFor each: something another part of the code should reuse → record it "
"with create_snippet (name, code, when to reach for it, location); built from a "
@@ -122,11 +129,11 @@ async def record_shape_check(
def outcome_for(phase: str, unjudged: list[dict]) -> str:
"""The recorded outcome: a first stop blocks or passes; the stop after a
block records whether the agent answered, and never blocks."""
"""The recorded outcome: a turn's stop notes or passes; the stop after
the note was read records whether the agent answered it."""
if phase == "after":
return "left_after_block" if unjudged else "judged_after_block"
return "blocked" if unjudged else "passed"
return "left_after_note" if unjudged else "judged_after_note"
return "noted" if unjudged else "passed"
def parse_written(raw: str, *, cap: int = 200) -> list[tuple[str, str, str]]:
@@ -158,14 +165,14 @@ WINDOW_DAYS = 7
def summarise(outcomes: list[str]) -> dict:
"""{checked, asked, left} from a list of recorded outcomes.
`checked` is turns the question was put to (a first stop that wrote
something): passed + blocked. `asked` is the blocked ones. `left` is
asks the agent walked past — the stop after a block that still had
unjudged shapes. That last number is the slip this check exists to make
visible."""
checked = sum(1 for o in outcomes if o in ("passed", "blocked"))
asked = sum(1 for o in outcomes if o == "blocked")
left = sum(1 for o in outcomes if o == "left_after_block")
`checked` is turns the question was put to (a stop after a turn that
wrote something): passed + asked. `asked` is the ones that found
something unjudged. `left` is asks the agent walked past — answered by a
stop that still had unjudged shapes. That last number is the slip this
check exists to make visible."""
checked = sum(1 for o in outcomes if o == "passed" or o in ASKED)
asked = sum(1 for o in outcomes if o in ASKED)
left = sum(1 for o in outcomes if o in LEFT)
return {"checked": checked, "asked": asked, "left": left}