chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+329
View File
@@ -0,0 +1,329 @@
// Package productdocs indexes the Academy documentation bundled with the
// server, so the built-in assistant can answer how the product works from
// the docs of the running version.
package productdocs
import (
"errors"
"fmt"
"io/fs"
"math"
"net/url"
"path"
"sort"
"strings"
"sync"
"unicode"
"unicode/utf8"
websitedocs "academy/website-docs"
)
// Categories are the documentation's sidebar groups, in site order. They
// mirror the sections list in website-docs/.vitepress/config.mts.
var Categories = []Category{
{Dir: "01-getting-started", Label: "快速开始"},
{Dir: "02-architecture", Label: "架构"},
{Dir: "03-features", Label: "功能模块"},
{Dir: "04-api", Label: "API 参考"},
{Dir: "05-clients", Label: "客户端"},
{Dir: "06-development", Label: "开发指南"},
{Dir: "07-releases", Label: "版本发布"},
}
// Category is one sidebar group.
type Category struct {
Dir string
Label string
}
// BM25 parameters; headings count several times so a section titled with
// the query outranks one that mentions it in passing.
const (
bm25K1 = 1.2
bm25B = 0.75
headingWeight = 3
snippetRunes = 160
)
// Library is a loaded, searchable set of pages.
type Library struct {
docs []*Doc
byPath map[string]*Doc
sections []*indexedSection
df map[string]int
avgLen float64
}
type indexedSection struct {
*Section
tf map[string]int
length int
}
// Hit is one search result.
type Hit struct {
Section *Section
Score float64
Snippet string
}
var (
defaultOnce sync.Once
defaultLib *Library
defaultErr error
)
// Default returns the library built from the pages embedded in the binary.
// As with Load, a non-nil library may come with an error naming the pages
// left out.
func Default() (*Library, error) {
defaultOnce.Do(func() { defaultLib, defaultErr = Load(websitedocs.Pages) })
return defaultLib, defaultErr
}
// Load parses every category's pages in fsys. A page that cannot be read or
// parsed is left out and reported in the error, alongside a library of the
// remaining pages, so one broken page does not take the others with it.
func Load(fsys fs.FS) (*Library, error) {
lib := &Library{byPath: map[string]*Doc{}, df: map[string]int{}}
var pageErrs []error
for _, cat := range Categories {
names, err := fs.Glob(fsys, cat.Dir+"/*.md")
if err != nil {
return nil, err
}
sort.Strings(names)
for _, name := range names {
raw, err := fs.ReadFile(fsys, name)
if err != nil {
pageErrs = append(pageErrs, err)
continue
}
doc, err := parseDoc(name, cat.Label, string(raw))
if err != nil {
pageErrs = append(pageErrs, err)
continue
}
lib.add(doc)
}
}
if len(lib.docs) == 0 {
return nil, errors.Join(append(pageErrs, fmt.Errorf("no documentation pages found"))...)
}
total := 0
for _, s := range lib.sections {
total += s.length
}
lib.avgLen = float64(total) / float64(len(lib.sections))
return lib, errors.Join(pageErrs...)
}
func (l *Library) add(doc *Doc) {
l.docs = append(l.docs, doc)
l.byPath[doc.Path] = doc
titleTokens := tokenize(doc.Title)
for _, s := range doc.Sections {
tf := map[string]int{}
for _, tok := range tokenize(s.plain) {
tf[tok]++
}
for _, tok := range tokenize(s.Heading + " " + strings.Join(s.Parents, " ")) {
tf[tok] += headingWeight
}
for _, tok := range titleTokens {
tf[tok]++
}
length := 0
for tok, n := range tf {
length += n
l.df[tok]++
}
l.sections = append(l.sections, &indexedSection{Section: s, tf: tf, length: length})
}
}
// Docs lists the pages of category (a Dir or Label), or all pages when empty.
func (l *Library) Docs(category string) []*Doc {
var out []*Doc
for _, d := range l.docs {
if category == "" || inCategory(d, category) {
out = append(out, d)
}
}
return out
}
// Doc resolves a page by its path, file name or public URL.
func (l *Library) Doc(ref string) (*Doc, string, bool) {
p, anchor := normalizeRef(ref)
d, ok := l.byPath[p]
return d, anchor, ok
}
// Search ranks sections for query, optionally within one category.
func (l *Library) Search(query, category string, limit int) []Hit {
terms := uniqueTokens(tokenize(query))
if len(terms) == 0 || limit <= 0 {
return nil
}
n := float64(len(l.sections))
var hits []Hit
for _, s := range l.sections {
if category != "" && !inCategory(s.Doc, category) {
continue
}
score := 0.0
for _, term := range terms {
tf := float64(s.tf[term])
if tf == 0 {
continue
}
df := float64(l.df[term])
idf := math.Log(1 + (n-df+0.5)/(df+0.5))
score += idf * tf * (bm25K1 + 1) /
(tf + bm25K1*(1-bm25B+bm25B*float64(s.length)/l.avgLen))
}
if score > 0 {
hits = append(hits, Hit{Section: s.Section, Score: score})
}
}
sort.SliceStable(hits, func(i, j int) bool { return hits[i].Score > hits[j].Score })
if len(hits) > limit {
hits = hits[:limit]
}
for i := range hits {
hits[i].Snippet = snippet(hits[i].Section.plain, terms)
}
return hits
}
func inCategory(d *Doc, category string) bool {
return strings.HasPrefix(d.Path, category+"/") || d.Category == category
}
// normalizeRef accepts "03-features/14-wiki", "03-features/14-wiki.md",
// "/docs/03-features/14-wiki" or the public URL, each with an optional
// "#anchor" that may be percent-encoded as a browser copies it.
func normalizeRef(ref string) (string, string) {
ref = strings.TrimSpace(ref)
ref, anchor, _ := strings.Cut(ref, "#")
ref = strings.TrimPrefix(ref, PublicBaseURL)
ref = strings.TrimPrefix(ref, "http://"+strings.TrimPrefix(PublicBaseURL, "https://"))
ref = strings.TrimPrefix(ref, "/")
ref = strings.TrimPrefix(ref, "docs/")
ref = strings.TrimSuffix(strings.TrimSuffix(ref, "/"), ".md")
ref = strings.TrimSuffix(ref, ".html")
return path.Clean(ref), UnescapeAnchor(anchor)
}
// UnescapeAnchor decodes a percent-encoded anchor, leaving one that is not
// valid encoding as given.
func UnescapeAnchor(anchor string) string {
if decoded, err := url.PathUnescape(anchor); err == nil {
return decoded
}
return anchor
}
// tokenize lowercases text into words: runs of letters and digits, kept
// whole across "_", "." and "-" joins (OLLAMA_BASE_URL, v0.8.3, api-keys)
// and also split at them; Han text becomes overlapping character pairs,
// since Chinese has no spaces between words.
func tokenize(text string) []string {
var out []string
var word []rune
var han []rune
flushWord := func() {
w := strings.TrimRight(string(word), "._-")
word = word[:0]
if utf8.RuneCountInString(w) < 2 {
return
}
out = append(out, w)
if strings.ContainsAny(w, "._-") {
for _, part := range strings.FieldsFunc(w, isJoiner) {
if utf8.RuneCountInString(part) > 1 {
out = append(out, part)
}
}
}
}
flushHan := func() {
switch {
case len(han) == 1:
out = append(out, string(han))
case len(han) > 1:
for i := 0; i+1 < len(han); i++ {
out = append(out, string(han[i:i+2]))
}
}
han = han[:0]
}
runes := []rune(strings.ToLower(text))
for i, r := range runes {
switch {
case unicode.Is(unicode.Han, r):
flushWord()
han = append(han, r)
case unicode.IsLetter(r) || unicode.IsDigit(r):
flushHan()
word = append(word, r)
case isJoiner(r) && len(word) > 0 && i+1 < len(runes) &&
(unicode.IsLetter(runes[i+1]) || unicode.IsDigit(runes[i+1])) && !unicode.Is(unicode.Han, runes[i+1]):
word = append(word, r)
default:
flushWord()
flushHan()
}
}
flushWord()
flushHan()
return out
}
func isJoiner(r rune) bool { return r == '_' || r == '.' || r == '-' }
func uniqueTokens(tokens []string) []string {
seen := map[string]bool{}
out := tokens[:0]
for _, t := range tokens {
if !seen[t] {
seen[t] = true
out = append(out, t)
}
}
return out
}
// snippet returns about snippetRunes of text around the first query term.
func snippet(text string, terms []string) string {
text = strings.Join(strings.Fields(text), " ")
lower := strings.ToLower(text)
at := -1
for _, term := range terms {
if i := strings.Index(lower, term); i >= 0 && (at < 0 || i < at) {
at = i
}
}
runes := []rune(text)
start := 0
if at > 0 {
start = utf8.RuneCountInString(lower[:at]) - snippetRunes/4
if start < 0 {
start = 0
}
}
end := start + snippetRunes
if end > len(runes) {
end = len(runes)
}
out := string(runes[start:end])
if start > 0 {
out = "…" + out
}
if end < len(runes) {
out += "…"
}
return out
}
+304
View File
@@ -0,0 +1,304 @@
package productdocs
import (
"fmt"
"path"
"regexp"
"strings"
"golang.org/x/text/unicode/norm"
)
// PublicBaseURL is where the documentation site serves these pages.
const PublicBaseURL = "https://weknora.weixin.qq.com/docs/"
// maxSectionLevel is the deepest heading that starts its own section; deeper
// headings stay in their section's text. The site anchors every level, and
// pages link to "####" headings, so those must be readable on their own.
const maxSectionLevel = 4
var (
headingRE = regexp.MustCompile(`^(#{1,6})\s+(.*?)\s*$`)
customIDRE = regexp.MustCompile(`\s*\{#([^}\s]+)\}$`)
imageRE = regexp.MustCompile(`!\[([^\]]*)\]\([^)]*\)`)
linkRE = regexp.MustCompile(`\[([^\]]*)\]\(([^)\s]+)\)`)
inlineCodeRE = regexp.MustCompile("`([^`]*)`")
emphasisRE = regexp.MustCompile(`\*\*([^*]+)\*\*|\*([^*\s][^*]*)\*`)
captionRE = regexp.MustCompile(`caption="([^"]*)"`)
// slugSpecialRE and the steps in slugify follow VitePress's default
// heading slugify (@mdit-vue/shared), so anchors match the published site.
slugSpecialRE = regexp.MustCompile("[\\s~`!@#$%^&*()\\-_+=\\[\\]{}|\\\\;:\"'\u201c\u201d\u2018\u2019<>,.?/]+")
slugControlRE = regexp.MustCompile(`[\x00-\x1f]`)
slugCombiningRE = regexp.MustCompile(`[\x{0300}-\x{036f}]`)
slugDashesRE = regexp.MustCompile(`-{2,}`)
)
// Doc is one documentation page.
type Doc struct {
Path string // "03-features/14-wiki", the page's path under the site
Category string // Sidebar group, e.g. "功能模块"
Title string
Sections []*Section // In page order; the first is the text before any "##"
}
// URL is the page's public address.
func (d *Doc) URL() string { return PublicBaseURL + d.Path }
// Span returns the section at anchor followed by its subsections; "" is the
// whole page.
func (d *Doc) Span(anchor string) ([]*Section, bool) {
if anchor == "" {
return d.Sections, true
}
for i, s := range d.Sections {
if s.Anchor != anchor {
continue
}
end := i + 1
for end < len(d.Sections) && d.Sections[end].Level > s.Level {
end++
}
return d.Sections[i:end], true
}
return nil, false
}
// Render joins sections back into Markdown with their headings.
func Render(sections []*Section) string {
var sb strings.Builder
for _, s := range sections {
if s.Level > 1 {
sb.WriteString(strings.Repeat("#", s.Level) + " " + s.Heading + "\n\n")
}
if s.Content != "" {
sb.WriteString(s.Content + "\n\n")
}
}
return strings.TrimSpace(sb.String())
}
// Section is the text under one heading of level 2 to maxSectionLevel, up to
// the next such heading.
type Section struct {
Doc *Doc
Anchor string // "" for the page's lead section
Heading string
Level int // 1 for the lead section, then 2 to maxSectionLevel
Parents []string // Headings of the enclosing sections, outermost first
Content string // Cleaned Markdown shown to the model
plain string // Content without link targets, for indexing and snippets
}
// URL is the section's public address.
func (s *Section) URL() string {
if s.Anchor == "" {
return s.Doc.URL()
}
return s.Doc.URL() + "#" + s.Anchor
}
// Trail is the heading path shown in search results.
func (s *Section) Trail() string {
parts := []string{s.Doc.Title}
parts = append(parts, s.Parents...)
if s.Level > 1 {
parts = append(parts, s.Heading)
}
return strings.Join(parts, " › ")
}
// parseDoc splits a page into sections. pagePath is its file name under the
// docs root, e.g. "03-features/14-wiki.md".
func parseDoc(pagePath, category, raw string) (*Doc, error) {
doc := &Doc{Path: strings.TrimSuffix(pagePath, ".md"), Category: category}
lines := strings.Split(stripFrontMatter(strings.ReplaceAll(raw, "\r\n", "\n")), "\n")
slugs := map[string]bool{}
current := &Section{Doc: doc, Level: 1}
var body []string
var stack []*Section
flush := func() {
current.Content = strings.TrimSpace(strings.Join(body, "\n"))
current.plain = plainText(current.Content)
doc.Sections = append(doc.Sections, current)
body = nil
}
fence := ""
dropFence := false
for i := 0; i < len(lines); i++ {
line := lines[i]
trimmed := strings.TrimSpace(line)
if fence != "" {
if strings.HasPrefix(trimmed, fence) && strings.Trim(trimmed, fence[:1]) == "" {
fence = ""
if dropFence {
dropFence = false
continue
}
}
if !dropFence {
body = append(body, line)
}
continue
}
if marker := fenceMarker(trimmed); marker != "" {
fence = marker
if strings.TrimSpace(strings.TrimLeft(trimmed, marker[:1])) == "mermaid" {
dropFence = true
body = append(body, "(此处为流程图,略)")
continue
}
body = append(body, line)
continue
}
if strings.HasPrefix(trimmed, "<Screenshot") {
block := trimmed
for !strings.Contains(block, "/>") && i+1 < len(lines) {
i++
block += " " + strings.TrimSpace(lines[i])
}
if m := captionRE.FindStringSubmatch(block); m != nil && m[1] != "" {
body = append(body, "(截图:"+m[1]+")")
}
continue
}
m := headingRE.FindStringSubmatch(line)
if m == nil {
body = append(body, rewriteLinks(doc.Path, line))
continue
}
level := len(m[1])
text, anchor := splitCustomID(m[2])
text = plainText(text)
anchor = uniqueSlug(slugs, anchor, text)
switch {
case level == 1 && doc.Title == "":
doc.Title = text
case level >= 2 && level <= maxSectionLevel:
flush()
for len(stack) > 0 && stack[len(stack)-1].Level >= level {
stack = stack[:len(stack)-1]
}
parents := make([]string, 0, len(stack))
for _, s := range stack {
parents = append(parents, s.Heading)
}
current = &Section{Doc: doc, Anchor: anchor, Heading: text, Level: level, Parents: parents}
stack = append(stack, current)
default:
body = append(body, rewriteLinks(doc.Path, line))
}
}
if fence != "" {
return nil, fmt.Errorf("%s: unterminated code fence", pagePath)
}
flush()
if doc.Title == "" {
return nil, fmt.Errorf("%s: no title heading", pagePath)
}
doc.Sections[0].Heading = doc.Title
return doc, nil
}
func stripFrontMatter(raw string) string {
if !strings.HasPrefix(raw, "---\n") {
return raw
}
if end := strings.Index(raw[4:], "\n---\n"); end >= 0 {
return raw[4+end+5:]
}
return raw
}
func fenceMarker(trimmed string) string {
for _, ch := range []string{"`", "~"} {
if strings.HasPrefix(trimmed, ch+ch+ch) {
n := len(trimmed) - len(strings.TrimLeft(trimmed, ch))
return strings.Repeat(ch, n)
}
}
return ""
}
func splitCustomID(heading string) (text, id string) {
if m := customIDRE.FindStringSubmatchIndex(heading); m != nil {
return heading[:m[0]], heading[m[2]:m[3]]
}
return heading, ""
}
// uniqueSlug registers a heading's anchor the way markdown-it-anchor does:
// an explicit {#id} or the slugified text, suffixed "-1", "-2"… while taken.
func uniqueSlug(seen map[string]bool, custom, text string) string {
base := custom
if base == "" {
base = slugify(text)
}
slug := base
for i := 1; seen[slug]; i++ {
slug = fmt.Sprintf("%s-%d", base, i)
}
seen[slug] = true
return slug
}
func slugify(s string) string {
s = norm.NFKD.String(s)
s = slugCombiningRE.ReplaceAllString(s, "")
s = slugControlRE.ReplaceAllString(s, "")
s = slugSpecialRE.ReplaceAllString(s, "-")
s = slugDashesRE.ReplaceAllString(s, "-")
s = strings.Trim(s, "-")
if s != "" && s[0] >= '0' && s[0] <= '9' {
s = "_" + s
}
return strings.ToLower(s)
}
// plainText drops Markdown syntax that is not words: link targets, image
// sources, code ticks and emphasis.
func plainText(s string) string {
s = imageRE.ReplaceAllString(s, "$1")
s = linkRE.ReplaceAllString(s, "$1")
s = inlineCodeRE.ReplaceAllString(s, "$1")
s = emphasisRE.ReplaceAllString(s, "${1}${2}")
return strings.TrimSpace(s)
}
// rewriteLinks turns site-relative links into public URLs so the model can
// hand them to the user, and reduces images to their alt text.
func rewriteLinks(docPath, line string) string {
line = imageRE.ReplaceAllStringFunc(line, func(m string) string {
alt := imageRE.FindStringSubmatch(m)[1]
if alt == "" {
return ""
}
return "(图:" + alt + ")"
})
return linkRE.ReplaceAllStringFunc(line, func(m string) string {
sub := linkRE.FindStringSubmatch(m)
return "[" + sub[1] + "](" + resolveLink(docPath, sub[2]) + ")"
})
}
func resolveLink(docPath, target string) string {
switch {
case strings.HasPrefix(target, "http://"), strings.HasPrefix(target, "https://"),
strings.HasPrefix(target, "mailto:"):
return target
case strings.HasPrefix(target, "#"):
return PublicBaseURL + docPath + target
case strings.HasPrefix(target, "/"):
return PublicBaseURL + strings.TrimPrefix(target, "/")
}
file, anchor, _ := strings.Cut(target, "#")
resolved := path.Clean(path.Join(path.Dir(docPath), strings.TrimSuffix(file, ".md")))
if strings.HasPrefix(resolved, "..") {
return target
}
if anchor != "" {
resolved += "#" + anchor
}
return PublicBaseURL + resolved
}
+295
View File
@@ -0,0 +1,295 @@
package productdocs
import (
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"testing/fstest"
websitedocs "academy/website-docs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const samplePage = "# Wiki 能力(Wiki)\n" +
"\n" +
"Wiki 将资料整理为页面,详见[观测](16-observability.md)与[本节](#抽取粒度)。\n" +
"\n" +
"<Screenshot\n" +
" src=\"/screenshots/wiki.png\"\n" +
" caption=\"Wiki 浏览器\"\n" +
" hint=\"不应出现\" />\n" +
"\n" +
"## 开启并浏览 Wiki {#怎么开启}\n" +
"\n" +
"1. 编辑知识库 → 打开 **Wiki**;见[配置](../01-getting-started/04-configuration.md#模型与推理)。\n" +
"\n" +
"```mermaid\n" +
"graph TD\n" +
" A --> B\n" +
"```\n" +
"\n" +
"```bash\n" +
"# 不是标题\n" +
"export WIKI_ENABLED=true\n" +
"```\n" +
"\n" +
"### 4.2 队列(Asynq):Worker 池\n" +
"\n" +
"队列内容。![拓扑](/screenshots/topology.png)\n" +
"\n" +
"#### 抽取粒度\n" +
"\n" +
"选择 `focused` 或 `exhaustive`。\n" +
"\n" +
"##### 更深的标题\n" +
"\n" +
"仍属于抽取粒度。\n" +
"\n" +
"## 常见问题\n" +
"\n" +
"## 常见问题\n" +
"\n" +
"第二个同名标题。\n"
func parseSample(t *testing.T) *Doc {
t.Helper()
doc, err := parseDoc("03-features/14-wiki.md", "功能模块", samplePage)
require.NoError(t, err)
return doc
}
func TestParseDocSplitsSectionsWithSiteAnchors(t *testing.T) {
doc := parseSample(t)
assert.Equal(t, "03-features/14-wiki", doc.Path)
assert.Equal(t, "Wiki 能力(Wiki)", doc.Title)
var anchors []string
for _, s := range doc.Sections {
anchors = append(anchors, s.Anchor)
}
// The lead section, an explicit {#id}, a slug whose full-width
// punctuation folds to dashes and gains "_" before a digit, a "####"
// section, and a repeated heading suffixed like the site does.
assert.Equal(t, []string{"", "怎么开启", "_4-2-队列-asynq-worker-池", "抽取粒度", "常见问题", "常见问题-1"}, anchors)
deep := doc.Sections[3]
assert.Equal(t, 4, deep.Level)
assert.Equal(t, []string{"开启并浏览 Wiki", "4.2 队列(Asynq):Worker 池"}, deep.Parents)
assert.Equal(t, "Wiki 能力(Wiki) › 开启并浏览 Wiki › 4.2 队列(Asynq):Worker 池 › 抽取粒度", deep.Trail())
assert.Contains(t, deep.Content, "##### 更深的标题", "headings below level 4 stay in their section")
assert.Equal(t, PublicBaseURL+"03-features/14-wiki#抽取粒度", deep.URL())
}
func TestParseDocCleansSiteMarkup(t *testing.T) {
doc := parseSample(t)
lead := doc.Sections[0].Content
assert.Contains(t, lead, "(截图:Wiki 浏览器)")
assert.NotContains(t, lead, "不应出现")
assert.Contains(t, lead, "[观测]("+PublicBaseURL+"03-features/16-observability)")
assert.Contains(t, lead, "[本节]("+PublicBaseURL+"03-features/14-wiki#抽取粒度)")
enable := doc.Sections[1].Content
assert.Contains(t, enable, "[配置]("+PublicBaseURL+"01-getting-started/04-configuration#模型与推理)")
assert.NotContains(t, enable, "graph TD", "Mermaid diagrams are dropped")
assert.Contains(t, enable, "(此处为流程图,略)")
assert.Contains(t, enable, "# 不是标题", "a # line inside a code fence is not a heading")
assert.Contains(t, enable, "export WIKI_ENABLED=true")
assert.Contains(t, doc.Sections[2].Content, "(图:拓扑)")
assert.NotContains(t, doc.Sections[2].Content, "topology.png")
}
func TestParseDocRejectsBrokenPages(t *testing.T) {
_, err := parseDoc("x/a.md", "", "no title here\n")
assert.Error(t, err)
_, err = parseDoc("x/a.md", "", "# T\n\n```go\nunterminated\n")
assert.Error(t, err)
}
func TestSpanIncludesSubsections(t *testing.T) {
doc := parseSample(t)
span, ok := doc.Span("怎么开启")
require.True(t, ok)
require.Len(t, span, 3)
rendered := Render(span)
assert.True(t, strings.HasPrefix(rendered, "## 开启并浏览 Wiki"))
assert.Contains(t, rendered, "#### 抽取粒度")
assert.NotContains(t, rendered, "常见问题")
whole, ok := doc.Span("")
require.True(t, ok)
assert.Len(t, whole, len(doc.Sections))
_, ok = doc.Span("missing")
assert.False(t, ok)
}
func TestTokenizeKeepsIdentifiersAndPairsHan(t *testing.T) {
assert.Equal(t, []string{"ollama_base_url", "ollama", "base", "url"}, tokenize("OLLAMA_BASE_URL"))
assert.Equal(t, []string{"v0.8.3", "v0"}, tokenize("v0.8.3."))
assert.Equal(t, []string{"抽取", "取粒", "粒度"}, tokenize("抽取粒度"))
assert.Equal(t, []string{"wiki", "页"}, tokenize("Wiki 页"))
}
func TestNormalizeRefAcceptsSiteForms(t *testing.T) {
for _, ref := range []string{
"03-features/14-wiki",
"03-features/14-wiki.md",
"/docs/03-features/14-wiki",
PublicBaseURL + "03-features/14-wiki/",
"docs/03-features/14-wiki.html",
} {
p, anchor := normalizeRef(ref)
assert.Equal(t, "03-features/14-wiki", p, ref)
assert.Empty(t, anchor, ref)
}
for _, ref := range []string{
PublicBaseURL + "03-features/14-wiki#抽取粒度",
PublicBaseURL + "03-features/14-wiki#%E6%8A%BD%E5%8F%96%E7%B2%92%E5%BA%A6",
"http://weknora.weixin.qq.com/docs/03-features/14-wiki#抽取粒度",
} {
p, anchor := normalizeRef(ref)
assert.Equal(t, "03-features/14-wiki", p, ref)
assert.Equal(t, "抽取粒度", anchor, ref)
}
}
func TestLoadLeavesOutBrokenPages(t *testing.T) {
lib, err := Load(fstest.MapFS{
"03-features/14-wiki.md": {Data: []byte(samplePage)},
"03-features/99-broken.md": {Data: []byte("# 坏页\n\n```go\nunterminated\n")},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "99-broken.md")
require.NotNil(t, lib, "the pages that parse stay available")
assert.Len(t, lib.Docs(""), 1)
assert.NotEmpty(t, lib.Search("抽取粒度", "", 1))
lib, err = Load(fstest.MapFS{"03-features/99-broken.md": {Data: []byte("no title\n")}})
assert.Error(t, err)
assert.Nil(t, lib)
}
func TestLoadAndSearch(t *testing.T) {
lib, err := Load(fstest.MapFS{
"03-features/14-wiki.md": {Data: []byte(samplePage)},
"03-features/13-embed.md": {Data: []byte("# 网页嵌入\n\n## 直接 iframe 接入\n\n复制 iframe 代码到页面。\n")},
"01-getting-started/x.md": {Data: []byte("# 配置详解\n\n## 模型与推理\n\nOLLAMA_BASE_URL 指向 Ollama。\n")},
"homepage/not-a-category.md": {Data: []byte("# 首页\n\n抽取粒度\n")},
})
require.NoError(t, err)
assert.Len(t, lib.Docs(""), 3, "only category directories are loaded")
assert.Len(t, lib.Docs("功能模块"), 2)
assert.Len(t, lib.Docs("03-features"), 2)
hits := lib.Search("Wiki 抽取粒度", "", 3)
require.NotEmpty(t, hits)
assert.Equal(t, "抽取粒度", hits[0].Section.Anchor)
assert.Contains(t, hits[0].Snippet, "focused")
hits = lib.Search("iframe", "01-getting-started", 5)
assert.Empty(t, hits, "the category filter applies")
hits = lib.Search("ollama", "", 5)
require.Len(t, hits, 1)
assert.Equal(t, "01-getting-started/x", hits[0].Section.Doc.Path)
assert.Empty(t, lib.Search(" ", "", 5))
doc, anchor, ok := lib.Doc(PublicBaseURL + "03-features/14-wiki#怎么开启")
require.True(t, ok)
assert.Equal(t, "Wiki 能力(Wiki)", doc.Title)
assert.Equal(t, "怎么开启", anchor)
_, _, ok = lib.Doc("03-features/../../etc/passwd")
assert.False(t, ok)
}
// The pages shipped in the binary must all parse, and every link between
// them must point at a page and anchor that exist, so a link the assistant
// hands the user opens the section it named.
func TestEmbeddedDocsParseAndLinksResolve(t *testing.T) {
lib, err := Default()
require.NoError(t, err)
require.Greater(t, len(lib.Docs("")), 50)
for _, cat := range Categories {
assert.NotEmpty(t, lib.Docs(cat.Dir), cat.Dir)
}
anchors := map[string]map[string]bool{}
for _, doc := range lib.Docs("") {
set := map[string]bool{"": true}
for _, s := range doc.Sections {
assert.False(t, set[s.Anchor] && s.Anchor != "", "%s: duplicate anchor %q", doc.Path, s.Anchor)
set[s.Anchor] = true
}
anchors[doc.Path] = set
}
for _, doc := range lib.Docs("") {
for _, s := range doc.Sections {
for _, m := range linkRE.FindAllStringSubmatch(s.Content, -1) {
target := m[2]
if !strings.HasPrefix(target, PublicBaseURL) {
continue
}
p, anchor := normalizeRef(target)
set, ok := anchors[p]
if !ok {
// Screenshots and other site assets live outside the pages.
assert.NotContains(t, p, ".md", "%s links to a missing page %s", doc.Path, target)
continue
}
if anchor != "" && !set[anchor] && !headingBelowSections(lib, p, anchor) {
t.Errorf("%s links to a missing anchor %s", doc.Path, target)
}
}
}
}
}
// Categories must match the site's sidebar groups, and every embedded
// directory must be one of them, so a new section is neither left out of the
// index nor labelled differently from the site.
func TestCategoriesMatchTheSiteAndTheEmbed(t *testing.T) {
config, err := os.ReadFile(filepath.Join("..", "..", "website-docs", ".vitepress", "config.mts"))
require.NoError(t, err)
var site []Category
groupRE := regexp.MustCompile(`\{ dir: '([^']+)', label: '([^']+)'`)
for _, m := range groupRE.FindAllStringSubmatch(string(config), -1) {
site = append(site, Category{Dir: m[1], Label: m[2]})
}
assert.Equal(t, site, Categories)
known := map[string]bool{}
for _, c := range Categories {
known[c.Dir] = true
}
entries, err := fs.ReadDir(websitedocs.Pages, ".")
require.NoError(t, err)
for _, e := range entries {
assert.True(t, known[e.Name()], "embedded directory %s has no category", e.Name())
}
}
// headingBelowSections reports whether anchor names a heading deeper than
// maxSectionLevel, which the site anchors but this index keeps inside text.
func headingBelowSections(lib *Library, docPath, anchor string) bool {
doc, _, ok := lib.Doc(docPath)
if !ok {
return false
}
for _, s := range doc.Sections {
for _, line := range strings.Split(s.Content, "\n") {
if m := headingRE.FindStringSubmatch(line); m != nil && len(m[1]) > maxSectionLevel {
text, id := splitCustomID(m[2])
if id == anchor || slugify(plainText(text)) == anchor {
return true
}
}
}
}
return false
}