fix(text): truncate on rune boundaries, not byte offsets (#93)
Four call sites did `s[:limit] + "…"`. Both halves are byte operations: len() counts bytes and a slice cuts bytes. On Swedish text — å ä ö are two bytes, an em dash three — the cut lands mid-character and leaves an orphaned lead byte, producing invalid UTF-8. It failed loudly in exactly one place: wiki/index.md is written raw to disk, where every strict decoder then rejects the whole file. The other three (brain_context excerpts x2, brain_query excerpts) feed MCP responses, where encoding/json silently substitutes U+FFFD — so those had been quietly eating the last character of truncated excerpts, with no error anywhere and nothing to notice. textutil.Truncate counts runes and appends the marker only when content was actually dropped; an ellipsis on complete text is a lie about the content. The test is a property, not an example: it walks the limit across every offset of a multi-byte string and asserts utf8.Valid at each one, so a future off-by-one cannot pass by picking a lucky boundary. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
This commit is contained in:
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/search"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
|
||||
)
|
||||
|
||||
// brainContextArgs is the input shape of brain_context. project_root is
|
||||
@@ -170,10 +171,7 @@ func (s *Server) brainContext(ctx context.Context, args json.RawMessage) (json.R
|
||||
// without re-running the frontmatter parser. The ellipsis suffix matches
|
||||
// the convention used in search.excerpt.
|
||||
func truncateExcerpt(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + "…"
|
||||
return textutil.Truncate(s, maxLen)
|
||||
}
|
||||
|
||||
// readExcerpt loads a doc relative to brainDir, strips its frontmatter,
|
||||
@@ -193,10 +191,7 @@ func readExcerpt(brainDir, relPath string, maxLen int) string {
|
||||
if len(parts) == 3 {
|
||||
body = strings.TrimSpace(parts[2])
|
||||
}
|
||||
if len(body) > maxLen {
|
||||
return body[:maxLen] + "…"
|
||||
}
|
||||
return body
|
||||
return textutil.Truncate(body, maxLen)
|
||||
}
|
||||
|
||||
// max1 returns the maximum of n and 1, used to guard against divide-by-zero
|
||||
|
||||
Reference in New Issue
Block a user