feat(7730): prior art and preferences speak only past a cue-swap gate, at most two lines
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Failing after 1m35s
CI & Build / integration (push) Successful in 2m1s
CI & Build / Build & push image (push) Skipped
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Failing after 1m35s
CI & Build / integration (push) Successful in 2m1s
CI & Build / Build & push image (push) Skipped
A record or preference found by resemblance alone is shown only when the message's score beats all but a set share (default 10%) of the user's own recent cues on that surface and project. The comparison set is the best_available_score already logged per call, so the bar rises with the store by construction and a fixed floor no longer decides. Too few cues to judge by is silence; the searches still run and calibrate the gate. - cue_gate: conformal bar, per (user, surface, project) with a user-wide fallback, cached five minutes; readout for Settings. - Notes arms (auto_inject, write_path) abstain unless the top line passes, show at most two lines, and hold slots to the same bar and cap. - Rule arms hold preference lines to the gate; rules are not gated. - retrieval_logs gains gate_bar and gate_kept (migration 0131). - Turns the harness wrote are refused server-side as well as in the plugin. - Settings: the rate field and a per-surface readout of bar and how often each surface spoke; GET /api/retrieval/gate. - Replay test: on unrelated cues a fixed bar tuned to 5% on a 32-record store fires ~97% on 2,048 records; the gate stays near 10% at both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,7 +35,7 @@ import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from grimoire.services import rule_order
|
||||
from grimoire.services import cue_gate, rule_order
|
||||
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -374,6 +374,12 @@ class RuleArm:
|
||||
kind: str | None = None
|
||||
"""Ask the ranker for one record kind only ("preference"), or every kind."""
|
||||
|
||||
gates_preferences: bool = False
|
||||
"""A preference this arm found by resemblance alone speaks only past the
|
||||
cue-swap gate (`cue_gate`). A rule binds, so a missed rule costs a mistake
|
||||
and is never gated here; a preference guides, and an unrelated one beside
|
||||
the work costs the reader's attention on every call."""
|
||||
|
||||
stop_only: bool = False
|
||||
"""The door shows nothing but the stop (the reply moment).
|
||||
|
||||
@@ -409,7 +415,7 @@ RULE_FLOOR_DEFAULT = 0.70
|
||||
# preference.
|
||||
PROMPT_RULE = RuleArm(
|
||||
"prompt_rule", band=False, compact_tail=False, checkpoint=False,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="prompt_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -424,7 +430,7 @@ PROMPT_RULE = RuleArm(
|
||||
)
|
||||
PRE_TOOL_RULE = RuleArm(
|
||||
"pre_tool_rule", band=True, compact_tail=True, checkpoint=True,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="pre_tool_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -439,7 +445,7 @@ PRE_TOOL_RULE = RuleArm(
|
||||
)
|
||||
WRITE_PATH_RULE = RuleArm(
|
||||
"write_path_rule", band=True, compact_tail=True, checkpoint=True,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="write_path_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -514,6 +520,9 @@ class RuleIO:
|
||||
retired: Callable[..., Any] | None = None
|
||||
"""`rule_deliveries.retired`: the repeats this session has already had
|
||||
its one reminder of. None retires nothing."""
|
||||
gate: Callable[..., Any] | None = None
|
||||
"""`cue_gate.gate_for`: the bar a line found by resemblance must reach.
|
||||
None, or a call returning None, leaves the arm ungated."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -578,9 +587,35 @@ def _telemetry_failed(source: str) -> None:
|
||||
logger.debug("retrieval telemetry failed for %s", source, exc_info=True)
|
||||
|
||||
|
||||
def _gate_preferences(kept: list, gate) -> list:
|
||||
"""`kept` without the preferences the gate turned away; rules untouched."""
|
||||
if gate is None:
|
||||
return kept
|
||||
return [(score, rule) for score, rule in kept
|
||||
if getattr(rule, "kind", None) != "preference" or gate.passes(score)]
|
||||
|
||||
|
||||
def _gate_fields(gate, kept: int) -> dict:
|
||||
"""The call row's record of the gate: its bar and how many lines passed."""
|
||||
if gate is None:
|
||||
return {}
|
||||
return {"gate_bar": gate.bar, "gate_kept": kept}
|
||||
|
||||
|
||||
async def _gate(io, user_id: int, source: str, project_id) -> Any:
|
||||
"""This arm's gate, or None when the door has none or it cannot be read."""
|
||||
if io.gate is None:
|
||||
return None
|
||||
try:
|
||||
return await io.gate(user_id, source, project_id or None)
|
||||
except Exception: # noqa: BLE001 - an unreadable gate leaves the arm as it was
|
||||
logger.debug("cue gate unreadable for %s", source, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def _ranked(
|
||||
io: RuleIO, moment: RuleMoment, *, source: str, floor: float, limit: int,
|
||||
band: bool = False, kind: str | None = None,
|
||||
band: bool = False, kind: str | None = None, gate=None,
|
||||
) -> tuple[list, list, list]:
|
||||
"""Search, band, split fresh from repeats, and log the call — every call.
|
||||
|
||||
@@ -610,6 +645,11 @@ async def _ranked(
|
||||
hits = [(score, rule) for score, rule in hits
|
||||
if getattr(rule, "kind", None) == kind]
|
||||
kept = _rule_band(hits) if band else hits
|
||||
# The gate is part of the cut, like the band: what it turns away is not
|
||||
# shown, so it is not in the row's results either.
|
||||
gated = _gate_preferences(kept, gate)
|
||||
passed = sum(1 for _s, r in gated if getattr(r, "kind", None) == "preference")
|
||||
kept = gated
|
||||
fresh = [(score, rule) for score, rule in kept if rule.id not in moment.exclude]
|
||||
try:
|
||||
io.record_retrieval(
|
||||
@@ -621,6 +661,7 @@ async def _ranked(
|
||||
best_available_id=report.get("best_available_id"),
|
||||
searched=bool(report.get("searched", True)),
|
||||
suppressed=len(hits) - len(fresh),
|
||||
**_gate_fields(gate, passed),
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
@@ -628,7 +669,7 @@ async def _ranked(
|
||||
|
||||
|
||||
async def _reserve_slot_for_preference(
|
||||
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float,
|
||||
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float, gate=None,
|
||||
) -> tuple[list, int | None]:
|
||||
"""Guarantee a preference one slot, if one clears the bar.
|
||||
|
||||
@@ -679,12 +720,12 @@ async def _reserve_slot_for_preference(
|
||||
# ITS OWN SOURCE, and both sides of the trade logged. A slot whose query
|
||||
# is not logged beside the hit it pushed out can never be judged against
|
||||
# what it displaced.
|
||||
found, _kept, _fresh = await _ranked(
|
||||
_found, kept, _fresh = await _ranked(
|
||||
io, moment, source=PREFERENCE_SLOT_SOURCE, floor=floor, limit=1,
|
||||
kind="preference",
|
||||
kind="preference", gate=gate,
|
||||
)
|
||||
seen = {rule.id for _s, rule in hits}
|
||||
slot = [(s, r) for s, r in found
|
||||
slot = [(s, r) for s, r in kept
|
||||
if r.kind == "preference" and r.id not in seen][:1]
|
||||
if not slot:
|
||||
return hits, None
|
||||
@@ -777,9 +818,13 @@ async def run_rule_arm(
|
||||
surfacing rows → checkpoint. Fails open to an empty result.
|
||||
"""
|
||||
try:
|
||||
gate = (
|
||||
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||
if arm.gates_preferences else None
|
||||
)
|
||||
_hits, kept, fresh = await _ranked(
|
||||
io, moment, source=arm.source, floor=floor, limit=budget,
|
||||
band=arm.band, kind=arm.kind,
|
||||
band=arm.band, kind=arm.kind, gate=gate,
|
||||
)
|
||||
shown = kept
|
||||
if arm.preference_slot:
|
||||
@@ -789,7 +834,7 @@ async def run_rule_arm(
|
||||
# preference ranked below that window is invisible to it while a
|
||||
# kind-filtered query finds it at once.
|
||||
shown, _slot_id = await _reserve_slot_for_preference(
|
||||
io, moment, shown, floor=floor,
|
||||
io, moment, shown, floor=floor, gate=gate,
|
||||
)
|
||||
# A repeat already reminded once this session says nothing more.
|
||||
gone = await _retired(io, moment, [rule for _s, rule in shown])
|
||||
@@ -1078,6 +1123,10 @@ class NoteArm:
|
||||
a record shared one-to-one with the operator."""
|
||||
|
||||
slots: tuple[NoteSlot, ...] = ()
|
||||
gated: bool = False
|
||||
"""Its lines speak only past the cue-swap gate (`cue_gate`), and at most
|
||||
`cue_gate.LINES` of them, slots included."""
|
||||
|
||||
withholds: bool = False
|
||||
"""A menu sits above this arm in the same response, and what it lists is
|
||||
kept out of the search (`exclude_ids`) — same-call duplication, which is a
|
||||
@@ -1089,6 +1138,7 @@ class NoteArm:
|
||||
|
||||
AUTO_INJECT = NoteArm(
|
||||
"auto_inject", surfaced_as="auto_inject", slots=(REUSE_SLOT, LESSON_SLOT),
|
||||
gated=True,
|
||||
tuning=Surface(
|
||||
name="auto_inject",
|
||||
floor_key="kb_autoinject_threshold",
|
||||
@@ -1111,7 +1161,7 @@ AUTO_INJECT = NoteArm(
|
||||
WRITE_PATH = NoteArm(
|
||||
"write_path", surfaced_as="write_path_semantic",
|
||||
note_type=("snippet", "note", LESSON_NOTE_TYPE), task_kind="issue",
|
||||
withholds=True,
|
||||
withholds=True, gated=True,
|
||||
tuning=Surface(
|
||||
name="write_path",
|
||||
floor_key="kb_writepath_threshold",
|
||||
@@ -1164,6 +1214,8 @@ class NoteIO:
|
||||
|
||||
record_retrieval: Callable[..., Any]
|
||||
record_surfaced: Callable[..., Any]
|
||||
gate: Callable[..., Any] | None = None
|
||||
"""`cue_gate.gate_for`, for a gated arm. None leaves the arm ungated."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -1209,6 +1261,9 @@ class NoteResult:
|
||||
slot_ids: dict = field(default_factory=dict)
|
||||
"""{slot source: the id it spent}."""
|
||||
|
||||
gate: Any = None
|
||||
"""The `cue_gate.Gate` this call's lines were held to, or None."""
|
||||
|
||||
|
||||
def _note_band(hits: list) -> list:
|
||||
"""The top hit, plus every hit within `_NOTE_BAND` of it.
|
||||
@@ -1225,7 +1280,7 @@ def _note_band(hits: list) -> list:
|
||||
|
||||
async def _reserve_note_slot(
|
||||
io: NoteIO, arm: NoteArm, slot: NoteSlot, moment: NoteMoment, menu: list,
|
||||
*, floor: float, budget: int, shown: set[int],
|
||||
*, floor: float, budget: int, shown: set[int], capped: bool = False,
|
||||
) -> tuple[list, int | None]:
|
||||
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
|
||||
|
||||
@@ -1254,6 +1309,10 @@ async def _reserve_note_slot(
|
||||
"""
|
||||
if any(_record_kind(n) in slot.kinds for _s, n in menu):
|
||||
return menu, None
|
||||
# Under the gate the budget is a ceiling for every line, so a slot that
|
||||
# only extends has no room once the menu is full.
|
||||
if capped and not slot.evicts and len(menu) >= budget:
|
||||
return menu, None
|
||||
|
||||
t0 = time.perf_counter()
|
||||
report: dict = {}
|
||||
@@ -1324,6 +1383,10 @@ async def run_note_arm(
|
||||
band → reserved slots → surfacing rows. Fails open to an empty result.
|
||||
"""
|
||||
try:
|
||||
gate = (
|
||||
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||
if arm.gated else None
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
report: dict = {}
|
||||
scored = moment.in_menu & moment.still_scored
|
||||
@@ -1355,6 +1418,12 @@ async def run_note_arm(
|
||||
(s, n) for s, n in hits
|
||||
if int(n.id) not in moment.seen and int(n.id) not in moment.named
|
||||
]
|
||||
# What the gate lets through, counted before the band and the slots so
|
||||
# the row says how often this arm spoke at all.
|
||||
passed = (
|
||||
min(cue_gate.LINES, sum(1 for s, _n in hits if gate.passes(s)))
|
||||
if gate is not None else 0
|
||||
)
|
||||
source = arm.source
|
||||
try:
|
||||
io.record_retrieval(
|
||||
@@ -1373,21 +1442,34 @@ async def run_note_arm(
|
||||
searched=bool(report.get("searched", True)),
|
||||
suppressed=len(hits) - len(fresh),
|
||||
duration_ms=(time.perf_counter() - t0) * 1000.0,
|
||||
**_gate_fields(gate, passed),
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
result = NoteResult(answered=answered, chunks=report.get("best_chunk") or {})
|
||||
result = NoteResult(
|
||||
answered=answered, chunks=report.get("best_chunk") or {}, gate=gate,
|
||||
)
|
||||
if not hits:
|
||||
return result
|
||||
|
||||
menu = _note_band(hits)
|
||||
if gate is not None:
|
||||
# ABSTAIN BY DEFAULT. A line speaks only past the gate, and at most
|
||||
# the top few do; a cue whose best match is ordinary for this
|
||||
# reader gets nothing, slots included — a slot's candidate scores
|
||||
# no higher than the best hit, so it could not pass either.
|
||||
menu = [(s, n) for s, n in menu if gate.passes(s)][:cue_gate.LINES]
|
||||
if not menu:
|
||||
return result
|
||||
floor = max(floor, gate.bar)
|
||||
budget = min(budget, cue_gate.LINES)
|
||||
# The slots are told about the named records as if already shown, so
|
||||
# a slot that picks one does not book a surfacing the lookup booked.
|
||||
shown = set(moment.seen | moment.named)
|
||||
for slot in arm.slots:
|
||||
menu, slot_id = await _reserve_note_slot(
|
||||
io, arm, slot, moment, menu, floor=floor, budget=budget,
|
||||
shown=shown,
|
||||
shown=shown, capped=gate is not None,
|
||||
)
|
||||
if slot_id is not None:
|
||||
result.slot_ids[slot.source] = slot_id
|
||||
|
||||
Reference in New Issue
Block a user