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
+78 -15
View File
@@ -14,6 +14,7 @@ from quart import Blueprint, g, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.config import Config
from grimoire.services import hook_payload as hook_payload_svc
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import moment_delivery as moment_delivery_svc
from grimoire.services import plugin_context as plugin_ctx_svc
@@ -53,6 +54,17 @@ async def _bind_delivery_session() -> None:
rule_deliveries_svc.bind_session(sid)
@plugin_bp.after_request
async def _flush_deliveries(response):
"""Write any rule deliveries a door rendered without fitting a payload.
A door that fits its payload (`hook_payload.fit`) has already written the
lines it kept and dropped the rest, so this finds nothing left for it.
"""
rule_deliveries_svc.flush()
return response
def _int_list(raw: str | None) -> list[int]:
"""A comma-separated id list from the query string; non-ints dropped."""
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
@@ -155,10 +167,12 @@ async def autoinject_retrieve():
ledger is swept on compaction, which is how the
full core comes back after one.
THE TURN'S REPLY SHAPE COMES FIRST. Every turn ends
in a reply and this is the last point before it is written, so the core
shape and whatever is mounted on `reply.report` lead the payload. Fresh
shape keys come back as `shape_keys` for the ledger.
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.
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
@@ -199,12 +213,32 @@ async def autoinject_retrieve():
project_id=project_id,
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
held=frozenset(held_rule_ids),
record=False,
)
blocks = [b for b in (turn["context"], rules["context"], result["context"], proposal) if b]
result["context"] = "\n\n".join(blocks)
result["rule_ids"] = list(dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]))
result["shape_keys"] = [k for k, form in turn["shape_forms"].items()
if form == reply_shapes_svc.FULL]
# One payload, in the one order: the rules, then the reply shape, then
# the records menu, then the lesson-rule proposal, fitted to the budget.
turn_parts = (
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
else [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,
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
])
shapes = set(fitted.ids(hook_payload_svc.SHAPE))
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
await reply_shapes_svc.record_delivery(g.user.id, forms, via="turn")
result["context"] = fitted.context
result["note_ids"] = fitted.keep_only(hook_payload_svc.NOTE, result.get("note_ids"))
result["rule_ids"] = fitted.keep_only(
hook_payload_svc.RULE, dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]),
)
result["shape_keys"] = [k for k, form in forms.items() if form == reply_shapes_svc.FULL]
return jsonify(result)
@@ -282,6 +316,15 @@ async def pre_tool_rules():
cwd=(request.args.get("cwd") or "").strip(),
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
)
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
hook_payload_svc.RULE: "rule_ids", hook_payload_svc.RULING: "ruling_system_ids",
}))
result["context"] = fitted.context
result["rule_ids"] = fitted.keep_only(hook_payload_svc.RULE, result.get("rule_ids"))
if "ruling_system_ids" in result:
result["ruling_system_ids"] = fitted.keep_only(
hook_payload_svc.RULING, result["ruling_system_ids"],
)
return jsonify(result)
@@ -318,9 +361,10 @@ async def moment():
`moments` (the names reached). A lookup, not a ranked search: no
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
A moment that carries a default reply shape brings it too,
ahead of the rules: in full unless `shapes_seen` names it, then as its
reminder. `shape_keys` are the ones sent in full, for the hook's ledger.
A moment that carries a default reply shape brings it too, after the
rules: in full unless `shapes_seen` names it, then as its reminder. The
payload is fitted to the user's budget (`hook_payload`), and `shape_keys`
are the ones sent in full and kept, for the hook's ledger.
"""
event = await request.get_json(silent=True) or {}
tool = str(event.get("tool_name") or "").strip()
@@ -337,11 +381,17 @@ async def moment():
shapes, forms = moment_delivery_svc.shapes_for_act(
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
)
fitted = await hook_payload_svc.fit(g.user.id, [
*hook_payload_svc.rule_parts(result.lines, result.rule_per_line(), block="rules"),
*(hook_payload_svc.Part(text=block, ids={hook_payload_svc.SHAPE: (key,)})
for block, key in zip(shapes, forms, strict=False)),
])
kept_shapes = set(fitted.ids(hook_payload_svc.SHAPE))
forms = {k: f for k, f in forms.items() if k in kept_shapes}
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
context = "\n\n".join(b for b in ("\n\n".join(shapes), "\n".join(result.lines)) if b)
return jsonify({
"context": context,
"rule_ids": result.rule_ids,
"context": fitted.context,
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
"moments": [hit["moment"] for hit in reached],
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
})
@@ -537,6 +587,19 @@ async def write_path_prior_art():
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
)
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
hook_payload_svc.NOTE: "note_ids", hook_payload_svc.SYNC: "sync_note_ids",
hook_payload_svc.DERIVE: "derive_keys", hook_payload_svc.RULE: "rule_ids",
hook_payload_svc.RULING: "ruling_system_ids",
}))
result["context"] = fitted.context
for key, kind in (
("note_ids", hook_payload_svc.NOTE), ("sync_note_ids", hook_payload_svc.SYNC),
("derive_keys", hook_payload_svc.DERIVE), ("rule_ids", hook_payload_svc.RULE),
("ruling_system_ids", hook_payload_svc.RULING),
):
if key in result:
result[key] = fitted.keep_only(kind, result[key])
return jsonify(result)