Files
FabledGrimoire/tests/test_reply_shape_turn.py
T
bvandeusenandClaude Opus 5.5 a3c4cc5921
CI & Build / Python lint (push) Successful in 1s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 2m28s
CI & Build / integration (push) Successful in 2m23s
CI & Build / Build & push image (push) Successful in 25s
fix(7716): the reply shape rides after the top two rule lines, so a compaction cannot push it out
A compaction sweeps the rule ledger as well as the shape ledger. On the
next prompt every rule the prompt arm reaches and every rule mounted on
reply.report comes back as a first mention with its statement (about 750
characters each), and the route placed all of them ahead of the shape. Six
fill the 4,500-character default budget, so the 2,343-character core was
left out on exactly the turn it is meant to return in full. Seen in a real
session: after 9 of 10 compactions the first prompt payload carried no
reply shape at all.

The prompt payload is now ordered as milestone 639 designed it: the first
two rule lines, the reply shape, the remaining rule lines, the reply's
lessons, the carried note, the records menu. Rules that do not fit stay off
the ledger and arrive on a later call.

The lesson-placement test now pins the lesson after the shape (a lesson
binds nothing; the shape is what the reply is written to). New test: six
full-length rule lines and the real core at the default budget; the shape
is kept and the later rules wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:03:46 -05:00

186 lines
8.7 KiB
Python

"""The core reply shape rides every turn.
Every turn ends in a reply, and the operator's prompt is the last point before
it is written, so the per-turn retrieval carries the core shape after the
rules and ahead of the records menu: in full the first time a session sees it, as its one-line
reminder after that, and in full again once a compaction has swept the
ledger. What is pinned here is that round trip across the shell/Python seam —
the route's order and keys, and the hook's ledger.
"""
from __future__ import annotations
import inspect
import json
import os
import subprocess
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from quart import Quart, g
from grimoire.services import reply_shapes
from tests.helpers import http_sink, need_tools
ROOT = Path(__file__).resolve().parents[1]
HOOK = ROOT / "plugin" / "hooks" / "grimoire_autoinject.sh"
SESSION_START = ROOT / "plugin" / "hooks" / "grimoire_session_context.sh"
# ── the route ────────────────────────────────────────────────────────────
async def _retrieve(query_string, turn_context="CORE SHAPE", turn_value=None):
from grimoire.routes import plugin as routes
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)
with patch.object(routes.plugin_ctx_svc, "build_prompt_rule_hint",
AsyncMock(return_value={"context": "RULE LINE", "rule_ids": [11],
"shown_rule_ids": [11]})), \
patch.object(routes.plugin_ctx_svc, "build_autoinject_hint",
AsyncMock(return_value={"context": "NOTES MENU", "note_ids": []})), \
patch.object(routes.moment_delivery_svc, "deliver_for_turn", turn):
resp = await inspect.unwrap(routes.autoinject_retrieve)()
return await resp.get_json(), turn
async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back():
body, _turn = await _retrieve({"q": "fix the flaky thing"})
ctx = body["context"]
assert ctx.index("RULE LINE") < ctx.index("CORE SHAPE") < ctx.index("NOTES MENU")
assert body["shape_keys"] == ["core"]
# Both arms' fresh rules reach the shared ledger.
assert body["rule_ids"] == [11, 173]
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={
"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("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():
_body, turn = await _retrieve({"q": "x", "shapes_seen": "core,bogus",
"exclude_rule_ids": "9", "held_rule_ids": "4"})
kw = turn.await_args.kwargs
assert kw["seen"] == frozenset({"core"})
# A rule the prompt arm just named is not quoted again by the turn.
assert kw["exclude"] == frozenset({9, 11})
assert kw["held"] == frozenset({4})
# ── the hook ─────────────────────────────────────────────────────────────
def _env(tmp_path, port):
return {"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}",
"GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path), "HOME": str(tmp_path)}
def _prompt(tmp_path, port, session="s-shape"):
need_tools("bash", "curl", "awk")
out = subprocess.run(
["bash", str(HOOK)],
input=json.dumps({"session_id": session, "cwd": str(tmp_path),
"prompt": "please fix the importer"}),
capture_output=True, text=True, env=_env(tmp_path, port), timeout=30,
)
assert out.returncode == 0, out.stderr
return out.stdout
def _compact(tmp_path, session="s-shape"):
out = subprocess.run(
["bash", str(SESSION_START)],
input=json.dumps({"session_id": session, "source": "compact"}),
capture_output=True, text=True,
env={"PATH": os.environ["PATH"], "HOME": str(tmp_path), "TMPDIR": str(tmp_path)},
timeout=60,
)
assert out.returncode == 0, out.stderr
REPLY = json.dumps({"context": "Reply shape · Every reply", "note_ids": [], "rule_ids": [],
"shape_keys": ["core"]}).encode()
def test_the_core_goes_whole_once_then_as_a_reminder_then_whole_after_a_compaction(tmp_path):
with http_sink(by_path={"/api/plugin/retrieve": REPLY}) as (port, seen):
out = _prompt(tmp_path, port)
_prompt(tmp_path, port)
_compact(tmp_path)
_prompt(tmp_path, port)
asks = [e for e in seen if e["_path"] == "/api/plugin/retrieve"]
assert len(asks) == 3
assert "shapes_seen" not in asks[0]
assert asks[1]["shapes_seen"] == ["core"]
# The compaction swept the ledger: the session no longer holds the shape.
assert "shapes_seen" not in asks[2]
assert "Every reply" in json.loads(out)["hookSpecificOutput"]["additionalContext"]
def test_the_route_reads_the_shape_ledger_the_hook_sends_and_returns_its_keys():
"""A contract across the seam: a renamed field fails silently. The hook
half (it sends `shapes_seen` and keeps the `shape_keys` it is given) is
the runtime test above; this is the route half."""
from grimoire.routes import plugin as routes
from tests.helpers import route_query_args
assert "shapes_seen" in route_query_args(routes.autoinject_retrieve)
assert '"shape_keys"' in inspect.getsource(routes.autoinject_retrieve)