feat(7832): records reach an edit and a message by structure first; resemblance offers notes
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Failing after 12s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Failing after 1m39s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Skipped

The kind×moment table's first measured defaults (baseline note #7892):

- The edit door splits in two rows. work.change is what is recorded where
  the edit is (snippets beside the file, issues naming it or open in its
  area); work.change.similar is what the code resembles, notes by default.
  Issues and snippets no longer reach an edit by resemblance.
- Snippets recorded beside the file are named by id in an "Also recorded
  beside this file" pointer line instead of taking menu lines.
- The message door leaves lessons and issues out by default: a lesson
  arrives at its confirmed situation, an issue through its area or its id.
  Its lesson slot runs only for a user who turns lessons back on.
- The static context teaches the new pointer line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:17:29 -05:00
co-authored by Claude Opus 5.5
parent 07c4a716bd
commit 4c69f9c163
10 changed files with 175 additions and 97 deletions
+8 -5
View File
@@ -29,10 +29,11 @@ async def _user(name: str = "record_kinds_owner") -> int:
async def test_a_door_follows_its_default_until_the_user_changes_it():
uid = await _user()
assert await record_kinds.kinds_for(uid, "work.change") == record_kinds.DOORS["work.change"].default
await record_kinds.set_kinds(uid, "work.change", ["snippet", "task:issue"])
assert await record_kinds.kinds_for(uid, "work.change") == {"snippet", "task:issue"}
await record_kinds.set_kinds(uid, "work.change", ["snippet"])
assert await record_kinds.kinds_for(uid, "work.change") == {"snippet"}
# Another door is untouched.
assert await record_kinds.kinds_for(uid, "message") == frozenset(record_kinds.KINDS)
assert (await record_kinds.kinds_for(uid, "message")
== record_kinds.DOORS["message"].default)
table = await record_kinds.set_kinds(uid, "work.change", None)
row = next(d for d in table["doors"] if d["door"] == "work.change")
assert row["changed"] is False and row["kinds"] == row["default"]
@@ -51,7 +52,7 @@ async def test_an_unknown_door_or_kind_is_refused_and_nothing_is_stored():
await record_kinds.set_kinds(uid, "work.nowhere", ["snippet"])
with pytest.raises(ValueError, match="unknown kind"):
await record_kinds.set_kinds(uid, "message", ["snippet", "rule"])
assert await record_kinds.kinds_for(uid, "message") == frozenset(record_kinds.KINDS)
assert await record_kinds.kinds_for(uid, "message") == record_kinds.DOORS["message"].default
async def test_the_clause_matches_exactly_the_kinds_named():
@@ -88,6 +89,8 @@ async def test_each_cell_carries_the_lines_its_door_pushed_and_the_opens():
await s.commit()
table = await record_kinds.table(uid, days=7)
cells = {d["door"]: d["evidence"] for d in table["doors"]}
assert cells["work.change"] == {"snippet": {"delivered": 2, "opened": 1}}
# The search by resemblance on an edit has its own row.
assert cells["work.change.similar"] == {"snippet": {"delivered": 2, "opened": 1}}
assert cells["work.change"] == {}
assert cells["message"] == {"task:issue": {"delivered": 1, "opened": 0}}
assert table["evidence_failed"] is False
+32 -11
View File
@@ -3,11 +3,12 @@
Three decisions are guarded here, and each has a way of going quietly wrong
that these tests are shaped to catch rather than to describe:
WHICH ARM. The two note arms, and no new one. An arm that FILTERS kinds does
not merely outrank a kind it omits — it makes it unreachable, and nothing
reports an arm that never had the candidate. The write path filters;
the prompt menu does not, but is project-scoped, which for a kind whose whole
claim is that it transfers amounts to the same silence.
WHICH ARM. By default neither note arm offers a lesson by resemblance: a
lesson reaches the work through the situation confirmed for it
(`lesson_situations`). A user can turn lessons on at the message door in
the record-kinds table, and then the prompt menu reserves a slot for one,
looking beyond the bound project, since a lesson's claim is that it
transfers. The slot tests below run as that user.
WHOSE BUDGET. A reserved slot in the prompt menu, none on the write path.
The slot has to be falsifiable, so it logs under its own source from the
@@ -21,6 +22,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from grimoire.services import plugin_context as pc
from grimoire.services import record_kinds
from grimoire.services.lessons import LESSON_NOTE_TYPE
from tests.helpers import fake_lesson, fake_note, writepath_cfg
@@ -33,9 +35,14 @@ _CFG = {"enabled": True, "threshold": 0.55, "top_k": 3}
_BINDING_PHRASE = "it binds"
# A user who has turned every kind on at the message door, lessons included.
EVERY_KIND = frozenset(record_kinds.KINDS)
async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
exclude_ids=None, rec=None, surf=None):
"""Run the prompt menu with each query stubbed by the kinds it asks for."""
exclude_ids=None, rec=None, surf=None, kinds=EVERY_KIND):
"""Run the prompt menu with each query stubbed by the kinds it asks for.
`kinds` is the user's message door; None is the shipped default."""
calls: list[dict] = []
async def fake_search(*_a, **kw):
@@ -52,7 +59,10 @@ async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
patch.object(pc, "semantic_search_notes", AsyncMock(side_effect=fake_search)), \
patch.object(pc, "record_retrieval", rec or MagicMock()), \
patch.object(pc, "record_surfaced", surf or MagicMock()), \
patch.object(pc, "owner_names_for", AsyncMock(return_value={})):
patch.object(pc, "owner_names_for", AsyncMock(return_value={})), \
patch.object(record_kinds, "kinds_for", AsyncMock(
return_value=record_kinds.DOORS[record_kinds.MESSAGE].default
if kinds is None else kinds)):
out = await pc.build_autoinject_hint(
1, "two overlapping badges on the card", project_id=2,
exclude_ids=exclude_ids or [],
@@ -83,12 +93,24 @@ async def test_the_prompt_menu_looks_beyond_the_bound_project_for_a_lesson():
assert calls[0]["include_global_kinds"] is True
@pytest.mark.asyncio
async def test_the_prompt_menu_leaves_lessons_to_their_situation_by_default():
"""The shipped message door does not offer a lesson by resemblance: its
search leaves lessons out and the reserved lesson slot does not run."""
_out, calls = await _menu(
[(0.70, fake_note(id=1, user_id=1))],
lesson_hits=[(0.61, fake_lesson(id=42, user_id=1))], kinds=None,
)
assert LESSON_NOTE_TYPE not in calls[0]["record_kinds"]
assert _query_for_lessons(calls) is None
@pytest.mark.asyncio
async def test_the_write_path_leaves_lessons_to_their_situation():
"""An edit's words resemble a lesson far more often than the edit is its
situation, so the edit door's search by meaning leaves lessons out; a
lesson reaches an edit through a situation confirmed for it
(`lesson_situations`). The kinds the door does consider stay."""
(`lesson_situations`). By default that search considers notes only."""
search = AsyncMock(return_value=[])
with patch.object(pc, "get_writepath_config",
AsyncMock(return_value=writepath_cfg(threshold=0.6))), \
@@ -101,8 +123,7 @@ async def test_the_write_path_leaves_lessons_to_their_situation():
await pc.build_write_path_hint(1, "src/ui/Badge.vue", code="x" * 400)
kw = search.await_args.kwargs
assert LESSON_NOTE_TYPE not in kw["record_kinds"]
assert {"snippet", "note"} <= set(kw["record_kinds"])
assert kw["record_kinds"] == ["note"]
assert kw["include_global_kinds"] is True
+16 -7
View File
@@ -15,6 +15,7 @@ from unittest.mock import MagicMock
import pytest
from grimoire.services import record_kinds
from grimoire.services import retrieval_pipeline as rp
from grimoire.services.lessons import LESSON_NOTE_TYPE
from grimoire.services.retrieval_registry import FAN_OUT_SITES, POINTS
@@ -43,6 +44,10 @@ def _note(nid, score=None, **kw):
return (score, note) if score is not None else note
# Every kind on at a door, as a user may set it in the record-kinds table.
EVERY_KIND = frozenset(record_kinds.KINDS)
async def _run(arm, route, *, budget=3, **moment):
io, calls = _io(route)
result = await rp.run_note_arm(
@@ -193,8 +198,9 @@ async def test_reuse_evicts_the_last_line_and_the_lesson_extends():
main = [_note(1, 0.70), _note(2, 0.69), _note(3, 0.68)]
reuse = [_note(9, 0.60, note_type="snippet")]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)]
# A user who has turned lessons on at the message door (off by default).
result, io, calls = await _run(
rp.AUTO_INJECT, _routed(main, reuse, lesson), budget=3,
rp.AUTO_INJECT, _routed(main, reuse, lesson), budget=3, kinds=EVERY_KIND,
)
# Reuse took the last of three; the lesson was added as a fourth.
assert [int(n.id) for _s, n in result.menu] == [1, 2, 9, 42]
@@ -228,7 +234,7 @@ async def test_a_slot_spends_itself_on_a_repeat_without_booking_it_again():
main = [_note(1, 0.70)]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)]
result, io, _ = await _run(
rp.AUTO_INJECT, _routed(main, lesson=lesson), seen=frozenset({42}),
rp.AUTO_INJECT, _routed(main, lesson=lesson), seen=frozenset({42}), kinds=EVERY_KIND,
)
assert 42 in [int(n.id) for _s, n in result.menu]
assert not _rows(io.record_surfaced, "lesson_slot")
@@ -271,17 +277,20 @@ def test_the_pipelines_fan_out_sites_declare_every_notes_source():
def test_the_filters_say_whose_records_and_the_table_says_which_kinds():
for arm in (rp.AUTO_INJECT, rp.WRITE_PATH):
assert rp.note_search_filters(arm) == {"include_global_kinds": True, "scope": "browse"}
assert rp.AUTO_INJECT.door == "message" and rp.WRITE_PATH.door == "work.change"
assert rp.AUTO_INJECT.door == "message" and rp.WRITE_PATH.door == "work.change.similar"
@pytest.mark.asyncio
async def test_an_arm_searches_only_the_kinds_its_door_allows():
# The shipped defaults: the message door considers every kind, so its
# search is unfiltered; the write path narrows to its row.
# The shipped defaults: the message door leaves out the kinds that reach
# the work through their structure (lessons, issues); the write path's
# search by resemblance considers notes only.
_r, _io_, calls = await _run(rp.AUTO_INJECT, lambda kw: [])
assert calls[0]["record_kinds"] is None
assert "lesson" not in calls[0]["record_kinds"]
assert "task:issue" not in calls[0]["record_kinds"]
assert {"note", "snippet", "task:work"} <= set(calls[0]["record_kinds"])
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [])
assert calls[0]["record_kinds"] == ["note", "snippet", "task:issue"]
assert calls[0]["record_kinds"] == ["note"]
# A user's own row replaces the default.
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"}))
assert calls[0]["record_kinds"] == ["snippet"]
+9 -8
View File
@@ -165,17 +165,18 @@ async def test_no_ids_short_circuits_without_a_query():
@pytest.mark.parametrize(
"lookups, expected_source",
"lookups, expected_source, listed",
[
# A hit AT the exact file is the sync class; a hit from the
# directory query is the reuse-shaped place arm. Both are un-scored,
# and both must leave a usage trace under their own name.
([(1, "hit"), (2, "empty")], "write_path_sync"),
([(1, "empty"), (2, "hit")], "write_path_place"),
# A hit AT the exact file is the sync class, given a line; a hit from
# the directory query is the place arm, named by id in a pointer
# line. Both are un-scored, and both must leave a usage trace under
# their own name.
([(1, "hit"), (2, "empty")], "write_path_sync", [42]),
([(1, "empty"), (2, "hit")], "write_path_place", []),
],
ids=["at-the-file", "nearby"],
)
async def test_unscored_location_arms_are_recorded(lookups, expected_source):
async def test_unscored_location_arms_are_recorded(lookups, expected_source, listed):
"""The location arms carry no score, so they have no home in retrieval_logs
— without a usage row they would surface snippets while leaving no trace
anywhere. Asserted per class."""
@@ -205,7 +206,7 @@ async def test_unscored_location_arms_are_recorded(lookups, expected_source):
1, "src/a.py", code="def f(): pass"
)
assert out["note_ids"] == [42]
assert out["note_ids"] == listed
sources = {c.kwargs["source"] for c in surfaced.call_args_list}
assert expected_source in sources
+4 -2
View File
@@ -89,9 +89,11 @@ async def test_build_autoinject_hint_titles_only_with_margin_gate():
assert "↳" not in out["context"]
# Telemetry fired for BOTH retrievals this path runs: the scored menu and
# the reuse-slot query competing against it. The hit the slot displaces is
# in retrieval_logs, so the query that displaced it must be too.
# in retrieval_logs, so the query that displaced it must be too. The
# lesson slot does not run: the shipped message door leaves lessons to
# their situation.
sources = [c.kwargs["source"] for c in rec.call_args_list]
assert sources == ["auto_inject", "reuse_slot", "lesson_slot"]
assert sources == ["auto_inject", "reuse_slot"]
@pytest.mark.asyncio
+19 -27
View File
@@ -207,7 +207,10 @@ async def test_directory_is_only_consulted_when_the_file_leaves_room():
@pytest.mark.asyncio
async def test_directory_hits_are_marked_nearby_not_here():
async def test_a_snippet_beside_the_file_is_named_by_id_not_given_a_line():
"""A snippet recorded in the same folder is offered for where it sits, so
it is named in one pointer line that says so, with the call that opens
it, and takes no line or budget from the menu."""
from grimoire.services import plugin_context as pc
async def _listing(uid, **kw):
@@ -221,7 +224,10 @@ async def test_directory_hits_are_marked_nearby_not_here():
patch.object(pc, "record_retrieval", MagicMock()), \
patch.object(pc, "owner_names_for", AsyncMock(return_value={})):
out = await pc.build_write_path_hint(1, "src/lib/x.py", code=REAL_CODE)
assert '#9 [nearby] "sibling helper"' in out["context"]
assert '#9 [' not in out["context"]
assert ("> Also recorded beside this file: snippets #9 (`get_snippet(id)`)"
in out["context"])
assert out["note_ids"] == []
@pytest.mark.asyncio
@@ -334,22 +340,12 @@ async def test_semantic_arm_only_asks_for_the_budget_the_place_arm_left():
@pytest.mark.asyncio
async def test_session_dedup_marks_the_reuse_arms_rather_than_silencing_them():
"""exclude_ids governs the REUSE classes — nearby and semantic. (The sync
class has its own channel; see the tests above.)
WHY A MARKER AND NOT SILENCE. Dropping the hit and pushing its id into the
search's `exclude_ids` means that the second time a record is the best
answer, the session gets silence, which reads exactly like "nothing is
recorded here". So the repeat is rendered with a `seen` marker, and the
ledger never reaches the query, so the score the search reports describes
the bar rather than a candidate set the caller had already edited.
Marked on BOTH reuse arms, which is what this asserts: one menu with two
rules — `seen` on the semantic hits, silence on the nearby ones — would
make the marker read as a complete account of what the session has met,
when it would only cover half the lines.
"""
async def test_a_snippet_beside_the_file_already_shown_is_not_named_again():
"""exclude_ids is the session's ledger. A snippet beside the file that
the session already has is in its context, so the pointer line does not
name it again; it is still withheld from the search by resemblance, since
the place lookup found it in this same call. (The sync class has its own
channel; see the tests above.)"""
from grimoire.services import plugin_context as pc
async def _listing(uid, **kw):
@@ -364,15 +360,11 @@ async def test_session_dedup_marks_the_reuse_arms_rather_than_silencing_them():
patch.object(pc, "semantic_search_notes", search), \
patch.object(pc, "record_retrieval", MagicMock()):
out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE, exclude_ids=[12])
assert out["note_ids"] == [12]
assert "seen" in next(
line for line in out["context"].splitlines() if "#12" in line
)
# #12 IS in this call's `exclude_ids`, and that is the other rule working:
# the place arm has just listed it, so the semantic arm must not list it
# again. What must never reach the query is the LEDGER, which is asserted
# on its own in tests/test_ledger_references_not_silence.py against a
# record this call has not otherwise rendered.
assert "#12" not in out["context"]
# #12 IS in this call's `exclude_ids` because the place lookup found it in
# this call, not because the ledger reached the query; that is asserted on
# its own in tests/test_ledger_references_not_silence.py against a record
# this call has not otherwise found.
assert 12 in search.await_args.kwargs["exclude_ids"]