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
+19
View File
@@ -425,3 +425,22 @@ def _ungated_doors(request):
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)), \
patch.object(plugin_context, "_routed_for", AsyncMock(return_value=frozenset())):
yield
@pytest.fixture(autouse=True)
def _no_lesson_situations(request):
"""Stub the lesson-situation lookups (`lesson_situations`) to find none.
Every moment door asks which lessons are recorded for the act, and the
plugin's tool filter asks which tools a lesson listens on; a unit test of
those doors has written no lessons. A test about situated lessons patches
its own answer. The integration lane runs the real queries.
"""
if request.node.get_closest_marker("integration"):
yield
return
from grimoire.services import lesson_situations
with patch.object(lesson_situations, "for_act", AsyncMock(return_value=[])), \
patch.object(lesson_situations, "reachable", AsyncMock(return_value=(set(), set()))):
yield
+102
View File
@@ -0,0 +1,102 @@
"""Real-Postgres tests for `lesson_situations`: a pass proposes when a lesson
applies, a person confirms or rejects it, and only a confirmed situation
delivers its lesson — at the moment it names, or on an act its trigger
matches, to a reader who may read the lesson."""
import uuid
import pytest
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.services import lesson_situations as svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
async def _world() -> dict:
tag = uuid.uuid4().hex[:8]
async with async_session() as s:
owner = await ensure_user(s, f"situations_owner_{tag}")
stranger = await ensure_user(s, f"situations_stranger_{tag}")
made = {
key: Note(user_id=owner.id, note_type="lesson", title=title, body="")
for key, title in (
("deploy", "A green build is not a running deploy"),
("migrate", "Migrations need their constraint in the same change"),
("plain", "Name things for a stranger"),
)
}
s.add_all(made.values())
await s.commit()
return {"owner": owner.id, "stranger": stranger.id,
**{k: int(n.id) for k, n in made.items()}}
async def test_a_proposal_waits_and_delivers_only_once_confirmed():
w = await _world()
out = await svc.propose(w["owner"], [
{"lesson_id": w["deploy"], "moments": ["work.deliver"], "why": "about shipping"},
{"lesson_id": w["migrate"], "triggers": [{"kind": "path", "pattern": "alembic/versions/*.py"}],
"why": "about writing migrations"},
{"lesson_id": w["plain"], "why": "about naming, whatever the act"},
{"lesson_id": w["plain"], "moments": ["not.a.moment"]},
])
assert out["written"] == 3 and len(out["refused"]) == 1
# Suggested rows deliver nothing.
assert await svc.for_act(w["owner"], ["work.deliver"]) == []
waiting = await svc.pending(w["owner"])
ids = {p["lesson_id"]: p["proposals"][0]["id"] for p in waiting["lessons"]}
assert set(ids) == {w["deploy"], w["migrate"]}, "a `none` answer waits on nobody"
await svc.judge(w["owner"], [{"id": ids[w["deploy"]], "verdict": "confirm"},
{"id": ids[w["migrate"]], "verdict": "confirm"}])
at_deliver = await svc.for_act(w["owner"], ["work.deliver"])
assert [a.lesson_id for a in at_deliver] == [w["deploy"]]
assert "moment `work.deliver`" in svc.line(at_deliver[0])
on_migration = await svc.for_act(
w["owner"], ["work.change"], tool="Edit",
tool_input={"file_path": "/repo/alembic/versions/0001_init.py"},
)
assert [a.lesson_id for a in on_migration] == [w["migrate"]]
assert await svc.for_act(w["owner"], ["work.change"], tool="Edit",
tool_input={"file_path": "/repo/src/app.py"}) == []
# Another user's lesson never reaches them.
assert await svc.for_act(w["stranger"], ["work.deliver"]) == []
# The session already has it: left out.
assert await svc.for_act(w["owner"], ["work.deliver"], exclude=frozenset({w["deploy"]})) == []
async def test_a_rejected_value_is_never_proposed_again_and_the_lesson_returns_to_the_queue():
w = await _world()
await svc.propose(w["owner"], [{"lesson_id": w["deploy"], "moments": ["work.finish"]}])
pid = (await svc.pending(w["owner"]))["lessons"][0]["proposals"][0]["id"]
await svc.judge(w["owner"], [{"id": pid, "verdict": "reject", "note": "too broad"}])
queue = await svc.to_situate(w["owner"], limit=100)
entry = next(item for item in queue["lessons"] if item["id"] == w["deploy"])
assert entry["rejected"] == [{"describes": "moment `work.finish`", "why": "too broad"}]
again = await svc.propose(w["owner"], [{"lesson_id": w["deploy"], "moments": ["work.finish"]}])
assert again == {"written": 0, "skipped": 1, "refused": []}
async def test_a_person_adds_and_takes_off_a_situation_and_the_counts_follow():
w = await _world()
await svc.propose(w["owner"], [{"lesson_id": w["plain"], "why": "none fits"}])
added = await svc.add(w["owner"], w["plain"], trigger={"kind": "command", "pattern": "git push"})
assert added["state"] == "confirmed" and added["source"] == "edit"
live = await svc.for_lesson(w["owner"], w["plain"])
assert [s["describes"] for s in live] == ["command `git push`"]
moments, tools = await svc.reachable(w["owner"])
assert "bash" in tools
counts = await svc.counts(w["owner"])
assert counts["situated"] == 1 and counts["none_fits"] == 0, "adding one clears `none`"
assert counts["unsituated"] == 2
await svc.remove(w["owner"], added["id"])
assert await svc.for_lesson(w["owner"], w["plain"]) == []
with pytest.raises(ValueError):
await svc.add(w["stranger"], w["plain"], moment="work.deliver")
+46
View File
@@ -0,0 +1,46 @@
"""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."""
from unittest.mock import AsyncMock, patch
import pytest
from grimoire.services import lesson_situations, moment_delivery
from grimoire.services import retrieval_pipeline as rp
ARRIVALS = [
lesson_situations.Arrival(41, "A green build is not a running deploy", "moment `work.deliver`"),
lesson_situations.Arrival(42, "Read the job log first", "command `git push`"),
]
@pytest.mark.asyncio
async def test_the_plugin_door_leaves_out_what_the_session_already_has():
with patch.object(lesson_situations, "for_act", AsyncMock(return_value=ARRIVALS)), \
patch("grimoire.services.record_deliveries.delivered_this_session",
AsyncMock(return_value={41})):
lines, ids = await moment_delivery.lessons_for_act(
1, [{"moment": "work.deliver"}], "Bash", {"command": "git push"},
)
assert ids == [42]
assert lines == [lesson_situations.line(ARRIVALS[1])]
assert "`get_lesson(42)`" in lines[0] and "command `git push`" in lines[0]
@pytest.mark.asyncio
async def test_an_mcp_reply_carries_the_lessons_for_its_act_every_time():
ledger = AsyncMock(return_value={41, 42})
with patch.object(moment_delivery, "deliver_for_act",
AsyncMock(return_value=([{"moment": "work.finish"}], rp.RuleResult()))), \
patch.object(moment_delivery, "shapes_for_act", lambda reached: ([], {})), \
patch.object(lesson_situations, "for_act", AsyncMock(return_value=ARRIVALS[:1])), \
patch("grimoire.services.record_deliveries.delivered_this_session", ledger):
data = await moment_delivery.attach_moment_rules(1, "update_task", {"status": "done"}, {})
assert data["moment_lessons"]["lesson_ids"] == [41]
assert data["moment_lessons"]["open_with"] == "get_lesson(id)"
ledger.assert_not_awaited()
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/**`"
+1 -1
View File
@@ -281,7 +281,7 @@ async def test_an_arm_searches_only_the_kinds_its_door_allows():
_r, _io_, calls = await _run(rp.AUTO_INJECT, lambda kw: [])
assert calls[0]["record_kinds"] is None
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [])
assert calls[0]["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
assert calls[0]["record_kinds"] == ["note", "snippet", "task:issue"]
# A user's own row replaces the default.
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"}))
assert calls[0]["record_kinds"] == ["snippet"]
+1 -1
View File
@@ -487,7 +487,7 @@ async def test_write_path_semantic_arm_asks_for_experience_not_just_snippets():
kw = search.await_args.kwargs
# An open to-do resembling the code answers nothing; an ISSUE carries a root
# cause and a NOTE carries durable knowledge. Only the todo is excluded.
assert kw["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
assert kw["record_kinds"] == ["note", "snippet", "task:issue"]
# Telemetry must not claim this was a notes-only retrieval any more.
assert rec.call_args.kwargs["is_task"] is None
+1 -1
View File
@@ -255,7 +255,7 @@ async def test_semantic_arm_is_snippet_only_and_browse_scoped():
# code shape. What
# stays out is the open to-do list, which resembles the code and answers
# nothing.
assert kwargs["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
assert kwargs["record_kinds"] == ["note", "snippet", "task:issue"]
# Nobody asked for this, so it must not reach a one-to-one direct share.
assert kwargs["scope"] == "browse"