From 07c4a716bd43e32aa5910cc2c372c974463a833c Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 25 Nov 2026 10:48:12 -0500 Subject: [PATCH] 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 --- src/grimoire/mcp/tools/lessons.py | 5 ++- src/grimoire/routes/lessons.py | 7 ++-- src/grimoire/routes/plugin.py | 6 +++- src/grimoire/services/lesson_situations.py | 32 ++++++++++++++--- src/grimoire/services/moment_delivery.py | 27 ++++++++++----- tests/test_lesson_situation_delivery.py | 40 ++++++++++++++++++++-- tests/test_reply_shape_turn.py | 20 +++++++++-- 7 files changed, 114 insertions(+), 23 deletions(-) diff --git a/src/grimoire/mcp/tools/lessons.py b/src/grimoire/mcp/tools/lessons.py index b300a875..0437210a 100644 --- a/src/grimoire/mcp/tools/lessons.py +++ b/src/grimoire/mcp/tools/lessons.py @@ -465,7 +465,10 @@ async def lessons_to_situate(limit: int = 25, offset: int = 0) -> dict: 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`. + The page carries the `catalog` of moments a lesson can arrive at and the + `trigger_kinds`. A lesson about writing a reply (a report, a proposal, a + question put to the operator) goes on `reply.report`, which arrives + before every reply is written. """ return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset) diff --git a/src/grimoire/routes/lessons.py b/src/grimoire/routes/lessons.py index 8d4070df..852b760f 100644 --- a/src/grimoire/routes/lessons.py +++ b/src/grimoire/routes/lessons.py @@ -392,14 +392,13 @@ async def judge_lesson_situations_route(): @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 + catalog and trigger kinds its page offers for adding one — the moments a + lesson can arrive at, not every moment a rule can mount on.""" 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"]], + "catalog": lesson_situations_svc.lesson_moments(), "trigger_kinds": list(rule_triggers.KINDS), }) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 4e5ad148..e31656ab 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -227,8 +227,12 @@ async def autoinject_retrieve(): # what the last turn left unjudged, then the records menu, fitted to the # budget. carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS] + # Lessons recorded for the reply, once per session: booked in the record + # ledger only if the fit keeps their line. + record_deliveries_svc.record(g.user.id, turn.get("lesson_ids") or [], "lesson_situation") turn_parts = ( - [*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn + [*turn["rule_parts"], *turn.get("lesson_parts", []), *turn["shape_parts"]] + if "shape_parts" in turn else [hook_payload_svc.Part(text=turn.get("context") or "", ids={ hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()), hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()), diff --git a/src/grimoire/services/lesson_situations.py b/src/grimoire/services/lesson_situations.py index 10d7cfc9..e174aec8 100644 --- a/src/grimoire/services/lesson_situations.py +++ b/src/grimoire/services/lesson_situations.py @@ -21,8 +21,10 @@ THE STATES (models/lesson_situation.py): 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. + 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 @@ -58,6 +60,28 @@ 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.""" @@ -108,7 +132,7 @@ 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))) + 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)) @@ -179,7 +203,7 @@ async def to_situate(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> d "lessons": lessons, "total": int(total), "offset": int(offset or 0), - "catalog": [{"name": m["name"], "means": m["means"]} for m in moments.catalog()["moments"]], + "catalog": lesson_moments(), "trigger_kinds": list(triggers_svc.KINDS), } diff --git a/src/grimoire/services/moment_delivery.py b/src/grimoire/services/moment_delivery.py index 7780b334..58f0e7f4 100644 --- a/src/grimoire/services/moment_delivery.py +++ b/src/grimoire/services/moment_delivery.py @@ -217,15 +217,17 @@ async def deliver_for_turn( The core reply shape — in full once per session and again after a compaction (the ledger is swept then), otherwise its one-line reminder — - and the rules and preferences mounted on `reply.report`, under the same - rule ledger as every other arm. The Stop hook's reply moment fires after - the reply exists, which is too late to shape it and is kept as the - backstop; this is the point before. + the rules and preferences mounted on `reply.report`, under the same rule + ledger as every other arm, and the lessons recorded for `reply.report`, + each once per session. The Stop hook's reply moment fires after the reply + exists, which is too late to shape it and is kept as the backstop; this + is the point before. - Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts}`; the - parts are for a door that fits its payload, which passes `record=False` - and records the shapes it kept. Fails open to the core alone, and the - core itself never fails: it is a constant. + Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts, + lesson_parts, lesson_ids}`; the parts are for a door that fits its + payload, which passes `record=False`, records the shapes it kept and + books `lesson_ids` in the record ledger before fitting. Fails open to the + core alone, and the core itself never fails: it is a constant. """ blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen) shape_parts = [ @@ -247,11 +249,20 @@ async def deliver_for_turn( ) except Exception: # noqa: BLE001 - the mounted half never costs the core logger.debug("reply.report mounts not delivered for the turn", exc_info=True) + lesson_lines, lesson_ids = await lessons_for_act( + user_id, [{"moment": "reply.report"}], None, {}, + ) + blocks.extend(lesson_lines) + lesson_parts = [ + hook_payload.Part(text=text, block="lessons", ids={hook_payload.NOTE: (lid,)}) + for text, lid in zip(lesson_lines, lesson_ids, strict=True) + ] if record: await reply_shapes.record_delivery(user_id, forms, via="turn") return { "context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms, "shape_parts": shape_parts, "rule_parts": rule_parts, + "lesson_parts": lesson_parts, "lesson_ids": lesson_ids, } diff --git a/tests/test_lesson_situation_delivery.py b/tests/test_lesson_situation_delivery.py index 27906859..a696b870 100644 --- a/tests/test_lesson_situation_delivery.py +++ b/tests/test_lesson_situation_delivery.py @@ -1,6 +1,7 @@ """A situated lesson reaches the work through the moment doors: the plugin's -door shows it once per session, and an MCP reply, which has no session, -carries it every time its act happens.""" +act door and the turn's delivery before a reply show it once per session, +and an MCP reply, which has no session, carries it every time its act +happens. A moment no door reaches is not offered to a lesson.""" from unittest.mock import AsyncMock, patch import pytest @@ -41,6 +42,41 @@ async def test_an_mcp_reply_carries_the_lessons_for_its_act_every_time(): ledger.assert_not_awaited() +@pytest.mark.asyncio +async def test_a_turn_carries_the_lessons_recorded_for_the_reply_before_it_is_written(): + found = AsyncMock(return_value=ARRIVALS[:1]) + with patch.object(moment_delivery, "deliver_moments", AsyncMock(return_value=rp.RuleResult())), \ + patch.object(lesson_situations, "for_act", found), \ + patch("grimoire.services.record_deliveries.delivered_this_session", + AsyncMock(return_value=set())): + out = await moment_delivery.deliver_for_turn(1, record=False) + assert found.await_args.args[1] == ["reply.report"] + assert out["lesson_ids"] == [41] + assert [p.block for p in out["lesson_parts"]] == ["lessons"] + assert lesson_situations.line(ARRIVALS[0]) in out["context"] + + +@pytest.mark.asyncio +async def test_a_turn_leaves_out_a_reply_lesson_the_session_already_has(): + with patch.object(moment_delivery, "deliver_moments", AsyncMock(return_value=rp.RuleResult())), \ + patch.object(lesson_situations, "for_act", AsyncMock(return_value=ARRIVALS[:1])), \ + patch("grimoire.services.record_deliveries.delivered_this_session", + AsyncMock(return_value={41})): + out = await moment_delivery.deliver_for_turn(1, record=False) + assert out["lesson_ids"] == [] and out["lesson_parts"] == [] + + +def test_a_lesson_is_offered_only_the_moments_a_door_brings_it_to(): + offered = {m["name"] for m in lesson_situations.lesson_moments()} + assert "reply.report" in offered and "work.deliver" in offered + assert offered.isdisjoint(lesson_situations.NO_LESSON_DOOR) + # Whether a reply asks is known only after it is written: refused, with + # the moment that does arrive in time named in the reason. + with pytest.raises(ValueError, match="reply.report"): + lesson_situations._values(["reply.ask"], []) + assert lesson_situations._values(["reply.report"], []) == [("moment", "reply.report")] + + def test_a_situation_reads_as_what_the_act_carries(): assert lesson_situations.describe("moment", "work.finish") == "moment `work.finish`" assert lesson_situations.describe("trigger", "path\tmigrations/**\t") == "path `migrations/**`" diff --git a/tests/test_reply_shape_turn.py b/tests/test_reply_shape_turn.py index 5c843dc5..5ba5df33 100644 --- a/tests/test_reply_shape_turn.py +++ b/tests/test_reply_shape_turn.py @@ -30,11 +30,11 @@ SESSION_START = ROOT / "plugin" / "hooks" / "grimoire_session_context.sh" # ── the route ──────────────────────────────────────────────────────────── -async def _retrieve(query_string, turn_context="CORE SHAPE"): +async def _retrieve(query_string, turn_context="CORE SHAPE", turn_value=None): from grimoire.routes import plugin as routes - turn = AsyncMock(return_value={"context": turn_context, "rule_ids": [173], - "shape_forms": {"core": reply_shapes.FULL}}) + turn = AsyncMock(return_value=turn_value or {"context": turn_context, "rule_ids": [173], + "shape_forms": {"core": reply_shapes.FULL}}) app = Quart(__name__) async with app.test_request_context("/api/plugin/retrieve", query_string=query_string): g.user = SimpleNamespace(id=7) @@ -57,6 +57,20 @@ async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back(): assert body["rule_ids"] == [11, 173] +async def test_a_lesson_recorded_for_the_reply_sits_between_the_turns_rules_and_its_shape(): + from grimoire.services import hook_payload as hp + + body, _turn = await _retrieve({"q": "write the report"}, turn_value={ + "context": "", "rule_ids": [173], "shape_forms": {"core": reply_shapes.FULL}, + "rule_parts": [hp.Part(text="TURN RULE", block="rules", ids={hp.RULE: (173,)})], + "lesson_parts": [hp.Part(text="LESSON LINE", block="lessons", ids={hp.NOTE: (41,)})], + "lesson_ids": [41], + "shape_parts": [hp.Part(text="CORE SHAPE", ids={hp.SHAPE: ("core",)})], + }) + ctx = body["context"] + assert ctx.index("TURN RULE") < ctx.index("LESSON LINE") < ctx.index("CORE SHAPE") < ctx.index("NOTES MENU") + + async def test_the_route_hands_the_ledger_and_the_rules_just_named_to_the_turn(): _body, turn = await _retrieve({"q": "x", "shapes_seen": "core,bogus", "exclude_rule_ids": "9", "held_rule_ids": "4"})