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:
@@ -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
|
||||
|
||||
@@ -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(" <task-notification><task-id>x</task-id>")
|
||||
assert is_harness_turn("<command-name>/compact</command-name>")
|
||||
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, "<task-notification>done</task-notification>")
|
||||
assert out["context"] == "" and not search.called
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user