diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 588f0ef92..73af9250e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -7,10 +7,11 @@ | Package | Role | |---|---| | `cmd/archied/` | Binary entry: config→forge→store→runtime→workflows→daemon | +| `cmd/archie-agent/` | One-invocation autonomous stage worker (JSON stdin/stdout) | | `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/agentexec/` | Versioned agent-stage protocol, worker, and in-process/subprocess runners | | `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 | @@ -146,10 +147,13 @@ Daemon-level TOML (`~/.config/archie/config.toml`): - `[[repos]]` — owner, name, base branch, gate commands, protected paths, ecosystem - `[models]` — planner, builder, triage (provider/model refs) - `[providers]` — LLM provider configs +- `[agent]` — execution mode (`inprocess` or `subprocess`), worker command, environment allowlist - `[budgets]` — max steps, max tokens, wall clock, gate max failures - `[web]` — dashboard listen address - `[notify]` — webhook URL for notifications +Subprocess mode is a migration transport boundary, not a security sandbox: the worker still runs under the daemon UID and can access daemon-readable host resources. The "daemon never runs untrusted code" boundary requires the later container runner with a separate user, a restricted filesystem and process namespace, and explicit mounts. + Per-repo gates are command lists: `[[repos.gate]] = ["go", "vet", "./..."]`. The last command is the test runner (by convention — TDD inverts it). ## Observability diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go new file mode 100644 index 000000000..95d1e9fca --- /dev/null +++ b/cmd/archie-agent/main.go @@ -0,0 +1,28 @@ +// Command archie-agent executes one unprivileged autonomous agent stage from +// a versioned JSON invocation on stdin and writes one response to stdout. +package main + +import ( + "context" + "log/slog" + "os" + "os/signal" + "syscall" + + "github.com/samcharles93/archie-core/internal/agentexec" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) + if err := agentexec.ServeOne(ctx, os.Stdin, os.Stdout, log); err != nil { + log.Error("agent worker failed", "err", err) + return 1 + } + return 0 +} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index d490f5b18..5b58bfe7c 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -14,8 +14,6 @@ import ( "path/filepath" "syscall" - "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" @@ -62,7 +60,11 @@ func run() int { log.Error("open store", "err", err) return 1 } - defer st.Close() + defer func() { + if err := st.Close(); err != nil { + log.Error("close store", "err", err) + } + }() if *requeue > 0 { if err := st.Requeue(context.Background(), *requeue, "manual", ""); err != nil { @@ -103,10 +105,22 @@ func run() int { }() } - llm := llmRuntime(cfg) + providers := executionProviders(cfg) + llm := agentexec.NewRuntime(providers) var agentRunner agentexec.Runner if llm != nil { - agentRunner = agentexec.NewInProcessRunner(llm, log) + switch cfg.Agent.Mode { + case "subprocess": + agentRunner = &agentexec.SubprocessRunner{ + Command: cfg.Agent.Command, + Environ: os.Environ(), + AdditionalEnv: cfg.Agent.Env, + Diagnostics: os.Stderr, + Providers: providers, + } + case "inprocess": + agentRunner = agentexec.NewInProcessRunner(llm, log) + } } d := &daemon.Daemon{ Cfg: cfg, @@ -149,25 +163,12 @@ func run() int { 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)) +func executionProviders(cfg config.Config) map[string]agentexec.Provider { + providers := make(map[string]agentexec.Provider, 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 + providers[name] = agentexec.Provider{Class: p.Class, APIKeyEnv: p.APIKeyEnv, BaseURL: p.BaseURL} } - return runtime.NewRuntime(runtime.Config{Providers: providers}) + return providers } func configHome() string { diff --git a/config.example.toml b/config.example.toml index a175cc3ee..c2b2428b7 100644 --- a/config.example.toml +++ b/config.example.toml @@ -36,6 +36,13 @@ api_key_env = "OPENAI_API_KEY" [providers.ollama] class = "ollama" +[agent] +mode = "inprocess" # "subprocess" runs each autonomous stage through archie-agent +command = "archie-agent" # executable path for subprocess mode +# Subprocess mode isolates the protocol and process lifecycle, not OS privileges. +# The worker still runs as the daemon user until the Docker sandbox phase lands. +# env = ["GOCACHE"] # extra environment variable names forwarded to the worker + [web] # observability dashboard (read-only, no auth — keep it local/tailnet) listen = "127.0.0.1:8484" # "off" disables diff --git a/internal/agentexec/inprocess.go b/internal/agentexec/inprocess.go index e0bf77038..32a1ddb11 100644 --- a/internal/agentexec/inprocess.go +++ b/internal/agentexec/inprocess.go @@ -132,7 +132,6 @@ func protectionMatcher(p Protection, readOnly bool) func(string) bool { 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 { diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go index 21c37822d..7277d8e05 100644 --- a/internal/agentexec/protocol.go +++ b/internal/agentexec/protocol.go @@ -5,6 +5,8 @@ package agentexec import ( "encoding/json" "fmt" + "net/url" + "strings" "time" ) @@ -108,6 +110,67 @@ type Result struct { Captures map[string][]json.RawMessage `json:"captures,omitempty"` } +// Provider describes how the worker resolves a model provider. API keys are +// referenced by environment variable name and never serialized. +type Provider struct { + Class string `json:"class"` + APIKeyEnv string `json:"api_key_env,omitempty"` + BaseURL string `json:"base_url,omitempty"` +} + +func (p Provider) validate() error { + if strings.TrimSpace(p.Class) == "" { + return fmt.Errorf("provider class is required") + } + if p.BaseURL == "" { + return nil + } + u, err := url.Parse(p.BaseURL) + if err != nil { + return fmt.Errorf("parse provider base_url: %w", err) + } + if u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return fmt.Errorf("provider base_url must not contain userinfo, query parameters, or a fragment") + } + return nil +} + +// Invocation is the single request accepted by archie-agent on stdin. +type Invocation struct { + Version int `json:"version"` + Workspace string `json:"workspace"` + Request Request `json:"request"` + Providers map[string]Provider `json:"providers"` +} + +// Validate rejects invocations that cannot be executed safely. +func (i Invocation) Validate() error { + if i.Version != ProtocolVersion { + return fmt.Errorf("agent invocation protocol version %d is unsupported (want %d)", i.Version, ProtocolVersion) + } + if i.Workspace == "" { + return fmt.Errorf("agent invocation workspace is required") + } + if len(i.Providers) == 0 { + return fmt.Errorf("agent invocation providers are required") + } + for name, provider := range i.Providers { + if err := provider.validate(); err != nil { + return fmt.Errorf("agent invocation provider %q: %w", name, err) + } + } + return i.Request.Validate() +} + +// Response is the single envelope written by archie-agent on stdout. +// Error carries execution errors after the worker successfully decoded the +// invocation; process-level protocol failures use a non-zero exit status. +type Response struct { + Version int `json:"version"` + Result Result `json:"result"` + Error string `json:"error,omitempty"` +} + // ValidateFor rejects incompatible or misrouted results before the daemon // applies them to task state. func (r Result) ValidateFor(req Request) error { diff --git a/internal/agentexec/runtime.go b/internal/agentexec/runtime.go new file mode 100644 index 000000000..1833f0c68 --- /dev/null +++ b/internal/agentexec/runtime.go @@ -0,0 +1,23 @@ +package agentexec + +import "github.com/samcharles93/ai-sdk/runtime" + +// NewRuntime builds the provider runtime shared by archied's in-process mode +// and the archie-agent worker. Nil means no providers were configured. +func NewRuntime(providers map[string]Provider) *runtime.Runtime { + if len(providers) == 0 { + return nil + } + runtime.RegisterBuiltinClasses() + catalog := make(map[string]runtime.ProviderConfig, len(providers)) + for name, provider := range providers { + cfg := runtime.ProviderConfig{ID: name, Class: provider.Class, BaseURL: provider.BaseURL} + if provider.APIKeyEnv == "" { + cfg.Auth = runtime.AuthConfig{Type: runtime.AuthTypeNone} + } else { + cfg.Auth = runtime.AuthConfig{APIKeyEnv: provider.APIKeyEnv} + } + catalog[name] = cfg + } + return runtime.NewRuntime(runtime.Config{Providers: catalog}) +} diff --git a/internal/agentexec/subprocess.go b/internal/agentexec/subprocess.go new file mode 100644 index 000000000..787dd22b5 --- /dev/null +++ b/internal/agentexec/subprocess.go @@ -0,0 +1,162 @@ +package agentexec + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os/exec" + "strings" +) + +const maxDiagnosticBytes = 64 << 10 + +// SubprocessRunner executes each agent stage in a fresh archie-agent process. +type SubprocessRunner struct { + Command string + Args []string + // Environ is the daemon environment to select from. AdditionalEnv names + // operator-approved compatibility variables; the requested provider's key + // variable is added automatically for that invocation only. + Environ []string + AdditionalEnv []string + Diagnostics io.Writer + Providers map[string]Provider +} + +func (r *SubprocessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) { + providerName, _, ok := strings.Cut(req.Model, "/") + if !ok || providerName == "" { + return Result{}, fmt.Errorf("agent model %q must be provider/model", req.Model) + } + provider, ok := r.Providers[providerName] + if !ok { + return Result{}, fmt.Errorf("agent model provider %q is not configured", providerName) + } + providers := map[string]Provider{providerName: provider} + invocation := Invocation{Version: ProtocolVersion, Workspace: workspace, Request: req, Providers: providers} + if err := invocation.Validate(); err != nil { + return Result{}, err + } + if strings.TrimSpace(r.Command) == "" { + return Result{}, fmt.Errorf("archie-agent command is required") + } + payload, err := json.Marshal(invocation) + if err != nil { + return Result{}, fmt.Errorf("encode invocation: %w", err) + } + payload = append(payload, '\n') + + cmd := exec.CommandContext(ctx, r.Command, r.Args...) + configureProcessCancellation(cmd) + cmd.Stdin = bytes.NewReader(payload) + cmd.Env = WorkerEnvironment(r.Environ, r.AdditionalEnv, providers) + stdout := &cappedBuffer{limit: maxProtocolBytes} + stderr := &cappedBuffer{limit: maxDiagnosticBytes} + cmd.Stdout = stdout + cmd.Stderr = stderr + if r.Diagnostics != nil { + cmd.Stderr = io.MultiWriter(r.Diagnostics, stderr) + } + if err := cmd.Run(); err != nil { + if cause := context.Cause(ctx); cause != nil { + if diagnostic := strings.TrimSpace(stderr.String()); diagnostic != "" { + return Result{}, fmt.Errorf("%w: archie-agent: %s", cause, diagnostic) + } + return Result{}, cause + } + return Result{}, fmt.Errorf("archie-agent process: %w: %s", err, strings.TrimSpace(stderr.String())) + } + if stdout.truncated { + return Result{}, fmt.Errorf("archie-agent response exceeds %d bytes", maxProtocolBytes) + } + var response Response + if err := decodeOne(bytes.NewReader(stdout.Bytes()), &response); err != nil { + return Result{}, fmt.Errorf("decode archie-agent response: %w: %s", err, strings.TrimSpace(stderr.String())) + } + if response.Version != ProtocolVersion { + return Result{}, fmt.Errorf("archie-agent response protocol version %d is unsupported", response.Version) + } + if response.Result.Version != 0 { + if err := response.Result.ValidateFor(req); err != nil { + return Result{}, err + } + } + if response.Error != "" { + return response.Result, errors.New(response.Error) + } + if err := response.Result.ValidateFor(req); err != nil { + return Result{}, err + } + return response.Result, nil +} + +type cappedBuffer struct { + bytes.Buffer + limit int + truncated bool +} + +func (b *cappedBuffer) Write(p []byte) (int, error) { + original := len(p) + remaining := b.limit - b.Len() + if remaining <= 0 { + b.truncated = true + return original, nil + } + if len(p) > remaining { + _, _ = b.Buffer.Write(p[:remaining]) + b.truncated = true + return original, nil + } + _, _ = b.Buffer.Write(p) + return original, nil +} + +// SelectEnvironment copies only named variables from environ. Later entries +// win, matching os.Environ and exec.Cmd semantics without accidentally +// inheriting unrelated variables. This is not an OS security boundary: a +// same-UID subprocess may still access daemon-readable host resources. +func SelectEnvironment(environ, names []string) []string { + allowed := make(map[string]bool, len(names)) + for _, name := range names { + if name != "" { + allowed[name] = true + } + } + values := make(map[string]string, len(allowed)) + for _, entry := range environ { + name, _, ok := strings.Cut(entry, "=") + if ok && allowed[name] { + values[name] = entry + } + } + out := make([]string, 0, len(values)) + for _, name := range names { + if entry, ok := values[name]; ok { + out = append(out, entry) + delete(values, name) + } + } + return out +} + +// DefaultEnvironmentNames are compatibility variables safe to forward by +// default. Additional toolchain variables must be explicitly configured. +func DefaultEnvironmentNames() []string { + return []string{"PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"} +} + +// WorkerEnvironment selects the default compatibility variables, configured +// additions, and each provider's API-key variable. Forge credentials are not +// forwarded unless an operator explicitly lists or reuses their variable. +func WorkerEnvironment(environ, additional []string, providers map[string]Provider) []string { + names := DefaultEnvironmentNames() + names = append(names, additional...) + for _, provider := range providers { + names = append(names, provider.APIKeyEnv) + } + return SelectEnvironment(environ, names) +} diff --git a/internal/agentexec/subprocess_process_unix.go b/internal/agentexec/subprocess_process_unix.go new file mode 100644 index 000000000..39c5350dc --- /dev/null +++ b/internal/agentexec/subprocess_process_unix.go @@ -0,0 +1,27 @@ +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris + +package agentexec + +import ( + "errors" + "os" + "os/exec" + "syscall" +) + +// configureProcessCancellation puts the worker and every command it starts in +// a dedicated process group. CommandContext cancellation then kills the whole +// group so toolchain grandchildren cannot continue mutating the worktree. +func configureProcessCancellation(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + if cmd.Process == nil { + return os.ErrProcessDone + } + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } +} diff --git a/internal/agentexec/subprocess_process_windows.go b/internal/agentexec/subprocess_process_windows.go new file mode 100644 index 000000000..11c88166b --- /dev/null +++ b/internal/agentexec/subprocess_process_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package agentexec + +import "os/exec" + +// Windows keeps exec.CommandContext's direct-process cancellation. Production +// subprocess and container execution are currently supported on Unix hosts. +func configureProcessCancellation(_ *exec.Cmd) {} diff --git a/internal/agentexec/subprocess_test.go b/internal/agentexec/subprocess_test.go new file mode 100644 index 000000000..f0c152d6e --- /dev/null +++ b/internal/agentexec/subprocess_test.go @@ -0,0 +1,247 @@ +package agentexec + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestSubprocessRunnerRoundTrip(t *testing.T) { + req := testRequest() + result, err := helperRunner("success").Run(context.Background(), "/workspace", req) + if err != nil { + t.Fatal(err) + } + if result.Summary != "from child" || result.TaskID != req.TaskID || result.Attempt != req.Attempt { + t.Fatalf("result = %#v", result) + } +} + +func TestSubprocessRunnerReturnsStampedWorkerError(t *testing.T) { + req := testRequest() + result, err := helperRunner("worker-error").Run(context.Background(), "/workspace", req) + if err == nil || err.Error() != "provider unavailable" { + t.Fatalf("error = %v", err) + } + if result.TaskID != req.TaskID || result.Stage != req.Stage { + t.Fatalf("partial result lost identity: %#v", result) + } +} + +func TestSubprocessRunnerRejectsMalformedAndOversizedOutput(t *testing.T) { + for _, behavior := range []string{"malformed", "oversized", "multiple", "mismatched"} { + t.Run(behavior, func(t *testing.T) { + _, err := helperRunner(behavior).Run(context.Background(), "/workspace", testRequest()) + if err == nil { + t.Fatal("Run succeeded") + } + }) + } +} + +func TestSubprocessRunnerReportsExitDiagnostics(t *testing.T) { + _, err := helperRunner("exit").Run(context.Background(), "/workspace", testRequest()) + if err == nil || !strings.Contains(err.Error(), "child diagnostic") { + t.Fatalf("error = %v", err) + } +} + +func TestSubprocessRunnerCancelsChild(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err := helperRunner("hang").Run(ctx, "/workspace", testRequest()) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("error = %v, want deadline exceeded", err) + } +} + +func TestSubprocessRunnerCancellationKillsGrandchildren(t *testing.T) { + marker := filepath.Join(t.TempDir(), "grandchild-survived") + runner := helperRunner("spawn-grandchild") + runner.Environ = append(runner.Environ, "AGENT_HELPER_MARKER="+marker) + runner.AdditionalEnv = append(runner.AdditionalEnv, "AGENT_HELPER_MARKER") + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err := runner.Run(ctx, "/workspace", testRequest()) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("error = %v, want deadline exceeded", err) + } + time.Sleep(300 * time.Millisecond) + if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("grandchild survived cancellation: stat error = %v", err) + } +} + +func TestSubprocessRunnerForwardsOnlyRequestedProvider(t *testing.T) { + runner := helperRunner("provider-scope") + runner.Environ = append(runner.Environ, "OTHER_KEY=must-not-leak") + runner.Providers["other"] = Provider{Class: "openai", APIKeyEnv: "OTHER_KEY"} + if _, err := runner.Run(context.Background(), "/workspace", testRequest()); err != nil { + t.Fatal(err) + } +} + +func TestInvocationRejectsCredentialBearingProviderURL(t *testing.T) { + for _, baseURL := range []string{ + "https://token@example.com/v1", + "https://example.com/v1?api_key=secret", + "https://example.com/v1#secret", + } { + t.Run(baseURL, func(t *testing.T) { + invocation := Invocation{ + Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(), + Providers: map[string]Provider{"provider": {Class: "openai", BaseURL: baseURL}}, + } + if err := invocation.Validate(); err == nil { + t.Fatal("Validate succeeded") + } + }) + } +} + +func TestSelectEnvironmentDoesNotLeakUnlistedValues(t *testing.T) { + got := WorkerEnvironment( + []string{"PATH=/bin", "ARCHIE_GITHUB_TOKEN=secret", "OPENAI_API_KEY=model", "PATH=/usr/bin"}, + nil, + map[string]Provider{"openai": {APIKeyEnv: "OPENAI_API_KEY"}}, + ) + want := []string{"PATH=/usr/bin", "OPENAI_API_KEY=model"} + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("environment = %v, want %v", got, want) + } +} + +func TestServeOneRejectsMultipleInvocations(t *testing.T) { + input := `{"version":1} {"version":1}` + err := ServeOne(context.Background(), strings.NewReader(input), &strings.Builder{}, nil) + if err == nil || !strings.Contains(err.Error(), "multiple JSON values") { + t.Fatalf("error = %v", err) + } +} + +func TestServeOneWritesStampedExecutionError(t *testing.T) { + invocation := Invocation{ + Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(), + Providers: map[string]Provider{"provider": {Class: "openai"}}, + } + input, err := json.Marshal(invocation) + if err != nil { + t.Fatal(err) + } + var output strings.Builder + err = serveOne(context.Background(), strings.NewReader(string(input)), &output, func(Invocation) Runner { + return runnerFunc(func(_ context.Context, _ string, req Request) (Result, error) { + return Result{ + Version: ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, + Stage: req.Stage, Status: StatusPassed, + }, errors.New("provider unavailable") + }) + }) + if err != nil { + t.Fatal(err) + } + var response Response + if err := json.Unmarshal([]byte(output.String()), &response); err != nil { + t.Fatal(err) + } + if response.Error != "provider unavailable" || response.Result.TaskID != invocation.Request.TaskID { + t.Fatalf("response = %#v", response) + } +} + +func TestDecodeOneRejectsOversizedInput(t *testing.T) { + var value any + err := decodeOne(strings.NewReader(`"`+strings.Repeat("x", maxProtocolBytes)+`"`), &value) + if err == nil || !strings.Contains(err.Error(), "exceeds") { + t.Fatalf("error = %v", err) + } +} + +func helperRunner(behavior string) *SubprocessRunner { + return &SubprocessRunner{ + Command: os.Args[0], Args: []string{"-test.run=TestAgentHelperProcess"}, + Environ: []string{ + "GO_WANT_AGENT_HELPER=1", "AGENT_HELPER_BEHAVIOR=" + behavior, + "PROVIDER_KEY=selected", + }, + AdditionalEnv: []string{"GO_WANT_AGENT_HELPER", "AGENT_HELPER_BEHAVIOR"}, + Providers: map[string]Provider{"provider": {Class: "openai", APIKeyEnv: "PROVIDER_KEY"}}, + } +} + +type runnerFunc func(context.Context, string, Request) (Result, error) + +func (f runnerFunc) Run(ctx context.Context, workspace string, req Request) (Result, error) { + return f(ctx, workspace, req) +} + +func testRequest() Request { + return Request{ + Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "build", + Model: "provider/model", Mission: "test mission", + } +} + +func TestAgentHelperProcess(t *testing.T) { + if os.Getenv("GO_WANT_AGENT_HELPER") != "1" { + return + } + var invocation Invocation + if err := json.NewDecoder(os.Stdin).Decode(&invocation); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + result := Result{ + Version: ProtocolVersion, TaskID: invocation.Request.TaskID, Attempt: invocation.Request.Attempt, + Stage: invocation.Request.Stage, Status: StatusPassed, Summary: "from child", + } + switch os.Getenv("AGENT_HELPER_BEHAVIOR") { + case "success": + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) + case "worker-error": + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result, Error: "provider unavailable"}) + case "malformed": + if _, err := fmt.Fprint(os.Stdout, "not-json"); err != nil { + os.Exit(2) + } + case "oversized": + if _, err := fmt.Fprint(os.Stdout, strings.Repeat("x", maxProtocolBytes+1)); err != nil { + os.Exit(2) + } + case "multiple": + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) + case "mismatched": + result.Attempt++ + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) + case "exit": + fmt.Fprintln(os.Stderr, "child diagnostic") + os.Exit(2) + case "hang": + time.Sleep(10 * time.Second) + case "spawn-grandchild": + cmd := exec.Command("/bin/sh", "-c", `sleep 0.2; printf survived > "$AGENT_HELPER_MARKER"`) + cmd.Env = os.Environ() + if err := cmd.Start(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + time.Sleep(10 * time.Second) + case "provider-scope": + if len(invocation.Providers) != 1 || invocation.Providers["provider"].APIKeyEnv != "PROVIDER_KEY" || + os.Getenv("PROVIDER_KEY") != "selected" || os.Getenv("OTHER_KEY") != "" { + os.Exit(2) + } + _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) + default: + os.Exit(2) + } + os.Exit(0) +} diff --git a/internal/agentexec/worker.go b/internal/agentexec/worker.go new file mode 100644 index 000000000..f9aafe887 --- /dev/null +++ b/internal/agentexec/worker.go @@ -0,0 +1,65 @@ +package agentexec + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" +) + +const maxProtocolBytes = 8 << 20 + +// ServeOne decodes and executes exactly one invocation. Stdout contains only +// the response envelope; callers should direct the supplied logger to stderr. +func ServeOne(ctx context.Context, in io.Reader, out io.Writer, log *slog.Logger) error { + return serveOne(ctx, in, out, func(invocation Invocation) Runner { + return NewInProcessRunner(NewRuntime(invocation.Providers), log) + }) +} + +func serveOne(ctx context.Context, in io.Reader, out io.Writer, newRunner func(Invocation) Runner) error { + var invocation Invocation + if err := decodeOne(in, &invocation); err != nil { + return fmt.Errorf("decode invocation: %w", err) + } + if err := invocation.Validate(); err != nil { + return err + } + runner := newRunner(invocation) + if runner == nil { + return fmt.Errorf("agent runner is not configured") + } + result, runErr := runner.Run(ctx, invocation.Workspace, invocation.Request) + response := Response{Version: ProtocolVersion, Result: result} + if runErr != nil { + response.Error = runErr.Error() + } + if err := json.NewEncoder(out).Encode(response); err != nil { + return fmt.Errorf("encode response: %w", err) + } + return nil +} + +func decodeOne(r io.Reader, value any) error { + data, err := io.ReadAll(io.LimitReader(r, maxProtocolBytes+1)) + if err != nil { + return err + } + if len(data) > maxProtocolBytes { + return fmt.Errorf("JSON value exceeds %d bytes", maxProtocolBytes) + } + decoder := json.NewDecoder(bytes.NewReader(data)) + if err := decoder.Decode(value); err != nil { + return err + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + if err == nil { + return fmt.Errorf("multiple JSON values are not allowed") + } + return err + } + return nil +} diff --git a/internal/config/config.go b/internal/config/config.go index 5229b20a4..5a71e7d16 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -5,6 +5,7 @@ package config import ( "errors" "fmt" + "net/url" "os" "path/filepath" "strings" @@ -127,6 +128,17 @@ type Provider struct { BaseURL string `toml:"base_url"` } +// Agent configures how archied executes autonomous stages. +type Agent struct { + // Mode is "inprocess" during migration or "subprocess" to invoke the + // standalone archie-agent worker for every autonomous stage. + Mode string `toml:"mode"` + // Command is the archie-agent executable path used in subprocess mode. + Command string `toml:"command"` + // Env adds environment variable names to the worker allowlist. + Env []string `toml:"env"` +} + // Forge configures the code forge integration. type Forge struct { Type string `toml:"type"` @@ -210,6 +222,7 @@ type Config struct { Models map[string]string `toml:"models"` Providers map[string]Provider `toml:"providers"` + Agent Agent `toml:"agent"` Budgets Budgets `toml:"budgets"` Web Web `toml:"web"` @@ -264,6 +277,37 @@ func Load(path string) (Config, error) { if cfg.Forge.TokenEnv == "" { cfg.Forge.TokenEnv = "ARCHIE_GITHUB_TOKEN" } + if cfg.Agent.Mode == "" { + cfg.Agent.Mode = "inprocess" + } + if cfg.Agent.Command == "" { + cfg.Agent.Command = "archie-agent" + } + switch cfg.Agent.Mode { + case "inprocess", "subprocess": + default: + return cfg, fmt.Errorf("config: agent.mode %q is invalid (want inprocess or subprocess)", cfg.Agent.Mode) + } + if cfg.Agent.Mode == "subprocess" && strings.TrimSpace(cfg.Agent.Command) == "" { + return cfg, fmt.Errorf("config: agent.command is required in subprocess mode") + } + for i, name := range cfg.Agent.Env { + if strings.TrimSpace(name) == "" || strings.Contains(name, "=") { + return cfg, fmt.Errorf("config: agent.env[%d] %q is not an environment variable name", i, name) + } + } + for name, provider := range cfg.Providers { + if provider.BaseURL == "" { + continue + } + u, err := url.Parse(provider.BaseURL) + if err != nil { + return cfg, fmt.Errorf("config: providers.%s.base_url is invalid: %w", name, err) + } + if u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return cfg, fmt.Errorf("config: providers.%s.base_url must not contain userinfo, query parameters, or a fragment", name) + } + } if cfg.Dispatch.Trigger == "" { cfg.Dispatch.Trigger = "assignee" } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a8a2fe3ad..4fe876038 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -3,6 +3,7 @@ package config import ( "os" "path/filepath" + "strings" "testing" ) @@ -158,6 +159,11 @@ func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) { extra string }{ {name: "dispatch trigger", extra: "\n[dispatch]\ntrigger = \"labels\"\n"}, + {name: "agent mode", extra: "\n[agent]\nmode = \"remote\"\n"}, + {name: "agent command", extra: "\n[agent]\nmode = \"subprocess\"\ncommand = \" \"\n"}, + {name: "agent env", extra: "\n[agent]\nenv = [\"TOKEN=value\"]\n"}, + {name: "provider userinfo", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n"}, + {name: "provider query secret", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://example.com/v1?api_key=secret\"\n"}, {name: "test glob", extra: "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n"}, } @@ -180,6 +186,38 @@ func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) { } } +func TestLoadAgentDefaultsAndOverrides(t *testing.T) { + tests := []struct { + name string + agent string + wantMode string + wantCommand string + wantEnv []string + }{ + {name: "defaults", wantMode: "inprocess", wantCommand: "archie-agent"}, + { + name: "subprocess", agent: "\n[agent]\nmode = \"subprocess\"\ncommand = \"/opt/archie-agent\"\nenv = [\"GOCACHE\"]\n", + wantMode: "subprocess", wantCommand: "/opt/archie-agent", wantEnv: []string{"GOCACHE"}, + }, + } + 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.agent + "\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.Agent.Mode != tt.wantMode || cfg.Agent.Command != tt.wantCommand || strings.Join(cfg.Agent.Env, ",") != strings.Join(tt.wantEnv, ",") { + t.Fatalf("agent config = %#v", cfg.Agent) + } + }) + } +} + func TestExampleConfigLoads(t *testing.T) { cfg, err := Load(filepath.Join("..", "..", "config.example.toml")) if err != nil { diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 9ec871f6b..7b788f60b 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -8,6 +8,7 @@ import ( "context" "fmt" "log/slog" + "slices" "strings" "time" @@ -198,17 +199,14 @@ func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forg } 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"}) + 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 + return slices.Contains(labels, want) } // reconcilePRs moves pr_open tasks to merged/rejected from GitHub state diff --git a/internal/forge/github.go b/internal/forge/github.go index 8edaebb5d..a24491b56 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -134,7 +134,7 @@ func (c *GitHubClient) IssuesWithLabel(ctx context.Context, owner, repo, label s // workflow can watch for replies that come after it. 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)}) + &github.IssueComment{Body: new(body)}) if err != nil { return 0, err } @@ -169,10 +169,10 @@ func (c *GitHubClient) RepliesAfter(ctx context.Context, owner, repo string, num // CreatePR opens a pull request and returns its number. 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), - Base: github.Ptr(base), - Body: github.Ptr(body), + Title: new(title), + Head: new(head), + Base: new(base), + Body: new(body), }) if err != nil { return 0, fmt.Errorf("create PR %s/%s: %w", owner, repo, err) @@ -200,7 +200,7 @@ func (c *GitHubClient) CloseIssue(ctx context.Context, owner, repo string, numbe } } _, _, err := c.gh.Issues.Edit(ctx, owner, repo, number, - &github.IssueRequest{State: github.Ptr("closed")}) + &github.IssueRequest{State: new("closed")}) return err } @@ -244,9 +244,9 @@ func (c *GitHubClient) ensureLabel(ctx context.Context, owner, repo, name string 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)"), + Name: new(name), + Color: new(color), + Description: new("archie task state (managed automatically)"), }) // 422 = already exists; both outcomes mean the label is available. if err != nil && !strings.Contains(err.Error(), "already_exists") { diff --git a/internal/store/events.go b/internal/store/events.go index cef69a08d..087168513 100644 --- a/internal/store/events.go +++ b/internal/store/events.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "errors" "fmt" "time" @@ -31,7 +32,7 @@ CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind, id); func (s *Store) InsertEvent(ctx context.Context, e events.Event) (int64, error) { data, err := json.Marshal(e.Data) if err != nil { - data = []byte(fmt.Sprintf(`{"marshal_error":%q}`, err.Error())) + data = fmt.Appendf(nil, `{"marshal_error":%q}`, err.Error()) } res, err := s.db.ExecContext(ctx, ` INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, detail, data) @@ -44,9 +45,10 @@ func (s *Store) InsertEvent(ctx context.Context, e events.Event) (int64, error) return res.LastInsertId() } -func scanEvents(rows *sql.Rows) ([]events.Event, error) { - defer rows.Close() - var out []events.Event +func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) { + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var e events.Event var at, data string @@ -95,7 +97,7 @@ func (s *Store) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, e } // Tasks returns all tasks, newest first (dashboard listing). -func (s *Store) Tasks(ctx context.Context, limit int) ([]Task, error) { +func (s *Store) Tasks(ctx context.Context, limit int) (tasks []Task, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, owner, repo, issue_number, title, status, workflow, stage, pr_number, tokens_used, iterations, attempt, park_reason @@ -103,8 +105,9 @@ func (s *Store) Tasks(ctx context.Context, limit int) ([]Task, error) { if err != nil { return nil, err } - defer rows.Close() - var out []Task + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var t Task if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title, @@ -112,28 +115,30 @@ func (s *Store) Tasks(ctx context.Context, limit int) ([]Task, error) { &t.Iterations, &t.Attempt, &t.ParkReason); err != nil { return nil, err } - out = append(out, t) + tasks = append(tasks, t) } - return out, rows.Err() + return tasks, rows.Err() } // StatusCounts returns task counts by status. -func (s *Store) StatusCounts(ctx context.Context) (map[string]int, error) { +func (s *Store) StatusCounts(ctx context.Context) (counts map[string]int, retErr error) { rows, err := s.db.QueryContext(ctx, `SELECT status, COUNT(*) FROM tasks GROUP BY status`) if err != nil { return nil, err } - defer rows.Close() - out := map[string]int{} + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() + counts = map[string]int{} for rows.Next() { var st string var n int if err := rows.Scan(&st, &n); err != nil { return nil, err } - out[st] = n + counts[st] = n } - return out, rows.Err() + return counts, rows.Err() } // WorkflowStat is one row of the per-workflow metrics table. @@ -150,7 +155,7 @@ type WorkflowStat struct { // WorkflowStats aggregates outcomes and spend per workflow — the // core "is archie getting better per dollar" table. -func (s *Store) WorkflowStats(ctx context.Context) ([]WorkflowStat, error) { +func (s *Store) WorkflowStats(ctx context.Context) (stats []WorkflowStat, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT workflow, COUNT(*), SUM(status='merged'), SUM(status='pr_open'), SUM(status='parked'), @@ -159,17 +164,18 @@ func (s *Store) WorkflowStats(ctx context.Context) ([]WorkflowStat, error) { if err != nil { return nil, err } - defer rows.Close() - var out []WorkflowStat + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var w WorkflowStat if err := rows.Scan(&w.Workflow, &w.Runs, &w.Merged, &w.PROpen, &w.Parked, &w.AvgTokens, &w.AvgSteps, &w.TotalToken); err != nil { return nil, err } - out = append(out, w) + stats = append(stats, w) } - return out, rows.Err() + return stats, rows.Err() } // StageStat is average stage duration and failure counts per stage. @@ -182,7 +188,7 @@ type StageStat struct { // StageStats aggregates stage_finish events — where does time go, and // which stages fail. -func (s *Store) StageStats(ctx context.Context) ([]StageStat, error) { +func (s *Store) StageStats(ctx context.Context) (stats []StageStat, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT workflow, stage, COUNT(*), CAST(AVG(json_extract(data,'$.duration_ms')) AS INTEGER), @@ -192,8 +198,9 @@ func (s *Store) StageStats(ctx context.Context) ([]StageStat, error) { if err != nil { return nil, err } - defer rows.Close() - var out []StageStat + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var st StageStat var avg sql.NullInt64 @@ -201,9 +208,9 @@ func (s *Store) StageStats(ctx context.Context) ([]StageStat, error) { return nil, err } st.AvgMs = int(avg.Int64) - out = append(out, st) + stats = append(stats, st) } - return out, rows.Err() + return stats, rows.Err() } // DayTokens is token spend per UTC day. @@ -213,7 +220,7 @@ type DayTokens struct { } // TokensByDay sums agent token spend per day from agent_finish events. -func (s *Store) TokensByDay(ctx context.Context, days int) ([]DayTokens, error) { +func (s *Store) TokensByDay(ctx context.Context, days int) (tokens []DayTokens, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT substr(at,1,10) AS day, CAST(SUM(json_extract(data,'$.tokens')) AS INTEGER) @@ -222,14 +229,15 @@ func (s *Store) TokensByDay(ctx context.Context, days int) ([]DayTokens, error) if err != nil { return nil, err } - defer rows.Close() - var out []DayTokens + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var d DayTokens if err := rows.Scan(&d.Day, &d.Tokens); err != nil { return nil, err } - out = append(out, d) + tokens = append(tokens, d) } - return out, rows.Err() + return tokens, rows.Err() } diff --git a/internal/store/store.go b/internal/store/store.go index 82761c20c..c29e3e439 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -63,14 +63,12 @@ func Open(path string) (*Store, error) { return nil, err } if _, err := db.Exec(schema + eventsSchema); err != nil { - db.Close() - return nil, fmt.Errorf("store: init schema: %w", err) + return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close()) } // Additive migrations; "duplicate column" means already applied. if _, err := db.Exec(`ALTER TABLE tasks ADD COLUMN watch_comment_id INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") { - db.Close() - return nil, fmt.Errorf("store: migrate: %w", err) + return nil, errors.Join(fmt.Errorf("store: migrate: %w", err), db.Close()) } return &Store{db: db}, nil } @@ -193,7 +191,7 @@ func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) } // WaitingTasks returns tasks blocked on human input. -func (s *Store) WaitingTasks(ctx context.Context) ([]Task, error) { +func (s *Store) WaitingTasks(ctx context.Context) (tasks []Task, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, owner, repo, issue_number, title, body, plan, workflow, watch_comment_id, status @@ -201,17 +199,18 @@ func (s *Store) WaitingTasks(ctx context.Context) ([]Task, error) { if err != nil { return nil, err } - defer rows.Close() - var out []Task + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var t Task if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title, &t.Body, &t.Plan, &t.Workflow, &t.WatchCommentID, &t.Status); err != nil { return nil, err } - out = append(out, t) + tasks = append(tasks, t) } - return out, rows.Err() + return tasks, rows.Err() } // Requeue puts a task back on the queue. A non-empty workflow forces it @@ -242,22 +241,23 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) { } // OpenPRs returns tasks whose PR state should be reconciled with GitHub. -func (s *Store) OpenPRs(ctx context.Context) ([]Task, error) { +func (s *Store) OpenPRs(ctx context.Context) (tasks []Task, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, owner, repo, issue_number, pr_number, status FROM tasks WHERE status='pr_open'`) if err != nil { return nil, err } - defer rows.Close() - var out []Task + defer func() { + retErr = errors.Join(retErr, rows.Close()) + }() for rows.Next() { var t Task if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber, &t.Status); err != nil { return nil, err } - out = append(out, t) + tasks = append(tasks, t) } - return out, rows.Err() + return tasks, rows.Err() } func clip(s string, n int) string { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index c05b72d97..1f797acfd 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -14,7 +14,11 @@ func openTest(t *testing.T) *Store { if err != nil { t.Fatal(err) } - t.Cleanup(func() { s.Close() }) + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Errorf("close store: %v", err) + } + }) return s } diff --git a/internal/webui/webui.go b/internal/webui/webui.go index 15a0b3e7e..976530bed 100644 --- a/internal/webui/webui.go +++ b/internal/webui/webui.go @@ -46,7 +46,7 @@ func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Write(indexHTML) + _, _ = w.Write(indexHTML) }) mux.HandleFunc("GET /api/summary", s.handleSummary) mux.HandleFunc("GET /api/tasks", s.handleTasks) diff --git a/internal/workflow/feasibility.go b/internal/workflow/feasibility.go index 9895b9783..f32277494 100644 --- a/internal/workflow/feasibility.go +++ b/internal/workflow/feasibility.go @@ -162,5 +162,7 @@ func notify(ctx context.Context, tc *TaskContext, kind string) { tc.Log.Warn("notify webhook failed", "err", err) return } - resp.Body.Close() + if err := resp.Body.Close(); err != nil { + tc.Log.Warn("close notify webhook response", "err", err) + } } diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 372b83fdf..78cc9d9e8 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -98,8 +98,8 @@ func Route(t *store.Task, reg Registry) Workflow { return wf } } - labels := strings.Split(t.Labels, ",") - for _, l := range labels { + labels := strings.SplitSeq(t.Labels, ",") + for l := range labels { switch strings.TrimSpace(l) { case "bug": if wf, ok := reg["tdd"]; ok { diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index 57147731c..c051417c3 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -132,15 +132,20 @@ func (m *Manager) ChangedLines(ctx context.Context, dir, base string) (int, erro return 0, err } total := 0 - for _, f := range strings.Fields(out) { + for f := range strings.FieldsSeq(out) { var n int if _, err := fmt.Sscanf(f, "%d", &n); err == nil { total += n } } // The first field is the file count; subtract it back out. + if strings.TrimSpace(out) == "" { + return 0, nil + } var files int - fmt.Sscanf(strings.TrimSpace(out), "%d", &files) + if _, err := fmt.Sscanf(strings.TrimSpace(out), "%d", &files); err != nil { + return 0, fmt.Errorf("parse git diff shortstat %q: %w", strings.TrimSpace(out), err) + } return total - files, nil }