Files
FabledGrimoire/src/grimoire/services/lesson_situations.py
T
bvandeusenandClaude Opus 5.5 07c4a716bd
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 2m0s
CI & Build / Python tests (push) Successful in 3m48s
CI & Build / Build & push image (push) Successful in 20s
fix(7883): a lesson recorded for reply.report reaches the turn before the reply, and reply.ask is not offered to a lesson
Situated lessons arrived only at tool acts and in MCP replies, so a lesson
given a reply moment was accepted and never shown. The per-turn delivery now
carries lessons confirmed on reply.report, once per session, between the
turn's rules and its reply shape. reply.ask is known only after the reply is
written, so lesson_situations refuses it and leaves it out of the catalog the
pass and the lesson page offer.

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

530 lines
22 KiB
Python

"""When a lesson applies: moments and triggers, proposed by a pass, judged by
a person, delivered when the work reaches them.
WHY THIS EXISTS
A lesson records one situation and what was learned in it. Found by meaning,
it arrives whenever the words of an edit or a prompt resemble it, which is
most of the time and rarely the situation. A lesson that names WHEN it
applies — a moment of work (`work.deliver`, `work.finish`, …) or a typed
trigger on the act (a path, a command, a tool, a keyword) — can arrive at
exactly that point, and at no other.
THE STATES (models/lesson_situation.py):
- THE PASS. An agent reads each lesson that has no situation yet
(`to_situate`), beside its stated "when to apply" and the moments and
triggers of the rules it is a confirmed instance of, and proposes its
situation (`propose`): moments, triggers, or that none fits. A proposal
delivers nothing.
- THE JUDGMENT. A person confirms or rejects each proposal (`judge`), or sets
a lesson's situation directly (`add` / `remove`), which is a judgment too.
A rejected value is never proposed again.
- DELIVERY. `for_act` returns the lessons whose confirmed moment this act
reached or whose confirmed trigger it matches. The plugin's doors show each
once per session: the act door for tool calls, and the turn's delivery for
`reply.report`, before the reply is written. `reply.ask` has no door
(`NO_LESSON_DOOR`) and is refused.
ACL (services/access.py). Proposing, judging and editing change what a
lesson says about itself, so they need WRITE on the lesson
(`access.can_write_note`). Delivery reads only lessons the reader may read.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from sqlalchemy import exists, func, or_, select
from grimoire.models import async_session
from grimoire.models.lesson_situation import (
CONFIRMED, MOMENT, NONE, REJECTED, SUGGESTED, TRIGGER, LessonSituation,
)
from grimoire.models.note import Note
from grimoire.services import access, moments
from grimoire.services import rule_triggers as triggers_svc
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line, lesson_trigger
logger = logging.getLogger(__name__)
VERDICTS = {"confirm": CONFIRMED, "reject": REJECTED}
# Lessons per pass page: enough to batch the reading, few enough that each
# lesson is actually read.
PASS_PAGE = 25
# A lesson's situation is a handful of points, not a net: past this it is
# being reached by everything again.
SITUATIONS_MAX = 8
_NOTE_CHARS = 600
_REMOVED_NOTE = "removed by an edit"
# Moments no door can bring a lesson to. Whether a reply asks something is
# known only once it is written, at the Stop hook, which can hold a reply for
# a rule but cannot inform it; a lesson about asking belongs on
# `reply.report`, which arrives before every reply.
NO_LESSON_DOOR = {
"reply.ask": "a lesson cannot arrive at reply.ask: whether a reply asks is known only "
"after it is written. Use reply.report, which arrives before every reply.",
}
def lesson_moments() -> list[dict]:
"""The moments a lesson can be recorded for, as `{name, means}`."""
return [{"name": m["name"], "means": m["means"]}
for m in moments.catalog()["moments"] if m["name"] not in NO_LESSON_DOOR]
def _require_lesson_moment(name: str) -> str:
clean = moments.require_moment(name)
if clean in NO_LESSON_DOOR:
raise ValueError(NO_LESSON_DOOR[clean])
return clean
def trigger_value(trigger: triggers_svc.Trigger) -> str:
"""A trigger as one stored string, the form rule_field_judgments uses."""
from grimoire.services.rule_field_judgments import trigger_value as _value
return _value(trigger)
def parse_trigger(value: str) -> triggers_svc.Trigger:
from grimoire.services.rule_field_judgments import parse_trigger_value
return parse_trigger_value(value)
def describe(kind: str, value: str) -> str:
"""How a situation reads in a line: "moment `work.deliver`"."""
if kind == MOMENT:
return f"moment `{value}`"
if kind == TRIGGER:
return parse_trigger(value).describe()
return "no situation"
def _item(row: LessonSituation) -> dict:
out = row.to_dict()
out["describes"] = describe(row.kind, row.value)
if row.kind == TRIGGER:
out["trigger"] = parse_trigger(row.value).to_dict()
return out
def _lesson_clause():
return (Note.note_type == LESSON_NOTE_TYPE) & Note.deleted_at.is_(None)
async def _require_writable(user_id: int, lesson_id: int) -> None:
if not await access.can_write_note(user_id, int(lesson_id)):
raise ValueError(f"lesson {lesson_id} not found or not writable")
async with async_session() as session:
found = (await session.execute(
select(Note.id).where(Note.id == int(lesson_id), _lesson_clause())
)).scalar_one_or_none()
if found is None:
raise ValueError(f"{lesson_id} is not a lesson")
def _values(moment_names, trigger_raw) -> list[tuple[str, str]]:
"""(kind, value) pairs, validated and de-duplicated, or the first refusal."""
out: list[tuple[str, str]] = []
for name in moment_names or []:
out.append((MOMENT, _require_lesson_moment(name)))
for raw in trigger_raw or []:
out.append((TRIGGER, trigger_value(triggers_svc.require_trigger(raw))))
out = list(dict.fromkeys(out))
if len(out) > SITUATIONS_MAX:
raise ValueError(f"a lesson carries at most {SITUATIONS_MAX} situations")
return out
# ── the pass ─────────────────────────────────────────────────────────────
def _unsituated_clause():
"""No proposal waiting and no live answer: every row it has, if any, was
rejected — so a lesson whose proposals were all turned down returns to
the queue, without them."""
return ~exists().where(
LessonSituation.lesson_id == Note.id,
LessonSituation.state.in_((SUGGESTED, CONFIRMED)),
)
async def to_situate(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> dict:
"""One page of lessons with no situation, each with what a proposer reads:
its claim, its stated "when to apply", the rules it is a confirmed
instance of with their moments and triggers, and the values already
rejected for it. With the moment catalog and the trigger kinds, once."""
from grimoire.services import lesson_rules
limit = max(1, min(int(limit or PASS_PAGE), 100))
async with async_session() as session:
base = select(Note).where(
_lesson_clause(), access.readable_notes_clause(user_id), _unsituated_clause(),
)
total = (await session.execute(
select(func.count()).select_from(base.subquery())
)).scalar_one()
notes = (await session.execute(
base.order_by(Note.updated_at.desc(), Note.id.desc()).offset(max(0, int(offset or 0))).limit(limit)
)).scalars().all()
ids = [int(n.id) for n in notes]
rejected: dict[int, list[dict]] = {}
if ids:
for row in (await session.execute(
select(LessonSituation).where(
LessonSituation.lesson_id.in_(ids), LessonSituation.state == REJECTED,
)
)).scalars().all():
rejected.setdefault(int(row.lesson_id), []).append(
{"describes": describe(row.kind, row.value), "why": row.note or ""}
)
writable = [n for n in notes if await access.can_write_note(user_id, int(n.id))]
rules = await lesson_rules.rules_for_lessons(user_id, [int(n.id) for n in writable])
rule_ids = {r["id"] for links in rules.values() for r in links if r["state"] == CONFIRMED}
situations = await _rule_situations(rule_ids)
lessons = []
for n in writable:
confirmed = [r for r in rules.get(int(n.id), []) if r["state"] == CONFIRMED]
lessons.append({
"id": int(n.id),
"title": claim_line(n.title),
"when_to_apply": lesson_trigger(n),
"project_id": n.project_id,
"rules": [{"id": r["id"], "title": r["title"], **situations.get(r["id"], {})}
for r in confirmed],
"rejected": rejected.get(int(n.id), []),
})
return {
"lessons": lessons,
"total": int(total),
"offset": int(offset or 0),
"catalog": lesson_moments(),
"trigger_kinds": list(triggers_svc.KINDS),
}
async def _rule_situations(rule_ids) -> dict[int, dict]:
"""{rule_id: {moments, triggers}} for rules `rules_for_lessons` already
scoped to the reader: a lesson's confirmed rule is the strongest hint at
when the lesson applies."""
from grimoire.services import rulebooks
ids = sorted(int(i) for i in rule_ids or [])
if not ids:
return {}
try:
mounts = await rulebooks.list_rule_moments(ids)
trig = await triggers_svc.list_rule_triggers(ids)
except Exception: # noqa: BLE001 - a hint, not the proposal
logger.debug("rule situations unreadable", exc_info=True)
return {}
return {i: {"moments": list(mounts.get(i, [])), "triggers": trig.get(i, [])} for i in ids}
async def propose(user_id: int, proposals: list[dict]) -> dict:
"""Record a pass's proposals: `[{lesson_id, moments, triggers, why}]`.
Empty `moments` and `triggers` say no situation fits: that answer needs no
judgment, since it delivers nothing, and is recorded confirmed so the
lesson leaves the queue. A value already recorded for the lesson, in any
state, is skipped: a rejection is never proposed again, and a waiting or
live one is already there. A bad item (an unknown moment, a malformed
trigger, a lesson the caller cannot write) is refused alone, under
`refused`, and the rest are recorded.
"""
if not isinstance(proposals, list) or not proposals:
raise ValueError("proposals is a list of {lesson_id, moments, triggers, why}")
planned: list[tuple[int, list[tuple[str, str]], str]] = []
refused: list[dict] = []
for p in proposals:
if not isinstance(p, dict):
refused.append({"item": p, "error": "each proposal is {lesson_id, moments, triggers, why}"})
continue
try:
lesson_id = int(p.get("lesson_id") or 0)
await _require_writable(user_id, lesson_id)
values = _values(p.get("moments"), p.get("triggers"))
except (TypeError, ValueError) as e:
refused.append({"lesson_id": p.get("lesson_id"), "error": str(e)})
continue
why = " ".join(str(p.get("why") or "").split())[:_NOTE_CHARS]
planned.append((lesson_id, values, why))
now = datetime.now(timezone.utc)
written = skipped = 0
async with async_session() as session:
for lesson_id, values, why in planned:
have = {(r.kind, r.value) for r in (await session.execute(
select(LessonSituation).where(LessonSituation.lesson_id == lesson_id)
)).scalars().all()}
if not values:
if (NONE, "") in have:
skipped += 1
continue
session.add(LessonSituation(
lesson_id=lesson_id, kind=NONE, value="", state=CONFIRMED,
source="pass", note=why or None, judged_at=now,
))
written += 1
continue
for kind, value in values:
if (kind, value) in have:
skipped += 1
continue
session.add(LessonSituation(
lesson_id=lesson_id, kind=kind, value=value, state=SUGGESTED,
source="pass", note=why or None,
))
written += 1
await session.commit()
return {"written": written, "skipped": skipped, "refused": refused}
async def pending(user_id: int, lesson_id: int | None = None, limit: int = 200) -> dict:
"""The proposals waiting on a person, grouped by lesson, for lessons the
caller may write — the only ones they could judge."""
async with async_session() as session:
q = (
select(LessonSituation, Note)
.join(Note, Note.id == LessonSituation.lesson_id)
.where(LessonSituation.state == SUGGESTED, _lesson_clause(),
access.readable_notes_clause(user_id))
.order_by(Note.id, LessonSituation.id)
.limit(max(1, min(int(limit or 200), 500)))
)
if lesson_id:
q = q.where(LessonSituation.lesson_id == int(lesson_id))
rows = (await session.execute(q)).all()
grouped: dict[int, dict] = {}
for row, note in rows:
if int(note.id) not in grouped:
if not await access.can_write_note(user_id, int(note.id)):
continue
grouped[int(note.id)] = {
"lesson_id": int(note.id), "title": claim_line(note.title),
"when_to_apply": lesson_trigger(note), "proposals": [],
}
grouped[int(note.id)]["proposals"].append(_item(row))
lessons = list(grouped.values())
return {"lessons": lessons, "total": sum(len(g["proposals"]) for g in lessons)}
async def judge(user_id: int, judgments: list[dict]) -> dict:
"""Confirm or reject proposals: `[{id, verdict, note?}]`, `verdict`
"confirm" or "reject". Each must be a waiting proposal on a lesson the
caller may write; all are checked before any is applied."""
if not isinstance(judgments, list) or not judgments:
raise ValueError("judgments is a list of {id, verdict, note?}")
planned: list[tuple[int, str, str]] = []
for j in judgments:
if not isinstance(j, dict):
raise ValueError("each judgment is {id, verdict, note?}")
verdict = str(j.get("verdict") or "").strip().lower()
if verdict not in VERDICTS:
raise ValueError('verdict is "confirm" or "reject"')
note = " ".join(str(j.get("note") or "").split())[:_NOTE_CHARS]
planned.append((int(j.get("id") or 0), VERDICTS[verdict], note))
now = datetime.now(timezone.utc)
out = []
async with async_session() as session:
rows = {r.id: r for r in (await session.execute(
select(LessonSituation).where(LessonSituation.id.in_([p[0] for p in planned]))
)).scalars().all()}
for sid, _state, _note in planned:
row = rows.get(sid)
if row is None or row.state != SUGGESTED:
raise ValueError(f"situation {sid} is not a waiting proposal")
await _require_writable(user_id, row.lesson_id)
for sid, state, note in planned:
row = rows[sid]
row.state = state
row.judged_at = now
if note:
row.note = note
out.append(_item(row))
await session.commit()
return {"judged": out}
# ── a person setting a lesson's situation ────────────────────────────────
async def for_lesson(user_id: int, lesson_id: int) -> list[dict]:
"""A lesson's live situations and waiting proposals, for its page."""
if not await access.can_read_note(user_id, int(lesson_id)):
return []
async with async_session() as session:
rows = (await session.execute(
select(LessonSituation)
.where(LessonSituation.lesson_id == int(lesson_id),
LessonSituation.state.in_((CONFIRMED, SUGGESTED)),
LessonSituation.kind != NONE)
.order_by(LessonSituation.id)
)).scalars().all()
return [_item(r) for r in rows]
async def add(user_id: int, lesson_id: int, *, moment: str = "", trigger: dict | None = None) -> dict:
"""Make one moment or trigger live on a lesson — a person's judgment, so
it is confirmed at once. A row already there for the value (a rejection,
or a waiting proposal) is overturned to confirmed. A `none` answer is
cleared: the lesson now has a situation."""
await _require_writable(user_id, lesson_id)
values = _values([moment] if moment else [], [trigger] if trigger else [])
if len(values) != 1:
raise ValueError("add one moment or one trigger")
kind, value = values[0]
now = datetime.now(timezone.utc)
async with async_session() as session:
rows = (await session.execute(
select(LessonSituation).where(LessonSituation.lesson_id == int(lesson_id))
)).scalars().all()
if sum(1 for r in rows if r.state == CONFIRMED and r.kind != NONE) >= SITUATIONS_MAX:
raise ValueError(f"a lesson carries at most {SITUATIONS_MAX} situations")
row = next((r for r in rows if (r.kind, r.value) == (kind, value)), None)
for r in rows:
if r.kind == NONE:
await session.delete(r)
if row is None:
row = LessonSituation(lesson_id=int(lesson_id), kind=kind, value=value)
session.add(row)
row.state, row.source, row.judged_at = CONFIRMED, "edit", now
await session.commit()
await session.refresh(row)
return _item(row)
async def remove(user_id: int, situation_id: int) -> dict:
"""Take a live situation off its lesson. Kept as rejected, with the
reason, so a later pass does not propose it again."""
async with async_session() as session:
row = await session.get(LessonSituation, int(situation_id))
if row is None:
raise ValueError(f"situation {situation_id} not found")
await _require_writable(user_id, row.lesson_id)
row.state, row.source, row.note = REJECTED, "edit", _REMOVED_NOTE
row.judged_at = datetime.now(timezone.utc)
await session.commit()
return _item(row)
async def counts(user_id: int) -> dict:
"""How many readable lessons are situated, have no situation, wait on a
judgment, or were read and found to have none — the panel's header."""
async with async_session() as session:
def has(state, kind=None):
cond = [LessonSituation.lesson_id == Note.id, LessonSituation.state == state]
if kind == NONE:
cond.append(LessonSituation.kind == NONE)
elif kind:
cond.append(LessonSituation.kind != NONE)
return exists().where(*cond)
base = [_lesson_clause(), access.readable_notes_clause(user_id)]
async def n(*cond):
return int((await session.execute(
select(func.count(Note.id)).where(*base, *cond)
)).scalar_one())
return {
"situated": await n(has(CONFIRMED, "live")),
"none_fits": await n(has(CONFIRMED, NONE)),
"waiting": await n(has(SUGGESTED)),
"unsituated": await n(_unsituated_clause()),
}
# ── delivery ─────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class Arrival:
lesson_id: int
title: str
because: str
async def for_act(
user_id: int, reached: list[str], *, tool: str | None = None,
tool_input: dict | None = None, text: str = "",
exclude: frozenset[int] = frozenset(),
) -> list[Arrival]:
"""The lessons whose confirmed moment is among `reached` or whose
confirmed trigger this act (or, with no tool, this text) matches, most
recently updated first. Readable lessons only, from any project: a lesson
is offered wherever its situation comes up, not only where it was
written. `exclude` are lessons this session already has. Fails open."""
reached = [m for m in reached or [] if m]
try:
async with async_session() as session:
rows = (await session.execute(
select(LessonSituation.kind, LessonSituation.value, Note.id, Note.title)
.join(Note, Note.id == LessonSituation.lesson_id)
.where(
LessonSituation.state == CONFIRMED,
or_(
(LessonSituation.kind == MOMENT) & LessonSituation.value.in_(reached),
LessonSituation.kind == TRIGGER,
),
_lesson_clause(),
access.readable_notes_clause(user_id),
)
.order_by(Note.updated_at.desc(), Note.id.desc(), LessonSituation.id)
)).all()
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.warning("lesson situations unreadable", exc_info=True)
return []
out: dict[int, Arrival] = {}
for kind, value, nid, title in rows:
nid = int(nid)
if nid in out or nid in exclude:
continue
if kind == TRIGGER:
try:
if not triggers_svc.matches(parse_trigger(value), tool, tool_input, text):
continue
except Exception: # noqa: BLE001 - one bad row never blocks the rest
continue
out[nid] = Arrival(nid, claim_line(title), describe(kind, value))
return list(out.values())
def line(arrival: Arrival) -> str:
"""One lesson, as the line the work sees."""
return (
f"> Lesson #{arrival.lesson_id} \"{arrival.title}\" — recorded for this "
f"situation ({arrival.because}); `get_lesson({arrival.lesson_id})` has what was learned."
)
async def reachable(user_id: int) -> tuple[set[str], set[str]]:
"""(moments, tool keys) that a confirmed lesson situation listens on, for
the plugin's catch-all filter: a call that reaches neither never leaves
the machine, so a lesson's trigger must name its tools here."""
try:
async with async_session() as session:
rows = (await session.execute(
select(LessonSituation.kind, LessonSituation.value)
.join(Note, Note.id == LessonSituation.lesson_id)
.where(LessonSituation.state == CONFIRMED,
LessonSituation.kind.in_((MOMENT, TRIGGER)),
_lesson_clause(), access.readable_notes_clause(user_id))
.distinct()
)).all()
except Exception: # noqa: BLE001 - the rules' tools are still worth listing
logger.debug("lesson situations unreadable", exc_info=True)
return set(), set()
found_moments: set[str] = set()
tools: set[str] = set()
for kind, value in rows:
if kind == MOMENT:
found_moments.add(value)
else:
tools |= triggers_svc.tools_for(parse_trigger(value))
return found_moments, tools