fix(7736): #N in a body links to the record it names, not to a tag
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Failing after 1m37s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Skipped
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Failing after 1m37s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Skipped
A purely numeric #N is a record reference everywhere now. The tag patterns (frontend utils/tags.ts, the editor decoration, the first-line tag strip, tag autocomplete, backend utils/tags.py) leave digits alone, so #3127 is no longer drawn as a tag chip linking to /notes?tag=3127. - utils/recordRefs.ts links #N, milestone N and rule N in rendered markdown, with the same patterns and other-numbering word list as services/record_refs.py. A drift test reads the TS source and fails when the two differ. - v-record-refs (directives/recordRefs.ts) asks POST /api/notes/resolve-refs once per body for what each id is. A link gets the route for its kind (task, lesson, snippet, note, milestone, rule) and its kind and title on hover. One the reader cannot open is drawn as a dead reference, and missing vs not shared read the same. Applied on every surface that renders markdown. - /milestones/:id finds the project and opens its board at that milestone (?milestone= expands it, scrolls to it and focuses it). - Backlinks include records that cite #N in a body or a work log, through readable_notes_clause instead of an owner-only filter, and route by kind. The graph draws #N citations as dashed reference edges. - create_note, create_task and add_task_log say which forms link. There were no numeric tags to clean up: tags are stored only from the explicit field, and none of the 200 most used is numeric. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -986,33 +986,80 @@ async def get_notes_by_ids(user_id: int, note_ids: list[int]) -> dict[int, Note]
|
||||
|
||||
|
||||
async def get_backlinks(user_id: int, note_id: int) -> list[dict]:
|
||||
note = await get_note(user_id, note_id)
|
||||
if note is None:
|
||||
return []
|
||||
"""The records that link to this one, among those the caller may read.
|
||||
|
||||
title = note.title
|
||||
if not title:
|
||||
Two ways to link: a `[[title]]` wikilink, and a `#N` reference in a body or
|
||||
in a task's work log (most cross-references agents write are the second).
|
||||
Each row says which one it was in `via`. A record reached both ways is
|
||||
listed once, as a wikilink.
|
||||
"""
|
||||
from grimoire.models.task_log import TaskLog
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
from grimoire.services.record_refs import referenced
|
||||
|
||||
found = await get_note_for_user(user_id, note_id)
|
||||
if found is None:
|
||||
return []
|
||||
note, _ = found
|
||||
readable = readable_notes_clause(user_id)
|
||||
rows: dict[int, dict] = {}
|
||||
|
||||
def _row(n: Note, via: str) -> dict:
|
||||
return {
|
||||
"type": "task" if n.is_task else "note",
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"is_task": n.is_task,
|
||||
"note_type": n.note_type or "note",
|
||||
"via": via,
|
||||
}
|
||||
|
||||
async with async_session() as session:
|
||||
escaped = title.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
pattern = f"%[[{escaped}]]%"
|
||||
pattern_alias = f"%[[{escaped}|%"
|
||||
if note.title:
|
||||
escaped = note.title.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
linking = (await session.execute(
|
||||
select(Note).where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
or_(Note.body.like(f"%[[{escaped}]]%"),
|
||||
Note.body.like(f"%[[{escaped}|%")),
|
||||
)
|
||||
)).scalars().all()
|
||||
for n in linking:
|
||||
rows[n.id] = _row(n, "wikilink")
|
||||
|
||||
results = await session.execute(
|
||||
select(Note.id, Note.title, Note.status).where(
|
||||
Note.user_id == user_id,
|
||||
# LIKE narrows to bodies holding the digits after a `#`; `referenced`
|
||||
# then reads each one the way the renderer does, so `#12` does not
|
||||
# count as a link to 1, and "PR #12" is not a link at all.
|
||||
needle = f"%#{note_id}%"
|
||||
citing = (await session.execute(
|
||||
select(Note).where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
or_(Note.body.like(pattern), Note.body.like(pattern_alias)),
|
||||
Note.body.like(needle),
|
||||
)
|
||||
)
|
||||
backlinks: list[dict] = []
|
||||
for row in results.fetchall():
|
||||
link_type = "task" if row[2] is not None else "note"
|
||||
backlinks.append({"type": link_type, "id": row[0], "title": row[1]})
|
||||
)).scalars().all()
|
||||
for n in citing:
|
||||
if n.id not in rows and note_id in referenced(n.body)["notes"]:
|
||||
rows[n.id] = _row(n, "reference")
|
||||
|
||||
return backlinks
|
||||
logged = (await session.execute(
|
||||
select(Note, TaskLog.content)
|
||||
.join(TaskLog, TaskLog.task_id == Note.id)
|
||||
.where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
TaskLog.content.like(needle),
|
||||
)
|
||||
)).all()
|
||||
for n, content in logged:
|
||||
if n.id not in rows and note_id in referenced(content)["notes"]:
|
||||
rows[n.id] = _row(n, "reference")
|
||||
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
_WIKILINK_RE = re.compile(r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]')
|
||||
@@ -1071,6 +1118,22 @@ async def build_note_graph(
|
||||
edge_set.add(pair)
|
||||
edges.append({"source": n.id, "target": target_id, "type": "wikilink"})
|
||||
|
||||
# `#N` reference edges, read the way the renderer links them. Only between
|
||||
# records already on the graph: a reference to something outside it (another
|
||||
# project, a record the caller cannot read) has no node to end at.
|
||||
from grimoire.services.record_refs import referenced
|
||||
|
||||
on_graph = {n.id for n in notes}
|
||||
for n in notes:
|
||||
if not n.body:
|
||||
continue
|
||||
for target_id in sorted(referenced(n.body)["notes"]):
|
||||
if target_id in on_graph and target_id != n.id:
|
||||
pair = (n.id, target_id)
|
||||
if pair not in edge_set:
|
||||
edge_set.add(pair)
|
||||
edges.append({"source": n.id, "target": target_id, "type": "reference"})
|
||||
|
||||
# Build tag nodes + note→tag edges
|
||||
if include_shared_tags:
|
||||
tag_to_ids: dict[str, list[int]] = {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names.
|
||||
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names, and saying what a body links to.
|
||||
|
||||
THE DEFECT THIS EXISTS FOR
|
||||
|
||||
@@ -41,6 +41,7 @@ restores and internal writers that legitimately carry numbers from elsewhere.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
@@ -209,6 +210,128 @@ def _prev_word(before: str) -> str:
|
||||
return m.group(1).lower() if m else ""
|
||||
|
||||
|
||||
# ── References written into a record's prose ───────────────────────────────
|
||||
#
|
||||
# What a body, a work log or a plan names, read the way the web UI links it.
|
||||
# `frontend/src/utils/recordRefs.ts` holds the same patterns and the same word
|
||||
# list, and tests/test_record_ref_links.py reads that file and fails when its
|
||||
# patterns or words differ from these.
|
||||
#
|
||||
# Three id spaces, three forms:
|
||||
# `#N` a note, task, lesson or snippet (one sequence, the notes table)
|
||||
# `milestone N` a milestone — what `{{ref:milestone}}` renders as
|
||||
# `rule N` a rule; `preference N` too, since preferences are rules
|
||||
# A `#N` after a word that names another numbering ("PR #198", "rule #34",
|
||||
# "step #3") is not a note: `_OTHER_SPACE` above decides, exactly as it does for
|
||||
# the numbers an operator names in a message.
|
||||
|
||||
PROSE_REF_RE = re.compile(r"(?<![\w/])\b(milestone|rule|preference)\s+#?(\d+)\b", re.IGNORECASE)
|
||||
|
||||
# Fenced and inline code: a pasted log or a snippet of source names nothing.
|
||||
_CODE_RE = re.compile(r"```[\s\S]*?```|`[^`\n]+`")
|
||||
|
||||
|
||||
def referenced(*texts: str | None) -> dict[str, set[int]]:
|
||||
"""Every record these texts link to, by id space: notes, milestones, rules."""
|
||||
out: dict[str, set[int]] = {"notes": set(), "milestones": set(), "rules": set()}
|
||||
for text in texts:
|
||||
if not text:
|
||||
continue
|
||||
text = _CODE_RE.sub(" ", text)
|
||||
for m in PROSE_REF_RE.finditer(text):
|
||||
space = "milestones" if m.group(1).lower() == "milestone" else "rules"
|
||||
out[space].add(int(m.group(2)))
|
||||
for m in REF_RE.finditer(text):
|
||||
if _prev_word(text[:m.start()]) not in _OTHER_SPACE:
|
||||
out["notes"].add(int(m.group(1)))
|
||||
return out
|
||||
|
||||
|
||||
# How many references one resolve call answers. A long plan cites a few dozen;
|
||||
# past this the caller is listing, not rendering, and gets a 400 at the door.
|
||||
RESOLVE_LIMIT = 200
|
||||
|
||||
|
||||
async def resolve_refs(
|
||||
user_id: int,
|
||||
*,
|
||||
notes: Iterable[int] = (),
|
||||
milestones: Iterable[int] = (),
|
||||
rules: Iterable[int] = (),
|
||||
) -> dict[str, dict[int, dict]]:
|
||||
"""What each referenced id IS, for the records this user may read.
|
||||
|
||||
An id that is missing, trashed or not readable is simply absent, and the
|
||||
caller shows it as a reference that leads nowhere. The answer never says
|
||||
which of the three it was: "not shared with you" and "does not exist" must
|
||||
read the same, or the resolver becomes a way to probe other people's ids.
|
||||
|
||||
No pull is recorded. Hovering a link is not choosing to read the record;
|
||||
the view it opens records that, the same as any other way of arriving.
|
||||
"""
|
||||
from grimoire.models.milestone import Milestone
|
||||
from grimoire.services import rulebooks as rulebooks_svc
|
||||
from grimoire.services.access import can_read_project, readable_notes_clause
|
||||
|
||||
out: dict[str, dict[int, dict]] = {"notes": {}, "milestones": {}, "rules": {}}
|
||||
note_ids = sorted({int(i) for i in notes})
|
||||
milestone_ids = sorted({int(i) for i in milestones})
|
||||
rule_ids = sorted({int(i) for i in rules})
|
||||
|
||||
async with async_session() as session:
|
||||
if note_ids:
|
||||
rows = (await session.execute(
|
||||
select(Note).where(
|
||||
Note.id.in_(note_ids),
|
||||
Note.deleted_at.is_(None),
|
||||
readable_notes_clause(user_id),
|
||||
)
|
||||
)).scalars().all()
|
||||
for n in rows:
|
||||
out["notes"][n.id] = {
|
||||
"id": n.id,
|
||||
"title": n.title or "",
|
||||
"is_task": n.is_task,
|
||||
"note_type": n.note_type or "note",
|
||||
"status": n.status,
|
||||
"task_kind": n.task_kind if n.is_task else None,
|
||||
}
|
||||
if milestone_ids:
|
||||
rows = (await session.execute(
|
||||
select(Milestone).where(
|
||||
Milestone.id.in_(milestone_ids), Milestone.deleted_at.is_(None),
|
||||
)
|
||||
)).scalars().all()
|
||||
readable_projects: dict[int, bool] = {}
|
||||
for ms in rows:
|
||||
if ms.user_id != user_id:
|
||||
pid = ms.project_id
|
||||
if pid is None:
|
||||
continue
|
||||
if pid not in readable_projects:
|
||||
readable_projects[pid] = await can_read_project(user_id, pid)
|
||||
if not readable_projects[pid]:
|
||||
continue
|
||||
out["milestones"][ms.id] = {
|
||||
"id": ms.id,
|
||||
"title": ms.title or "",
|
||||
"project_id": ms.project_id,
|
||||
"status": ms.status,
|
||||
}
|
||||
|
||||
# One lookup per rule: readability runs through rulebook ownership and
|
||||
# project ownership, which `get_rule` already resolves. A body names a few.
|
||||
for rid in rule_ids:
|
||||
rule = await rulebooks_svc.get_rule(rid, user_id)
|
||||
if rule is not None:
|
||||
out["rules"][rule.id] = {
|
||||
"id": rule.id,
|
||||
"title": rule.title or "",
|
||||
"kind": getattr(rule, "kind", None) or "rule",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _next_word(after: str) -> str:
|
||||
m = _NEXT_WORD_RE.match(after)
|
||||
return m.group(1).lower() if m else ""
|
||||
|
||||
Reference in New Issue
Block a user