Files
core/solutions/cli/more.go
T
terminarandClaude Opus 5.5 2481a0dd27 solutions: Solutions Guide engine (catalog, rules, wizard state, native config, knowledge index, CLI)
New nested module yetano.dev/yetano/core/solutions: loads the catalog
in assets/solutions on top of the Big Picture, evaluates questions and
conditions, resolves packages/modules/capabilities, generates native
configuration from typed fragments with per-value origins, and builds
architecture graph, plan, lock file and handbook. Knowledge index with
yetano: references, search and lint (incl. manual sections). CLI with
yet's conventions (solution, task, knowledge, open), standalone as
yetano-solutions. No execution, no network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 08:42:58 +01:00

624 lines
16 KiB
Go

package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/knowledge"
"yetano.dev/yetano/core/solutions/ref"
)
// ---- search --------------------------------------------------------------------
func (a *app) searchCmd(args []string, kinds []string) error {
fs := a.flags("search")
all := fs.Bool("all", false, "search everything (manuals, packages, Big Picture, ...)")
limit := fs.Int("limit", 8, "hits per group")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() == 0 {
return fail(ExitUsage, "usage: search <words>")
}
if err := a.load(); err != nil {
return err
}
if *all {
kinds = nil
}
groups := a.ix.Search(strings.Join(fs.Args(), " "), knowledge.SearchOptions{Kinds: kinds, Limit: *limit, Locale: a.locale})
if a.jsonOut {
if groups == nil {
groups = []knowledge.Group{}
}
return a.printJSON(groups)
}
if len(groups) == 0 {
a.note("nothing found\n")
return exitErr{ExitNotFound, errors.New("")}
}
for _, g := range groups {
a.say("%s\n", g.Title)
for _, h := range g.Hits {
a.say(" %-44s %s\n", trunc(h.Title, 44), h.Ref)
}
a.say("\n")
}
return nil
}
func trunc(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// ---- instances --------------------------------------------------------------------
func (a *app) instance(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution instance " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
inst, err := a.store.Instances()
if err != nil {
return err
}
sess, err := a.store.Sessions()
if err != nil {
return err
}
type row struct {
Name string `json:"name"`
Kind string `json:"kind"`
Solution string `json:"solution"`
Status string `json:"status"`
Updated string `json:"updated"`
}
var rows []row
for _, list := range [][]string{inst, sess} {
for _, n := range list {
in, err := a.store.LoadInstance(n)
if err != nil {
continue
}
status := "Draft"
if in.Kind == catalog.KindInstance {
status = "Configured"
if a.load() == nil {
if st, err := a.evaluate(in, nil); err == nil && !st.Complete {
status = "Invalid"
}
}
}
rows = append(rows, row{n, in.Kind, in.Spec.Solution.ID, status, in.Metadata.Updated})
}
}
if a.jsonOut {
if rows == nil {
rows = []row{}
}
return a.printJSON(rows)
}
if len(rows) == 0 {
a.note("no saved solutions (save one with: %s solution setup <id> --save)\n", a.env.Program)
}
for _, r := range rows {
a.say("%-24s %-14s %-11s %s\n", r.Name, r.Solution, r.Status, r.Updated)
}
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance %s <name>", a.env.Program, args[0])
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(in)
}
b, err := engine.Marshal(in)
if err != nil {
return err
}
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if err := a.load(); err != nil {
return err
}
if _, err := a.evaluate(in, nil); err != nil {
return err
}
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("imported %s\n", in.Metadata.Name)
return nil
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance delete <name>", a.env.Program)
}
return a.store.DeleteInstance(fs.Arg(0))
case "duplicate", "cp":
if fs.NArg() != 2 {
return fail(ExitUsage, "usage: %s solution instance duplicate <name> <new-name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Name, in.Metadata.Created = fs.Arg(1), ""
return a.store.SaveInstance(in)
case "favorite":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance favorite <name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Favorite = !in.Metadata.Favorite
return a.store.SaveInstance(in)
}
return a.usage("solution instance " + args[0])
}
// ---- presets ------------------------------------------------------------------------
func (a *app) preset(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution preset " + args[0])
from := fs.String("from", "", "save: the instance to take the answers from")
file := fs.String("file", "", "save: a solution.yaml to take the answers from")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
names, err := a.store.Presets()
if err != nil {
return err
}
if a.jsonOut {
if names == nil {
names = []string{}
}
return a.printJSON(names)
}
for _, n := range names {
p, err := a.store.LoadPreset(n)
if err != nil {
continue
}
a.say("%-24s %-14s %d answer(s)\n", n, p.Spec.Solution, len(p.Spec.Parameters))
}
return nil
case "save":
if fs.NArg() != 1 || (*from == "" && *file == "") {
return fail(ExitUsage, "usage: %s solution preset save <name> --from <instance> | --file <solution.yaml>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
var in *engine.Instance
var err error
if *file != "" {
in, err = a.instanceFrom(*file, fs)
} else {
in, err = a.store.LoadInstance(*from)
}
if err != nil {
return err
}
s := a.cat.Lookup(in.Spec.Solution.ID)
if s == nil {
return fmt.Errorf("%w: solution %s", engine.ErrNotFound, in.Spec.Solution.ID)
}
p := engine.PresetFrom(fs.Arg(0), in, s)
if err := a.store.SavePreset(p); err != nil {
return err
}
a.note("saved preset %s (%d answers; instance-specific and secret answers are left out)\n", p.Metadata.Name, len(p.Spec.Parameters))
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset show <name>", a.env.Program)
}
p, err := a.store.LoadPreset(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(p)
}
b, _ := engine.Marshal(p)
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
p, err := engine.ReadPreset(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
return a.store.SavePreset(p)
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset delete <name>", a.env.Program)
}
return a.store.DeletePreset(fs.Arg(0))
}
return a.usage("solution preset " + args[0])
}
// ---- catalog --------------------------------------------------------------------------
func (a *app) catalogCmd(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s solution catalog validate|test|coverage", a.env.Program)
}
fs := a.flags("solution catalog " + args[0])
update := fs.Bool("update", false, "test: rewrite the golden files")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
var ee exitErr
if a.cat != nil && !errors.As(err, &ee) {
// print every load issue, not just the first
for _, i := range a.cat.Issues {
a.note("%s\n", i)
}
}
return err
}
switch args[0] {
case "validate", "lint":
issues := knowledge.Lint(a.ix)
errs := 0
for _, i := range issues {
if i.Severity == "error" {
errs++
}
}
if a.jsonOut {
if issues == nil {
issues = []catalog.Issue{}
}
_ = a.printJSON(issues)
} else {
for _, i := range issues {
a.say("%-7s %s\n", strings.ToUpper(i.Severity), i)
}
a.note("%d solution(s), %d task(s), %d package(s), %d capabilities, %d manual topics: %d error(s), %d warning(s)\n",
len(a.cat.Solutions), len(a.cat.Tasks), len(a.cat.Packages), len(a.cat.Capabilities), len(a.ix.Topics), errs, len(issues)-errs)
}
if errs > 0 {
return exitErr{ExitError, errors.New("")}
}
return nil
case "test":
return a.catalogTest(*update)
case "schema":
dir := filepath.Join(a.cat.Root, "schema")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for _, name := range sortedKeys(catalog.SchemaKinds) {
b, err := json.MarshalIndent(catalog.JSONSchema(name), "", " ")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, name+".schema.json"), append(b, '\n'), 0o644); err != nil {
return err
}
}
a.note("wrote %d schemas to %s\n", len(catalog.SchemaKinds), dir)
return nil
case "coverage":
cov := knowledge.ComputeCoverage(a.ix)
if a.jsonOut {
return a.printJSON(cov)
}
a.say("Yetano Knowledge Coverage (%d packages in the catalog)\n\n", cov.Packages)
for _, m := range cov.Metrics {
a.say(" %-38s %5.1f%% (%d/%d)\n", m.Name, m.Pct, m.Have, m.Total)
}
if len(cov.ProgramsWithout) > 0 {
a.say("\nBig Picture programs not in the catalog yet: %s\n", strings.Join(cov.ProgramsWithout, ", "))
}
return nil
}
return a.usage("solution catalog " + args[0])
}
// catalogTest evaluates every example, generates its output and compares
// it with the golden files next to the solution (EX-02, QS-08). An example
// that stops being complete or changes output fails (ACC-J).
func (a *app) catalogTest(update bool) error {
failed := 0
for _, key := range catalog.SortedIDs(a.cat.Examples) {
x := a.cat.Examples[key]
s := a.cat.Lookup(x.Spec.Solution)
in := engine.NewInstance(x.Meta.ID, s, x.Spec.Mode)
in.Kind = catalog.KindInstance
for k, v := range x.Spec.Parameters {
in.Spec.Parameters[k] = v
}
in.Spec.Locale = "en"
st, err := a.eng.Evaluate(in, nil)
if err != nil {
return err
}
out, err := a.eng.Generate(st, in, nil, false)
if err != nil {
a.say("FAIL %s: %v\n", key, err)
failed++
continue
}
dir := filepath.Join(a.cat.Root, filepath.FromSlash(path.Dir(path.Dir(x.File))), "testdata", x.Meta.ID)
if update {
if err := os.RemoveAll(dir); err != nil {
return err
}
for _, f := range out.Files {
if f.Kind == "lock" {
continue // hashes of the whole catalog: not stable across unrelated edits
}
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, f.Content, 0o644); err != nil {
return err
}
}
a.say("UPDATED %s (%d files)\n", key, len(out.Files)-1)
continue
}
var diffs []string
want := map[string]bool{}
for _, f := range out.Files {
if f.Kind == "lock" {
continue
}
want[f.Path] = true
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f.Path)))
if err != nil {
diffs = append(diffs, f.Path+" (no golden file)")
} else if !bytes.Equal(b, f.Content) {
diffs = append(diffs, f.Path+" ("+firstDiff(b, f.Content)+")")
}
}
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() {
rel, _ := filepath.Rel(dir, p)
if !want[filepath.ToSlash(rel)] {
diffs = append(diffs, filepath.ToSlash(rel)+" (no longer generated)")
}
}
return nil
})
sort.Strings(diffs)
if len(diffs) > 0 {
a.say("FAIL %s\n", key)
for _, d := range diffs {
a.say(" %s\n", d)
}
failed++
continue
}
a.say("ok %s\n", key)
}
if failed > 0 {
a.note("%d example(s) failed; after an intended change: make golden (catalog test --update) and review the diff\n", failed)
return exitErr{ExitError, errors.New("")}
}
return nil
}
func firstDiff(a, b []byte) string {
la, lb := strings.Split(string(a), "\n"), strings.Split(string(b), "\n")
for i := 0; i < len(la) || i < len(lb); i++ {
var x, y string
if i < len(la) {
x = la[i]
}
if i < len(lb) {
y = lb[i]
}
if x != y {
return fmt.Sprintf("line %d: golden %q, now %q", i+1, trunc(x, 50), trunc(y, 50))
}
}
return "differs"
}
// ---- knowledge, open ------------------------------------------------------------------
func (a *app) knowledge(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s knowledge search|show|status|backlinks|coverage|validate", a.env.Program)
}
switch args[0] {
case "search":
return a.searchCmd(args[1:], nil)
case "show":
return a.open(args[1:])
case "validate", "lint":
return a.catalogCmd(append([]string{"validate"}, args[1:]...))
case "coverage":
return a.catalogCmd(append([]string{"coverage"}, args[1:]...))
case "status", "index":
fs := a.flags("knowledge " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
kinds := map[string]int{}
for _, e := range a.ix.Entries {
kinds[e.Kind]++
}
st := map[string]any{"catalog": a.cat.Root, "id": a.cat.Meta.ID, "version": a.cat.Meta.Version, "hash": a.cat.Hash(),
"entries": len(a.ix.Entries), "byKind": kinds, "manualTopics": len(a.ix.Topics), "sourcesNotAvailable": a.ix.Missing}
if args[0] == "index" {
st["index"] = a.ix.Entries
}
if a.jsonOut {
return a.printJSON(st)
}
a.say("catalog %s %s (%s)\nentries %d\n", a.cat.Meta.ID, a.cat.Meta.Version, a.cat.Root, len(a.ix.Entries))
for _, k := range sortedKeys(kinds) {
a.say(" %-12s %d\n", k, kinds[k])
}
if len(a.ix.Missing) > 0 {
a.say("not available locally: %s\n", strings.Join(a.ix.Missing, ", "))
}
return nil
case "backlinks":
fs := a.flags("knowledge backlinks")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s knowledge backlinks <yetano:ref>", a.env.Program)
}
bl := a.ix.BacklinksOf(fs.Arg(0))
if a.jsonOut {
if bl == nil {
bl = []string{}
}
return a.printJSON(bl)
}
for _, b := range bl {
a.say("%s\n", b)
}
return nil
}
return a.usage("knowledge " + args[0])
}
// open shows a reference in the terminal (REF-04): manual text, a
// solution's details, or where it lives.
func (a *app) open(args []string) error {
fs := a.flags("open")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s open <yetano:reference>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
r := fs.Arg(0)
if !strings.HasPrefix(r, "yetano:") {
r = "yetano:" + r
}
res, err := a.ix.Resolve(r)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if !res.Exists {
return fmt.Errorf("%w: %s", engine.ErrNotFound, r)
}
if !res.SectionExists {
return fmt.Errorf("%w: %s has no such section", engine.ErrNotFound, r)
}
if a.jsonOut {
return a.printJSON(res)
}
p, _ := ref.Parse(r)
switch p.Kind {
case ref.Solution:
return a.show([]string{p.Path[0]}, false)
case ref.Task:
return a.show([]string{p.Path[0]}, true)
case ref.Package:
return a.packageCmd([]string{p.Path[0]})
case ref.Manual:
if _, md, err := a.ix.Read(r); err == nil {
a.say("%s", md)
return nil
}
case ref.Example:
if x := a.cat.Examples[p.Path[0]+"/"+p.Path[1]]; x != nil {
b, _ := engine.Marshal(x.Spec)
a.say("# %s\n%s", x.Meta.Title, b)
return nil
}
case ref.Profile:
if pr := a.cat.Profiles[p.Path[0]+"/"+p.Path[1]]; pr != nil {
b, _ := engine.Marshal(pr.Spec)
a.say("# %s\n%s", firstNonEmpty(pr.Meta.Title, pr.Meta.ID), b)
return nil
}
case ref.Capability:
a.say("%s -- %s\n", res.Title, res.Summary)
for _, pr := range a.cat.ProvidersOf(p.Path[0]) {
a.say(" provided by %s\n", pr)
}
for _, b := range a.ix.BacklinksOf(r) {
a.say(" used by %s\n", b)
}
return nil
}
a.say("%s\n", res.Title)
if res.Summary != "" {
a.say("%s\n", wrap(res.Summary, 76, ""))
}
if res.Web != "" {
a.say("web: %s\n", res.Web)
}
if res.CLI != "" {
a.say("cli: %s\n", res.CLI)
}
if res.Note != "" {
a.say("note: %s\n", res.Note)
}
return nil
}