Records reach an edit and a message by structure first; resemblance offers notes (#7832) #233

Merged
bvandeusen merged 2 commits from dev into main 2026-11-25 12:58:37 -05:00
11 changed files with 189 additions and 114 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.25.0016", "version": "2026.11.25.1721",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+2
View File
@@ -22,6 +22,8 @@ What only Claude Code needs said:
how to correct a moment that fired wrongly. A line beginning "Also how to correct a moment that fired wrongly. A line beginning "Also
resembling this, not shown" names records by id only, because they matched resembling this, not shown" names records by id only, because they matched
less clearly than the lines above it: open one when it may bear on the work. less clearly than the lines above it: open one when it may bear on the work.
"Also recorded beside this file" names the snippets recorded in the same
folder as the file being written, by id, for the same judgement.
- **A rule can hold or refuse a tool call.** A held call names its rule and - **A rule can hold or refuse a tool call.** A held call names its rule and
goes ahead once the rule has been read: read it, then make the call again. goes ahead once the rule has been read: read it, then make the call again.
A refused call is a boundary the operator drew; it moves when they change A refused call is a boundary the operator drew; it moves when they change
+38 -23
View File
@@ -1077,6 +1077,9 @@ def _rule_io() -> rp.RuleIO:
# How a door's pointer line opens: records that cleared the floor and were # How a door's pointer line opens: records that cleared the floor and were
# not shown. The static context teaches what a line opening this way means. # not shown. The static context teaches what a line opening this way means.
POINTER_LEAD = "Also resembling this, not shown" POINTER_LEAD = "Also resembling this, not shown"
# The write path's line naming snippets recorded beside the file being
# written: offered for where they sit, so the lead says that, not resemblance.
PLACE_POINTER_LEAD = "Also recorded beside this file"
def _prior_art_line(item: dict, marker: str, owner: str | None, foreign_lang: str = "") -> str: def _prior_art_line(item: dict, marker: str, owner: str | None, foreign_lang: str = "") -> str:
@@ -1398,11 +1401,12 @@ async def build_write_path_hint(
# `path` matches exact-or-under (see knowledge.py), and nothing sits under # `path` matches exact-or-under (see knowledge.py), and nothing sits under
# a FILE path — so the file query returns precisely the snippets recorded # a FILE path — so the file query returns precisely the snippets recorded
# AT this path: the sync class. The directory query is the reuse-shaped # AT this path: the sync class. The directory query is the reuse-shaped
# "nearby" arm, unchanged. # "nearby" arm, named by id only.
# The kinds this user's write path considers (the kind×moment table). # The kinds the structural lookups below consider (the kind×moment table's
# The structural lookups below read it as the search by meaning does: a # `work.change` row). The search by meaning reads its own row
# kind turned off at this door is not offered here by any arm. # (`work.change.similar`), so a kind can be offered where it is recorded
kinds = await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door) # and not by resemblance.
kinds = await record_kinds.kinds_for(user_id, record_kinds.WORK_CHANGE)
here: list[dict] = [] here: list[dict] = []
nearby: list[dict] = [] nearby: list[dict] = []
try: try:
@@ -1434,19 +1438,18 @@ async def build_write_path_hint(
if nid not in sync_excluded and len(synced) < top_k: if nid not in sync_excluded and len(synced) < top_k:
synced.append(item) synced.append(item)
placed: list[tuple[str, dict]] = [] # A snippet recorded beside the file is named by id, not given a line: it
# is offered because of where it sits, not because it bears on this edit,
# and the session is the one placed to judge whether it does. One already
# shown this session is in context and is not named again.
placed: list[int] = []
for item in nearby: for item in nearby:
nid = int(item["id"]) nid = int(item["id"])
if nid in seen: if nid in seen:
continue continue
seen.add(nid) seen.add(nid)
# MARKED HERE TOO, not just on the semantic arm, because these are one if nid not in excluded:
# menu. A hint where some repeats carry `seen` and others are silently placed.append(nid)
# dropped — decided by which arm happened to find them — is worse than
# either rule applied consistently: the marker would read as a complete
# account of what the session has met before, and it would not be one.
item["seen"] = nid in excluded
placed.append(("nearby · seen" if nid in excluded else "nearby", item))
# --- arm 1b: issues linked by structure --- # --- arm 1b: issues linked by structure ---
# An issue that names this file, or is open in its area, needs no # An issue that names this file, or is open in its area, needs no
@@ -1454,7 +1457,7 @@ async def build_write_path_hint(
# search by meaning runs, and that search does not list it again. # search by meaning runs, and that search does not list it again.
linked: list[tuple[str, dict]] = [] linked: list[tuple[str, dict]] = []
if "task:issue" in kinds and project_id: if "task:issue" in kinds and project_id:
room = min(LINKED_ISSUES_MAX, top_k - len(synced) - len(placed)) room = min(LINKED_ISSUES_MAX, top_k - len(synced))
for link, note in await record_links_svc.issues_for_path( for link, note in await record_links_svc.issues_for_path(
user_id, project_id, path, limit=room, exclude=frozenset(seen), user_id, project_id, path, limit=room, exclude=frozenset(seen),
): ):
@@ -1479,7 +1482,7 @@ async def build_write_path_hint(
# --- arm 2: by meaning --- # --- arm 2: by meaning ---
scored: list[tuple[str, dict]] = [] scored: list[tuple[str, dict]] = []
remaining = top_k - len(synced) - len(placed) - len(linked) remaining = top_k - len(synced) - len(linked)
query = (code or "").strip() query = (code or "").strip()
# Drop payloads too small to carry meaning before spending an embedding on # Drop payloads too small to carry meaning before spending an embedding on
# them — a one-line Edit is not a helper being rewritten, and its embedding # them — a one-line Edit is not a helper being rewritten, and its embedding
@@ -1516,7 +1519,7 @@ async def build_write_path_hint(
user_id=user_id, query=query, project_id=project_id, user_id=user_id, query=query, project_id=project_id,
seen=frozenset(excluded), in_menu=frozenset(seen), seen=frozenset(excluded), in_menu=frozenset(seen),
still_scored=frozenset(pulled), still_scored=frozenset(pulled),
kinds=kinds, kinds=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door),
), ),
floor=cfg["threshold"], budget=remaining, io=_note_io(), floor=cfg["threshold"], budget=remaining, io=_note_io(),
) )
@@ -1576,9 +1579,9 @@ async def build_write_path_hint(
}, },
)) ))
# Structure first: what is linked to the file, then what sits beside it, # Structure first: what is linked to the file, then what was found by
# then what was found by meaning. # meaning. What sits beside the file is named in its own pointer line.
menu = (linked + placed + scored)[:max(0, top_k - len(synced))] menu = (linked + scored)[:max(0, top_k - len(synced))]
# The suggestion runs whether or not anything is rendered — after dedup, # The suggestion runs whether or not anything is rendered — after dedup,
# the common case is a silent hint and a pulled canon being instantiated. # the common case is a silent hint and a pulled canon being instantiated.
@@ -1728,7 +1731,8 @@ async def build_write_path_hint(
] ]
if (not staleness and not synced and not menu and not suggested if (not staleness and not synced and not menu and not suggested
and not divergence and not derive and not rule_lines and not pointers): and not divergence and not derive and not rule_lines and not pointers
and not placed):
if design_text or rulings["lines"]: if design_text or rulings["lines"]:
return { return {
**empty, **empty,
@@ -1853,6 +1857,17 @@ async def build_write_path_hint(
entry.append(f"> ↳ {passage}") entry.append(f"> ↳ {passage}")
parts[-1] = replace(parts[-1], text="\n".join(entry)) parts[-1] = replace(parts[-1], text="\n".join(entry))
place_pointer = record_kinds.pointer_line({"snippet": placed}, PLACE_POINTER_LEAD)
place_named: list[int] = []
if place_pointer:
place_named = place_pointer[1]
lines.append(place_pointer[0])
parts.append(hook_payload.Part(
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 = record_kinds.pointer_line(pointers, POINTER_LEAD)
if pointer: if pointer:
lines.append(pointer[0]) lines.append(pointer[0])
@@ -1885,7 +1900,9 @@ async def build_write_path_hint(
by_arm: dict[str, list[int]] = {} by_arm: dict[str, list[int]] = {}
if sync_note_ids: if sync_note_ids:
by_arm["write_path_sync"] = list(sync_note_ids) by_arm["write_path_sync"] = list(sync_note_ids)
for marker, item in menu: if place_named:
by_arm["write_path_place"] = list(place_named)
for _marker, item in menu:
# A rendered repeat is not a new surfacing — same cut the log row # A rendered repeat is not a new surfacing — same cut the log row
# takes, so this table and `retrieval_logs` keep agreeing about the # takes, so this table and `retrieval_logs` keep agreeing about the
# same call. The semantic arm's rows (`write_path_semantic`) # same call. The semantic arm's rows (`write_path_semantic`)
@@ -1895,8 +1912,6 @@ async def build_write_path_hint(
continue continue
if item.get("linked"): if item.get("linked"):
by_arm.setdefault("write_path_linked", []).append(int(item["id"])) by_arm.setdefault("write_path_linked", []).append(int(item["id"]))
elif marker.startswith("nearby"):
by_arm.setdefault("write_path_place", []).append(int(item["id"]))
for arm, ids in by_arm.items(): for arm, ids in by_arm.items():
record_surfaced( record_surfaced(
user_id=user_id, note_ids=ids, source=arm, project_id=project_id, user_id=user_id, note_ids=ids, source=arm, project_id=project_id,
+45 -12
View File
@@ -35,6 +35,27 @@ A door is a point where records are offered: a catalog moment
(`work.change` before a write, `work.start` when a task is taken up), or the (`work.change` before a write, `work.start` when a task is taken up), or the
operator's message, which is when a session first hears what the work is and operator's message, which is when a session first hears what the work is and
is not a moment rules mount on, so it has its own key (`message`). is not a moment rules mount on, so it has its own key (`message`).
One moment can have two doors when it finds records two ways. An edit is
offered what sits where the edit is (`work.change`: snippets recorded at or
beside the file, issues that name it or are open in its area) and what the
code being written resembles (`work.change.similar`). The two make different
claims: "this is recorded here" holds whatever the words are, and "this
reads like what you are writing" holds only as far as resemblance is
evidence. So each has its own row, and a kind can be on for one and off for
the other.
WHAT THE DEFAULTS SAY
A kind is offered by resemblance only where resemblance is evidence for it.
Notes are written in the words of the work they describe, so a note that
reads like the work is usually about it. An issue, a lesson or a snippet
resembles the words around it far more often than the work is its case,
so each reaches the work through its structure instead: a snippet through
the file it is recorded at, an issue through the file or area it names and
when a task in its area is taken up, a lesson through the situation
confirmed for it (`lesson_situations`), and any record when the work names
its id.
""" """
from __future__ import annotations from __future__ import annotations
@@ -67,6 +88,8 @@ LABELS: dict[str, str] = {
SETTING_KEY = "record_kinds" SETTING_KEY = "record_kinds"
MESSAGE = "message" MESSAGE = "message"
WORK_CHANGE = "work.change"
WORK_CHANGE_SIMILAR = "work.change.similar"
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -85,21 +108,31 @@ class Door:
DOORS: dict[str, Door] = { DOORS: dict[str, Door] = {
# Found by resemblance to the operator's words. Issues and lessons are
# left out (see WHAT THE DEFAULTS SAY); a record the message names by id
# is looked up whatever its kind.
MESSAGE: Door( MESSAGE: Door(
MESSAGE, "The operator's message", "once per operator turn", MESSAGE, "The operator's message", "once per operator turn",
frozenset(KINDS), sources=("auto_inject", "lesson_slot"), frozenset(KINDS) - {"lesson", "task:issue"}, sources=("auto_inject", "lesson_slot"),
), ),
# What is about to be written: code to reuse, and what was already tried # What sits where the edit is: snippets recorded beside the file (named
# (an issue, a dev-log, a lesson). The open to-do list resembles the code # by id), and issues that name the file or are open in its area. The
# and answers nothing, so work tasks are left out. # snippets recorded at the file itself are always shown: they are the
# Not lessons: an edit's words resemble a lesson far more often than the # record of the code being changed.
# edit is its situation. A lesson reaches an edit through a situation WORK_CHANGE: Door(
# confirmed for it (`lesson_situations`), once per session. WORK_CHANGE, "Altering the thing being worked on: what is recorded there",
"work.change": Door( "before every write or edit",
"work.change", "Altering the thing being worked on", "before every write or edit", frozenset({"snippet", "task:issue"}),
frozenset({"snippet", "note", "task:issue"}), sources=("write_path_place", "write_path_sync", "write_path_linked"),
sources=("write_path_semantic", "write_path_place", "write_path_sync", ),
"write_path_linked"), # What the code being written resembles. Notes only by default; the open
# to-do list resembles the code and answers nothing, and the other kinds
# reach an edit through the door above or their situation.
WORK_CHANGE_SIMILAR: Door(
WORK_CHANGE_SIMILAR, "Altering the thing being worked on: what it resembles",
"before a write or edit long enough to compare",
frozenset({"note"}),
sources=("write_path_semantic",),
), ),
# Taking up a task: what is recorded in the task's own areas, named by id # Taking up a task: what is recorded in the task's own areas, named by id
# in the reply that set it in progress. Notes for what is known there, # in the reply that set it in progress. Notes for what is known there,
+2 -2
View File
@@ -1172,7 +1172,7 @@ AUTO_INJECT = NoteArm(
# 200:1 dilution a slot answers does not happen. # 200:1 dilution a slot answers does not happen.
WRITE_PATH = NoteArm( WRITE_PATH = NoteArm(
"write_path", surfaced_as="write_path_semantic", "write_path", surfaced_as="write_path_semantic",
door="work.change", withholds=True, gated=True, door=record_kinds.WORK_CHANGE_SIMILAR, withholds=True, gated=True,
tuning=Surface( tuning=Surface(
name="write_path", name="write_path",
floor_key="kb_writepath_threshold", floor_key="kb_writepath_threshold",
@@ -1181,7 +1181,7 @@ WRITE_PATH = NoteArm(
budget_default=3, budget_default=3,
budget_falls_back_to="kb_autoinject_top_k", budget_falls_back_to="kb_autoinject_top_k",
asks="the code being written, rewritten as a concept query", asks="the code being written, rewritten as a concept query",
over="snippets and recorded issues", over="the kinds its row of the record-kinds table allows (notes by default)",
fires="before every Write and Edit", fires="before every Write and Edit",
), ),
declared=Declared("prior art offered when a file is about to be written"), declared=Declared("prior art offered when a file is about to be written"),
+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(): async def test_a_door_follows_its_default_until_the_user_changes_it():
uid = await _user() uid = await _user()
assert await record_kinds.kinds_for(uid, "work.change") == record_kinds.DOORS["work.change"].default 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"]) await record_kinds.set_kinds(uid, "work.change", ["snippet"])
assert await record_kinds.kinds_for(uid, "work.change") == {"snippet", "task:issue"} assert await record_kinds.kinds_for(uid, "work.change") == {"snippet"}
# Another door is untouched. # 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) table = await record_kinds.set_kinds(uid, "work.change", None)
row = next(d for d in table["doors"] if d["door"] == "work.change") row = next(d for d in table["doors"] if d["door"] == "work.change")
assert row["changed"] is False and row["kinds"] == row["default"] 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"]) await record_kinds.set_kinds(uid, "work.nowhere", ["snippet"])
with pytest.raises(ValueError, match="unknown kind"): with pytest.raises(ValueError, match="unknown kind"):
await record_kinds.set_kinds(uid, "message", ["snippet", "rule"]) 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(): 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() await s.commit()
table = await record_kinds.table(uid, days=7) table = await record_kinds.table(uid, days=7)
cells = {d["door"]: d["evidence"] for d in table["doors"]} 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 cells["message"] == {"task:issue": {"delivered": 1, "opened": 0}}
assert table["evidence_failed"] is False 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 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: 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 WHICH ARM. By default neither note arm offers a lesson by resemblance: a
not merely outrank a kind it omits — it makes it unreachable, and nothing lesson reaches the work through the situation confirmed for it
reports an arm that never had the candidate. The write path filters; (`lesson_situations`). A user can turn lessons on at the message door in
the prompt menu does not, but is project-scoped, which for a kind whose whole the record-kinds table, and then the prompt menu reserves a slot for one,
claim is that it transfers amounts to the same silence. 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. 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 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 import pytest
from grimoire.services import plugin_context as pc from grimoire.services import plugin_context as pc
from grimoire.services import record_kinds
from grimoire.services.lessons import LESSON_NOTE_TYPE from grimoire.services.lessons import LESSON_NOTE_TYPE
from tests.helpers import fake_lesson, fake_note, writepath_cfg 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" _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, async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
exclude_ids=None, rec=None, surf=None): exclude_ids=None, rec=None, surf=None, kinds=EVERY_KIND):
"""Run the prompt menu with each query stubbed by the kinds it asks for.""" """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] = [] calls: list[dict] = []
async def fake_search(*_a, **kw): 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, "semantic_search_notes", AsyncMock(side_effect=fake_search)), \
patch.object(pc, "record_retrieval", rec or MagicMock()), \ patch.object(pc, "record_retrieval", rec or MagicMock()), \
patch.object(pc, "record_surfaced", surf 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( out = await pc.build_autoinject_hint(
1, "two overlapping badges on the card", project_id=2, 1, "two overlapping badges on the card", project_id=2,
exclude_ids=exclude_ids or [], 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 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 @pytest.mark.asyncio
async def test_the_write_path_leaves_lessons_to_their_situation(): 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 """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 situation, so the edit door's search by meaning leaves lessons out; a
lesson reaches an edit through a situation confirmed for it 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=[]) search = AsyncMock(return_value=[])
with patch.object(pc, "get_writepath_config", with patch.object(pc, "get_writepath_config",
AsyncMock(return_value=writepath_cfg(threshold=0.6))), \ 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) await pc.build_write_path_hint(1, "src/ui/Badge.vue", code="x" * 400)
kw = search.await_args.kwargs kw = search.await_args.kwargs
assert LESSON_NOTE_TYPE not in kw["record_kinds"] assert kw["record_kinds"] == ["note"]
assert {"snippet", "note"} <= set(kw["record_kinds"])
assert kw["include_global_kinds"] is True assert kw["include_global_kinds"] is True
+16 -7
View File
@@ -15,6 +15,7 @@ from unittest.mock import MagicMock
import pytest import pytest
from grimoire.services import record_kinds
from grimoire.services import retrieval_pipeline as rp from grimoire.services import retrieval_pipeline as rp
from grimoire.services.lessons import LESSON_NOTE_TYPE from grimoire.services.lessons import LESSON_NOTE_TYPE
from grimoire.services.retrieval_registry import FAN_OUT_SITES, POINTS 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 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): async def _run(arm, route, *, budget=3, **moment):
io, calls = _io(route) io, calls = _io(route)
result = await rp.run_note_arm( 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)] main = [_note(1, 0.70), _note(2, 0.69), _note(3, 0.68)]
reuse = [_note(9, 0.60, note_type="snippet")] reuse = [_note(9, 0.60, note_type="snippet")]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)] 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( 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. # 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] 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)] main = [_note(1, 0.70)]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)] lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)]
result, io, _ = await _run( 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 42 in [int(n.id) for _s, n in result.menu]
assert not _rows(io.record_surfaced, "lesson_slot") 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(): def test_the_filters_say_whose_records_and_the_table_says_which_kinds():
for arm in (rp.AUTO_INJECT, rp.WRITE_PATH): for arm in (rp.AUTO_INJECT, rp.WRITE_PATH):
assert rp.note_search_filters(arm) == {"include_global_kinds": True, "scope": "browse"} 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 @pytest.mark.asyncio
async def test_an_arm_searches_only_the_kinds_its_door_allows(): async def test_an_arm_searches_only_the_kinds_its_door_allows():
# The shipped defaults: the message door considers every kind, so its # The shipped defaults: the message door leaves out the kinds that reach
# search is unfiltered; the write path narrows to its row. # 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: []) _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: []) _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. # A user's own row replaces the default.
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"})) _r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"}))
assert calls[0]["record_kinds"] == ["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( @pytest.mark.parametrize(
"lookups, expected_source", "lookups, expected_source, listed",
[ [
# A hit AT the exact file is the sync class; a hit from the # A hit AT the exact file is the sync class, given a line; a hit from
# directory query is the reuse-shaped place arm. Both are un-scored, # the directory query is the place arm, named by id in a pointer
# and both must leave a usage trace under their own name. # line. Both are un-scored, and both must leave a usage trace under
([(1, "hit"), (2, "empty")], "write_path_sync"), # their own name.
([(1, "empty"), (2, "hit")], "write_path_place"), ([(1, "hit"), (2, "empty")], "write_path_sync", [42]),
([(1, "empty"), (2, "hit")], "write_path_place", []),
], ],
ids=["at-the-file", "nearby"], 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 """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 — without a usage row they would surface snippets while leaving no trace
anywhere. Asserted per class.""" 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" 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} sources = {c.kwargs["source"] for c in surfaced.call_args_list}
assert expected_source in sources assert expected_source in sources
+12 -11
View File
@@ -89,9 +89,11 @@ async def test_build_autoinject_hint_titles_only_with_margin_gate():
assert "↳" not in out["context"] assert "↳" not in out["context"]
# Telemetry fired for BOTH retrievals this path runs: the scored menu and # 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 # 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] 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 @pytest.mark.asyncio
@@ -460,11 +462,12 @@ async def test_a_process_counts_as_reuse_too():
# --- write-path prior art beyond snippets ------------------------------------ # --- write-path prior art beyond snippets ------------------------------------
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_write_path_semantic_arm_asks_for_experience_not_just_snippets(): async def test_write_path_search_by_resemblance_asks_its_own_row_for_notes():
"""The inverse of auto-inject's mistake. This arm was snippets-only, so an """The search by resemblance on an edit reads its own row of the
issue saying "we tried this and it deadlocked" could never reach the moment record-kinds table (`work.change.similar`), notes by default. A snippet
that code was about to be written — arguably the better prior art, because reaches an edit through the file it is recorded at, and an issue saying
it says what NOT to do.""" "we tried this and it deadlocked" through the file or area it names (the
`work.change` row), so neither is offered by resemblance by default."""
from grimoire.services import plugin_context as pc from grimoire.services import plugin_context as pc
hits = [(0.72, fake_note(id=9, title="debounce helper", user_id=1, note_type="snippet")), hits = [(0.72, fake_note(id=9, title="debounce helper", user_id=1, note_type="snippet")),
@@ -485,10 +488,8 @@ async def test_write_path_semantic_arm_asks_for_experience_not_just_snippets():
) )
kw = search.await_args.kwargs kw = search.await_args.kwargs
# An open to-do resembling the code answers nothing; an ISSUE carries a root assert kw["record_kinds"] == ["note"]
# cause and a NOTE carries durable knowledge. Only the todo is excluded. # The call row is not a tasks-only or notes-only retrieval by is_task.
assert kw["record_kinds"] == ["note", "snippet", "task:issue"]
# Telemetry must not claim this was a notes-only retrieval any more.
assert rec.call_args.kwargs["is_task"] is None assert rec.call_args.kwargs["is_task"] is None
+24 -34
View File
@@ -207,7 +207,10 @@ async def test_directory_is_only_consulted_when_the_file_leaves_room():
@pytest.mark.asyncio @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 from grimoire.services import plugin_context as pc
async def _listing(uid, **kw): 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, "record_retrieval", MagicMock()), \
patch.object(pc, "owner_names_for", AsyncMock(return_value={})): patch.object(pc, "owner_names_for", AsyncMock(return_value={})):
out = await pc.build_write_path_hint(1, "src/lib/x.py", code=REAL_CODE) 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 @pytest.mark.asyncio
@@ -241,7 +247,7 @@ async def test_a_failing_location_lookup_does_not_sink_the_hint():
# --- arm 2: by meaning, under the milestone-93 gates ------------------------- # --- arm 2: by meaning, under the milestone-93 gates -------------------------
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_semantic_arm_is_snippet_only_and_browse_scoped(): async def test_semantic_arm_offers_notes_by_default_and_is_browse_scoped():
from grimoire.services import plugin_context as pc from grimoire.services import plugin_context as pc
search = AsyncMock(return_value=[]) search = AsyncMock(return_value=[])
with patch.object(pc, "get_writepath_config", AsyncMock(return_value=_cfg())), \ with patch.object(pc, "get_writepath_config", AsyncMock(return_value=_cfg())), \
@@ -250,12 +256,10 @@ async def test_semantic_arm_is_snippet_only_and_browse_scoped():
patch.object(pc, "record_retrieval", MagicMock()): patch.object(pc, "record_retrieval", MagicMock()):
await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE) await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE)
kwargs = search.await_args.kwargs kwargs = search.await_args.kwargs
# Prior art is snippets AND recorded experience — an issue saying "we tried # By resemblance an edit is offered notes; snippets and issues reach it
# this and it broke" belongs here — AND lessons, which are often about a # through where they are recorded (the `work.change` row), lessons
# code shape. What # through their situation, and the open to-do list not at all.
# stays out is the open to-do list, which resembles the code and answers assert kwargs["record_kinds"] == ["note"]
# nothing.
assert kwargs["record_kinds"] == ["note", "snippet", "task:issue"]
# Nobody asked for this, so it must not reach a one-to-one direct share. # Nobody asked for this, so it must not reach a one-to-one direct share.
assert kwargs["scope"] == "browse" assert kwargs["scope"] == "browse"
@@ -334,22 +338,12 @@ async def test_semantic_arm_only_asks_for_the_budget_the_place_arm_left():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_session_dedup_marks_the_reuse_arms_rather_than_silencing_them(): async def test_a_snippet_beside_the_file_already_shown_is_not_named_again():
"""exclude_ids governs the REUSE classes — nearby and semantic. (The sync """exclude_ids is the session's ledger. A snippet beside the file that
class has its own channel; see the tests above.) 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
WHY A MARKER AND NOT SILENCE. Dropping the hit and pushing its id into the the place lookup found it in this same call. (The sync class has its own
search's `exclude_ids` means that the second time a record is the best channel; see the tests above.)"""
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.
"""
from grimoire.services import plugin_context as pc from grimoire.services import plugin_context as pc
async def _listing(uid, **kw): async def _listing(uid, **kw):
@@ -364,15 +358,11 @@ async def test_session_dedup_marks_the_reuse_arms_rather_than_silencing_them():
patch.object(pc, "semantic_search_notes", search), \ patch.object(pc, "semantic_search_notes", search), \
patch.object(pc, "record_retrieval", MagicMock()): patch.object(pc, "record_retrieval", MagicMock()):
out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE, exclude_ids=[12]) out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE, exclude_ids=[12])
assert out["note_ids"] == [12] assert "#12" not in out["context"]
assert "seen" in next( # #12 IS in this call's `exclude_ids` because the place lookup found it in
line for line in out["context"].splitlines() if "#12" in line # 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
# #12 IS in this call's `exclude_ids`, and that is the other rule working: # this call has not otherwise found.
# 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 in search.await_args.kwargs["exclude_ids"] assert 12 in search.await_args.kwargs["exclude_ids"]