diff --git a/docs/prds/skill-curator.md b/docs/prds/skill-curator.md new file mode 100644 index 000000000..41c4a3203 --- /dev/null +++ b/docs/prds/skill-curator.md @@ -0,0 +1,176 @@ +# Skill curator (reference implementation) -- decision + +**Status:** Approved for archie-core-1786637499206 implementation +**Date:** 2026-09-02 +**Beads issue:** `archie-core-1786637499206` +**Parent epic:** `archie-core-1786637500725` (curator engine) + +## Decision + +The skill curator's v1 scope is **mechanical validation and safe +normalization only** -- it never rewrites skill prose, never deletes a +skill, and never calls the model. Each pass: + +1. Lists every skill under one configured root. +2. Reads each `SKILL.md` and attempts to parse its frontmatter + (`internal/skill.Parse`). +3. Records an `Action` for any structural problem: a parse failure, or a + missing `name`/`description` in the frontmatter that parsed. +4. Normalizes trivial whitespace (trailing whitespace per line, exactly + one trailing newline) and writes back **only** when normalization + actually changes the bytes, recording an `Action` for that write. + +Nothing here needs judgment. "Review, prune, and improve" -- the epic's +framing -- is real for v1 but deliberately narrow: review is structural +validation, improve is whitespace normalization, and prune is *reporting* +a problem, never removing a skill. `Manifest.Skills = true` still marks +this curator agentic (existing `agentic()` rule), so it receives model +access from the registrar -- unused today, but nothing about the contract +or the runtime needs to change to let a later version reason about +content quality using it. + +## Why this scope, not more + +An autonomous process that rewrites or deletes a user's skill content +is a real risk with no undo path today (no draft/approval flow for +curator writes exists yet, unlike the workflow engine's PR-based review). +The epic's own stated purpose for this issue is proving the curator +contract holds for a second, structurally different consumer than the +session-memory curator (files-as-skills vs. observations-as-memory), not +solving "what makes a skill good." Mechanical validation is real, +useful, safe to run unattended, and fully exercises +List/Read/Write -- every method `curator.SkillStore` declares except +`Delete`, which this curator's Pass never has a safe reason to call in +v1 (kept implemented on the store adapter regardless, since the +interface requires it and a future consumer may). + +## Why `internal/skill` isn't `curator.SkillStore` directly + +`internal/skill.Discover` parses every `SKILL.md` under a root and +returns an error for the **whole** call if any one of them fails to +parse -- the read side was built for "load the catalog to start the +daemon," where one bad skill failing the whole boot is arguably correct, +not for "review each skill and report what's wrong with it +individually." A per-skill parse failure must become one `Action`, not +abort the pass before any skill is reviewed. So +`internal/infrastructure/skillcurator` gets its own thin store adapter +that lists raw directory names and reads/writes raw `SKILL.md` bytes +per name; the skill curator itself calls `internal/skill.Parse` on each +one, isolated per skill. + +## Root scope + +One root only, resolved the same way `loadWorkflows` already resolves +`skillsBase` (`cfg.SkillsDir`, falling back to `cfg.WorkDir`) -- not +every root `skill.CatalogRoots`/`DefaultRoots` would read for a model +(which layers a shared dir over the per-profile one). Write and Delete +need one unambiguous target; a curator that could write into a shared, +multi-tenant skills directory is a bigger decision than this issue +covers. The model still sees the full multi-root catalog through the +existing read path -- this curator only maintains the local one. + +## Shape + +### `internal/infrastructure/skillcurator/store.go` + +```go +// Store implements curator.SkillStore over one root directory's +// .agents/skills/*/SKILL.md files, tolerating a per-skill parse failure +// as the curator's problem to report rather than this store's problem +// to abort on. +type Store struct { root string } + +func NewStore(root string) *Store + +func (s *Store) List(ctx context.Context) ([]curator.SkillRef, error) +func (s *Store) Read(ctx context.Context, name string) (curator.Skill, error) +func (s *Store) Write(ctx context.Context, sk curator.Skill) error +func (s *Store) Delete(ctx context.Context, name string) error +``` + +`Read` best-effort parses frontmatter for `Skill.Description` (empty on +parse failure -- not this method's job to report that; `Pass` does, via +its own `skill.Parse` call on `Skill.Content`). `Write` rejects a name +that does not already exist as a directory (this store curates existing +skills; creating a new one is out of scope). `Delete` removes the whole +skill directory, matching "delete a skill," not just `SKILL.md`. + +### `internal/infrastructure/skillcurator/skillcurator.go` + +```go +// Curator implements domain/curator.CuratorEngine. See +// docs/prds/skill-curator.md for what a pass does and why. +type Curator struct { /* unexported: registrar view, interval */ } + +func New(interval time.Duration) *Curator + +func (c *Curator) Manifest() curator.Manifest { + return curator.Manifest{Interval: c.interval, Skills: true} +} + +func (c *Curator) Check(ctx context.Context) (bool, error) // len(skills) > 0 +func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) +``` + +`Pass` walks every skill via `Bind`'s `Skills` (the filtered +`SkillStore` the registry already narrows to declared curators, see +`Registry.filter`), classifying each into exactly one of: + +- **parse failure** -- `Action{Type: "skill.invalid", Reason: "frontmatter failed to parse"}` +- **missing required field** -- `Action{Type: "skill.incomplete", Reason: "name" | "description"}` +- **normalized** -- content changed by whitespace cleanup, written back, + `Action{Type: "skill.normalized", Detail: ": trimmed trailing whitespace"}` +- **clean** -- no action recorded (a pass with nothing to report is not + an error, and not every skill needs an entry every time) + +One pass reviews every skill currently on disk; there is no +per-skill "already reviewed, skip" state; this errs toward re-checking +over missing a regression, and the cost is cheap (no model calls, just +file reads). + +## What we deliberately do NOT do + +- **No LLM-authored rewrites of skill content.** Real "improve" in the + sense of better prose is out of scope until there is a review/approval + path for autonomous content changes to something a human wrote. +- **No automatic deletion of a skill**, however broken. `Delete` exists + on the store for a future consumer; this curator's `Pass` never calls + it. +- **No dangling-tool-reference checking** (a skill's + `metadata.archie.tools` naming a tool that no longer exists). The + mechanism to check "does this tool exist" belongs to a tool registry + this curator has no access to and shouldn't be given for this -- + `curator.ToolBuilder.Build` resolves the curator's *own* declared + tools, not an arbitrary existence check against skill-referenced + names. A real fix here is a separate, better-scoped issue. +- **No multi-root awareness.** One configured root, matching + `loadWorkflows`'s existing resolution, not the full layered catalog a + chat turn sees. +- **No new curator-specific webui or chat surface.** Activity is visible + through the existing curator observability surface + (`archie-core-1786637489932`, already shipped) -- `/api/curators` and + the dashboard Curators page already show any registered curator's + recent actions. + +## Acceptance criteria + +Restated from the issue against this shape: + +1. Registers and runs through `curator.Registry` with no curator-specific + special-casing in the runtime -- proven by using the existing + `Registry.Register`/`Runtime` path, no new registry method. +2. Its changes to skills are observable and attributable -- every write + is preceded by an `Action` recording what changed and why, surfaced + through the existing curator activity tracker. +3. It operates within its declared tool set and cannot reach tools it + did not declare -- `Manifest.Tools` is empty; nothing about this + curator ever touches `Registrar.Tools`. + +## Files this change adds + +- `internal/infrastructure/skillcurator/store.go` -- `curator.SkillStore` adapter +- `internal/infrastructure/skillcurator/store_test.go` +- `internal/infrastructure/skillcurator/skillcurator.go` -- the `CuratorEngine` +- `internal/infrastructure/skillcurator/skillcurator_test.go` +- `internal/app/archied/bootstrap.go` -- register it in `setupCurators`, root + resolved the same way `loadWorkflows` resolves `skillsBase` diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index abccd1406..986916c6a 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -43,6 +43,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory" "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" + "github.com/samcharles93/archie-core/internal/infrastructure/skillcurator" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/memory" "github.com/samcharles93/archie-core/internal/plugin" @@ -827,6 +828,14 @@ func (b *boot) setupMemoryAll() error { // never backpressure the daemon or a chat turn. func (b *boot) setupCurators(ctx context.Context) { log := b.log + // Skills root matches loadWorkflows' own resolution of skillsBase -- + // the skill curator maintains the same local skills this daemon + // already treats as authoritative, not the full multi-root catalog a + // chat turn reads. See docs/prds/skill-curator.md. + skillsRoot := b.cfg.SkillsDir + if skillsRoot == "" { + skillsRoot = b.cfg.WorkDir + } b.curatorRegistry = curator.NewRegistry(curator.Registrar{ Events: curatorEventSink{b.bus}, // b.memEngines (*domainmemory.Registry) satisfies @@ -834,7 +843,14 @@ func (b *boot) setupCurators(ctx context.Context) { // adapter needed. Set by setupMemoryAll, which Run() calls before // setupCurators. MemoryEngines: b.memEngines, + // Skills is a shared host service like Events/MemoryEngines -- + // registry.filter narrows it out of the view for any curator that + // doesn't declare Manifest.Skills, per curator not per instance. + Skills: skillcurator.NewStore(skillsRoot), }) + if err := b.curatorRegistry.Register(skillcurator.New(skillcurator.DefaultInterval)); err != nil { + log.Error("skill curator registration failed", "err", err) + } // The runtime owns the per-curator loops (archie-core-89x): one // goroutine per curator, wake nudges, per-pass budgets, panic // recovery, bounded shutdown. Stop order at shutdown: runtime first diff --git a/internal/infrastructure/skillcurator/skillcurator.go b/internal/infrastructure/skillcurator/skillcurator.go new file mode 100644 index 000000000..34bb5570d --- /dev/null +++ b/internal/infrastructure/skillcurator/skillcurator.go @@ -0,0 +1,163 @@ +package skillcurator + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/samcharles93/archie-core/internal/domain/curator" + "github.com/samcharles93/archie-core/internal/skill" +) + +// Name is the identifier this curator registers under. +const Name = "skill" + +// DefaultInterval is the check-in cadence used when nothing more specific +// configures one. No config surface for per-curator intervals exists yet +// (this is the first real curator registered); this constant is the +// obvious place a future one would read from. +const DefaultInterval = time.Hour + +const ( + // ActionInvalid records a skill whose SKILL.md failed to parse. + ActionInvalid = "skill.invalid" + // ActionIncomplete records a skill that parsed but is missing a + // required frontmatter field. + ActionIncomplete = "skill.incomplete" + // ActionNormalized records a skill whose content was rewritten by + // whitespace normalization. + ActionNormalized = "skill.normalized" +) + +// Curator implements domain/curator.CuratorEngine. See +// docs/prds/skill-curator.md for what a pass does and why: mechanical +// validation and safe whitespace normalization only -- no LLM-authored +// rewrites, no deletion. +type Curator struct { + interval time.Duration + host curator.Registrar +} + +// New builds a skill curator that checks in every interval. +func New(interval time.Duration) *Curator { + return &Curator{interval: interval} +} + +func (c *Curator) Name() string { return Name } +func (c *Curator) Version() string { return "1" } + +func (c *Curator) Manifest() curator.Manifest { + return curator.Manifest{Interval: c.interval, Skills: true} +} + +func (c *Curator) Bind(host curator.Registrar) { c.host = host } + +func (c *Curator) Start(context.Context) error { return nil } + +func (c *Curator) Health(context.Context) curator.Health { + return curator.Health{Status: curator.HealthHealthy} +} + +func (c *Curator) Stop(context.Context) error { return nil } + +// Check reports whether there is anything to review. Cheap by +// construction: a directory listing, no model calls, no parsing. +func (c *Curator) Check(ctx context.Context) (bool, error) { + refs, err := c.host.Skills.List(ctx) + if err != nil { + return false, err + } + return len(refs) > 0, nil +} + +// Pass reviews every skill currently on disk. There is no per-skill +// "already reviewed" state: each pass re-checks everything, which is +// cheap (file reads, no model calls) and errs toward catching a +// regression over missing one. See docs/prds/skill-curator.md for the +// exact classification rules. +func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) { + refs, err := c.host.Skills.List(ctx) + if err != nil { + return curator.PassResult{}, err + } + + var actions []curator.Action + for _, ref := range refs { + acts, err := c.reviewOne(ctx, ref.Name) + if err != nil { + return curator.PassResult{}, fmt.Errorf("skill %q: %w", ref.Name, err) + } + actions = append(actions, acts...) + } + return curator.PassResult{Actions: actions}, nil +} + +// reviewOne classifies a single skill and, for a normalizable one, +// writes the cleaned content back. It never returns more than one +// Action: a parse failure and a missing field can't both be reported for +// the same skill in the same pass (a Frontmatter that failed to parse +// has no fields to check), and a normalization is reported once even +// though it may have fixed multiple lines. +func (c *Curator) reviewOne(ctx context.Context, name string) ([]curator.Action, error) { + sk, err := c.host.Skills.Read(ctx, name) + if err != nil { + return nil, err + } + + fm, _, parseErr := skill.Parse([]byte(sk.Content)) + if parseErr != nil { + return []curator.Action{{ + Type: ActionInvalid, + Detail: name, + Reason: parseErr.Error(), + }}, nil + } + + if missing := missingField(fm); missing != "" { + return []curator.Action{{ + Type: ActionIncomplete, + Detail: name, + Reason: "missing " + missing, + }}, nil + } + + normalized := normalizeWhitespace(sk.Content) + if normalized == sk.Content { + return nil, nil + } + if err := c.host.Skills.Write(ctx, curator.Skill{Name: name, Content: normalized}); err != nil { + return nil, err + } + return []curator.Action{{ + Type: ActionNormalized, + Detail: name, + Reason: "trailing whitespace or missing final newline", + }}, nil +} + +// missingField returns the name of the first required frontmatter field +// fm lacks, or "" if both are present. Order (name before description) +// only affects which single reason is reported when both are missing; +// either is worth flagging on its own. +func missingField(fm *skill.Frontmatter) string { + if strings.TrimSpace(fm.Name) == "" { + return "name" + } + if strings.TrimSpace(fm.Description) == "" { + return "description" + } + return "" +} + +// normalizeWhitespace trims trailing whitespace from every line and +// ensures the content ends in exactly one newline. It never touches +// leading whitespace (meaningful in YAML frontmatter and Markdown list +// nesting) or blank-line structure. +func normalizeWhitespace(content string) string { + lines := strings.Split(content, "\n") + for i, line := range lines { + lines[i] = strings.TrimRight(line, " \t") + } + return strings.TrimRight(strings.Join(lines, "\n"), "\n") + "\n" +} diff --git a/internal/infrastructure/skillcurator/skillcurator_test.go b/internal/infrastructure/skillcurator/skillcurator_test.go new file mode 100644 index 000000000..ecec099ff --- /dev/null +++ b/internal/infrastructure/skillcurator/skillcurator_test.go @@ -0,0 +1,212 @@ +package skillcurator + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/domain/curator" +) + +func newTestCurator(t *testing.T, root string) *Curator { + t.Helper() + c := New(time.Hour) + c.Bind(curator.Registrar{Skills: NewStore(root)}) + return c +} + +func TestCheckReportsFalseWithNoSkills(t *testing.T) { + t.Parallel() + c := newTestCurator(t, t.TempDir()) + ok, err := c.Check(context.Background()) + if err != nil { + t.Fatalf("Check() = %v, want nil", err) + } + if ok { + t.Error("Check() = true, want false: no skills to review") + } +} + +func TestCheckReportsTrueWithASkill(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + c := newTestCurator(t, root) + + ok, err := c.Check(context.Background()) + if err != nil { + t.Fatalf("Check() = %v, want nil", err) + } + if !ok { + t.Error("Check() = false, want true: a skill exists to review") + } +} + +func TestPassFlagsAParseFailureWithoutWriting(t *testing.T) { + t.Parallel() + root := t.TempDir() + const broken = "---\nname: [unterminated\n---\n" + writeSkill(t, root, "broken", broken) + c := newTestCurator(t, root) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 1 || res.Actions[0].Type != ActionInvalid { + t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionInvalid) + } + if res.Actions[0].Detail != "broken" { + t.Errorf("Detail = %q, want the skill name", res.Actions[0].Detail) + } + + // The broken skill must be untouched: this curator never rewrites + // content it could not parse. + got, err := NewStore(root).Read(context.Background(), "broken") + if err != nil { + t.Fatalf("Read(broken) after Pass = %v", err) + } + if got.Content != broken { + t.Errorf("Content after Pass = %q, want unchanged %q", got.Content, broken) + } +} + +func TestPassFlagsAMissingRequiredField(t *testing.T) { + t.Parallel() + tests := []struct { + name string + content string + }{ + {"missing name", "---\ndescription: does a thing\n---\nBody.\n"}, + {"missing description", "---\nname: my-skill\n---\nBody.\n"}, + {"missing both", "---\nversion: \"1\"\n---\nBody.\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "incomplete", tt.content) + c := newTestCurator(t, root) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 1 || res.Actions[0].Type != ActionIncomplete { + t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionIncomplete) + } + }) + } +} + +func TestPassNormalizesTrailingWhitespaceAndWritesBack(t *testing.T) { + t.Parallel() + root := t.TempDir() + const messy = "---\nname: tdd-bugfix \ndescription: Fix a bug\n---\nBody text. \nMore.\t\n\n\n" + writeSkill(t, root, "tdd-bugfix", messy) + c := newTestCurator(t, root) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 1 || res.Actions[0].Type != ActionNormalized { + t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionNormalized) + } + + got, err := NewStore(root).Read(context.Background(), "tdd-bugfix") + if err != nil { + t.Fatalf("Read() after Pass = %v", err) + } + if strings.Contains(got.Content, " \n") || strings.Contains(got.Content, "\t\n") { + t.Errorf("Content still has trailing whitespace: %q", got.Content) + } + if strings.HasSuffix(got.Content, "\n\n") { + t.Errorf("Content still has multiple trailing newlines: %q", got.Content) + } +} + +func TestPassLeavesACleanSkillUntouchedWithNoAction(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + c := newTestCurator(t, root) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 0 { + t.Fatalf("Actions = %#v, want none for an already-clean skill", res.Actions) + } +} + +func TestPassReviewsEverySkillIndependently(t *testing.T) { + // A parse failure in one skill must not abort review of the others -- + // the whole reason this curator has its own store instead of + // delegating List/Read to internal/skill.Discover. + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "broken", "---\nname: [unterminated\n---\n") + writeSkill(t, root, "clean", validSkill) + writeSkill(t, root, "incomplete", "---\nname: x\n---\nBody.\n") + c := newTestCurator(t, root) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 2 { + t.Fatalf("Actions = %#v, want exactly 2 (broken + incomplete; clean reports nothing)", res.Actions) + } + byType := map[string]bool{} + for _, a := range res.Actions { + byType[a.Type+":"+a.Detail] = true + } + if !byType[ActionInvalid+":broken"] { + t.Errorf("missing invalid action for 'broken': %#v", res.Actions) + } + if !byType[ActionIncomplete+":incomplete"] { + t.Errorf("missing incomplete action for 'incomplete': %#v", res.Actions) + } +} + +func TestManifestDeclaresOnlySkills(t *testing.T) { + t.Parallel() + c := New(30 * time.Minute) + m := c.Manifest() + if !m.Skills { + t.Error("Manifest().Skills = false, want true") + } + if len(m.Tools) != 0 { + t.Errorf("Manifest().Tools = %v, want none: this curator never reaches tools", m.Tools) + } + if m.MemoryEngine != "" { + t.Errorf("Manifest().MemoryEngine = %q, want empty: this curator does not use memory", m.MemoryEngine) + } + if m.Interval != 30*time.Minute { + t.Errorf("Manifest().Interval = %v, want the configured 30m", m.Interval) + } +} + +func TestRegistersAndRunsThroughTheRegistry(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + + r := curator.NewRegistry(curator.Registrar{Skills: NewStore(root)}) + c := New(time.Hour) + if err := r.Register(c); err != nil { + t.Fatalf("Register() = %v, want nil", err) + } + if err := r.Start(context.Background()); err != nil { + t.Fatalf("registry Start() = %v, want nil", err) + } + if health := r.Health(context.Background()); health[Name].Status != curator.HealthHealthy { + t.Errorf("Health() = %v, want healthy", health) + } + if err := r.Stop(context.Background()); err != nil { + t.Fatalf("registry Stop() = %v, want nil", err) + } +} diff --git a/internal/infrastructure/skillcurator/store.go b/internal/infrastructure/skillcurator/store.go new file mode 100644 index 000000000..4f06669ac --- /dev/null +++ b/internal/infrastructure/skillcurator/store.go @@ -0,0 +1,123 @@ +// Package skillcurator implements domain/curator.CuratorEngine for skill +// maintenance. See docs/prds/skill-curator.md for what a pass does and +// why, and the scope this package deliberately does not cover. +package skillcurator + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/samcharles93/archie-core/internal/domain/curator" + "github.com/samcharles93/archie-core/internal/skill" +) + +// skillsDir mirrors internal/skill's own unexported constant of the same +// name and value -- the discovery convention (.agents/skills/) is fixed +// across both packages, not configurable per caller. +const skillsDir = ".agents/skills" + +// skillFile is the file name every skill's definition lives in, within +// its own directory under skillsDir. +const skillFile = "SKILL.md" + +// Store implements curator.SkillStore over one root directory's +// .agents/skills/*/SKILL.md files. Unlike internal/skill.Discover, which +// parses every skill up front and fails the whole call if any one of +// them doesn't parse, Store's List and Read never parse frontmatter +// themselves beyond a best-effort Description -- a per-skill parse +// failure is the curator's problem to report as an Action, not this +// store's problem to abort on. See docs/prds/skill-curator.md. +type Store struct { + root string +} + +// NewStore builds a Store rooted at root (root/.agents/skills/...). +func NewStore(root string) *Store { + return &Store{root: root} +} + +func (s *Store) skillsPath() string { + return filepath.Join(s.root, skillsDir) +} + +func (s *Store) skillPath(name string) string { + return filepath.Join(s.skillsPath(), name, skillFile) +} + +// List returns every skill directory under root, in directory order. A +// directory with no SKILL.md is skipped -- consistent with +// internal/skill.Discover's own treatment of that case -- and a missing +// skills directory returns an empty list, not an error, matching +// internal/skill's discovery convention (missing directory is not an +// error). +func (s *Store) List(_ context.Context) ([]curator.SkillRef, error) { + entries, err := os.ReadDir(s.skillsPath()) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("skillcurator: reading %s: %w", s.skillsPath(), err) + } + + var refs []curator.SkillRef + for _, e := range entries { + if !e.IsDir() { + continue + } + path := s.skillPath(e.Name()) + if _, err := os.Stat(path); err != nil { + continue + } + refs = append(refs, curator.SkillRef{Name: e.Name(), Path: path}) + } + return refs, nil +} + +// Read returns the named skill's raw SKILL.md content. Description is a +// best-effort frontmatter read: empty on a parse failure, which Read +// does not treat as an error -- Pass is what decides a parse failure is +// worth reporting, and it needs the raw Content to do so via its own +// skill.Parse call regardless of whether this convenience field could be +// populated. +func (s *Store) Read(_ context.Context, name string) (curator.Skill, error) { + path := s.skillPath(name) + data, err := os.ReadFile(path) + if err != nil { + return curator.Skill{}, fmt.Errorf("skillcurator: reading %s: %w", path, err) + } + sk := curator.Skill{Name: name, Content: string(data)} + if fm, _, err := skill.Parse(data); err == nil { + sk.Description = fm.Description + } + return sk, nil +} + +// Write persists s.Content to the named skill's SKILL.md. The skill's +// directory must already exist -- Write curates an existing skill, it +// does not create a new one, which is a bigger decision (naming, +// directory layout, an author writing the rest of the frontmatter) that +// this store does not make. +func (s *Store) Write(_ context.Context, sk curator.Skill) error { + dir := filepath.Join(s.skillsPath(), sk.Name) + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return fmt.Errorf("skillcurator: skill %q does not exist under %s", sk.Name, s.skillsPath()) + } + if err := os.WriteFile(s.skillPath(sk.Name), []byte(sk.Content), 0o644); err != nil { + return fmt.Errorf("skillcurator: writing %s: %w", s.skillPath(sk.Name), err) + } + return nil +} + +// Delete removes the named skill's entire directory (SKILL.md, plugins/, +// anything else under it) -- not just SKILL.md, matching "delete a +// skill." Deleting a name that does not exist is not an error: the end +// state (skill absent) already holds. +func (s *Store) Delete(_ context.Context, name string) error { + dir := filepath.Join(s.skillsPath(), name) + if err := os.RemoveAll(dir); err != nil { + return fmt.Errorf("skillcurator: deleting %s: %w", dir, err) + } + return nil +} diff --git a/internal/infrastructure/skillcurator/store_test.go b/internal/infrastructure/skillcurator/store_test.go new file mode 100644 index 000000000..58042e3fb --- /dev/null +++ b/internal/infrastructure/skillcurator/store_test.go @@ -0,0 +1,154 @@ +package skillcurator + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/curator" +) + +func writeSkill(t *testing.T, root, name, content string) { + t.Helper() + dir := filepath.Join(root, skillsDir, name) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("MkdirAll(%s) = %v", dir, err) + } + if err := os.WriteFile(filepath.Join(dir, skillFile), []byte(content), 0o644); err != nil { + t.Fatalf("WriteFile = %v", err) + } +} + +const validSkill = "---\nname: tdd-bugfix\ndescription: Fix a bug with a red-then-green test\n---\nBody text.\n" + +func TestStoreListMissingDirIsEmptyNotError(t *testing.T) { + t.Parallel() + s := NewStore(t.TempDir()) + refs, err := s.List(context.Background()) + if err != nil { + t.Fatalf("List() = %v, want nil", err) + } + if len(refs) != 0 { + t.Fatalf("List() = %v, want empty", refs) + } +} + +func TestStoreListSkipsADirectoryWithNoSkillFile(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "good", validSkill) + if err := os.MkdirAll(filepath.Join(root, skillsDir, "empty-dir"), 0o755); err != nil { + t.Fatal(err) + } + + s := NewStore(root) + refs, err := s.List(context.Background()) + if err != nil { + t.Fatalf("List() = %v, want nil", err) + } + if len(refs) != 1 || refs[0].Name != "good" { + t.Fatalf("List() = %v, want only 'good'", refs) + } +} + +func TestStoreReadReturnsContentAndDescription(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + + s := NewStore(root) + sk, err := s.Read(context.Background(), "tdd-bugfix") + if err != nil { + t.Fatalf("Read() = %v, want nil", err) + } + if sk.Content != validSkill { + t.Errorf("Content = %q, want the raw file content", sk.Content) + } + if sk.Description != "Fix a bug with a red-then-green test" { + t.Errorf("Description = %q, want the frontmatter description", sk.Description) + } +} + +func TestStoreReadUnparseableSkillStillReturnsRawContent(t *testing.T) { + // Read never treats a parse failure as an error -- Pass decides that, + // via its own skill.Parse call. Description is simply empty. + t.Parallel() + root := t.TempDir() + const broken = "---\nname: [unterminated\n---\n" + writeSkill(t, root, "broken", broken) + + s := NewStore(root) + sk, err := s.Read(context.Background(), "broken") + if err != nil { + t.Fatalf("Read() = %v, want nil even for unparseable frontmatter", err) + } + if sk.Content != broken { + t.Errorf("Content = %q, want the raw content regardless of parse failure", sk.Content) + } + if sk.Description != "" { + t.Errorf("Description = %q, want empty for a skill that failed to parse", sk.Description) + } +} + +func TestStoreReadMissingSkillIsAnError(t *testing.T) { + t.Parallel() + s := NewStore(t.TempDir()) + if _, err := s.Read(context.Background(), "nonexistent"); err == nil { + t.Fatal("Read(nonexistent) = nil, want error") + } +} + +func TestStoreWriteRequiresAnExistingSkillDirectory(t *testing.T) { + t.Parallel() + s := NewStore(t.TempDir()) + err := s.Write(context.Background(), curator.Skill{Name: "new-skill", Content: "content"}) + if err == nil { + t.Fatal("Write(new skill) = nil, want error: Write curates, it does not create") + } +} + +func TestStoreWritePersistsContent(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + + s := NewStore(root) + updated := validSkill + "\nMore body.\n" + if err := s.Write(context.Background(), curator.Skill{Name: "tdd-bugfix", Content: updated}); err != nil { + t.Fatalf("Write() = %v, want nil", err) + } + + got, err := s.Read(context.Background(), "tdd-bugfix") + if err != nil { + t.Fatalf("Read() after Write = %v", err) + } + if got.Content != updated { + t.Errorf("Content after Write = %q, want %q", got.Content, updated) + } +} + +func TestStoreDeleteRemovesTheWholeSkillDirectory(t *testing.T) { + t.Parallel() + root := t.TempDir() + writeSkill(t, root, "tdd-bugfix", validSkill) + if err := os.WriteFile(filepath.Join(root, skillsDir, "tdd-bugfix", "extra.txt"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + + s := NewStore(root) + if err := s.Delete(context.Background(), "tdd-bugfix"); err != nil { + t.Fatalf("Delete() = %v, want nil", err) + } + if _, err := os.Stat(filepath.Join(root, skillsDir, "tdd-bugfix")); !os.IsNotExist(err) { + t.Fatalf("skill directory still exists after Delete, or unexpected error: %v", err) + } +} + +func TestStoreDeleteMissingSkillIsNotAnError(t *testing.T) { + t.Parallel() + s := NewStore(t.TempDir()) + if err := s.Delete(context.Background(), "never-existed"); err != nil { + t.Fatalf("Delete(missing) = %v, want nil: the end state (absent) already holds", err) + } +}