feat(7729): one assembler per hook — rule statements first, then the reply shape, then records, under a budget
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m47s
CI & Build / integration (push) Failing after 2m0s
CI & Build / Build & push image (push) Skipped

A rule line on first mention now carries the rule's own statement, written as
a statement about the rule ("Rule 11 … may apply here; it binds: …") rather
than an instruction to go read it; a repeat or lower-ranked line is a
reference ("Also relevant: Rule 11 …"). Every line ends with where the session
stands with the rule and get_rule(id) for the full text.

services/hook_payload.py fits every injecting door's payload (prompt,
pre-tool rules, moment, write path) to the user's budget: parts in one order,
kept while they fit, dropped whole otherwise. A dropped part's ids leave the
response lists, so the plugin ledgers mark only what was shown, and rule
deliveries are buffered per request and written only for kept lines.

Budget: Settings, default 4,500 characters (the full core reply shape is
2,343 and a full rule line up to ~750, so 3,000 would have crowded the shape
out of most turns), clamped to 1,000-7,500 — under the lower of the two
recorded hook caps (10,000 in the docs, 8,000 read from an installed build).
check_plugin asserts the ceiling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 19:04:58 -05:00
co-authored by Claude Opus 5.5
parent 97d79927b5
commit a16dee4080
20 changed files with 656 additions and 213 deletions
+18
View File
@@ -347,3 +347,21 @@ def _default_gate_bars():
with patch("grimoire.services.dedup._gate_setting", AsyncMock(side_effect=_default)):
yield
@pytest.fixture(autouse=True)
def _default_payload_budget(request):
"""Stub the settings read behind a hook payload's budget.
Every injecting plugin door fits its payload through `hook_payload.fit`,
which reads the user's budget; stubbed to the default so a unit test of a
door needs no database. The integration lane reads the real setting.
"""
if request.node.get_closest_marker("integration"):
yield
return
from grimoire.services import hook_payload
with patch.object(hook_payload, "payload_budget",
AsyncMock(return_value=hook_payload.DEFAULT_BUDGET)):
yield
+110
View File
@@ -0,0 +1,110 @@
"""A hook payload fitted to a budget: what is kept, in what order, what its
ids say, and which rule deliveries are recorded."""
import contextvars
from unittest.mock import MagicMock, patch
from grimoire.services import hook_payload as hp
from grimoire.services import rule_deliveries
from grimoire.services.hook_payload import Part
def _p(text, **kw):
return Part(text=text, **kw)
def test_parts_are_kept_in_order_and_the_payload_stays_within_the_budget():
parts = [_p("a" * 600, ids={hp.RULE: (1,)}), _p("b" * 600, ids={hp.RULE: (2,)}),
_p("c" * 600, ids={hp.NOTE: (9,)})]
fitted = hp.assemble(parts, 1300)
assert len(fitted.context) <= 1300
assert fitted.ids(hp.RULE) == [1, 2] and fitted.ids(hp.NOTE) == []
assert fitted.context.index("a") < fitted.context.index("b")
def test_a_part_that_does_not_fit_is_skipped_and_a_smaller_later_one_still_fits():
parts = [_p("r" * 500), _p("S" * 2000, ids={hp.SHAPE: ("core",)}), _p("n" * 300, ids={hp.NOTE: (4,)})]
fitted = hp.assemble(parts, 1000)
assert "S" not in fitted.context
assert fitted.ids(hp.SHAPE) == [] and fitted.ids(hp.NOTE) == [4]
def test_a_blocks_header_prints_once_before_its_first_kept_part_and_is_charged():
head = "> Possibly relevant:"
parts = [_p("> - #1 one", block="menu", header=head, ids={hp.NOTE: (1,)}),
_p("> - #2 two", block="menu", header=head, ids={hp.NOTE: (2,)})]
fitted = hp.assemble(parts, 5000)
assert fitted.context == f"{head}\n> - #1 one\n> - #2 two"
# The header counts against the part it rides: one that fits alone does
# not fit once its block's header is added.
long_head, line = "h" * 600, "x" * 500
tight = hp.assemble([_p(line, block="m", header=long_head, ids={hp.NOTE: (1,)})], 1000)
assert tight.context == "" and tight.ids(hp.NOTE) == []
def test_separate_blocks_are_separated_by_a_blank_line():
fitted = hp.assemble([_p("rule", block="rules"), _p("shape")], 5000)
assert fitted.context == "rule\n\nshape"
def test_keep_only_filters_a_response_list_to_what_was_shown():
fitted = hp.assemble([_p("x" * 400, ids={hp.RULE: (3,)}), _p("y" * 9000, ids={hp.RULE: (5,)})], 2000)
assert fitted.keep_only(hp.RULE, [5, 3, 7]) == [3]
def test_the_budget_is_bounded_under_the_hook_context_cap():
assert hp.HARD_MAX < 8_000
assert hp.clamp(50_000) == hp.HARD_MAX
assert hp.clamp(10) == hp.MIN_BUDGET
assert hp.clamp("not a number") == hp.DEFAULT_BUDGET
assert hp.MIN_BUDGET <= hp.DEFAULT_BUDGET <= hp.HARD_MAX
def test_a_result_without_parts_is_one_part_carrying_all_its_ids():
result = {"context": "whole", "rule_ids": [1, 2]}
parts = hp.parts_of(result, {hp.RULE: "rule_ids"})
assert parts == [Part(text="whole", ids={hp.RULE: (1, 2)})]
assert hp.parts_of({"context": ""}, {}) == []
own = {"context": "c", "parts": [_p("p")]}
assert hp.parts_of(own, {}) == [_p("p")] and "parts" not in own
def test_rule_parts_pair_each_line_with_its_rule():
parts = hp.rule_parts(["one", "two"], [11, 34], block="rules")
assert [p.ids[hp.RULE] for p in parts] == [(11,), (34,)]
# ── the delivery record ────────────────────────────────────────────────
# Each runs in a copy of the context, so the session it binds ends with it.
def test_a_bound_request_records_only_the_rule_lines_that_were_kept():
contextvars.copy_context().run(_bound_request_records_only_kept)
def _bound_request_records_only_kept():
spawned = MagicMock()
with patch.object(rule_deliveries, "spawn", spawned), \
patch.object(rule_deliveries, "_insert", lambda rows: rows):
rule_deliveries.bind_session("s-1")
rule_deliveries.record(1, None, "pre_tool_rule", [(11, "pre_tool_rule", "full"),
(34, "pre_tool_rule", "full")])
assert not spawned.called, "a bound request's rows wait for the payload"
rule_deliveries.flush({11})
rows = spawned.call_args.args[0]
assert [r["rule_id"] for r in rows] == [11]
spawned.reset_mock()
rule_deliveries.flush()
assert not spawned.called, "the buffer is spent once flushed"
def test_a_session_named_outright_records_at_once():
contextvars.copy_context().run(_named_session_records_at_once)
def _named_session_records_at_once():
spawned = MagicMock()
with patch.object(rule_deliveries, "spawn", spawned), \
patch.object(rule_deliveries, "_insert", lambda rows: rows):
rule_deliveries.bind_session("s-2")
rule_deliveries.record(1, "other", "x", [(5, "x", "full")])
assert spawned.called
+2 -2
View File
@@ -30,7 +30,7 @@ _CFG = {"enabled": True, "threshold": 0.55, "top_k": 3}
# The phrase the rule arms use. A lesson line that acquired it would be a rule
# with a different table, which is the thing this milestone exists to avoid.
_BINDING_PHRASE = "before deciding it does not apply"
_BINDING_PHRASE = "it binds"
async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
@@ -284,5 +284,5 @@ def test_the_surfacing_guards_can_fail():
assert [42] != []
# A header that borrowed the binding voice.
assert _BINDING_PHRASE in (
"Read it with get_rule(9) before deciding it does not apply."
"Rule 9 “CI polling” may apply here; it binds: CI is polled by the agent."
)
+2 -2
View File
@@ -462,7 +462,7 @@ async def test_an_unshaped_act_through_a_tool_carries_no_shape():
assert "reply_shape" not in out
async def test_the_route_puts_the_shape_ahead_of_the_rules_and_returns_its_key():
async def test_the_route_puts_the_rules_ahead_of_the_shape_and_returns_its_key():
from grimoire.routes import plugin as routes
deliver = AsyncMock(return_value=(ASK, rp.RuleResult(lines=["a line"], rule_ids=[5])))
@@ -473,7 +473,7 @@ async def test_the_route_puts_the_shape_ahead_of_the_rules_and_returns_its_key()
with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver):
body = await (await routes.moment.__wrapped__()).get_json()
assert body["shape_keys"] == ["asks"]
assert body["context"].index("Who decides what") < body["context"].index("a line")
assert body["context"].index("a line") < body["context"].index("Who decides what")
async with app.test_request_context("/api/plugin/moment", method="POST", json=event,
query_string={"shapes_seen": "asks"}):
+4 -4
View File
@@ -1,8 +1,8 @@
"""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 ahead of
everything else: in full the first time a session sees it, as its one-line
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.
@@ -49,10 +49,10 @@ async def _retrieve(query_string, turn_context="CORE SHAPE"):
return await resp.get_json(), turn
async def test_the_turns_shape_leads_the_payload_and_its_key_comes_back():
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("CORE SHAPE") < ctx.index("RULE LINE") < ctx.index("NOTES MENU")
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]
+12 -13
View File
@@ -107,15 +107,13 @@ def test_the_band_is_computed_from_scores_not_from_the_ledger():
assert [r.id for _s, r in kept] == [1, 2]
@pytest.mark.parametrize("seen", [False, True])
def test_the_leading_line_carries_the_trigger(seen):
"""Rank 0 gets the full rendering, on either tail."""
line = _rule_hint_line(
fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER),
where="to this Bash call", seen=seen, compact=False,
)
assert _TRIGGER in line
assert "get_rule(4)" in line
def test_the_leading_line_carries_the_statement_on_a_first_mention():
"""Rank 0 on a first mention says what the rule says; a repeat cites it."""
rule = fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER)
first = _rule_hint_line(rule, where="to this Bash call", seen=False)
assert rule.statement in first and "get_rule(4)" in first
again = _rule_hint_line(rule, where="to this Bash call", seen=True)
assert rule.statement not in again and "get_rule(4)" in again
@pytest.mark.parametrize("seen", [False, True])
@@ -161,12 +159,12 @@ def test_shortening_a_line_does_not_decide_what_it_says_about_holding():
assert len({fresh, named, held}) == 3, (
"the compact branch collapsed two holding states into one line"
)
assert "not in this session's loaded set" in fresh
assert "First mention" in fresh
assert "not opened" in named
assert "no longer hold it" in held
assert "Opened earlier" in held
# The claim that most needs to survive shortening: a line the session never
# opened must not imply it did, however little room the line was given.
assert "no longer hold it" not in named
assert "Opened earlier" not in named
def test_a_compact_line_is_materially_shorter_than_a_full_one():
@@ -188,7 +186,8 @@ def test_a_compact_line_is_materially_shorter_than_a_full_one():
"the next step feels like shipping it, and whenever an earlier merge "
"this session reads like standing permission for the next one."
)
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger)
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger,
statement=long_trigger)
full = _rule_hint_line(rule, where="here", seen=False, compact=False)
compact = _rule_hint_line(rule, where="here", seen=False, compact=True)
assert len(compact) * 2 < len(full)
+3 -3
View File
@@ -48,7 +48,7 @@ def _rule(rid=156, kind="rule"):
def test_a_rule_never_surfaced_is_offered_as_new():
line = _rule_hint_line(_rule(), where="here", seen=False, held=False)
assert "not in this session's loaded set" in line
assert "First mention this session" in line
def test_a_rule_named_but_not_opened_says_so_and_still_invites():
@@ -65,7 +65,7 @@ def test_a_rule_named_but_not_opened_says_so_and_still_invites():
def test_a_rule_the_session_opened_is_described_as_opened():
line = _rule_hint_line(_rule(), where="here", seen=True, held=True)
assert "opened it earlier" in line
assert "Opened earlier this session" in line
assert "get_rule(156)" in line
@@ -85,7 +85,7 @@ def test_held_outranks_seen_regardless_of_kind():
the two together is how one of them gets forgotten."""
for kind in ("rule", "preference"):
line = _rule_hint_line(_rule(kind=kind), where="here", seen=True, held=True)
assert "opened it earlier" in line
assert "Opened earlier this session" in line
# ── the recorder ───────────────────────────────────────────────────────────
+25 -26
View File
@@ -1149,14 +1149,14 @@ _HELD = fake_rule(
statement="Every wait on something that can fail to answer carries a deadline.",
when_to_apply="writing any call that crosses a process boundary",
)
_FRESH_TAIL = "not in this session's loaded set"
_FRESH_TAIL = "First mention this session"
# `seen` WITHOUT `held` is the middle state: an arm named this rule earlier,
# and the session never opened it. Every test below drives the arms with
# `exclude_rule_ids` alone — the naming ledger — so this is the tail they
# produce, and it must not claim the session read a teaser nobody opened.
_SEEN_TAIL = "Mentioned earlier this session but not opened"
_SEEN_TAIL = "Named earlier this session, not opened"
# The third state, reached only when the opened ledger names the rule too.
_HELD_TAIL = "You opened it earlier this session"
_HELD_TAIL = "Opened earlier this session"
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@@ -1235,8 +1235,8 @@ _PREF = fake_rule(
statement="Advance one investigative step per turn.",
when_to_apply="during hard debugging",
)
_RULE_FORCE = "before deciding it does not apply"
_PREF_FORCE = "for how this has been done before"
_RULE_FORCE = "it binds"
_PREF_FORCE = "how this has been done before"
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@@ -1251,7 +1251,7 @@ async def test_a_preference_does_not_speak_in_the_rules_voice(source, run):
"""
ctx = (await run([(0.81, _PREF)], MagicMock()))["context"]
assert "Preference that may apply" in ctx, (
assert "Preference 177" in ctx, (
f"{source} announced a preference as something else. The noun is the "
f"one word a skimming reader gets to place the register, so it is the "
f"word that has to move. Context was: {ctx!r}"
@@ -1297,7 +1297,7 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
)
# And the head still differs in the seen case — a repeat of a preference
# is still a preference.
assert "Preference that may apply" in pref_seen, (
assert "Preference 177" in pref_seen, (
f"{source} lost the preference register on a repeat, so a preference "
f"seen twice reads as a rule the second time"
)
@@ -1305,25 +1305,24 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@pytest.mark.asyncio
async def test_neither_tail_injects_the_rule_statement(source, run):
"""The budget, pinned on both branches.
async def test_a_first_mention_carries_the_statement_and_a_repeat_does_not(source, run):
"""What a line is for, pinned on both branches.
A reference costs the same ~40 tokens as a first surfacing precisely
because neither carries the statement. If a repeat ever starts inlining the
body "since we are re-showing it anyway", this arm stops being cheap enough
to always emit — and always emitting is the whole mechanism.
A first mention carries the rule's own words, so the reader has what it
says without a second call. A repeat is a reference: the session was
handed the statement already, and quoting it again on every call is the
cost this line is built to avoid.
"""
for excluded in ([], [156]):
ctx = (await run([(0.81, _HELD)], MagicMock(),
exclude_rule_ids=excluded))["context"]
assert _HELD.statement not in ctx, (
f"{source} inlined the rule statement (excluded={excluded!r}); the "
f"line carries title, trigger and a pull pointer and nothing more"
)
assert _HELD.title in ctx and "process boundary" in ctx, (
"the line dropped the title or the trigger — those are what let a "
"reader decide whether to pull without pulling"
)
fresh = (await run([(0.81, _HELD)], MagicMock()))["context"]
assert _HELD.statement in fresh, (
f"{source} named the rule without saying what it says"
)
repeat = (await run([(0.81, _HELD)], MagicMock(), exclude_rule_ids=[156]))["context"]
assert _HELD.statement not in repeat, (
f"{source} quoted the statement again on a repeat"
)
for ctx in (fresh, repeat):
assert _HELD.title in ctx and "get_rule(156)" in ctx
# ── What a reference IS in the telemetry: nothing new ──────────────────────
@@ -1449,7 +1448,7 @@ async def test_a_preference_that_lost_the_ranking_still_gets_a_line():
"dropped — which is the outcome with no symptom: the rules that won "
"are legitimate hits and nothing in the telemetry looks wrong"
)
assert "Preference that may apply" in out["context"]
assert "Preference 140" in out["context"]
@pytest.mark.asyncio
@@ -1466,7 +1465,7 @@ async def test_the_slot_is_not_spent_when_a_preference_already_placed():
"reserved line for a kind already represented is noise the general "
"ranking had already decided against"
)
assert out["context"].count("Preference that may apply") == 1
assert out["context"].count("Preference 140") == 1
@pytest.mark.asyncio
+1 -1
View File
@@ -76,7 +76,7 @@ async def test_a_matching_linked_lesson_brings_its_rule_in_rule_voice():
)
lines, ids = await _run(stack)
assert ids == [7]
assert lines[0].startswith("Standing rule")
assert lines[0].startswith("Rule ")
assert "Reached through lesson #41" in lines[0]
assert log.call_args.kwargs["source"] == "rule_via_lesson"
assert surfaced.call_args.kwargs == {"user_id": 1, "rule_ids": [7], "source": "rule_via_lesson"}