feat(7834): issues linked to the file being written arrive before anything found by meaning
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m53s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 30s

Before a write, the write path now looks up issues by structure:
- an issue whose body or a log names the file (any status: a closed one
  is the record of what was already tried there);
- an open issue tagged to an area whose path patterns cover the file.

At most two, listed first, withheld from the search by meaning, which
fills only what is left and only past the gate. Measured under
write_path_linked. The lookups follow the kind x moment table: no issue
lookup when issues are off at work.change, no nearby-snippet lookup when
snippets are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 18:58:59 -05:00
co-authored by Claude Opus 5.5
parent 1363936ed7
commit a2e474f401
7 changed files with 328 additions and 8 deletions
+40 -5
View File
@@ -26,6 +26,7 @@ from grimoire.services import notes as notes_svc
from grimoire.services import projects as projects_svc from grimoire.services import projects as projects_svc
from grimoire.services import record_refs as record_refs_svc from grimoire.services import record_refs as record_refs_svc
from grimoire.services import record_kinds from grimoire.services import record_kinds
from grimoire.services import record_links as record_links_svc
from grimoire.services import shape_ledger as shape_ledger_svc from grimoire.services import shape_ledger as shape_ledger_svc
from grimoire.services import snippets as snippets_svc from grimoire.services import snippets as snippets_svc
from grimoire.services import task_claims as task_claims_svc from grimoire.services import task_claims as task_claims_svc
@@ -340,6 +341,11 @@ _TOOL_QUERY_CHARS = 400
# pointless embedding round-trip on trivial edits. # pointless embedding round-trip on trivial edits.
WRITEPATH_MIN_CODE_CHARS = 48 WRITEPATH_MIN_CODE_CHARS = 48
# At most this many issues linked by structure on one write: a file worked on
# for months is named by dozens, and the newest two carry what was last tried
# there; the rest are one search away.
LINKED_ISSUES_MAX = 2
# --- concept extraction for the semantic arm's query ------------------------- # --- concept extraction for the semantic arm's query -------------------------
# A snippet's embedded text is f"{title}\n{body}", and for a snippet that body is # A snippet's embedded text is f"{title}\n{body}", and for a snippet that body is
# composed markdown: **When to use:**, **Signature:**, **Location:**, then the # composed markdown: **When to use:**, **Signature:**, **Location:**, then the
@@ -1384,6 +1390,10 @@ async def build_write_path_hint(
# 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, unchanged.
# The kinds this user's write path considers (the kind×moment table).
# The structural lookups below read it as the search by meaning does: a
# kind turned off at this door is not offered here by any arm.
kinds = await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door)
here: list[dict] = [] here: list[dict] = []
nearby: list[dict] = [] nearby: list[dict] = []
try: try:
@@ -1391,7 +1401,7 @@ async def build_write_path_hint(
user_id, path=path, limit=top_k, project_id=scope_project, user_id, path=path, limit=top_k, project_id=scope_project,
) )
directory = path.rsplit("/", 1)[0] if "/" in path else "" directory = path.rsplit("/", 1)[0] if "/" in path else ""
if directory and len(here) < top_k: if directory and len(here) < top_k and "snippet" in kinds:
nearby, _ = await snippets_svc.list_snippets( nearby, _ = await snippets_svc.list_snippets(
user_id, path=directory, limit=top_k, project_id=scope_project, user_id, path=directory, limit=top_k, project_id=scope_project,
) )
@@ -1429,6 +1439,26 @@ async def build_write_path_hint(
item["seen"] = nid in excluded item["seen"] = nid in excluded
placed.append(("nearby · seen" if nid in excluded else "nearby", item)) placed.append(("nearby · seen" if nid in excluded else "nearby", item))
# --- arm 1b: issues linked by structure ---
# An issue that names this file, or is open in its area, needs no
# resemblance to belong here, so it takes the issue's place before the
# search by meaning runs, and that search does not list it again.
linked: list[tuple[str, dict]] = []
if "task:issue" in kinds and project_id:
room = min(LINKED_ISSUES_MAX, top_k - len(synced) - len(placed))
for link, note in await record_links_svc.issues_for_path(
user_id, project_id, path, limit=room, exclude=frozenset(seen),
):
nid = int(note.id)
seen.add(nid)
kind = _record_kind(note)
marker = f"{link} · {kind}" + (" · seen" if nid in excluded else "")
linked.append((marker, {
"id": nid, "title": note.title, "user_id": note.user_id,
"name": _menu_name(note.title, note.note_type, note.data, note.body),
"seen": nid in excluded, "kind": kind, "linked": True,
}))
# The stamping feed's "actually pulled it" half. Read once, before # The stamping feed's "actually pulled it" half. Read once, before
# the semantic arm, because the arm's query doubles as the resemblance # the semantic arm, because the arm's query doubles as the resemblance
# test: a pulled snippet this session already saw (so it sits in `seen`) # test: a pulled snippet this session already saw (so it sits in `seen`)
@@ -1440,7 +1470,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) remaining = top_k - len(synced) - len(placed) - 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
@@ -1476,7 +1506,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=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door), kinds=kinds,
), ),
floor=cfg["threshold"], budget=remaining, io=_note_io(), floor=cfg["threshold"], budget=remaining, io=_note_io(),
) )
@@ -1535,7 +1565,9 @@ async def build_write_path_hint(
}, },
)) ))
menu = (placed + scored)[:max(0, top_k - len(synced))] # Structure first: what is linked to the file, then what sits beside it,
# then what was found by meaning.
menu = (linked + placed + 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.
@@ -1844,8 +1876,11 @@ async def build_write_path_hint(
# same call. The semantic arm's rows (`write_path_semantic`) # same call. The semantic arm's rows (`write_path_semantic`)
# were written by the pipeline beside its call row, so only the # were written by the pipeline beside its call row, so only the
# lookups are booked here. # lookups are booked here.
if int(item["id"]) in excluded or not marker.startswith("nearby"): if int(item["id"]) in excluded:
continue continue
if item.get("linked"):
by_arm.setdefault("write_path_linked", []).append(int(item["id"]))
elif marker.startswith("nearby"):
by_arm.setdefault("write_path_place", []).append(int(item["id"])) 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(
+2 -1
View File
@@ -95,7 +95,8 @@ DOORS: dict[str, Door] = {
"work.change": Door( "work.change": Door(
"work.change", "Altering the thing being worked on", "before every write or edit", "work.change", "Altering the thing being worked on", "before every write or edit",
frozenset({"snippet", "note", "lesson", "task:issue"}), frozenset({"snippet", "note", "lesson", "task:issue"}),
sources=("write_path_semantic",), sources=("write_path_semantic", "write_path_place", "write_path_sync",
"write_path_linked"),
), ),
} }
+113
View File
@@ -0,0 +1,113 @@
"""Records linked to the work by structure: no score, no bar.
WHY THIS EXISTS
A search by meaning asks "what resembles the words of this edit", and the
answer is often a record about something else that happens to read the same.
A record that NAMES the file being edited, or is open in the area the file
belongs to, needs no resemblance to be relevant: the link is the reason. So
these lookups run first, their lines take the kind's place in the payload,
and the search by meaning only fills what they left.
THE TWO LINKS, strongest first
- **Names this file** — an issue whose body, or one of whose logs, carries the
file's repo-relative path. That is how a session records what it touched,
so an issue that fixed something in this file says so in its own words.
Any status: a closed issue is the record of what was already tried here.
- **Open in this area** — an issue still open, tagged to an area (System)
whose path patterns cover the file. A finished issue in the area is
history the file may not share; an open one is live work on it.
Both are scoped to the project and to what the reader may read.
"""
from __future__ import annotations
import logging
from sqlalchemy import exists, or_, select
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.system import RecordSystem
from grimoire.models.task_log import TaskLog
from grimoire.services.access import readable_notes_clause
logger = logging.getLogger(__name__)
NAMES_FILE = "names this file"
OPEN_IN_AREA = "open in this area"
_CLOSED = ("done", "cancelled")
def _issue(user_id: int, project_id: int):
return (
select(Note)
.where(
Note.project_id == project_id,
Note.status.isnot(None),
Note.task_kind == "issue",
Note.deleted_at.is_(None),
readable_notes_clause(user_id),
)
)
async def issues_for_path(
user_id: int, project_id: int, path: str, *, limit: int,
exclude: set[int] | frozenset[int] = frozenset(),
) -> list[tuple[str, Note]]:
"""Issues linked to the file at `path`, each with the link that found it:
those naming the file first, then those open in its area, most recently
touched first within each, at most `limit` in all."""
path = (path or "").strip()
if not project_id or not path or limit <= 0:
return []
from grimoire.services.systems import systems_for_paths
out: list[tuple[str, Note]] = []
taken = set(exclude)
try:
async with async_session() as session:
# A literal path, not a pattern: `_` and `%` are common in file
# names and would otherwise match any character.
named = (await session.execute(
_issue(user_id, project_id)
.where(or_(
Note.body.contains(path, autoescape=True),
exists().where(
TaskLog.task_id == Note.id,
TaskLog.content.contains(path, autoescape=True),
),
))
.order_by(Note.updated_at.desc(), Note.id.desc())
.limit(limit + len(taken))
)).scalars().all()
for note in named:
if int(note.id) not in taken and len(out) < limit:
out.append((NAMES_FILE, note))
taken.add(int(note.id))
if len(out) >= limit:
return out
areas = [s.id for s, _hit in await systems_for_paths(user_id, project_id, [path])]
if not areas:
return out
open_here = (await session.execute(
_issue(user_id, project_id)
.where(
Note.status.not_in(_CLOSED),
exists().where(
RecordSystem.note_id == Note.id,
RecordSystem.system_id.in_(areas),
),
)
.order_by(Note.updated_at.desc(), Note.id.desc())
.limit(limit + len(taken))
)).scalars().all()
for note in open_here:
if int(note.id) not in taken and len(out) < limit:
out.append((OPEN_IN_AREA, note))
taken.add(int(note.id))
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.warning("linked-issue lookup failed", exc_info=True)
return out
+3 -1
View File
@@ -181,6 +181,8 @@ POINTS: dict[str, Point] = dict([
# the strongest possible claim, "there is already a canonical helper in # the strongest possible claim, "there is already a canonical helper in
# this exact file", be measured. # this exact file", be measured.
_p("write_path_place", AMBIENT, "a snippet already placed in this very file"), _p("write_path_place", AMBIENT, "a snippet already placed in this very file"),
_p("write_path_linked", AMBIENT,
"an issue that names the file being written, or is open in its area"),
_p("write_path_semantic", AMBIENT, "prior art matched by meaning"), _p("write_path_semantic", AMBIENT, "prior art matched by meaning"),
_p("write_path_sync", AMBIENT, _p("write_path_sync", AMBIENT,
"records that should be updated alongside this edit"), "records that should be updated alongside this edit"),
@@ -230,7 +232,7 @@ FAN_OUT_SITES: dict[str, tuple[str, ...]] = {
# The write path's two LOOKUPS. Its ranked arm (`write_path_semantic`) # The write path's two LOOKUPS. Its ranked arm (`write_path_semantic`)
# records through the pipeline's site below. # records through the pipeline's site below.
"grimoire/services/plugin_context.py::record_surfaced(source=arm)": ( "grimoire/services/plugin_context.py::record_surfaced(source=arm)": (
"write_path_place", "write_path_sync", "write_path_place", "write_path_sync", "write_path_linked",
), ),
"grimoire/services/system_rulings.py::record_system_surfaced(source=source)": ( "grimoire/services/system_rulings.py::record_system_surfaced(source=source)": (
"rulings_pre_tool", "rulings_write_path", "rulings_pre_tool", "rulings_write_path",
+17
View File
@@ -388,6 +388,23 @@ def _default_record_kinds(request):
yield yield
@pytest.fixture(autouse=True)
def _no_linked_issues(request):
"""Stub the write path's structural issue lookup to find nothing.
It reads notes and task logs, which a unit test of the write path has
not written; a test about linked issues patches it with its own answer.
The integration lane runs the real query.
"""
if request.node.get_closest_marker("integration"):
yield
return
from grimoire.services import record_links
with patch.object(record_links, "issues_for_path", AsyncMock(return_value=[])):
yield
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _ungated_doors(request): def _ungated_doors(request):
"""Leave the plugin doors' cue-swap gate off unless a test asks for it. """Leave the plugin doors' cue-swap gate off unless a test asks for it.
+80
View File
@@ -0,0 +1,80 @@
"""Real-Postgres tests for `record_links.issues_for_path`: an issue naming the
file in its body or a log comes first; an open issue in the file's area comes
next; a closed one there, another project's and a plain task are
left out, as is everything for a reader without access; and a path is
matched literally."""
import pytest
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.project import Project
from grimoire.models.system import RecordSystem, System
from grimoire.models.task_log import TaskLog
from grimoire.services import record_links
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
PATH = "src/app/lock_guard.py"
async def _world():
async with async_session() as s:
owner = await ensure_user(s, "record_links_owner")
stranger = await ensure_user(s, "record_links_stranger")
project = Project(user_id=owner.id, title="record links project")
other = Project(user_id=owner.id, title="record links other")
s.add_all([project, other])
await s.flush()
area = System(user_id=owner.id, project_id=project.id, name="locks",
path_patterns=["src/app/**"])
s.add(area)
await s.flush()
def issue(title, status="done", body="", pid=project.id, uid=owner.id, kind="issue"):
return Note(user_id=uid, project_id=pid, title=title, status=status,
task_kind=kind, body=body)
made = {
"in_body": issue("names it in its body", body=f"fixed in {PATH}"),
"in_log": issue("names it in a log"),
"open_area": issue("open in the area", status="todo"),
"closed_area": issue("closed in the area"),
"other_project": issue("other project", body=f"see {PATH}", pid=other.id),
"work_task": issue("a work task naming it", body=f"edit {PATH}", kind="work"),
# `_` is a single-character wildcard to LIKE; matched literally it
# must not stand in for the `_` in the path.
"near_miss": issue("a near miss", body="src/app/lockXguard.py"),
}
s.add_all(made.values())
await s.flush()
s.add(TaskLog(task_id=made["in_log"].id, user_id=owner.id, content=f"touched {PATH}"))
s.add_all(RecordSystem(note_id=made[k].id, system_id=area.id)
for k in ("open_area", "closed_area"))
await s.commit()
ids = {k: n.id for k, n in made.items()}
return owner.id, project.id, ids, stranger.id
async def test_issues_naming_the_file_come_first_then_open_ones_in_its_area():
uid, pid, ids, _stranger = await _world()
found = await record_links.issues_for_path(uid, pid, PATH, limit=5)
got = [(link, int(n.id)) for link, n in found]
named = {i for link, i in got if link == record_links.NAMES_FILE}
assert named == {ids["in_body"], ids["in_log"]}
assert got[:2] == [(link, i) for link, i in got if link == record_links.NAMES_FILE]
assert (record_links.OPEN_IN_AREA, ids["open_area"]) in got
left_out = {"closed_area", "other_project", "work_task", "near_miss"}
assert not {ids[k] for k in left_out} & {i for _l, i in got}
async def test_the_limit_and_the_exclusions_hold():
uid, pid, ids, stranger = await _world()
assert len(await record_links.issues_for_path(uid, pid, PATH, limit=1)) == 1
found = await record_links.issues_for_path(
uid, pid, PATH, limit=5, exclude={ids["in_body"], ids["in_log"]},
)
assert [int(n.id) for _l, n in found] == [ids["open_area"]]
assert await record_links.issues_for_path(uid, 0, PATH, limit=5) == []
# A reader who cannot read the project is shown none of its issues.
assert await record_links.issues_for_path(stranger, pid, PATH, limit=5) == []
+72
View File
@@ -0,0 +1,72 @@
"""The write path's structural issue arm: an issue that names the file being
written, or is open in its area, is listed before anything found by meaning,
withheld from that search, measured under its own source, and not looked for
at all when the user's table turns issues off at this door."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from grimoire.services import record_kinds, record_links
from tests.helpers import fake_note, fake_task
from tests.test_write_path_trigger import REAL_CODE, _cfg
async def _hint(linked, *, semantic=(), kinds=None, project_id=2):
from grimoire.services import plugin_context as pc
search = AsyncMock(return_value=list(semantic))
surfaced = MagicMock()
lookup = AsyncMock(return_value=linked)
patches = [
patch.object(pc, "get_writepath_config", AsyncMock(return_value=_cfg())),
patch.object(pc.snippets_svc, "list_snippets", AsyncMock(return_value=([], 0))),
patch.object(pc, "semantic_search_notes", search),
patch.object(pc, "record_retrieval", MagicMock()),
patch.object(pc, "record_surfaced", surfaced),
patch.object(pc, "owner_names_for", AsyncMock(return_value={})),
patch.object(record_links, "issues_for_path", lookup),
]
if kinds is not None:
patches.append(patch.object(record_kinds, "kinds_for", AsyncMock(return_value=kinds)))
for p in patches:
p.start()
try:
out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE, project_id=project_id)
finally:
for p in reversed(patches):
p.stop()
return out, search, surfaced, lookup
@pytest.mark.asyncio
async def test_a_linked_issue_is_listed_before_meaning_and_withheld_from_it():
issue = fake_task(id=41, title="the lock leaked in x.py", task_kind="issue", status="done",
user_id=1, note_type="note", data=None)
similar = (0.90, fake_note(id=7, title="a snippet like it", note_type="snippet", user_id=1))
out, search, surfaced, lookup = await _hint(
[(record_links.NAMES_FILE, issue)], semantic=[similar],
)
lines = [ln for ln in out["context"].splitlines() if ln.startswith("> - #")]
assert lines[0].startswith('> - #41 [names this file · issue (done)]')
assert lookup.await_args.args[:3] == (1, 2, "src/x.py")
# The search by meaning is told the linked issue is already listed.
assert 41 in search.await_args.kwargs["exclude_ids"]
by_source = {c.kwargs["source"]: c.kwargs["note_ids"] for c in surfaced.call_args_list}
assert by_source["write_path_linked"] == [41]
assert "write_path_place" not in by_source
@pytest.mark.asyncio
async def test_no_issue_is_looked_up_when_the_door_turned_issues_off():
_out, _search, _surfaced, lookup = await _hint(
[], kinds=frozenset({"snippet", "note", "lesson"}),
)
lookup.assert_not_awaited()
@pytest.mark.asyncio
async def test_no_issue_is_looked_up_without_a_project():
_out, _search, _surfaced, lookup = await _hint([], project_id=0)
lookup.assert_not_awaited()