// Package knowledge is the Knowledge Engine: one local index over the // catalog, the Big Picture and the existing manuals, with reference // resolution per client, backlinks, search, lint and coverage. The index // is derived data: it is rebuilt from the sources and never edited. package knowledge import ( "bufio" "bytes" "fmt" "io/fs" "os" "path/filepath" "sort" "strings" "yetano.dev/yetano/core/solutions/catalog" "yetano.dev/yetano/core/solutions/ref" ) // Entry is one searchable, linkable thing. type Entry struct { Ref string `json:"ref"` Kind string `json:"kind"` Title string `json:"title"` Summary string `json:"summary,omitempty"` Package string `json:"package,omitempty"` Category string `json:"category,omitempty"` Tags []string `json:"tags,omitempty"` Synonyms []string `json:"synonyms,omitempty"` Capabilities []string `json:"capabilities,omitempty"` Status string `json:"status,omitempty"` File string `json:"file,omitempty"` // local file (manuals) Line int `json:"line,omitempty"` Body string `json:"-"` // searchable text Translations catalog.Translations `json:"-"` } // Section is a heading of a manual topic. type Section struct { ID string `json:"id"` Title string `json:"title"` Level int `json:"level"` Start int `json:"start"` // first line (1-based) End int `json:"end"` // last line } // Topic is one manual document. type Topic struct { Source string `json:"source"` Slug string `json:"slug"` Title string `json:"title"` File string `json:"file"` Sections []Section `json:"sections"` lines []string } // Index is the knowledge index of one catalog. type Index struct { Cat *catalog.Catalog Entries []*Entry byRef map[string]*Entry Topics map[string]*Topic // "/" Backlinks map[string][]string // target ref -> refs that point to it // Missing lists knowledge sources whose files are not checked out. Missing []string } // Build indexes the catalog, the Big Picture and the manuals that are // available locally under the catalog's sourcesRoot. func Build(c *catalog.Catalog) *Index { ix := &Index{Cat: c, byRef: map[string]*Entry{}, Topics: map[string]*Topic{}, Backlinks: map[string][]string{}} ix.catalogEntries() ix.bigPictureEntries() ix.manuals() ix.links() sort.Slice(ix.Entries, func(i, j int) bool { return ix.Entries[i].Ref < ix.Entries[j].Ref }) return ix } func (ix *Index) add(e *Entry) { if _, dup := ix.byRef[e.Ref]; dup { return } ix.byRef[e.Ref] = e ix.Entries = append(ix.Entries, e) } // Entry returns the entry for a reference target (no section/version). func (ix *Index) Entry(r string) *Entry { return ix.byRef[r] } func (ix *Index) catalogEntries() { c := ix.Cat for _, id := range catalog.SortedIDs(c.Solutions) { ix.add(solutionEntry(c, c.Solutions[id], ref.Solution)) } for _, id := range catalog.SortedIDs(c.Tasks) { ix.add(solutionEntry(c, c.Tasks[id], ref.Task)) } for _, id := range catalog.SortedIDs(c.Packages) { p := c.Packages[id] e := &Entry{Ref: ref.For(ref.Package, id), Kind: ref.Package, Title: id, Package: id, Summary: p.Meta.Summary} if bp := c.BigPicture; bp != nil { if pr, ok := bp.Products[p.Spec.BigPicture]; ok { e.Summary = firstNonEmpty(e.Summary, pr.Summary) e.Body = strings.Join(pr.Tasks, "\n") } } for _, m := range p.Spec.Modules { e.Capabilities = append(e.Capabilities, m.Provides...) e.Body += "\n" + m.Title + " " + m.Program ix.add(&Entry{Ref: ref.For(ref.Module, id, m.ID), Kind: ref.Module, Title: firstNonEmpty(m.Program, m.ID) + ": " + m.Title, Summary: m.Description, Package: id, Capabilities: m.Provides, Status: string(m.Support)}) } if p.Spec.Microsite != "" { ix.add(&Entry{Ref: ref.For(ref.Microsite, id), Kind: ref.Microsite, Title: id + " microsite", Package: id, Summary: e.Summary}) } ix.add(e) } for _, id := range catalog.SortedIDs(c.Capabilities) { cp := c.Capabilities[id] ix.add(&Entry{Ref: ref.For(ref.Capability, id), Kind: ref.Capability, Title: cp.Title, Summary: cp.Description, Capabilities: []string{id}, Translations: cp.Translations}) } for _, id := range catalog.SortedIDs(c.Profiles) { p := c.Profiles[id] ix.add(&Entry{Ref: ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), Kind: ref.Profile, Title: firstNonEmpty(p.Meta.Title, p.Meta.ID), Summary: p.Meta.Description, Package: p.Meta.Package}) } for _, id := range catalog.SortedIDs(c.Examples) { x := c.Examples[id] ix.add(&Entry{Ref: ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), Kind: ref.Example, Title: x.Meta.Title, Summary: x.Meta.Summary, Translations: x.Meta.Translations, Body: x.Spec.Scenario}) } } func solutionEntry(c *catalog.Catalog, s *catalog.Solution, kind string) *Entry { e := &Entry{Ref: ref.For(kind, s.Meta.ID), Kind: kind, Title: s.Meta.Title, Summary: s.Meta.Summary, Category: s.Meta.Category, Tags: s.Meta.Tags, Synonyms: s.Meta.Synonyms, Status: string(s.Meta.Status), Translations: s.Meta.Translations} if bp := c.BigPicture; bp != nil { if g, ok := bp.Stories[s.Spec.BigPicture]; ok { e.Title = firstNonEmpty(e.Title, g.Title) e.Summary = firstNonEmpty(e.Summary, g.Intent) e.Body = g.Intent + "\n" + g.Outcome } } e.Body += "\n" + strings.Join(s.Spec.Goals, "\n") + "\n" + strings.Join(s.Spec.Scenarios, "\n") for _, q := range s.Spec.Questions { e.Body += "\n" + q.Title for _, o := range q.Options { e.Body += "\n" + o.Title } } e.Capabilities = append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...) for _, p := range s.Spec.Packages { e.Body += "\n" + p.ID } return e } func (ix *Index) bigPictureEntries() { bp := ix.Cat.BigPicture if bp == nil { return } for _, id := range catalog.SortedIDs(bp.Topics) { t := bp.Topics[id] ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: t.Title, Summary: t.Summary}) } for _, id := range catalog.SortedIDs(bp.Stories) { s := bp.Stories[id] ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: s.Title, Summary: s.Intent, Body: s.Outcome + "\n" + s.Explanation}) } for _, id := range catalog.SortedIDs(bp.Products) { p := bp.Products[id] ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: p.Name + " (Big Picture)", Summary: p.Summary}) } } // ---- manuals --------------------------------------------------------------- // SourceDir is where a knowledge source's files are, or "" if unknown. func (ix *Index) SourceDir(k *catalog.KnowledgeSource) string { if ix.Cat.Spec.SourcesRoot == "" || ix.Cat.Root == "" { return "" } root := ix.Cat.Spec.SourcesRoot if !filepath.IsAbs(root) { root = filepath.Join(ix.Cat.Root, root) } return filepath.Join(root, filepath.FromSlash(k.Spec.Repository), filepath.FromSlash(k.Spec.Root)) } // MaxManualSize bounds one manual file. const MaxManualSize = 2 << 20 func (ix *Index) manuals() { for _, id := range catalog.SortedIDs(ix.Cat.Sources) { k := ix.Cat.Sources[id] dir := ix.SourceDir(k) if dir == "" { ix.Missing = append(ix.Missing, id) continue } if _, err := os.Stat(filepath.Join(dir, "README.md")); err != nil { ix.Missing = append(ix.Missing, id) continue } files := []string{"README.md"} docs := filepath.Join(dir, "docs") _ = filepath.WalkDir(docs, func(p string, d fs.DirEntry, err error) error { if err != nil { return nil } rel, _ := filepath.Rel(dir, p) rel = filepath.ToSlash(rel) for _, ex := range k.Spec.Exclude { if rel == ex || strings.HasPrefix(rel, ex+"/") { if d.IsDir() { return fs.SkipDir } return nil } } if d.IsDir() && strings.HasPrefix(d.Name(), ".") { return fs.SkipDir } // *.conflict.md: a wiki-sync conflict copy (meta-repo // AGENTS.md), never documentation of its own if !d.IsDir() && strings.HasSuffix(p, ".md") && !strings.HasSuffix(p, ".conflict.md") { files = append(files, rel) } return nil }) sort.Strings(files) for _, f := range files { b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f))) if err != nil || len(b) > MaxManualSize { continue } t := parseTopic(id, TopicSlug(f), filepath.Join(dir, filepath.FromSlash(f)), b) ix.Topics[id+"/"+t.Slug] = t caps := []string{} for _, st := range k.Spec.Topics { if st.Slug == t.Slug { caps = st.Capabilities } } r := ref.For(ref.Manual, id, t.Slug) ix.add(&Entry{Ref: r, Kind: ref.Manual, Title: t.Title, Summary: firstLine(t), Package: k.Spec.Package, Capabilities: caps, File: t.File, Body: strings.Join(t.lines, "\n")}) for _, s := range t.Sections[1:] { ix.add(&Entry{Ref: r + "#" + s.ID, Kind: "section", Title: t.Title + " › " + s.Title, Package: k.Spec.Package, File: t.File, Line: s.Start, Body: strings.Join(t.lines[s.Start-1:s.End], "\n")}) } } } } // TopicSlug follows core/manual: README.md -> readme, docs/x.md -> x, // docs/x/README.md -> x. func TopicSlug(rel string) string { if rel == "README.md" { return "readme" } s := strings.TrimSuffix(strings.TrimPrefix(rel, "docs/"), ".md") s = strings.TrimSuffix(s, "/README") return strings.ReplaceAll(s, "/", ".") } func parseTopic(source, slug, file string, b []byte) *Topic { t := &Topic{Source: source, Slug: slug, File: file} sc := bufio.NewScanner(bytes.NewReader(b)) sc.Buffer(make([]byte, 64<<10), MaxManualSize) fence := false seen := map[string]int{} for sc.Scan() { line := sc.Text() t.lines = append(t.lines, line) trimmed := strings.TrimSpace(line) if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") { fence = !fence continue } if fence || !strings.HasPrefix(line, "#") { continue } level := len(line) - len(strings.TrimLeft(line, "#")) title := strings.TrimSpace(line[level:]) if level > 6 || title == "" { continue } id := ref.Slug(title) if n := seen[id]; n > 0 { id = fmt.Sprintf("%s-%d", id, n) } seen[ref.Slug(title)]++ if len(t.Sections) > 0 { t.Sections[len(t.Sections)-1].End = len(t.lines) - 1 } t.Sections = append(t.Sections, Section{ID: id, Title: title, Level: level, Start: len(t.lines)}) if t.Title == "" && level == 1 { t.Title = title } } if len(t.Sections) == 0 { t.Sections = []Section{{ID: "", Title: slug, Level: 1, Start: 1}} } t.Sections[len(t.Sections)-1].End = len(t.lines) if t.Title == "" { t.Title = slug } return t } func firstLine(t *Topic) string { for _, l := range t.lines { l = strings.TrimSpace(l) if l != "" && !strings.HasPrefix(l, "#") && !strings.HasPrefix(l, "```") && !strings.HasPrefix(l, "|") && !strings.HasPrefix(l, "<") { if len(l) > 200 { l = l[:200] + "…" } return l } } return "" } func firstNonEmpty(a ...string) string { for _, s := range a { if s != "" { return s } } return "" } // links collects every reference the catalog makes, for backlinks (REL-01/02). func (ix *Index) links() { c := ix.Cat link := func(from string, to string) { r, err := ref.Parse(to) if err != nil { return } t := r.Target() for _, x := range ix.Backlinks[t] { if x == from { return } } ix.Backlinks[t] = append(ix.Backlinks[t], from) } for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} { for _, id := range catalog.SortedIDs(m) { s := m[id] kind := ref.Solution if s.IsTask() { kind = ref.Task } from := ref.For(kind, id) for _, r := range RefsOf(s) { link(from, r) } for _, p := range s.Spec.Packages { link(from, ref.For(ref.Package, p.ID)) } for _, cp := range append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...) { link(from, ref.For(ref.Capability, cp)) } if s.Spec.BigPicture != "" { link(from, ref.For(ref.BigPicture, s.Spec.BigPicture)) } for _, r := range s.Spec.Related { k := ref.Solution if c.Tasks[r] != nil { k = ref.Task } link(from, ref.For(k, r)) } } } for _, id := range catalog.SortedIDs(c.Packages) { p := c.Packages[id] from := ref.For(ref.Package, id) for _, m := range p.Spec.Modules { for _, cp := range m.Provides { link(ref.For(ref.Module, id, m.ID), ref.For(ref.Capability, cp)) link(from, ref.For(ref.Capability, cp)) } } if p.Spec.BigPicture != "" { link(from, ref.For(ref.BigPicture, p.Spec.BigPicture)) } } for _, id := range catalog.SortedIDs(c.Profiles) { p := c.Profiles[id] for _, r := range p.Spec.References { link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), r) } link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), ref.For(ref.Package, p.Meta.Package)) } for _, id := range catalog.SortedIDs(c.Examples) { x := c.Examples[id] k := ref.Solution if c.Tasks[x.Spec.Solution] != nil { k = ref.Task } link(ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), ref.For(k, x.Spec.Solution)) } for k := range ix.Backlinks { sort.Strings(ix.Backlinks[k]) } } // RefsOf lists every yetano: reference a solution or task contains. func RefsOf(s *catalog.Solution) []string { var out []string out = append(out, s.Spec.References.All()...) for _, q := range s.Spec.Questions { out = append(out, q.References...) for _, o := range q.Options { out = append(out, o.References...) } } for _, st := range s.Spec.Steps { out = append(out, st.References...) } for _, c := range s.Spec.Requirements { out = append(out, c.References...) } return out } // Backlinks of a reference (its target), sorted. func (ix *Index) BacklinksOf(r string) []string { p, err := ref.Parse(r) if err != nil { return nil } return ix.Backlinks[p.Target()] }