diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d2c4335c3..588f0ef92 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -10,6 +10,7 @@ | `internal/config/` | TOML config, per-repo gates, budgets, providers, ecosystems | | `internal/daemon/` | Resident loop: poll, enqueue, claim, route, process, reconcile | | `internal/workflow/` | Engine: stage lists, routing, shared steps, workflow definitions | +| `internal/agentexec/` | Versioned agent-stage protocol and current in-process runner | | `internal/forge/` | GitHub interface: issues, labels, PRs, comments, reactions | | `internal/worktree/` | Git operations: clone, branch, commit, push, diff, cleanup | | `internal/store/` | SQLite: task rows, status transitions, crash recovery | @@ -39,7 +40,7 @@ queued → running(workflow:stage) → pr_open → merged | rejected - `Workflow` = named list of `Stage`s - `Stage` = `Name` + `Run(ctx, *TaskContext) error` -- `TaskContext` = mutable bag: Task, Repo, Config, Forge, Store, Runtime, worktree dir/branch, scratch fields +- `TaskContext` = mutable bag: Task, Repo, Config, Forge, Store, Agent runner, worktree dir/branch, scratch fields - `Outcome` = terminal decision (status + detail) — ends the workflow immediately - `Registry` = `map[string]Workflow` @@ -167,6 +168,7 @@ Every lifecycle event flows through an internal event bus: 5. **Shared code with tau at the module level.** `ai-sdk/agentloop` and `ai-sdk/toolkit` are extracted from tau's coordinator and promoted to shared libraries. 6. **No daemon-internal cron.** Polling is a ticker loop, not cron. The feasibility PRD notification uses an external webhook (n8n). 7. **Fresh worktree per task.** No persistent state between runs. Crash recovery just re-queues. +8. **Agent execution is a data boundary.** Autonomous stages receive a versioned request and return a fenced result; SQLite, forge operations, git, workflow sequencing, and outcome handling stay daemon-owned. ## What's Implemented vs Planned diff --git a/cmd/archied/main.go b/cmd/archied/main.go index b797e246b..d490f5b18 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -16,6 +16,7 @@ import ( "github.com/samcharles93/ai-sdk/runtime" + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/events" @@ -102,6 +103,11 @@ func run() int { }() } + llm := llmRuntime(cfg) + var agentRunner agentexec.Runner + if llm != nil { + agentRunner = agentexec.NewInProcessRunner(llm, log) + } d := &daemon.Daemon{ Cfg: cfg, Store: st, @@ -114,7 +120,8 @@ func run() int { BotEmail: cfg.BotEmail, BaseURL: cfg.Forge.Host, }, - Runtime: llmRuntime(cfg), + Runtime: llm, + Agent: agentRunner, Workflows: workflow.Registry{ "bootstrap": workflow.Bootstrap(), "implement": workflow.Implement(), diff --git a/internal/agentexec/inprocess.go b/internal/agentexec/inprocess.go new file mode 100644 index 000000000..e0bf77038 --- /dev/null +++ b/internal/agentexec/inprocess.go @@ -0,0 +1,183 @@ +package agentexec + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "path/filepath" + "strings" + + "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/core" + "github.com/samcharles93/ai-sdk/runtime" +) + +// Runner executes one autonomous stage against an already prepared workspace. +type Runner interface { + Run(ctx context.Context, workspace string, req Request) (Result, error) +} + +type loopFunc func(context.Context, agentloop.Config) (agentloop.Result, error) + +// InProcessRunner preserves the current execution behavior behind the v1 +// agent protocol. It is replaced by a subprocess or container runner without +// changing workflow orchestration. +type InProcessRunner struct { + runtime *runtime.Runtime + log *slog.Logger + run loopFunc +} + +func NewInProcessRunner(rt *runtime.Runtime, log *slog.Logger) *InProcessRunner { + return &InProcessRunner{runtime: rt, log: log, run: agentloop.Run} +} + +func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) { + if err := req.Validate(); err != nil { + return Result{}, err + } + if r.runtime == nil { + return Result{}, fmt.Errorf("agent runtime is not configured") + } + if r.run == nil { + return Result{}, fmt.Errorf("agent loop is not configured") + } + + notes := &memoryNotes{initial: req.Notes} + captures := make(map[string][]json.RawMessage) + res, err := r.run(ctx, agentloop.Config{ + Runtime: r.runtime, + ModelRef: req.Model, + WorkDir: workspace, + Mission: req.Mission, + ExtraRules: req.ExtraRules, + Notes: notes, + Gate: toAgentGate(req.Gate), + Preflight: toAgentCommands(req.Preflight), + Budget: agentloop.Budget(req.Budget), + ReadOnly: req.ReadOnly, + ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly), + Extra: captureToolSet(req.CaptureTools, captures), + Logger: r.logger(req), + }) + result := Result{ + Version: ProtocolVersion, + TaskID: req.TaskID, + Attempt: req.Attempt, + Stage: req.Stage, + Status: string(res.Status), + StopReason: res.StopReason, + Changes: res.Changes, + Iterations: res.Iterations, + TokensUsed: res.TokensUsed, + Summary: res.Summary, + Detail: res.Detail, + AppendedNotes: notes.appended, + Captures: captures, + } + if cause := context.Cause(ctx); cause != nil { + return result, cause + } + return result, err +} + +func (r *InProcessRunner) logger(req Request) *slog.Logger { + if r.log == nil { + return slog.New(slog.DiscardHandler) + } + return r.log.With("task", req.TaskID, "attempt", req.Attempt, "stage", req.Stage, "model", req.Model) +} + +func toAgentGate(g Gate) agentloop.GateConfig { + return agentloop.GateConfig{ + Commands: toAgentCommands(g.Commands), + MaxConsecutiveFailures: g.MaxConsecutiveFailures, + } +} + +func toAgentCommands(commands []Command) []agentloop.GateCommand { + out := make([]agentloop.GateCommand, 0, len(commands)) + for _, command := range commands { + out = append(out, agentloop.GateCommand{ + Name: command.Name, Argv: command.Argv, ExpectFailure: command.ExpectFailure, + }) + } + return out +} + +func protectionMatcher(p Protection, readOnly bool) func(string) bool { + if readOnly || len(p.Suffixes)+len(p.Globs) == 0 { + return nil + } + return func(path string) bool { + for _, suffix := range p.Suffixes { + if strings.HasSuffix(path, suffix) { + return true + } + } + for _, glob := range p.Globs { + matchPath := path + if !strings.ContainsAny(glob, `/\`) { + matchPath = filepath.Base(path) + } + if matched, err := filepath.Match(glob, matchPath); err == nil && matched { + return true + } + } + return false + } +} + +func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage) core.ToolSet { + tools := make(core.ToolSet, len(specs)) + for _, spec := range specs { + spec := spec + tools[spec.Name] = core.NewTool(spec.Name, spec.Description, spec.Parameters, + func(_ context.Context, input string) (string, error) { + if spec.MaxCalls > 0 && len(captures[spec.Name]) >= spec.MaxCalls { + return fmt.Sprintf("%s rejected: maximum call count is %d", spec.Name, spec.MaxCalls), nil + } + value := json.RawMessage(input) + if !json.Valid(value) { + return spec.Name + " rejected: arguments are not valid JSON", nil + } + var object map[string]json.RawMessage + if err := json.Unmarshal(value, &object); err != nil { + return spec.Name + " rejected: arguments must be a JSON object", nil + } + for _, field := range spec.RequiredFields { + if _, ok := object[field]; !ok { + return fmt.Sprintf("%s rejected: %s is required", spec.Name, field), nil + } + } + for _, field := range spec.NonEmptyStrings { + var text string + if raw, ok := object[field]; !ok || json.Unmarshal(raw, &text) != nil || strings.TrimSpace(text) == "" { + return fmt.Sprintf("%s rejected: %s must be a non-empty string", spec.Name, field), nil + } + } + for _, field := range spec.BooleanFields { + var value bool + if raw, ok := object[field]; !ok || json.Unmarshal(raw, &value) != nil { + return fmt.Sprintf("%s rejected: %s must be a boolean", spec.Name, field), nil + } + } + captures[spec.Name] = append(captures[spec.Name], append(json.RawMessage(nil), value...)) + return spec.Name + " recorded", nil + }) + } + return tools +} + +type memoryNotes struct { + initial string + appended []string +} + +func (n *memoryNotes) Load(context.Context) (string, error) { return n.initial, nil } + +func (n *memoryNotes) Append(_ context.Context, entry string) error { + n.appended = append(n.appended, entry) + return nil +} diff --git a/internal/agentexec/inprocess_test.go b/internal/agentexec/inprocess_test.go new file mode 100644 index 000000000..43c254b7b --- /dev/null +++ b/internal/agentexec/inprocess_test.go @@ -0,0 +1,112 @@ +package agentexec + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/runtime" +) + +func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) { + runner := &InProcessRunner{ + runtime: runtime.NewRuntime(runtime.Config{}), + run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) { + if cfg.WorkDir != "/workspace" || cfg.ModelRef != "provider/model" || cfg.Mission != "mission" { + t.Fatalf("unexpected config: workdir=%q model=%q mission=%q", cfg.WorkDir, cfg.ModelRef, cfg.Mission) + } + if cfg.ProtectPaths == nil || !cfg.ProtectPaths("nested/file_test.go") || !cfg.ProtectPaths("view_templ.go") { + t.Fatal("declarative path protection was not applied") + } + if err := cfg.Notes.Append(ctx, "verified note"); err != nil { + t.Fatal(err) + } + if _, err := cfg.Extra["decide"].Execute(ctx, `{"fit":true}`); err != nil { + t.Fatal(err) + } + return agentloop.Result{Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10}, nil + }, + } + req := Request{ + Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", Mission: "mission", + Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}}, + CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}}, + } + got, err := runner.Run(context.Background(), "/workspace", req) + if err != nil { + t.Fatal(err) + } + if got.Status != StatusPassed || got.Summary != "done" || got.TokensUsed != 10 { + t.Fatalf("unexpected result: %#v", got) + } + if len(got.AppendedNotes) != 1 || got.AppendedNotes[0] != "verified note" { + t.Fatalf("appended notes = %v", got.AppendedNotes) + } + if len(got.Captures["decide"]) != 1 || string(got.Captures["decide"][0]) != `{"fit":true}` { + t.Fatalf("captures = %v", got.Captures) + } +} + +func TestProtectionMatcherAppliesBasenameAndPathGlobs(t *testing.T) { + match := protectionMatcher(Protection{Globs: []string{"*_test.go", "tests/*.rs"}}, false) + tests := []struct { + path string + want bool + }{ + {path: "main_test.go", want: true}, + {path: "internal/foo/bar_test.go", want: true}, + {path: "tests/widget.rs", want: true}, + {path: "src/widget.rs", want: false}, + } + for _, tt := range tests { + if got := match(tt.path); got != tt.want { + t.Errorf("match(%q) = %v, want %v", tt.path, got, tt.want) + } + } +} + +func TestCaptureToolRejectsInvalidDataBeforeRecording(t *testing.T) { + captures := make(map[string][]json.RawMessage) + tool := captureToolSet([]CaptureTool{{ + Name: "decide", RequiredFields: []string{"fit", "reasons"}, NonEmptyStrings: []string{"reasons"}, + BooleanFields: []string{"fit"}, + }}, captures)["decide"] + output, err := tool.Execute(context.Background(), `{"fit":true,"reasons":""}`) + if err != nil { + t.Fatal(err) + } + if len(captures["decide"]) != 0 || output != "decide rejected: reasons must be a non-empty string" { + t.Fatalf("invalid capture output=%q captures=%v", output, captures) + } +} + +func TestCaptureToolRejectsWrongFieldTypeBeforeRecording(t *testing.T) { + captures := make(map[string][]json.RawMessage) + tool := captureToolSet([]CaptureTool{{Name: "decide", BooleanFields: []string{"fit"}}}, captures)["decide"] + output, err := tool.Execute(context.Background(), `{"fit":"true"}`) + if err != nil { + t.Fatal(err) + } + if len(captures["decide"]) != 0 || output != "decide rejected: fit must be a boolean" { + t.Fatalf("invalid capture output=%q captures=%v", output, captures) + } +} + +func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + runner := &InProcessRunner{ + runtime: runtime.NewRuntime(runtime.Config{}), + run: func(context.Context, agentloop.Config) (agentloop.Result, error) { + return agentloop.Result{Status: agentloop.StatusParked, StopReason: agentloop.StopTimedOut}, nil + }, + } + _, err := runner.Run(ctx, "/workspace", Request{ + Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build", Model: "provider/model", Mission: "mission", + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("Run error = %v, want context.Canceled", err) + } +} diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go new file mode 100644 index 000000000..21c37822d --- /dev/null +++ b/internal/agentexec/protocol.go @@ -0,0 +1,127 @@ +// Package agentexec defines the unprivileged agent execution boundary. +// Workflow orchestration and external side effects remain daemon-owned. +package agentexec + +import ( + "encoding/json" + "fmt" + "time" +) + +const ProtocolVersion = 1 + +const StatusPassed = "passed" + +// Command is one executable gate or preflight command. +type Command struct { + Name string `json:"name"` + Argv []string `json:"argv"` + ExpectFailure bool `json:"expect_failure,omitempty"` +} + +// Gate is the quality gate an agent must satisfy. +type Gate struct { + Commands []Command `json:"commands,omitempty"` + MaxConsecutiveFailures int `json:"max_consecutive_failures,omitempty"` +} + +// Budget bounds one autonomous execution. +type Budget struct { + MaxSteps int `json:"max_steps,omitempty"` + MaxTokens int `json:"max_tokens,omitempty"` + WallClock time.Duration `json:"wall_clock,omitempty"` +} + +// Protection describes paths the agent may read but not mutate. +type Protection struct { + Suffixes []string `json:"suffixes,omitempty"` + Globs []string `json:"globs,omitempty"` +} + +// CaptureTool declares a structured-output tool whose calls are returned +// to the daemon as data. It cannot call back into daemon state. +type CaptureTool struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Parameters json.RawMessage `json:"parameters,omitempty"` + RequiredFields []string `json:"required_fields,omitempty"` + NonEmptyStrings []string `json:"non_empty_strings,omitempty"` + BooleanFields []string `json:"boolean_fields,omitempty"` + MaxCalls int `json:"max_calls,omitempty"` +} + +// Request is the complete, serializable input for one agent stage. The +// workspace path is supplied separately by Runner so a container runner can +// map a host path to a fixed path without exposing host layout in the wire +// protocol. +type Request struct { + Version int `json:"version"` + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Stage string `json:"stage"` + Model string `json:"model"` + Mission string `json:"mission"` + ExtraRules string `json:"extra_rules,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + Budget Budget `json:"budget"` + Gate Gate `json:"gate"` + Preflight []Command `json:"preflight,omitempty"` + Protection Protection `json:"protection"` + Notes string `json:"notes,omitempty"` + CaptureTools []CaptureTool `json:"capture_tools,omitempty"` +} + +// Validate rejects requests that this runner cannot safely interpret. +func (r Request) Validate() error { + if r.Version != ProtocolVersion { + return fmt.Errorf("agent protocol version %d is unsupported (want %d)", r.Version, ProtocolVersion) + } + if r.TaskID <= 0 { + return fmt.Errorf("agent request task_id must be positive") + } + if r.Attempt <= 0 { + return fmt.Errorf("agent request attempt must be positive") + } + if r.Stage == "" { + return fmt.Errorf("agent request stage is required") + } + if r.Model == "" { + return fmt.Errorf("agent request model is required") + } + return nil +} + +// Result is the serializable outcome of one agent stage. +type Result struct { + Version int `json:"version"` + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Stage string `json:"stage"` + Status string `json:"status"` + StopReason string `json:"stop_reason,omitempty"` + Changes []string `json:"changes,omitempty"` + Iterations int `json:"iterations,omitempty"` + TokensUsed int `json:"tokens_used,omitempty"` + Summary string `json:"summary,omitempty"` + Detail string `json:"detail,omitempty"` + AppendedNotes []string `json:"appended_notes,omitempty"` + Captures map[string][]json.RawMessage `json:"captures,omitempty"` +} + +// ValidateFor rejects incompatible or misrouted results before the daemon +// applies them to task state. +func (r Result) ValidateFor(req Request) error { + if r.Version != ProtocolVersion { + return fmt.Errorf("agent result protocol version %d is unsupported (want %d)", r.Version, ProtocolVersion) + } + if r.TaskID != req.TaskID || r.Attempt != req.Attempt || r.Stage != req.Stage { + return fmt.Errorf( + "agent result identity %d/%d/%s does not match request %d/%d/%s", + r.TaskID, r.Attempt, r.Stage, req.TaskID, req.Attempt, req.Stage, + ) + } + if r.Status == "" { + return fmt.Errorf("agent result status is required") + } + return nil +} diff --git a/internal/agentexec/protocol_test.go b/internal/agentexec/protocol_test.go new file mode 100644 index 000000000..6ea347e2b --- /dev/null +++ b/internal/agentexec/protocol_test.go @@ -0,0 +1,46 @@ +package agentexec + +import ( + "encoding/json" + "reflect" + "testing" + "time" +) + +func TestProtocolRoundTrip(t *testing.T) { + want := Request{ + Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "fix", Model: "openai/gpt-5", + Mission: "fix it", Budget: Budget{MaxSteps: 12, MaxTokens: 4000, WallClock: 2 * time.Minute}, + Gate: Gate{Commands: []Command{{Name: "go", Argv: []string{"go", "test", "./..."}}}, MaxConsecutiveFailures: 2}, + Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}}, + CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}}, + } + b, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + var got Request + if err := json.Unmarshal(b, &got); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("round trip mismatch\ngot: %#v\nwant: %#v", got, want) + } +} + +func TestRequestRejectsUnknownProtocol(t *testing.T) { + req := Request{Version: ProtocolVersion + 1, TaskID: 1, Stage: "plan", Model: "provider/model"} + if err := req.Validate(); err == nil { + t.Fatal("Validate accepted an unsupported protocol version") + } +} + +func TestResultRejectsMismatchedIdentity(t *testing.T) { + req := Request{Version: ProtocolVersion, TaskID: 1, Attempt: 2, Stage: "build", Model: "provider/model"} + result := Result{ + Version: ProtocolVersion, TaskID: 1, Attempt: 3, Stage: "build", Status: StatusPassed, + } + if err := result.ValidateFor(req); err == nil { + t.Fatal("ValidateFor accepted a result from another attempt") + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 14124d335..9ec871f6b 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -14,6 +14,7 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -28,6 +29,7 @@ type Daemon struct { Forge forge.Forge Trees *worktree.Manager Runtime *runtime.Runtime + Agent agentexec.Runner Bus *events.Bus Workflows workflow.Registry Log *slog.Logger @@ -358,15 +360,15 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { 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, - Cfg: d.Cfg, - Forge: d.Forge, - Store: d.Store, - Trees: d.Trees, - Runtime: d.Runtime, - Bus: d.Bus, - Log: d.Log, + Task: task, + Repo: repo, + Cfg: d.Cfg, + Forge: d.Forge, + Store: d.Store, + Trees: d.Trees, + Agent: d.Agent, + Bus: d.Bus, + Log: d.Log, }) } diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index df396d896..109daa2f3 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -4,9 +4,7 @@ import ( "context" "fmt" - "github.com/samcharles93/ai-sdk/agentloop" - "github.com/samcharles93/ai-sdk/core" - + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" ) @@ -25,30 +23,30 @@ type AgentStage struct { Mission func(*TaskContext) string // Gate returns the stage's quality gate; nil means ungated (e.g. // read-only analysis stages). - Gate func(*TaskContext) agentloop.GateConfig + Gate func(*TaskContext) agentexec.Gate // ExtraRules is appended to the system prompt. ExtraRules string // MaxSteps overrides the configured step budget when > 0 (planner // stages are cheaper than builder stages). MaxSteps int - // ProtectPaths blocks write/edit on matching paths for this stage — + // ProtectGlobs blocks write/edit on matching paths for this stage — // an environmental constraint, not a prompt rule (TDD's fix stage // protects the committed repro tests; every builder stage protects - // the repo's generated files). The returned matcher is combined + // the repo's generated files). The returned globs are combined // with the repo's configured protected suffixes. - ProtectPaths func(*TaskContext) func(path string) bool - // Extra adds stage-specific tools to the agent's toolset (e.g. - // feasibility's decide tool). - Extra func(*TaskContext) core.ToolSet + ProtectGlobs func(*TaskContext) []string + // CaptureTools adds structured-output tools whose calls are returned + // as data rather than receiving callbacks into daemon state. + CaptureTools func(*TaskContext) []agentexec.CaptureTool // OnResult consumes a successful (passed) result. Parked and idle // results park the workflow before OnResult is called. - OnResult func(*TaskContext, agentloop.Result) error + OnResult func(*TaskContext, agentexec.Result) error } // Stage adapts the AgentStage to the engine. func (a AgentStage) Stage() Stage { return Stage{Name: a.Name, Run: func(ctx context.Context, tc *TaskContext) error { - if tc.Runtime == nil { + if tc.Agent == nil { return fmt.Errorf("no LLM runtime configured (missing [providers] in config?)") } modelRef := tc.Cfg.Models[a.Role] @@ -59,7 +57,7 @@ func (a AgentStage) Stage() Stage { return fmt.Errorf("no model configured for role %q (set [models] in config)", a.Role) } - budget := agentloop.Budget{ + budget := agentexec.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, MaxTokens: tc.Cfg.Budgets.MaxTokens, WallClock: tc.Cfg.Budgets.WallClock.Std(), @@ -68,54 +66,62 @@ func (a AgentStage) Stage() Stage { budget.MaxSteps = a.MaxSteps } - var gate agentloop.GateConfig + var gate agentexec.Gate if a.Gate != nil { gate = a.Gate(tc) } - var extra core.ToolSet - if a.Extra != nil { - extra = a.Extra(tc) + var captureTools []agentexec.CaptureTool + if a.CaptureTools != nil { + captureTools = a.CaptureTools(tc) } - // Repo-configured protected suffixes (generated files) apply to - // every writing stage; stage-specific matchers stack on top. - var stageProtect func(string) bool - if a.ProtectPaths != nil { - stageProtect = a.ProtectPaths(tc) - } - protect := func(path string) bool { - if tc.Repo.Protected(path) { - return true - } - return stageProtect != nil && stageProtect(path) + protection := agentexec.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)} + if a.ProtectGlobs != nil { + protection.Globs = a.ProtectGlobs(tc) } if a.ReadOnly { - protect = nil // nothing to protect from read-only tools + protection = agentexec.Protection{} } - var preflight []agentloop.GateCommand + var preflight []agentexec.Command for _, argv := range tc.Repo.ResolvedPreflight() { if len(argv) == 0 { continue } - preflight = append(preflight, agentloop.GateCommand{Name: argv[0], Argv: argv}) + preflight = append(preflight, agentexec.Command{Name: argv[0], Argv: argv}) } - res, err := agentloop.Run(ctx, agentloop.Config{ - Runtime: tc.Runtime, - ModelRef: modelRef, - WorkDir: tc.Dir, + req := agentexec.Request{ + Version: agentexec.ProtocolVersion, + TaskID: tc.Task.ID, + Attempt: tc.Task.Attempt, + Stage: a.Name, + Model: modelRef, Mission: a.Mission(tc), ExtraRules: a.ExtraRules, - Notes: taskNotes{tc: tc}, + ReadOnly: a.ReadOnly, + Budget: budget, Gate: gate, Preflight: preflight, - Budget: budget, - ReadOnly: a.ReadOnly, - ProtectPaths: protect, - Extra: extra, - Logger: tc.Log.With("stage", a.Name, "model", modelRef), - }) + Protection: protection, + Notes: tc.Task.Notes, + CaptureTools: captureTools, + } + res, err := tc.Agent.Run(ctx, tc.Dir, req) + if err != nil && res.Version == 0 { + return fmt.Errorf("agent run: %w", err) + } + if validateErr := res.ValidateFor(req); validateErr != nil { + return fmt.Errorf("validate agent result: %w", validateErr) + } + if len(res.AppendedNotes) > 0 { + for _, note := range res.AppendedNotes { + tc.Task.Notes += "- " + note + "\n" + } + if saveErr := tc.Store.Update(ctx, tc.Task); saveErr != nil { + return fmt.Errorf("persist agent notes: %w", saveErr) + } + } if err != nil { return fmt.Errorf("agent run: %w", err) } @@ -127,7 +133,7 @@ func (a AgentStage) Stage() Stage { "tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef, }) - if res.Status != agentloop.StatusPassed { + if res.Status != agentexec.StatusPassed { detail := res.Detail if detail == "" { detail = res.Summary @@ -141,28 +147,15 @@ func (a AgentStage) Stage() Stage { }} } -// taskNotes stores agent notes on the task row — orchestrator-side, so -// they survive worktree cleanup and never pollute the PR diff. -type taskNotes struct{ tc *TaskContext } - -func (n taskNotes) Load(context.Context) (string, error) { - return n.tc.Task.Notes, nil -} - -func (n taskNotes) Append(ctx context.Context, entry string) error { - n.tc.Task.Notes += "- " + entry + "\n" - return n.tc.Store.Update(ctx, n.tc.Task) -} - // GateFromRepo converts the repo's configured command lists into an -// agentloop gate. -func GateFromRepo(repo config.Repo, budgets config.Budgets) agentloop.GateConfig { - cmds := make([]agentloop.GateCommand, 0, len(repo.Gate)) +// agent execution gate. +func GateFromRepo(repo config.Repo, budgets config.Budgets) agentexec.Gate { + cmds := make([]agentexec.Command, 0, len(repo.Gate)) for _, argv := range repo.Gate { if len(argv) == 0 { continue } - cmds = append(cmds, agentloop.GateCommand{Name: argv[0], Argv: argv}) + cmds = append(cmds, agentexec.Command{Name: argv[0], Argv: argv}) } - return agentloop.GateConfig{Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures} + return agentexec.Gate{Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures} } diff --git a/internal/workflow/agent_test.go b/internal/workflow/agent_test.go new file mode 100644 index 000000000..f0fc2001c --- /dev/null +++ b/internal/workflow/agent_test.go @@ -0,0 +1,210 @@ +package workflow + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "path/filepath" + "reflect" + "testing" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/store" +) + +type fakeAgentRunner struct { + workspace string + request agentexec.Request + result agentexec.Result + err error +} + +type agentRunnerFunc func(context.Context, string, agentexec.Request) (agentexec.Result, error) + +func (f agentRunnerFunc) Run(ctx context.Context, workspace string, req agentexec.Request) (agentexec.Result, error) { + return f(ctx, workspace, req) +} + +func (r *fakeAgentRunner) Run(_ context.Context, workspace string, req agentexec.Request) (agentexec.Result, error) { + r.workspace = workspace + r.request = req + if r.result.Version == 0 { + r.result.Version = agentexec.ProtocolVersion + } + r.result.TaskID = req.TaskID + r.result.Attempt = req.Attempt + r.result.Stage = req.Stage + return r.result, r.err +} + +func TestAgentStageBuildsExecutionRequestAndAppliesResult(t *testing.T) { + runner := &fakeAgentRunner{result: agentexec.Result{ + Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed, + Summary: "finished", TokensUsed: 23, Iterations: 4, + }} + resultCalled := false + stage := AgentStage{ + Name: "plan", Role: "planner", ReadOnly: true, MaxSteps: 7, + Mission: func(*TaskContext) string { return "inspect the repository" }, + OnResult: func(_ *TaskContext, result agentexec.Result) error { + resultCalled = result.Summary == "finished" + return nil + }, + }.Stage() + task := &store.Task{ID: 9, Attempt: 2} + tc := &TaskContext{ + Task: task, Agent: runner, Dir: "/tmp/workspace", Log: slog.New(slog.DiscardHandler), + Cfg: config.Config{ + Models: map[string]string{"builder": "provider/fallback"}, + Budgets: config.Budgets{MaxSteps: 50, MaxTokens: 5000}, + }, + Repo: config.Repo{Protect: []string{"_templ.go"}, Preflight: [][]string{{"go", "version"}}}, + } + if err := stage.Run(context.Background(), tc); err != nil { + t.Fatal(err) + } + if runner.workspace != tc.Dir { + t.Fatalf("workspace = %q, want %q", runner.workspace, tc.Dir) + } + wantPreflight := []agentexec.Command{{Name: "go", Argv: []string{"go", "version"}}} + if runner.request.Version != agentexec.ProtocolVersion || runner.request.TaskID != 9 || runner.request.Attempt != 2 || + runner.request.Model != "provider/fallback" || runner.request.Budget.MaxSteps != 7 || !runner.request.ReadOnly || + !reflect.DeepEqual(runner.request.Preflight, wantPreflight) { + t.Fatalf("unexpected request: %#v", runner.request) + } + if len(runner.request.Protection.Suffixes) != 0 { + t.Fatalf("read-only request has protection rules: %#v", runner.request.Protection) + } + if !resultCalled || task.TokensUsed != 23 || task.Iterations != 4 { + t.Fatalf("result not applied: called=%v task=%#v", resultCalled, task) + } +} + +func TestAgentStagePersistsReturnedNotes(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "archie.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := st.Close(); err != nil { + t.Errorf("close store: %v", err) + } + }) + ctx := context.Background() + if _, err := st.EnqueueIssue(ctx, "owner", "repo", 1, "title", "body", ""); err != nil { + t.Fatal(err) + } + task, err := st.ClaimNext(ctx) + if err != nil { + t.Fatal(err) + } + runner := &fakeAgentRunner{result: agentexec.Result{ + Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed, + AppendedNotes: []string{"checked with go test"}, + }} + stage := AgentStage{ + Name: "build", Role: "builder", Mission: func(*TaskContext) string { return "build" }, + }.Stage() + tc := &TaskContext{ + Task: task, Store: st, Agent: runner, Log: slog.New(slog.DiscardHandler), + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + } + if err := stage.Run(ctx, tc); err != nil { + t.Fatal(err) + } + if task.Notes != "- checked with go test\n" { + t.Fatalf("task notes = %q", task.Notes) + } +} + +func TestAgentStageDiscardsUnstampedErrorResult(t *testing.T) { + task := &store.Task{ID: 1, Attempt: 1, Notes: "existing\n"} + runner := agentRunnerFunc(func(context.Context, string, agentexec.Request) (agentexec.Result, error) { + return agentexec.Result{AppendedNotes: []string{"untrusted"}}, errors.New("worker exited") + }) + stage := AgentStage{ + Name: "build", Role: "builder", Mission: func(*TaskContext) string { return "build" }, + }.Stage() + err := stage.Run(context.Background(), &TaskContext{ + Task: task, Agent: runner, Log: slog.New(slog.DiscardHandler), + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + }) + if err == nil { + t.Fatal("stage accepted an unstamped error result") + } + if task.Notes != "existing\n" { + t.Fatalf("unstamped error result mutated notes: %q", task.Notes) + } +} + +func TestFeasibilityDecisionCrossesAsCapturedData(t *testing.T) { + runner := &fakeAgentRunner{result: agentexec.Result{ + Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed, + Captures: map[string][]json.RawMessage{"decide": {json.RawMessage(`{"fit":true,"reasons":"aligned"}`)}}, + }} + tc := &TaskContext{ + Task: &store.Task{ID: 1}, Agent: runner, Log: slog.New(slog.DiscardHandler), + Cfg: config.Config{Models: map[string]string{"planner": "provider/model"}}, + Repo: config.Repo{Owner: "owner", Name: "repo"}, + } + if err := Feasibility().Stages[1].Run(context.Background(), tc); err != nil { + t.Fatal(err) + } + if tc.decision == nil || !tc.decision.Fit || tc.decision.Reasons != "aligned" { + t.Fatalf("decision = %#v", tc.decision) + } +} + +func TestFeasibilityRejectsNullFitValue(t *testing.T) { + runner := &fakeAgentRunner{result: agentexec.Result{ + Status: agentexec.StatusPassed, + Captures: map[string][]json.RawMessage{"decide": {json.RawMessage(`{"fit":null,"reasons":"not valid"}`)}}, + }} + tc := &TaskContext{ + Task: &store.Task{ID: 1}, Agent: runner, Log: slog.New(slog.DiscardHandler), + Cfg: config.Config{Models: map[string]string{"planner": "provider/model"}}, + Repo: config.Repo{Owner: "owner", Name: "repo"}, + } + if err := Feasibility().Stages[1].Run(context.Background(), tc); err == nil { + t.Fatal("assess accepted a null fit value") + } + if tc.decision != nil { + t.Fatalf("decision mutated from invalid capture: %#v", tc.decision) + } +} + +func TestRunLeavesInterruptedTaskForCrashRecovery(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "archie.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := st.Close(); err != nil { + t.Errorf("close store: %v", err) + } + }) + if _, err := st.EnqueueIssue(context.Background(), "owner", "repo", 2, "title", "body", ""); err != nil { + t.Fatal(err) + } + task, err := st.ClaimNext(context.Background()) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + Run(ctx, Workflow{Name: "test", Stages: []Stage{{ + Name: "agent", Run: func(ctx context.Context, _ *TaskContext) error { return ctx.Err() }, + }}}, &TaskContext{ + Task: task, Store: st, Repo: config.Repo{Owner: "owner", Name: "repo"}, + Log: slog.New(slog.DiscardHandler), + }) + got, err := st.TaskByIssue(context.Background(), "owner", "repo", 2) + if err != nil { + t.Fatal(err) + } + if got.Status != store.StatusRunning || got.ParkReason != "" { + t.Fatalf("interrupted task status=%q park_reason=%q, want running with no park reason", got.Status, got.ParkReason) + } +} diff --git a/internal/workflow/feasibility.go b/internal/workflow/feasibility.go index d7408be26..9895b9783 100644 --- a/internal/workflow/feasibility.go +++ b/internal/workflow/feasibility.go @@ -8,9 +8,7 @@ import ( "net/http" "time" - "github.com/samcharles93/ai-sdk/agentloop" - "github.com/samcharles93/ai-sdk/core" - + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/store" ) @@ -28,11 +26,11 @@ func Feasibility() Workflow { StagePrepareWorktree(), // read-only stages still need the checkout AgentStage{ - Name: "assess", - Role: "planner", - ReadOnly: true, - MaxSteps: 15, - Extra: decideToolSet, + Name: "assess", + Role: "planner", + ReadOnly: true, + MaxSteps: 15, + CaptureTools: decideCaptureTools, Mission: func(tc *TaskContext) string { return fmt.Sprintf( "Assess whether this feature request fits the project %s.\n\n"+ @@ -44,10 +42,25 @@ func Feasibility() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { - if tc.decision == nil { - return fmt.Errorf("assess stage finished without calling the decide tool") + OnResult: func(tc *TaskContext, res agentexec.Result) error { + calls := res.Captures["decide"] + if len(calls) != 1 { + return fmt.Errorf("assess stage called the decide tool %d times (want exactly once)", len(calls)) } + var captured struct { + Fit *bool `json:"fit"` + Reasons string `json:"reasons"` + } + if err := json.Unmarshal(calls[0], &captured); err != nil { + return fmt.Errorf("decode feasibility decision: %w", err) + } + if captured.Fit == nil { + return fmt.Errorf("assess stage decision has no boolean fit value") + } + if captured.Reasons == "" { + return fmt.Errorf("assess stage decision has no reasons") + } + tc.decision = &decision{Fit: *captured.Fit, Reasons: captured.Reasons} if !tc.decision.Fit { comment := fmt.Sprintf("**archie assessed this feature as not a fit — closing as won't-do.**\n\n%s\n\n_Reopen and re-assign if you disagree._", tc.decision.Reasons) if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, comment); err != nil { @@ -75,7 +88,7 @@ func Feasibility() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.decision.Reasons, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { + OnResult: func(tc *TaskContext, res agentexec.Result) error { tc.Task.Plan = res.Summary return nil }, @@ -101,14 +114,13 @@ func Feasibility() Workflow { // decision is the assess stage's structured verdict. type decision struct { - Fit bool - Reasons string + Fit bool `json:"fit"` + Reasons string `json:"reasons"` } -// decideToolSet gives the assess agent a decide tool that records its -// verdict on the TaskContext — structured output as a tool call, not -// parsed out of prose. -func decideToolSet(tc *TaskContext) core.ToolSet { +// decideCaptureTools gives the assess agent a structured verdict tool. Its +// arguments cross the execution boundary as data and are applied by OnResult. +func decideCaptureTools(*TaskContext) []agentexec.CaptureTool { params := json.RawMessage(`{ "type": "object", "properties": { @@ -117,25 +129,11 @@ func decideToolSet(tc *TaskContext) core.ToolSet { }, "required": ["fit", "reasons"] }`) - return core.ToolSet{ - "decide": core.NewTool("decide", - "Record the feasibility verdict. Call exactly once, before finish.", - params, - func(ctx context.Context, input string) (string, error) { - var args struct { - Fit bool `json:"fit"` - Reasons string `json:"reasons"` - } - if err := json.Unmarshal([]byte(input), &args); err != nil { - return "decide rejected: invalid arguments: " + err.Error(), nil - } - if args.Reasons == "" { - return "decide rejected: reasons are required", nil - } - tc.decision = &decision{Fit: args.Fit, Reasons: args.Reasons} - return fmt.Sprintf("verdict recorded: fit=%v", args.Fit), nil - }), - } + return []agentexec.CaptureTool{{ + Name: "decide", Description: "Record the feasibility verdict. Call exactly once, before finish.", + Parameters: params, RequiredFields: []string{"fit", "reasons"}, + NonEmptyStrings: []string{"reasons"}, BooleanFields: []string{"fit"}, MaxCalls: 1, + }} } // notify POSTs a JSON payload to the configured webhook (n8n turns it diff --git a/internal/workflow/implement.go b/internal/workflow/implement.go index d923b4c4c..b3a3e6dc3 100644 --- a/internal/workflow/implement.go +++ b/internal/workflow/implement.go @@ -6,7 +6,7 @@ import ( "os/exec" "strings" - "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/archie-core/internal/agentexec" ) // StageBaselineGate verifies the repo's gate is green at the base commit @@ -61,7 +61,7 @@ func Implement() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { + OnResult: func(tc *TaskContext, res agentexec.Result) error { tc.Task.Plan = res.Summary body := fmt.Sprintf("**archie's plan** (review now if you want to veto — building starts immediately):\n\n%s", res.Summary) if _, err := tc.Forge.Comment(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil { @@ -74,7 +74,7 @@ func Implement() Workflow { AgentStage{ Name: "build", Role: "builder", - Gate: func(tc *TaskContext) agentloop.GateConfig { + Gate: func(tc *TaskContext) agentexec.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, ExtraRules: "Files matching the repository's protected suffixes (e.g. generated code) are " + @@ -90,7 +90,7 @@ func Implement() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Plan, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { + OnResult: func(tc *TaskContext, res agentexec.Result) error { tc.BuildSummary = res.Summary return nil }, diff --git a/internal/workflow/tdd.go b/internal/workflow/tdd.go index 2cd90b2d9..e419009f1 100644 --- a/internal/workflow/tdd.go +++ b/internal/workflow/tdd.go @@ -4,11 +4,9 @@ import ( "context" "fmt" "os/exec" - "path/filepath" "strings" - "github.com/samcharles93/ai-sdk/agentloop" - + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" ) @@ -40,7 +38,7 @@ func TDD() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { + OnResult: func(tc *TaskContext, res agentexec.Result) error { tc.Task.Plan = res.Summary return nil }, @@ -52,7 +50,7 @@ func TDD() Workflow { // 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 { + Gate: func(tc *TaskContext) agentexec.Gate { return tddReproGate(tc.Repo, tc.Cfg.Budgets) }, Mission: func(tc *TaskContext) string { @@ -93,17 +91,17 @@ func TDD() Workflow { AgentStage{ Name: "fix", Role: "builder", - Gate: func(tc *TaskContext) agentloop.GateConfig { + Gate: func(tc *TaskContext) agentexec.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, // Environmental, not advisory: the fix stage cannot touch // test files at all — the committed repro is the spec. - ProtectPaths: func(tc *TaskContext) func(string) bool { + ProtectGlobs: func(tc *TaskContext) []string { glob := tc.Repo.ResolvedTestGlob() if glob == "" { return nil } - return func(path string) bool { return matchesTestPath(glob, path) } + return []string{glob} }, 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.", @@ -117,7 +115,7 @@ func TDD() Workflow { tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Plan, ) }, - OnResult: func(tc *TaskContext, res agentloop.Result) error { + OnResult: func(tc *TaskContext, res agentexec.Result) error { tc.BuildSummary = res.Summary return nil }, @@ -152,22 +150,22 @@ func TDD() Workflow { // 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 { +func tddReproGate(repo config.Repo, budgets config.Budgets) agentexec.Gate { if len(repo.Gate) == 0 { - return agentloop.GateConfig{} + return agentexec.Gate{} } - cmds := make([]agentloop.GateCommand, 0, len(repo.Gate)) + cmds := make([]agentexec.Command, 0, len(repo.Gate)) for _, argv := range repo.Gate { if len(argv) == 0 { continue } - gc := agentloop.GateCommand{Name: argv[0], Argv: argv} + gc := agentexec.Command{Name: argv[0], Argv: argv} cmds = append(cmds, gc) } if len(cmds) > 0 { cmds[len(cmds)-1].ExpectFailure = true } - return agentloop.GateConfig{ + return agentexec.Gate{ Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures, } @@ -193,14 +191,3 @@ func testCommandArgv(repo config.Repo) []string { } 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 index a14799156..fce2d49e3 100644 --- a/internal/workflow/tdd_test.go +++ b/internal/workflow/tdd_test.go @@ -7,30 +7,6 @@ import ( "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", "./..."}, diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 00de9a89c..372b83fdf 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -12,8 +12,7 @@ import ( "strings" "time" - "github.com/samcharles93/ai-sdk/runtime" - + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -25,15 +24,15 @@ import ( // forward by mutating Task (persisted after every stage) and the // scratch fields below. type TaskContext struct { - Task *store.Task - Repo config.Repo - Cfg config.Config - Forge forge.Forge - Store *store.Store - Trees *worktree.Manager - Runtime *runtime.Runtime - Bus *events.Bus // nil-safe via Emit - Log *slog.Logger + Task *store.Task + Repo config.Repo + Cfg config.Config + Forge forge.Forge + Store *store.Store + Trees *worktree.Manager + Agent agentexec.Runner + Bus *events.Bus // nil-safe via Emit + Log *slog.Logger // Dir/Branch are set by the prepare step. Dir string @@ -155,6 +154,13 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { tc.Emit(events.KindStageFinish, stage.Name, "", data) if err != nil { + // Daemon shutdown is not a workflow failure. Leave the task running + // so Startup's existing crash recovery requeues it; parking here + // would publish a false failure and require manual intervention. + if ctx.Err() != nil { + log.Info("stage interrupted", "stage", stage.Name, "err", err) + return + } t.ParkReason = fmt.Sprintf("stage %s: %v", stage.Name, err) log.Warn("stage failed — parking", "stage", stage.Name, "err", err) park(ctx, tc, t.ParkReason)