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
+270
View File
@@ -0,0 +1,270 @@
"""Each non-rule record put in front of a session, how it got there, and
whether the session opened it.
One table (`record_deliveries`), the note-side twin of `rule_deliveries`, and
four calls:
- `record` — from `note_usage.record_surfaced`, every record a plugin door
pushed to a bound session. Within a request the rows wait until the door's
payload is fitted, and `flush` writes only those whose line made it in
(`hook_payload.fit`), exactly as rule lines are kept.
- `from_search` — the session ran `search` itself; the plugin reports it and
the results that call returned are recorded as `asked`.
- `mark_opened` — the session opened a record. The latest unopened delivery
of it in the session gets the stamp. With nothing delivering it first, a
`direct` row is written, delivered and opened at once: the record was
reached without being shown.
- `summary` — per kind, how records arrived (`pushed`, `asked`, `direct`),
by door, and how many were opened.
Only rows from a plugin that reports its version count in the readout: an
older plugin does not report opens, so its rows would read as never opened.
"""
from __future__ import annotations
import logging
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from sqlalchemy import case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDelivery
from grimoire.models.retrieval_log import RetrievalLog
from grimoire.services import rule_deliveries
from grimoire.services.access import readable_notes_clause
from grimoire.services.background import spawn
logger = logging.getLogger(__name__)
# A search the plugin reports is matched to the call the server logged within
# this long before; the report follows the call by a second or two, so a
# longer window only adds the chance of matching an older identical query.
SEARCH_MATCH_WINDOW = timedelta(minutes=3)
SEARCH_SOURCE = "mcp_search"
DIRECT_SOURCE = "direct"
# Rows a bound request rendered, written by `flush`. Reset per request by
# `rule_deliveries.bind_session`, so the two ledgers share one binding.
_pending: ContextVar[list | None] = ContextVar("record_delivery_pending", default=None)
def reset() -> None:
_pending.set([])
def record(user_id: int | None, note_ids, source: str) -> None:
"""Record records a hook pushed to the bound session. A no-op outside a
plugin request, since an open could never be tied back to it."""
sid = rule_deliveries.current_session()
if not sid or not user_id:
return
try:
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": int(n),
"way": PUSHED, "source": source, "plugin": rule_deliveries.current_plugin()}
for n in dict.fromkeys(note_ids or [])]
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("record delivery payload build failed", exc_info=True)
return
pending = _pending.get()
if pending is not None:
pending.extend(rows)
elif rows:
spawn(_insert(rows), site="record_delivery_write")
def flush(kept: set[int] | None = None) -> None:
"""Write this request's buffered rows: those for records in `kept`, or all
of them when `kept` is None. A record whose line the payload left out was
never shown, so its row is dropped."""
rows = _pending.get()
if not rows:
return
_pending.set([])
if kept is not None:
rows = [r for r in rows if r["note_id"] in kept]
if rows:
spawn(_insert(rows), site="record_delivery_write")
def _kind(note_type: str | None, status: str | None, task_kind: str | None) -> str:
# A task is told by its status; its kind says what sort of task it is.
if status is not None:
return f"task:{task_kind or 'work'}"
return note_type or "note"
async def _kinds(session, user_id: int, ids) -> dict[int, str]:
"""`{note_id: kind}` for the ids this user may read; any other id is left
out, so the ledger never records a record its reader could not open."""
rows = (await session.execute(
select(Note.id, Note.note_type, Note.status, Note.task_kind)
.where(Note.id.in_(list(ids)), readable_notes_clause(user_id))
)).all()
return {int(i): _kind(t, s, k) for i, t, s, k in rows}
async def _insert(rows: list[dict]) -> None:
"""Write rows, each with its record's kind. An id that is not a record (a
rule id in a mixed list, a deleted note) is dropped. A record the session
already opened within the open window is stamped opened as it is
written, as `rule_deliveries` does: it reached a reader who has it."""
now = datetime.now(timezone.utc)
async with async_session() as session:
kinds: dict[tuple[int, int], str] = {}
for uid in {r["user_id"] for r in rows}:
found = await _kinds(session, uid, {r["note_id"] for r in rows if r["user_id"] == uid})
kinds.update({(uid, nid): k for nid, k in found.items()})
rows = [{**r, "kind": kinds[(r["user_id"], r["note_id"])]}
for r in rows if (r["user_id"], r["note_id"]) in kinds]
if not rows:
return
keys = list({(r["user_id"], r["session_id"], r["note_id"]) for r in rows})
read = {tuple(k) for k in (await session.execute(
select(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id)
.where(
tuple_(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id).in_(keys),
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
)
.distinct()
)).all()}
for r in rows:
if (r["user_id"], r["session_id"], r["note_id"]) in read:
r["opened_at"] = now
session.add_all(RecordDelivery(**r) for r in rows)
await session.commit()
async def from_search(user_id: int, session_id: str | None, query: str, plugin: str | None = None) -> int:
"""Record the results of a search this session ran itself, as `asked`.
The MCP call does not know its session; the plugin does, and reports the
query after the call. The server's own log of that call
(`retrieval_logs`, source `mcp_search`) holds what it returned, so the
report is matched to the latest logged call with the same query in
`SEARCH_MATCH_WINDOW`. Returns how many records were recorded.
"""
sid = rule_deliveries.clean_session(session_id)
if not sid or not (query or "").strip():
return 0
since = datetime.now(timezone.utc) - SEARCH_MATCH_WINDOW
async with async_session() as session:
result_ids = (await session.execute(
select(RetrievalLog.result_ids)
.where(RetrievalLog.user_id == user_id, RetrievalLog.source == SEARCH_SOURCE,
RetrievalLog.query == query, RetrievalLog.created_at >= since)
.order_by(RetrievalLog.created_at.desc(), RetrievalLog.id.desc())
.limit(1)
)).scalar_one_or_none()
ids = [int(h["id"]) for h in (result_ids or []) if isinstance(h, dict) and str(h.get("id", "")).isdigit()]
if not ids:
return 0
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": n, "way": ASKED,
"source": SEARCH_SOURCE, "plugin": plugin} for n in dict.fromkeys(ids)]
await _insert(rows)
return len(rows)
async def mark_opened(user_id: int, session_id: str | None, note_id: int, plugin: str | None = None) -> str:
"""Stamp this session's latest unopened delivery of the record, within the
open window. With none, write a `direct` row: the session reached the
record without being shown it. Returns the way the open is counted
under, or "" when nothing was recorded."""
sid = rule_deliveries.clean_session(session_id)
if not sid or not note_id:
return ""
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(RecordDelivery.id, RecordDelivery.way)
.where(
RecordDelivery.user_id == user_id,
RecordDelivery.session_id == sid,
RecordDelivery.note_id == int(note_id),
RecordDelivery.opened_at.is_(None),
RecordDelivery.delivered_at >= now - rule_deliveries.OPEN_WINDOW,
)
.order_by(RecordDelivery.delivered_at.desc(), RecordDelivery.id.desc())
.limit(1)
)).first()
if latest is not None:
await session.execute(
update(RecordDelivery).where(RecordDelivery.id == latest[0]).values(opened_at=now)
)
await session.commit()
return str(latest[1])
kinds = await _kinds(session, int(user_id), {int(note_id)})
if int(note_id) not in kinds:
return ""
already = (await session.execute(
select(RecordDelivery.id).where(
RecordDelivery.user_id == user_id, RecordDelivery.session_id == sid,
RecordDelivery.note_id == int(note_id),
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
).limit(1)
)).scalar_one_or_none()
if already is not None:
# Read again: the first open was counted where it happened.
return ""
session.add(RecordDelivery(
user_id=int(user_id), session_id=sid, note_id=int(note_id), kind=kinds[int(note_id)],
way=DIRECT, source=DIRECT_SOURCE, delivered_at=now, opened_at=now, plugin=plugin,
))
await session.commit()
return DIRECT
async def summary(user_id: int, days: int = 30) -> dict:
"""How records reached this user's sessions over the last `days`.
Per kind: `delivered` and `opened` rows for each way a record arrived
(`pushed` by a hook, `asked` through the session's own search, `direct`
when it was opened with nothing delivering it), and per door. A `direct`
row is always opened; it is counted so the readout shows how much a
session reaches without being shown.
"""
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
since = datetime.now(timezone.utc) - timedelta(days=days)
async with async_session() as session:
rows = (await session.execute(
select(
RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source,
func.count(RecordDelivery.id),
func.sum(case((RecordDelivery.opened_at.is_not(None), 1), else_=0)),
func.count(func.distinct(RecordDelivery.session_id)),
)
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.plugin.is_not(None))
.group_by(RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source)
)).all()
sessions = (await session.execute(
select(func.count(func.distinct(RecordDelivery.session_id)))
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.plugin.is_not(None))
)).scalar_one()
def zero() -> dict:
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, ASKED, DIRECT)}
kinds: dict[str, dict] = {}
totals = zero()
for kind, way, source, delivered, opened, _sessions in rows:
slot = kinds.setdefault(kind, {"kind": kind, "ways": zero(), "sources": []})
for bucket in (slot["ways"], totals):
bucket[way]["delivered"] += int(delivered)
bucket[way]["opened"] += int(opened or 0)
slot["sources"].append({"way": way, "source": source,
"delivered": int(delivered), "opened": int(opened or 0)})
for slot in kinds.values():
slot["sources"].sort(key=lambda s: (-s["delivered"], s["source"]))
by_kind = sorted(kinds.values(),
key=lambda k: (-sum(w["delivered"] for w in k["ways"].values()), k["kind"]))
return {"days": days, "sessions": int(sessions or 0), "totals": totals, "by_kind": by_kind}
async def prune(cutoff: datetime) -> int:
async with async_session() as session:
result = await session.execute(delete(RecordDelivery).where(RecordDelivery.delivered_at < cutoff))
await session.commit()
return int(result.rowcount or 0)