diff --git a/alembic/versions/0131_retrieval_gate.py b/alembic/versions/0131_retrieval_gate.py new file mode 100644 index 00000000..5c6645ef --- /dev/null +++ b/alembic/versions/0131_retrieval_gate.py @@ -0,0 +1,28 @@ +"""retrieval_logs records the cue-swap gate: its bar and how many lines passed + +Revision ID: 0131 +Revises: 0130 +Create Date: 2026-11-23 + +A gated surface shows a line found by resemblance only when its score beats +most of the user's own recent cues on that surface. Each call row keeps the +bar it was held to and how many lines reached it, so how often a surface +speaks can be read back, per surface, as the store grows. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0131" +down_revision = "0130" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column("retrieval_logs", sa.Column("gate_bar", sa.Float(), nullable=True)) + op.add_column("retrieval_logs", sa.Column("gate_kept", sa.Integer(), nullable=True)) + + +def downgrade() -> None: + op.drop_column("retrieval_logs", "gate_kept") + op.drop_column("retrieval_logs", "gate_bar") diff --git a/frontend/src/views/SettingsView.vue b/frontend/src/views/SettingsView.vue index 6395a855..bf022d45 100644 --- a/frontend/src/views/SettingsView.vue +++ b/frontend/src/views/SettingsView.vue @@ -174,6 +174,40 @@ const kbReplyRuleThreshold = ref("0.8"); const kbWritePathTopK = ref("3"); // The most one hook call may inject, in characters (hook_payload.DEFAULT_BUDGET). const kbHookBudget = ref("4500"); +// How often a record found by resemblance alone may speak, as a percent of +// cues that match nothing in particular (cue_gate.RATE_DEFAULT). +const kbCueGateRate = ref("10"); + +// GatedSurface — one row of /api/retrieval/gate. +interface GatedSurface { + surface: string; + gates: string; + bar: number | null; + sample: number; + calls: number; + fired: number; + days: number; + unreadable?: boolean; +} +const gatedSurfaces = ref([]); +const gateMinSample = ref(20); + +function gateSummary(g: GatedSurface): string { + if (g.unreadable) return "unreadable right now"; + const spoke = g.calls ? `spoke on ${g.fired} of ${g.calls} calls in ${g.days} days` : "no gated calls yet"; + if (g.bar === null) return `learning (${g.sample} of ${gateMinSample.value} cues), silent until then; ${spoke}`; + return `bar ${g.bar.toFixed(2)} from your last ${g.sample} cues; ${spoke}`; +} + +async function loadGate() { + try { + const res = await apiGet<{ surfaces: GatedSurface[]; min_sample: number }>("/api/retrieval/gate"); + gatedSurfaces.value = res.surfaces ?? []; + gateMinSample.value = res.min_sample ?? 20; + } catch { + gatedSurfaces.value = []; + } +} const kbRuleHintTopK = ref("5"); const kbToolRuleTopK = ref("5"); const kbPromptRuleTopK = ref("3"); @@ -391,6 +425,9 @@ async function saveKbInject() { // a hook's context past its cap only as a short preview. const budget = Math.min(7500, Math.max(1000, Math.floor(Number(kbHookBudget.value) || 4500))); kbHookBudget.value = String(budget); + // Clamped as the server clamps it (cue_gate.RATE_MIN / RATE_MAX). + const gateRate = Math.min(50, Math.max(1, Math.floor(Number(kbCueGateRate.value) || 10))); + kbCueGateRate.value = String(gateRate); kbRuleHintTopK.value = String(rhK); kbToolRuleTopK.value = String(trK); kbPromptRuleTopK.value = String(prK); @@ -440,6 +477,7 @@ async function saveKbInject() { // quietly tune back. kb_writepath_top_k: String(wpK), kb_hook_budget_chars: String(budget), + kb_cue_gate_rate: String(gateRate), kb_rulehint_top_k: String(rhK), kb_toolrule_top_k: String(trK), kb_promptrule_top_k: String(prK), @@ -461,6 +499,7 @@ async function saveKbInject() { // the operator is looking at it to confirm. await loadTuningHistory(); await loadSurfaces(); + await loadGate(); } catch { toastStore.show('Failed to save auto-inject settings', 'error'); } finally { @@ -867,6 +906,9 @@ onMounted(async () => { if (allSettings.kb_hook_budget_chars !== undefined) { kbHookBudget.value = allSettings.kb_hook_budget_chars; } + if (allSettings.kb_cue_gate_rate !== undefined) { + kbCueGateRate.value = allSettings.kb_cue_gate_rate; + } if (allSettings.kb_writepath_top_k !== undefined) { kbWritePathTopK.value = allSettings.kb_writepath_top_k; } else if (allSettings.kb_autoinject_top_k !== undefined) { @@ -889,6 +931,7 @@ onMounted(async () => { } await loadTuningHistory(); await loadSurfaces(); + await loadGate(); if (allSettings.kb_duplicate_threshold_snippet !== undefined) { kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet; } @@ -1664,7 +1707,7 @@ async function deleteUser(userId: number) { class="fs-input input" style="max-width: 8rem" /> -

Ceiling on titles surfaced at once (1–10).

+

How many records each prompt is ranked against (1–10); at most two are shown, and only past the resemblance gate below.

+
+ + +

+ A record or preference matched only by wording is shown when the message + resembles it better than all but this share of your recent messages did: + at most two lines, and none until {{ gateMinSample }} messages have been seen. +

+ +
", methods=["PUT"]) @login_required async def tune_surface_route(surface: str): diff --git a/src/grimoire/routes/settings.py b/src/grimoire/routes/settings.py index e59db1e2..7fe8e8da 100644 --- a/src/grimoire/routes/settings.py +++ b/src/grimoire/routes/settings.py @@ -95,6 +95,10 @@ async def update_settings_route(): if to_save: await set_settings_batch(uid, to_save) + # The gate caches its bar for a few minutes; a new rate takes at once. + from grimoire.services import cue_gate + if cue_gate.RATE_KEY in data: + cue_gate.forget(uid) settings = await get_all_settings(uid) return jsonify(_masked(settings)) diff --git a/src/grimoire/services/cue_gate.py b/src/grimoire/services/cue_gate.py new file mode 100644 index 00000000..464c4f1f --- /dev/null +++ b/src/grimoire/services/cue_gate.py @@ -0,0 +1,219 @@ +"""When a record found by resemblance alone may speak: the cue-swap gate. + +WHY A FIXED BAR CANNOT DO THIS + +Every message resembles something in a store of any size. The best score that +N unrelated records reach against a message keeps rising as N grows, so a +similarity bar that is quiet on a small store fires on nearly every message on +a large one: the bar measures the store, not the message. (*The Price of Scale +in Proactive Memory Recall*, arXiv 2610.34507: a cosine bar tuned to 5% false +alarms on 8 memories hit 84–100% at 2,048, and a cross-encoder fared no +better.) A floor tuned on one install says nothing about another, or about the +same install a year later. + +WHAT THE GATE ASKS INSTEAD + +Not "is this score high" but "is this message's best match unusual for this +reader". The comparison set is the best score each of the user's own recent +messages reached on the same surface and scope — already in `retrieval_logs` +as `best_available_score`, measured before any bar. A line may speak only when +its score beats all but `rate` of them: a conformal test whose null is the +user's other cues against (very nearly) the same store. Because the null is +drawn from the same store, the bar rises with the store by construction, and +on cues that match nothing in particular it fires at about `rate` however large +the store grows. + +The recent messages include relevant ones, so the comparison set runs high +and the gate errs toward silence. That is the intended direction: injected +retrieval has measured below no memory at all in three independent benchmarks, +so a missed line costs less than a wrong one, +and every record stays one `search` away. + +TOO FEW CUES TO JUDGE BY IS SILENCE. Until `MIN_SAMPLE` messages have been +searched on a surface, nothing found by resemblance is shown there. The +searches still run and are still logged, so the gate calibrates itself within +a session or so; records reached by number, path or moment are not gated. +""" +from __future__ import annotations + +import math +import time +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone + +from grimoire.services.settings import get_setting + +RATE_KEY = "kb_cue_gate_rate" +# Percent of cues a gated surface may speak on when they match nothing in +# particular. The paper's cue-swap gate fired on 6–8% against 57% for the +# deployed similarity bar; 10 sits just above it so a store whose cues are +# mostly relevant is not muted outright. +RATE_DEFAULT = 10 +RATE_MIN, RATE_MAX = 1, 50 + +# At most this many lines found by resemblance per call, whatever the arm's +# search width: the top one or two, and the reader asks for more. +LINES = 2 + +SAMPLE = 200 +MIN_SAMPLE = 20 +WINDOW_DAYS = 30 +_TTL_SECONDS = 300.0 + + +@dataclass(frozen=True) +class Gate: + """The bar one surface's lines must reach on this call.""" + + bar: float | None + """None when there are too few cues to judge by: nothing passes.""" + + sample: int + rate: int + scope: str = "project" + """"project" when the comparison set is this project's own cues, "all" + when there were too few and the user's cues everywhere stood in.""" + + def passes(self, score: float) -> bool: + return self.bar is not None and float(score) >= self.bar + + def to_dict(self) -> dict: + return {"bar": None if self.bar is None else round(self.bar, 4), + "sample": self.sample, "rate": self.rate, "scope": self.scope, + "calibrated": self.bar is not None} + + +OPEN = Gate(bar=-math.inf, sample=0, rate=100, scope="open") +"""Everything passes — for a caller that has no gate to apply.""" + + +def clamp_rate(raw) -> int: + try: + n = int(float(raw)) + except (TypeError, ValueError): + return RATE_DEFAULT + return max(RATE_MIN, min(RATE_MAX, n)) + + +def conformal_bar(null_scores, rate: int) -> float | None: + """The score a cue must reach to beat all but `rate`% of `null_scores`. + + With K cues sorted ascending, a score at or above the k-th, where + k = ceil((K + 1) * (1 - rate / 100)), has a conformal p-value of at most + `rate`%. None when K is too small for any score to get there. + """ + scores = sorted(float(s) for s in null_scores if s is not None) + k = math.ceil((len(scores) + 1) * (1 - rate / 100.0)) + if len(scores) < MIN_SAMPLE or k > len(scores) or k < 1: + return None + return scores[k - 1] + + +_cache: dict[tuple, tuple[float, Gate]] = {} + + +async def _null_scores(user_id: int, source: str, project_id: int | None, + *, any_project: bool) -> list[float]: + from sqlalchemy import select + + from grimoire.models import async_session + from grimoire.models.retrieval_log import RetrievalLog + + since = datetime.now(timezone.utc) - timedelta(days=WINDOW_DAYS) + stmt = ( + select(RetrievalLog.best_available_score) + .where( + RetrievalLog.source == source, + RetrievalLog.user_id == user_id, + RetrievalLog.created_at >= since, + RetrievalLog.best_available_score.isnot(None), + ) + .order_by(RetrievalLog.created_at.desc()) + .limit(SAMPLE) + ) + if not any_project: + stmt = stmt.where(RetrievalLog.project_id.is_not_distinct_from(project_id)) + async with async_session() as session: + return [float(s) for (s,) in (await session.execute(stmt)).all()] + + +async def gate_for(user_id: int, source: str, project_id: int | None) -> Gate: + """This surface's gate for this user and scope, cached for a few minutes. + + The comparison set moves by one cue per call, so re-reading it on every + call buys nothing: a bar five minutes old is the same bar. A read that + fails is a gate that cannot judge, which is silence. + """ + project_id = project_id or None + key = (user_id, source, project_id) + hit = _cache.get(key) + now = time.monotonic() + if hit and now - hit[0] < _TTL_SECONDS: + return hit[1] + try: + rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT))) + except Exception: # noqa: BLE001 - a settings read never costs the gate + rate = RATE_DEFAULT + try: + scores = await _null_scores(user_id, source, project_id, any_project=False) + scope = "project" + if len(scores) < MIN_SAMPLE and project_id is not None: + scores = await _null_scores(user_id, source, project_id, any_project=True) + scope = "all" + gate = Gate(bar=conformal_bar(scores, rate), sample=len(scores), + rate=rate, scope=scope) + except Exception: # noqa: BLE001 - an unreadable gate is a quiet one + gate = Gate(bar=None, sample=0, rate=rate, scope="unreadable") + _cache[key] = (now, gate) + return gate + + +def forget(user_id: int | None = None) -> None: + """Drop cached gates — after the rate setting changes, so it takes at once.""" + if user_id is None: + _cache.clear() + return + for key in [k for k in _cache if k[0] == user_id]: + _cache.pop(key, None) + + +async def readout(user_id: int, surfaces: list[tuple[str, str]], *, days: int = 7) -> list[dict]: + """Each gated surface as Settings shows it: the bar it holds lines to now, + from the user's cues on every project, and how often it spoke lately. + + `surfaces` is `(source, what it gates)` pairs. `fired` counts calls in the + last `days` where at least one line passed; `calls` every gated call. + """ + from sqlalchemy import func, select + + from grimoire.models import async_session + from grimoire.models.retrieval_log import RetrievalLog + + try: + rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT))) + except Exception: # noqa: BLE001 - a settings read never costs the readout + rate = RATE_DEFAULT + since = datetime.now(timezone.utc) - timedelta(days=days) + out: list[dict] = [] + for source, gates in surfaces: + row = {"surface": source, "gates": gates, "rate": rate, "bar": None, + "sample": 0, "calls": 0, "fired": 0, "days": days} + try: + scores = await _null_scores(user_id, source, None, any_project=True) + bar = conformal_bar(scores, rate) + row["bar"] = None if bar is None else round(bar, 4) + row["sample"] = len(scores) + async with async_session() as session: + calls, fired = (await session.execute( + select(func.count(), + func.count().filter(RetrievalLog.gate_kept > 0)) + .where(RetrievalLog.user_id == user_id, + RetrievalLog.source == source, + RetrievalLog.created_at >= since, + RetrievalLog.gate_kept.isnot(None)) + )).one() + row["calls"], row["fired"] = int(calls or 0), int(fired or 0) + except Exception: # noqa: BLE001 - one unreadable surface leaves the rest + row["unreadable"] = True + out.append(row) + return out diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index a41af078..2487d836 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -20,7 +20,7 @@ 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 cue_gate, 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 @@ -452,6 +452,22 @@ _NO_SUBJECT_WORDS = frozenset(""" """.split()) +# A TURN THE HARNESS WROTE. Claude Code delivers a background task's +# completion, a slash command's expansion and a local command's output as if +# the operator had typed them. None is a question about anything, so none is +# searched: the plugin skips them before calling, and the server refuses them +# too, for a plugin that predates the skip. +_HARNESS_OPENINGS = ( + "", "", "", "", "", + "", "", "", +) + + +def is_harness_turn(prompt: str) -> bool: + return (prompt or "").lstrip().startswith(_HARNESS_OPENINGS) + + def _has_subject(prompt: str) -> bool: """Does the operator's message name anything a record could be about? @@ -647,7 +663,7 @@ async def build_autoinject_hint( cfg = await get_autoinject_config(user_id) empty = {"context": "", "note_ids": [], "config": cfg} q = (query or "").strip() - if not cfg["enabled"] or not q: + if not cfg["enabled"] or not q or is_harness_turn(q): return empty # RECORDS NAMED BY NUMBER, read from the operator's own words before # the query is enriched: a number in the assistant's reply is not one the @@ -847,9 +863,15 @@ def _note_io() -> rp.NoteIO: search=semantic_search_notes, record_retrieval=record_retrieval, record_surfaced=record_surfaced, + gate=_gate_for, ) +async def _gate_for(user_id: int, source: str, project_id): + """`cue_gate.gate_for`, read at call time like the rest of the door's IO.""" + return await cue_gate.gate_for(user_id, source, project_id) + + async def _rules_via_lessons( user_id: int, query: str, *, project_id: int | None, skip: set[int], held: set[int], where: str, @@ -951,7 +973,7 @@ async def build_prompt_rule_hint( """ out: dict = {"context": "", "rule_ids": []} q = (query or "").strip() - if not q: + if not q or is_harness_turn(q): return out # The same enrichment the notes arm gets. A rule is meant to # arrive while the work it governs is under way, not once the operator @@ -1006,6 +1028,7 @@ def _rule_io() -> rp.RuleIO: history=rule_deliveries.history if bound else None, record_delivery=rule_deliveries.record if bound else None, retired=rule_deliveries.retired if bound else None, + gate=_gate_for, ) diff --git a/src/grimoire/services/retrieval_pipeline.py b/src/grimoire/services/retrieval_pipeline.py index 2bcd97b7..7dab287e 100644 --- a/src/grimoire/services/retrieval_pipeline.py +++ b/src/grimoire/services/retrieval_pipeline.py @@ -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 diff --git a/src/grimoire/services/retrieval_telemetry.py b/src/grimoire/services/retrieval_telemetry.py index 9b607ccc..3c5a6948 100644 --- a/src/grimoire/services/retrieval_telemetry.py +++ b/src/grimoire/services/retrieval_telemetry.py @@ -152,6 +152,8 @@ def _build_payload( suppressed: int | None = None, best_available: float | None = None, best_available_id: int | None = None, + gate_bar: float | None = None, + gate_kept: int | None = None, ) -> dict: """Reduce a retrieval call to a flat, JSON-safe RetrievalLog payload. @@ -200,6 +202,14 @@ def _build_payload( ), "result_ids": items, "duration_ms": (round(duration_ms, 2) if duration_ms is not None else None), + # The cue-swap gate, on a gated surface: the bar a line had to reach + # and how many did. Null bar with a count means the gate could not + # judge yet and nothing spoke; both null means the surface is ungated. + "gate_bar": ( + None if gate_bar is None or gate_bar == float("-inf") + else round(float(gate_bar), 5) + ), + "gate_kept": None if gate_kept is None else int(gate_kept), } @@ -239,6 +249,8 @@ def record_retrieval( best_available: float | None = None, best_available_id: int | None = None, searched: bool = True, + gate_bar: float | None = None, + gate_kept: int | None = None, ) -> None: """Fire-and-forget: record one retrieval call. @@ -292,6 +304,8 @@ def record_retrieval( suppressed=suppressed, best_available=best_available, best_available_id=best_available_id, + gate_bar=gate_bar, + gate_kept=gate_kept, ) except Exception: logger.debug("retrieval telemetry payload build failed", exc_info=True) diff --git a/tests/conftest.py b/tests/conftest.py index c3fc064c..0e0e2d30 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -365,3 +365,21 @@ def _default_payload_budget(request): with patch.object(hook_payload, "payload_budget", AsyncMock(return_value=hook_payload.DEFAULT_BUDGET)): yield + + +@pytest.fixture(autouse=True) +def _ungated_doors(request): + """Leave the plugin doors' cue-swap gate off unless a test asks for it. + + The gate reads the user's earlier cues from `retrieval_logs`, which a + test that is about something else has not written, so with it on every + door would abstain. A test of the gate marks itself `cue_gate`, or calls + `cue_gate` directly. + """ + if request.node.get_closest_marker("cue_gate"): + yield + return + from grimoire.services import plugin_context + + with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)): + yield diff --git a/tests/test_cue_gate.py b/tests/test_cue_gate.py new file mode 100644 index 00000000..257fc0f3 --- /dev/null +++ b/tests/test_cue_gate.py @@ -0,0 +1,181 @@ +"""The cue-swap gate: when a record found by resemblance alone may speak. + +The property it exists for is pinned by replay: on cues that match nothing in +particular, a fixed similarity bar fires more and more often as the store +grows, while the gate fires at about its rate on a small store and a large +one alike. Then the arms that take it: a notes menu abstains unless its top +line is unusual for this reader and shows at most two lines; a preference +found by resemblance is held to the gate while a rule is not. +""" +from __future__ import annotations + +import random +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from grimoire.services import cue_gate +from grimoire.services import retrieval_pipeline as rp +from grimoire.services.cue_gate import Gate, conformal_bar +from tests.helpers import fake_note + + +# ── the statistic ────────────────────────────────────────────────────────── + + +def test_too_few_cues_to_judge_by_is_no_bar(): + assert conformal_bar([0.5] * (cue_gate.MIN_SAMPLE - 1), 10) is None + assert Gate(bar=None, sample=3, rate=10).passes(0.99) is False + + +def test_the_bar_beats_all_but_the_rate_of_earlier_cues(): + scores = [i / 100 for i in range(100)] # 0.00 … 0.99 + # k = ceil(101 * 0.9) = 91, so the bar is the 91st smallest: 0.90. + assert conformal_bar(scores, 10) == pytest.approx(0.90) + assert conformal_bar(scores, 50) == pytest.approx(0.50) + + +def test_the_rate_setting_is_clamped(): + assert cue_gate.clamp_rate("0") == cue_gate.RATE_MIN + assert cue_gate.clamp_rate("90") == cue_gate.RATE_MAX + assert cue_gate.clamp_rate("x") == cue_gate.RATE_DEFAULT + + +def _best_of(store_size: int, rng: random.Random) -> float: + """The best score a cue that matches nothing reaches against a store: + the maximum of `store_size` unrelated resemblances.""" + return max(0.45 + 0.05 * rng.gauss(0, 1) for _ in range(store_size)) + + +def test_on_unrelated_cues_a_fixed_bar_fires_more_as_the_store_grows_and_the_gate_does_not(): + rng = random.Random(7) + small, large, calibration, trials, rate = 32, 2048, 200, 400, 10 + + def cues(n, count): + return [_best_of(n, rng) for _ in range(count)] + + # A fixed bar tuned to fire on 5% of unrelated cues against the small store. + tuned = sorted(cues(small, 1000))[949] + fired = {} + for n in (small, large): + bar = conformal_bar(cues(n, calibration), rate) + test = cues(n, trials) + fired[n] = ( + sum(s >= tuned for s in test) / trials, + sum(s >= bar for s in test) / trials, + ) + fixed_small, gate_small = fired[small] + fixed_large, gate_large = fired[large] + assert fixed_small < 0.10 and fixed_large > 0.80, fired + assert gate_small <= 0.16 and gate_large <= 0.16, fired + assert abs(gate_small - gate_large) < 0.08, fired + + +# ── the notes arm ────────────────────────────────────────────────────────── + + +def _note(nid, score): + return score, fake_note(id=nid, title=f"record {nid}", user_id=1) + + +def _note_io(hits, gate): + async def search(_uid, _q, **kw): + return [] if kw.get("note_type") else list(hits) + + return rp.NoteIO(search=search, record_retrieval=MagicMock(), + record_surfaced=MagicMock(), gate=AsyncMock(return_value=gate)) + + +async def _menu(hits, gate, budget=4): + io = _note_io(hits, gate) + result = await rp.run_note_arm( + rp.AUTO_INJECT, rp.NoteMoment(user_id=1, query="q", project_id=2), + floor=0.5, budget=budget, io=io, + ) + return result, io + + +@pytest.mark.asyncio +async def test_a_menu_speaks_only_past_the_gate_and_at_most_two_lines(): + hits = [_note(1, 0.86), _note(2, 0.85), _note(3, 0.84), _note(4, 0.83)] + result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10)) + assert [int(n.id) for _s, n in result.menu] == [1, 2] + (row,) = [c.kwargs for c in io.record_retrieval.call_args_list + if c.kwargs["source"] == "auto_inject"] + assert row["gate_bar"] == 0.80 and row["gate_kept"] == 2 + # The searched candidates are still the row's results: they are what the + # next call's comparison set and any floor review read. + assert len(row["results"]) == 4 + + +@pytest.mark.asyncio +async def test_a_cue_whose_best_match_is_ordinary_gets_nothing(): + hits = [_note(1, 0.79), _note(2, 0.75)] + result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10)) + assert result.menu == [] + io.record_surfaced.assert_not_called() + (row,) = [c.kwargs for c in io.record_retrieval.call_args_list] + assert row["gate_kept"] == 0 + + +@pytest.mark.asyncio +async def test_an_uncalibrated_gate_is_silence_and_no_gate_is_the_old_menu(): + hits = [_note(1, 0.95), _note(2, 0.90)] + quiet, _ = await _menu(hits, Gate(bar=None, sample=4, rate=10)) + assert quiet.menu == [] + ungated, _ = await _menu(hits, None) + assert [int(n.id) for _s, n in ungated.menu] == [1, 2] + + +# ── preferences on the rule arms ────────────────────────────────────────── + + +def _rule(rid, kind): + return SimpleNamespace(id=rid, title=f"{kind} {rid}", kind=kind, statement="Said plainly.", + when_to_apply="when", enforcement="inform", salience="normal") + + +@pytest.mark.asyncio +async def test_a_preference_found_by_resemblance_is_held_to_the_gate_and_a_rule_is_not(): + hits = [(0.78, _rule(1, "rule")), (0.77, _rule(2, "preference")), (0.92, _rule(3, "preference"))] + hits.sort(key=lambda h: -h[0]) + io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(), + record_rule_surfaced=MagicMock(), + gate=AsyncMock(return_value=Gate(bar=0.85, sample=200, rate=10))) + result = await rp.run_rule_arm( + rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"), + floor=0.5, budget=5, io=io, + ) + assert sorted(result.shown_rule_ids) == [1, 3] + row = io.record_retrieval.call_args_list[0].kwargs + assert row["gate_bar"] == 0.85 and row["gate_kept"] == 1 + + +def test_the_reply_backstop_takes_no_gate(): + assert rp.REPLY_RULE.gates_preferences is False + assert all(arm.gates_preferences for arm in (rp.PROMPT_RULE, rp.PRE_TOOL_RULE, rp.WRITE_PATH_RULE)) + assert rp.AUTO_INJECT.gated and rp.WRITE_PATH.gated + + +# ── turns the harness wrote ─────────────────────────────────────────────── + + +def test_a_turn_the_harness_wrote_is_not_searched(): + from grimoire.services.plugin_context import is_harness_turn + + assert is_harness_turn(" x") + assert is_harness_turn("/compact") + assert not is_harness_turn("merge it and redeploy") + + +@pytest.mark.asyncio +async def test_the_prompt_menu_refuses_a_harness_turn(monkeypatch): + from grimoire.services import plugin_context + + monkeypatch.setattr(plugin_context, "get_autoinject_config", AsyncMock( + return_value={"enabled": True, "threshold": 0.55, "top_k": 3})) + search = AsyncMock(return_value=[]) + monkeypatch.setattr(plugin_context, "semantic_search_notes", search) + out = await plugin_context.build_autoinject_hint(1, "done") + assert out["context"] == "" and not search.called diff --git a/tests/test_integration_cue_gate.py b/tests/test_integration_cue_gate.py new file mode 100644 index 00000000..d866d03c --- /dev/null +++ b/tests/test_integration_cue_gate.py @@ -0,0 +1,71 @@ +"""Real-Postgres tests for the cue-swap gate: its comparison set is the user's +own recent cues on one surface and scope, read from `retrieval_logs`.""" +import pytest +from sqlalchemy import delete + +from grimoire.models import async_session +from grimoire.models.retrieval_log import RetrievalLog +from grimoire.services import cue_gate +from tests.helpers import ensure_user + +pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")] + +SOURCE = "auto_inject" + + +async def _user() -> int: + async with async_session() as s: + user = await ensure_user(s, "cue_gate_owner") + uid = user.id + await s.commit() + await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid)) + await s.commit() + cue_gate.forget(uid) + return uid + + +async def _cues(uid, scores, *, project_id=None, source=SOURCE): + async with async_session() as s: + for score in scores: + s.add(RetrievalLog(user_id=uid, source=source, query="q", project_id=project_id, + result_count=0, result_ids=[], best_available_score=score)) + await s.commit() + + +async def test_the_bar_is_read_from_this_users_cues_on_this_surface_and_project(): + uid = await _user() + await _cues(uid, [i / 100 for i in range(100)], project_id=5) + # Another surface's cues and another project's do not move it. + await _cues(uid, [0.99] * 50, project_id=5, source="write_path") + await _cues(uid, [0.99] * 50, project_id=6) + gate = await cue_gate.gate_for(uid, SOURCE, 5) + assert gate.scope == "project" and gate.sample == 100 + assert gate.bar == pytest.approx(0.90) + assert gate.passes(0.91) and not gate.passes(0.89) + + +async def test_a_project_with_too_few_cues_borrows_the_users_cues_everywhere(): + uid = await _user() + await _cues(uid, [0.5] * 30, project_id=7) + await _cues(uid, [0.6] * 5, project_id=8) + gate = await cue_gate.gate_for(uid, SOURCE, 8) + assert gate.scope == "all" and gate.sample == 35 + + +async def test_with_too_few_cues_anywhere_nothing_passes(): + uid = await _user() + await _cues(uid, [0.5] * 5) + gate = await cue_gate.gate_for(uid, SOURCE, None) + assert gate.bar is None and not gate.passes(0.99) + + +async def test_the_readout_counts_how_often_a_surface_spoke(): + uid = await _user() + await _cues(uid, [0.5] * 25) + async with async_session() as s: + for kept in (0, 0, 2, 1): + s.add(RetrievalLog(user_id=uid, source=SOURCE, query="q", result_count=0, + result_ids=[], gate_bar=0.8, gate_kept=kept)) + await s.commit() + (row,) = await cue_gate.readout(uid, [(SOURCE, "records")]) + assert row["calls"] == 4 and row["fired"] == 2 and row["sample"] == 25