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