fix(wiki): harden slug integrity across ingest and agent write paths

Weak LLMs routinely mangle high-entropy wiki slugs (especially UUID-based
summary/<id> slugs), producing dead cross-links and cross-item dedup
hallucinations. This tightens integrity end to end:

- Ingest dedup now groups each new item with only its own trigram
  candidates and validates merges against that per-item scope, rejecting
  cross-item mispairings; candidate top-K narrowed 20 -> 5.
- Editor path aliases out-link slugs behind low-entropy ref-N tokens and
  translates them back after generation, removing the chance to mangle.
- Agent write tool normalizes/validates slugs, blocks manual creation of
  system-owned summary pages, and auto-repairs dead [[slug]] links
  (rewrite-only, never strips) via bigram/display-text resolution.
- llmresource registry aliases summary/<uuid> slugs the same way as
  storage handles so they round-trip safely through chat.

Adds unit tests for slug validation, aliasing round-trip, dead-link
repair, and dedup rejection rules.
This commit is contained in:
wizardchen
2026-07-24 15:06:49 +08:00
committed by lyingbug
parent d283fabc99
commit 5d0326f987
14 changed files with 750 additions and 68 deletions
+67
View File
@@ -92,12 +92,45 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (
return &types.ToolResult{Success: false, Error: "title, summary, content, and page_type are required for write action"}, nil
}
// Validate + normalize the slug up front. The model routinely emits
// malformed slugs (stray characters, mangled UUIDs); persisting them
// verbatim creates unreachable pages and dead cross-links.
normalizedSlug, slugErr := normalizeAndValidateWikiSlug(params.Slug)
if slugErr != nil {
return &types.ToolResult{Success: false, Error: slugErr.Error()}, nil
}
params.Slug = normalizedSlug
// Try to get the existing page
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
if err != nil && !errors.Is(err, repository.ErrWikiPageNotFound) {
return &types.ToolResult{Success: false, Error: "Failed to check existing page: " + err.Error()}, nil
}
// Summary pages are system-owned: they are generated deterministically
// from a source document and keyed by its knowledge ID
// (summary/<knowledgeID>). Letting the agent CREATE one with an
// arbitrary/hand-typed slug is precisely how mangled-UUID ghost summary
// pages (e.g. summary/…b171c…) get into the KB. Allow updating an
// existing summary page, but never fabricating a new one.
if existingPage == nil &&
(isSummaryNamespace(params.Slug) || strings.EqualFold(params.PageType, types.WikiPageTypeSummary)) {
return &types.ToolResult{
Success: false,
Error: "summary pages are generated automatically from source documents and cannot be created manually. " +
"Use page_type 'synthesis'/'comparison'/'entity'/'concept' for authored pages, " +
"or target an existing summary page to update it.",
}, nil
}
// Auto-repair dead [[slug]] references in the body before persisting.
// This rewrites LLM-mangled links (most importantly UUID-based summary
// slugs) back to their real target when a confident match exists, and
// leaves everything else untouched. Best-effort — never block the write.
if repaired, changed, rerr := t.wikiPageService.RepairContentLinks(ctx, kbID, params.Slug, params.Content); rerr == nil && changed {
params.Content = repaired
}
resolvedRefs := resolveSourceRefs(ctx, t.knowledgeService, params.SourceRefs)
var action string
@@ -164,3 +197,37 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (
},
}, nil
}
// normalizeAndValidateWikiSlug lowercases + trims a model-supplied slug and
// rejects malformed ones. A valid slug contains only lowercase ASCII letters,
// digits, '-', '/', or CJK characters, has no leading/trailing/duplicate '/',
// and is non-empty. Keeping this strict stops the agent from persisting
// unreachable pages built from stray characters or garbled identifiers.
func normalizeAndValidateWikiSlug(raw string) (string, error) {
s := strings.ToLower(strings.TrimSpace(raw))
s = strings.ReplaceAll(s, " ", "-")
if s == "" {
return "", errors.New("slug is required and must be non-empty")
}
if strings.Contains(s, "//") || strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") {
return "", fmt.Errorf("invalid slug %q: '/' separators are malformed", raw)
}
for _, r := range s {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '/':
case r >= 0x4E00 && r <= 0x9FFF: // keep CJK characters
default:
return "", fmt.Errorf(
"invalid slug %q: character %q is not allowed (use lowercase letters, digits, '-', '/', or CJK)",
raw, string(r),
)
}
}
return s, nil
}
// isSummaryNamespace reports whether a slug lives in the system-owned summary
// namespace (summary/…).
func isSummaryNamespace(slug string) bool {
return strings.HasPrefix(slug, types.WikiPageTypeSummary+"/")
}
@@ -0,0 +1,53 @@
package tools
import "testing"
func TestNormalizeAndValidateWikiSlug(t *testing.T) {
tests := []struct {
name string
in string
want string
wantErr bool
}{
{name: "already valid", in: "entity/acme-corp", want: "entity/acme-corp"},
{name: "lowercased and spaces", in: "Entity/Acme Corp", want: "entity/acme-corp"},
{name: "trimmed", in: " concept/rag ", want: "concept/rag"},
{name: "cjk kept", in: "entity/上海中心大厦", want: "entity/上海中心大厦"},
{name: "uuid summary", in: "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e", want: "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"},
{name: "empty", in: " ", wantErr: true},
{name: "leading slash", in: "/entity/x", wantErr: true},
{name: "trailing slash", in: "entity/x/", wantErr: true},
{name: "double slash", in: "entity//x", wantErr: true},
{name: "invalid char", in: "entity/x!y", wantErr: true},
{name: "invalid space-only becomes empty", in: " ", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := normalizeAndValidateWikiSlug(tt.in)
if tt.wantErr {
if err == nil {
t.Fatalf("expected error for %q, got slug %q", tt.in, got)
}
return
}
if err != nil {
t.Fatalf("unexpected error for %q: %v", tt.in, err)
}
if got != tt.want {
t.Fatalf("normalizeAndValidateWikiSlug(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestIsSummaryNamespace(t *testing.T) {
if !isSummaryNamespace("summary/abc") {
t.Fatal("summary/abc must be in the summary namespace")
}
if isSummaryNamespace("summary") {
t.Fatal("bare 'summary' (no slash) must not count as the summary namespace")
}
if isSummaryNamespace("entity/summary-of-x") {
t.Fatal("entity/summary-of-x must not count as the summary namespace")
}
}