feat(7836): a lesson arrives at the situation confirmed for it, once per session
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

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>
This commit is contained in:
2026-11-25 06:10:23 -05:00
co-authored by Claude Opus 5.5
parent ff3fca6a94
commit c22e8e1844
24 changed files with 1506 additions and 8 deletions
+2
View File
@@ -168,6 +168,7 @@ _READ_ONLY_TOOLS = frozenset({
# rules are unjudged and which proposals wait. Reads of the caller's own
# rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals",
"lessons_to_situate", "lesson_situation_proposals",
"rules_to_weigh", "rule_weight_proposals",
# Adherence: the readout, and the queue a transcript review works from.
"rule_adherence", "adherence_to_judge",
@@ -183,6 +184,7 @@ _WRITE_TOOLS = frozenset({
# notes, tasks, planning
"create_note", "update_note", "delete_note",
"create_lesson", "update_lesson", "delete_lesson", "judge_lesson_link",
"propose_lesson_situations", "judge_lesson_situations",
"create_task", "update_task", "delete_task", "add_task_log",
"create_records", "start_planning",
"create_milestone", "update_milestone", "delete_milestone",
+66 -1
View File
@@ -14,6 +14,7 @@ from grimoire.services import access as access_svc
from grimoire.services import dedup as dedup_svc
from grimoire.services import knowledge as knowledge_svc
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import lesson_situations as lesson_situations_svc
from grimoire.services import lessons as lessons_svc
from grimoire.services import systems as systems_svc
from grimoire.services import trash as trash_svc
@@ -451,7 +452,71 @@ async def delete_lesson(lesson_id: int) -> dict:
}
async def lessons_to_situate(limit: int = 25, offset: int = 0) -> dict:
"""The lessons with no situation yet — the pass over the corpus, a page at a time.
A lesson with no situation arrives only when a prompt's words resemble
it. Read each one here and decide WHEN it applies: a moment of work it
belongs to, a trigger on the act (a `path` glob, a `command` prefix, a
`tool`, a `keyword`), or that none fits. Record the answer with
`propose_lesson_situations`. A lesson leaves this list once any answer is
recorded, so the next call returns the next unread lessons.
Each lesson carries its title, its stated `when_to_apply`, the `rules` it
is a confirmed instance of with their own moments and triggers (the
strongest hint at its situation), and values already `rejected` for it.
The page carries the moment `catalog` and the `trigger_kinds`.
"""
return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset)
async def propose_lesson_situations(proposals: list[dict]) -> dict:
"""Propose when lessons apply — for the operator to confirm; nothing is delivered by this call.
Each item is `{"lesson_id": N, "moments": ["work.deliver"], "triggers":
[{"kind": "path", "pattern": "alembic/versions/*.py"}], "why": "…"}`.
Empty `moments` and `triggers` say no situation fits: the lesson stays
reachable by meaning, and leaves the pass's list.
Propose a moment when the lesson is about that point in the work whatever
the work is about; a trigger when it is about a kind of file, command or
tool. Keep it to the few points where the lesson changes what is done —
a lesson that matches every edit is noise there. `why` is shown to the
operator beside the proposal; write it so they can say yes or no without
opening the lesson.
Returns `written`, `skipped` (already recorded, in any state) and
`refused` (a bad item, refused alone). Then show the operator what waits
(`lesson_situation_proposals`); they judge it in Settings › Moments or
through `judge_lesson_situations`.
"""
return await lesson_situations_svc.propose(current_user_id(), proposals)
async def lesson_situation_proposals(lesson_id: int = 0) -> dict:
"""The lesson situations waiting on the operator, grouped by lesson.
Each proposal has its `id` (what `judge_lesson_situations` takes), its
`kind` (`moment` or `trigger`), what it `describes`, and the proposer's
`note`. `lesson_id` narrows to one lesson.
"""
return await lesson_situations_svc.pending(current_user_id(), lesson_id=lesson_id or None)
async def judge_lesson_situations(judgments: list[dict]) -> dict:
"""Confirm or reject lesson situations — on the operator's word, since a confirm changes what reaches their sessions.
Each item is `{"id": N, "verdict": "confirm" | "reject", "note": "why"}`,
with the id from `lesson_situation_proposals`. A confirmed situation
delivers its lesson when the work reaches it, once per session; a
rejected one is never proposed again. Put the operator's reason in `note`.
"""
return await lesson_situations_svc.judge(current_user_id(), judgments)
def register(mcp) -> None:
for fn in (list_lessons, create_lesson, get_lesson, update_lesson,
delete_lesson, judge_lesson_link):
delete_lesson, judge_lesson_link, lessons_to_situate,
propose_lesson_situations, lesson_situation_proposals,
judge_lesson_situations):
mcp.tool(name=fn.__name__)(fn)
+1
View File
@@ -84,6 +84,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
)
# After notes and rules: it foreign-keys both.
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
from grimoire.models.lesson_situation import LessonSituation # noqa: E402, F401
# After rules: it foreign-keys them.
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
+77
View File
@@ -0,0 +1,77 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import CreatedAtMixin, iso
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
__all__ = [
"CONFIRMED", "KINDS", "MOMENT", "NONE", "REJECTED", "SITUATION_STATES", "SOURCES",
"SUGGESTED", "TRIGGER", "LessonSituation",
]
# The same three states as a lesson's link to a rule. CHECK
# ck_lesson_situations_state (migration 0137).
SITUATION_STATES = LINK_STATES
# What a row names. `moment` — a catalog moment key: the lesson arrives when
# the work reaches it. `trigger` — a typed predicate on the act (tool, path,
# command, keyword), stored as `rule_field_judgments.trigger_value` writes it,
# so it is matched exactly as a rule's trigger is. `none` — the lesson was
# read and no situation fits it; it is reached by meaning alone, and the row
# keeps it out of the next pass's queue. CHECK ck_lesson_situations_kind.
MOMENT, TRIGGER, NONE = "moment", "trigger", "none"
KINDS = (MOMENT, TRIGGER, NONE)
# `pass` — an agent read the lesson and proposed; `edit` — a person set the
# lesson's situations directly. CHECK ck_lesson_situations_source.
SOURCES = ("pass", "edit")
class LessonSituation(Base, CreatedAtMixin):
"""When a lesson applies, as something the work can be checked against.
One row per (lesson, kind, value):
- ``suggested`` — proposed by a pass. Delivers nothing until judged.
- ``confirmed`` — the lesson arrives when this moment is reached or this
trigger matches the act, once per session.
- ``rejected`` — judged not to be when it applies, kept with the reason
so the same value is never proposed again.
"""
__tablename__ = "lesson_situations"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
lesson_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("notes.id", ondelete="CASCADE"), index=True,
)
kind: Mapped[str] = mapped_column(Text)
value: Mapped[str] = mapped_column(Text, default="", server_default="")
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
# For a suggestion, what the proposer read in the lesson; for a judgment,
# why it was confirmed or rejected.
note: Mapped[str | None] = mapped_column(Text, nullable=True)
judged_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True,
)
__table_args__ = (
UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"lesson_id": self.lesson_id,
"kind": self.kind,
"value": self.value,
"state": self.state,
"source": self.source,
"note": self.note or "",
"judged_at": iso(self.judged_at),
"created_at": iso(self.created_at),
}
+73
View File
@@ -27,6 +27,7 @@ from grimoire.routes.utils import not_found, parse_pagination
from grimoire.services import dedup as dedup_svc
from grimoire.services import knowledge as knowledge_svc
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import lesson_situations as lesson_situations_svc
from grimoire.services import lessons as lessons_svc
from grimoire.services import systems as systems_svc
from grimoire.services import trash as trash_svc
@@ -358,6 +359,78 @@ async def judge_lesson_link_route(lesson_id: int, rule_id: int):
return jsonify(link)
# ── when a lesson applies (services/lesson_situations.py) ───────────────────
@lessons_bp.route("/situations/proposals", methods=["GET"])
@login_required
async def lesson_situation_proposals_route():
"""The situations a pass proposed and a person has not judged, grouped
by lesson, with how many lessons are situated, have none, or are unread
— `lesson_situation_proposals` from the browser."""
uid = get_current_user_id()
out = await lesson_situations_svc.pending(uid)
out["counts"] = await lesson_situations_svc.counts(uid)
return jsonify(out)
@lessons_bp.route("/situations/judge", methods=["POST"])
@login_required
async def judge_lesson_situations_route():
"""Confirm or reject proposals: `{"judgments": [{id, verdict, note}]}`.
A confirm changes what reaches the user's sessions."""
data = await request.get_json(silent=True)
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
try:
return jsonify(await lesson_situations_svc.judge(get_current_user_id(), data["judgments"]))
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
@lessons_bp.route("/<int:lesson_id>/situations", methods=["GET"])
@login_required
async def lesson_situations_route(lesson_id: int):
"""A lesson's live situations and waiting proposals, with the moment
catalog and trigger kinds its page offers for adding one."""
from grimoire.services import moments as moments_svc
from grimoire.services import rule_triggers
return jsonify({
"situations": await lesson_situations_svc.for_lesson(get_current_user_id(), lesson_id),
"catalog": [{"name": m["name"], "means": m["means"]}
for m in moments_svc.catalog()["moments"]],
"trigger_kinds": list(rule_triggers.KINDS),
})
@lessons_bp.route("/<int:lesson_id>/situations", methods=["POST"])
@login_required
async def add_lesson_situation_route(lesson_id: int):
"""Make one situation live on a lesson. Body: `{"moment": "work.deliver"}`
or `{"trigger": {"kind", "pattern"}}`."""
data = await request.get_json(silent=True) or {}
trigger = data.get("trigger") if isinstance(data, dict) else None
try:
return jsonify(await lesson_situations_svc.add(
get_current_user_id(), lesson_id,
moment=str(data.get("moment") or "") if isinstance(data, dict) else "",
trigger=trigger if isinstance(trigger, dict) else None,
)), 201
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
@lessons_bp.route("/situations/<int:situation_id>", methods=["DELETE"])
@login_required
async def remove_lesson_situation_route(situation_id: int):
"""Take a situation off its lesson; kept as rejected so it is not proposed again."""
try:
return jsonify(await lesson_situations_svc.remove(get_current_user_id(), situation_id))
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
@lessons_bp.route("/<int:lesson_id>", methods=["DELETE"])
@login_required
async def delete_lesson_route(lesson_id: int):
+8
View File
@@ -399,8 +399,16 @@ async def moment():
shapes, forms = moment_delivery_svc.shapes_for_act(
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
)
# Lessons recorded for this situation, after the rules: each once per
# session, and booked in the record ledger only if its line is kept.
lesson_lines, lesson_ids = await moment_delivery_svc.lessons_for_act(
g.user.id, reached, tool, tool_input if isinstance(tool_input, dict) else {},
)
record_deliveries_svc.record(g.user.id, lesson_ids, "lesson_situation")
fitted = await hook_payload_svc.fit(g.user.id, [
*hook_payload_svc.rule_parts(result.lines, result.rule_per_line(), block="rules"),
*(hook_payload_svc.Part(text=text, block="lessons", ids={hook_payload_svc.NOTE: (lid,)})
for text, lid in zip(lesson_lines, lesson_ids, strict=True)),
*(hook_payload_svc.Part(text=block, ids={hook_payload_svc.SHAPE: (key,)})
for block, key in zip(shapes, forms, strict=False)),
])
+505
View File
@@ -0,0 +1,505 @@
"""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 door shows each
once per session.
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"
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, moments.require_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": [{"name": m["name"], "means": m["means"]} for m in moments.catalog()["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
+38 -2
View File
@@ -56,8 +56,11 @@ async def reachable_tools(user_id: int) -> list[str]:
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
from grimoire.services import rule_triggers
from grimoire.services import lesson_situations
mounted = set(await rulebooks.mounted_moments(user_id))
wanted = mounted | shaped
lesson_moments, lesson_tools = await lesson_situations.reachable(user_id)
wanted = mounted | shaped | lesson_moments
mappings = await moment_actions.list_mappings(user_id)
keys = {
moment_actions.tool_key(action.tool)
@@ -72,7 +75,8 @@ async def reachable_tools(user_id: int) -> list[str]:
keys |= await rule_triggers.reachable_tools(user_id)
except Exception: # noqa: BLE001 - the mounts' tools are still worth listing
logger.debug("rule trigger tools unreadable", exc_info=True)
return sorted(keys)
# A lesson triggered by an act is reached the same way.
return sorted(keys | lesson_tools)
async def _board(user_id: int, project_id: int | None, **act):
@@ -130,6 +134,31 @@ async def deliver_for_act(
return reached, result
async def lessons_for_act(
user_id: int, reached: list[dict], tool: str | None, tool_input: dict | None, *,
once_per_session: bool = True,
) -> tuple[list[str], list[int]]:
"""The lines and ids of the lessons recorded for this act's situation: a
confirmed moment it reached, or a confirmed trigger it matches.
`once_per_session` leaves out a lesson the session's record ledger
already holds, and is what the plugin's door asks for; a door with no
session (an MCP reply) shows them every time its act happens, as it does
the rules mounted there."""
from grimoire.services import lesson_situations, record_deliveries
arrivals = await lesson_situations.for_act(
user_id, [hit["moment"] for hit in reached or []],
tool=tool, tool_input=tool_input or {},
)
if once_per_session and arrivals:
had = await record_deliveries.delivered_this_session(
user_id, [a.lesson_id for a in arrivals],
)
arrivals = [a for a in arrivals if a.lesson_id not in had]
return [lesson_situations.line(a) for a in arrivals], [a.lesson_id for a in arrivals]
# The file-writing tools, as tool keys: a `hold` rule never holds these.
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
@@ -254,6 +283,13 @@ async def attach_moment_rules(
"rule_ids": result.shown_rule_ids,
"open_with": "get_rule(id)",
}
lesson_lines, lesson_ids = await lessons_for_act(
user_id, _reached, tool, arguments or {}, once_per_session=False,
)
if lesson_lines:
data["moment_lessons"] = {
"lines": lesson_lines, "lesson_ids": lesson_ids, "open_with": "get_lesson(id)",
}
# The reply shape for this moment, in full: no ledger reaches this
# door, and an act like closing a task is rare enough that the shape
# arriving each time costs less than one report written without it.
@@ -91,6 +91,30 @@ def flush(kept: set[int] | None = None) -> None:
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."""
+4 -1
View File
@@ -92,9 +92,12 @@ DOORS: dict[str, Door] = {
# What is about to be written: code to reuse, and what was already tried
# (an issue, a dev-log, a lesson). The open to-do list resembles the code
# and answers nothing, so work tasks are left out.
# Not lessons: an edit's words resemble a lesson far more often than the
# edit is its situation. A lesson reaches an edit through a situation
# confirmed for it (`lesson_situations`), once per session.
"work.change": Door(
"work.change", "Altering the thing being worked on", "before every write or edit",
frozenset({"snippet", "note", "lesson", "task:issue"}),
frozenset({"snippet", "note", "task:issue"}),
sources=("write_path_semantic", "write_path_place", "write_path_sync",
"write_path_linked"),
),
+3
View File
@@ -51,6 +51,9 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
"update_lesson": {"lesson_id": NOTE},
"delete_lesson": {"lesson_id": NOTE},
"judge_lesson_link": {},
# When a lesson applies: judgments on how the corpus is retrieved.
"propose_lesson_situations": {},
"judge_lesson_situations": {},
"create_task": {"project_id": PROJECT, "milestone_id": MILESTONE, "parent_id": NOTE},
"update_task": {"task_id": NOTE, "project_id": PROJECT, "milestone_id": MILESTONE},
"delete_task": {"task_id": NOTE},