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
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:
@@ -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],
|
||||
|
||||
Reference in New Issue
Block a user