From 173547a17a97707f681415821f03ba4a7377ab7e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Sun, 19 Apr 2026 22:59:38 +0800 Subject: [PATCH] feat: Refactor cross-link injection logic for wiki pages - Simplified the `InjectCrossLinks` and `injectCrossLinks` methods by utilizing a shared `linkifyContent` function, ensuring consistent handling of code blocks, existing links, and word boundaries. - Replaced manual reference collection and sorting with a dedicated `collectLinkRefs` function to streamline the process of gathering link references from wiki pages. - Enhanced the overall readability and maintainability of the code by removing redundant structures and logic. These changes improve the efficiency and clarity of the cross-linking functionality within the wiki service, contributing to a more robust content management system. --- internal/application/service/wiki_ingest.go | 113 +--- internal/application/service/wiki_linkify.go | 565 ++++++++++++++++++ .../application/service/wiki_linkify_test.go | 285 +++++++++ internal/application/service/wiki_page.go | 63 +- 4 files changed, 891 insertions(+), 135 deletions(-) create mode 100644 internal/application/service/wiki_linkify.go create mode 100644 internal/application/service/wiki_linkify_test.go diff --git a/internal/application/service/wiki_ingest.go b/internal/application/service/wiki_ingest.go index 1b8a2083..3fbf8192 100644 --- a/internal/application/service/wiki_ingest.go +++ b/internal/application/service/wiki_ingest.go @@ -412,49 +412,23 @@ func (s *wikiIngestService) cleanDeadLinks(ctx context.Context, kbID string) { // injectCrossLinks scans affected pages and injects [[wiki-links]] for mentions // of other wiki page titles in the content. Pure text replacement, no LLM call. // Processes entity/concept/synthesis/comparison and summary pages (not index/log). +// +// The actual matching is delegated to linkifyContent, which handles code-block +// and existing-link exclusions plus ASCII word-boundary checks. func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string) { - // Build a title→slug lookup from ALL pages in this KB allPages, err := s.wikiService.ListAllPages(ctx, kbID) if err != nil || len(allPages) < 2 { return } - type pageRef struct { - slug string - matchText string - } - var allRefs []pageRef - for _, p := range allPages { - if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { - continue - } - if p.Title != "" { - allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: p.Title}) - } - for _, alias := range p.Aliases { - if alias != "" { - allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: alias}) - } - } - } - if len(allRefs) == 0 { + refs := collectLinkRefs(allPages) + if len(refs) == 0 { return } - // Sort by title length descending — match longer names first to avoid - // partial matches (e.g. "北京邮电大学" before "北京") - for i := 0; i < len(allRefs); i++ { - for j := i + 1; j < len(allRefs); j++ { - if len([]rune(allRefs[j].matchText)) > len([]rune(allRefs[i].matchText)) { - allRefs[i], allRefs[j] = allRefs[j], allRefs[i] - } - } - } - - // Process only the pages we just created/updated affectedSet := make(map[string]bool, len(affectedSlugs)) - for _, s := range affectedSlugs { - affectedSet[s] = true + for _, slug := range affectedSlugs { + affectedSet[slug] = true } var updated int @@ -462,36 +436,20 @@ func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, a if !affectedSet[p.Slug] { continue } - // Skip system pages (index, log). We allow summary to be processed so it gets links to other KB entities. if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { continue } - content := p.Content - changed := false - - for _, ref := range allRefs { - if ref.slug == p.Slug { - continue - } - // Skip if already linked with this slug (either [[slug]] or [[slug|...]]) - if strings.Contains(content, "[["+ref.slug+"|") || strings.Contains(content, "[["+ref.slug+"]]") { - continue - } - if strings.Contains(content, ref.matchText) { - content = replaceFirstOutsideLinks(content, ref.matchText, "[["+ref.slug+"|"+ref.matchText+"]]") - changed = true - } + newContent, changed := linkifyContent(p.Content, refs, p.Slug) + if !changed { + continue } - - if changed { - p.Content = content - if _, err := s.wikiService.UpdatePage(ctx, p); err != nil { - logger.Warnf(ctx, "wiki ingest: cross-link injection failed for %s: %v", p.Slug, err) - } else { - updated++ - } + p.Content = newContent + if _, err := s.wikiService.UpdatePage(ctx, p); err != nil { + logger.Warnf(ctx, "wiki ingest: cross-link injection failed for %s: %v", p.Slug, err) + continue } + updated++ } if updated > 0 { @@ -499,37 +457,24 @@ func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, a } } -// replaceFirstOutsideLinks replaces the first occurrence of `old` with `new` in s, -// but only if it's not already inside a [[...]] wiki link. -func replaceFirstOutsideLinks(s, old, newStr string) string { - idx := 0 - for { - pos := strings.Index(s[idx:], old) - if pos < 0 { - return s // not found +// collectLinkRefs flattens (title + aliases) of all non-system pages into a +// single linkRef slice suitable for linkifyContent. +func collectLinkRefs(pages []*types.WikiPage) []linkRef { + refs := make([]linkRef, 0, len(pages)*2) + for _, p := range pages { + if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { + continue } - absPos := idx + pos - - // Check if this occurrence is inside a [[ ... ]] link - // Look backwards for [[ without encountering ]] - insideLink := false - for i := absPos - 1; i >= 0 && i >= absPos-200; i-- { - if i > 0 && s[i-1:i+1] == "]]" { - break // closed link before us - } - if i > 0 && s[i-1:i+1] == "[[" { - insideLink = true - break + if p.Title != "" { + refs = append(refs, linkRef{slug: p.Slug, matchText: p.Title}) + } + for _, alias := range p.Aliases { + if alias != "" { + refs = append(refs, linkRef{slug: p.Slug, matchText: alias}) } } - - if !insideLink { - return s[:absPos] + newStr + s[absPos+len(old):] - } - - // Skip this match, try next - idx = absPos + len(old) } + return refs } // getExistingPageSlugsForKnowledge returns all page slugs that currently reference diff --git a/internal/application/service/wiki_linkify.go b/internal/application/service/wiki_linkify.go new file mode 100644 index 00000000..0f9d62e1 --- /dev/null +++ b/internal/application/service/wiki_linkify.go @@ -0,0 +1,565 @@ +package service + +import ( + "sort" + "strings" + "unicode" + "unicode/utf8" +) + +// linkRef is a single (slug, matchText) candidate for cross-link injection. +type linkRef struct { + slug string + matchText string +} + +// span is a half-open byte range [start, end) inside the content that must not +// be touched by linkification. It covers fenced code blocks, inline code, +// existing [[...]] wiki links, markdown links [text](url), and image +// ![alt](url) forms. +type span struct { + start int + end int +} + +// linkifyContent injects [[slug|matchText]] cross-links into content for each +// ref, skipping occurrences that fall inside code or existing links and +// requiring word boundaries for ASCII-letter matchTexts. +// +// For every ref, at most the FIRST eligible occurrence is wrapped. Refs that +// are already linked to their slug (either [[slug]] or [[slug|...]]) are +// skipped entirely. Refs pointing at selfSlug are skipped. +// +// Returns the possibly-updated content and a bool indicating whether any +// change was made. The input ref slice is not mutated. +func linkifyContent(content string, refs []linkRef, selfSlug string) (string, bool) { + if content == "" || len(refs) == 0 { + return content, false + } + + // Work on a local copy sorted by matchText length (rune count) descending so + // longer names win over their substrings. + sorted := make([]linkRef, 0, len(refs)) + for _, r := range refs { + if r.slug == "" || r.matchText == "" { + continue + } + if r.slug == selfSlug { + continue + } + sorted = append(sorted, r) + } + sort.SliceStable(sorted, func(i, j int) bool { + return utf8.RuneCountInString(sorted[i].matchText) > + utf8.RuneCountInString(sorted[j].matchText) + }) + + forbidden, used := computeForbiddenSpans(content) + changed := false + + for _, ref := range sorted { + // Skip if the ref's slug is already wired up anywhere in content. + if _, ok := used[ref.slug]; ok { + continue + } + pos := findFirstSafeMatch(content, ref.matchText, forbidden) + if pos < 0 { + continue + } + replacement := "[[" + ref.slug + "|" + ref.matchText + "]]" + content = content[:pos] + replacement + content[pos+len(ref.matchText):] + // Shift / extend the forbidden spans to reflect the edit so subsequent + // refs don't nest a link inside the newly created [[...]]. + delta := len(replacement) - len(ref.matchText) + forbidden = shiftSpansAfter(forbidden, pos, delta) + forbidden = append(forbidden, span{start: pos, end: pos + len(replacement)}) + sortSpans(forbidden) + used[ref.slug] = struct{}{} + changed = true + } + + return content, changed +} + +// findFirstSafeMatch returns the byte offset of the first occurrence of needle +// in haystack that (a) doesn't fall inside any forbidden span and (b) for +// ASCII-letter needles is not adjacent to other word characters. +// Returns -1 if no such occurrence exists. +func findFirstSafeMatch(haystack, needle string, forbidden []span) int { + if needle == "" { + return -1 + } + needsBoundary := hasASCIILetterEdge(needle) + + start := 0 + for start <= len(haystack)-len(needle) { + rel := strings.Index(haystack[start:], needle) + if rel < 0 { + return -1 + } + pos := start + rel + end := pos + len(needle) + + if spanContains(forbidden, pos, end) { + start = pos + 1 + continue + } + if needsBoundary && !hasWordBoundary(haystack, pos, end) { + start = pos + 1 + continue + } + return pos + } + return -1 +} + +// hasASCIILetterEdge reports whether the needle starts or ends with an ASCII +// letter/digit. Only such needles need word-boundary checks — pure CJK or +// punctuation-led matchText doesn't have a word-boundary concept. +func hasASCIILetterEdge(s string) bool { + if s == "" { + return false + } + first, _ := utf8.DecodeRuneInString(s) + last, _ := utf8.DecodeLastRuneInString(s) + return isASCIIWordRune(first) || isASCIIWordRune(last) +} + +func isASCIIWordRune(r rune) bool { + if r > unicode.MaxASCII { + return false + } + return r == '_' || (r >= '0' && r <= '9') || + (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') +} + +// hasWordBoundary checks that the characters immediately before pos and at end +// are not ASCII word runes (letters/digits/underscore). Non-ASCII runes (e.g. +// CJK) are treated as boundaries so "北京" embedded in "北京邮电大学" still +// matches — length-descending ordering handles that conflict separately. +func hasWordBoundary(s string, pos, end int) bool { + if pos > 0 { + r, _ := utf8.DecodeLastRuneInString(s[:pos]) + if isASCIIWordRune(r) { + return false + } + } + if end < len(s) { + r, _ := utf8.DecodeRuneInString(s[end:]) + if isASCIIWordRune(r) { + return false + } + } + return true +} + +// spanContains reports whether any span overlaps [pos, end). +func spanContains(spans []span, pos, end int) bool { + for _, sp := range spans { + if pos < sp.end && end > sp.start { + return true + } + } + return false +} + +func shiftSpansAfter(spans []span, pivot, delta int) []span { + if delta == 0 { + return spans + } + out := make([]span, len(spans)) + for i, sp := range spans { + if sp.start >= pivot { + sp.start += delta + sp.end += delta + } + out[i] = sp + } + return out +} + +func sortSpans(spans []span) { + sort.Slice(spans, func(i, j int) bool { + if spans[i].start != spans[j].start { + return spans[i].start < spans[j].start + } + return spans[i].end < spans[j].end + }) +} + +// computeForbiddenSpans returns byte ranges in s that must be left untouched +// by cross-link injection, plus the set of wiki-link slugs already referenced +// in content so callers can skip already-linked refs without a second scan. +// +// Covered forbidden regions: +// - fenced code blocks delimited by ``` or ~~~ +// - inline code delimited by matching ` runs +// - existing [[slug|...]] / [[slug]] wiki links +// - inline markdown links [text](url) and images ![alt](url) +// - full reference-style links [text][label] +// - reference link definitions: lines of the form [label]: url ... +// - autolinks +func computeForbiddenSpans(s string) ([]span, map[string]struct{}) { + spans := make([]span, 0, 8) + used := make(map[string]struct{}) + i := 0 + n := len(s) + + // Pass 1: reference link definitions. These live on their own line and the + // main structural pass below would otherwise treat `[label]` as a dangling + // open bracket. Recording them up-front keeps both branches simple. + for _, sp := range scanReferenceDefinitions(s) { + spans = append(spans, sp) + } + + for i < n { + // Fenced code block: line starts with ``` or ~~~ + if isFenceStart(s, i) { + fenceLen, fenceCh := fenceRun(s, i) + end := findFenceEnd(s, i+fenceLen, fenceCh, fenceLen) + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + + c := s[i] + switch c { + case '`': + // inline code: count backticks, find matching closing run of same length + run := 1 + for i+run < n && s[i+run] == '`' { + run++ + } + closeIdx := findInlineCodeClose(s, i+run, run) + if closeIdx < 0 { + i += run + continue + } + spans = append(spans, span{start: i, end: closeIdx + run}) + i = closeIdx + run + case '[': + // [[slug...]] wiki link — record the slug in `used` + if i+1 < n && s[i+1] == '[' { + if close := strings.Index(s[i+2:], "]]"); close >= 0 { + end := i + 2 + close + 2 + inner := s[i+2 : i+2+close] + if slug := extractWikiSlug(inner); slug != "" { + used[slug] = struct{}{} + } + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + } + // [text](url) inline markdown link + if end, ok := matchMarkdownLink(s, i); ok { + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + // [text][label] reference-style link + if end, ok := matchReferenceStyleLink(s, i); ok { + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + i++ + case '!': + // ![alt](url) image + if i+1 < n && s[i+1] == '[' { + if end, ok := matchMarkdownLink(s, i+1); ok { + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + if end, ok := matchReferenceStyleLink(s, i+1); ok { + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + } + i++ + case '<': + if end, ok := matchAutolink(s, i); ok { + spans = append(spans, span{start: i, end: end}) + i = end + continue + } + i++ + default: + i++ + } + } + + sortSpans(spans) + return spans, used +} + +// extractWikiSlug parses the inner text of [[...]] and returns the slug part. +// For [[slug|display]] returns "slug"; for [[slug]] returns the whole inner +// text (trimmed). Returns "" if the inner text contains whitespace that would +// make it an unlikely real slug. +func extractWikiSlug(inner string) string { + if pipe := strings.IndexByte(inner, '|'); pipe >= 0 { + inner = inner[:pipe] + } + inner = strings.TrimSpace(inner) + if inner == "" { + return "" + } + return inner +} + +// matchReferenceStyleLink matches `[text][label]` starting at `[` and returns +// the byte offset just past the closing `]`. The text and label portions must +// not span multiple lines and must both be bracket-balanced. +func matchReferenceStyleLink(s string, i int) (int, bool) { + if i >= len(s) || s[i] != '[' { + return 0, false + } + // First `[text]` + textEnd, ok := findClosingBracket(s, i) + if !ok { + return 0, false + } + if textEnd+1 >= len(s) || s[textEnd+1] != '[' { + return 0, false + } + // Second `[label]` + labelEnd, ok := findClosingBracket(s, textEnd+1) + if !ok { + return 0, false + } + return labelEnd + 1, true +} + +// findClosingBracket returns the byte offset of the matching `]` for the `[` +// at position i, honoring `\[` / `\]` escapes and giving up on newlines. +func findClosingBracket(s string, i int) (int, bool) { + if i >= len(s) || s[i] != '[' { + return 0, false + } + depth := 1 + j := i + 1 + for j < len(s) { + switch s[j] { + case '\\': + if j+1 < len(s) { + j += 2 + continue + } + case '[': + depth++ + case ']': + depth-- + if depth == 0 { + return j, true + } + case '\n': + return 0, false + } + j++ + } + return 0, false +} + +// scanReferenceDefinitions finds all `[label]: url ...` definition lines and +// returns their byte ranges (including the trailing newline if present). +// Only lines whose first non-space character is `[` are considered, matching +// CommonMark's rule that definitions may be indented up to 3 spaces. +func scanReferenceDefinitions(s string) []span { + var out []span + lineStart := 0 + for lineStart < len(s) { + nl := strings.IndexByte(s[lineStart:], '\n') + var lineEnd int + if nl < 0 { + lineEnd = len(s) + } else { + lineEnd = lineStart + nl + 1 // include trailing \n + } + + // Measure leading indent (up to 3 spaces per CommonMark) + indent := 0 + for indent < 3 && lineStart+indent < lineEnd && s[lineStart+indent] == ' ' { + indent++ + } + start := lineStart + indent + + if start < lineEnd && s[start] == '[' { + labelEnd, ok := findClosingBracket(s, start) + if ok && labelEnd+1 < lineEnd && s[labelEnd+1] == ':' { + // It's a reference definition; guard region covers the whole line. + out = append(out, span{start: lineStart, end: lineEnd}) + } + } + + lineStart = lineEnd + } + return out +} + +// isFenceStart reports whether index i is at the start of a line and begins a +// fence run (``` or ~~~, three or more). +func isFenceStart(s string, i int) bool { + if i > 0 && s[i-1] != '\n' { + return false + } + if i+2 >= len(s) { + return false + } + c := s[i] + if c != '`' && c != '~' { + return false + } + return s[i+1] == c && s[i+2] == c +} + +func fenceRun(s string, i int) (int, byte) { + c := s[i] + j := i + for j < len(s) && s[j] == c { + j++ + } + return j - i, c +} + +// findFenceEnd returns the byte offset just past the closing fence, or len(s) +// if no close is found. +func findFenceEnd(s string, start int, ch byte, minLen int) int { + // Advance to next line + nl := strings.IndexByte(s[start:], '\n') + if nl < 0 { + return len(s) + } + pos := start + nl + 1 + for pos < len(s) { + if s[pos] == ch { + runLen, _ := fenceRun(s, pos) + if runLen >= minLen { + // Close must be at start of line (we're past a newline already). + // Skip trailing chars to end of line. + endLine := strings.IndexByte(s[pos:], '\n') + if endLine < 0 { + return len(s) + } + return pos + endLine + 1 + } + } + nl := strings.IndexByte(s[pos:], '\n') + if nl < 0 { + return len(s) + } + pos += nl + 1 + } + return len(s) +} + +// findInlineCodeClose returns the byte offset of the start of a closing +// backtick run of exactly runLen, or -1 if none. +func findInlineCodeClose(s string, start, runLen int) int { + i := start + for i < len(s) { + // newlines do not terminate inline code in CommonMark, but we stop at + // a double newline (paragraph break) to avoid runaway spans. + if i+1 < len(s) && s[i] == '\n' && s[i+1] == '\n' { + return -1 + } + if s[i] == '`' { + j := i + for j < len(s) && s[j] == '`' { + j++ + } + if j-i == runLen { + return i + } + i = j + continue + } + i++ + } + return -1 +} + +// matchMarkdownLink matches [text](url) starting at i where s[i] == '['. +// Returns the byte offset just past the closing ')' and true on match. +func matchMarkdownLink(s string, i int) (int, bool) { + if i >= len(s) || s[i] != '[' { + return 0, false + } + // Find ']' respecting balanced [[ ]] inside (rare) + depth := 1 + j := i + 1 + for j < len(s) && depth > 0 { + switch s[j] { + case '\\': + if j+1 < len(s) { + j += 2 + continue + } + case '[': + depth++ + case ']': + depth-- + // depth==0 is handled by the post-switch check below, which breaks + // out of the for loop (switch-local break would only exit the switch) + case '\n': + // markdown link text can't span many newlines; give up to avoid + // runaway spans + return 0, false + } + if depth == 0 { + break + } + j++ + } + if j >= len(s) || s[j] != ']' { + return 0, false + } + if j+1 >= len(s) || s[j+1] != '(' { + return 0, false + } + // Find matching ')' with shallow paren nesting. + k := j + 2 + parenDepth := 1 + for k < len(s) && parenDepth > 0 { + switch s[k] { + case '\\': + if k+1 < len(s) { + k += 2 + continue + } + case '(': + parenDepth++ + case ')': + parenDepth-- + if parenDepth == 0 { + return k + 1, true + } + case '\n': + return 0, false + } + k++ + } + return 0, false +} + +// matchAutolink matches starting at i where s[i] == '<'. +func matchAutolink(s string, i int) (int, bool) { + if i >= len(s) || s[i] != '<' { + return 0, false + } + close := strings.IndexByte(s[i+1:], '>') + if close < 0 { + return 0, false + } + inner := s[i+1 : i+1+close] + if len(inner) == 0 || strings.ContainsAny(inner, " \t\n") { + return 0, false + } + // Require scheme://host or mailto: style + if !strings.Contains(inner, "://") && !strings.HasPrefix(inner, "mailto:") { + return 0, false + } + return i + 1 + close + 1, true +} diff --git a/internal/application/service/wiki_linkify_test.go b/internal/application/service/wiki_linkify_test.go new file mode 100644 index 00000000..2d81f08c --- /dev/null +++ b/internal/application/service/wiki_linkify_test.go @@ -0,0 +1,285 @@ +package service + +import ( + "strings" + "testing" +) + +func TestLinkifyContent_BasicCJK(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + got, changed := linkifyContent("我住在北京市", refs, "") + if !changed { + t.Fatalf("expected change") + } + want := "我住在[[beijing|北京]]市" + if got != want { + t.Fatalf("got %q, want %q", got, want) + } +} + +func TestLinkifyContent_LongerNameWinsOverSubstring(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + {slug: "bupt", matchText: "北京邮电大学"}, + } + got, changed := linkifyContent("我就读于北京邮电大学", refs, "") + if !changed { + t.Fatalf("expected change") + } + // The longer match should win; "北京" must not swallow the prefix. + if !strings.Contains(got, "[[bupt|北京邮电大学]]") { + t.Fatalf("longer match not preferred: %q", got) + } + if strings.Contains(got, "[[beijing|") { + t.Fatalf("shorter substring should not have linked: %q", got) + } +} + +func TestLinkifyContent_ASCIIWordBoundary(t *testing.T) { + refs := []linkRef{ + {slug: "ai", matchText: "AI"}, + } + // Should NOT match "AI" inside "TRAINING" or "PAINT". + in := "TRAINING and PAINT are words." + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not change, got %q", got) + } + + // SHOULD match standalone "AI". + in2 := "AI is cool." + got2, changed2 := linkifyContent(in2, refs, "") + if !changed2 { + t.Fatalf("expected change, got %q", got2) + } + if !strings.HasPrefix(got2, "[[ai|AI]] ") { + t.Fatalf("standalone AI should link: %q", got2) + } +} + +func TestLinkifyContent_SkipsExistingWikiLink(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + // Already linked — should not double-wrap. + in := "我住在[[beijing|北京]]市" + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not change already-linked content: %q", got) + } +} + +func TestLinkifyContent_SkipsInsideFencedCode(t *testing.T) { + refs := []linkRef{ + {slug: "go", matchText: "Go"}, + } + in := "Prose mentions Go.\n\n```go\nfunc Go() {}\n```\nAfter code." + got, _ := linkifyContent(in, refs, "") + // The prose occurrence should link. + if !strings.Contains(got, "Prose mentions [[go|Go]].") { + t.Fatalf("prose occurrence not linked: %q", got) + } + // The occurrence inside the fenced block must be untouched. Since linkifyContent + // only wraps the first eligible match, the code-block one is skipped anyway, + // but double-check that no link was injected inside the code fence. + if strings.Contains(got, "func [[go|Go]]") { + t.Fatalf("should not link inside fenced code: %q", got) + } +} + +func TestLinkifyContent_SkipsInsideInlineCode(t *testing.T) { + refs := []linkRef{ + {slug: "foo", matchText: "Foo"}, + } + // Only occurrence is inside `Foo` — must NOT be linked. + in := "Use the `Foo` type." + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not link inside inline code: %q", got) + } + + // Second case: prose before the inline code — should link the prose one. + in2 := "Foo is a type. Use `Foo` here." + got2, changed2 := linkifyContent(in2, refs, "") + if !changed2 { + t.Fatalf("expected change, got %q", got2) + } + if !strings.HasPrefix(got2, "[[foo|Foo]] is") { + t.Fatalf("prose occurrence not linked: %q", got2) + } + if strings.Contains(got2, "`[[foo|Foo]]`") { + t.Fatalf("inline code occurrence should not be linked: %q", got2) + } +} + +func TestLinkifyContent_SkipsInsideMarkdownLink(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + // Occurrence inside [text](url) should be skipped. + in := "参见 [北京](https://example.com/beijing)" + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not link inside markdown link text: %q", got) + } +} + +func TestLinkifyContent_OnlyFirstOccurrenceWrapped(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + in := "北京很大。北京有很多人。北京是首都。" + got, changed := linkifyContent(in, refs, "") + if !changed { + t.Fatalf("expected change") + } + // Only first match should be wrapped. + count := strings.Count(got, "[[beijing|北京]]") + if count != 1 { + t.Fatalf("expected exactly 1 link, got %d: %q", count, got) + } + // Later occurrences remain bare. + if strings.Count(got, "北京") != 3 { + t.Fatalf("expected 3 total 北京 (incl. one inside the link), got content %q", got) + } +} + +func TestLinkifyContent_SkipsSelfSlug(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + // Rendering on the beijing page itself — must not self-link. + got, changed := linkifyContent("北京是首都", refs, "beijing") + if changed { + t.Fatalf("should not self-link: %q", got) + } +} + +func TestLinkifyContent_SkipsWhenSlugAlreadyUsed(t *testing.T) { + // Title matches by alias, but slug already appears via a different mention. + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + {slug: "beijing", matchText: "京师"}, + } + in := "我在[[beijing|京师]]出差,后来去了北京。" + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should skip when slug already linked: %q", got) + } +} + +func TestLinkifyContent_MultipleRefsDisjoint(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + {slug: "shanghai", matchText: "上海"}, + } + in := "我今天去北京,明天去上海。" + got, changed := linkifyContent(in, refs, "") + if !changed { + t.Fatalf("expected change") + } + if !strings.Contains(got, "[[beijing|北京]]") { + t.Fatalf("missing beijing link: %q", got) + } + if !strings.Contains(got, "[[shanghai|上海]]") { + t.Fatalf("missing shanghai link: %q", got) + } +} + +func TestLinkifyContent_EmptyOrNoMatch(t *testing.T) { + if _, c := linkifyContent("", []linkRef{{slug: "x", matchText: "y"}}, ""); c { + t.Fatalf("empty content must not change") + } + if _, c := linkifyContent("hello", nil, ""); c { + t.Fatalf("nil refs must not change") + } + if _, c := linkifyContent("hello world", []linkRef{{slug: "x", matchText: "zzz"}}, ""); c { + t.Fatalf("no match must not change") + } +} + +func TestFindFirstSafeMatch_BoundaryCases(t *testing.T) { + // Case where the first occurrence is unsafe (in code), second is safe. + s := "See `AI` in docs. AI rocks." + forb, _ := computeForbiddenSpans(s) + idx := findFirstSafeMatch(s, "AI", forb) + // First AI is inside `...`, second is safe. + want := strings.Index(s, "AI rocks") + if idx != want { + t.Fatalf("expected safe match at %d, got %d", want, idx) + } +} + +func TestComputeForbiddenSpans_FencedCode(t *testing.T) { + s := "before\n```\nhidden\n```\nafter" + spans, _ := computeForbiddenSpans(s) + if len(spans) == 0 { + t.Fatalf("expected at least one span") + } + // Ensure "hidden" is inside a forbidden span. + h := strings.Index(s, "hidden") + if !spanContains(spans, h, h+len("hidden")) { + t.Fatalf("hidden should be forbidden, spans=%v", spans) + } + // "before" and "after" must NOT be forbidden. + b := strings.Index(s, "before") + if spanContains(spans, b, b+len("before")) { + t.Fatalf("before should not be forbidden") + } + a := strings.Index(s, "after") + if spanContains(spans, a, a+len("after")) { + t.Fatalf("after should not be forbidden") + } +} + +func TestComputeForbiddenSpans_CollectsUsedSlugs(t *testing.T) { + s := "Refer to [[beijing|北京]] and [[shanghai]] and [[nope|x]]." + _, used := computeForbiddenSpans(s) + for _, slug := range []string{"beijing", "shanghai", "nope"} { + if _, ok := used[slug]; !ok { + t.Fatalf("expected slug %q in used set, got %v", slug, used) + } + } +} + +func TestLinkifyContent_SkipsInsideReferenceStyleLink(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + } + // [text][label] form — occurrence should not be linkified. + in := "See [北京][capital] for details.\n\n[capital]: https://example.com/beijing" + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not link inside reference-style link or definition: %q", got) + } +} + +func TestLinkifyContent_SkipsReferenceDefinitionLine(t *testing.T) { + refs := []linkRef{ + {slug: "example", matchText: "example"}, + } + // The `example` inside the definition URL must not be wrapped. + in := "[cap]: https://example.com/x" + got, changed := linkifyContent(in, refs, "") + if changed { + t.Fatalf("should not link inside reference definition: %q", got) + } +} + +func TestLinkifyContent_RepeatedLinkifyIsIdempotent(t *testing.T) { + refs := []linkRef{ + {slug: "beijing", matchText: "北京"}, + {slug: "shanghai", matchText: "上海"}, + } + in := "今天去北京,明天去上海。" + once, _ := linkifyContent(in, refs, "") + twice, changed := linkifyContent(once, refs, "") + if changed { + t.Fatalf("second run should be a no-op, got %q", twice) + } + if once != twice { + t.Fatalf("second run altered content:\nbefore: %q\nafter: %q", once, twice) + } +} diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.go index 23b984a1..58a63019 100644 --- a/internal/application/service/wiki_page.go +++ b/internal/application/service/wiki_page.go @@ -506,44 +506,19 @@ func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string, // InjectCrossLinks scans affected pages and injects [[wiki-links]] for mentions // of other wiki page titles in the content. Pure text replacement, no LLM call. +// Shares the linkifyContent helper with the ingest pipeline so both paths honor +// the same code-block / existing-link / word-boundary rules. func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string) { - // Build a title→slug lookup from ALL pages in this KB allPages, err := s.ListAllPages(ctx, kbID) if err != nil || len(allPages) < 2 { return } - type pageRef struct { - slug string - matchText string - } - var allRefs []pageRef - for _, p := range allPages { - if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { - continue - } - if p.Title != "" { - allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: p.Title}) - } - for _, alias := range p.Aliases { - if alias != "" { - allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: alias}) - } - } - } - if len(allRefs) == 0 { + refs := collectLinkRefs(allPages) + if len(refs) == 0 { return } - // Sort by title length descending - for i := 0; i < len(allRefs); i++ { - for j := i + 1; j < len(allRefs); j++ { - if len([]rune(allRefs[j].matchText)) > len([]rune(allRefs[i].matchText)) { - allRefs[i], allRefs[j] = allRefs[j], allRefs[i] - } - } - } - affectedSet := make(map[string]bool, len(affectedSlugs)) for _, slug := range affectedSlugs { affectedSet[slug] = true @@ -558,30 +533,16 @@ func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, aff continue } - content := p.Content - changed := false - - for _, ref := range allRefs { - if ref.slug == p.Slug { - continue - } - if strings.Contains(content, "[["+ref.slug+"|") || strings.Contains(content, "[["+ref.slug+"]]") { - continue - } - if strings.Contains(content, ref.matchText) { - content = replaceFirstOutsideLinks(content, ref.matchText, "[["+ref.slug+"|"+ref.matchText+"]]") - changed = true - } + newContent, changed := linkifyContent(p.Content, refs, p.Slug) + if !changed { + continue } - - if changed { - p.Content = content - if _, err := s.UpdatePage(ctx, p); err != nil { - logger.Warnf(ctx, "wiki: cross-link injection failed for %s: %v", p.Slug, err) - } else { - updated++ - } + p.Content = newContent + if _, err := s.UpdatePage(ctx, p); err != nil { + logger.Warnf(ctx, "wiki: cross-link injection failed for %s: %v", p.Slug, err) + continue } + updated++ } if updated > 0 {