"""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) ]