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>
This commit is contained in:
1 parent
586e76889c
commit
2481a0dd27
48 files changed
+10304
No files matched your search
@@ -0,0 +1,379 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// Lock pins what a generation was made from (LOCK-01). It has no
|
||||
// timestamps, so the same inputs give the same file.
|
||||
type Lock struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Spec LockSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// LockSpec is the content of a lock.
|
||||
type LockSpec struct {
|
||||
Generator string `yaml:"generator" json:"generator"`
|
||||
Catalog Pinned `yaml:"catalog" json:"catalog"`
|
||||
Solution Pinned `yaml:"solution" json:"solution"`
|
||||
Profiles []Pinned `yaml:"profiles,omitempty" json:"profiles,omitempty"`
|
||||
Packages []Pinned `yaml:"packages,omitempty" json:"packages,omitempty"`
|
||||
Capability string `yaml:"capabilities" json:"capabilities"` // hash of the capability files
|
||||
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||
Answers string `yaml:"answers" json:"answers"`
|
||||
Files []FileHash `yaml:"files" json:"files"`
|
||||
}
|
||||
|
||||
// Pinned is an entity with version and content hash.
|
||||
type Pinned struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||
Hash string `yaml:"sha256" json:"sha256"`
|
||||
}
|
||||
|
||||
// FileHash is a generated file and its hash.
|
||||
type FileHash = catalog.FileHash
|
||||
|
||||
// OutFile is one file of a generated solution directory.
|
||||
type OutFile struct {
|
||||
Path string `json:"path"`
|
||||
Kind string `json:"kind"` // instance | lock | config | architecture | handbook | plan | readme
|
||||
Content []byte `json:"-"`
|
||||
}
|
||||
|
||||
// Output is everything Generate produces.
|
||||
type Output struct {
|
||||
Files []OutFile `json:"files"`
|
||||
Lock *Lock `json:"lock"`
|
||||
}
|
||||
|
||||
// ManualReader gives the handbook existing manual text (implemented by
|
||||
// package knowledge). It may be nil: the handbook then links instead.
|
||||
type ManualReader interface {
|
||||
// Excerpt returns the title and Markdown of a manual reference
|
||||
// (yetano:manual/...#section), shortened to at most maxLines lines.
|
||||
Excerpt(ref string, maxLines int) (title, markdown string, ok bool)
|
||||
// Link returns a human link for a reference (web URL or CLI command).
|
||||
Link(ref string) string
|
||||
}
|
||||
|
||||
// Generate renders all output files of a complete state. It refuses an
|
||||
// incomplete state unless allowIncomplete is set.
|
||||
func (e *Engine) Generate(st *State, in *Instance, mr ManualReader, allowIncomplete bool) (*Output, error) {
|
||||
if !st.Complete && !allowIncomplete {
|
||||
return nil, fmt.Errorf("%w: %s", ErrIncomplete, incompleteText(st))
|
||||
}
|
||||
s := e.Cat.Lookup(st.Solution.ID)
|
||||
out := &Output{}
|
||||
addf := func(path, kind string, b []byte) {
|
||||
out.Files = append(out.Files, OutFile{Path: path, Kind: kind, Content: b})
|
||||
}
|
||||
inst := *in
|
||||
inst.Kind = catalog.KindInstance
|
||||
inst.Spec.Solution.Version = s.Meta.Version
|
||||
inst.Spec.Cursor = ""
|
||||
b, err := Marshal(&inst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addf("solution.yaml", "instance", b)
|
||||
for _, f := range st.Files {
|
||||
addf(f.Path, "config", []byte(f.Content))
|
||||
}
|
||||
gj, _ := json.MarshalIndent(st.Graph, "", " ")
|
||||
addf("architecture/graph.json", "architecture", append(gj, '\n'))
|
||||
addf("architecture/graph.txt", "architecture", []byte(GraphText(st.Graph)))
|
||||
pb, err := Marshal(PlanOf(st))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addf("deployment-plan.yaml", "plan", pb)
|
||||
for _, h := range e.Handbook(st, mr) {
|
||||
addf(h.Path, "handbook", h.Content)
|
||||
}
|
||||
addf("README.md", "readme", []byte(readme(st)))
|
||||
sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Path < out.Files[j].Path })
|
||||
for _, f := range out.Files {
|
||||
if !catalog.SafeRelPath(f.Path) {
|
||||
return nil, fmt.Errorf("refusing unsafe output path %q", f.Path)
|
||||
}
|
||||
}
|
||||
out.Lock = e.lock(st, s, in, out.Files)
|
||||
lb, err := Marshal(out.Lock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.Files = append(out.Files, OutFile{Path: "solution.lock.yaml", Kind: "lock", Content: lb})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ErrIncomplete: required answers are missing or errors remain.
|
||||
var ErrIncomplete = errors.New("the solution is not complete")
|
||||
|
||||
func incompleteText(st *State) string {
|
||||
var parts []string
|
||||
if len(st.Progress.Missing) > 0 {
|
||||
parts = append(parts, "missing: "+strings.Join(st.Progress.Missing, ", "))
|
||||
}
|
||||
for _, m := range st.Messages {
|
||||
if m.Severity == "error" {
|
||||
parts = append(parts, m.Text)
|
||||
}
|
||||
}
|
||||
for _, q := range st.Questions {
|
||||
for _, e := range q.Errors {
|
||||
parts = append(parts, q.ID+": "+e)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
func hashBytes(b []byte) string {
|
||||
h := sha256.Sum256(b)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func (e *Engine) lock(st *State, s *catalog.Solution, in *Instance, files []OutFile) *Lock {
|
||||
c := e.Cat
|
||||
l := &Lock{APIVersion: catalog.APIVersion, Kind: "SolutionLock"}
|
||||
l.Spec.Generator = GeneratorVersion
|
||||
l.Spec.Catalog = Pinned{ID: c.Meta.ID, Version: c.Meta.Version, Hash: c.Hash()}
|
||||
l.Spec.Solution = Pinned{ID: s.Meta.ID, Version: s.Meta.Version, Hash: s.Hash}
|
||||
for _, p := range st.Packages {
|
||||
if !p.Selected {
|
||||
continue
|
||||
}
|
||||
if cp := c.Packages[p.ID]; cp != nil {
|
||||
l.Spec.Packages = append(l.Spec.Packages, Pinned{ID: p.ID, Hash: cp.Hash})
|
||||
}
|
||||
if p.Profile != "" {
|
||||
chain, _ := c.ProfileChain(p.ID, p.Profile)
|
||||
for _, pr := range chain {
|
||||
l.Spec.Profiles = append(l.Spec.Profiles, Pinned{ID: pr.Key(), Hash: pr.Hash})
|
||||
}
|
||||
}
|
||||
}
|
||||
var capFiles, bpFiles []string
|
||||
for _, f := range c.Files {
|
||||
if strings.HasPrefix(f.Path, "bigpicture:") {
|
||||
bpFiles = append(bpFiles, f.Path+" "+f.Hash)
|
||||
} else if strings.HasPrefix(f.Path, "capabilities") {
|
||||
capFiles = append(capFiles, f.Path+" "+f.Hash)
|
||||
}
|
||||
}
|
||||
l.Spec.Capability = hashBytes([]byte(strings.Join(capFiles, "\n")))
|
||||
if len(bpFiles) > 0 {
|
||||
l.Spec.BigPicture = hashBytes([]byte(strings.Join(bpFiles, "\n")))
|
||||
}
|
||||
ab, _ := json.Marshal(in.Spec.Parameters) // map keys are sorted by encoding/json
|
||||
ob, _ := json.Marshal(in.Spec.Overrides)
|
||||
l.Spec.Answers = hashBytes(append(append(ab, '\n'), ob...))
|
||||
for _, f := range files {
|
||||
l.Spec.Files = append(l.Spec.Files, FileHash{Path: f.Path, Hash: hashBytes(f.Content)})
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// LockDrift lists what changed meaning between a previous lock and now
|
||||
// (LOCK-02/03): a changed solution, profile or package definition.
|
||||
func LockDrift(prev, cur *Lock) []string {
|
||||
var out []string
|
||||
if prev.Spec.Solution.Hash != cur.Spec.Solution.Hash {
|
||||
out = append(out, fmt.Sprintf("solution %s changed (%s -> %s)", cur.Spec.Solution.ID, prev.Spec.Solution.Version, cur.Spec.Solution.Version))
|
||||
}
|
||||
cmp := func(kind string, a, b []Pinned) {
|
||||
m := map[string]string{}
|
||||
for _, p := range a {
|
||||
m[p.ID] = p.Hash
|
||||
}
|
||||
for _, p := range b {
|
||||
if h, ok := m[p.ID]; !ok {
|
||||
out = append(out, fmt.Sprintf("%s %s is new", kind, p.ID))
|
||||
} else if h != p.Hash {
|
||||
out = append(out, fmt.Sprintf("%s %s changed", kind, p.ID))
|
||||
}
|
||||
delete(m, p.ID)
|
||||
}
|
||||
for id := range m {
|
||||
out = append(out, fmt.Sprintf("%s %s is no longer used", kind, id))
|
||||
}
|
||||
}
|
||||
cmp("profile", prev.Spec.Profiles, cur.Spec.Profiles)
|
||||
cmp("package", prev.Spec.Packages, cur.Spec.Packages)
|
||||
if prev.Spec.Capability != cur.Spec.Capability {
|
||||
out = append(out, "the capability catalog changed")
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// ReadLock reads dir/solution.lock.yaml; a missing file is (nil, nil).
|
||||
func ReadLock(dir string) (*Lock, error) {
|
||||
f, err := os.Open(filepath.Join(dir, "solution.lock.yaml"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
var l Lock
|
||||
if err := strict(f, &l); err != nil {
|
||||
return nil, fmt.Errorf("solution.lock.yaml: %w", err)
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
// ErrModified: a file in the output directory was changed by hand.
|
||||
var ErrModified = errors.New("output directory has changes that would be overwritten")
|
||||
|
||||
// Write writes out into dir (CONF-05, CONF-06). Without force it refuses
|
||||
// to overwrite a file that differs from what the previous lock recorded
|
||||
// (a hand edit) or a file the previous generation did not write. Files of
|
||||
// the previous generation that are no longer produced are removed only
|
||||
// when they are unchanged.
|
||||
func Write(dir string, out *Output, force bool) error {
|
||||
prev, err := ReadLock(dir)
|
||||
if err != nil && !force {
|
||||
return err
|
||||
}
|
||||
known := map[string]string{}
|
||||
if prev != nil {
|
||||
for _, f := range prev.Spec.Files {
|
||||
known[f.Path] = f.Hash
|
||||
}
|
||||
known["solution.lock.yaml"] = "*"
|
||||
}
|
||||
var conflicts []string
|
||||
for _, f := range out.Files {
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
cur, err := os.ReadFile(p)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, isKnown := known[f.Path]
|
||||
switch {
|
||||
case h == "*":
|
||||
case !isKnown && hashBytes(cur) != hashBytes(f.Content):
|
||||
conflicts = append(conflicts, f.Path+" (not written by the guide)")
|
||||
case isKnown && hashBytes(cur) != h:
|
||||
conflicts = append(conflicts, f.Path+" (changed by hand)")
|
||||
}
|
||||
}
|
||||
if len(conflicts) > 0 && !force {
|
||||
return fmt.Errorf("%w: %s; use --force to overwrite", ErrModified, strings.Join(conflicts, ", "))
|
||||
}
|
||||
for _, f := range out.Files {
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, f.Content, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// stale files of the previous generation
|
||||
now := map[string]bool{}
|
||||
for _, f := range out.Files {
|
||||
now[f.Path] = true
|
||||
}
|
||||
if prev != nil {
|
||||
for _, f := range prev.Spec.Files {
|
||||
if now[f.Path] || !catalog.SafeRelPath(f.Path) {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
if cur, err := os.ReadFile(p); err == nil && hashBytes(cur) == f.Hash {
|
||||
os.Remove(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Plan is the deployment plan: what an operator (or a later apply) does,
|
||||
// in order. It is never executed by the engine (LIFE-01).
|
||||
type Plan struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Spec PlanSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// PlanSpec lists files, steps and checks.
|
||||
type PlanSpec struct {
|
||||
Solution string `yaml:"solution" json:"solution"`
|
||||
Instance string `yaml:"instance" json:"instance"`
|
||||
Target string `yaml:"target" json:"target"`
|
||||
Apply string `yaml:"apply" json:"apply"`
|
||||
Packages []string `yaml:"packages" json:"packages"`
|
||||
Files []string `yaml:"files" json:"files"`
|
||||
Steps []PlannedStep `yaml:"steps" json:"steps"`
|
||||
Checks []PlanCheck `yaml:"checks" json:"checks"`
|
||||
}
|
||||
|
||||
// PlanCheck is a check to run after applying.
|
||||
type PlanCheck struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Run string `yaml:"run,omitempty" json:"run,omitempty"`
|
||||
}
|
||||
|
||||
// PlanOf builds the plan of a state.
|
||||
func PlanOf(st *State) *Plan {
|
||||
p := &Plan{APIVersion: catalog.APIVersion, Kind: "DeploymentPlan"}
|
||||
p.Spec.Solution = st.Solution.ID + " " + st.Solution.Version
|
||||
p.Spec.Instance = st.Instance
|
||||
p.Spec.Target = firstNonEmpty(st.Platform, "local")
|
||||
p.Spec.Apply = "manual: the guide does not apply plans yet; run the steps yourself (LIFE-01)"
|
||||
for _, pk := range st.Packages {
|
||||
if pk.Selected {
|
||||
p.Spec.Packages = append(p.Spec.Packages, pk.ID)
|
||||
}
|
||||
}
|
||||
for _, f := range st.Files {
|
||||
p.Spec.Files = append(p.Spec.Files, f.Path)
|
||||
}
|
||||
p.Spec.Steps = st.Steps
|
||||
if p.Spec.Steps == nil {
|
||||
p.Spec.Steps = []PlannedStep{}
|
||||
}
|
||||
for _, c := range st.Checks {
|
||||
if c.Status != CheckNotApplicable {
|
||||
p.Spec.Checks = append(p.Spec.Checks, PlanCheck{ID: c.ID, Title: c.Title, Run: c.Run})
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func readme(st *State) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "# %s\n\n", firstNonEmpty(st.Instance, st.Solution.Title))
|
||||
fmt.Fprintf(&b, "Solution: %s (`%s` %s), generated by the Yetano Solutions Guide.\n\n", st.Solution.Title, st.Solution.ID, st.Solution.Version)
|
||||
b.WriteString("| Path | Content |\n|---|---|\n")
|
||||
b.WriteString("| `solution.yaml` | your answers (SolutionInstance); regenerate with `yet solution generate --file solution.yaml --output .` |\n")
|
||||
b.WriteString("| `solution.lock.yaml` | what this was generated from (catalog, profiles, file hashes) |\n")
|
||||
b.WriteString("| `config/` | native configuration files, one directory per package |\n")
|
||||
b.WriteString("| `deployment-plan.yaml` | the steps to install, configure and check it (not executed by the guide) |\n")
|
||||
b.WriteString("| `architecture/` | the resolved architecture (`graph.json`, `graph.txt`) |\n")
|
||||
b.WriteString("| `handbook/` | your handbook: start with `handbook/index.md` |\n\n")
|
||||
b.WriteString("Nothing here has been installed or changed on any system.\n")
|
||||
return b.String()
|
||||
}
|
||||
Reference in new issue
Block a user