diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 621472e3a..7dceac9c7 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -202,7 +202,8 @@ func run() int { pluginReg = &plugin.Registry{} for _, p := range plugins { pluginReg.Register(p) - log.Info("daemon plugin loaded", "name", p.Name(), "version", p.Version()) + name, version := safePluginInfo(p) + log.Info("daemon plugin loaded", "name", name, "version", version) } } @@ -261,3 +262,15 @@ func configHome() string { home, _ := os.UserHomeDir() return filepath.Join(home, ".config") } + +// safePluginInfo calls Name() and Version() on a plugin, recovering from +// panics. A panicking plugin must not crash the daemon at startup. +func safePluginInfo(p plugin.Plugin) (name, version string) { + defer func() { + if r := recover(); r != nil { + name = "(panic)" + version = "(panic)" + } + }() + return p.Name(), p.Version() +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 3f2e000a2..fc7830ada 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -505,19 +505,29 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { } wf := workflow.Route(task, registry) d.Log.Info("processing task", "repo", repo.FullName(), "issue", task.IssueNumber, "workflow", wf.Name, "attempt", task.Attempt) - d.Forge.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues()) // Acquire a container for the task when Docker sandboxing is enabled. if d.ContainerPool != nil { // Write task.json — the container's boot-time brief. - _ = container.WriteTaskJSON(workDir, container.TaskPayload{ + if err := container.WriteTaskJSON(workDir, container.TaskPayload{ ID: task.ID, Owner: task.Owner, Repo: task.Repo, Number: task.IssueNumber, Title: task.Title, Body: task.Body, Labels: strings.Split(task.Labels, ","), Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan, - }) + }); err != nil { + d.Log.Error("task.json write failed", "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "task.json write failed: "+err.Error()) + return + } // Build the mount list from the storage backend. + // Guard: Storage may be nil if the daemon was wired incorrectly. + // In normal operation, Storage is always set when ContainerPool is set. + if d.Storage == nil { + d.Log.Error("storage backend is nil — cannot acquire container") + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "storage backend not configured") + return + } mounts, err := d.Storage.Setup(ctx, storage.TaskRef{ WorktreeDir: workDir, Ecosystem: repo.Ecosystem, @@ -539,6 +549,10 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { defer d.ContainerPool.Release(ctr) } + // Set the working label only after successful container setup (or when no + // container is needed). This prevents label/database divergence on failure. + d.Forge.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues()) + workflow.Run(ctx, wf, &workflow.TaskContext{ Task: task, Repo: repo, diff --git a/internal/plugin/plugin_test.go b/internal/plugin/plugin_test.go index 17c188f74..110c7c427 100644 --- a/internal/plugin/plugin_test.go +++ b/internal/plugin/plugin_test.go @@ -389,6 +389,60 @@ var Plugin = struct{}{} _ = plugins } +func TestGeneratedWrapperHasNilGuards(t *testing.T) { + // C4: the generated _Plugin wrapper must nil-guard WName and WVersion. + // If go generate strips these guards, the daemon panics at startup + // when logging plugin names. This test verifies the guards exist + // and will fail if someone regenerates without them. + // + // The _Plugin type is in the pluginextract package. We verify + // indirectly by loading a plugin with nil funcs and calling + // Name()/Version() — they must return empty strings, not panic. + + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "nilguard.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/plugin" + +var Plugin = plugin._Plugin{ + WName: nil, + WVersion: nil, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + plugins, err := plugin.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if len(plugins) != 1 { + t.Fatal("plugin with nil funcs not loaded") + } + + // These must not panic. If they do, go generate was run and stripped + // the nil guards from the generated wrapper. + var name, version string + func() { + defer func() { + if r := recover(); r != nil { + t.Fatalf("Name()/Version() panicked with nil funcs — "+ + "the generated _Plugin wrapper is missing nil guards. "+ + "Re-run `go generate` may have overwritten them: %v", r) + } + }() + name = plugins[0].Name() + version = plugins[0].Version() + }() + + if name != "" { + t.Errorf("Name() = %q, want empty from nil WName", name) + } + if version != "" { + t.Errorf("Version() = %q, want empty from nil WVersion", version) + } +} + func TestLoadDirPluginWithGoBuildTag(t *testing.T) { // Build tags in Yaegi-interpreted code are just comments — they // don't gate evaluation. The file loads normally. diff --git a/internal/skill/skill.go b/internal/skill/skill.go index 692157403..9df6ee9da 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -41,7 +41,8 @@ type CatalogEntry struct { // Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries // (Tier 1: name + description + workflow only). Only the frontmatter is -// parsed — full bodies are not loaded. Missing directory returns nil. +// parsed — full bodies are not loaded. Missing directory or a file at the +// skills path returns nil (no error) — the caller treats this as "no skills." func Catalog(dir string) ([]CatalogEntry, error) { skillsPath := filepath.Join(dir, skillsDir) entries, err := os.ReadDir(skillsPath) @@ -49,7 +50,9 @@ func Catalog(dir string) ([]CatalogEntry, error) { return nil, nil } if err != nil { - return nil, fmt.Errorf("read skills dir %s: %w", skillsPath, err) + // A file at .agents/skills (ENOTDIR) is not fatal — treat as no skills. + // Same for permission errors and other non-fatal ReadDir failures. + return nil, nil } var names []string diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 9de7fd3e8..5aebae331 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -23,6 +23,7 @@ import ( "context" "fmt" "sort" + "strings" "github.com/moby/moby/api/types/mount" "github.com/moby/moby/client" @@ -90,8 +91,9 @@ var cacheVolumesByEcosystem = map[string][]cacheVolume{ // cacheMounts returns the cache mount specs for an ecosystem, sorted by // destination path for deterministic container configuration. +// Ecosystem is case-insensitive — "Python" and "python" are equivalent. func cacheMounts(ecosystem string) []Mount { - vols, ok := cacheVolumesByEcosystem[ecosystem] + vols, ok := cacheVolumesByEcosystem[strings.ToLower(ecosystem)] if !ok { return nil } @@ -136,6 +138,8 @@ func NewDockerBackend(cli *client.Client) *DockerBackend { } // ensureVolume creates a Docker volume if it doesn't already exist. +// It is idempotent: concurrent callers racing to create the same volume +// will not see an error — "already exists" is treated as success. func (d *DockerBackend) ensureVolume(ctx context.Context, name string) error { if d.cli == nil { return nil // nil client for testing @@ -149,6 +153,12 @@ func (d *DockerBackend) ensureVolume(ctx context.Context, name string) error { Driver: "local", }) if err != nil { + // TOCTOU: a concurrent caller may have created the volume between + // our inspect and create calls. Docker returns an error for + // duplicate volumes — treat that as success. + if strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "already in use") { + return nil + } return &ErrVolumeCreate{Volume: name, Cause: err} } return nil diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index 78207a27f..277a8a284 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -369,6 +369,43 @@ func TestRepoVolumeName(t *testing.T) { } } +// ── audit fixes ────────────────────────────────────────────────────── + +func TestCacheMountsCaseInsensitive(t *testing.T) { + // C6: ecosystem must be case-insensitive. "Python", "Go", "NODE" + // must all return the same cache mounts as their lowercase forms. + for _, eco := range []string{"Go", "GO", "go", "gO"} { + mounts := cacheMounts(eco) + names := mountDestinations(mounts) + if !contains(names, "/data/cache/go") { + t.Errorf("ecosystem %q: missing /data/cache/go in %v", eco, names) + } + } + for _, eco := range []string{"Python", "PYTHON", "python"} { + mounts := cacheMounts(eco) + names := mountDestinations(mounts) + if !contains(names, "/data/cache/pip") { + t.Errorf("ecosystem %q: missing /data/cache/pip in %v", eco, names) + } + } +} + +func TestEnsureVolumeAlreadyExistsIsNotError(t *testing.T) { + // N1: if a volume already exists (concurrent creation), ensureVolume + // must not treat it as an error. The TOCTOU between VolumeInspect and + // VolumeCreate must be handled. + // + // We can't test against a real Docker daemon, but we can test the + // design: ensureVolume should only return an error when Docker returns + // something OTHER than "already exists". For now, verify that + // ensureVolume with nil client returns nil (existing behavior). + backend := &DockerBackend{} + err := backend.ensureVolume(context.Background(), "test-volume") + if err != nil { + t.Error("ensureVolume with nil client should not error:", err) + } +} + // ── helpers ────────────────────────────────────────────────────────── func mountDestinations(mounts []Mount) []string { diff --git a/internal/workflow/skillbuild/skillbuild.go b/internal/workflow/skillbuild/skillbuild.go index 39c12d72d..3b20df58c 100644 --- a/internal/workflow/skillbuild/skillbuild.go +++ b/internal/workflow/skillbuild/skillbuild.go @@ -5,6 +5,7 @@ package skillbuild import ( "context" "fmt" + "log/slog" "os" "path/filepath" "sort" @@ -57,6 +58,12 @@ func BuildRegistry(worktree string) (workflow.Registry, error) { // an empty workflow means the skill declared intent but has no // plugins yet, so keep the built-in. if len(wf.Stages) > 0 { + if _, dup := reg[entry.Workflow]; dup { + slog.Default().Warn("duplicate workflow name — overriding", + "workflow", entry.Workflow, + "skill", entry.Dir, + ) + } reg[entry.Workflow] = wf } } @@ -106,6 +113,12 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry // An empty workflow means the skill declared intent but has no // plugins yet — keep the base (or built-in) definition. if len(wf.Stages) > 0 { + if _, dup := reg[entry.Workflow]; dup { + slog.Default().Warn("duplicate workflow name — overriding", + "workflow", entry.Workflow, + "skill", entry.Dir, + ) + } reg[entry.Workflow] = wf } }