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
+41 -6
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 record_refs as record_refs_svc
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 snippets as snippets_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.
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 -------------------------
# 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
@@ -1384,6 +1390,10 @@ async def build_write_path_hint(
# 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
# "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] = []
nearby: list[dict] = []
try:
@@ -1391,7 +1401,7 @@ async def build_write_path_hint(
user_id, path=path, limit=top_k, project_id=scope_project,
)
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(
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
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 semantic arm, because the arm's query doubles as the resemblance
# 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 ---
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()
# 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
@@ -1476,7 +1506,7 @@ async def build_write_path_hint(
user_id=user_id, query=query, project_id=project_id,
seen=frozenset(excluded), in_menu=frozenset(seen),
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(),
)
@@ -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 common case is a silent hint and a pulled canon being instantiated.
@@ -1844,9 +1876,12 @@ async def build_write_path_hint(
# same call. The semantic arm's rows (`write_path_semantic`)
# were written by the pipeline beside its call row, so only the
# lookups are booked here.
if int(item["id"]) in excluded or not marker.startswith("nearby"):
if int(item["id"]) in excluded:
continue
by_arm.setdefault("write_path_place", []).append(int(item["id"]))
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"]))
for arm, ids in by_arm.items():
record_surfaced(
user_id=user_id, note_ids=ids, source=arm, project_id=project_id,
+2 -1
View File
@@ -95,7 +95,8 @@ DOORS: dict[str, Door] = {
"work.change": Door(
"work.change", "Altering the thing being worked on", "before every write or edit",
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
# this exact file", be measured.
_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_sync", AMBIENT,
"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`)
# records through the pipeline's site below.
"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)": (
"rulings_pre_tool", "rulings_write_path",