fix(knowledge): stitch chunks by text overlap, not by position

Reconstructing full document content from chunks relied on position math
(offset = content length - (EndAt - lastEndAt)) that assumes
len([]rune(Content)) == EndAt - StartAt. Two upstream behaviors break that
invariant and caused the merged "全文" view to drop or duplicate text:

- The parent-child chunker prepends a synthetic table header to split
  tables; that header is zero-width in position space (start == end), so
  Content is longer than EndAt - StartAt.
- Chunk Content can retain HTML entities (", > ...), inflating the
  rune count relative to the source span.

Replace position-based trimming with text-overlap matching: find where the
accumulated text's suffix reappears at the head of the next chunk and join
there. Positions are only used to size the search window. This naturally
skips the prepended header and is immune to entity length drift.

Extract the logic into searchutil.AppendWithOverlap / MergeTextChunks and
reuse it across the three backend stitching sites (wiki_ingest
reconstructContent, graph mergeChunkContents, chat_pipeline
mergeOverlappingChunks). Mirror the same algorithm in the frontend
doc-content merge. Also fix the markdown hr/heading styles (thin solid
divider, primary heading color).
This commit is contained in:
wizardchen
2026-05-30 17:47:54 +08:00
committed by lyingbug
parent c8645843c3
commit f92302cc64
7 changed files with 320 additions and 134 deletions
+2 -41
View File
@@ -1878,47 +1878,8 @@ func reconstructContent(chunks []*types.Chunk) string {
}
}
// Sort by StartAt, then ChunkIndex
sort.Slice(textChunks, func(i, j int) bool {
if textChunks[i].StartAt == textChunks[j].StartAt {
return textChunks[i].ChunkIndex < textChunks[j].ChunkIndex
}
return textChunks[i].StartAt < textChunks[j].StartAt
})
var sb strings.Builder
lastEndAt := -1
for _, c := range textChunks {
toAppend := c.Content
if c.StartAt > lastEndAt || c.EndAt == 0 {
// Non-overlapping or missing position info
if sb.Len() > 0 {
sb.WriteString("\n")
}
sb.WriteString(toAppend)
if c.EndAt > 0 {
lastEndAt = c.EndAt
}
} else if c.EndAt > lastEndAt {
// Partial overlap
contentRunes := []rune(toAppend)
offset := len(contentRunes) - (c.EndAt - lastEndAt)
if offset >= 0 && offset < len(contentRunes) {
sb.WriteString(string(contentRunes[offset:]))
} else {
// Fallback if offset calculation is invalid
if sb.Len() > 0 {
sb.WriteString("\n")
}
sb.WriteString(toAppend)
}
lastEndAt = c.EndAt
}
// If c.EndAt <= lastEndAt, it's fully contained, so skip appending text
}
return sb.String()
// 重叠去重与排序统一交给公共逻辑(按文本匹配,兼容补写表头 / HTML 实体)。
return searchutil.MergeTextChunks(textChunks, "\n")
}
// reconstructEnrichedContent rebuilds document text and inlines image_info