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
+88 -11
View File
@@ -17,9 +17,10 @@ from __future__ import annotations
import logging
import re
import textwrap
from dataclasses import replace
from grimoire.services import design_systems as design_systems_svc
from grimoire.services import hook_payload
from grimoire.services import knowledge as knowledge_svc
from grimoire.services import notes as notes_svc
from grimoire.services import projects as projects_svc
@@ -711,27 +712,37 @@ async def build_autoinject_hint(
lines: list[str] = []
note_ids: list[int] = []
# The same menu as parts, one per record, for a door that fits its payload
# to a budget (`hook_payload`): a block's header rides its first kept record.
parts: list[hook_payload.Part] = []
named_header = ""
# FIRST, because the operator said which record they meant and everything
# after this block is a guess at what else might bear on it. The header
# says these were found by NUMBER: the parser reads "with 4448" as a
# reference, and the reader is the one placed to notice it was a quantity.
if named:
lines.append(
named_header = (
"> Named in your message — the records with those numbers, looked "
"up by id rather than matched. Open any in full with `get_note(id)`; "
"a line marked `seen` is already in your context:"
)
lines.append(named_header)
for note in named:
nid = int(note.id)
note_ids.append(nid)
# The OPENING under the line, not a passage: nothing matched here, so
# there is no passage to keep, and what the reader needs is what the
# record IS — which is where a record says it.
lines.extend(menu_entry(
entry = menu_entry(
nid, kind=_record_kind(note),
name=_menu_name(note.title, note.note_type, note.data, note.body),
systems=systems.get(nid), seen=nid in already, stale=nid in stale,
shared_by=_shared_by(note), under=_named_opening(note.body),
)
lines.extend(entry)
parts.append(hook_payload.Part(
text="\n".join(entry), block="named", header=named_header,
ids={hook_payload.NOTE: (nid,)},
))
# "records", not "notes" — the menu can hold snippets, processes and tasks
@@ -740,6 +751,7 @@ async def build_autoinject_hint(
# A repeat is shown again with a marker rather than withheld, so the header
# says what the marker means, once, rather than each repeated line having
# to explain itself.
head_at = len(lines)
if kept:
lines.append(
"> Possibly relevant from your Grimoire records — open any in full with "
@@ -771,6 +783,7 @@ async def build_autoinject_hint(
"what you are doing and use your judgement — a lesson is not a "
"rule and binds nothing."
)
kept_header = "\n".join(lines[head_at:])
for score, note in kept:
nid = int(note.id)
@@ -789,11 +802,16 @@ async def build_autoinject_hint(
(chunks.get(nid) or {}).get("text"), name,
)
who = _shared_by(note)
lines.extend(menu_entry(
entry = menu_entry(
nid, kind=_record_kind(note), name=name, systems=systems.get(nid),
seen=nid in already, stale=nid in stale, score=score,
shared_by=f"{who}, treat as a suggestion" if who else "",
under=passage,
)
lines.extend(entry)
parts.append(hook_payload.Part(
text="\n".join(entry), block="kept", header=kept_header,
ids={hook_payload.NOTE: (nid,)},
))
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
@@ -818,7 +836,7 @@ async def build_autoinject_hint(
]
return {
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
"lesson_ids": lesson_ids,
"lesson_ids": lesson_ids, "parts": parts,
}
@@ -886,6 +904,7 @@ async def _rule_moment(
skip=set(moment.exclude) | set(result.shown_rule_ids),
held=set(moment.held), where=moment.where,
)
result.line_rule_ids = [*result.rule_per_line(), *ids]
result.lines.extend(lines)
result.rule_ids.extend(ids)
return result
@@ -919,7 +938,7 @@ async def build_prompt_rule_hint(
THE OUTPUT IS DELIBERATELY NOT QUOTED, where the notes menu is, and the
two share no header. A note line is a bare title and needs the menu's header to say what
it is doing there, while a rule line names itself in its opening words
("Standing rule that may apply…" / "Preference that may apply…"). Leaving
("Rule N …; it binds" / "Preference N …; how this has been done before"). Leaving
rules unquoted separates the two claims visually with no extra prose, and
matches how a rule line already renders on both act arms.
@@ -958,6 +977,9 @@ async def build_prompt_rule_hint(
if result.lines:
out["context"] = "\n".join(result.lines)
out["rule_ids"] = result.rule_ids
out["parts"] = hook_payload.rule_parts(
result.lines, result.rule_per_line(), block="rules",
)
# Every rule LINE the direct arm showed, repeats and the reserved
# slot included — for the soft-link recorder. Distinct
# from `rule_ids`, which is telemetry's fresh-only cut.
@@ -1581,6 +1603,7 @@ async def build_write_path_hint(
# The direct band, then a rule reached through a linked lesson,
# composed by `_rule_moment` exactly as the other two rule builders are.
rule_lines: list[str] = []
rule_line_ids: list[int] = []
rule_ids: list[int] = []
shown_rule_ids: list[int] = []
checkpoint: dict = {}
@@ -1597,6 +1620,7 @@ async def build_write_path_hint(
checkpoint_floor=cfg["checkpoint_threshold"],
)
rule_lines = result.lines
rule_line_ids = result.rule_per_line()
rule_ids.extend(result.rule_ids)
# Every rule line the band showed, repeats included — what the
# soft-link recorder pairs with this response's lessons.
@@ -1605,6 +1629,25 @@ async def build_write_path_hint(
except Exception:
logger.debug("write-path rule arm failed", exc_info=True)
# The payload as parts, for the door that fits it to a budget: the rules,
# then the rulings and design system that bind, then the prior art.
binding: list[hook_payload.Part] = []
if rulings["lines"]:
binding.append(hook_payload.Part(
text="\n".join(rulings["lines"]),
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
))
if design_text:
binding.append(hook_payload.Part(
text=design_text,
ids={hook_payload.DERIVE: (design_dedup,)} if design_dedup else {},
))
parts = [
*hook_payload.rule_parts(rule_lines, rule_line_ids, block="rules"),
*binding,
*(hook_payload.Part(text=line) for line in staleness),
]
if (not staleness and not synced and not menu and not suggested
and not divergence and not derive and not rule_lines):
if design_text or rulings["lines"]:
@@ -1613,6 +1656,7 @@ async def build_write_path_hint(
"context": "\n".join(rulings["lines"] + ([design_text] if design_text else [])),
"derive_keys": [design_dedup] if design_dedup else [],
"ruling_system_ids": rulings["system_ids"],
"parts": parts,
}
return empty
@@ -1639,12 +1683,13 @@ async def build_write_path_hint(
if design_text:
lines.append(design_text)
sync_note_ids: list[int] = []
sync_header = ""
if synced:
# The sync framing. Deliberately imperative about the record —
# the reuse claim ("start from this shape") is still implied by the
# title being right there, but the load-bearing sentence is the one no
# other surface says: keeping the record true is part of THIS edit.
lines.append(
sync_header = (
f"> Recorded in Grimoire AT `{path}` — the snippet(s) below record "
"the file this edit is changing. Reuse/extend the recorded shape "
"rather than writing a parallel one; and if this edit changes what "
@@ -1653,10 +1698,18 @@ async def build_write_path_hint(
"`verify_snippet(id, status=\"ok\", commit_sha=…)` after confirming "
"it still holds. Open with `get_snippet(id)` (shown once per session):"
)
lines.append(sync_header)
for item in synced:
sync_note_ids.append(int(item["id"]))
lines.append(_prior_art_line(item, "records this file", _owner_of(item)))
sid = int(item["id"])
sync_note_ids.append(sid)
line = _prior_art_line(item, "records this file", _owner_of(item))
lines.append(line)
parts.append(hook_payload.Part(
text=line, block="synced", header=sync_header,
ids={hook_payload.SYNC: (sid,), hook_payload.NOTE: (sid,)},
))
menu_at = len(lines)
if menu:
lines.append(
f"> Prior art already recorded in Grimoire for `{path}` — open one with "
@@ -1691,10 +1744,17 @@ async def build_write_path_hint(
"shape of a solution to adapt, not code to copy."
)
menu_header = "\n".join(lines[menu_at:])
note_ids: list[int] = list(sync_note_ids)
for item, marker, owner, foreign_lang in rendered:
note_ids.append(int(item["id"]))
lines.append(_prior_art_line(item, marker, owner, foreign_lang))
nid = int(item["id"])
note_ids.append(nid)
entry = [_prior_art_line(item, marker, owner, foreign_lang)]
lines.append(entry[0])
parts.append(hook_payload.Part(
text=entry[0], block="menu", header=menu_header,
ids={hook_payload.NOTE: (nid,)},
))
# Only the semantically-matched lines carry a passage. The records-this-
# file lines came from a LOCATION lookup — nothing was matched, so there
# is no matching passage and the body's opening would be a fabricated
@@ -1711,15 +1771,23 @@ async def build_write_path_hint(
)
if passage:
lines.append(f"> ↳ {passage}")
entry.append(f"> ↳ {passage}")
parts[-1] = replace(parts[-1], text="\n".join(entry))
if suggested:
lines.append(_suggest_line(path, suggested))
parts.append(hook_payload.Part(text=lines[-1]))
if divergence:
lines.append(_divergence_line(path, divergence))
parts.append(hook_payload.Part(text=lines[-1]))
if derive:
lines.append(_derive_line(path, derive))
parts.append(hook_payload.Part(
text=lines[-1], ids={hook_payload.DERIVE: tuple(d["key"] for d in derive)},
))
if copies:
lines.append(_copy_line(copies))
parts.append(hook_payload.Part(text=lines[-1]))
# Split by arm, which is the whole reason this table exists. The place arm
# carries no score and so has no home in retrieval_logs, yet it fires on
@@ -1758,9 +1826,11 @@ async def build_write_path_hint(
)
if proposal:
lines.append(proposal)
parts.append(hook_payload.Part(text=proposal))
return {
"context": "\n".join(lines),
"parts": parts,
"note_ids": note_ids,
"sync_note_ids": sync_note_ids,
"config": cfg,
@@ -1855,6 +1925,9 @@ async def build_tool_rule_hint(
out["context"] = "\n".join(result.lines)
out["rule_ids"] = result.rule_ids
out["checkpoint"] = result.checkpoint
out["parts"] = hook_payload.rule_parts(
result.lines, result.rule_per_line(), block="rules",
)
except Exception:
logger.debug("pre-tool rule arm failed", exc_info=True)
@@ -1875,6 +1948,10 @@ async def build_tool_rule_hint(
rulings["lines"] + ([out["context"]] if out.get("context") else [])
)
out["ruling_system_ids"] = rulings["system_ids"]
out["parts"] = [hook_payload.Part(
text="\n".join(rulings["lines"]),
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
), *out.get("parts", [])]
except Exception:
logger.debug("pre-tool rulings arm failed", exc_info=True)
return out