Files
FabledGrimoire/src/grimoire/services/record_deliveries.py
T
bvandeusenandClaude Opus 5.5 c22e8e1844
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Skipped
feat(7836): a lesson arrives at the situation confirmed for it, once per session
Each lesson can carry its situation: a moment of work (work.deliver,
work.finish, ...) or a typed trigger on the act (path, command, tool,
keyword, matched as rule triggers are). A pass proposes, a person judges:

- lesson_situations (migration 0137): one row per lesson, kind and value,
  suggested / confirmed / rejected; `none` records that no situation fits;
- MCP: lessons_to_situate, propose_lesson_situations,
  lesson_situation_proposals, judge_lesson_situations;
- Settings > Moments lists waiting proposals with Apply / Not this /
  Apply all; a lesson page lists its situations and lets a writer add one
  or take one off (kept as rejected, never proposed again).

Delivery: the moment doors (the plugin catch-all hook and MCP replies) add
the lessons whose confirmed moment the act reached or whose trigger it
matches. The plugin door shows each once per session, using the record
ledger, and records it as pushed (source lesson_situation); the tool filter
now includes the tools a lesson trigger listens on.

The edit door no longer finds lessons by meaning: lesson leaves the
work.change default kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:10:23 -05:00

291 lines
13 KiB
Python

"""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`, `pointed`, `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, POINTED, 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.record_kinds import kind_of
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, way: str = PUSHED) -> None:
"""Record records a hook put in front of the bound session: `pushed` as a
line, or `pointed` when only named by id in a pointer line. 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": way, "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")
async def delivered_this_session(user_id: int, note_ids) -> set[int]:
"""Which of these records the bound session was already shown or pointed
at, so a door that shows a record once per session can leave them out.
Empty outside a plugin request, where there is no session to ask about."""
sid = rule_deliveries.current_session()
ids = {int(n) for n in note_ids or []}
if not sid or not user_id or not ids:
return set()
try:
async with async_session() as session:
rows = (await session.execute(
select(RecordDelivery.note_id).where(
RecordDelivery.user_id == int(user_id),
RecordDelivery.session_id == sid,
RecordDelivery.note_id.in_(ids),
RecordDelivery.way.in_((PUSHED, POINTED)),
).distinct()
)).scalars().all()
except Exception: # noqa: BLE001 - a repeat is better than a lost line
logger.debug("session record ledger unreadable", exc_info=True)
return set()
return {int(r) for r in rows}
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_of(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, POINTED, 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)