feat(7831): every record a session is shown, asks for or opens on its own is recorded per session, by kind
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 32s

A ledger beside the rule deliveries (record_deliveries, migration 0136):
- every note, snippet, issue, lesson or process line a plugin door pushes
  is recorded against the session, only when the payload kept it;
- a search the session runs itself records its results as asked, matched
  to the server log of that call;
- an open is stamped on the delivery it followed, or recorded as direct
  when nothing showed the record first.

The plugin reports opens and searches from the tool calls
(grimoire_record_read.sh). The readout is in retrieval_telemetry
(record_reach), at /api/retrieval/record-reach, and in Settings > Moments
as "How records reach the work". Plugin 2026.11.24.1827.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 13:27:13 -05:00
co-authored by Claude Opus 5.5
parent 394f83427d
commit b0fab00fe2
21 changed files with 951 additions and 9 deletions
+140
View File
@@ -0,0 +1,140 @@
"""Real-Postgres tests for `record_deliveries`: every non-rule record put in
front of a session, the way it arrived (pushed, asked, direct), and the open
stamped on the delivery it followed."""
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.record_delivery import RecordDelivery
from grimoire.models.retrieval_log import RetrievalLog
from grimoire.services import background, note_usage, record_deliveries, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
PLUGIN = "2026.11.24.1900"
async def _setup(name: str = "record_delivery_owner") -> tuple[int, dict[str, int]]:
"""A user with one record of each kind the readout tells apart."""
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid))
await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid))
notes = {
"snippet": Note(user_id=uid, title="a snippet", note_type="snippet"),
"note": Note(user_id=uid, title="a note", note_type="note"),
"issue": Note(user_id=uid, title="an issue", status="todo", task_kind="issue"),
"lesson": Note(user_id=uid, title="a lesson", note_type="lesson"),
}
s.add_all(notes.values())
await s.commit()
return uid, {k: n.id for k, n in notes.items()}
async def _rows(uid: int) -> list[RecordDelivery]:
async with async_session() as s:
return list((await s.execute(
select(RecordDelivery).where(RecordDelivery.user_id == uid).order_by(RecordDelivery.id)
)).scalars().all())
async def _push(uid, sid, ids, source="write_path_semantic", kept=None):
"""What a plugin door does: bind the session, surface, fit, flush."""
rule_deliveries.bind_session(sid, PLUGIN)
try:
note_usage.record_surfaced(user_id=uid, note_ids=ids, source=source)
record_deliveries.flush(kept)
await background.drain()
finally:
rule_deliveries.bind_session("")
async def test_a_pushed_line_is_recorded_with_its_kind_only_when_the_payload_kept_it():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"], n["issue"], n["lesson"]], kept={n["snippet"], n["issue"]})
rows = await _rows(uid)
assert [(r.note_id, r.kind, r.way, r.source, r.plugin) for r in rows] == [
(n["snippet"], "snippet", "pushed", "write_path_semantic", PLUGIN),
(n["issue"], "task:issue", "pushed", "write_path_semantic", PLUGIN),
]
async def test_nothing_is_recorded_outside_a_session_or_for_a_synced_skill():
uid, n = await _setup()
note_usage.record_surfaced(user_id=uid, note_ids=[n["note"]], source="auto_inject")
await _push(uid, "s-1", [n["note"]], source="process_skill_sync")
await background.drain()
assert await _rows(uid) == []
async def test_a_record_the_reader_cannot_read_is_not_recorded():
uid, _n = await _setup()
_other, theirs = await _setup("record_delivery_stranger")
await _push(uid, "s-1", [theirs["note"]])
assert await _rows(uid) == []
assert await record_deliveries.mark_opened(uid, "s-1", theirs["note"]) == ""
async def test_an_open_is_stamped_on_the_delivery_it_followed_and_otherwise_counts_as_direct():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"]])
assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "pushed"
# Nothing delivered the note to this session: reached on its own.
assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == "direct"
# Opened again: the first open was already counted.
assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == ""
rows = {(r.note_id, r.way): r.opened_at is not None for r in await _rows(uid)}
assert rows == {(n["snippet"], "pushed"): True, (n["note"], "direct"): True}
async def test_a_search_the_session_ran_records_its_results_as_asked():
uid, n = await _setup()
async with async_session() as s:
s.add(RetrievalLog(user_id=uid, source="mcp_search", query="how is the lock released",
result_count=2,
result_ids=[{"id": n["issue"], "score": 0.8, "rank": 1},
{"id": n["note"], "score": 0.7, "rank": 2}]))
s.add(RetrievalLog(user_id=uid, source="mcp_search", query="something else", result_count=1,
result_ids=[{"id": n["lesson"], "score": 0.9, "rank": 1}]))
await s.commit()
assert await record_deliveries.from_search(uid, "s-1", "how is the lock released", PLUGIN) == 2
assert await record_deliveries.from_search(uid, "s-1", "never searched", PLUGIN) == 0
assert await record_deliveries.mark_opened(uid, "s-1", n["issue"], PLUGIN) == "asked"
assert sorted((r.note_id, r.way) for r in await _rows(uid)) == sorted(
[(n["issue"], "asked"), (n["note"], "asked")])
async def test_a_record_already_opened_in_the_session_counts_as_opened_when_pushed_again():
uid, n = await _setup()
assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "direct"
await _push(uid, "s-1", [n["snippet"]])
await _push(uid, "s-2", [n["snippet"]])
later = {r.session_id: r.opened_at is not None for r in await _rows(uid) if r.way == "pushed"}
assert later == {"s-1": True, "s-2": False}
async def test_the_readout_counts_each_way_per_kind_from_plugins_that_report_opens():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"], n["issue"]])
await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN)
await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN)
# A row from a plugin that never reports opens says nothing about them.
async with async_session() as s:
s.add(RecordDelivery(user_id=uid, session_id="old", note_id=n["lesson"], kind="lesson",
way="pushed", source="write_path_semantic", plugin=None,
delivered_at=datetime.now(timezone.utc) - timedelta(minutes=1)))
await s.commit()
out = await record_deliveries.summary(uid, days=7)
kinds = {k["kind"]: k["ways"] for k in out["by_kind"]}
assert kinds["snippet"]["pushed"] == {"delivered": 1, "opened": 1}
assert kinds["task:issue"]["pushed"] == {"delivered": 1, "opened": 0}
assert kinds["note"]["direct"] == {"delivered": 1, "opened": 1}
assert "lesson" not in kinds
assert out["totals"]["pushed"] == {"delivered": 2, "opened": 1}
assert out["sessions"] == 1
+59
View File
@@ -0,0 +1,59 @@
"""`grimoire_record_read.sh`, run for real through bash with a stand-in `curl`:
an opened record and a search the session ran are reported to the server
with the session, and the hook is registered on exactly those tools."""
from __future__ import annotations
import json
import re
from tests.test_rule_moment_signal_hooks import HOOKS, _run, sandbox # noqa: F401 - fixture
ROOT = HOOKS.parents[1]
def _sent(tmp) -> tuple[str, dict | None]:
log = (tmp / "curl.log").read_text() if (tmp / "curl.log").exists() else ""
body = (tmp / "curl.body").read_text() if (tmp / "curl.body").exists() else ""
return log, (json.loads(body) if body else None)
def test_an_opened_record_is_reported_with_its_session(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_task", "tool_input": {"task_id": 42}},
env)
log, body = _sent(tmp)
assert "/api/plugin/record-opened" in log
assert body == {"session_id": "s1", "note_id": 42}
def test_a_search_is_reported_with_its_query(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__plugin_grimoire_grimoire__search",
"tool_input": {"q": 'why does "the lock" stick', "content_type": "issue"}},
env)
log, body = _sent(tmp)
assert "/api/plugin/record-searched" in log
assert body == {"session_id": "s1", "q": 'why does "the lock" stick'}
def test_a_process_opened_by_name_is_not_reported(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_process",
"tool_input": {"name_or_id": "Drift Audit"}},
env)
assert _sent(tmp) == ("", None)
def test_the_hook_runs_after_every_record_getter_and_search_and_nothing_else():
hooks = json.loads((ROOT / "plugin" / "hooks" / "hooks.json").read_text())["hooks"]["PostToolUse"]
matchers = [e["matcher"] for e in hooks
if any("grimoire_record_read.sh" in h["command"] for h in e["hooks"])]
assert len(matchers) == 1
runs = re.compile(f"^(?:{matchers[0]})$")
for tool in ("get_note", "get_task", "get_snippet", "get_lesson", "get_process", "search"):
assert runs.match(f"mcp__plugin_grimoire_grimoire__{tool}"), tool
for tool in ("get_rule", "search_rules", "update_task", "get_milestone"):
assert not runs.match(f"mcp__plugin_grimoire_grimoire__{tool}"), tool
+1
View File
@@ -41,6 +41,7 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/surfaces",
"/api/retrieval/surfaces/<surface>",
"/api/retrieval/adherence",
"/api/retrieval/record-reach",
"/api/retrieval/gate",
"/api/retrieval/tuning-history",
"/api/retrieval/moments",