diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 06913dcc..0daaa564 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -133,6 +133,10 @@ async def session_context(): # The longest carried note a prompt takes: the shape check's note names a # few definitions and the call that lists the rest. _CARRY_CHARS = 3000 +# How many rule lines ride ahead of the reply shape in the prompt payload: the +# default budget (hook_payload.DEFAULT_BUDGET) is sized for the core shape +# beside two full rule lines. +_LEAD_RULES = 2 @plugin_bp.get("/retrieve") @@ -183,12 +187,15 @@ async def autoinject_retrieve(): nobody has judged (/shape-check's `note`). Fitted after the reply shape, before the records. - ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules - this prompt reaches and those mounted on `reply.report`, then the turn's - reply shape, then the records menu. Every turn ends in a reply and this - is the last point before it is written, so the shape rides every call; - what does not fit is left off the ledgers and can arrive on a later call. - Shape keys sent in full come back as `shape_keys` for the ledger. + ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the first + two of the rule lines this prompt reaches and those mounted on + `reply.report`, then the turn's reply shape, then the remaining rule + lines, the reply's lessons, and the records menu. Every turn ends in a + reply and this is the last point before it is written, so the shape rides + every call and is placed where a full set of rule statements cannot push + it out; what does not fit is left off the ledgers and can arrive on a + later call. Shape keys sent in full come back as `shape_keys` for the + ledger. TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query but nothing else: the notes menu can be disabled, thresholded and top-k'd @@ -196,10 +203,10 @@ async def autoinject_retrieve(): here rather than inside either builder so neither one's early return can silently suppress the other. - Rules come FIRST in the payload. A rule or preference governing the answer - is more consequential than a menu of things that might be worth reading, - and a reader who stops after the first block should have stopped after - the right one. + The top rules come FIRST in the payload. A rule or preference governing + the answer is more consequential than a menu of things that might be + worth reading, and a reader who stops after the first block should have + stopped after the right one. """ q = (request.args.get("q") or "").strip() project_id, _repo, _unbound = await _project_scope() @@ -224,24 +231,31 @@ async def autoinject_retrieve(): held=frozenset(held_rule_ids), record=False, ) - # One payload, in the one order: the rules, then the reply shape, then - # what the last turn left unjudged, then the records menu, fitted to the - # budget. + # One payload, in the one order, fitted to the budget: the top rule lines, + # the reply shape, the remaining rule lines, the lessons recorded for the + # reply, what the last turn left unjudged, then the records menu. + # + # The shape sits after only the first _LEAD_RULES lines. A compaction + # sweeps the rule ledger as well as the shape ledger, so every rule then + # comes back as a first mention with its statement: six of those fill the + # default budget on their own, and with every rule ahead of it the shape + # was left out on exactly the turn it is meant to return in full. 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.get("lesson_parts", []), *turn["shape_parts"]] - if "shape_parts" in turn - else [hook_payload_svc.Part(text=turn.get("context") or "", ids={ + prompt_rules = hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}) + if "shape_parts" in turn: + every_rule = [*prompt_rules, *turn["rule_parts"]] + lead = every_rule[:_LEAD_RULES] + ordered = [*lead, *turn["shape_parts"], *every_rule[_LEAD_RULES:], *turn.get("lesson_parts", [])] + else: + ordered = [*prompt_rules, 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 ()), })] - ) fitted = await hook_payload_svc.fit(g.user.id, [ - *hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}), - *turn_parts, + *ordered, *([hook_payload_svc.Part(text=carry)] if carry else []), *hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}), ]) diff --git a/tests/test_reply_shape_turn.py b/tests/test_reply_shape_turn.py index e3121333..2ad85bee 100644 --- a/tests/test_reply_shape_turn.py +++ b/tests/test_reply_shape_turn.py @@ -57,7 +57,8 @@ 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(): +async def test_a_lesson_recorded_for_the_reply_follows_its_shape(): + """A lesson binds nothing; the shape is what the reply is written to.""" from grimoire.services import hook_payload as hp body, _turn = await _retrieve({"q": "write the report"}, turn_value={ @@ -68,7 +69,49 @@ async def test_a_lesson_recorded_for_the_reply_sits_between_the_turns_rules_and_ "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") + assert ctx.index("TURN RULE") < ctx.index("CORE SHAPE") < ctx.index("LESSON LINE") < ctx.index("NOTES MENU") + + +async def test_the_full_shape_survives_a_turn_where_every_rule_is_a_first_mention(): + """After a compaction both ledgers are swept, so the prompt arm's rules and + those mounted on reply.report all return with their statements. Six of + them fill the default budget on their own; the shape still goes out in + full, and it is later rule lines that wait for a later call.""" + from grimoire.services import hook_payload as hp + + def long_rules(first_id, block_text): + lines = [f"{block_text} {first_id + i}: " + "x" * 700 for i in range(3)] + return hp.rule_parts(lines, [first_id + i for i in range(3)], block="rules") + + core = reply_shapes.core() + blocks, forms = reply_shapes.deliver([core], frozenset()) + from grimoire.routes import plugin as routes + + turn = AsyncMock(return_value={ + "context": "", "rule_ids": [201, 202, 203], "shape_forms": forms, + "rule_parts": long_rules(201, "TURN RULE"), + "shape_parts": [hp.Part(text=b, ids={hp.SHAPE: (k,)}) for b, k in zip(blocks, forms, strict=False)], + }) + app = Quart(__name__) + async with app.test_request_context("/api/plugin/retrieve", query_string={"q": "carry on"}): + g.user = SimpleNamespace(id=7) + with patch.object(routes.plugin_ctx_svc, "build_prompt_rule_hint", + AsyncMock(return_value={"context": "", "rule_ids": [101, 102, 103], + "parts": long_rules(101, "PROMPT RULE")})), \ + patch.object(routes.plugin_ctx_svc, "build_autoinject_hint", + AsyncMock(return_value={"context": "", "note_ids": []})), \ + patch.object(routes.moment_delivery_svc, "deliver_for_turn", turn), \ + patch.object(routes.hook_payload_svc, "payload_budget", + AsyncMock(return_value=hp.DEFAULT_BUDGET)): + body = await (await inspect.unwrap(routes.autoinject_retrieve)()).get_json() + + assert body["shape_keys"] == ["core"] + assert blocks[0] in body["context"] + assert len(body["context"]) <= hp.DEFAULT_BUDGET + # The top two rules still lead, and the rules that did not fit are left + # off the ledger so they can arrive on a later call. + assert body["context"].index("PROMPT RULE 101") < body["context"].index(blocks[0][:40]) + assert 101 in body["rule_ids"] and 203 not in body["rule_ids"] async def test_the_route_hands_the_ledger_and_the_rules_just_named_to_the_turn():