A lesson recorded for reply.report reaches the turn before the reply (#7883) #232
@@ -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
|
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
|
is a confirmed instance of with their own moments and triggers (the
|
||||||
strongest hint at its situation), and values already `rejected` for it.
|
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)
|
return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset)
|
||||||
|
|
||||||
|
|||||||
@@ -392,14 +392,13 @@ async def judge_lesson_situations_route():
|
|||||||
@login_required
|
@login_required
|
||||||
async def lesson_situations_route(lesson_id: int):
|
async def lesson_situations_route(lesson_id: int):
|
||||||
"""A lesson's live situations and waiting proposals, with the moment
|
"""A lesson's live situations and waiting proposals, with the moment
|
||||||
catalog and trigger kinds its page offers for adding one."""
|
catalog and trigger kinds its page offers for adding one — the moments a
|
||||||
from grimoire.services import moments as moments_svc
|
lesson can arrive at, not every moment a rule can mount on."""
|
||||||
from grimoire.services import rule_triggers
|
from grimoire.services import rule_triggers
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"situations": await lesson_situations_svc.for_lesson(get_current_user_id(), lesson_id),
|
"situations": await lesson_situations_svc.for_lesson(get_current_user_id(), lesson_id),
|
||||||
"catalog": [{"name": m["name"], "means": m["means"]}
|
"catalog": lesson_situations_svc.lesson_moments(),
|
||||||
for m in moments_svc.catalog()["moments"]],
|
|
||||||
"trigger_kinds": list(rule_triggers.KINDS),
|
"trigger_kinds": list(rule_triggers.KINDS),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -227,8 +227,12 @@ async def autoinject_retrieve():
|
|||||||
# what the last turn left unjudged, then the records menu, fitted to the
|
# what the last turn left unjudged, then the records menu, fitted to the
|
||||||
# budget.
|
# budget.
|
||||||
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
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_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={
|
else [hook_payload_svc.Part(text=turn.get("context") or "", ids={
|
||||||
hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()),
|
hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()),
|
||||||
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
||||||
|
|||||||
@@ -21,8 +21,10 @@ THE STATES (models/lesson_situation.py):
|
|||||||
a lesson's situation directly (`add` / `remove`), which is a judgment too.
|
a lesson's situation directly (`add` / `remove`), which is a judgment too.
|
||||||
A rejected value is never proposed again.
|
A rejected value is never proposed again.
|
||||||
- DELIVERY. `for_act` returns the lessons whose confirmed moment this act
|
- DELIVERY. `for_act` returns the lessons whose confirmed moment this act
|
||||||
reached or whose confirmed trigger it matches. The plugin's door shows each
|
reached or whose confirmed trigger it matches. The plugin's doors show each
|
||||||
once per session.
|
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
|
ACL (services/access.py). Proposing, judging and editing change what a
|
||||||
lesson says about itself, so they need WRITE on the lesson
|
lesson says about itself, so they need WRITE on the lesson
|
||||||
@@ -58,6 +60,28 @@ SITUATIONS_MAX = 8
|
|||||||
_NOTE_CHARS = 600
|
_NOTE_CHARS = 600
|
||||||
_REMOVED_NOTE = "removed by an edit"
|
_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:
|
def trigger_value(trigger: triggers_svc.Trigger) -> str:
|
||||||
"""A trigger as one stored string, the form rule_field_judgments uses."""
|
"""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."""
|
"""(kind, value) pairs, validated and de-duplicated, or the first refusal."""
|
||||||
out: list[tuple[str, str]] = []
|
out: list[tuple[str, str]] = []
|
||||||
for name in moment_names or []:
|
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 []:
|
for raw in trigger_raw or []:
|
||||||
out.append((TRIGGER, trigger_value(triggers_svc.require_trigger(raw))))
|
out.append((TRIGGER, trigger_value(triggers_svc.require_trigger(raw))))
|
||||||
out = list(dict.fromkeys(out))
|
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,
|
"lessons": lessons,
|
||||||
"total": int(total),
|
"total": int(total),
|
||||||
"offset": int(offset or 0),
|
"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),
|
"trigger_kinds": list(triggers_svc.KINDS),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -217,15 +217,17 @@ async def deliver_for_turn(
|
|||||||
|
|
||||||
The core reply shape — in full once per session and again after a
|
The core reply shape — in full once per session and again after a
|
||||||
compaction (the ledger is swept then), otherwise its one-line reminder —
|
compaction (the ledger is swept then), otherwise its one-line reminder —
|
||||||
and the rules and preferences mounted on `reply.report`, under the same
|
the rules and preferences mounted on `reply.report`, under the same rule
|
||||||
rule ledger as every other arm. The Stop hook's reply moment fires after
|
ledger as every other arm, and the lessons recorded for `reply.report`,
|
||||||
the reply exists, which is too late to shape it and is kept as the
|
each once per session. The Stop hook's reply moment fires after the reply
|
||||||
backstop; this is the point before.
|
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
|
Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts,
|
||||||
parts are for a door that fits its payload, which passes `record=False`
|
lesson_parts, lesson_ids}`; the parts are for a door that fits its
|
||||||
and records the shapes it kept. Fails open to the core alone, and the
|
payload, which passes `record=False`, records the shapes it kept and
|
||||||
core itself never fails: it is a constant.
|
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)
|
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
||||||
shape_parts = [
|
shape_parts = [
|
||||||
@@ -247,11 +249,20 @@ async def deliver_for_turn(
|
|||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
||||||
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
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:
|
if record:
|
||||||
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
||||||
return {
|
return {
|
||||||
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
||||||
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
||||||
|
"lesson_parts": lesson_parts, "lesson_ids": lesson_ids,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""A situated lesson reaches the work through the moment doors: the plugin's
|
"""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,
|
act door and the turn's delivery before a reply show it once per session,
|
||||||
carries it every time its act happens."""
|
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
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -41,6 +42,41 @@ async def test_an_mcp_reply_carries_the_lessons_for_its_act_every_time():
|
|||||||
ledger.assert_not_awaited()
|
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():
|
def test_a_situation_reads_as_what_the_act_carries():
|
||||||
assert lesson_situations.describe("moment", "work.finish") == "moment `work.finish`"
|
assert lesson_situations.describe("moment", "work.finish") == "moment `work.finish`"
|
||||||
assert lesson_situations.describe("trigger", "path\tmigrations/**\t") == "path `migrations/**`"
|
assert lesson_situations.describe("trigger", "path\tmigrations/**\t") == "path `migrations/**`"
|
||||||
|
|||||||
@@ -30,10 +30,10 @@ SESSION_START = ROOT / "plugin" / "hooks" / "grimoire_session_context.sh"
|
|||||||
# ── the route ────────────────────────────────────────────────────────────
|
# ── 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
|
from grimoire.routes import plugin as routes
|
||||||
|
|
||||||
turn = AsyncMock(return_value={"context": turn_context, "rule_ids": [173],
|
turn = AsyncMock(return_value=turn_value or {"context": turn_context, "rule_ids": [173],
|
||||||
"shape_forms": {"core": reply_shapes.FULL}})
|
"shape_forms": {"core": reply_shapes.FULL}})
|
||||||
app = Quart(__name__)
|
app = Quart(__name__)
|
||||||
async with app.test_request_context("/api/plugin/retrieve", query_string=query_string):
|
async with app.test_request_context("/api/plugin/retrieve", query_string=query_string):
|
||||||
@@ -57,6 +57,20 @@ async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back():
|
|||||||
assert body["rule_ids"] == [11, 173]
|
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():
|
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",
|
_body, turn = await _retrieve({"q": "x", "shapes_seen": "core,bogus",
|
||||||
"exclude_rule_ids": "9", "held_rule_ids": "4"})
|
"exclude_rule_ids": "9", "held_rule_ids": "4"})
|
||||||
|
|||||||
Reference in New Issue
Block a user