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