Merge pull request 'Open rates count only deliveries whose plugin reports opens; a rule with triggers holds only the acts they match' (#227) from dev into main
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Successful in 2m11s
CI & Build / integration (push) Successful in 2m23s
CI & Build / Build & push image (push) Successful in 19s

This commit was merged in pull request #227.
This commit is contained in:
2026-11-23 16:12:35 -05:00
28 changed files with 200 additions and 21 deletions
@@ -0,0 +1,26 @@
"""rule deliveries record the plugin version that asked for the line
Revision ID: 0133
Revises: 0132
Create Date: 2026-11-23
Only a plugin that sends its version reports every open, so the open-rate
readers count only deliveries that carry one. Existing rows stay null: they
were made while sessions ran a plugin that did not report opens of the rules
a hook had named, so their missing opens are not evidence.
"""
import sqlalchemy as sa
from alembic import op
revision = "0133"
down_revision = "0132"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("rule_deliveries", sa.Column("plugin", sa.Text(), nullable=True))
def downgrade() -> None:
op.drop_column("rule_deliveries", "plugin")
+2 -1
View File
@@ -99,7 +99,8 @@ onMounted(load);
Suggested from each rule's text and what happened when it reached sessions. Inform is a Suggested from each rule's text and what happened when it reached sessions. Inform is a
line beside the work; hold makes the act or reply wait until the rule has been read once line beside the work; hold makes the act or reply wait until the rule has been read once
(file edits are never held); enforce refuses the act it governs. A trigger reaches the (file edits are never held); enforce refuses the act it governs. A trigger reaches the
rule exactly, by the tool, path, command or word the act carries. rule exactly, by the tool, path, command or word the act carries; a rule with triggers
holds or refuses only the acts they match, and elsewhere it is a line.
</p> </p>
<ul class="proposal-list"> <ul class="proposal-list">
<li v-for="rule in rules" :key="rule.id" class="proposal-rule"> <li v-for="rule in rules" :key="rule.id" class="proposal-rule">
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.23.1802", "version": "2026.11.23.2051",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+1
View File
@@ -191,6 +191,7 @@ while IFS= read -r rel_path; do
reached=1 reached=1
body=$(curl -fsS --max-time 8 \ body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; } "${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
# A call that was owed and didn't come back is said, once per outage — # A call that was owed and didn't come back is said, once per outage —
# shared marker with the pre-write hook, so one outage is one # shared marker with the pre-write hook, so one outage is one
+1
View File
@@ -149,6 +149,7 @@ fi
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0 [ -n "$body" ] || exit 0
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null [ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
+1
View File
@@ -41,6 +41,7 @@ task_id=$(printf '%s' "$task_id" | tr -cd '0-9')
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0 sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \ curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \ "${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
>/dev/null 2>&1 || true >/dev/null 2>&1 || true
exit 0 exit 0
+8
View File
@@ -868,6 +868,14 @@ grimoire_config() {
# garbage Bearer token and 401. Treat it as unset. # garbage Bearer token and 401. Treat it as unset.
case "$url" in *'${'*) url="" ;; esac case "$url" in *'${'*) url="" ;; esac
case "$token" in *'${'*) token="" ;; esac case "$token" in *'${'*) token="" ;; esac
# Sent as `X-Grimoire-Plugin` on every request. The server keeps it on each
# rule line it delivers, and counts a line toward a rule's open rate only
# when it is there: a plugin that sends it also reports every open, so a
# line without it is one whose opens were never going to be heard. The hooks
# that source this file read it, which shellcheck cannot see from here.
# shellcheck disable=SC2034
plugin_version=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' \
"$(dirname "${BASH_SOURCE[0]}")/../.claude-plugin/plugin.json" 2>/dev/null | head -n 1)
[ -n "$url" ] && [ -n "$token" ] [ -n "$url" ] && [ -n "$token" ]
} }
+2
View File
@@ -101,6 +101,7 @@ case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac
if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then
listed=$(curl -fsS --max-time 3 \ listed=$(curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed="" "${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
{ {
printf '%s\n' "$now" printf '%s\n' "$now"
@@ -141,6 +142,7 @@ query="${repo_q}${ledger_q}"
query=${query#&} query=${query#&}
body=$(printf '%s' "$event" | curl -fsS --max-time 3 \ body=$(printf '%s' "$event" | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0
+1
View File
@@ -251,6 +251,7 @@ fi
reached=1 reached=1
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; } "${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
unreached_context="" unreached_context=""
if [ "$reached" = 1 ]; then if [ "$reached" = 1 ]; then
+1 -1
View File
@@ -228,7 +228,7 @@ while IFS= read -r check; do
act=${check#*$'\t'} act=${check#*$'\t'}
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)" q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
fi fi
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" "${base}${q}" 2>/dev/null) || { resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" -H "X-Grimoire-Plugin: ${plugin_version:-}" "${base}${q}" 2>/dev/null) || {
fence_unreached fence_unreached
exit 0 exit 0
} }
+1
View File
@@ -110,6 +110,7 @@ scope=$(grimoire_scope_query "${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}")
body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \ body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \
| curl -fsS --max-time 3 \ | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0
+1
View File
@@ -107,6 +107,7 @@ query=${query#&}
answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \ answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0
+1
View File
@@ -192,6 +192,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then
local resp meta local resp meta
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \ resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/context${q}" 2>/dev/null) "${url%/}/api/plugin/context${q}" 2>/dev/null)
ctx_rc=$? ctx_rc=$?
meta=${resp##*$'\n'} meta=${resp##*$'\n'}
+1
View File
@@ -49,6 +49,7 @@ grimoire_config || exit 0
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0 sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \ curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \ "${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
>/dev/null 2>&1 || true >/dev/null 2>&1 || true
exit 0 exit 0
+2
View File
@@ -95,6 +95,7 @@ if [ -s "$asked_file" ]; then
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc="" asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \ if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \ "${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \
>/dev/null 2>&1; then >/dev/null 2>&1; then
rm -f "$asked_file" 2>/dev/null || true rm -f "$asked_file" 2>/dev/null || true
@@ -106,6 +107,7 @@ written=$(_unique "$ledger")
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0 written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
answer=$(curl -fsS --max-time 4 \ answer=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \ "${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \
|| exit 0 # unreachable: keep the ledger || exit 0 # unreachable: keep the ledger
+1
View File
@@ -32,6 +32,7 @@ grimoire_config || exit 0
body=$(curl -fsS --max-time 8 \ body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/processes" 2>/dev/null) || exit 0 "${url%/}/api/plugin/processes" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0 [ -n "$body" ] || exit 0
+1
View File
@@ -114,6 +114,7 @@ fi
# than silence. See the header. # than silence. See the header.
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
body_flat=$(printf '%s' "$body" | grimoire_json_flat) body_flat=$(printf '%s' "$body" | grimoire_json_flat)
+12
View File
@@ -28,6 +28,16 @@ class RuleDelivery(Base):
(`repeat`). Repeats are recorded too: they are deliveries a session can (`repeat`). Repeats are recorded too: they are deliveries a session can
open, and the case for retiring a rule rests on how rarely they are. open, and the case for retiring a rule rests on how rarely they are.
`plugin` is the version of the plugin that asked for the line, from the
request's `X-Grimoire-Plugin` header. Only a plugin that sends it reports
every open (`grimoire_record_opened.sh`), so a delivery without one was
made to a session whose opens never reach the server, and its unstamped
`opened_at` says nothing about whether it was read. The open-rate readers
count only deliveries that carry it. The server and the plugin ship on
different channels (the server from `dev`, the plugin from `main`, and a
running session keeps the plugin it started with), so rows from an older
plugin keep arriving for as long as such a session lives.
FK-free on `rule_id` and `user_id`, like the other telemetry tables: the FK-free on `rule_id` and `user_id`, like the other telemetry tables: the
evidence that a rule was delivered forty times and opened never outlives evidence that a rule was delivered forty times and opened never outlives
the rule, because it is the case for having deleted it. the rule, because it is the case for having deleted it.
@@ -46,6 +56,7 @@ class RuleDelivery(Base):
DateTime(timezone=True), nullable=False, server_default=func.now(), DateTime(timezone=True), nullable=False, server_default=func.now(),
) )
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = ( __table_args__ = (
# Stamping an open: this session's latest delivery of this rule. # Stamping an open: this session's latest delivery of this rule.
@@ -66,4 +77,5 @@ class RuleDelivery(Base):
"form": self.form, "form": self.form,
"delivered_at": iso(self.delivered_at), "delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at), "opened_at": iso(self.opened_at),
"plugin": self.plugin,
} }
+5 -2
View File
@@ -44,14 +44,17 @@ async def _bind_delivery_session() -> None:
A hook names it as `session_id` in the query, or carries it in the event A hook names it as `session_id` in the query, or carries it in the event
it posts (`/moment` sends the PreToolUse event whole). A request that it posts (`/moment` sends the PreToolUse event whole). A request that
names none records no deliveries and reads no delivery history. names none records no deliveries and reads no delivery history. The
plugin's version comes in the `X-Grimoire-Plugin` header and is kept on
each delivery, which is how the open-rate readers tell a session that
did not open a rule from one whose plugin never said.
""" """
sid = request.args.get("session_id") or "" sid = request.args.get("session_id") or ""
if not sid and request.method == "POST": if not sid and request.method == "POST":
body = await request.get_json(silent=True) body = await request.get_json(silent=True)
if isinstance(body, dict): if isinstance(body, dict):
sid = str(body.get("session_id") or "") sid = str(body.get("session_id") or "")
rule_deliveries_svc.bind_session(sid) rule_deliveries_svc.bind_session(sid, request.headers.get("X-Grimoire-Plugin"))
@plugin_bp.after_request @plugin_bp.after_request
+13 -3
View File
@@ -1748,10 +1748,13 @@ async def run_moment_arm(
by_moment = {hit["moment"]: hit for hit in reached} by_moment = {hit["moment"]: hit for hit in reached}
# (rule, at, where, specificity) for every candidate line. # (rule, at, where, specificity) for every candidate line.
cands = [] cands = []
# A mounted rule whose unscoped trigger also matched this act was
# reached by its trigger: it ranks, and may stop the act, as one.
fired_ids = {rule.id for rule, _trig in fired}
for rule, at in pairs or []: for rule, at in pairs or []:
if board is not None and (rule.id, at) in board.gated: if board is not None and (rule.id, at) in board.gated:
continue continue
met = board is not None and (rule.id, at) in board.matched met = board is not None and ((rule.id, at) in board.matched or rule.id in fired_ids)
cands.append((rule, at, f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}", cands.append((rule, at, f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
rule_order.BY_TRIGGER if met else rule_order.BY_MOUNT)) rule_order.BY_TRIGGER if met else rule_order.BY_MOUNT))
taken = {c[0].id for c in cands} taken = {c[0].id for c in cands}
@@ -1762,9 +1765,16 @@ async def run_moment_arm(
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act", cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
rule_order.BY_TRIGGER)) rule_order.BY_TRIGGER))
# Read before retirement: a rule that enforces does so on every act it # Read before retirement: a rule that enforces does so on every act it
# reaches, however often this session has been shown it. # reaches, however often this session has been shown it. A rule with
# triggers of its own stops only an act one of them matched: its
# triggers name the acts it governs, and its moment is broader (a
# rule about pushing to `main` mounted on work.deliver would hold
# every push to `dev`). Reached by the mount alone, it is a line.
triggered = board.triggered if board is not None else set()
decision = act_decision( decision = act_decision(
[(rule, at, where) for rule, at, where, _s in cands], held=moment.held, [(rule, at, where) for rule, at, where, spec in cands
if spec == rule_order.BY_TRIGGER or rule.id not in triggered],
held=moment.held,
) )
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands]) gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
if gone: if gone:
+18 -3
View File
@@ -13,6 +13,10 @@ Three calls, one table (`rule_deliveries`):
- `history` — for the ordering function: each rule's smoothed open rate at - `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`. the place it is about to be delivered, over the last `HISTORY_DAYS`.
An open rate counts only deliveries that carry the plugin version (`REPORTS_OPENS`):
a plugin that does not send it does not report opens either, so its
deliveries would read as never opened however often they were read.
Deliveries are kept `RETAIN_DAYS` and pruned daily: enough history to rank on 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. and to read adherence from, without a row per tool call accumulating forever.
""" """
@@ -46,10 +50,17 @@ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="") _session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
# Rows rendered during the bound request, written by `flush`. # Rows rendered during the bound request, written by `flush`.
_pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None) _pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None)
# The plugin version that sent the bound request (`X-Grimoire-Plugin`).
_plugin: ContextVar[str] = ContextVar("rule_delivery_plugin", default="")
_PLUGIN_MAX = 64
# The deliveries an open rate is read from: those whose plugin reports opens.
REPORTS_OPENS = RuleDelivery.plugin.is_not(None)
def bind_session(session_id: str | None) -> None: def bind_session(session_id: str | None, plugin: str | None = None) -> None:
_session.set(_clean_session(session_id)) _session.set(_clean_session(session_id))
_plugin.set(_UNSAFE.sub("_", (plugin or "").strip())[:_PLUGIN_MAX])
_pending.set([]) _pending.set([])
@@ -89,10 +100,12 @@ def record(
sid = _clean_session(_session.get() if session_id is None else session_id) sid = _clean_session(_session.get() if session_id is None else session_id)
if not sid or not lines: if not sid or not lines:
return return
plugin = _plugin.get() or None
try: try:
rows = [ rows = [
{"user_id": int(user_id), "session_id": sid, "rule_id": int(rid), {"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} "source": source, "at": str(at or source), "form": form if form in FORMS else FULL,
"plugin": plugin}
for rid, at, form in lines for rid, at, form in lines
] ]
except Exception: # noqa: BLE001 - observation never breaks the observed except Exception: # noqa: BLE001 - observation never breaks the observed
@@ -148,7 +161,8 @@ 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. """`{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 A rule with no delivery there is left out, which the ordering reads as
unknown rather than as never opened. unknown rather than as never opened. So is one delivered only to
sessions whose plugin does not report opens.
""" """
wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs)) wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs))
if not wanted: if not wanted:
@@ -164,6 +178,7 @@ async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float
.where( .where(
RuleDelivery.user_id == user_id, RuleDelivery.user_id == user_id,
RuleDelivery.delivered_at >= since, RuleDelivery.delivered_at >= since,
REPORTS_OPENS,
tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted), tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted),
) )
.group_by(RuleDelivery.rule_id, RuleDelivery.at) .group_by(RuleDelivery.rule_id, RuleDelivery.at)
@@ -46,7 +46,7 @@ from grimoire.models.rule_field_judgment import (
from grimoire.models.rule_moment_judgment import RuleMomentJudgment from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_usage import RuleUsageEvent from grimoire.models.rule_usage import RuleUsageEvent
from grimoire.models.rulebook import Rule from grimoire.models.rulebook import Rule
from grimoire.services import lesson_rules, rule_order from grimoire.services import lesson_rules, rule_deliveries, rule_order
from grimoire.services import rule_triggers as triggers_svc from grimoire.services import rule_triggers as triggers_svc
from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned
from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES
@@ -108,6 +108,8 @@ async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
(`at`: a moment, or the arm that found it), busiest first; `pulled`, (`at`: a moment, or the arm that found it), busiest first; `pulled`,
`applied` and `departed` from the usage events; `misfire_days`, the days `applied` and `departed` from the usage events; `misfire_days`, the days
sessions reported a mount of it arriving where it did not apply. sessions reported a mount of it arriving where it did not apply.
Deliveries count only when their plugin reports opens
(`rule_deliveries.REPORTS_OPENS`), so `opened` over `delivered` is a rate.
""" """
ids = sorted({int(r) for r in rule_ids or []}) ids = sorted({int(r) for r in rule_ids or []})
out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [], out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [],
@@ -122,7 +124,7 @@ async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)), func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
) )
.where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since, .where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
RuleDelivery.rule_id.in_(ids)) rule_deliveries.REPORTS_OPENS, RuleDelivery.rule_id.in_(ids))
.group_by(RuleDelivery.rule_id, RuleDelivery.at) .group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all() )).all()
for rid, at, delivered, opened in rows: for rid, at, delivered, opened in rows:
+6
View File
@@ -247,11 +247,15 @@ class Board:
condition this act did not meet: not delivered. `matched` — conditional condition this act did not meet: not delivered. `matched` — conditional
mounts this act met: delivered as triggered. `fired` — rules an unscoped mounts this act met: delivered as triggered. `fired` — rules an unscoped
trigger delivers on this act, each with the trigger that fired. trigger delivers on this act, each with the trigger that fired.
`triggered` — every in-scope rule that has a trigger at all, whether or
not this act met it: such a rule names the acts it governs, so a mount
alone shows it beside the work and only its trigger can stop an act.
""" """
gated: set[tuple[int, str]] = field(default_factory=set) gated: set[tuple[int, str]] = field(default_factory=set)
matched: set[tuple[int, str]] = field(default_factory=set) matched: set[tuple[int, str]] = field(default_factory=set)
fired: list[tuple[object, Trigger]] = field(default_factory=list) fired: list[tuple[object, Trigger]] = field(default_factory=list)
triggered: set[int] = field(default_factory=set)
async def board( async def board(
@@ -261,6 +265,8 @@ async def board(
"""Check every in-scope trigger against this act (or this text).""" """Check every in-scope trigger against this act (or this text)."""
out = Board() out = Board()
for rule, triggers in await _in_scope(user_id, project_id): for rule, triggers in await _in_scope(user_id, project_id):
if triggers:
out.triggered.add(rule.id)
first_unscoped = None first_unscoped = None
for trig in triggers: for trig in triggers:
hit = matches(trig, tool, tool_input, text) hit = matches(trig, tool, tool_input, text)
+2 -2
View File
@@ -85,13 +85,13 @@ def _bound_request_records_only_kept():
spawned = MagicMock() spawned = MagicMock()
with patch.object(rule_deliveries, "spawn", spawned), \ with patch.object(rule_deliveries, "spawn", spawned), \
patch.object(rule_deliveries, "_insert", lambda rows: rows): patch.object(rule_deliveries, "_insert", lambda rows: rows):
rule_deliveries.bind_session("s-1") rule_deliveries.bind_session("s-1", "2026.11.23.2100")
rule_deliveries.record(1, None, "pre_tool_rule", [(11, "pre_tool_rule", "full"), rule_deliveries.record(1, None, "pre_tool_rule", [(11, "pre_tool_rule", "full"),
(34, "pre_tool_rule", "full")]) (34, "pre_tool_rule", "full")])
assert not spawned.called, "a bound request's rows wait for the payload" assert not spawned.called, "a bound request's rows wait for the payload"
rule_deliveries.flush({11}) rule_deliveries.flush({11})
rows = spawned.call_args.args[0] rows = spawned.call_args.args[0]
assert [r["rule_id"] for r in rows] == [11] assert [(r["rule_id"], r["plugin"]) for r in rows] == [(11, "2026.11.23.2100")]
spawned.reset_mock() spawned.reset_mock()
rule_deliveries.flush() rule_deliveries.flush()
assert not spawned.called, "the buffer is spent once flushed" assert not spawned.called, "the buffer is spent once flushed"
+38 -2
View File
@@ -15,6 +15,9 @@ pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine"
RULE = 9_100_001 RULE = 9_100_001
OTHER = 9_100_002 OTHER = 9_100_002
# A plugin version, as the `X-Grimoire-Plugin` header carries it. Deliveries
# count toward an open rate only when their plugin sent one.
PLUGIN = "2026.11.23.2100"
async def _user() -> int: async def _user() -> int:
@@ -34,12 +37,19 @@ async def _rows(uid: int) -> list[RuleDelivery]:
)).scalars().all()) )).scalars().all())
async def _record(uid, sid, source, lines): async def _record(uid, sid, source, lines, plugin=PLUGIN):
# A bound request's rows wait for the door's payload; flushing all of # A bound request's rows wait for the door's payload; flushing all of
# them is what a door does when every line it rendered was kept. # them is what a door does when every line it rendered was kept. A named
# session is recorded as a request from `plugin` would be.
if sid is not None:
rule_deliveries.bind_session("", plugin)
try:
rule_deliveries.record(uid, sid, source, lines) rule_deliveries.record(uid, sid, source, lines)
rule_deliveries.flush() rule_deliveries.flush()
await background.drain() await background.drain()
finally:
if sid is not None:
rule_deliveries.bind_session("")
async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only(): async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only():
@@ -96,6 +106,32 @@ async def test_history_is_the_smoothed_open_rate_at_each_place():
assert await rule_deliveries.history(uid, [(RULE, "reply.report")]) == {} assert await rule_deliveries.history(uid, [(RULE, "reply.report")]) == {}
async def test_a_delivery_keeps_the_plugin_version_that_asked_for_it():
uid = await _user()
rule_deliveries.bind_session("s-p", PLUGIN)
try:
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
finally:
rule_deliveries.bind_session("")
await _record(uid, "s-old", "prompt_rule", [(RULE, "prompt_rule", "full")], plugin=None)
assert [(r.session_id, r.plugin) for r in await _rows(uid)] == [("s-p", PLUGIN), ("s-old", None)]
async def test_history_counts_only_deliveries_whose_plugin_reports_opens():
uid = await _user()
# An older plugin never reported these opens, so they read as unopened
# however often they were read; the rate is taken over the others.
await _record(uid, "s-old", "moment_rule", [(RULE, "work.finish", "full")] * 4, plugin=None)
await _record(uid, "s-old", "moment_rule", [(OTHER, "work.finish", "full")], plugin=None)
await _record(uid, "s-new", "moment_rule", [(RULE, "work.finish", "full")])
await rule_deliveries.mark_opened(uid, "s-new", RULE)
history = await rule_deliveries.history(uid, [(RULE, "work.finish"), (OTHER, "work.finish")])
assert history[RULE] == pytest.approx((1 + 1) / (1 + 2))
# Delivered only to a plugin that does not report opens: unknown, not zero.
assert OTHER not in history
async def test_old_deliveries_are_pruned(): async def test_old_deliveries_are_pruned():
uid = await _user() uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")]) await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")])
@@ -195,8 +195,11 @@ async def test_the_pass_reads_each_rule_with_its_history(world):
for i, (at, opened) in enumerate([("work.deliver", True), ("work.deliver", False), for i, (at, opened) in enumerate([("work.deliver", True), ("work.deliver", False),
("pre_tool_rule", False)]): ("pre_tool_rule", False)]):
s.add(RuleDelivery(user_id=uid, session_id=f"s{i}", rule_id=push.id, s.add(RuleDelivery(user_id=uid, session_id=f"s{i}", rule_id=push.id,
source="hook", at=at, form="full", source="hook", at=at, form="full", plugin="2026.11.23.2100",
opened_at=now if opened else None)) opened_at=now if opened else None))
# From a plugin that does not report opens: not part of the history.
s.add(RuleDelivery(user_id=uid, session_id="s-old", rule_id=push.id,
source="hook", at="work.deliver", form="full"))
s.add(RuleUsageEvent(user_id=uid, rule_id=push.id, event="departed", s.add(RuleUsageEvent(user_id=uid, rule_id=push.id, event="departed",
source="mcp_rule_outcome", detail="the operator asked")) source="mcp_rule_outcome", detail="the operator asked"))
await s.commit() await s.commit()
+16
View File
@@ -133,6 +133,22 @@ def test_an_open_sends_the_window_and_prints_the_answer(sandbox):
assert (tmp / "grimoire-priorart" / "s1.opened.ids").read_text().startswith("11\t") assert (tmp / "grimoire-priorart" / "s1.opened.ids").read_text().startswith("11\t")
def test_every_request_names_the_plugin_version_that_sent_it(sandbox):
# The server counts a delivery toward a rule's open rate only when its
# plugin sent its version, since that is the plugin that reports opens.
tmp, env = sandbox
version = json.loads((ROOT / "plugin" / ".claude-plugin" / "plugin.json").read_text())["version"]
_run("grimoire_moment.sh", {"session_id": "s1", "tool_name": "Bash",
"tool_input": {"command": "ls"}}, env,
FAKE_CURL_REPLY='{"tools":["bash"]}')
_run("grimoire_record_opened.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env)
calls = (tmp / "curl.log").read_text().splitlines()
assert len(calls) >= 2
assert all(f"X-Grimoire-Plugin: {version}" in call for call in calls), calls
def test_the_window_is_the_last_three_acts(sandbox): def test_the_window_is_the_last_three_acts(sandbox):
tmp, env = sandbox tmp, env = sandbox
ledger = tmp / "grimoire-moment" ledger = tmp / "grimoire-moment"
+27
View File
@@ -148,5 +148,32 @@ async def test_a_rule_both_mounted_and_fired_is_delivered_once():
assert result.shown_rule_ids == [1] assert result.shown_rule_ids == [1]
async def test_a_rule_with_triggers_stops_only_the_acts_they_match():
# Rule 2 holds pushes to main; mounted on work.deliver it reaches every
# push, and only its own trigger may make one wait.
guard = _r(2, enforcement="hold")
pairs = [(guard, "work.deliver")]
deliver = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
to_dev = rt.Board(triggered={2})
result = await _arm(pairs, to_dev, reached=deliver)
assert result.decision == {} and result.shown_rule_ids == [2]
to_main = rt.Board(triggered={2}, fired=[(guard, T("command", "git push origin main"))])
result = await _arm(pairs, to_main, reached=deliver)
assert result.decision["kind"] == "hold" and result.decision["rule_ids"] == [2]
# With no trigger of its own, the mount is all that says where it applies.
result = await _arm(pairs, rt.Board(), reached=deliver)
assert result.decision["kind"] == "hold"
async def test_the_board_lists_every_rule_that_has_a_trigger(monkeypatch):
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(_r(1), [T("path", "alembic/**", "work.change")]),
(_r(2), [T("command", "git push origin main")]),
(_r(3), []),
]))
out = await rt.board(1, 2, tool="Bash", tool_input={"command": "ls"})
assert out.triggered == {1, 2}
def test_triggered_outranks_mounted_in_the_one_order(): def test_triggered_outranks_mounted_in_the_one_order():
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE