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

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:
2026-11-22 14:15:15 -05:00
co-authored by Claude Opus 5.5
parent 6be44013bb
commit 38bc25a2b7
24 changed files with 846 additions and 48 deletions
+106
View File
@@ -0,0 +1,106 @@
"""Real-Postgres proof that a reference resolves only to what the reader may open, and that backlinks follow `#N`.
What mocks cannot show: the access clause applied in SQL to a shared project,
the LIKE prefilter not admitting `#12` as a link to 1, and a citation in a work
log reaching the cited record's backlinks.
"""
import pytest
import pytest_asyncio
from grimoire.models import async_session
from grimoire.models.milestone import Milestone
from grimoire.models.note import Note
from grimoire.models.project import Project
from grimoire.models.share import ProjectShare
from grimoire.models.task_log import TaskLog
from grimoire.services.notes import get_backlinks
from grimoire.services.record_refs import resolve_refs
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine", "_no_embedding")]
@pytest_asyncio.fixture
async def world():
async with async_session() as s:
owner = await ensure_user(s, "ref_links_owner")
reader = await ensure_user(s, "ref_links_reader")
stranger = await ensure_user(s, "ref_links_stranger")
shared = Project(user_id=owner.id, title="Shared project")
private = Project(user_id=owner.id, title="Private project")
s.add_all([shared, private])
await s.flush()
s.add(ProjectShare(project_id=shared.id, shared_with_user_id=reader.id,
permission="viewer", invited_by=owner.id))
target = Note(user_id=owner.id, project_id=shared.id, title="Target", body="")
hidden = Note(user_id=owner.id, project_id=private.id, title="Hidden", body="")
lesson = Note(user_id=owner.id, project_id=shared.id, title="A lesson",
body="", note_type="lesson")
ms_shared = Milestone(user_id=owner.id, project_id=shared.id, title="Shared plan")
ms_private = Milestone(user_id=owner.id, project_id=private.id, title="Private plan")
s.add_all([target, hidden, lesson, ms_shared, ms_private])
await s.flush()
ids = {
"owner": owner.id, "reader": reader.id, "stranger": stranger.id,
"shared": shared.id, "target": target.id, "hidden": hidden.id,
"lesson": lesson.id, "ms_shared": ms_shared.id, "ms_private": ms_private.id,
}
await s.commit()
return ids
async def test_the_owner_resolves_every_kind_with_its_route_fields(world):
out = await resolve_refs(
world["owner"],
notes=[world["target"], world["lesson"], world["hidden"]],
milestones=[world["ms_shared"], world["ms_private"]],
)
assert set(out["notes"]) == {world["target"], world["lesson"], world["hidden"]}
assert out["notes"][world["lesson"]]["note_type"] == "lesson"
assert out["notes"][world["target"]]["is_task"] is False
assert out["milestones"][world["ms_shared"]]["project_id"] == world["shared"]
async def test_a_collaborator_resolves_the_shared_project_and_nothing_else(world):
out = await resolve_refs(
world["reader"],
notes=[world["target"], world["hidden"]],
milestones=[world["ms_shared"], world["ms_private"]],
)
assert set(out["notes"]) == {world["target"]}
assert set(out["milestones"]) == {world["ms_shared"]}
async def test_unreadable_and_nonexistent_ids_read_the_same(world):
"""Absent either way, so the resolver cannot be used to probe for ids."""
out = await resolve_refs(world["stranger"], notes=[world["target"], 2_000_000_000])
assert out["notes"] == {}
async def test_backlinks_follow_references_in_bodies_and_work_logs(world):
t = world["target"]
async with async_session() as s:
citing = Note(user_id=world["owner"], project_id=world["shared"],
title="Cites it", body=f"Builds on #{t}.")
logged = Note(user_id=world["owner"], project_id=world["shared"],
title="Logs it", body="", status="todo")
other_space = Note(user_id=world["owner"], project_id=world["shared"],
title="Other numbering", body=f"See PR #{t}.")
longer = Note(user_id=world["owner"], project_id=world["shared"],
title="Longer id", body=f"See #{t}0.")
s.add_all([citing, logged, other_space, longer])
await s.flush()
s.add(TaskLog(task_id=logged.id, user_id=world["owner"], content=f"Fixed with #{t} in mind."))
ids = {"citing": citing.id, "logged": logged.id}
await s.commit()
rows = await get_backlinks(world["owner"], t)
by_id = {r["id"]: r for r in rows}
assert set(by_id) == {ids["citing"], ids["logged"]}
assert by_id[ids["citing"]]["via"] == "reference"
assert by_id[ids["logged"]]["is_task"] is True
# The collaborator sees the same backlinks, since every record is in the
# project shared with them; a stranger cannot open the target at all.
assert {r["id"] for r in await get_backlinks(world["reader"], t)} == set(by_id)
assert await get_backlinks(world["stranger"], t) == []
+105
View File
@@ -0,0 +1,105 @@
"""What a body cites, and that the web UI and the backend read it the same way.
A `#N` in prose names a note, task, lesson or snippet; `milestone N` and
`rule N` name records in their own id spaces. The backend reads these for
backlinks and graph edges (services/record_refs.referenced); the web UI links
them (frontend/src/utils/recordRefs.ts). A token made only of digits is never a
tag, on either side.
There is no frontend test runner, so the TS half is held to the Python half by
reading its source: the two patterns and the word list must be the same text.
"""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from grimoire.services import record_refs
from grimoire.services.record_refs import referenced
from grimoire.utils.tags import extract_tags
FRONTEND = Path(__file__).resolve().parents[1] / "frontend" / "src"
REFS_TS = FRONTEND / "utils" / "recordRefs.ts"
TAGS_TS = FRONTEND / "utils" / "tags.ts"
def _refs(notes=(), milestones=(), rules=()):
return {"notes": set(notes), "milestones": set(milestones), "rules": set(rules)}
@pytest.mark.parametrize(("text", "expected"), [
("see #123", _refs(notes={123})),
("steps #5110–#5119 shipped", _refs(notes={5110, 5119})),
("(#4286) and #4290.", _refs(notes={4286, 4290})),
("#v2 is a tag", _refs()),
("a colour #123abc", _refs()),
("inline `#12` is code", _refs()),
("```\nlog line #77\n```\nafter #78", _refs(notes={78})),
("PR #198 and run #4", _refs()),
("rule #34 and rule 10", _refs(rules={34, 10})),
("preference 12 holds", _refs(rules={12})),
("part of milestone 639", _refs(milestones={639})),
('Part of milestone 7 "Ship it"; next is #9 "Step two".', _refs(notes={9}, milestones={7})),
("an entity &#123; and a path a/#9", _refs()),
("", _refs()),
])
def test_referenced_reads_what_the_ui_links(text, expected):
assert referenced(text) == expected
def test_referenced_ignores_none_among_texts():
assert referenced(None, "#5", None) == _refs(notes={5})
@pytest.mark.parametrize(("body", "tags"), [
("#123", []),
("cites (#4286)", []),
("#5110–#5119", []),
("#v2 #123abc #2fa", ["123abc", "2fa", "v2"]),
("#123-notes and #12/x", ["12/x", "123-notes"]),
("#python #review", ["python", "review"]),
])
def test_a_token_of_digits_alone_is_never_a_tag(body, tags):
assert extract_tags(body) == tags
# ── The TS reader is the same text as the Python one ───────────────────────
def _ts_regex(src: str, name: str) -> str:
m = re.search(rf"export const {name} = /(.+?)/[gimsuy]*;", src)
assert m, f"{name} is no longer a regex literal in {REFS_TS.name}"
return m.group(1)
def test_the_ui_reads_note_references_with_the_backend_pattern():
src = REFS_TS.read_text()
assert _ts_regex(src, "NOTE_REF_RE") == record_refs.REF_RE.pattern
def test_the_ui_reads_milestone_and_rule_references_with_the_backend_pattern():
src = REFS_TS.read_text()
assert _ts_regex(src, "PROSE_REF_RE") == record_refs.PROSE_REF_RE.pattern
# Python compiles it IGNORECASE; the literal must carry `i` too.
assert re.search(r"export const PROSE_REF_RE = /.+?/[gmsuy]*i[gmsuy]*;", src)
assert record_refs.PROSE_REF_RE.flags & re.IGNORECASE
def test_the_ui_skips_the_same_other_numberings():
src = REFS_TS.read_text()
m = re.search(r"export const OTHER_SPACE: readonly string\[\] = \[(.*?)\];", src, re.S)
assert m, f"OTHER_SPACE is no longer a string-array literal in {REFS_TS.name}"
words = set(re.findall(r'"([a-z]+)"', m.group(1)))
assert words == set(record_refs._OTHER_SPACE)
def test_both_tag_patterns_leave_digits_alone_to_the_reference_reader():
from grimoire.utils import tags as tags_py
guard = r"#(?!\d+(?![\w/-]))"
assert guard in tags_py._TAG_RE.pattern
ts = TAGS_TS.read_text()
m = re.search(r"export const TAG_RE = /(.+?)/g;", ts)
assert m, f"TAG_RE is no longer a regex literal in {TAGS_TS.name}"
assert guard in m.group(1)