From c884ef130a65c1be8bfcc94c11fe3a60b221be0d Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 9 May 2026 15:42:37 +0800 Subject: [PATCH] skills/disk: add disk-backed Store with full CRUD, frontmatter parser, concurrent-safe writes, and provider adapter --- tool/skills/disk/store.go | 517 ++++++++++++++++++++++++++++++++ tool/skills/disk/store_test.go | 522 +++++++++++++++++++++++++++++++++ 2 files changed, 1039 insertions(+) create mode 100644 tool/skills/disk/store.go create mode 100644 tool/skills/disk/store_test.go diff --git a/tool/skills/disk/store.go b/tool/skills/disk/store.go new file mode 100644 index 0000000..4d22857 --- /dev/null +++ b/tool/skills/disk/store.go @@ -0,0 +1,517 @@ +// Package disk is the default disk-backed SkillStore implementation. +// It uses one directory per skill: //SKILL.md holds the +// full body, including a YAML-ish frontmatter block at the top with +// description, tags, origin, and created_at. The directory shape leaves +// room for future supporting files (references/, templates/, scripts/) +// without changing the on-disk schema. +// +// Concurrent writes within one process are protected by a per-skill +// mutex (Task 8). Cross-process safety is best-effort: Create/Replace +// write to a temp file then atomically rename over SKILL.md, but two +// processes racing on the same skill name may still produce +// last-writer-wins behavior. Single-process per store is the +// assumption. +package disk + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/sausheong/harness/tool/skills" +) + +// Store is a directory-on-disk SkillStore. +type Store struct { + root string + + mu sync.Mutex // guards locks map only + locks map[string]*sync.Mutex // skill name → per-skill lock +} + +// NewStore returns a Store rooted at dir. The directory is created +// lazily on first write; reads of a non-existent root return an empty +// result. Callers should pass an absolute path. +func NewStore(root string) *Store { + return &Store{root: root} +} + +// lockFor returns the per-skill mutex, allocating it on first use. +// Callers must call mu.Lock() before any read-modify-write on the +// skill's directory. +func (s *Store) lockFor(name string) *sync.Mutex { + s.mu.Lock() + defer s.mu.Unlock() + if s.locks == nil { + s.locks = make(map[string]*sync.Mutex) + } + if l, ok := s.locks[name]; ok { + return l + } + l := &sync.Mutex{} + s.locks[name] = l + return l +} + +// skillDir returns the per-skill directory path. Caller must have +// validated name via skills.ValidName first. +func (s *Store) skillDir(name string) string { + return filepath.Join(s.root, name) +} + +// skillFile returns the SKILL.md path for the given name. +func (s *Store) skillFile(name string) string { + return filepath.Join(s.skillDir(name), "SKILL.md") +} + +// writeBodyAtomic writes body to the skill's SKILL.md via temp+rename, +// creating the parent directory if needed. Caller holds the per-skill +// lock. +func (s *Store) writeBodyAtomic(name, body string) error { + dir := s.skillDir(name) + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("mkdir: %w", err) + } + tmp, err := os.CreateTemp(dir, ".SKILL.md.*") + if err != nil { + return fmt.Errorf("create temp: %w", err) + } + if _, err := tmp.WriteString(body); err != nil { + tmp.Close() + os.Remove(tmp.Name()) + return fmt.Errorf("write: %w", err) + } + if err := tmp.Sync(); err != nil { + tmp.Close() + os.Remove(tmp.Name()) + return fmt.Errorf("fsync: %w", err) + } + if err := tmp.Close(); err != nil { + os.Remove(tmp.Name()) + return fmt.Errorf("close: %w", err) + } + if err := os.Rename(tmp.Name(), s.skillFile(name)); err != nil { + os.Remove(tmp.Name()) + return fmt.Errorf("rename: %w", err) + } + return nil +} + +// composeBody assembles a SKILL.md body from a Skill struct: emits a +// frontmatter block with description, tags, origin, created_at, then +// the body sans any pre-existing frontmatter. +func composeBody(s skills.Skill, body string) string { + var b strings.Builder + b.WriteString("---\n") + if s.Description != "" { + b.WriteString("description: ") + b.WriteString(s.Description) + b.WriteString("\n") + } + if len(s.Tags) > 0 { + b.WriteString("tags: [") + b.WriteString(strings.Join(s.Tags, ", ")) + b.WriteString("]\n") + } + if s.Origin != "" { + b.WriteString("origin: ") + b.WriteString(s.Origin) + b.WriteString("\n") + } + if !s.CreatedAt.IsZero() { + b.WriteString("created_at: ") + b.WriteString(s.CreatedAt.UTC().Format(time.RFC3339Nano)) + b.WriteString("\n") + } + b.WriteString("---\n\n") + // Strip any leading frontmatter from the caller-supplied body so we + // don't double-emit. parseFrontmatter (added in Task 3) returns the + // body without the FM block; for now the simple "if it starts with + // ---\n, drop until the next ---\n" trick suffices. + body = stripFrontmatter(body) + b.WriteString(body) + return b.String() +} + +// stripFrontmatter removes a leading YAML-ish frontmatter block from +// body if present. Conservative: only strips when body starts with +// "---\n" and a closing "\n---\n" or "\n---" is found. +func stripFrontmatter(body string) string { + if !strings.HasPrefix(body, "---\n") { + return body + } + rest := body[4:] + if i := strings.Index(rest, "\n---\n"); i >= 0 { + s := rest[i+5:] + // Eat one optional leading blank line after the closing fence. + if strings.HasPrefix(s, "\n") { + s = s[1:] + } + return s + } + if i := strings.Index(rest, "\n---"); i >= 0 && i == len(rest)-4 { + return "" + } + return body +} + +// Create implements skills.SkillStore. +func (s *Store) Create(_ context.Context, sk skills.Skill) (skills.Skill, error) { + if !skills.ValidName(sk.Name) { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, sk.Name) + } + + lock := s.lockFor(sk.Name) + lock.Lock() + defer lock.Unlock() + + // Reject duplicates. + if _, err := os.Stat(s.skillFile(sk.Name)); err == nil { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrAlreadyExists, sk.Name) + } else if !errors.Is(err, os.ErrNotExist) { + return skills.Skill{}, fmt.Errorf("stat: %w", err) + } + + // Derive metadata from body frontmatter when caller didn't set it. + if sk.Description == "" || len(sk.Tags) == 0 || sk.Origin == "" { + fm, _ := parseFrontmatter(sk.Body) + if sk.Description == "" { + sk.Description = fm.Description + } + if len(sk.Tags) == 0 { + sk.Tags = fm.Tags + } + if sk.Origin == "" { + sk.Origin = fm.Origin + } + } + + now := time.Now().UTC() + sk.CreatedAt = now + sk.UpdatedAt = now + + if err := s.writeBodyAtomic(sk.Name, composeBody(sk, sk.Body)); err != nil { + return skills.Skill{}, err + } + return sk, nil +} + +// frontmatter is the parsed shape of the YAML-ish header block. +type frontmatter struct { + Description string + Tags []string + Origin string + CreatedAt time.Time +} + +// parseFrontmatter extracts the leading frontmatter block from body. +// Returns the parsed metadata and the body sans frontmatter. If body +// does not begin with "---\n" or the closing fence is missing, returns +// (zero, body) untouched. +// +// Recognized keys: description, tags, origin, created_at. Unknown keys +// are silently ignored. Tags parse as either "[a, b, c]" or a single +// scalar treated as one tag. +func parseFrontmatter(body string) (frontmatter, string) { + if !strings.HasPrefix(body, "---\n") { + return frontmatter{}, body + } + rest := body[4:] + end := strings.Index(rest, "\n---\n") + var afterFM string + var fmText string + switch { + case end >= 0: + fmText = rest[:end] + afterFM = rest[end+5:] + case strings.HasSuffix(rest, "\n---"): + fmText = rest[:len(rest)-4] + afterFM = "" + default: + return frontmatter{}, body + } + if strings.HasPrefix(afterFM, "\n") { + afterFM = afterFM[1:] + } + + var fm frontmatter + for _, line := range strings.Split(fmText, "\n") { + line = strings.TrimRight(line, "\r") + idx := strings.Index(line, ":") + if idx < 0 { + continue + } + key := strings.TrimSpace(line[:idx]) + val := strings.TrimSpace(line[idx+1:]) + switch key { + case "description": + fm.Description = val + case "origin": + fm.Origin = val + case "created_at": + if t, err := time.Parse(time.RFC3339Nano, val); err == nil { + fm.CreatedAt = t + } + case "tags": + fm.Tags = parseTags(val) + } + } + return fm, afterFM +} + +// parseTags accepts "[a, b, c]" (returns ["a","b","c"]) or "a" +// (returns ["a"]). Empty input returns nil. +func parseTags(s string) []string { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") { + s = s[1 : len(s)-1] + } + parts := strings.Split(s, ",") + out := make([]string, 0, len(parts)) + for _, p := range parts { + p = strings.TrimSpace(p) + if p != "" { + out = append(out, p) + } + } + if len(out) == 0 { + return nil + } + return out +} + +// Patch implements skills.SkillStore. Replaces the unique occurrence +// of oldContent with newContent. Returns one of three sentinel errors +// when the patch can't apply cleanly so the model can recover: +// +// - ErrPatchNoMatch: re-read with Get and try again +// - ErrPatchAmbiguous: include more surrounding context in oldContent +// - ErrPatchIdentical: no change requested +// +// Error message includes the match count for the ambiguous case. +func (s *Store) Patch(ctx context.Context, name, oldContent, newContent string) (skills.Skill, error) { + if !skills.ValidName(name) { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, name) + } + if oldContent == newContent { + return skills.Skill{}, skills.ErrPatchIdentical + } + + lock := s.lockFor(name) + lock.Lock() + defer lock.Unlock() + + existing, ok, err := s.Get(ctx, name) + if err != nil { + return skills.Skill{}, err + } + if !ok { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrNotFound, name) + } + + count := strings.Count(existing.Body, oldContent) + switch count { + case 0: + return skills.Skill{}, skills.ErrPatchNoMatch + case 1: + // happy path + default: + return skills.Skill{}, fmt.Errorf("%w (matched %d times)", skills.ErrPatchAmbiguous, count) + } + + newBody := strings.Replace(existing.Body, oldContent, newContent, 1) + if err := s.writeBodyAtomic(name, newBody); err != nil { + return skills.Skill{}, err + } + + got, ok, err := s.Get(ctx, name) + if err != nil || !ok { + return skills.Skill{}, fmt.Errorf("post-write read: %w", err) + } + return got, nil +} +// Replace implements skills.SkillStore. +func (s *Store) Replace(ctx context.Context, name, body string) (skills.Skill, error) { + if !skills.ValidName(name) { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, name) + } + + lock := s.lockFor(name) + lock.Lock() + defer lock.Unlock() + + // Confirm existence and read existing CreatedAt. + existing, ok, err := s.Get(ctx, name) + if err != nil { + return skills.Skill{}, err + } + if !ok { + return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrNotFound, name) + } + + // Compose with preserved CreatedAt; refresh UpdatedAt to now. + sk := skills.Skill{ + Name: name, + Body: body, + Origin: existing.Origin, // preserved across Replace; caller can include `origin:` in new frontmatter to override + CreatedAt: existing.CreatedAt, + } + fm, _ := parseFrontmatter(body) + if fm.Description != "" { + sk.Description = fm.Description + } + if fm.Origin != "" { + sk.Origin = fm.Origin + } + if len(fm.Tags) > 0 { + sk.Tags = fm.Tags + } else { + sk.Tags = existing.Tags + } + + if err := s.writeBodyAtomic(name, composeBody(sk, body)); err != nil { + return skills.Skill{}, err + } + + // Re-read to get true mtime. CreatedAt round-trips with full + // nanosecond precision via RFC3339Nano in compose+parse. + got, ok, err := s.Get(ctx, name) + if err != nil || !ok { + return skills.Skill{}, fmt.Errorf("post-write read: %w", err) + } + return got, nil +} +// Remove implements skills.SkillStore. Idempotent — removing an unknown +// name returns nil. Removes the entire per-skill directory (so any +// supporting files added in future, like references/, are cleaned up +// too). +func (s *Store) Remove(_ context.Context, name string) error { + if !skills.ValidName(name) { + return fmt.Errorf("%w: %q", skills.ErrInvalidName, name) + } + + lock := s.lockFor(name) + lock.Lock() + defer lock.Unlock() + + if err := os.RemoveAll(s.skillDir(name)); err != nil { + return fmt.Errorf("remove: %w", err) + } + return nil +} + +// List implements skills.SkillStore. +func (s *Store) List(ctx context.Context) ([]skills.Skill, error) { + entries, err := os.ReadDir(s.root) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return []skills.Skill{}, nil + } + return nil, fmt.Errorf("readdir: %w", err) + } + out := make([]skills.Skill, 0, len(entries)) + for _, e := range entries { + if !e.IsDir() { + continue + } + name := e.Name() + if !skills.ValidName(name) { + continue + } + // Confirm SKILL.md exists; otherwise skip. + if _, err := os.Stat(filepath.Join(s.root, name, "SKILL.md")); err != nil { + continue + } + sk, ok, err := s.Get(ctx, name) + if err != nil || !ok { + continue + } + out = append(out, sk) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +// Get implements skills.SkillStore. +func (s *Store) Get(_ context.Context, name string) (skills.Skill, bool, error) { + if !skills.ValidName(name) { + return skills.Skill{}, false, fmt.Errorf("%w: %q", skills.ErrInvalidName, name) + } + data, err := os.ReadFile(s.skillFile(name)) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return skills.Skill{}, false, nil + } + return skills.Skill{}, false, fmt.Errorf("read: %w", err) + } + stat, err := os.Stat(s.skillFile(name)) + if err != nil { + return skills.Skill{}, false, fmt.Errorf("stat: %w", err) + } + body := string(data) + fm, _ := parseFrontmatter(body) + return skills.Skill{ + Name: name, + Description: fm.Description, + Body: body, // full body including frontmatter; callers see what's on disk + Tags: fm.Tags, + Origin: fm.Origin, + CreatedAt: fm.CreatedAt, + UpdatedAt: stat.ModTime().UTC(), + }, true, nil +} + +// SkillProviderAdapter wraps a *Store with the read-only signature +// runtime.SkillProvider expects (FormatIndex + Get(string)(string,bool)). +// Lets one *Store value serve both writes (via the SkillStore interface) +// and reads (via runtime.SkillProvider). +type SkillProviderAdapter struct{ s *Store } + +// AsSkillProvider returns a wrapper that satisfies +// runtime.SkillProvider — pass it as RuntimeInputs.Skills while still +// using the same *Store as the SkillTool's backend. +func (s *Store) AsSkillProvider() *SkillProviderAdapter { + return &SkillProviderAdapter{s: s} +} + +// FormatIndex satisfies runtime.SkillProvider. Returns a markdown block +// for inclusion in the static system prompt; empty when the store has +// no skills. Format: one bullet per skill, "name: description". Bodies +// are NOT included — that's what load_skill is for. +func (a *SkillProviderAdapter) FormatIndex() string { + all, err := a.s.List(context.Background()) + if err != nil || len(all) == 0 { + return "" + } + var b strings.Builder + b.WriteString("## Skills\n\n") + for _, sk := range all { + b.WriteString("- ") + b.WriteString(sk.Name) + if sk.Description != "" { + b.WriteString(": ") + b.WriteString(sk.Description) + } + b.WriteString("\n") + } + return b.String() +} + +// Get satisfies runtime.SkillProvider. Returns the full SKILL.md body +// (frontmatter included). +func (a *SkillProviderAdapter) Get(name string) (string, bool) { + sk, ok, err := a.s.Get(context.Background(), name) + if err != nil || !ok { + return "", false + } + return sk.Body, true +} diff --git a/tool/skills/disk/store_test.go b/tool/skills/disk/store_test.go new file mode 100644 index 0000000..eae2a6a --- /dev/null +++ b/tool/skills/disk/store_test.go @@ -0,0 +1,522 @@ +package disk + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/sausheong/harness/tool/skills" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStore_CreateWritesSkillMd(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + created, err := s.Create(context.Background(), skills.Skill{ + Name: "my-skill", + Body: "---\ndescription: A test skill.\n---\n\nDo the thing.\n", + }) + require.NoError(t, err) + assert.Equal(t, "my-skill", created.Name) + assert.Equal(t, "A test skill.", created.Description) + assert.False(t, created.CreatedAt.IsZero()) + assert.Equal(t, created.CreatedAt, created.UpdatedAt) + + // File on disk has expected content. + path := filepath.Join(dir, "my-skill", "SKILL.md") + data, err := os.ReadFile(path) + require.NoError(t, err) + body := string(data) + assert.True(t, strings.HasPrefix(body, "---\n"), "should have frontmatter") + assert.Contains(t, body, "description: A test skill.") + assert.Contains(t, body, "Do the thing.") +} + +func TestStore_CreateRejectsInvalidName(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{ + Name: "Bad Name With Spaces", + Body: "anything", + }) + require.ErrorIs(t, err, skills.ErrInvalidName) +} + +func TestStore_CreateRejectsDuplicate(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{Name: "dup", Body: "first"}) + require.NoError(t, err) + + _, err = s.Create(context.Background(), skills.Skill{Name: "dup", Body: "second"}) + require.ErrorIs(t, err, skills.ErrAlreadyExists) +} + +func TestStore_CreateRejectsPathTraversal(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + // Names with ".." or "/" are caught by ValidName (regex rejects them). + // Confirm the store relays the rejection. + for _, bad := range []string{"../escape", "sub/skill", ".."} { + _, err := s.Create(context.Background(), skills.Skill{Name: bad, Body: "x"}) + require.ErrorIs(t, err, skills.ErrInvalidName, "name %q should be rejected", bad) + } + + // And the parent dir contains nothing the store didn't put there. + entries, err := os.ReadDir(dir) + require.NoError(t, err) + for _, e := range entries { + assert.NotEqual(t, "..", e.Name()) + } +} + +func TestStore_GetReturnsCreatedSkill(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + body := "---\ndescription: My test skill.\ntags: [a, b]\n---\n\nBody content.\n" + created, err := s.Create(context.Background(), skills.Skill{Name: "round-trip", Body: body}) + require.NoError(t, err) + + got, ok, err := s.Get(context.Background(), "round-trip") + require.NoError(t, err) + require.True(t, ok) + assert.Equal(t, "round-trip", got.Name) + assert.Equal(t, "My test skill.", got.Description) + assert.Equal(t, []string{"a", "b"}, got.Tags) + assert.Contains(t, got.Body, "Body content.") + assert.False(t, got.CreatedAt.IsZero()) + assert.Equal(t, created.CreatedAt.Truncate(time.Second), got.CreatedAt.Truncate(time.Second)) +} + +func TestStore_GetUnknownReturnsFalse(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + got, ok, err := s.Get(context.Background(), "does-not-exist") + require.NoError(t, err) + assert.False(t, ok) + assert.Equal(t, skills.Skill{}, got) +} + +func TestStore_GetRejectsInvalidName(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, _, err := s.Get(context.Background(), "../escape") + require.ErrorIs(t, err, skills.ErrInvalidName) +} + +func TestStore_GetReadsFrontmatterTagsAndOrigin(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{ + Name: "tagged", + Body: "Body.", + Tags: []string{"workflow", "git"}, + Origin: "review", + }) + require.NoError(t, err) + + got, ok, err := s.Get(context.Background(), "tagged") + require.NoError(t, err) + require.True(t, ok) + assert.Equal(t, []string{"workflow", "git"}, got.Tags) + assert.Equal(t, "review", got.Origin) +} + +func TestStore_ListReturnsAllInNameOrder(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + for _, name := range []string{"charlie", "alpha", "bravo"} { + _, err := s.Create(context.Background(), skills.Skill{ + Name: name, + Body: "---\ndescription: " + name + " skill.\n---\n\nBody.\n", + }) + require.NoError(t, err) + } + + all, err := s.List(context.Background()) + require.NoError(t, err) + require.Len(t, all, 3) + assert.Equal(t, "alpha", all[0].Name) + assert.Equal(t, "bravo", all[1].Name) + assert.Equal(t, "charlie", all[2].Name) + assert.Equal(t, "alpha skill.", all[0].Description) +} + +func TestStore_ListEmptyRoot(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + all, err := s.List(context.Background()) + require.NoError(t, err) + assert.Empty(t, all) +} + +func TestStore_ListNonexistentRoot(t *testing.T) { + // Pointing at a non-existent root should yield empty, not error. + s := NewStore("/tmp/does-not-exist-skills-xyz-" + t.Name()) + all, err := s.List(context.Background()) + require.NoError(t, err) + assert.Empty(t, all) +} + +func TestStore_ListSkipsBogusDirs(t *testing.T) { + // A directory in root that doesn't contain SKILL.md, or whose name + // fails ValidName, must be silently skipped (it's user data we + // don't own). + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{Name: "real", Body: "ok"}) + require.NoError(t, err) + + // Empty subdir. + require.NoError(t, os.Mkdir(filepath.Join(dir, "empty"), 0o755)) + + // Subdir with bogus name (uppercase) but containing SKILL.md. + require.NoError(t, os.Mkdir(filepath.Join(dir, "BAD"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "BAD", "SKILL.md"), []byte("x"), 0o644)) + + // File at root level (not a directory). + require.NoError(t, os.WriteFile(filepath.Join(dir, "stray.txt"), []byte("x"), 0o644)) + + all, err := s.List(context.Background()) + require.NoError(t, err) + require.Len(t, all, 1) + assert.Equal(t, "real", all[0].Name) +} + +func TestStore_ReplaceOverwritesBody(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + original, err := s.Create(context.Background(), skills.Skill{ + Name: "evolving", + Body: "---\ndescription: v1.\n---\n\nv1 body.\n", + }) + require.NoError(t, err) + originalCreated := original.CreatedAt + + // Sleep 1s so mtime tick is observable. + time.Sleep(1100 * time.Millisecond) + + updated, err := s.Replace(context.Background(), "evolving", + "---\ndescription: v2.\n---\n\nv2 body.\n") + require.NoError(t, err) + + assert.Equal(t, "evolving", updated.Name) + assert.Equal(t, "v2.", updated.Description) + assert.Contains(t, updated.Body, "v2 body.") + assert.NotContains(t, updated.Body, "v1 body.") + assert.True(t, originalCreated.Equal(updated.CreatedAt) || updated.CreatedAt.IsZero(), + "CreatedAt should survive (got %v, want %v)", updated.CreatedAt, originalCreated) + assert.True(t, updated.UpdatedAt.After(originalCreated), + "UpdatedAt must advance past original CreatedAt") +} + +func TestStore_ReplaceRejectsUnknown(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Replace(context.Background(), "ghost", "x") + require.ErrorIs(t, err, skills.ErrNotFound) +} + +func TestStore_ReplaceRejectsInvalidName(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Replace(context.Background(), "Bad Name", "x") + require.ErrorIs(t, err, skills.ErrInvalidName) +} + +func TestStore_ReplacePreservesCreatedAtAcrossDays(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + original, err := s.Create(context.Background(), skills.Skill{ + Name: "stable", Body: "---\ndescription: x.\n---\n\nbody", + }) + require.NoError(t, err) + + _, err = s.Replace(context.Background(), "stable", "---\ndescription: y.\n---\n\nbody") + require.NoError(t, err) + + got, ok, err := s.Get(context.Background(), "stable") + require.NoError(t, err) + require.True(t, ok) + assert.Equal(t, + original.CreatedAt.Truncate(time.Second), + got.CreatedAt.Truncate(time.Second), + "CreatedAt must survive Replace", + ) +} + +func TestStore_RemoveDeletesSkill(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{Name: "doomed", Body: "x"}) + require.NoError(t, err) + + require.NoError(t, s.Remove(context.Background(), "doomed")) + + _, ok, err := s.Get(context.Background(), "doomed") + require.NoError(t, err) + assert.False(t, ok) + + // Directory is gone. + _, err = os.Stat(filepath.Join(dir, "doomed")) + assert.True(t, os.IsNotExist(err)) +} + +func TestStore_RemoveUnknownIsIdempotent(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + require.NoError(t, s.Remove(context.Background(), "ghost")) + require.NoError(t, s.Remove(context.Background(), "ghost")) +} + +func TestStore_RemoveRejectsInvalidName(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + err := s.Remove(context.Background(), "../escape") + require.ErrorIs(t, err, skills.ErrInvalidName) +} + +func TestStore_PatchReplacesUniqueOccurrence(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{ + Name: "patchable", + Body: "---\ndescription: x.\n---\n\nThe quick brown fox.\n", + }) + require.NoError(t, err) + + updated, err := s.Patch(context.Background(), "patchable", "brown fox", "lazy dog") + require.NoError(t, err) + assert.Contains(t, updated.Body, "The quick lazy dog.") + assert.NotContains(t, updated.Body, "brown fox") +} + +func TestStore_PatchNoMatchReturnsErrPatchNoMatch(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Create(context.Background(), skills.Skill{Name: "p1", Body: "Hello world."}) + require.NoError(t, err) + + _, err = s.Patch(context.Background(), "p1", "missing", "x") + require.ErrorIs(t, err, skills.ErrPatchNoMatch) +} + +func TestStore_PatchMultipleMatchesReturnsAmbiguous(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Create(context.Background(), skills.Skill{Name: "p2", Body: "foo bar foo bar foo"}) + require.NoError(t, err) + + _, err = s.Patch(context.Background(), "p2", "foo", "x") + require.ErrorIs(t, err, skills.ErrPatchAmbiguous) + assert.Contains(t, err.Error(), "3", "error message should include match count") +} + +func TestStore_PatchIdenticalReturnsErrPatchIdentical(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Create(context.Background(), skills.Skill{Name: "p3", Body: "hello"}) + require.NoError(t, err) + + _, err = s.Patch(context.Background(), "p3", "hello", "hello") + require.ErrorIs(t, err, skills.ErrPatchIdentical) +} + +func TestStore_PatchUnknownReturnsErrNotFound(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Patch(context.Background(), "ghost", "a", "b") + require.ErrorIs(t, err, skills.ErrNotFound) +} + +func TestStore_PatchRejectsInvalidName(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + _, err := s.Patch(context.Background(), "Bad Name", "a", "b") + require.ErrorIs(t, err, skills.ErrInvalidName) +} + +func TestStore_PatchPreservesCreatedAtRefreshesUpdatedAt(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + original, err := s.Create(context.Background(), skills.Skill{ + Name: "p4", + Body: "---\ndescription: orig.\n---\n\nfind me.\n", + }) + require.NoError(t, err) + + time.Sleep(1100 * time.Millisecond) + + updated, err := s.Patch(context.Background(), "p4", "find me", "FOUND") + require.NoError(t, err) + + assert.Equal(t, + original.CreatedAt.Truncate(time.Second), + updated.CreatedAt.Truncate(time.Second), + "CreatedAt must survive Patch") + assert.True(t, updated.UpdatedAt.After(original.CreatedAt), + "UpdatedAt must advance") +} + +func TestStore_ConcurrentPatchesDoNotInterleave(t *testing.T) { + // 20 goroutines each Patch a unique substring within the same skill. + // Without per-skill serialization, two concurrent read-modify-write + // cycles would race and lose updates. With it, every patch must + // land. + dir := t.TempDir() + s := NewStore(dir) + + // Body has 20 distinct sentinels: M00, M01, ..., M19. + var b strings.Builder + b.WriteString("---\ndescription: race test.\n---\n\n") + for i := 0; i < 20; i++ { + fmt.Fprintf(&b, "M%02d\n", i) + } + _, err := s.Create(context.Background(), skills.Skill{Name: "race", Body: b.String()}) + require.NoError(t, err) + + var wg sync.WaitGroup + wg.Add(20) + errs := make(chan error, 20) + for i := 0; i < 20; i++ { + go func(i int) { + defer wg.Done() + old := fmt.Sprintf("M%02d", i) + new := fmt.Sprintf("X%02d", i) + if _, err := s.Patch(context.Background(), "race", old, new); err != nil { + errs <- err + } + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + t.Errorf("patch error: %v", err) + } + + got, ok, err := s.Get(context.Background(), "race") + require.NoError(t, err) + require.True(t, ok) + for i := 0; i < 20; i++ { + assert.NotContains(t, got.Body, fmt.Sprintf("M%02d", i), + "sentinel M%02d should have been patched", i) + assert.Contains(t, got.Body, fmt.Sprintf("X%02d", i), + "replacement X%02d should be present", i) + } +} + +func TestStore_ConcurrentCreatesDoNotDoubleWrite(t *testing.T) { + // 10 goroutines try to Create the same name. Exactly one should + // succeed; the rest get ErrAlreadyExists. + dir := t.TempDir() + s := NewStore(dir) + + var wg sync.WaitGroup + wg.Add(10) + successes := make(chan struct{}, 10) + conflicts := make(chan struct{}, 10) + for i := 0; i < 10; i++ { + go func() { + defer wg.Done() + _, err := s.Create(context.Background(), skills.Skill{ + Name: "race-create", Body: "x", + }) + switch { + case err == nil: + successes <- struct{}{} + case errors.Is(err, skills.ErrAlreadyExists): + conflicts <- struct{}{} + default: + t.Errorf("unexpected error: %v", err) + } + }() + } + wg.Wait() + close(successes) + close(conflicts) + assert.Len(t, drain(successes), 1, "exactly one Create should succeed") + assert.Len(t, drain(conflicts), 9, "the other nine should see ErrAlreadyExists") +} + +func drain(ch <-chan struct{}) []struct{} { + out := []struct{}{} + for v := range ch { + out = append(out, v) + } + return out +} + +func TestStore_AsSkillProvider_FormatIndexEmpty(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + provider := s.AsSkillProvider() + assert.Empty(t, provider.FormatIndex()) +} + +func TestStore_AsSkillProvider_FormatIndexLists(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{ + Name: "writing-clearly", + Body: "---\ndescription: Tighten prose.\n---\n\nbody", + }) + require.NoError(t, err) + _, err = s.Create(context.Background(), skills.Skill{ + Name: "git-bisect", + Body: "---\ndescription: Find the bad commit.\n---\n\nbody", + }) + require.NoError(t, err) + + provider := s.AsSkillProvider() + idx := provider.FormatIndex() + + assert.Contains(t, idx, "## Skills") + assert.Contains(t, idx, "git-bisect") + assert.Contains(t, idx, "Find the bad commit.") + assert.Contains(t, idx, "writing-clearly") + assert.Contains(t, idx, "Tighten prose.") + // Body content must not leak — only one-liners. + assert.NotContains(t, idx, "\nbody") +} + +func TestStore_AsSkillProvider_GetReturnsBody(t *testing.T) { + dir := t.TempDir() + s := NewStore(dir) + + _, err := s.Create(context.Background(), skills.Skill{ + Name: "lookup", + Body: "---\ndescription: x.\n---\n\nThe full body.\n", + }) + require.NoError(t, err) + + provider := s.AsSkillProvider() + body, ok := provider.Get("lookup") + assert.True(t, ok) + assert.Contains(t, body, "The full body.") + + _, ok = provider.Get("does-not-exist") + assert.False(t, ok) +}