Files
pad/internal
xarmian c67c167c43 feat(backlinks): title-form wiki-links + rename cascade (Phase 2a) (#621)
* feat(backlinks): title-form wiki-links + rename cascade (Phase 2a)

Phase 2a of PLAN-1593 (TASK-1595). Extends the server-side wiki-link
reverse index from Phase 1's `[[REF-N]]` coverage to also handle
`[[Title]]` and `[[collection/Title]]`. Cross-workspace `[[ws::REF]]`
forms stay gated until TASK-1597 (Phase 2b) ships the request-
independent ACL helper.

What changed
- internal/links/extract.go: lift the Phase-1 emit gate for
  WikiLinkKindTitle; keep WikiLinkKindWorkspaceRef gated.
- internal/store/wiki_links.go: title branch in replaceWikiLinks
  (verbatim target_title storage + case-insensitive resolution),
  resolveTitleTx with full-key match first / `/`-split fallback
  (mirrors renderer order — Codex review caught the inverse on the
  planning round), cascadeTitleRename + resolveBrokenTitleLinks.
- internal/store/items.go: rename cascade fires in-tx on title
  change; create path flips pre-existing broken title rows.
- internal/store/migrations/062 + pgmigrations/041: one-shot
  `DELETE FROM item_wiki_links` so the startup backfill repopulates
  with the Phase 2a vocabulary.
- Tests cover title round-trip, case-insensitive resolution, broken-
  link persistence + later resolution, full rename cascade with
  content rewrite, collection-qualified form, full-key-beats-split
  precedence (regresses Codex finding #3), broken-row flip on rename,
  no-op rename, and self-reference filtering.

PLAN-1593 / TASK-1595.

* fix(backlinks): rename cascade preserves display aliases (Codex round 1)

Codex round 1 against PR #621 caught: the title-rename cascade
selects sources via target_item_id (correctly hitting all rows that
resolve to the renamed item — including aliased and mixed-case
shapes), but the literal `strings.ReplaceAll` rewrite step only
matched `[[Old Title]]` / `[[<slug>/Old Title]]`. Rows from
`[[Old Title|alias]]`, `[[old title]]` (mixed case), or
`[[<slug>/Old Title|alias]]` slipped past the rewrite; the trailing
replaceWikiLinks re-parse then saw the same body, failed to resolve
under the new title, and converted the row to broken — exactly the
regression the cascade exists to prevent.

Fix: new internal/links/RewriteWikiTitle helper handles all four
title-form shapes with case-insensitive title matching and verbatim
display-alias preservation. Cascade swaps from ReplaceAll to this
helper. Unit tests in links_test.go cover the matrix; integration
test in wiki_links_test.go regresses the original failure mode by
mixing all four shapes in one source and asserting all four stay
resolved after rename.

Known limitation documented in the helper: titles containing wiki-
link escape characters (`]`, `|`, `\`) — stored escaped in source
content — don't match the regex's literal old-title segment. Same
limitation exists in the legacy ReplaceTitle helper; promotable if
a real user hits it.

PLAN-1593 / TASK-1595.

* fix(backlinks): retarget qualified-fallback rows on literal-title arrival (Codex round 2)

Codex round 2 against PR #621 (P2): resolveBrokenTitleLinks only
flipped target_item_id IS NULL rows, missing the arrival-order case
where a literal `[[tasks/Setup]]` should win stage 1 over a row
previously resolved via stage 2 (qualified fallback to item "Setup"
in collection "tasks"). The index would stay stale until the source's
content was rewritten — a latent inconsistency between the persisted
backlink and what the renderer would actually show.

Fix: drop the IS NULL constraint on the stage-1 UPDATE. Stage 1
ALWAYS wins per the renderer's order at markdown.ts:541, so any row
with a matching literal title flips to the new item — including
rows currently pointing at a qualified-fallback target. Added a
target_item_id != ? guard so we don't churn rows that already point
at us. Stage 2 keeps the NULL constraint so already-resolved
qualified rows don't churn when another fallback candidate appears.

Regression test in wiki_links_test.go reproduces the exact scenario
Codex described: fallback resolves first, literal arrival steals the
row from the fallback target.

PLAN-1593 / TASK-1595.

* fix(backlinks): renderer parity for [[A|B]] + scope arrival retarget (Codex round 3)

Two findings from Codex round 3 against PR #621:

P1 — parser/renderer parity for [[A|B]] matching literal title "A|B".
The renderer (web/src/lib/utils/markdown.ts:516-525) tries the FULL
body as a title FIRST when a pipe is present, only falling through
to the split interpretation on miss. Our parseBody always split on
the first unescaped pipe, so an item literally titled "A|B" was
indexed as title="A" with display="B" — the index would miss
backlinks the UI shows, or point them at a different "A" item.

Fix: in replaceWikiLinks for title kind, when HasDisplay, try the
full body (Title+"|"+Display) as a title FIRST via resolveTitleTx;
on hit, store target_title=fullBody and drop the display override
(the display segment was actually part of the title). On miss, fall
back to the existing split-key interpretation. The cascade's
RewriteWikiTitle regex correctly handles both storage shapes via
QuoteMeta on the title.

P2 — stage-1 UPDATE was too aggressive after the round-2 fix. The
broad UPDATE (no IS NULL constraint) silently stole backlinks from
legitimately-resolved rows when a SECOND item was created/renamed
to the same title. Titles aren't unique, the renderer's
Array.find() is order-dependent, and silent churn is worse than
no-op stability.

Fix: split resolveBrokenTitleLinks into three updates:
  (1) Plain literal flip — NULL only.
  (2) Qualified literal flip — NULL only.
  (3) Literal-arrival retarget — gated on title containing `/`.
      Only fires for `[[<slug>/Title]]` rows, which are the only
      ones that COULD have been stage-2 qualified-fallback
      resolved. Rows with target_title='Foo' (no slash) can only
      have been stage-1 literal — we don't steal those.

Regression tests:
- TestWikiLinks_LiteralPipeInTitleResolves — `[[A|B]]` resolves to
  item literally titled "A|B".
- TestWikiLinks_LiteralPipeInTitleFallsThroughToSplit — `[[A|B]]`
  falls back to item "A" when no "A|B" item exists.
- TestWikiLinks_SecondItemSameTitleDoesNotStealBacklinks — adding a
  second "Foo" item doesn't redirect the existing backlink.

PLAN-1593 / TASK-1595.

* fix(backlinks): broken pipe-in-body rows keyed on full body (Codex round 4)

Codex round 4 against PR #621: when a source body `[[A|B]]` is
written before any matching item exists, the broken row was stored
with target_title="A" (the split key). If an item literally titled
"A|B" was later created, resolveBrokenTitleLinks looking for
target_title="A|B" couldn't find the row — index went stale while
the renderer's preferred full-body interpretation would correctly
resolve the link.

Fix: when nothing resolves AND a pipe was present (HasDisplay), key
the broken row on the FULL body (Title+"|"+Display) instead of the
split key. resolveBrokenTitleLinks then naturally finds it via the
literal-arrival path.

The remaining asymmetry — a broken row keyed on full body won't pick
up a future split-fallback resolution to a new item titled "A" — is
documented in the code as a v3-promotable limitation. The full-body
path is the renderer's PREFERRED interpretation (markdown.ts:516),
so prioritizing it is the right tradeoff in the rare case both
interpretations could apply.

Regression test in wiki_links_test.go reproduces the scenario:
source written first with `[[A|B]]`, item titled "A|B" created
later, backlink should resolve.

PLAN-1593 / TASK-1595.

* fix(backlinks): scope stage-3 retarget + cascade self-refs (Codex round 5)

Two findings from Codex round 5 against PR #621:

Finding 1 — stage-3 literal-arrival retarget could still steal
backlinks from a legitimate stage-1 literal-match row when a SECOND
item with the same slash-containing title is created. The previous
fix (round 3) gated stage-3 on title containing `/`, which let
through the qualified-fallback retarget case correctly but didn't
distinguish stage-1-resolved rows pointing at a literal twin from
stage-2-resolved rows pointing at the fallback target.

Fix: add an EXISTS check that scopes the flip to rows whose CURRENT
target has a title NOT matching ours. Stage-1 (literal) resolutions
point at items literally titled the same as the row's target_title;
stage-2 (qualified-fallback) resolutions point at items titled just
the trailing segment. The EXISTS clause picks out only the latter.

Finding 2 — self-references on the renamed item went stale on
title-only renames. The cascade's `s.id != renamedItemID` filter
excluded self, but items.go only re-indexes content when
input.Content != nil. So a title-only rename of an item whose body
mentions itself by its old title kept the body's now-broken
`[[Old Title]]` literal in place while the index still recorded a
"working" backlink — drift between renderer state and index state.

Fix: drop the self-exclusion from the cascade SELECT. RewriteWikiTitle
rewrites the renamed item's own content along with everyone else's;
GetBacklinks still hides self-links at query time, so the backlinks
panel behavior is unchanged.

Tests:
- TestWikiLinks_DuplicateSlashTitleNoTheft regresses Finding 1.
- TestWikiLinks_TitleRenameRewritesSelfReferences asserts Finding 2's
  new correct behavior (replaces the prior test that asserted the
  old buggy behavior).

PLAN-1593 / TASK-1595.

* fix(backlinks): ref→title fallback + reorder cascade self-ref (Codex round 6)

Two findings from Codex round 6 against PR #621:

Finding 1 — ref-shaped title fallback missing. parseBody returns
WikiLinkKindRef for `[[ISO-9001]]` (matches refPattern), but if no
ISO-9001 ref-item exists, the renderer falls through to legacy
title lookup (markdown.ts:513) and resolves to an item literally
titled "ISO-9001". The store inserted only a broken ref-kind row
with target_title=NULL, so GetBacklinks never surfaced the backlink
even when the renderer rendered it.

Fix: in replaceWikiLinks' WikiLinkKindRef branch, when resolveRefTx
misses, try resolveTitleTx on the same body. If title resolves,
INSERT as title-kind row with target_title=ref-shaped-body. The
rename cascade catches these correctly via target_kind='title' +
target_item_id. The asymmetry — a future ref-item creation can't
auto-retarget these title-stored rows — is documented as a v3
limitation.

Finding 2 — combined title+content update broke self-ref cascade.
The original order (main UPDATE → replaceWikiLinks(self) → cascade)
wiped self's `target_item_id=renamedItemID` row before cascade ran:
when input.Content contains `[[Old Title]]`, re-indexing self
resolved it as broken (target_item_id=NULL), so cascade's SELECT
missed self for the title+content path.

Fix: reorder so cascade runs BEFORE the self re-index — the
pre-existing wl rows are still intact at cascade time. The final
re-index re-reads items.content from the DB (since cascade may
have rewritten it in-band) rather than using *input.Content
directly; otherwise the re-index would undo the cascade's
self-ref rewrite.

Tests:
- TestWikiLinks_RefShapedFallsThroughToTitle — `[[ISO-9001]]`
  resolves to an item titled "ISO-9001".
- TestWikiLinks_TitleAndContentRenameCascadesSelfRef — combined
  title+content rename with self-ref in new content gets the
  self-ref rewritten by cascade.

PLAN-1593 / TASK-1595.

* fix(backlinks): ref+pipe→title parity, position-based cascade, scoped self-rewrite (Codex round 7)

Three intertwined fixes addressing Codex round 7 findings against
PR #621:

Finding 1 — ref→title fallback missed pipe-bodies. For
`[[ISO-9001|Spec]]`, renderer tries full-body title "ISO-9001|Spec"
BEFORE falling to bare "ISO-9001" (markdown.ts:516). Our
ref-fallback only tried bare. Extended ref-branch's fallback to
try full body first when HasDisplay, then bare — same order as
the title-branch's stage (a)/(b) pattern.

Finding 2 — cascade corrupted UNRELATED literal-pipe titles. Items
A "Old Title" and B "Old Title|alias" both referenced from one
source; renaming A previously triggered RewriteWikiTitle's regex
`(?i:Old Title)((?:\|...)?)` which matched BOTH A's `[[Old Title]]`
AND B's `[[Old Title|alias]]` — corrupting the B link.

Refactored cascadeTitleRename to be POSITION-BASED: SELECT each
individual wl row with its position + target_title (no longer
DISTINCT sources). Per-row, rewrite the bracket AT THAT EXACT
POSITION via new links.RewriteBracketAt helper. Process rows in
descending position order per source so earlier offsets don't
shift. Brackets whose wl row doesn't resolve to the renamed item
are never visited.

Scoped self-rewrite — title-only renames cascade self
(input.Content == nil); combined title+content renames EXCLUDE
self (input.Content != nil). User-supplied content is
authoritative; auto-rewriting their just-submitted brackets would
surprise them. Mirrors documents.go::updateLinksInTx, which also
leaves the renamed entity's own content alone. Codex round 6
finding 2 is fully addressed: title-only path still rewrites
self-refs, combined path respects user submission and the index
correctly records the bracket as broken (matching what the
renderer would render).

New links.RewriteBracketAt helper with full unit-test coverage:
plain/aliased/qualified/qualified+aliased shapes, case-insensitive
matching, slug-prefix preservation, full-body vs split-key target
disambiguation, out-of-bounds defensive guards. Integration test
TestWikiLinks_CascadeDoesNotCorruptLiteralPipeNeighbor reproduces
Codex round 7 finding 2's scenario.

PLAN-1593 / TASK-1595.

* fix(backlinks): retarget rows pointing at soft-deleted targets (Codex round 8)

Codex round 8 P2: resolveBrokenTitleLinks only considered
target_item_id IS NULL rows as eligible for flip. A row that
resolved to item A and then had A soft-deleted stayed pointing at
deleted A; creating a new item B titled the same as A wouldn't
flip the row, so GetBacklinks(B) missed the backlink the renderer
would actually show (renderer hides deleted-target links).

Fix: introduce a "broken-in-practice" predicate
  (target_item_id IS NULL
   OR NOT EXISTS (
       SELECT 1 FROM items t
       WHERE t.id = item_wiki_links.target_item_id
         AND t.deleted_at IS NULL
   ))
applied to stages 1 (plain literal flip) and 2 (qualified literal
flip). Stage 3 (slash-title literal-arrival retarget) already
considered "current target deleted" implicitly via its title-
mismatch EXISTS check.

Regression test in wiki_links_test.go covers the exact scenario:
A "Foo" resolves a backlink → A soft-deleted → B "Foo" created →
backlink flips to B.

Known limitation deferred to v3: the symmetric case (delete A
while B with same title already exists) doesn't fire any hook
that re-resolves the row. A dedicated DeleteItem hook would close
that gap; not blocking Phase 2a.

PLAN-1593 / TASK-1595.

* fix(backlinks): preserve title whitespace to match renderer (Codex round 9)

Codex round 9 P2: parseBody trimmed whitespace from the body BEFORE
deciding it was a title kind. The renderer doesn't trim before title
matching (markdown.ts:541-543) — `[[ Foo ]]` is matched against
items.title with the surrounding spaces intact, so an item titled
"Foo" wouldn't match. Trimming server-side created index entries
the UI couldn't click — backlinks showed in the panel for links
that the renderer rendered as broken.

Fix: keep an UNTRIMMED unescaped body for title-kind fallthrough,
and a trimmed copy only for ref / workspace_ref SHAPE detection
(refs are whitespace-free by construction, the renderer's
key.trim() at L503 is just typing forgiveness for the ref form).

Tests in extract_test.go:
- `[[ Foo ]]` emits title-kind with Title=" Foo " (whitespace preserved).
- `[[ TASK-5 ]]` still parses as ref (shape detection trims).
- `[[Project  Goals]]` (two spaces inside) preserves internal whitespace.

PLAN-1593 / TASK-1595.

* fix(backlinks): ref→title fallback uses raw untrimmed key (Codex round 10)

Codex round 10 P2: after round 9's title-kind whitespace fix, the
ref→title FALLBACK path still used canonical-trimmed link.Ref for
its title lookup. The renderer's fallback at markdown.ts:541-543
uses the UNTRIMMED key (no .trim() on the title-lookup path), so
`[[ TASK-5 ]]` falling through to title would search " TASK-5 "
(with whitespace) — an item literally titled " TASK-5 " resolves
in the UI but not in our index.

Fix: add a RawKey field to WikiLinkRef capturing the untrimmed
unescaped key for ref kinds. parseBody populates it alongside the
canonical Ref. replaceWikiLinks' ref→title fallback path uses
RawKey (with defensive fallback to Ref for old rows) when
constructing title candidates. Mirrors the renderer's untrimmed
title lookup across both bare and pipe forms.

Regression test in wiki_links_test.go covers the exact scenario:
item titled " TASK-5 " (with whitespace), source body `[[ TASK-5 ]]`,
backlink resolves via the untrimmed ref→title fallback.

PLAN-1593 / TASK-1595.
2026-05-24 12:01:05 -04:00
..
2026-03-26 01:52:36 +00:00