feat(7728): one delivery order for rules, and each delivery recorded with whether it was opened
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 1m59s
CI & Build / Build & push image (push) Skipped

Every rule arm now ranks what it delivers with one function
(services/rule_order.py): enforcement, then salience, then how narrowly
the rule was reached, then first mention before reminder, then the
rule's own open rate at that moment, then similarity. A crowded moment
drops the same rules whichever arm brought them, and a rule that holds
is never cut for a line beside it.

The open rate comes from a new table, rule_deliveries (migration 0129):
one row per rule line a plugin session is shown, full or repeat, with the
open stamped on the latest delivery it followed. The plugin routes bind
the session per request; the prompt, pre-tool and write-path hooks now
send it, and the opened hook reports every open, with its acts only when
no hook had just named the rule. Rows are pruned daily after 180 days.

Also fixes the TypeScript check: the store's list row now carries the
new enforcement field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:13:16 -05:00
co-authored by Claude Opus 5.5
parent 61077752b9
commit 61873b184b
20 changed files with 759 additions and 23 deletions
+4
View File
@@ -183,6 +183,10 @@ _NOT_INCLUDED = [
"app_logs", "notifications",
"invitation_tokens", "password_reset_tokens",
"retrieval_logs",
# Per-session delivery rows, keyed by session ids that mean nothing on
# another instance and pruned after months anyway. The ordering reads
# them as history; a restored instance rebuilds it within weeks.
"rule_deliveries",
# Verdicts on retrieval_logs rows, so they go where their subject
# goes: a restore that carried a judgment of a call it did not carry would
# leave a verdict on nothing. A sample, re-takeable by the review pass.
+4 -1
View File
@@ -24,11 +24,14 @@ logger = logging.getLogger(__name__)
def _io() -> rp.MomentIO:
"""Resolved at CALL time, so a test patching either module's name is seen."""
from grimoire.services import rule_usage, rulebooks
from grimoire.services import rule_deliveries, rule_usage, rulebooks
bound = rule_deliveries.bound()
return rp.MomentIO(
lookup=rulebooks.rules_on_moments,
record_rule_surfaced=rule_usage.record_rule_surfaced,
history=rule_deliveries.history if bound else None,
record_delivery=rule_deliveries.record if bound else None,
)
+5
View File
@@ -974,10 +974,15 @@ def _rule_io() -> rp.RuleIO:
the pipeline reports to whatever this module's `semantic_search_rules`,
`record_retrieval` and `record_rule_surfaced` are at the moment it runs.
"""
from grimoire.services import rule_deliveries
bound = rule_deliveries.bound()
return rp.RuleIO(
search=semantic_search_rules,
record_retrieval=record_retrieval,
record_rule_surfaced=record_rule_surfaced,
history=rule_deliveries.history if bound else None,
record_delivery=rule_deliveries.record if bound else None,
)
+70 -2
View File
@@ -35,6 +35,7 @@ import time
from dataclasses import dataclass, field
from typing import Any, Callable
from grimoire.services import rule_order
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
logger = logging.getLogger(__name__)
@@ -576,6 +577,12 @@ class RuleIO:
record_retrieval: Callable[..., Any]
record_rule_surfaced: Callable[..., Any]
history: Callable[..., Any] | None = None
"""`rule_deliveries.history`: `{rule_id: open rate}` for (rule, at) pairs.
None leaves every rule's history unknown."""
record_delivery: Callable[..., Any] | None = None
"""`rule_deliveries.record`: each line shown, against the session the
door bound. None records nothing."""
@dataclass(frozen=True)
@@ -773,6 +780,30 @@ async def _reserve_slot_for_preference(
# ── The pipeline ─────────────────────────────────────────────────────────
def _record_delivery(io, moment: RuleMoment, source: str, shown: list[tuple[int, str, bool]]) -> None:
"""Record each line shown — `(rule_id, at, was_a_repeat)` — as a delivery."""
if io.record_delivery is None or not shown:
return
try:
io.record_delivery(moment.user_id, None, source, [
(rid, at, "repeat" if repeat else "full") for rid, at, repeat in shown
])
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(source)
async def _history(io, moment: RuleMoment, pairs: list[tuple[int, str]]) -> dict[int, float]:
"""Each rule's open rate where it is about to be delivered; {} when the
door has no history to read or the read fails — unknown, never an error."""
if io.history is None or not pairs:
return {}
try:
return await io.history(moment.user_id, pairs) or {}
except Exception: # noqa: BLE001 - history orders lines, it never withholds them
logger.debug("rule delivery history unreadable", exc_info=True)
return {}
async def run_rule_arm(
arm: RuleArm, moment: RuleMoment, *, floor: float, budget: int, io: RuleIO,
checkpoint_floor: float = 0.0,
@@ -801,6 +832,19 @@ async def run_rule_arm(
# still has something to say, it just says it differently.
if not shown:
return RuleResult()
# Into the one delivery order: a rule that holds outranks one that
# informs whatever their scores, and score breaks the last tie.
history = await _history(io, moment, [(rule.id, arm.source) for _s, rule in shown])
shown = [
c.extra for c in rule_order.ordered(
rule_order.Candidate(
rule=rule, specificity=rule_order.BY_RESEMBLANCE,
opened_rate=history.get(rule.id), similarity=score,
seen=rule.id in moment.exclude, extra=(score, rule),
)
for score, rule in shown
)
]
lines = [
_rule_hint_line(
@@ -836,6 +880,11 @@ async def run_rule_arm(
)
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(source)
# A stop-only arm shows its lines to nobody: only a hold speaks.
if not arm.stop_only:
_record_delivery(io, moment, source, [
(rule.id, source, rule.id in moment.exclude) for _s, rule in shown
])
return RuleResult(
lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for _score, rule in shown],
@@ -1597,6 +1646,10 @@ class MomentIO:
"""`rulebooks.rules_on_moments`, or a stand-in with its signature."""
record_rule_surfaced: Callable[..., Any]
history: Callable[..., Any] | None = None
"""As on `RuleIO`."""
record_delivery: Callable[..., Any] | None = None
"""As on `RuleIO`."""
def _reached_by(hit: dict) -> str:
@@ -1626,8 +1679,20 @@ async def run_moment_arm(
if not pairs:
return RuleResult()
by_moment = {hit["moment"]: hit for hit in reached}
# Stable: catalog order within each half, fresh half first.
shown = sorted(pairs, key=lambda pair: pair[0].id in moment.exclude)[:limit]
# 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.
history = await _history(io, moment, [(rule.id, at) for rule, at in pairs])
shown = [
c.extra for c in rule_order.ordered(
rule_order.Candidate(
rule=rule, specificity=rule_order.BY_MOUNT,
opened_rate=history.get(rule.id),
seen=rule.id in moment.exclude, extra=(rule, at),
)
for rule, at in pairs
)
][:limit]
lines = []
for rule, at in shown:
@@ -1651,6 +1716,9 @@ async def run_moment_arm(
)
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(MOMENT_RULE_SOURCE)
_record_delivery(io, moment, MOMENT_RULE_SOURCE, [
(rule.id, at, rule.id in moment.exclude) for rule, at in shown
])
return RuleResult(
lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for rule, _at in shown],
+180
View File
@@ -0,0 +1,180 @@
"""Each rule line a session is shown, whether it was opened after, and what
that history says about where a rule is worth delivering.
Three calls, one table (`rule_deliveries`):
- `record` — fire-and-forget, from the plugin doors that know the session:
every line an arm put in front of it, full or repeat.
- `mark_opened` — the session opened a rule: the latest unopened delivery of
it in that session gets the stamp. An open with no delivery behind it (the
agent looked a rule up unprompted) stamps nothing.
- `history` — for the ordering function: each rule's smoothed open rate at
the place it is about to be delivered, over the last `HISTORY_DAYS`.
Deliveries are kept `RETAIN_DAYS` and pruned daily: enough history to rank on
and to read adherence from, without a row per tool call accumulating forever.
"""
from __future__ import annotations
import logging
import re
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import FORMS, FULL, RuleDelivery
from grimoire.services import rule_order
from grimoire.services.background import spawn
logger = logging.getLogger(__name__)
HISTORY_DAYS = 90
RETAIN_DAYS = 180
# An open counts against a delivery made within this window before it; an
# older one was read by a context that is long gone.
OPEN_WINDOW = timedelta(hours=6)
_SESSION_MAX = 200
_UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
# The session a plugin request is delivering to, bound once per request by the
# plugin routes so the arms several calls deep record against it without every
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
def bind_session(session_id: str | None) -> None:
_session.set(_clean_session(session_id))
def bound() -> bool:
"""Whether this request delivers to a known session — the doors that
record deliveries are the ones that read their history back."""
return bool(_session.get())
def _clean_session(session_id: str | None) -> str:
# The plugin's own filename-safe form of the id, so a hook that sends the
# raw id and one that sends the safe one name the same session.
return _UNSAFE.sub("_", (session_id or "").strip())[:_SESSION_MAX]
def record(
user_id: int, session_id: str | None, source: str,
lines: list[tuple[int, str, str]],
) -> None:
"""Record delivered lines: `(rule_id, at, form)` each. Fire-and-forget,
and a no-op without a session, since an open could never be tied back.
`session_id` None means the one bound for this request."""
sid = _clean_session(_session.get() if session_id is None else session_id)
if not sid or not lines:
return
try:
rows = [
{"user_id": int(user_id), "session_id": sid, "rule_id": int(rid),
"source": source, "at": str(at or source), "form": form if form in FORMS else FULL}
for rid, at, form in lines
]
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("rule delivery payload build failed", exc_info=True)
return
spawn(_insert(rows), site="rule_delivery_write")
async def _insert(rows: list[dict]) -> None:
async with async_session() as session:
session.add_all(RuleDelivery(**row) for row in rows)
await session.commit()
async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> bool:
"""Stamp the latest unopened delivery of this rule in this session.
Returns whether a delivery was stamped. Only that one: a rule delivered
five times and opened once was opened after the fifth line, and the four
before it were passed over.
"""
sid = _clean_session(session_id)
if not sid or not rule_id:
return False
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(RuleDelivery.id)
.where(
RuleDelivery.user_id == user_id,
RuleDelivery.session_id == sid,
RuleDelivery.rule_id == rule_id,
RuleDelivery.opened_at.is_(None),
RuleDelivery.delivered_at >= now - OPEN_WINDOW,
)
.order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
.limit(1)
)).scalar_one_or_none()
if latest is None:
return False
await session.execute(
update(RuleDelivery).where(RuleDelivery.id == latest).values(opened_at=now)
)
await session.commit()
return True
async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float]:
"""`{rule_id: smoothed open rate}` at each pair's place, for this user.
A rule with no delivery there is left out, which the ordering reads as
unknown rather than as never opened.
"""
wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs))
if not wanted:
return {}
since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
async with async_session() as session:
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,
tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted),
)
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all()
return {
int(rid): rule_order.opened_rate(int(delivered), int(opened or 0))
for rid, _at, delivered, opened in rows
}
async def prune(retain_days: int = RETAIN_DAYS) -> int:
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
async with async_session() as session:
result = await session.execute(
delete(RuleDelivery).where(and_(RuleDelivery.delivered_at < cutoff))
)
await session.commit()
return int(result.rowcount or 0)
_prune_task = None
async def _prune_tick() -> None:
try:
removed = await prune()
if removed:
logger.info("Rule delivery retention: deleted %d row(s)", removed)
except Exception:
logger.exception("Rule delivery retention failed")
def start_prune_loop() -> None:
global _prune_task
if _prune_task is None or _prune_task.done():
from grimoire.services.background import start_periodic
_prune_task = start_periodic(86400, _prune_tick, label="rule_delivery_retention") # daily
+80
View File
@@ -0,0 +1,80 @@
"""The one order in which rules reach a moment.
Every arm that puts rules in front of a session — the rules mounted on a
moment, the rules a typed trigger matched, the rules a semantic search found —
ranks what it has the same way, so a crowded moment drops the same rules
whichever arm brought them:
1. **enforcement** — `enforce`, then `hold`, then `inform`. A rule that stops
the work is never the one cut to make room for a line beside it.
2. **salience** — `high`, `normal`, `low`, as the rule's author declared it.
3. **specificity** — how narrowly the rule was reached. A trigger that named
this command or this path says more than a mount on the whole moment, and a
mount says more than a resemblance.
4. **news** — at the same rank, a rule this session has not been shown yet
comes before one it has, so a cap cuts a reminder rather than a first
mention.
5. **history** — how often this rule was opened when delivered at this
moment before. A rule sessions keep opening here outranks one they keep
passing over.
6. **similarity** — the search score, when there is one. Last, because it is
the one signal that says what the work resembles rather than what it is.
Each key is a declared or recorded fact, read in that order, so the outcome
can be explained line by line: "it outranked that one because it holds".
"""
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
# How narrowly a rule was reached, larger is narrower.
BY_RESEMBLANCE = 0
BY_MOUNT = 1
BY_TRIGGER = 2
# A rule with no delivery history at a moment ranks as if half its deliveries
# there were opened: unknown is neither proof of use nor of neglect.
UNKNOWN_HISTORY = 0.5
@dataclass(frozen=True)
class Candidate:
"""One rule an arm could deliver, with what it knows about how it got here."""
rule: Any
specificity: int = BY_RESEMBLANCE
opened_rate: float | None = None
"""Share of this rule's earlier deliveries at this moment that were opened."""
similarity: float | None = None
seen: bool = False
"""Already shown to this session."""
extra: Any = None
"""Whatever the arm needs back with the rule — the moment it was mounted
on, its score pair — carried through the sort untouched."""
def order_key(c: Candidate) -> tuple:
rule = c.rule
return (
ENFORCEMENT_RANK.get(getattr(rule, "enforcement", None) or "inform", 2),
SALIENCE_RANK.get(getattr(rule, "salience", None) or "normal", 1),
-c.specificity,
c.seen,
-(UNKNOWN_HISTORY if c.opened_rate is None else c.opened_rate),
-(c.similarity or 0.0),
)
def ordered(candidates: Iterable[Candidate]) -> list[Candidate]:
"""The candidates in delivery order. Stable: ties keep the arm's own order."""
return sorted(candidates, key=order_key)
def opened_rate(delivered: int, opened: int) -> float:
"""A smoothed open rate, so one delivery opened once does not read as certainty."""
return (opened + 1) / (delivered + 2)