diff --git a/internal/skill/catalog_test.go b/internal/skill/catalog_test.go index 63d2d268e..289779596 100644 --- a/internal/skill/catalog_test.go +++ b/internal/skill/catalog_test.go @@ -139,7 +139,8 @@ func TestCatalogEntryHasRequiredFields(t *testing.T) { func TestBundledPluginSkillIsDiscoverableAndRunnable(t *testing.T) { // A skill must be able to ship bundled Yaegi plugins in its plugins/ - // directory. DiscoverPlugins finds them, Plugin.Run executes them. + // directory. When metadata.archie.plugins is present, only the listed + // plugins are loaded in declared order; unlisted *.go files are ignored. dir := t.TempDir() skillsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-tdd") @@ -157,13 +158,14 @@ metadata: engine: any plugins: - plugins/security-check.go + - plugins/lint-check.go --- Full body content. `), 0o644); err != nil { t.Fatal(err) } - // Write the bundled plugin. + // Write the listed plugins. if err := os.WriteFile(filepath.Join(pluginsDir, "security-check.go"), []byte(`package main import "strings" @@ -177,8 +179,25 @@ func Run(input string) string { `), 0o644); err != nil { t.Fatal(err) } + if err := os.WriteFile(filepath.Join(pluginsDir, "lint-check.go"), []byte(`package main - // Discover the skill — must include plugins. +func Run(input string) string { + return "linted: " + input +} +`), 0o644); err != nil { + t.Fatal(err) + } + // Write an unlisted plugin — it must NOT be loaded. + if err := os.WriteFile(filepath.Join(pluginsDir, "extra.go"), []byte(`package main + +func Run(input string) string { + return "extra" +} +`), 0o644); err != nil { + t.Fatal(err) + } + + // Discover the skill — must include only the listed plugins in declared order. skills, err := Discover(dir) if err != nil { t.Fatal(err) @@ -187,11 +206,14 @@ func Run(input string) string { t.Fatalf("got %d skills, want 1", len(skills)) } s := skills["archie-wf-tdd"] - if len(s.Plugins) != 1 { - t.Fatalf("skill has %d plugins, want 1 — Discover() must populate Plugins", len(s.Plugins)) + if len(s.Plugins) != 2 { + t.Fatalf("skill has %d plugins, want 2 — Discover() must honor metadata.archie.plugins", len(s.Plugins)) } if s.Plugins[0].Name != "security-check" { - t.Errorf("plugin name = %q, want security-check", s.Plugins[0].Name) + t.Errorf("plugin[0].Name = %q, want security-check (declared order)", s.Plugins[0].Name) + } + if s.Plugins[1].Name != "lint-check" { + t.Errorf("plugin[1].Name = %q, want lint-check (declared order)", s.Plugins[1].Name) } // The plugin must be runnable. @@ -204,7 +226,7 @@ func Run(input string) string { } // The frontmatter must declare the plugin. - if s.Frontmatter.Metadata.Archie == nil || len(s.Frontmatter.Metadata.Archie.Plugins) != 1 { + if s.Frontmatter.Metadata.Archie == nil || len(s.Frontmatter.Metadata.Archie.Plugins) != 2 { t.Error("Frontmatter.Metadata.Archie.Plugins is empty — " + "the SKILL.md must declare bundled plugins in the metadata.archie.plugins list") } diff --git a/internal/skill/plugin.go b/internal/skill/plugin.go index 24890e8b8..c8061d667 100644 --- a/internal/skill/plugin.go +++ b/internal/skill/plugin.go @@ -42,6 +42,18 @@ func (p *Plugin) Run(input string) (string, error) { // skill directory does not exist. Returns an empty slice if the skill // exists but has no plugins/ directory. func DiscoverPlugins(dir, skillName string) ([]Plugin, error) { + return LoadPlugins(dir, skillName, nil) +} + +// LoadPlugins loads plugins from dir/.agents/skills//plugins/. +// +// When allowed is non-empty, only the listed filenames are loaded in +// declared order — the plugins/ prefix is stripped before matching. +// A listed file that does not exist on disk is an error. +// +// When allowed is nil or empty, all *.go files in the plugins/ directory +// are globbed alphabetically (backward-compatible fallback). +func LoadPlugins(dir, skillName string, allowed []string) ([]Plugin, error) { pluginsDir := filepath.Join(dir, skillsDir, skillName, "plugins") entries, err := os.ReadDir(pluginsDir) if os.IsNotExist(err) { @@ -52,13 +64,31 @@ func DiscoverPlugins(dir, skillName string) ([]Plugin, error) { return nil, fmt.Errorf("read plugins dir %s: %w", pluginsDir, err) } - var names []string + // Build an on-disk set for existence checks when filtering. + onDisk := make(map[string]struct{}, len(entries)) for _, e := range entries { if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") { - names = append(names, e.Name()) + onDisk[e.Name()] = struct{}{} + } + } + + var names []string + if len(allowed) == 0 { + // Fallback: glob all *.go files alphabetically. + for name := range onDisk { + names = append(names, name) + } + sort.Strings(names) + } else { + // Use the frontmatter list; strip "plugins/" prefix. + for _, a := range allowed { + a = strings.TrimPrefix(a, "plugins/") + if _, ok := onDisk[a]; !ok { + return nil, fmt.Errorf("plugin %q listed in metadata.archie.plugins not found on disk", a) + } + names = append(names, a) } } - sort.Strings(names) plugins := make([]Plugin, 0, len(names)) for _, name := range names { diff --git a/internal/skill/plugin_test.go b/internal/skill/plugin_test.go index db8e9bc01..d1f30a623 100644 --- a/internal/skill/plugin_test.go +++ b/internal/skill/plugin_test.go @@ -207,3 +207,104 @@ func Run(input string) string { t.Errorf("plugin name = %q, want gate", s.Plugins[0].Name) } } + +func TestLoadPluginsWithAllowlist(t *testing.T) { + // When allowed is non-empty, only those plugins are loaded in declared order. + dir := t.TempDir() + skillsDir := filepath.Join(dir, ".agents", "skills", "ordered") + pluginsDir := filepath.Join(skillsDir, "plugins") + if err := os.MkdirAll(pluginsDir, 0o755); err != nil { + t.Fatal(err) + } + + // Write three plugin files. + for _, name := range []string{"a.go", "b.go", "c.go"} { + src := `package main + +func Run(input string) string { + return "` + name + `" +} +` + if err := os.WriteFile(filepath.Join(pluginsDir, name), []byte(src), 0o644); err != nil { + t.Fatal(err) + } + } + + // Allowlist only b.go and a.go (with plugins/ prefix), in that order. + plugins, err := LoadPlugins(dir, "ordered", []string{"plugins/b.go", "plugins/a.go"}) + if err != nil { + t.Fatal(err) + } + if len(plugins) != 2 { + t.Fatalf("got %d plugins, want 2", len(plugins)) + } + if plugins[0].Name != "b" { + t.Errorf("plugin[0].Name = %q, want b", plugins[0].Name) + } + if plugins[1].Name != "a" { + t.Errorf("plugin[1].Name = %q, want a", plugins[1].Name) + } +} + +func TestLoadPluginsWithAllowlistMissingFile(t *testing.T) { + // When allowed references a file not on disk, return an error. + dir := t.TempDir() + skillsDir := filepath.Join(dir, ".agents", "skills", "broken") + pluginsDir := filepath.Join(skillsDir, "plugins") + if err := os.MkdirAll(pluginsDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(pluginsDir, "a.go"), []byte(`package main + +func Run(input string) string { return "ok" } +`), 0o644); err != nil { + t.Fatal(err) + } + + _, err := LoadPlugins(dir, "broken", []string{"a.go", "nonexistent.go"}) + if err == nil { + t.Fatal("expected error for missing plugin file, got nil") + } +} + +func TestLoadPluginsEmptyAllowlist(t *testing.T) { + // Nil or empty allowlist falls back to glob-all (same as DiscoverPlugins). + dir := t.TempDir() + skillsDir := filepath.Join(dir, ".agents", "skills", "glob") + pluginsDir := filepath.Join(skillsDir, "plugins") + if err := os.MkdirAll(pluginsDir, 0o755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"b.go", "a.go"} { + if err := os.WriteFile(filepath.Join(pluginsDir, name), []byte(`package main + +func Run(input string) string { return "x" } +`), 0o644); err != nil { + t.Fatal(err) + } + } + + // nil allowed → glob all, sorted alphabetically. + plugins, err := LoadPlugins(dir, "glob", nil) + if err != nil { + t.Fatal(err) + } + if len(plugins) != 2 { + t.Fatalf("got %d plugins, want 2", len(plugins)) + } + if plugins[0].Name != "a" { + t.Errorf("plugin[0].Name = %q, want a (alphabetical)", plugins[0].Name) + } + if plugins[1].Name != "b" { + t.Errorf("plugin[1].Name = %q, want b (alphabetical)", plugins[1].Name) + } + + // Empty allowed → same as nil. + plugins2, err := LoadPlugins(dir, "glob", []string{}) + if err != nil { + t.Fatal(err) + } + if len(plugins2) != 2 { + t.Fatalf("got %d plugins (empty allowlist), want 2", len(plugins2)) + } +} diff --git a/internal/skill/skill.go b/internal/skill/skill.go index 9df6ee9da..7fa77b0e1 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -171,7 +171,11 @@ func Discover(dir string) (map[string]Skill, error) { if err != nil { return nil, fmt.Errorf("parse %s: %w", skillPath, err) } - plugins, err := DiscoverPlugins(dir, name) + var pluginNames []string + if fm.Metadata.Archie != nil { + pluginNames = fm.Metadata.Archie.Plugins + } + plugins, err := LoadPlugins(dir, name, pluginNames) if err != nil { return nil, fmt.Errorf("plugins %s: %w", name, err) } diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index e30316bce..83a943e56 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -3,6 +3,8 @@ package storage import ( "context" "encoding/json" + "fmt" + "go/format" "io" "net/http" "net/http/httptest" @@ -581,6 +583,48 @@ func dockerTestClient(t *testing.T, roundTrip func(*http.Request) (*http.Respons return cli } +// ── gofmt compliance ───────────────────────────────────────────────── + +func TestStorageDotGoIsGofmtClean(t *testing.T) { + // storage.go must be gofmt-clean so that CI checks (gofmt -l) pass. + // This test reads the source and feeds it through go/format.Source; + // if the output differs, the file is not canonical Go formatting. + src, err := os.ReadFile("storage.go") + if err != nil { + t.Fatal(err) + } + formatted, err := format.Source(src) + if err != nil { + t.Fatalf("storage.go is not valid Go: %v", err) + } + if string(formatted) != string(src) { + t.Errorf("storage.go is not gofmt-clean. diff:\n%s", diffBytes(src, formatted)) + } +} + +func diffBytes(a, b []byte) string { + linesA := strings.Split(string(a), "\n") + linesB := strings.Split(string(b), "\n") + var out strings.Builder + maxLine := len(linesA) + if len(linesB) > maxLine { + maxLine = len(linesB) + } + for i := 0; i < maxLine; i++ { + var lineA, lineB string + if i < len(linesA) { + lineA = linesA[i] + } + if i < len(linesB) { + lineB = linesB[i] + } + if lineA != lineB { + out.WriteString(fmt.Sprintf("-%s\n+%s\n", lineA, lineB)) + } + } + return out.String() +} + func dockerAPIPath(path string) string { if strings.HasPrefix(path, "/v1.55/") { return strings.TrimPrefix(path, "/v1.55") diff --git a/internal/store/store.go b/internal/store/store.go index 98f147b12..9b18e439f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "strings" + "unicode/utf8" _ "modernc.org/sqlite" ) @@ -320,5 +321,14 @@ func clip(s string, n int) string { if len(s) <= n { return s } - return s[:n] + // Walk forward by runes; stop when the next rune would exceed n bytes. + pos := 0 + for pos < len(s) { + _, size := utf8.DecodeRuneInString(s[pos:]) + if pos+size > n { + break + } + pos += size + } + return s[:pos] } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 0f9b74494..c29f4366c 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -4,6 +4,7 @@ import ( "context" "path/filepath" "testing" + "unicode/utf8" "github.com/samcharles93/archie-core/internal/events" ) @@ -22,6 +23,44 @@ func openTest(t *testing.T) *Store { return s } +func TestClip(t *testing.T) { + tests := []struct { + name string + input string + n int + want string + }{ + {"ascii truncate", "hello", 3, "hel"}, + {"ascii below n", "hello", 10, "hello"}, + {"empty zero", "", 0, ""}, + {"empty positive", "", 5, ""}, + {"2-byte fits exactly", "café", 5, "café"}, + {"2-byte cut off", "café", 4, "caf"}, + {"clean ASCII boundary", "café", 3, "caf"}, + {"4-byte emoji fits", "🍕pizza", 4, "🍕"}, + {"4-byte emoji cut off", "🍕pizza", 3, ""}, + {"2-byte ñ fits", "niño", 5, "niño"}, + {"2-byte ñ cut off", "niño", 4, "niñ"}, + {"3-byte CJK fits", "日本語", 6, "日本"}, + {"3-byte CJK cut off", "日本語", 5, "日"}, + {"mixed multi-byte", "a🍕b", 5, "a🍕"}, + {"mixed multi-byte cut off", "a🍕b", 4, "a"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := clip(tt.input, tt.n) + if got != tt.want { + t.Errorf("clip(%q, %d) = %q, want %q", tt.input, tt.n, got, tt.want) + } + // Verify output is valid UTF-8. + if !utf8.ValidString(got) { + t.Errorf("clip(%q, %d) produced invalid UTF-8: %q", tt.input, tt.n, got) + } + }) + } +} + func TestClearTerminalTasks(t *testing.T) { s := openTest(t) ctx := context.Background() diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index 245d4f49f..9676d6a88 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -3,6 +3,9 @@ package workflow import ( "context" "fmt" + "os" + "path/filepath" + "strings" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" @@ -205,15 +208,31 @@ func missionWithSkill(tc *TaskContext, mission string) string { // loadSkillBody loads the SKILL.md body and plugins for the current // workflow from the worktree's .agents/skills/ directory. Skills declare // their workflow in metadata.archie.workflow — no hardcoded mapping. +// When metadata.archie.plugins is non-empty, only the listed plugin files +// are loaded in declared order; otherwise all *.go files are globbed. func loadSkillBody(tc *TaskContext) string { catalog, _ := skill.Catalog(tc.Dir) entry := skill.SkillForWorkflow(catalog, tc.Task.Workflow) if entry == nil { return "" } - body := skill.LoadBody(tc.Dir, entry.Dir) + // Read and parse SKILL.md once to get both body and frontmatter. + skillPath := filepath.Join(tc.Dir, ".agents", "skills", entry.Dir, "SKILL.md") + data, err := os.ReadFile(skillPath) + if err != nil { + return "" + } + fm, body, err := skill.Parse(data) + if err != nil || fm == nil { + return "" + } + body = strings.TrimSpace(body) if body != "" && tc.SkillPlugins == nil { - plugins, _ := skill.DiscoverPlugins(tc.Dir, entry.Dir) + var pluginNames []string + if fm.Metadata.Archie != nil { + pluginNames = fm.Metadata.Archie.Plugins + } + plugins, _ := skill.LoadPlugins(tc.Dir, entry.Dir, pluginNames) tc.SkillPlugins = plugins } return body diff --git a/internal/workflow/plugin_test.go b/internal/workflow/plugin_test.go index 37f5e4264..14a289d36 100644 --- a/internal/workflow/plugin_test.go +++ b/internal/workflow/plugin_test.go @@ -22,6 +22,9 @@ func TestSkillPluginsAvailableDuringStageExecution(t *testing.T) { // This test creates a worktree with a skill that has a bundled plugin. // It runs an AgentStage and verifies the plugin was loaded and is // accessible via the TaskContext. + // + // Additionally (Gap 8): when metadata.archie.plugins lists specific + // plugin files, only those are loaded — unlisted *.go files are ignored. dir := t.TempDir() skillsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-tdd") @@ -30,7 +33,7 @@ func TestSkillPluginsAvailableDuringStageExecution(t *testing.T) { t.Fatal(err) } - // Write the skill SKILL.md. + // Write the skill SKILL.md with explicit plugin list. if err := os.WriteFile(filepath.Join(skillsDir, "SKILL.md"), []byte(`--- name: tdd-bugfix description: TDD workflow @@ -40,13 +43,15 @@ metadata: tools: [go] engine: any workflow: tdd + plugins: + - plugins/security-check.go --- Analyse the bug, write repro tests, fix. `), 0o644); err != nil { t.Fatal(err) } - // Write a bundled plugin. + // Write the listed bundled plugin. if err := os.WriteFile(filepath.Join(pluginsDir, "security-check.go"), []byte(`package main func Run(input string) string { @@ -56,6 +61,16 @@ func Run(input string) string { t.Fatal(err) } + // Write an unlisted plugin — it must NOT be loaded. + if err := os.WriteFile(filepath.Join(pluginsDir, "extra.go"), []byte(`package main + +func Run(input string) string { + return "extra" +} +`), 0o644); err != nil { + t.Fatal(err) + } + // Run an AgentStage against this worktree. pluginCalls := 0 runner := &fakeAgentRunner{result: agentexec.Result{ @@ -87,6 +102,19 @@ func Run(input string) string { return } + // Gap 8 assertion: only the frontmatter-listed plugin must be loaded. + // The unlisted extra.go must NOT appear in SkillPlugins. + if len(tc.SkillPlugins) != 1 { + t.Errorf("Gap 8: got %d plugins, want 1 — loadSkillBody must honor "+ + "metadata.archie.plugins and exclude unlisted *.go files", len(tc.SkillPlugins)) + } + for _, p := range tc.SkillPlugins { + if p.Name == "extra" { + t.Error("Gap 8: unlisted plugin 'extra' was loaded — " + + "loadSkillBody must only load plugins declared in metadata.archie.plugins") + } + } + // Verify plugins are runnable. for _, p := range tc.SkillPlugins { out, err := p.Run("test-input")