diff --git a/alembic/versions/0133_rule_delivery_plugin.py b/alembic/versions/0133_rule_delivery_plugin.py new file mode 100644 index 00000000..48a46c11 --- /dev/null +++ b/alembic/versions/0133_rule_delivery_plugin.py @@ -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") diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index e2710971..2db9a9f0 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "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).", - "version": "2026.11.23.1802", + "version": "2026.11.23.2051", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/hooks/grimoire_after_write.sh b/plugin/hooks/grimoire_after_write.sh index 3da6f372..16e1e944 100644 --- a/plugin/hooks/grimoire_after_write.sh +++ b/plugin/hooks/grimoire_after_write.sh @@ -191,6 +191,7 @@ while IFS= read -r rel_path; do reached=1 body=$(curl -fsS --max-time 8 \ -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; } # 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 diff --git a/plugin/hooks/grimoire_autoinject.sh b/plugin/hooks/grimoire_autoinject.sh index 8dcee1de..a4d98744 100755 --- a/plugin/hooks/grimoire_autoinject.sh +++ b/plugin/hooks/grimoire_autoinject.sh @@ -149,6 +149,7 @@ fi body=$(curl -fsS --max-time 5 \ -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 [ -n "$body" ] || exit 0 [ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null diff --git a/plugin/hooks/grimoire_claim_session.sh b/plugin/hooks/grimoire_claim_session.sh index d0ebc141..d0cb01e0 100755 --- a/plugin/hooks/grimoire_claim_session.sh +++ b/plugin/hooks/grimoire_claim_session.sh @@ -41,6 +41,7 @@ task_id=$(printf '%s' "$task_id" | tr -cd '0-9') sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0 curl -fsS --max-time 4 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \ >/dev/null 2>&1 || true exit 0 diff --git a/plugin/hooks/grimoire_defs.sh b/plugin/hooks/grimoire_defs.sh index e941dc19..16d899e7 100644 --- a/plugin/hooks/grimoire_defs.sh +++ b/plugin/hooks/grimoire_defs.sh @@ -868,6 +868,12 @@ grimoire_config() { # garbage Bearer token and 401. Treat it as unset. case "$url" in *'${'*) url="" ;; 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. + 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" ] } diff --git a/plugin/hooks/grimoire_moment.sh b/plugin/hooks/grimoire_moment.sh index f1734c47..a1534d5a 100644 --- a/plugin/hooks/grimoire_moment.sh +++ b/plugin/hooks/grimoire_moment.sh @@ -101,6 +101,7 @@ case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then listed=$(curl -fsS --max-time 3 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed="" { printf '%s\n' "$now" @@ -141,6 +142,7 @@ query="${repo_q}${ledger_q}" query=${query#&} body=$(printf '%s' "$event" | curl -fsS --max-time 3 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "Content-Type: application/json" \ --data-binary @- \ "${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0 diff --git a/plugin/hooks/grimoire_prior_art.sh b/plugin/hooks/grimoire_prior_art.sh index 5cf88fd1..95bc379a 100755 --- a/plugin/hooks/grimoire_prior_art.sh +++ b/plugin/hooks/grimoire_prior_art.sh @@ -251,6 +251,7 @@ fi reached=1 body=$(curl -fsS --max-time 5 \ -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; } unreached_context="" if [ "$reached" = 1 ]; then diff --git a/plugin/hooks/grimoire_project_fence.sh b/plugin/hooks/grimoire_project_fence.sh index 81a41965..92b0286e 100644 --- a/plugin/hooks/grimoire_project_fence.sh +++ b/plugin/hooks/grimoire_project_fence.sh @@ -228,7 +228,7 @@ while IFS= read -r check; do act=${check#*$'\t'} q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)" 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 exit 0 } diff --git a/plugin/hooks/grimoire_record_opened.sh b/plugin/hooks/grimoire_record_opened.sh index 6c338ee9..27406851 100644 --- a/plugin/hooks/grimoire_record_opened.sh +++ b/plugin/hooks/grimoire_record_opened.sh @@ -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" \ | curl -fsS --max-time 3 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "Content-Type: application/json" \ --data-binary @- \ "${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0 diff --git a/plugin/hooks/grimoire_reply_check.sh b/plugin/hooks/grimoire_reply_check.sh index 19e2210c..a2b1eead 100644 --- a/plugin/hooks/grimoire_reply_check.sh +++ b/plugin/hooks/grimoire_reply_check.sh @@ -107,6 +107,7 @@ query=${query#&} answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "Content-Type: application/json" \ --data-binary @- \ "${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0 diff --git a/plugin/hooks/grimoire_session_context.sh b/plugin/hooks/grimoire_session_context.sh index 7449fac5..8b730d98 100755 --- a/plugin/hooks/grimoire_session_context.sh +++ b/plugin/hooks/grimoire_session_context.sh @@ -192,6 +192,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then local resp meta resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/context${q}" 2>/dev/null) ctx_rc=$? meta=${resp##*$'\n'} diff --git a/plugin/hooks/grimoire_session_end.sh b/plugin/hooks/grimoire_session_end.sh index 2b43dae2..01dd283c 100755 --- a/plugin/hooks/grimoire_session_end.sh +++ b/plugin/hooks/grimoire_session_end.sh @@ -49,6 +49,7 @@ grimoire_config || exit 0 sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0 curl -fsS --max-time 4 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/release-session?session_id=${sid_enc}" \ >/dev/null 2>&1 || true exit 0 diff --git a/plugin/hooks/grimoire_shape_check.sh b/plugin/hooks/grimoire_shape_check.sh index a1567693..75e651f4 100644 --- a/plugin/hooks/grimoire_shape_check.sh +++ b/plugin/hooks/grimoire_shape_check.sh @@ -95,6 +95,7 @@ if [ -s "$asked_file" ]; then asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc="" if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \ >/dev/null 2>&1; then rm -f "$asked_file" 2>/dev/null || true @@ -106,6 +107,7 @@ written=$(_unique "$ledger") written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0 answer=$(curl -fsS --max-time 4 \ -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) \ || exit 0 # unreachable: keep the ledger diff --git a/plugin/hooks/grimoire_sync_processes.sh b/plugin/hooks/grimoire_sync_processes.sh index 408fa01f..5d6c1b59 100755 --- a/plugin/hooks/grimoire_sync_processes.sh +++ b/plugin/hooks/grimoire_sync_processes.sh @@ -32,6 +32,7 @@ grimoire_config || exit 0 body=$(curl -fsS --max-time 8 \ -H "Authorization: Bearer ${token}" \ + -H "X-Grimoire-Plugin: ${plugin_version:-}" \ "${url%/}/api/plugin/processes" 2>/dev/null) || exit 0 [ -n "$body" ] || exit 0 diff --git a/plugin/hooks/grimoire_tool_rules.sh b/plugin/hooks/grimoire_tool_rules.sh index d12d2f2b..2d2e64b4 100644 --- a/plugin/hooks/grimoire_tool_rules.sh +++ b/plugin/hooks/grimoire_tool_rules.sh @@ -114,6 +114,7 @@ fi # than silence. See the header. body=$(curl -fsS --max-time 5 \ -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 body_flat=$(printf '%s' "$body" | grimoire_json_flat) diff --git a/src/grimoire/models/rule_delivery.py b/src/grimoire/models/rule_delivery.py index 54144a67..c3f59b40 100644 --- a/src/grimoire/models/rule_delivery.py +++ b/src/grimoire/models/rule_delivery.py @@ -28,6 +28,16 @@ class RuleDelivery(Base): (`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. + `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 evidence that a rule was delivered forty times and opened never outlives 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(), ) opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + plugin: Mapped[str | None] = mapped_column(Text, nullable=True) __table_args__ = ( # Stamping an open: this session's latest delivery of this rule. @@ -66,4 +77,5 @@ class RuleDelivery(Base): "form": self.form, "delivered_at": iso(self.delivered_at), "opened_at": iso(self.opened_at), + "plugin": self.plugin, } diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index f9d1d3de..fcd2b738 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -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 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 "" if not sid and request.method == "POST": body = await request.get_json(silent=True) if isinstance(body, dict): 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 diff --git a/src/grimoire/services/rule_deliveries.py b/src/grimoire/services/rule_deliveries.py index 340855d8..ba08a6b0 100644 --- a/src/grimoire/services/rule_deliveries.py +++ b/src/grimoire/services/rule_deliveries.py @@ -13,6 +13,10 @@ Three calls, one table (`rule_deliveries`): - `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`. +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 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="") # Rows rendered during the bound request, written by `flush`. _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)) + _plugin.set(_UNSAFE.sub("_", (plugin or "").strip())[:_PLUGIN_MAX]) _pending.set([]) @@ -89,10 +100,12 @@ def record( sid = _clean_session(_session.get() if session_id is None else session_id) if not sid or not lines: return + plugin = _plugin.get() or None 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} + "source": source, "at": str(at or source), "form": form if form in FORMS else FULL, + "plugin": plugin} for rid, at, form in lines ] 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. 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)) if not wanted: @@ -164,6 +178,7 @@ async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float .where( RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since, + REPORTS_OPENS, tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted), ) .group_by(RuleDelivery.rule_id, RuleDelivery.at) diff --git a/src/grimoire/services/rule_field_judgments.py b/src/grimoire/services/rule_field_judgments.py index 04b302b3..8a9c1ae6 100644 --- a/src/grimoire/services/rule_field_judgments.py +++ b/src/grimoire/services/rule_field_judgments.py @@ -46,7 +46,7 @@ from grimoire.models.rule_field_judgment import ( from grimoire.models.rule_moment_judgment import RuleMomentJudgment from grimoire.models.rule_usage import RuleUsageEvent 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.rule_moment_judgments import _int, _mounts, _owned_rules as _owned 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`, `applied` and `departed` from the usage events; `misfire_days`, the days 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 []}) 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)), ) .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) )).all() for rid, at, delivered, opened in rows: diff --git a/tests/test_hook_payload.py b/tests/test_hook_payload.py index 04fdda83..fea65139 100644 --- a/tests/test_hook_payload.py +++ b/tests/test_hook_payload.py @@ -85,13 +85,13 @@ def _bound_request_records_only_kept(): spawned = MagicMock() with patch.object(rule_deliveries, "spawn", spawned), \ 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"), (34, "pre_tool_rule", "full")]) assert not spawned.called, "a bound request's rows wait for the payload" rule_deliveries.flush({11}) 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() rule_deliveries.flush() assert not spawned.called, "the buffer is spent once flushed" diff --git a/tests/test_integration_rule_deliveries.py b/tests/test_integration_rule_deliveries.py index 41c9375d..ec1a36a2 100644 --- a/tests/test_integration_rule_deliveries.py +++ b/tests/test_integration_rule_deliveries.py @@ -15,6 +15,9 @@ pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine" RULE = 9_100_001 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: @@ -34,12 +37,19 @@ async def _rows(uid: int) -> list[RuleDelivery]: )).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 - # them is what a door does when every line it rendered was kept. - rule_deliveries.record(uid, sid, source, lines) - rule_deliveries.flush() - await background.drain() + # 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.flush() + 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(): @@ -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")]) == {} +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(): uid = await _user() await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")]) diff --git a/tests/test_integration_rule_field_judgments.py b/tests/test_integration_rule_field_judgments.py index cf263aa2..ad12e7bb 100644 --- a/tests/test_integration_rule_field_judgments.py +++ b/tests/test_integration_rule_field_judgments.py @@ -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), ("pre_tool_rule", False)]): 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)) + # 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", source="mcp_rule_outcome", detail="the operator asked")) await s.commit() diff --git a/tests/test_rule_moment_signal_hooks.py b/tests/test_rule_moment_signal_hooks.py index 01994f02..426260d9 100644 --- a/tests/test_rule_moment_signal_hooks.py +++ b/tests/test_rule_moment_signal_hooks.py @@ -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") +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): tmp, env = sandbox ledger = tmp / "grimoire-moment"