diff --git a/src/grimoire/services/note_usage.py b/src/grimoire/services/note_usage.py index ba44dc99..5943a7bc 100644 --- a/src/grimoire/services/note_usage.py +++ b/src/grimoire/services/note_usage.py @@ -137,14 +137,18 @@ def record_surfaced( return _schedule(rows) # The same lines, against the session a plugin door is delivering to. A - # synced skill is not a line in front of the session, so it is left out. + # synced skill is not a line in front of the session, and a pointer is + # booked as `pointed` by the door that names it, so both are left out. if source not in _NOT_A_LINE: from grimoire.services import record_deliveries record_deliveries.record(user_id, note_ids, source) -# Surfacing sources that put nothing in front of the session as a line. -_NOT_A_LINE = frozenset({"process_skill_sync"}) +# Surfacing sources that put nothing in front of the session as a line: +# a synced skill, and the snippets beside an edited file, which are named by +# id in a pointer line (its door records them as `pointed`). Booking these +# as `pushed` too would count each delivery twice. +_NOT_A_LINE = frozenset({"process_skill_sync", "write_path_place"}) def record_pulled( diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index 7db40c5c..94be4dce 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -852,13 +852,12 @@ async def build_autoinject_hint( # What else cleared the floor, named by id only. Recorded as `pointed` # rather than surfaced: no line was spent on these, so an open that # follows says whether a pointer is enough. - pointer = record_kinds.pointer_line(pointers, POINTER_LEAD) + pointer = await _point(user_id, pointers, POINTER_LEAD, "auto_inject_pointer") if pointer: lines.append(pointer[0]) parts.append(hook_payload.Part( text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])}, )) - record_deliveries_svc.record(user_id, pointer[1], "auto_inject_pointer", way=POINTED) # A lookup, not a ranking, so it writes no retrieval_logs row — there is no # score or bar to tune — and its surfacings are its own source, which is @@ -877,6 +876,31 @@ async def build_autoinject_hint( } +async def _point( + user_id: int, pointers: dict[str, list[int]], lead: str, source: str, +) -> tuple[str, list[int]] | None: + """One pointer line, naming each record at most once a session, booked + under `source` as `pointed`; None when nothing is left to name. + + A pointer is for a record the session has not met. The plugin's own + ledger of what a session has seen holds only the records given a line, + so without this a record named by id comes back on every edit and every + message. A handoff note can then be named dozens of times in one session, + and a line that repeats on every turn stops being read. The server's + delivery ledger knows every record shown or pointed at in the session, + whatever the plugin version, so that is what is asked. Outside a plugin + request there is no session, nothing is left out, and nothing is booked. + """ + ids = [i for kind_ids in pointers.values() for i in kind_ids] + had = await record_deliveries_svc.delivered_this_session(user_id, ids) + if had: + pointers = {k: [i for i in v if i not in had] for k, v in pointers.items()} + pointer = record_kinds.pointer_line(pointers, lead) + if pointer: + record_deliveries_svc.record(user_id, pointer[1], source, way=POINTED) + return pointer + + async def _origins(notes, project_id: int | None) -> dict[int, str]: """{note id: project title} for the records here from a project other than the session's. Empty with no session project, where every record is @@ -1901,7 +1925,9 @@ async def build_write_path_hint( entry.append(f"> ↳ {passage}") parts[-1] = replace(parts[-1], text="\n".join(entry)) - place_pointer = record_kinds.pointer_line({"snippet": placed}, PLACE_POINTER_LEAD) + place_pointer = await _point( + user_id, {"snippet": placed}, PLACE_POINTER_LEAD, "write_path_place", + ) place_named: list[int] = [] if place_pointer: place_named = place_pointer[1] @@ -1910,15 +1936,13 @@ async def build_write_path_hint( text=place_pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(place_named)}, )) - record_deliveries_svc.record(user_id, place_named, "write_path_place", way=POINTED) - pointer = record_kinds.pointer_line(pointers, POINTER_LEAD) + pointer = await _point(user_id, pointers, POINTER_LEAD, "write_path_pointer") if pointer: lines.append(pointer[0]) parts.append(hook_payload.Part( text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])}, )) - record_deliveries_svc.record(user_id, pointer[1], "write_path_pointer", way=POINTED) if suggested: lines.append(_suggest_line(path, suggested)) diff --git a/tests/test_pointer_once_per_session.py b/tests/test_pointer_once_per_session.py new file mode 100644 index 00000000..d6c4a8ed --- /dev/null +++ b/tests/test_pointer_once_per_session.py @@ -0,0 +1,100 @@ +"""A pointer line names a record once a session, and is counted once. + +A pointer line names, by id, records that cleared the floor but got no line +of their own. The plugin's ledger of what a session has seen holds only the +records given a line, so the server asks its own delivery ledger which +records this session was already shown or pointed at, and leaves those out. +Without that a handoff note is named again on every edit and every message. + +And each delivery is booked once: the snippets beside an edited file are +named in a pointer line, so they are `pointed`, never also `pushed`. +""" +from __future__ import annotations + +import re +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from grimoire.services import note_usage +from grimoire.services import plugin_context as pc +from tests.helpers import fake_note + +# Six equally close notes: the menu shows its top three, and the rest are +# named in the pointer line. +HITS = [(0.8 - i * 0.001, fake_note(id=20 + i, title=f"a note {i}", note_type="note", user_id=1)) + for i in range(6)] + + +async def _pointer(ledger: set[int]) -> tuple[list[int], MagicMock]: + """The ids the auto-inject pointer line names, given what the session's + delivery ledger already holds, and the booking call.""" + calls: list[int] = [] + + async def _search(*_a, **kw): + calls.append(1) + return HITS if len(calls) == 1 else [] + + booked = MagicMock() + with patch.object(pc, "get_autoinject_config", + AsyncMock(return_value={"enabled": True, "threshold": 0.55, "top_k": 3})), \ + patch.object(pc, "semantic_search_notes", _search), \ + patch.object(pc, "superseded_ids", AsyncMock(return_value=set())), \ + patch.object(pc, "system_names_for", AsyncMock(return_value={})), \ + patch.object(pc, "record_retrieval", MagicMock()), \ + patch.object(pc, "record_surfaced", MagicMock()), \ + patch.object(pc.record_deliveries_svc, "delivered_this_session", + AsyncMock(return_value=set(ledger))), \ + patch.object(pc.record_deliveries_svc, "record", booked): + out = (await pc.build_autoinject_hint(1, "q", project_id=2))["context"] + line = next((ln for ln in out.splitlines() if pc.POINTER_LEAD in ln), "") + return [int(i) for i in re.findall(r"#(\d+)", line)], booked + + +@pytest.mark.asyncio +async def test_a_pointer_names_what_the_session_has_not_met(): + named, booked = await _pointer(set()) + assert named, "six close notes and a menu of three should leave a pointer line" + booked.assert_called_once() + assert list(booked.call_args.args[1]) == named + assert booked.call_args.args[2] == "auto_inject_pointer" + + +@pytest.mark.asyncio +async def test_a_record_already_pointed_at_this_session_is_not_named_again(): + first, _ = await _pointer(set()) + again, booked = await _pointer({first[0]}) + assert first[0] not in again + assert set(again) == set(first) - {first[0]} + # Only what the line names is booked, so the ledger stays a record of + # what the session actually saw. + assert first[0] not in booked.call_args.args[1] + + +@pytest.mark.asyncio +async def test_no_line_when_the_session_has_met_every_record_it_would_name(): + first, _ = await _pointer(set()) + again, booked = await _pointer(set(first)) + assert again == [] + booked.assert_not_called() + + +# --- each delivery booked once -------------------------------------------- + +def _booked_for(source: str) -> MagicMock: + booked = MagicMock() + with patch.object(note_usage, "_schedule"), \ + patch("grimoire.services.record_deliveries.record", booked): + note_usage.record_surfaced(user_id=1, note_ids=[7], source=source, project_id=2) + return booked + + +def test_snippets_beside_an_edited_file_are_not_also_booked_as_pushed(): + # Their door books them as `pointed` when it names them. + _booked_for("write_path_place").assert_not_called() + + +def test_a_line_shown_in_full_is_booked_as_pushed(): + # The same call books an ordinary line, so the test above is about the + # place arm and not about booking being switched off. + _booked_for("write_path_sync").assert_called_once()