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
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:
@@ -0,0 +1,153 @@
|
||||
"""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)
|
||||
]
|
||||
@@ -16,7 +16,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from grimoire.services import moment_actions, reply_shapes
|
||||
from grimoire.services import hook_payload, moment_actions, reply_shapes
|
||||
from grimoire.services import retrieval_pipeline as rp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -147,6 +147,7 @@ _REACHED_BY_TURN = "the reply this turn will end with"
|
||||
async def deliver_for_turn(
|
||||
user_id: int, *, seen: frozenset[str] = frozenset(), project_id: int | None = None,
|
||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||
record: bool = True,
|
||||
) -> dict:
|
||||
"""What every turn carries before its reply is written.
|
||||
|
||||
@@ -157,10 +158,17 @@ async def deliver_for_turn(
|
||||
the reply exists, which is too late to shape it and is kept as the
|
||||
backstop; this is the point before.
|
||||
|
||||
Returns `{context, rule_ids, shape_forms}`. Fails open to the core alone,
|
||||
and the core itself never fails: it is a constant.
|
||||
Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts}`; the
|
||||
parts are for a door that fits its payload, which passes `record=False`
|
||||
and records the shapes it kept. Fails open to the core alone, and the
|
||||
core itself never fails: it is a constant.
|
||||
"""
|
||||
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
||||
shape_parts = [
|
||||
hook_payload.Part(text=block, ids={hook_payload.SHAPE: (key,)})
|
||||
for block, key in zip(blocks, forms, strict=False)
|
||||
]
|
||||
rule_parts: list[hook_payload.Part] = []
|
||||
rule_ids: list[int] = []
|
||||
try:
|
||||
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_TURN,
|
||||
@@ -170,10 +178,17 @@ async def deliver_for_turn(
|
||||
)
|
||||
blocks.extend(result.lines)
|
||||
rule_ids = result.rule_ids
|
||||
rule_parts = hook_payload.rule_parts(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
||||
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
||||
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
||||
return {"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms}
|
||||
if record:
|
||||
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
||||
return {
|
||||
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
||||
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
||||
}
|
||||
|
||||
|
||||
async def attach_moment_rules(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -185,139 +185,64 @@ def checkpoint_reason(checkpoint: dict) -> str:
|
||||
)
|
||||
|
||||
|
||||
# How much of a rule's statement a first mention carries. A statement past it
|
||||
# is cut at a sentence boundary and the line says where the rest is.
|
||||
STATEMENT_CHARS = 600
|
||||
# The register clause, the one place a line says how much force it carries.
|
||||
RULE_FORCE = "it binds"
|
||||
PREFERENCE_FORCE = "how this has been done before"
|
||||
|
||||
|
||||
def _statement_excerpt(rule) -> str:
|
||||
"""The rule's own words, up to STATEMENT_CHARS, cut where a sentence ends."""
|
||||
text = getattr(rule, "statement", "")
|
||||
text = " ".join(text.split()) if isinstance(text, str) else ""
|
||||
if len(text) <= STATEMENT_CHARS:
|
||||
return text
|
||||
cut = text[:STATEMENT_CHARS]
|
||||
stop = max(cut.rfind(". "), cut.rfind("; "), cut.rfind(": "))
|
||||
return (cut[: stop + 1] if stop > STATEMENT_CHARS // 2 else cut.rstrip()) + " …"
|
||||
|
||||
|
||||
def _rule_hint_line(
|
||||
rule, *, where: str, seen: bool, held: bool = False, compact: bool = False,
|
||||
) -> str:
|
||||
"""One rule hint line — both arms, both tails, both kinds.
|
||||
"""One rule line, for every arm and both kinds.
|
||||
|
||||
THREE INDEPENDENT AXES. `compact` joins `kind` and `seen`, and like them
|
||||
it reads none of the others: it says how much ROOM this line
|
||||
gets, which is a fact about its rank among today's hits rather than about
|
||||
the rule. A compact line is still a full claim that the rule may apply —
|
||||
it simply cites the rule instead of quoting its trigger. Crucially it
|
||||
still carries the `seen` tail, so the three axes stay genuinely
|
||||
independent: shortening a line must not decide what it says about whether
|
||||
the session is holding the rule.
|
||||
A first mention carries the rule itself — its title, why it is here, and
|
||||
its statement — so the reader has what the rule says without a second
|
||||
call. A repeat, or a lower-ranked line (`compact`), is a reference: the
|
||||
rule's number and title. Every line ends by saying where this session
|
||||
stands with the rule and where its full text is.
|
||||
|
||||
WHY THE LATER LINES ARE QUIETER. A full line runs ~143 tokens once the
|
||||
trigger is rendered, so five full lines cost ~568 tokens before every Bash
|
||||
call. Top-full-plus-references costs ~299 — about 2x a single full line,
|
||||
for four more rules. The token budget forbids four voices at full volume,
|
||||
not four voices.
|
||||
Written as statements about the rule, never as instructions to the
|
||||
reader: a line beside the work reports what applies, and the reader
|
||||
decides what to do with it.
|
||||
|
||||
The top hit keeps the full rendering because it is the one the ranker is
|
||||
most confident about, and a reader who acts on exactly one line should
|
||||
have acted on that one.
|
||||
|
||||
TWO INDEPENDENT AXES. `kind` decides the head, `seen` decides the tail,
|
||||
and neither reads the other. A preference and a rule differ in force; a
|
||||
repeat and a first surfacing differ in whether the session already holds
|
||||
the line. Those are unrelated facts, and keeping them unrelated in the
|
||||
code is what lets a new kind join without reopening the repeat question.
|
||||
|
||||
ONE FUNCTION BECAUSE THE TAILS MUST NOT DRIFT. The two arms phrase their
|
||||
heads differently ("may apply here" vs "may apply to this Bash call") and
|
||||
that difference is deliberate. Everything after it must not differ: an
|
||||
arm modelled on its sibling rather than sharing with it inherits its
|
||||
defects, and two copies of a two-branch string is how one branch gets
|
||||
fixed and the other does not.
|
||||
|
||||
WHY A REPEAT GETS A LINE AT ALL. Dropping a hit whose id is already on the
|
||||
session's exclusion ledger is correct only while the session still HOLDS
|
||||
what it was told, and a compaction breaks exactly that: the earlier
|
||||
injection is summarized away while the id stays on the ledger, so the rule
|
||||
would be absent from context AND unreachable for the rest of the session.
|
||||
The same holds, more slowly, for a session that simply stops holding a
|
||||
line it read an hour ago.
|
||||
|
||||
Only ONE CLAUSE of a first-surfacing line is false on a repeat — the claim that
|
||||
the rule is not in the session's loaded set. So only that clause changes.
|
||||
Title, trigger and pull pointer are identical either way, the statement is
|
||||
never injected either way, and a repeat therefore costs the same ~40 tokens
|
||||
as a first surfacing and no more.
|
||||
|
||||
DELIBERATELY NOT ASKING THE SESSION WHETHER IT HOLDS THE RULE. A model
|
||||
asked "do you still hold rule N?" will say yes, and the claim is
|
||||
unverifiable self-report about its own context. The answer is also not
|
||||
needed: the line is cheap enough to always emit and carries its own remedy
|
||||
in both branches. Removing the question removes the fragility rather than
|
||||
managing it.
|
||||
Three independent axes:
|
||||
- `kind` moves the noun and the register clause: a rule binds, a
|
||||
preference says how this has been done before.
|
||||
- the ledger moves the closing clause: first mention, named earlier and
|
||||
not opened (`seen`), or opened earlier (`held`). The server cannot know
|
||||
what the reader still holds, only what it named and what was opened.
|
||||
- `compact`, or any repeat, drops the statement and keeps the rest.
|
||||
"""
|
||||
trigger = (rule.when_to_apply or "").strip()
|
||||
preference = rule.kind == "preference"
|
||||
# KIND CHANGES THE HEAD; `seen` CHANGES THE TAIL. The two axes are
|
||||
# independent and stay that way, which is what lets the repeat logic above
|
||||
# survive a second kind without being reasoned about again: whether a
|
||||
# record is already on the ledger has nothing to do with how much force it
|
||||
# carries, so the seen-branch is shared verbatim.
|
||||
#
|
||||
# The noun is the whole of the visual difference, and that is deliberate.
|
||||
# A reader skimming an injected block gets one word to place the register \u2014
|
||||
# so it is the SECOND word that moves, and it is the word naming force.
|
||||
# Everything structural after it is identical, so the three kinds read as
|
||||
# one set rather than three formats (the lesson voice is written against
|
||||
# these two; they are one paragraph, not three).
|
||||
noun = "Preference" if preference else "Standing rule"
|
||||
# The only other place force is asserted. A rule's line tells the reader
|
||||
# not to dismiss it unread, because dismissing a rule unread is how the
|
||||
# thing it prevents happens. A preference makes no such claim: it says
|
||||
# where to find how this has been done, and following it is what keeps
|
||||
# things consistent rather than what keeps them correct.
|
||||
reason = (
|
||||
"for how this has been done before" if preference
|
||||
else "before deciding it does not apply"
|
||||
)
|
||||
# THREE STATES, BECAUSE TWO OF THEM MUST NOT BE TOLD THE SAME THING.
|
||||
#
|
||||
# `seen` means an arm NAMED this rule earlier. It does not mean the session
|
||||
# read it — the line is a teaser, and a teaser skimmed past leaves nothing
|
||||
# behind, least of all after a compaction summarises the turn it arrived
|
||||
# in. "You saw it earlier this session" would assert something about the
|
||||
# reader's context that the server has no way to know.
|
||||
#
|
||||
# `held` is the observable half: a PostToolUse hook watches for the
|
||||
# `get_rule` call itself, so this is a recorded EVENT rather than a claim.
|
||||
# That distinction is what keeps the non-goal above intact — the objection
|
||||
# was to asking a model about its own context, not to noticing what it did.
|
||||
#
|
||||
# The middle state is the honest one: named, not opened. It gets the full
|
||||
# invitation, because a session that skipped
|
||||
# the teaser is in almost the same position as one that never saw it.
|
||||
noun = "Preference" if preference else "Rule"
|
||||
force = PREFERENCE_FORCE if preference else RULE_FORCE
|
||||
if held:
|
||||
tail = (
|
||||
f"You opened it earlier this session; pull it with "
|
||||
f"get_rule({rule.id}) again if you no longer hold it."
|
||||
)
|
||||
state = "Opened earlier this session"
|
||||
elif seen:
|
||||
tail = (
|
||||
f"Mentioned earlier this session but not opened — read it with "
|
||||
f"get_rule({rule.id}) {reason}."
|
||||
)
|
||||
state = "Named earlier this session, not opened"
|
||||
else:
|
||||
tail = (
|
||||
f"Read it with get_rule({rule.id}) {reason}; it is not in this "
|
||||
"session's loaded set."
|
||||
)
|
||||
if compact:
|
||||
# THE TRIGGER GOES; THE TAIL STAYS. Only one of the two is expensive \u2014
|
||||
# a trigger runs 300-400 characters, the tail about 100 \u2014
|
||||
# so dropping the trigger is nearly the whole saving and dropping the
|
||||
# tail would be mostly sacrifice.
|
||||
#
|
||||
# It would also destroy the one thing a repeat line exists to say. The
|
||||
# tail is what tells a reader whether they were already told this and
|
||||
# may no longer be holding it, and that is the entire difference they
|
||||
# can act on; a reference with no tail reads as a first surfacing
|
||||
# whether it is one or not.
|
||||
# test_a_rule_the_session_already_holds_is_referenced_not_re_offered
|
||||
# pins this.
|
||||
return (
|
||||
f"Also \u2014 {noun.lower()} \u201c{rule.title}\u201d. {tail}"
|
||||
)
|
||||
state = "First mention this session"
|
||||
tail = f"{state}; full text: get_rule({rule.id})."
|
||||
statement = "" if (compact or seen or held) else _statement_excerpt(rule)
|
||||
if not statement:
|
||||
return f"Also relevant: {noun} {rule.id} \u201c{rule.title}\u201d ({force}). {tail}"
|
||||
return (
|
||||
f"{noun} that may apply {where} \u2014 \u201c{rule.title}\u201d"
|
||||
+ (f" ({trigger})" if trigger else "")
|
||||
+ f". {tail}"
|
||||
f"{noun} {rule.id} \u201c{rule.title}\u201d may apply {where}; {force}: "
|
||||
f"{statement} {tail}"
|
||||
)
|
||||
|
||||
|
||||
@@ -626,6 +551,13 @@ class RuleResult:
|
||||
|
||||
checkpoint: dict = field(default_factory=dict)
|
||||
|
||||
line_rule_ids: list[int] = field(default_factory=list)
|
||||
"""The rule behind each of `lines`, in order, when a caller added lines
|
||||
of its own after the arm's; empty means `shown_rule_ids` lines up."""
|
||||
|
||||
def rule_per_line(self) -> list[int]:
|
||||
return list(self.line_rule_ids or self.shown_rule_ids)
|
||||
|
||||
|
||||
# ── The stages ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ Settings UI all enumerate THIS table rather than hard-coding special cases.
|
||||
WHAT A FLOOR IS, AND WHAT IT IS NOT
|
||||
|
||||
It is not a relevance judgement. Relevance is decided by the reader, which is
|
||||
the only participant that can read a trigger against a situation — and the
|
||||
injected line says so out loud ("read it before deciding it does not apply").
|
||||
the only participant that can read a rule against a situation, which is why
|
||||
the injected line carries the rule's statement rather than a verdict.
|
||||
|
||||
A floor answers the cheaper question: *is this worth ranking at all*. `k` is
|
||||
what binds, and `k` is a BUDGET — how much of this surface's attention a
|
||||
|
||||
@@ -3,8 +3,10 @@ that history says about where a rule is worth delivering.
|
||||
|
||||
Three calls, one table (`rule_deliveries`):
|
||||
|
||||
- `record` — fire-and-forget, from the plugin doors that know the session:
|
||||
every line an arm put in front of it, full or repeat.
|
||||
- `record` — from the plugin doors that know the session: every line an arm
|
||||
rendered, full or repeat. Within a bound request the rows wait in a buffer
|
||||
until the door's payload is assembled, and `flush` writes only the lines
|
||||
that made it into the payload (`hook_payload.fit`).
|
||||
- `mark_opened` — the session opened a rule: the latest unopened delivery of
|
||||
it in that session gets the stamp. An open with no delivery behind it (the
|
||||
agent looked a rule up unprompted) stamps nothing.
|
||||
@@ -42,10 +44,27 @@ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
|
||||
# plugin routes so the arms several calls deep record against it without every
|
||||
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
|
||||
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
|
||||
# Rows rendered during the bound request, written by `flush`.
|
||||
_pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None)
|
||||
|
||||
|
||||
def bind_session(session_id: str | None) -> None:
|
||||
_session.set(_clean_session(session_id))
|
||||
_pending.set([])
|
||||
|
||||
|
||||
def flush(kept: set[int] | None = None) -> None:
|
||||
"""Write this request's buffered rows: those for rules in `kept`, or all
|
||||
of them when `kept` is None. Rows for a line the payload left out are
|
||||
dropped, since the session was never shown it."""
|
||||
rows = _pending.get()
|
||||
if not rows:
|
||||
return
|
||||
_pending.set([])
|
||||
if kept is not None:
|
||||
rows = [r for r in rows if r["rule_id"] in kept]
|
||||
if rows:
|
||||
spawn(_insert(rows), site="rule_delivery_write")
|
||||
|
||||
|
||||
def bound() -> bool:
|
||||
@@ -64,9 +83,9 @@ def record(
|
||||
user_id: int, session_id: str | None, source: str,
|
||||
lines: list[tuple[int, str, str]],
|
||||
) -> None:
|
||||
"""Record delivered lines: `(rule_id, at, form)` each. Fire-and-forget,
|
||||
and a no-op without a session, since an open could never be tied back.
|
||||
`session_id` None means the one bound for this request."""
|
||||
"""Record delivered lines: `(rule_id, at, form)` each. A no-op without a
|
||||
session, since an open could never be tied back. `session_id` None means
|
||||
the one bound for this request, whose rows wait for `flush`."""
|
||||
sid = _clean_session(_session.get() if session_id is None else session_id)
|
||||
if not sid or not lines:
|
||||
return
|
||||
@@ -79,6 +98,10 @@ def record(
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
logger.debug("rule delivery payload build failed", exc_info=True)
|
||||
return
|
||||
pending = _pending.get() if session_id is None else None
|
||||
if pending is not None:
|
||||
pending.extend(rows)
|
||||
return
|
||||
spawn(_insert(rows), site="rule_delivery_write")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user