diff --git a/.gitignore b/.gitignore index 53f7ceaf5..5f0bb3ae7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -archied +/archied *.db diff --git a/cmd/archied/main.go b/cmd/archied/main.go new file mode 100644 index 000000000..b797e246b --- /dev/null +++ b/cmd/archied/main.go @@ -0,0 +1,172 @@ +// Command archied is the archie orchestrator daemon: it watches GitHub +// for issues labelled for archie, works each one in an isolated +// worktree through its routed workflow, and opens pull requests for +// human review. +package main + +import ( + "context" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "path/filepath" + "syscall" + + "github.com/samcharles93/ai-sdk/runtime" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/daemon" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/forge" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/webui" + "github.com/samcharles93/archie-core/internal/workflow" + "github.com/samcharles93/archie-core/internal/worktree" +) + +func main() { + os.Exit(run()) +} + +func run() int { + defaultCfg := filepath.Join(configHome(), "archie", "config.toml") + cfgPath := flag.String("config", defaultCfg, "path to config.toml") + once := flag.Bool("once", false, "run a single poll+process cycle and exit (systemd timer / testing)") + requeue := flag.Int64("requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set") + flag.Parse() + + log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) + + cfg, err := config.Load(*cfgPath) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + + token := os.Getenv(cfg.Forge.TokenEnv) + if token == "" { + fmt.Fprintln(os.Stderr, cfg.Forge.TokenEnv+" is required") + return 1 + } + forgeClient, err := forge.New(token, cfg.Forge.Host, log) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + + st, err := store.Open(cfg.DBPath) + if err != nil { + log.Error("open store", "err", err) + return 1 + } + defer st.Close() + + if *requeue > 0 { + if err := st.Requeue(context.Background(), *requeue, "manual", ""); err != nil { + log.Error("requeue failed", "task", *requeue, "err", err) + return 1 + } + log.Info("task requeued", "task", *requeue) + if !*once { + return 0 + } + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + // Observability: every event is logged to SQLite (stamped with its + // row id) and then fanned out to live dashboard connections. + bus := events.NewBus() + defer bus.Close() + web := &webui.Server{Store: st, Log: log} + sink := bus.Subscribe(256) + go func() { + for e := range sink.C { + id, err := st.InsertEvent(context.Background(), e) + if err != nil { + log.Error("event sink insert failed", "err", err) + continue + } + e.ID = id + web.Broadcast(e) + } + }() + if l := cfg.Web.Listen; l != "" && l != "off" { + go func() { + if err := web.Run(ctx, l); err != nil { + log.Error("web ui failed", "err", err) + } + }() + } + + d := &daemon.Daemon{ + Cfg: cfg, + Store: st, + Bus: bus, + Forge: forgeClient, + Trees: &worktree.Manager{ + WorkDir: cfg.WorkDir, + Token: token, + BotUser: cfg.BotUser, + BotEmail: cfg.BotEmail, + BaseURL: cfg.Forge.Host, + }, + Runtime: llmRuntime(cfg), + Workflows: workflow.Registry{ + "bootstrap": workflow.Bootstrap(), + "implement": workflow.Implement(), + "tdd": workflow.TDD(), + "feasibility": workflow.Feasibility(), + "default": workflow.Implement(), + }, + Log: log, + } + + if err := d.Startup(ctx); err != nil { + log.Error("startup", "err", err) + return 1 + } + + if *once { + d.Cycle(ctx) + return 0 + } + log.Info("archied running", "repos", len(cfg.Repos), "poll", cfg.PollInterval.Std().String(), "label", cfg.Label) + if err := d.Run(ctx); err != nil && ctx.Err() == nil { + log.Error("daemon exited", "err", err) + return 1 + } + return 0 +} + +// llmRuntime builds the ai-sdk runtime from the [providers] config. +// Nil when no providers are configured — agent workflows then park with +// a clear error while deterministic workflows keep working. +func llmRuntime(cfg config.Config) *runtime.Runtime { + if len(cfg.Providers) == 0 { + return nil + } + runtime.RegisterBuiltinClasses() + providers := make(map[string]runtime.ProviderConfig, len(cfg.Providers)) + for name, p := range cfg.Providers { + pc := runtime.ProviderConfig{ID: name, Class: p.Class, BaseURL: p.BaseURL} + if p.APIKeyEnv != "" { + pc.Auth = runtime.AuthConfig{APIKeyEnv: p.APIKeyEnv} + } else { + pc.Auth = runtime.AuthConfig{Type: runtime.AuthTypeNone} + } + providers[name] = pc + } + return runtime.NewRuntime(runtime.Config{Providers: providers}) +} + +func configHome() string { + if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { + return x + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".config") +} diff --git a/config.example.toml b/config.example.toml index 539703aae..a175cc3ee 100644 --- a/config.example.toml +++ b/config.example.toml @@ -1,5 +1,5 @@ # archied configuration. Copy to ~/.config/archie/config.toml. -# The GitHub token is NOT configured here: export ARCHIE_GITHUB_TOKEN. +# Forge tokens are NOT configured here: export the variable named by token_env. # work_dir = "~/.local/share/archie/work" # default # db_path = "~/.local/share/archie/archie.db" @@ -8,6 +8,22 @@ label = "archie" bot_user = "vectis-labs-archie" diff_cap_lines = 400 +[forge] +type = "github" +host = "https://github.com" +token_env = "ARCHIE_GITHUB_TOKEN" + +[dispatch] +trigger = "assignee" # "assignee", "label", or "either" +ack_reaction = "eyes" # "off" disables pickup reactions + +[dispatch.labels] +queued = "archie:queued" +working = "archie:working" +waiting = "archie:waiting" +pr = "archie:pr" +parked = "archie:parked" + [models] # role -> ai-sdk runtime ref (used by agent workflows, Phase 4b) triage = "openai/gpt-5.4" planner = "openai/gpt-5.4" @@ -36,6 +52,10 @@ gate_max_failures = 5 owner = "samcharles93" name = "todo" base = "main" +ecosystem = "go" # "go", "python", "node", "rust", or "custom" +# Override the ecosystem defaults when needed: +# preflight = [["go", "version"]] +# test_glob = "*_test.go" protect = ["_templ.go"] gate = [ ["templ", "generate", "./components/"], diff --git a/internal/config/config.go b/internal/config/config.go index 0b27d9d91..5229b20a4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,5 +1,5 @@ -// Package config loads archied's TOML configuration. The GitHub token is -// deliberately not part of the file: it comes from ARCHIE_GITHUB_TOKEN. +// Package config loads archied's TOML configuration. The forge API token is +// deliberately not part of the file: it comes from a configurable env var. package config import ( @@ -34,13 +34,28 @@ type Repo struct { // Base is the branch PRs target. Defaults to "main". Base string `toml:"base"` // Gate is the quality-gate command list for this repo, e.g. - // [["go","vet","./..."], ["task","check"]]. Workflow stages may - // extend or override it (a TDD repro stage inverts the test command). + // [["go","vet","./..."], ["task","check"]]. By convention the + // LAST command is the test runner — TDD workflows invert only + // that one with ExpectFailure during the repro stage and re-run + // it in capture-proof. Workflow stages may extend or override + // Gate (a TDD repro stage inverts the test command). Gate [][]string `toml:"gate"` // Protect lists path suffixes agents must never write directly — // generated files (e.g. "_templ.go") whose sources they should edit // instead. Enforced environmentally via agentloop.ProtectPaths. Protect []string `toml:"protect"` + + // Ecosystem selects a default preflight check and test-file glob + // ("go", "python", "node", "rust", or "custom"). Empty defaults + // to "go" for backward compatibility. + Ecosystem string `toml:"ecosystem"` + // Preflight is an explicit override for the ecosystem's default + // preflight commands. Empty inherits the ecosystem default. + Preflight [][]string `toml:"preflight"` + // TestGlob is an explicit override for the ecosystem's default + // test-file pattern (e.g. "*_test.go"). Empty inherits the + // ecosystem default. + TestGlob string `toml:"test_glob"` } // Protected reports whether path matches a protected suffix. @@ -53,6 +68,41 @@ func (r Repo) Protected(path string) bool { return false } +// effectiveEcosystem returns the ecosystem to use, defaulting to "go" +// when unset (backward compatibility: pre-ecosystem configs are Go). +func (r Repo) effectiveEcosystem() string { + if r.Ecosystem != "" { + return r.Ecosystem + } + return "go" +} + +// ResolvedPreflight returns the preflight commands for this repo. +// Explicit Preflight wins; otherwise the ecosystem default; empty +// for unknown ecosystems and "custom". +func (r Repo) ResolvedPreflight() [][]string { + if len(r.Preflight) > 0 { + return r.Preflight + } + if eco, ok := ecosystems[r.effectiveEcosystem()]; ok { + return eco.Preflight + } + return nil +} + +// ResolvedTestGlob returns the test-file glob pattern for this repo. +// Explicit TestGlob wins; otherwise the ecosystem default; empty +// for unknown ecosystems and "custom" (protection no-ops). +func (r Repo) ResolvedTestGlob() string { + if r.TestGlob != "" { + return r.TestGlob + } + if eco, ok := ecosystems[r.effectiveEcosystem()]; ok { + return eco.TestGlob + } + return "" +} + func (r Repo) FullName() string { return r.Owner + "/" + r.Name } func (r Repo) BaseBranch() string { @@ -77,6 +127,68 @@ type Provider struct { BaseURL string `toml:"base_url"` } +// Forge configures the code forge integration. +type Forge struct { + Type string `toml:"type"` + Host string `toml:"host"` + TokenEnv string `toml:"token_env"` +} + +// Dispatch configures how archied discovers work and reflects task state +// onto the forge via labels and reactions. +type Dispatch struct { + // Trigger is how tasks are discovered: "assignee" (poll assigned + // issues), "label" (poll labelled issues), or "either" (both). + Trigger string `toml:"trigger"` + // AckReaction is the emoji reaction posted on issue pickup. Set + // ack_reaction = "off" in TOML to disable it; Load normalizes that + // sentinel to an empty string for callers. + AckReaction string `toml:"ack_reaction"` + // Labels maps state names ("queued", "working", "waiting", "pr", + // "parked") to their forge label strings. Each key is defaulted + // independently; missing keys fall back to the legacy archie:* + // constants at call time via StateLabel(). + Labels map[string]string `toml:"labels"` +} + +// dispatchLabelDefaults is the fallback label set, reproducing the +// legacy archie:* constants that were previously in internal/forge. +var dispatchLabelDefaults = map[string]string{ + "queued": "archie:queued", + "working": "archie:working", + "waiting": "archie:waiting", + "pr": "archie:pr", + "parked": "archie:parked", +} + +// StateLabel returns the configured label for a state name. Falls back +// to the legacy archie:* constant when the key is missing or empty. +func (d Dispatch) StateLabel(state string) string { + if s, ok := d.Labels[state]; ok && s != "" { + return s + } + if s, ok := dispatchLabelDefaults[state]; ok { + return s + } + return "" +} + +// LabelValues returns the set of all configured state label strings. +// Used by SetStateLabel to detect and remove old state labels regardless +// of naming convention. +func (d Dispatch) LabelValues() []string { + seen := map[string]bool{} + var out []string + for _, k := range []string{"queued", "working", "waiting", "pr", "parked"} { + v := d.StateLabel(k) + if v != "" && !seen[v] { + seen[v] = true + out = append(out, v) + } + } + return out +} + // Config is the daemon configuration. type Config struct { WorkDir string `toml:"work_dir"` @@ -90,6 +202,9 @@ type Config struct { BotEmail string `toml:"bot_email"` DiffCapLines int `toml:"diff_cap_lines"` + Forge Forge `toml:"forge"` + Dispatch Dispatch `toml:"dispatch"` + // Models maps a role ("planner", "builder", "triage") to a runtime // model ref ("provider/model"). Models map[string]string `toml:"models"` @@ -111,7 +226,7 @@ type Notify struct { // Web configures the observability dashboard. type Web struct { - // Listen is the dashboard address; empty disables the web UI. + // Listen is the dashboard address; "off" disables the web UI. // Bind localhost (or a LAN/tailnet address) — there is no auth. Listen string `toml:"listen"` } @@ -140,19 +255,57 @@ func Load(path string) (Config, error) { if cfg.Web.Listen == "" { cfg.Web.Listen = "127.0.0.1:8484" // "off" disables } + if cfg.Forge.Type == "" { + cfg.Forge.Type = "github" + } + if cfg.Forge.Host == "" { + cfg.Forge.Host = "https://github.com" + } + if cfg.Forge.TokenEnv == "" { + cfg.Forge.TokenEnv = "ARCHIE_GITHUB_TOKEN" + } + if cfg.Dispatch.Trigger == "" { + cfg.Dispatch.Trigger = "assignee" + } + switch cfg.Dispatch.Trigger { + case "assignee", "label", "either": + default: + return cfg, fmt.Errorf("config: dispatch.trigger %q is invalid (want assignee, label, or either)", cfg.Dispatch.Trigger) + } + if cfg.Dispatch.AckReaction == "" { + cfg.Dispatch.AckReaction = "eyes" + } else if strings.EqualFold(cfg.Dispatch.AckReaction, "off") { + cfg.Dispatch.AckReaction = "" + } + if cfg.Dispatch.Labels == nil { + cfg.Dispatch.Labels = map[string]string{} + } + for k, v := range dispatchLabelDefaults { + if cfg.Dispatch.Labels[k] == "" { + cfg.Dispatch.Labels[k] = v + } + } if cfg.BotUser == "" { return cfg, errors.New("config: bot_user is required") } - if cfg.BotEmail == "" { + if cfg.BotEmail == "" && cfg.Forge.Type == "github" { cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" } if len(cfg.Repos) == 0 { return cfg, errors.New("config: at least one [[repos]] entry is required") } + if cfg.Forge.Type != "github" { + return cfg, fmt.Errorf("config: forge.type %q is not yet supported", cfg.Forge.Type) + } for i, r := range cfg.Repos { if r.Owner == "" || r.Name == "" { return cfg, fmt.Errorf("config: repos[%d] needs owner and name", i) } + if glob := r.ResolvedTestGlob(); glob != "" { + if _, err := filepath.Match(glob, ""); err != nil { + return cfg, fmt.Errorf("config: repos[%d] test_glob %q is invalid: %w", i, glob, err) + } + } } return cfg, nil } diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 000000000..a8a2fe3ad --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,249 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestDispatchDefaults(t *testing.T) { + // Simulate a config with no [dispatch] section — all fields zero. + var d Dispatch + d.Labels = map[string]string{} + + // Per-key defaults (mimicking Load's loop). + for k, v := range dispatchLabelDefaults { + if d.Labels[k] == "" { + d.Labels[k] = v + } + } + if d.Trigger == "" { + d.Trigger = "assignee" + } + if d.AckReaction == "" { + d.AckReaction = "eyes" + } + + // StateLabel should return the legacy constants. + if got := d.StateLabel("queued"); got != "archie:queued" { + t.Errorf("queued: got %q, want archie:queued", got) + } + if got := d.StateLabel("working"); got != "archie:working" { + t.Errorf("working: got %q, want archie:working", got) + } + if got := d.StateLabel("waiting"); got != "archie:waiting" { + t.Errorf("waiting: got %q, want archie:waiting", got) + } + if got := d.StateLabel("pr"); got != "archie:pr" { + t.Errorf("pr: got %q, want archie:pr", got) + } + if got := d.StateLabel("parked"); got != "archie:parked" { + t.Errorf("parked: got %q, want archie:parked", got) + } + + // Unknown state returns empty. + if got := d.StateLabel("nonexistent"); got != "" { + t.Errorf("nonexistent: got %q, want empty", got) + } + + // AckReaction default. + if d.AckReaction != "eyes" { + t.Errorf("AckReaction: got %q, want eyes", d.AckReaction) + } + + // Trigger default. + if d.Trigger != "assignee" { + t.Errorf("Trigger: got %q, want assignee", d.Trigger) + } +} + +func TestDispatchCustomLabels(t *testing.T) { + d := Dispatch{ + Trigger: "label", + AckReaction: "", + Labels: map[string]string{ + "queued": "bot:queued", + "working": "bot:working", + "parked": "bot:parked", + // "waiting" and "pr" intentionally missing — should fall back. + }, + } + + // Custom labels. + if got := d.StateLabel("queued"); got != "bot:queued" { + t.Errorf("queued: got %q, want bot:queued", got) + } + if got := d.StateLabel("parked"); got != "bot:parked" { + t.Errorf("parked: got %q, want bot:parked", got) + } + + // Missing keys fall back to defaults. + if got := d.StateLabel("waiting"); got != "archie:waiting" { + t.Errorf("waiting: got %q, want archie:waiting (fallback)", got) + } + if got := d.StateLabel("pr"); got != "archie:pr" { + t.Errorf("pr: got %q, want archie:pr (fallback)", got) + } + + // Empty AckReaction. + if d.AckReaction != "" { + t.Errorf("AckReaction: got %q, want empty", d.AckReaction) + } + + // LabelValues returns all five state labels. + vals := d.LabelValues() + if len(vals) != 5 { + t.Errorf("LabelValues: got %d values, want 5: %v", len(vals), vals) + } + seen := map[string]bool{} + for _, v := range vals { + seen[v] = true + } + for _, want := range []string{"bot:queued", "bot:working", "bot:parked", "archie:waiting", "archie:pr"} { + if !seen[want] { + t.Errorf("LabelValues missing %q", want) + } + } +} + +func TestDispatchLabelValuesDedup(t *testing.T) { + // When two state keys map to the same label string, LabelValues + // should deduplicate. + d := Dispatch{ + Labels: map[string]string{ + "queued": "bot:queued", + "working": "bot:queued", // same as queued + "parked": "bot:queued", // same again + }, + } + vals := d.LabelValues() + // Should have "bot:queued" plus fallbacks for waiting and pr. + if len(vals) != 3 { + t.Errorf("LabelValues: got %d values, want 3: %v", len(vals), vals) + } +} + +func TestLoadDispatchAckReaction(t *testing.T) { + tests := []struct { + name string + dispatch string + wantAck string + }{ + {name: "default", wantAck: "eyes"}, + {name: "disabled", dispatch: "\n[dispatch]\nack_reaction = \"off\"\n", wantAck: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + contents := "bot_user = \"archie\"\n" + tt.dispatch + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.Dispatch.AckReaction != tt.wantAck { + t.Errorf("AckReaction: got %q, want %q", cfg.Dispatch.AckReaction, tt.wantAck) + } + }) + } +} + +func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) { + tests := []struct { + name string + extra string + }{ + {name: "dispatch trigger", extra: "\n[dispatch]\ntrigger = \"labels\"\n"}, + {name: "test glob", extra: "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + contents := "bot_user = \"archie\"\n" + if tt.name != "test glob" { + contents += "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" + } + contents += tt.extra + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + + if _, err := Load(path); err == nil { + t.Fatal("Load() succeeded, want validation error") + } + }) + } +} + +func TestExampleConfigLoads(t *testing.T) { + cfg, err := Load(filepath.Join("..", "..", "config.example.toml")) + if err != nil { + t.Fatal(err) + } + if cfg.Forge.Host != "https://github.com" { + t.Errorf("Forge.Host: got %q", cfg.Forge.Host) + } + if cfg.Dispatch.AckReaction != "eyes" { + t.Errorf("Dispatch.AckReaction: got %q", cfg.Dispatch.AckReaction) + } + if len(cfg.Repos) != 1 || cfg.Repos[0].ResolvedTestGlob() != "*_test.go" { + t.Errorf("Repos: got %+v", cfg.Repos) + } +} + +func TestEcosystemDefaults(t *testing.T) { + // Empty ecosystem → "go" (backward compat). + r := Repo{} + if got := r.effectiveEcosystem(); got != "go" { + t.Errorf("effectiveEcosystem empty: got %q, want go", got) + } + if got := r.ResolvedTestGlob(); got != "*_test.go" { + t.Errorf("ResolvedTestGlob empty: got %q, want *_test.go", got) + } + pre := r.ResolvedPreflight() + if len(pre) != 1 || pre[0][0] != "go" || pre[0][1] != "version" { + t.Errorf("ResolvedPreflight empty: got %v, want [[go version]]", pre) + } + + // Explicit ecosystem. + r2 := Repo{Ecosystem: "python"} + if got := r2.ResolvedTestGlob(); got != "test_*.py" { + t.Errorf("ResolvedTestGlob python: got %q, want test_*.py", got) + } + pre2 := r2.ResolvedPreflight() + if len(pre2) != 1 || pre2[0][0] != "python" || pre2[0][1] != "--version" { + t.Errorf("ResolvedPreflight python: got %v, want [[python --version]]", pre2) + } +} + +func TestEcosystemOverrides(t *testing.T) { + // Explicit Preflight and TestGlob always win over ecosystem. + r := Repo{ + Ecosystem: "go", + Preflight: [][]string{{"make", "check"}}, + TestGlob: "spec_*.py", + } + if got := r.ResolvedTestGlob(); got != "spec_*.py" { + t.Errorf("ResolvedTestGlob override: got %q, want spec_*.py", got) + } + pre := r.ResolvedPreflight() + if len(pre) != 1 || pre[0][0] != "make" || pre[0][1] != "check" { + t.Errorf("ResolvedPreflight override: got %v, want [[make check]]", pre) + } +} + +func TestEcosystemCustom(t *testing.T) { + // "custom" ecosystem has no defaults — preflight empty, test glob empty. + r := Repo{Ecosystem: "custom"} + if got := r.ResolvedTestGlob(); got != "" { + t.Errorf("ResolvedTestGlob custom: got %q, want empty", got) + } + if got := r.ResolvedPreflight(); got != nil { + t.Errorf("ResolvedPreflight custom: got %v, want nil", got) + } +} diff --git a/internal/config/ecosystem.go b/internal/config/ecosystem.go new file mode 100644 index 000000000..1ba212fce --- /dev/null +++ b/internal/config/ecosystem.go @@ -0,0 +1,30 @@ +package config + +// ecosystemDefaults holds the per-ecosystem default preflight check and +// test-file glob. An ecosystem not listed here (or "custom") means: no +// preflight at all, empty test glob (protection no-ops). +type ecosystemDefaults struct { + Preflight [][]string + TestGlob string +} + +// ecosystems maps known ecosystem names to their defaults. +// "custom" is deliberately absent — it means user-configured everything. +var ecosystems = map[string]ecosystemDefaults{ + "go": { + Preflight: [][]string{{"go", "version"}}, + TestGlob: "*_test.go", + }, + "python": { + Preflight: [][]string{{"python", "--version"}}, + TestGlob: "test_*.py", + }, + "node": { + Preflight: [][]string{{"node", "--version"}}, + TestGlob: "*.test.ts", + }, + "rust": { + Preflight: [][]string{{"cargo", "--version"}}, + TestGlob: "tests/*.rs", + }, +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index e333b9232..14124d335 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -11,7 +11,6 @@ import ( "strings" "time" - "github.com/google/go-github/v78/github" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" @@ -26,7 +25,7 @@ import ( type Daemon struct { Cfg config.Config Store *store.Store - Forge *forge.Client + Forge forge.Forge Trees *worktree.Manager Runtime *runtime.Runtime Bus *events.Bus @@ -100,27 +99,114 @@ func (d *Daemon) Cycle(ctx context.Context) { func (d *Daemon) poll(ctx context.Context) { for _, repo := range d.Cfg.Repos { - issues, err := d.Forge.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser) - if err != nil { - d.Log.Error("poll failed", "repo", repo.FullName(), "err", err) - continue - } + issues := d.pollIssues(ctx, repo) for _, is := range issues { inserted, err := d.Store.EnqueueIssue(ctx, - repo.Owner, repo.Name, is.GetNumber(), is.GetTitle(), is.GetBody(), labelNames(is)) + repo.Owner, repo.Name, is.Number, is.Title, is.Body, strings.Join(is.Labels, ",")) if err != nil { - d.Log.Error("enqueue failed", "repo", repo.FullName(), "issue", is.GetNumber(), "err", err) + d.Log.Error("enqueue failed", "repo", repo.FullName(), "issue", is.Number, "err", err) continue } if inserted { - d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.GetNumber(), "title", is.GetTitle()) + d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title) + // Instant acknowledgement: the human sees pickup, not + // silence until a PR appears. + if ack := d.Cfg.Dispatch.AckReaction; ack != "" { + if err := d.Forge.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil { + d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err) + } + } + d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues()) d.emit(events.Event{ Kind: events.KindTaskQueued, Repo: repo.FullName(), - Issue: is.GetNumber(), Detail: is.GetTitle(), + Issue: is.Number, Detail: is.Title, }) + continue + } + d.maybeRetryParked(ctx, repo, is) + } + } +} + +// pollIssues discovers work for one repo according to cfg.Dispatch.Trigger. +func (d *Daemon) pollIssues(ctx context.Context, repo config.Repo) []forge.Issue { + switch d.Cfg.Dispatch.Trigger { + case "label": + issues, err := d.Forge.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label) + if err != nil { + d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err) + return nil + } + return issues + case "either": + return d.pollEither(ctx, repo) + default: // "assignee" (default) + issues, err := d.Forge.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser) + if err != nil { + d.Log.Error("poll failed", "repo", repo.FullName(), "err", err) + return nil + } + return issues + } +} + +// pollEither returns the union of assigned and labelled issues, deduped +// by issue number. An issue both assigned and labelled appears once. +func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue { + seen := map[int]bool{} + var out []forge.Issue + + assigned, err := d.Forge.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser) + if err != nil { + d.Log.Error("assigned poll failed", "repo", repo.FullName(), "err", err) + } else { + for _, is := range assigned { + seen[is.Number] = true + out = append(out, is) + } + } + + labelled, err := d.Forge.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label) + if err != nil { + d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err) + } else { + for _, is := range labelled { + if !seen[is.Number] { + out = append(out, is) } } } + + return out +} + +// maybeRetryParked requeues a parked task whose archie:parked label a +// human has removed — the forge-native retry trigger. +func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forge.Issue) { + if hasLabel(is.Labels, d.Cfg.Dispatch.StateLabel("parked")) { + return + } + task, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number) + if err != nil || task == nil || task.Status != store.StatusParked { + return + } + if err := d.Store.Requeue(ctx, task.ID, store.StatusParked, ""); err != nil { + d.Log.Error("label-triggered requeue failed", "issue", is.Number, "err", err) + return + } + d.Log.Info("parked task requeued via label removal", "repo", repo.FullName(), "issue", is.Number) + d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues()) + d.emit(events.Event{Kind: "task_retried", TaskID: task.ID, + Repo: repo.FullName(), Issue: is.Number, Detail: "archie:parked label removed"}) +} + +func hasLabel(labels []string, want string) bool { + for _, label := range labels { + if label == want { + return true + } + } + return false } // reconcilePRs moves pr_open tasks to merged/rejected from GitHub state @@ -141,6 +227,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { case "merged": _ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusMerged, "") _ = d.Trees.Cleanup(t.Owner, t.Repo, t.IssueNumber) + d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues()) d.Log.Info("PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber) d.emit(events.Event{ Kind: events.KindPRMerged, TaskID: t.ID, @@ -150,6 +237,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { case "closed": _ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusRejected, "PR closed without merge") _ = d.Trees.Cleanup(t.Owner, t.Repo, t.IssueNumber) + d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues()) d.Log.Info("PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber) d.emit(events.Event{ Kind: events.KindPRRejected, TaskID: t.ID, @@ -197,6 +285,7 @@ func (d *Daemon) checkWaiting(ctx context.Context) { } _, _ = d.Forge.Comment(ctx, t.Owner, t.Repo, t.IssueNumber, "**Go-ahead received — implementation is queued.** ("+reason+")") + d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues()) d.emit(events.Event{ Kind: "human_approved", TaskID: t.ID, Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason, @@ -205,6 +294,7 @@ func (d *Daemon) checkWaiting(ctx context.Context) { _ = d.Store.Transition(ctx, t.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, reason) _ = d.Forge.CloseIssue(ctx, t.Owner, t.Repo, t.IssueNumber, "**Understood — closing without implementation.** ("+reason+")") + d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues()) d.emit(events.Event{ Kind: "human_rejected", TaskID: t.ID, Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason, @@ -266,6 +356,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { } wf := workflow.Route(task, d.Workflows) 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()) workflow.Run(ctx, wf, &workflow.TaskContext{ Task: task, Repo: repo, @@ -287,11 +378,3 @@ func (d *Daemon) repoFor(t *store.Task) (config.Repo, bool) { } return config.Repo{}, false } - -func labelNames(is *github.Issue) string { - var names []string - for _, l := range is.Labels { - names = append(names, l.GetName()) - } - return strings.Join(names, ",") -} diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go new file mode 100644 index 000000000..7f79c7062 --- /dev/null +++ b/internal/daemon/daemon_test.go @@ -0,0 +1,17 @@ +package daemon + +import "testing" + +func TestHasLabelUsesExactNames(t *testing.T) { + labels := []string{"bug", "archie:parked-old", "feature", "custom,label"} + if hasLabel(labels, "archie:parked") { + t.Fatal("hasLabel matched a label-name substring") + } + if !hasLabel(labels, "custom,label") { + t.Fatal("hasLabel did not preserve a label containing a comma") + } + labels = append(labels, "archie:parked") + if !hasLabel(labels, "archie:parked") { + t.Fatal("hasLabel did not match the exact label name") + } +} diff --git a/internal/forge/forge.go b/internal/forge/forge.go new file mode 100644 index 000000000..dcc5be360 --- /dev/null +++ b/internal/forge/forge.go @@ -0,0 +1,56 @@ +// Package forge defines the interface archie uses to interact with a git +// host — polling issues, managing labels, opening PRs, and reacting to +// comments. GitHub is the primary implementation; other hosts (Gitea, +// GitLab) can be added later by implementing this interface. +package forge + +import "context" + +// Issue is a forge-neutral representation of an issue (not a PR). +type Issue struct { + Number int + Title string + Body string + Labels []string +} + +// Forge is the interface for interacting with a git host. +type Forge interface { + // AcceptInvitations auto-accepts pending repository invitations. + AcceptInvitations(ctx context.Context) error + + // AssignedIssues returns open issues assigned to the given user, + // excluding PRs. + AssignedIssues(ctx context.Context, owner, repo, assignee string) ([]Issue, error) + + // IssuesWithLabel returns open issues matching the given label, + // excluding PRs. Used when Dispatch.Trigger is "label" or "either". + IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]Issue, error) + + // Comment posts an issue (or PR) comment and returns its id. + Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) + + // RepliesAfter returns comments on the issue with id > afterID that + // were not written by exclude. + RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) + + // CreatePR opens a pull request and returns its number. + CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) + + // PRState returns "open", "merged", or "closed" for a PR. + PRState(ctx context.Context, owner, repo string, number int) (string, error) + + // CloseIssue closes an issue with an optional final comment. + CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error + + // React adds an emoji reaction to an issue. + React(ctx context.Context, owner, repo string, number int, reaction string) error + + // SetStateLabel makes label the issue's only state label, removing any + // other label that appears in knownLabels first. An empty label clears + // all state labels (terminal states). + SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) + + // VerifyPush confirms the token can push to the repo. + VerifyPush(ctx context.Context, owner, repo string) error +} diff --git a/internal/forge/github.go b/internal/forge/github.go index a91a944f4..8edaebb5d 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -8,22 +8,38 @@ import ( "context" "fmt" "log/slog" + "strings" + "sync" "github.com/google/go-github/v78/github" ) -type Client struct { +// GitHubClient implements Forge against the GitHub API. +type GitHubClient struct { gh *github.Client log *slog.Logger + + labelMu sync.Mutex + labelsEnsured map[string]bool } -func New(token string, log *slog.Logger) *Client { - return &Client{gh: github.NewClient(nil).WithAuthToken(token), log: log} +// New creates a GitHub-backed Forge implementation. Non-github.com hosts +// are configured using GitHub Enterprise's API and upload URL conventions. +func New(token, host string, log *slog.Logger) (Forge, error) { + client := github.NewClient(nil) + if strings.TrimRight(host, "/") != "https://github.com" { + var err error + client, err = client.WithEnterpriseURLs(host, host) + if err != nil { + return nil, fmt.Errorf("configure GitHub host %q: %w", host, err) + } + } + return &GitHubClient{gh: client.WithAuthToken(token), log: log}, nil } // AcceptInvitations auto-accepts pending repository invitations so // adding archie as a collaborator is all a human has to do. -func (c *Client) AcceptInvitations(ctx context.Context) error { +func (c *GitHubClient) AcceptInvitations(ctx context.Context) error { invites, _, err := c.gh.Users.ListInvitations(ctx, nil) if err != nil { return fmt.Errorf("list invitations: %w", err) @@ -41,8 +57,8 @@ func (c *Client) AcceptInvitations(ctx context.Context) error { // AssignedIssues returns open issues assigned to the given user, // excluding PRs. Assigning an issue to the bot is how work is handed to // archie (tink-bot style); labels only influence workflow routing. -func (c *Client) AssignedIssues(ctx context.Context, owner, repo, assignee string) ([]*github.Issue, error) { - var out []*github.Issue +func (c *GitHubClient) AssignedIssues(ctx context.Context, owner, repo, assignee string) ([]Issue, error) { + var out []Issue opts := &github.IssueListByRepoOptions{ State: "open", Assignee: assignee, @@ -55,7 +71,55 @@ func (c *Client) AssignedIssues(ctx context.Context, owner, repo, assignee strin } for _, is := range issues { if !is.IsPullRequest() { - out = append(out, is) + out = append(out, Issue{ + Number: is.GetNumber(), + Title: is.GetTitle(), + Body: is.GetBody(), + Labels: labelNames(is), + }) + } + } + if resp.NextPage == 0 { + break + } + opts.ListOptions.Page = resp.NextPage + } + return out, nil +} + +// labelNames extracts label names without flattening them, preserving +// valid label names that contain commas or leading/trailing whitespace. +func labelNames(is *github.Issue) []string { + var names []string + for _, l := range is.Labels { + names = append(names, l.GetName()) + } + return names +} + +// IssuesWithLabel returns open issues matching the given label, excluding +// PRs. Used when Dispatch.Trigger is "label" or "either" — no assignee +// required, just the label. +func (c *GitHubClient) IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]Issue, error) { + var out []Issue + opts := &github.IssueListByRepoOptions{ + State: "open", + Labels: []string{label}, + ListOptions: github.ListOptions{PerPage: 50}, + } + for { + issues, resp, err := c.gh.Issues.ListByRepo(ctx, owner, repo, opts) + if err != nil { + return nil, fmt.Errorf("list issues %s/%s: %w", owner, repo, err) + } + for _, is := range issues { + if !is.IsPullRequest() { + out = append(out, Issue{ + Number: is.GetNumber(), + Title: is.GetTitle(), + Body: is.GetBody(), + Labels: labelNames(is), + }) } } if resp.NextPage == 0 { @@ -68,7 +132,7 @@ func (c *Client) AssignedIssues(ctx context.Context, owner, repo, assignee strin // Comment posts an issue (or PR) comment and returns its id, so a // workflow can watch for replies that come after it. -func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { +func (c *GitHubClient) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { cm, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &github.IssueComment{Body: github.Ptr(body)}) if err != nil { @@ -86,7 +150,7 @@ type Reply struct { // RepliesAfter returns comments on the issue with id > afterID that were // not written by exclude (the bot) — the human side of waiting_human. -func (c *Client) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) { +func (c *GitHubClient) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) { comments, _, err := c.gh.Issues.ListComments(ctx, owner, repo, number, &github.IssueListCommentsOptions{ListOptions: github.ListOptions{PerPage: 50}}) if err != nil { @@ -103,7 +167,7 @@ func (c *Client) RepliesAfter(ctx context.Context, owner, repo string, number in } // CreatePR opens a pull request and returns its number. -func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) { +func (c *GitHubClient) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) { pr, _, err := c.gh.PullRequests.Create(ctx, owner, repo, &github.NewPullRequest{ Title: github.Ptr(title), Head: github.Ptr(head), @@ -117,7 +181,7 @@ func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, b } // PRState returns "open", "merged", or "closed" for a PR. -func (c *Client) PRState(ctx context.Context, owner, repo string, number int) (string, error) { +func (c *GitHubClient) PRState(ctx context.Context, owner, repo string, number int) (string, error) { pr, _, err := c.gh.PullRequests.Get(ctx, owner, repo, number) if err != nil { return "", err @@ -129,7 +193,7 @@ func (c *Client) PRState(ctx context.Context, owner, repo string, number int) (s } // CloseIssue closes an issue with a final comment (feasibility "won't do"). -func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { +func (c *GitHubClient) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { if comment != "" { if _, err := c.Comment(ctx, owner, repo, number, comment); err != nil { return err @@ -140,9 +204,99 @@ func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, return err } +// State labels mirror the task lifecycle onto the forge so archie's +// status is visible at a glance. SQLite remains the source of truth; +// labels are the human-facing projection — and removing the parked +// label is the forge-native retry trigger. +// Label strings are configured via [dispatch.labels]; these are the +// legacy defaults used as a fallback when config is absent. + +// stateLabelColors maps label name → colour for on-demand creation. +var stateLabelColors = map[string]string{ + "archie:queued": "bfd4f2", // grey-blue + "archie:working": "1d76db", // blue + "archie:waiting": "fbca04", // yellow + "archie:pr": "0e8a16", // green + "archie:parked": "d93f0b", // orange-red +} + +// defaultLabelColor is used for custom labels not in stateLabelColors. +const defaultLabelColor = "bfd4f2" + +// React adds an emoji reaction to an issue — the instant "received" +// acknowledgement on pickup. +func (c *GitHubClient) React(ctx context.Context, owner, repo string, number int, reaction string) error { + _, _, err := c.gh.Reactions.CreateIssueReaction(ctx, owner, repo, number, reaction) + return err +} + +// ensureLabel creates the state label in the repo if it doesn't exist. +func (c *GitHubClient) ensureLabel(ctx context.Context, owner, repo, name string) { + key := owner + "/" + repo + "/" + name + c.labelMu.Lock() + seen := c.labelsEnsured[key] + c.labelMu.Unlock() + if seen { + return + } + color := stateLabelColors[name] + if color == "" { + color = defaultLabelColor + } + _, _, err := c.gh.Issues.CreateLabel(ctx, owner, repo, &github.Label{ + Name: github.Ptr(name), + Color: github.Ptr(color), + Description: github.Ptr("archie task state (managed automatically)"), + }) + // 422 = already exists; both outcomes mean the label is available. + if err != nil && !strings.Contains(err.Error(), "already_exists") { + c.log.Warn("create label failed", "label", name, "err", err) + return + } + c.labelMu.Lock() + if c.labelsEnsured == nil { + c.labelsEnsured = map[string]bool{} + } + c.labelsEnsured[key] = true + c.labelMu.Unlock() +} + +// SetStateLabel makes label the issue's only state label, removing any +// other label found in knownLabels first. An empty label clears all +// state labels (terminal states). +func (c *GitHubClient) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) { + known := make(map[string]bool, len(knownLabels)) + for _, l := range knownLabels { + known[l] = true + } + issue, _, err := c.gh.Issues.Get(ctx, owner, repo, number) + if err != nil { + c.log.Warn("set state label: get issue failed", "issue", number, "err", err) + return + } + for _, l := range issue.Labels { + name := l.GetName() + if name != label && known[name] { + if _, err := c.gh.Issues.RemoveLabelForIssue(ctx, owner, repo, number, name); err != nil { + c.log.Warn("remove state label failed", "label", name, "err", err) + } + } + if name == label { + label = "" // already present; nothing to add + } + } + if label == "" { + return + } + c.ensureLabel(ctx, owner, repo, label) + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{label}); err != nil { + c.log.Warn("add state label failed", "label", label, "err", err) + } +} + // VerifyPush confirms the token can push to the repo (permission check // at startup so misconfiguration surfaces before any work is claimed). -func (c *Client) VerifyPush(ctx context.Context, owner, repo string) error { +func (c *GitHubClient) VerifyPush(ctx context.Context, owner, repo string) error { r, _, err := c.gh.Repositories.Get(ctx, owner, repo) if err != nil { return fmt.Errorf("get repo %s/%s: %w", owner, repo, err) diff --git a/internal/forge/github_test.go b/internal/forge/github_test.go new file mode 100644 index 000000000..17ac3b3e3 --- /dev/null +++ b/internal/forge/github_test.go @@ -0,0 +1,45 @@ +package forge + +import ( + "io" + "log/slog" + "testing" +) + +func TestNewConfiguresHost(t *testing.T) { + tests := []struct { + name string + host string + wantBase string + wantUpload string + }{ + { + name: "github.com", + host: "https://github.com", + wantBase: "https://api.github.com/", + wantUpload: "https://uploads.github.com/", + }, + { + name: "enterprise", + host: "https://git.example.com", + wantBase: "https://git.example.com/api/v3/", + wantUpload: "https://git.example.com/api/uploads/", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := New("token", tt.host, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatal(err) + } + client := f.(*GitHubClient) + if got := client.gh.BaseURL.String(); got != tt.wantBase { + t.Errorf("BaseURL = %q, want %q", got, tt.wantBase) + } + if got := client.gh.UploadURL.String(); got != tt.wantUpload { + t.Errorf("UploadURL = %q, want %q", got, tt.wantUpload) + } + }) + } +} diff --git a/internal/store/store.go b/internal/store/store.go index 95726882f..82761c20c 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -178,6 +178,20 @@ func (s *Store) Update(ctx context.Context, t *Task) error { return err } +// TaskByIssue returns the task tracking an issue, or nil. +func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*Task, error) { + row := s.db.QueryRowContext(ctx, ` + SELECT id, owner, repo, issue_number, title, body, labels, status, + workflow, stage, branch, plan, notes, pr_number, tokens_used, + iterations, attempt, park_reason + FROM tasks WHERE owner=? AND repo=? AND issue_number=?`, owner, repo, number) + t, err := scanTask(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return t, err +} + // WaitingTasks returns tasks blocked on human input. func (s *Store) WaitingTasks(ctx context.Context) ([]Task, error) { rows, err := s.db.QueryContext(ctx, ` diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index dc4929043..df396d896 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -93,17 +93,23 @@ func (a AgentStage) Stage() Stage { protect = nil // nothing to protect from read-only tools } + var preflight []agentloop.GateCommand + for _, argv := range tc.Repo.ResolvedPreflight() { + if len(argv) == 0 { + continue + } + preflight = append(preflight, agentloop.GateCommand{Name: argv[0], Argv: argv}) + } + res, err := agentloop.Run(ctx, agentloop.Config{ - Runtime: tc.Runtime, - ModelRef: modelRef, - WorkDir: tc.Dir, - Mission: a.Mission(tc), - ExtraRules: a.ExtraRules, - Notes: taskNotes{tc: tc}, - Gate: gate, - Preflight: []agentloop.GateCommand{ - {Name: "go-version", Argv: []string{"go", "version"}}, - }, + Runtime: tc.Runtime, + ModelRef: modelRef, + WorkDir: tc.Dir, + Mission: a.Mission(tc), + ExtraRules: a.ExtraRules, + Notes: taskNotes{tc: tc}, + Gate: gate, + Preflight: preflight, Budget: budget, ReadOnly: a.ReadOnly, ProtectPaths: protect, diff --git a/internal/workflow/feasibility.go b/internal/workflow/feasibility.go index 067a2ada1..d7408be26 100644 --- a/internal/workflow/feasibility.go +++ b/internal/workflow/feasibility.go @@ -149,7 +149,7 @@ func notify(ctx context.Context, tc *TaskContext, kind string) { payload, _ := json.Marshal(map[string]any{ "type": kind, "repo": tc.Repo.FullName(), "issue": tc.Task.IssueNumber, "title": tc.Task.Title, "prd": tc.Task.Plan, - "issue_url": fmt.Sprintf("https://github.com/%s/issues/%d", tc.Repo.FullName(), tc.Task.IssueNumber), + "issue_url": fmt.Sprintf("%s/%s/issues/%d", tc.Cfg.Forge.Host, tc.Repo.FullName(), tc.Task.IssueNumber), }) reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() diff --git a/internal/workflow/tdd.go b/internal/workflow/tdd.go index fff6f6f3a..2cd90b2d9 100644 --- a/internal/workflow/tdd.go +++ b/internal/workflow/tdd.go @@ -4,9 +4,12 @@ import ( "context" "fmt" "os/exec" + "path/filepath" "strings" "github.com/samcharles93/ai-sdk/agentloop" + + "github.com/samcharles93/archie-core/internal/config" ) // TDD is the bugfix workflow: prove the bug with failing tests before @@ -46,26 +49,22 @@ func TDD() Workflow { AgentStage{ Name: "repro-tests", Role: "builder", - // The inverted gate: code must still vet, but the test - // suite MUST fail — proof the repro captures the bug. + // The inverted gate: code-quality commands must still + // pass, but the test command (last in repo.Gate) MUST + // fail — proof the repro captures the bug. Gate: func(tc *TaskContext) agentloop.GateConfig { - return agentloop.GateConfig{ - Commands: []agentloop.GateCommand{ - {Name: "vet", Argv: []string{"go", "vet", "./..."}}, - {Name: "repro-must-fail", Argv: []string{"go", "test", "./...", "-count=1"}, ExpectFailure: true}, - }, - MaxConsecutiveFailures: tc.Cfg.Budgets.GateMaxFailures, - } + return tddReproGate(tc.Repo, tc.Cfg.Budgets) }, Mission: func(tc *TaskContext) string { + cmd := testCommand(tc.Repo) return fmt.Sprintf( "Write tests that REPRODUCE this bug in the repository %s. Do NOT fix the bug yet.\n\n"+ "\n# %s\n\n%s\n\n\n\n%s\n\n\n"+ "Add tests that pass once the bug is fixed but FAIL today because of it. The gate is "+ - "inverted for this stage: it requires 'go vet' to pass and 'go test ./...' to FAIL. "+ - "Do not touch non-test files. Call finish with status \"passed\" once the failing "+ + "inverted for this stage: it requires the full gate to pass EXCEPT %s which is required "+ + "to FAIL. Do not touch non-test files. Call finish with status \"passed\" once the failing "+ "repro is in place, summarising which tests capture the bug.", - tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Plan, + tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Plan, cmd, ) }, }.Stage(), @@ -73,7 +72,11 @@ func TDD() Workflow { // Capture the failing test run — the proof the repro // reproduces the bug, posted on the PR later. {Name: "capture-proof", Run: func(ctx context.Context, tc *TaskContext) error { - cmd := exec.CommandContext(ctx, "go", "test", "./...", "-count=1") + argv := testCommandArgv(tc.Repo) + if len(argv) == 0 { + return fmt.Errorf("tdd: repo %s has no gate configured — cannot capture repro proof (add at least one [[repos.gate]] command, with the test runner last)", tc.Repo.FullName()) + } + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) cmd.Dir = tc.Dir out, err := cmd.CombinedOutput() if err == nil { @@ -95,8 +98,12 @@ func TDD() Workflow { }, // Environmental, not advisory: the fix stage cannot touch // test files at all — the committed repro is the spec. - ProtectPaths: func(*TaskContext) func(string) bool { - return func(path string) bool { return strings.HasSuffix(path, "_test.go") } + ProtectPaths: func(tc *TaskContext) func(string) bool { + glob := tc.Repo.ResolvedTestGlob() + if glob == "" { + return nil + } + return func(path string) bool { return matchesTestPath(glob, path) } }, ExtraRules: "The repro tests written in the previous stage are the bug's specification. " + "Test files are write-protected in this stage — make them pass by fixing the code they exercise.", @@ -140,3 +147,60 @@ func TDD() Workflow { }, } } + +// tddReproGate builds the inverted gate for the repro-tests stage: +// every command from repo.Gate runs normally except the last one (the +// test runner, by convention), which gets ExpectFailure — the repro +// must fail the tests to prove the bug exists. +func tddReproGate(repo config.Repo, budgets config.Budgets) agentloop.GateConfig { + if len(repo.Gate) == 0 { + return agentloop.GateConfig{} + } + cmds := make([]agentloop.GateCommand, 0, len(repo.Gate)) + for _, argv := range repo.Gate { + if len(argv) == 0 { + continue + } + gc := agentloop.GateCommand{Name: argv[0], Argv: argv} + cmds = append(cmds, gc) + } + if len(cmds) > 0 { + cmds[len(cmds)-1].ExpectFailure = true + } + return agentloop.GateConfig{ + Commands: cmds, + MaxConsecutiveFailures: budgets.GateMaxFailures, + } +} + +// testCommand returns a human-readable representation of the test +// command (the last entry in repo.Gate). +func testCommand(repo config.Repo) string { + last := testCommandArgv(repo) + if len(last) == 0 { + return "(no gate configured)" + } + return strings.Join(last, " ") +} + +// testCommandArgv returns the test command argv (the last entry in +// repo.Gate), or nil when no gate is configured. +func testCommandArgv(repo config.Repo) []string { + for i := len(repo.Gate) - 1; i >= 0; i-- { + if len(repo.Gate[i]) > 0 { + return repo.Gate[i] + } + } + return nil +} + +// matchesTestPath applies basename-only patterns (such as *_test.go) to +// files in any directory. Patterns containing a path separator continue +// to match against the full repository-relative path. +func matchesTestPath(glob, path string) bool { + if !strings.ContainsAny(glob, `/\`) { + path = filepath.Base(path) + } + ok, err := filepath.Match(glob, path) + return err == nil && ok +} diff --git a/internal/workflow/tdd_test.go b/internal/workflow/tdd_test.go new file mode 100644 index 000000000..a14799156 --- /dev/null +++ b/internal/workflow/tdd_test.go @@ -0,0 +1,71 @@ +package workflow + +import ( + "reflect" + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +func TestMatchesTestPath(t *testing.T) { + tests := []struct { + name string + glob string + path string + want bool + }{ + {name: "root Go test", glob: "*_test.go", path: "main_test.go", want: true}, + {name: "nested Go test", glob: "*_test.go", path: "internal/foo/bar_test.go", want: true}, + {name: "nested Python test", glob: "test_*.py", path: "pkg/unit/test_widget.py", want: true}, + {name: "directory pattern", glob: "tests/*.rs", path: "tests/widget.rs", want: true}, + {name: "non-test file", glob: "*_test.go", path: "internal/foo/bar.go", want: false}, + {name: "wrong directory", glob: "tests/*.rs", path: "src/widget.rs", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := matchesTestPath(tt.glob, tt.path); got != tt.want { + t.Errorf("matchesTestPath(%q, %q) = %v, want %v", tt.glob, tt.path, got, tt.want) + } + }) + } +} + +func TestTDDGateUsesLastNonEmptyCommand(t *testing.T) { + repo := config.Repo{Gate: [][]string{ + {"go", "vet", "./..."}, + {"go", "test", "./..."}, + {}, + }} + + gate := tddReproGate(repo, config.Budgets{GateMaxFailures: 3}) + if len(gate.Commands) != 2 { + t.Fatalf("gate has %d commands, want 2", len(gate.Commands)) + } + if gate.Commands[0].ExpectFailure { + t.Error("first gate command unexpectedly requires failure") + } + if !gate.Commands[1].ExpectFailure { + t.Error("last non-empty gate command does not require failure") + } + if got, want := testCommandArgv(repo), []string{"go", "test", "./..."}; !reflect.DeepEqual(got, want) { + t.Errorf("testCommandArgv() = %v, want %v", got, want) + } + if got, want := testCommand(repo), "go test ./..."; got != want { + t.Errorf("testCommand() = %q, want %q", got, want) + } +} + +func TestTDDGateWithOnlyEmptyCommands(t *testing.T) { + repo := config.Repo{Gate: [][]string{{}, nil}} + + if got := tddReproGate(repo, config.Budgets{}).Commands; len(got) != 0 { + t.Errorf("gate commands = %v, want none", got) + } + if got := testCommandArgv(repo); got != nil { + t.Errorf("testCommandArgv() = %v, want nil", got) + } + if got := testCommand(repo); got != "(no gate configured)" { + t.Errorf("testCommand() = %q, want no-gate message", got) + } +} diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index afc96bf88..00de9a89c 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -28,7 +28,7 @@ type TaskContext struct { Task *store.Task Repo config.Repo Cfg config.Config - Forge *forge.Client + Forge forge.Forge Store *store.Store Trees *worktree.Manager Runtime *runtime.Runtime @@ -110,6 +110,12 @@ func Route(t *store.Task, reg Registry) Workflow { if wf, ok := reg["feasibility"]; ok { return wf } + case "bootstrap": + // Diagnostics: exercise the full pipeline deterministically + // (no LLM spend) — invites, clone, push, PR, labels. + if wf, ok := reg["bootstrap"]; ok { + return wf + } } } if wf, ok := reg["implement"]; ok { @@ -172,15 +178,33 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) { } _ = tc.Store.Update(ctx, t) _ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, tc.Outcome.Status, tc.Outcome.Detail) + tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, stateLabelFor(tc.Cfg.Dispatch, tc.Outcome.Status), tc.Cfg.Dispatch.LabelValues()) tc.Emit(events.KindOutcome, t.Stage, tc.Outcome.Detail, map[string]any{"status": tc.Outcome.Status}) log.Info("workflow finished", "status", tc.Outcome.Status) } +// stateLabelFor maps a terminal workflow status to its forge label by +// looking up the configured [dispatch.labels]; empty clears (done states +// — the issue closes or the PR speaks). +func stateLabelFor(d config.Dispatch, status string) string { + switch status { + case store.StatusPROpen: + return d.StateLabel("pr") + case store.StatusWaitingHuman: + return d.StateLabel("waiting") + case store.StatusParked: + return d.StateLabel("parked") + default: + return "" + } +} + func park(ctx context.Context, tc *TaskContext, reason string) { t := tc.Task t.ParkReason = reason _ = tc.Store.Update(ctx, t) _ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, store.StatusParked, reason) + tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, tc.Cfg.Dispatch.StateLabel("parked"), tc.Cfg.Dispatch.LabelValues()) tc.Emit(events.KindParked, t.Stage, reason, nil) body := fmt.Sprintf("**archie parked this task.**\n\n```\n%s\n```\n\nThe worktree is kept for inspection.", clip(reason, 3000)) diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index da76931dd..57147731c 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -21,8 +21,8 @@ type Manager struct { Token string BotUser string BotEmail string - // BaseURL overrides the forge host (tests use a local file:// remote). - // Empty means https://github.com. + // BaseURL overrides the forge host. Set from config [forge].host. + // Empty falls back to https://github.com. BaseURL string }