Files
FabledGrimoire/src/grimoire/services/hook_payload.py
T
bvandeusenandClaude Opus 5.5 a16dee4080
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
feat(7729): one assembler per hook — rule statements first, then the reply shape, then records, under a budget
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>
2026-11-22 19:04:58 -05:00

154 lines
5.2 KiB
Python

"""What one hook call puts in front of the session, fitted to a budget.
Every plugin door that injects context builds its payload as `Part`s in one
priority order: rules first, then the reply shape, then prior art and the
rest. `assemble` keeps parts in that order while they fit and leaves out
whole any that do not. A part's ids leave with it, so the plugin's ledgers
mark only what the session was actually shown and a trimmed record can still
arrive on a later call. `fit` is the one call a door makes: it reads the
user's budget, assembles, and records the rule deliveries that made it in.
Claude Code caps a hook's additional context: its docs give 10,000
characters, past which the model gets a 2,000-character preview it is not
asked to open, and an installed build has been read capping it at 8,000.
`HARD_MAX` sits under the lower figure whatever the setting says, with room
for the lines a hook adds on its own side.
"""
from __future__ import annotations
from dataclasses import dataclass, field
HARD_MAX = 7500
MIN_BUDGET = 1000
# Fits the full core reply shape (about 2,300 characters) beside two full rule
# lines (up to about 750 each) with room for a few records.
DEFAULT_BUDGET = 4500
BUDGET_KEY = "kb_hook_budget_chars"
# The id kinds a part can carry, each the source of one response list.
RULE = "rule"
SHAPE = "shape"
NOTE = "note"
SYNC = "sync"
DERIVE = "derive"
RULING = "ruling"
@dataclass(frozen=True)
class Part:
"""One unit the assembler keeps or drops whole.
Parts sharing a `block` print as consecutive lines, and the block's
`header` prints once, before its first kept part, and is charged to it.
A part with no block is a block of its own. Blocks are separated by a
blank line.
"""
text: str
block: str = ""
header: str = ""
ids: dict[str, tuple] = field(default_factory=dict)
@dataclass
class Fitted:
context: str = ""
kept: list[Part] = field(default_factory=list)
dropped: list[Part] = field(default_factory=list)
def ids(self, kind: str) -> list:
"""The ids of this kind on kept parts, in payload order."""
return list(dict.fromkeys(i for p in self.kept for i in p.ids.get(kind, ())))
def keep_only(self, kind: str, values) -> list:
"""`values` filtered to those a kept part carries, order preserved."""
kept = set(self.ids(kind))
return [v for v in (values or []) if v in kept]
def clamp(budget) -> int:
try:
n = int(budget)
except (TypeError, ValueError):
n = DEFAULT_BUDGET
return max(MIN_BUDGET, min(HARD_MAX, n))
async def payload_budget(user_id: int) -> int:
from grimoire.services.settings import get_setting
try:
return clamp(await get_setting(user_id, BUDGET_KEY, str(DEFAULT_BUDGET)))
except Exception: # noqa: BLE001 - a settings read never costs the payload
return DEFAULT_BUDGET
def assemble(parts, budget: int) -> Fitted:
"""Keep `parts` in order while the joined payload stays within `budget`.
A part that does not fit is skipped, not a stopping point: a smaller,
lower-priority part after it may still fit.
"""
budget = clamp(budget)
blocks: list[tuple[object, list[str]]] = []
started: set = set()
used = 0
out = Fitted()
for part in parts:
text = (part.text or "").strip("\n")
if not text.strip():
continue
key = part.block or id(part)
lines = [text]
if part.header and key not in started:
lines.insert(0, part.header)
joins_last = bool(blocks) and blocks[-1][0] == key
sep = 1 if joins_last else (2 if blocks else 0)
cost = sep + len("\n".join(lines))
if used + cost > budget:
out.dropped.append(part)
continue
used += cost
if joins_last:
blocks[-1][1].extend(lines)
else:
blocks.append((key, lines))
started.add(key)
out.kept.append(part)
out.context = "\n\n".join("\n".join(lines) for _key, lines in blocks)
return out
async def fit(user_id: int, parts) -> Fitted:
"""Assemble under this user's budget and record the rule lines delivered."""
from grimoire.services import rule_deliveries
fitted = assemble(list(parts), await payload_budget(user_id))
rule_deliveries.flush(set(fitted.ids(RULE)))
return fitted
def parts_of(result: dict, ids: dict[str, str]) -> list[Part]:
"""A builder result's parts, removed from it so it can be serialised.
A result that carries none is one part: its whole `context`, holding
every id its `ids` map names (`{kind: result key}`).
"""
parts = result.pop("parts", None)
if parts is not None:
return list(parts)
text = result.get("context") or ""
if not text:
return []
return [Part(text=text, ids={
kind: tuple(result.get(key) or ()) for kind, key in ids.items()
})]
def rule_parts(lines: list[str], rule_ids: list[int], *, block: str) -> list[Part]:
"""One part per rule line, each carrying the rule it names."""
return [
Part(text=line, block=block, ids={RULE: (rid,)} if rid else {})
for line, rid in zip(lines, list(rule_ids) + [0] * (len(lines) - len(rule_ids)), strict=False)
]