From f8df051b196d45f91730defffd1666693aac089a Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 24 Jul 2026 07:42:13 +1000 Subject: [PATCH] feat: bounded concurrent task dispatch in daemon (archie-core-u64) Daemon previously processed one task at a time. Add bounded concurrent dispatch for SQLite and NATS agent modes, reusing [containers].max_concurrency (0 = unlimited). Same-repository tasks stay FIFO-serialized to avoid worktree conflicts; different repositories now run concurrently. Unblocks archie-core-l1q (NATS transport) and archie-core-g1l (per-repo allow_concurrent override). --- .beads/interactions.jsonl | 1 + .beads/issues.jsonl | 2 +- cmd/archie-agent/main.go | 20 +-- cmd/archied/main.go | 16 +- config.example.toml | 2 +- docs/prds/archie-core-v2-architecture.md | 5 +- internal/agentexec/nats.go | 26 +-- internal/agentexec/skill_test.go | 2 +- internal/agentexec/worker.go | 6 +- internal/config/config.go | 9 +- internal/container/pool.go | 6 +- internal/daemon/daemon.go | 110 ++++++++++--- internal/daemon/daemon_test.go | 152 +++++++++++++++++- internal/forge/github.go | 2 +- internal/nats/client.go | 20 +-- internal/storage/storage.go | 10 +- internal/storage/storage_test.go | 8 +- internal/webui/webui_test.go | 18 +-- internal/webui/webui_test_missing_features.go | 16 +- internal/workflow/agent.go | 5 +- internal/workflow/agent_test.go | 4 +- internal/workflow/implement_test.go | 52 ++++-- internal/workflow/skillbuild/skillbuild.go | 5 +- .../workflow/skillbuild/skillbuild_test.go | 4 +- internal/worktree/worktree.go | 2 +- 25 files changed, 366 insertions(+), 137 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index ffe7a5b3d..ea46a8ff5 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -1 +1,2 @@ {"id":"int-fe360a2002888c6426a537d2363f900d","kind":"field_change","created_at":"2026-07-22T16:37:16.342832875Z","actor":"Sam Catlow","issue_id":"archie-core-rig","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Audit complete: 58 Gitea issues (#3-#60) filed at git.catlow.cloud/sam/archie-core. 60 raw findings, 59 verified, 58 successfully filed. 8 agents hit session limit at end (webui/workflow/worktree file-phase)."}} +{"id":"int-7e16fccbb985b4942cf8bace2a8bb7d4","kind":"field_change","created_at":"2026-07-23T21:37:42.460096183Z","actor":"Sam Catlow","issue_id":"archie-core-u64","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 6ddfa8e36..00a7a1a1c 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,4 +1,4 @@ -{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T19:36:31Z","dependency_count":0,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0} {"_type":"issue","id":"archie-core-358","title":"ContainerRunner: implement agentexec.Runner against Docker for sandboxed execution","description":"Phase 2 of docs/prds/archie-core-v2-architecture.md. agentexec.Runner (InProcessRunner/SubprocessRunner) is an interface deliberately designed to be swapped for a container-backed runner without touching workflow orchestration. internal/container/pool.go already handles Docker lifecycle (pull, create, start, release, orphan recovery). Implement ContainerRunner against the existing Runner interface.","design":"Do not redesign the execution boundary — implement strictly against the existing Runner interface per its doc comments.","acceptance_criteria":"ContainerRunner implements agentexec.Runner, runs tasks in ephemeral Docker containers with workspace bind-mounted, and is selectable via [agent] mode = \"nats\" + containers.enabled = true.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:32Z","created_by":"Sam Catlow","updated_at":"2026-07-23T19:36:32Z","dependencies":[{"issue_id":"archie-core-358","depends_on_id":"archie-core-5zh","type":"blocks","created_at":"2026-07-24T05:36:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-5zh","title":"Promote archie-agent to per-task process; move workflow routing out of archied","description":"cmd/archie-agent exists but only executes one workflow stage per invocation over the internal/agentexec stdin/stdout JSON protocol (v1). Phase 1 of the PRD requires promoting it to the PRD's per-task process model, moving workflow.Route/workflow.Run out of archied and into archie-agent.","acceptance_criteria":"workflow.Route and workflow.Run execute inside archie-agent, not archied; archie-agent handles a full task (not a single stage) per invocation.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:32Z","created_by":"Sam Catlow","updated_at":"2026-07-23T19:36:32Z","dependencies":[{"issue_id":"archie-core-5zh","depends_on_id":"archie-core-l1q","type":"blocks","created_at":"2026-07-24T05:36:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-l1q","title":"NATS transport: JetStream task queue + request-reply between daemon and archie-agent","description":"Phase 1 of docs/prds/archie-core-v2-architecture.md. internal/events.Bus (in-process pub/sub, already feeding SQLite + SSE) is the natural seam to replace the transport under. Daemon publishes tasks, archie-agent consumes, results return via NATS. Preserve current inprocess mode via [agent] mode default for local dev.","design":"Add optional [nats] config block (url, token_env), default anonymous auth for single-node, credentials required for multi-node per PRD sec.9 open question 2.","acceptance_criteria":"Daemon can dispatch a task to archie-agent over NATS JetStream and receive results via request-reply; inprocess mode still works unchanged.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T19:36:31Z","dependencies":[{"issue_id":"archie-core-l1q","depends_on_id":"archie-core-u64","type":"blocks","created_at":"2026-07-24T05:36:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index c0275fe06..3c8010515 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -67,10 +67,10 @@ func run() int { } stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{ - Name: streamName, - Subjects: []string{"archie.task.>", "archie.agent.>"}, - Storage: jetstream.FileStorage, - Retention: jetstream.WorkQueuePolicy, + Name: streamName, + Subjects: []string{"archie.task.>", "archie.agent.>"}, + Storage: jetstream.FileStorage, + Retention: jetstream.WorkQueuePolicy, Duplicates: dedupWindow, }) if err != nil { @@ -79,12 +79,12 @@ func run() int { } cons, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{ - Name: *consumer, - Durable: *consumer, - FilterSubject: arnats.SubjectAgentWildcard, - AckPolicy: jetstream.AckExplicitPolicy, - MaxDeliver: 3, - AckWait: ackWait, + Name: *consumer, + Durable: *consumer, + FilterSubject: arnats.SubjectAgentWildcard, + AckPolicy: jetstream.AckExplicitPolicy, + MaxDeliver: 3, + AckWait: ackWait, InactiveThreshold: 24 * time.Hour, }) if err != nil { diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 2c0bad0c6..760bd5fc4 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -14,6 +14,7 @@ import ( "path/filepath" "syscall" + "github.com/moby/moby/client" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" @@ -21,7 +22,6 @@ import ( "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/nats" - "github.com/moby/moby/client" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" @@ -138,7 +138,7 @@ func run() int { defer dockerCli.Close() containerPool, err = container.NewPool(ctx, container.Config{ - Image: cfg.Containers.Image, + Image: cfg.Containers.Image, MaxConcurrency: cfg.Containers.MaxConcurrency, MaxUptime: cfg.Containers.MaxUptime.Std(), PullPolicy: cfg.Containers.PullPolicy, @@ -222,15 +222,15 @@ func run() int { BotEmail: cfg.BotEmail, BaseURL: cfg.Forge.Host, }, - Runtime: llm, - Agent: agentRunner, + Runtime: llm, + Agent: agentRunner, Workflows: registry, PluginRegistry: pluginReg, Storage: storeBackend, - Log: log, - CustomStages: wfeval.Discover, - Nats: natsClient, - ContainerPool: containerPool, + Log: log, + CustomStages: wfeval.Discover, + Nats: natsClient, + ContainerPool: containerPool, } if err := d.Startup(ctx); err != nil { diff --git a/config.example.toml b/config.example.toml index f727b1af7..476a167b1 100644 --- a/config.example.toml +++ b/config.example.toml @@ -67,7 +67,7 @@ gate_max_failures = 5 # [containers] # enabled = true # image = "archie-agent:latest" # Docker image to run -# max_concurrency = 4 # max simultaneous containers +# max_concurrency = 4 # max simultaneous tasks/containers # max_uptime = "60m" # container lifetime cap # pull_policy = "missing" # "missing" or "always" diff --git a/docs/prds/archie-core-v2-architecture.md b/docs/prds/archie-core-v2-architecture.md index 0126531f4..ab76abfc1 100644 --- a/docs/prds/archie-core-v2-architecture.md +++ b/docs/prds/archie-core-v2-architecture.md @@ -13,7 +13,7 @@ This document describes a target end state. The table below is the ground truth; | Area | Status | What actually exists today (post-e4d11b1) | |---|---|---| | Daemon/agent binary split | **Implemented** | `cmd/archied` and `cmd/archie-agent` both exist. `archie-agent` is a 189-line NATS-connected per-task worker that subscribes to task subjects, runs the full multi-stage workflow, and reports results. Workflow routing and sequencing (`workflow.Route`, `workflow.Run`) now run inside the agent, not the daemon. Three agent modes: `inprocess`, `subprocess`, `nats`. | -| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. `max_concurrency` enforced. | +| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. Daemon dispatch and container lifecycle both enforce `max_concurrency`; same-repo tasks remain serialized. | | NATS / JetStream messaging | **Implemented** | `internal/nats/client.go` (176 lines): JetStream connect, stream creation (WorkQueue retention, file storage), pull consumer (durable, ack-wait 5min, max-deliver 3, dedup by Msg-Id), `PublishTask`, `Fetch`, `NewReplyInbox`. Subject hierarchy in `internal/nats/subjects.go`. `[nats]` config block in config.go. `internal/agentexec/nats.go` implements NATS-based agent runner. | | Docker container sandbox | **Implemented** | `internal/container/pool.go` (210 lines): Docker API client, image pull (always/missing/never), container create with workspace bind mount, start, release (stop+remove), orphan recovery on daemon restart. `Dockerfile` at repo root builds archie-agent fat image. `[containers]` config block: enabled, image, max_concurrency, max_uptime, pull_policy. `agent.mode = "nats"` required when containers enabled. | | `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the worktree at `/data/worktree`. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. Worktrees are still ephemeral fresh clones per task. | @@ -459,7 +459,8 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen - Daemon container lifecycle: spawn, volume create, env inject, kill -- not started - Persistent volumes with TTL -- not started (current worktree lifecycle is fresh-clone-per-task with status-driven cleanup, no TTL) -- `max_concurrency` enforcement -- not started (daemon processes one task at a time today) +- ~~`max_concurrency` enforcement~~ -- **done**: SQLite and NATS drains dispatch different repositories concurrently + up to `[containers].max_concurrency`; same-repo tasks remain serialized by default. - Grace period `max_uptime` -- not started - **Groundwork already in place:** `agentexec.Runner` (`InProcessRunner`/`SubprocessRunner`) is an interface designed, per its own doc comments, to be swapped for a container-backed runner without touching workflow orchestration -- diff --git a/internal/agentexec/nats.go b/internal/agentexec/nats.go index 50d05dd32..91cd6095e 100644 --- a/internal/agentexec/nats.go +++ b/internal/agentexec/nats.go @@ -17,24 +17,24 @@ import ( // When Workflow is set and Stages is populated, the agent runs all stages as a // per-task batch rather than a single stage. PRD §1. type AgentRequestMessage struct { - TaskID int64 `json:"task_id"` - Attempt int `json:"attempt"` - Stage string `json:"stage"` - Workflow string `json:"workflow,omitempty"` - Channel string `json:"channel,omitempty"` // "response" (default) or "system" - Workspace string `json:"workspace"` - Request Request `json:"request"` - Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Stage string `json:"stage"` + Workflow string `json:"workflow,omitempty"` + Channel string `json:"channel,omitempty"` // "response" (default) or "system" + Workspace string `json:"workspace"` + Request Request `json:"request"` + Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task Providers map[string]Provider `json:"providers,omitempty"` } // AgentResponseEnvelope is the response payload published to the reply inbox. type AgentResponseEnvelope struct { - Version int `json:"version"` - Result Result `json:"result"` - Error string `json:"error,omitempty"` - Channel string `json:"channel,omitempty"` // "response" (default) or "system" - TaskCompleted bool `json:"task_completed,omitempty"` // true when all stages finished (per-task mode) + Version int `json:"version"` + Result Result `json:"result"` + Error string `json:"error,omitempty"` + Channel string `json:"channel,omitempty"` // "response" (default) or "system" + TaskCompleted bool `json:"task_completed,omitempty"` // true when all stages finished (per-task mode) } const defaultAgentTimeout = 30 * time.Minute diff --git a/internal/agentexec/skill_test.go b/internal/agentexec/skill_test.go index 42a087976..7d2c00fc3 100644 --- a/internal/agentexec/skill_test.go +++ b/internal/agentexec/skill_test.go @@ -76,7 +76,7 @@ Analyse the bug. Write repro tests. Fix. Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "analyse", Model: "test/model", Mission: alreadyPrepended, - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1, MaxTokens: 10}, }, Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}, } diff --git a/internal/agentexec/worker.go b/internal/agentexec/worker.go index 18446062f..844aa829a 100644 --- a/internal/agentexec/worker.go +++ b/internal/agentexec/worker.go @@ -130,9 +130,9 @@ func runStages(ctx context.Context, runner Runner, msg AgentRequestMessage, chan } return &AgentResponseEnvelope{ - Version: lastResult.Version, - Result: lastResult, - Channel: channel, + Version: lastResult.Version, + Result: lastResult, + Channel: channel, TaskCompleted: lastResult.Status == StatusPassed, }, nil } diff --git a/internal/config/config.go b/internal/config/config.go index b05fd841c..df94c5708 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -222,13 +222,13 @@ func (d Dispatch) LabelValues() []string { // Config is the daemon configuration. type Config struct { - WorkDir string `toml:"work_dir"` + WorkDir string `toml:"work_dir"` // SkillsDir is an optional path to a shared skills directory // containing .agents/skills/*/SKILL.md files. When set, the // daemon builds its workflow registry from the skill catalog // (plugin-defined workflows override built-ins). When empty, // only built-in workflows are available. - SkillsDir string `toml:"skills_dir"` + SkillsDir string `toml:"skills_dir"` // MaxRetries caps how many times a parked task is retried before // being permanently parked (status "dead"). Defaults to 3. MaxRetries int `toml:"max_retries"` @@ -258,7 +258,7 @@ type Config struct { Providers map[string]Provider `toml:"providers"` Agent Agent `toml:"agent"` - Budgets Budgets `toml:"budgets"` + Budgets Budgets `toml:"budgets"` Web Web `toml:"web"` Notify Notify `toml:"notify"` NATS NATSConfig `toml:"nats"` @@ -283,7 +283,8 @@ type ContainerConfig struct { Enabled bool `toml:"enabled"` // Image is the Docker image to run (e.g. "ghcr.io/sam/archie-agent:latest"). Image string `toml:"image"` - // MaxConcurrency limits simultaneous containers. 0 = no limit. + // MaxConcurrency limits simultaneous daemon tasks and containers. + // Tasks from the same repository remain serialized. 0 = no limit. MaxConcurrency int `toml:"max_concurrency"` // MaxUptime caps a container's lifetime before recycling. MaxUptime Duration `toml:"max_uptime"` diff --git a/internal/container/pool.go b/internal/container/pool.go index 9482f4313..a8c7e553c 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -76,7 +76,7 @@ type Config struct { // container is killed. The agent stays alive to handle follow-ups // (gate re-runs, human replies) during this window. PRD §1. GracePeriod time.Duration - PullPolicy string + PullPolicy string // DockerClient is an optional pre-connected Docker client. When nil, // NewPool creates its own via client.New(client.FromEnv). Pass a // shared client to avoid multiple independent connections. @@ -211,7 +211,7 @@ func (p *Pool) Close() error { defer cancel() list, err := p.cli.ContainerList(ctx, client.ContainerListOptions{ - All: true, + All: true, Filters: client.Filters{}.Add("label", "archie-daemon=true"), }) if err != nil { @@ -258,7 +258,7 @@ func (p *Pool) pullImage(ctx context.Context) error { // recoverOrphans stops and removes containers left by a previous daemon. func (p *Pool) recoverOrphans(ctx context.Context) { list, err := p.cli.ContainerList(ctx, client.ContainerListOptions{ - All: true, + All: true, Filters: client.Filters{}.Add("label", "archie-daemon=true"), }) if err != nil { diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f67e43542..272ce362d 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1,7 +1,6 @@ // Package daemon is archied's resident loop: poll GitHub for labelled -// issues, enqueue them, and process one task at a time through its -// routed workflow. State lives in the store; the daemon is restartable -// at any point. +// issues, enqueue them, and process tasks through their routed workflows. +// State lives in the store; the daemon is restartable at any point. package daemon import ( @@ -11,6 +10,7 @@ import ( "os" "slices" "strings" + "sync" "time" "github.com/samcharles93/ai-sdk/core" @@ -108,7 +108,7 @@ func (d *Daemon) Run(ctx context.Context) error { // Cycle is one poll-and-drain pass: enqueue newly assigned issues, // reconcile open PRs, act on human replies to waiting tasks, then -// process every queued task sequentially. +// process queued tasks concurrently up to containers.max_concurrency. func (d *Daemon) Cycle(ctx context.Context) { d.poll(ctx) d.reconcilePRs(ctx) @@ -120,52 +120,118 @@ func (d *Daemon) Cycle(ctx context.Context) { } } -// drainSQLite processes queued tasks from SQLite (existing behaviour). +// drainSQLite claims queued tasks from SQLite and dispatches them concurrently. func (d *Daemon) drainSQLite(ctx context.Context) { - for { - if ctx.Err() != nil { - return - } + dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency) + for ctx.Err() == nil { task, err := d.Store.ClaimNext(ctx) if err != nil { d.Log.Error("claim failed", "err", err) - return + break } if task == nil { - return + break } - d.process(ctx, task) + dispatcher.Submit(ctx, task, d.process) } + dispatcher.Wait() } // drainNATS processes tasks from NATS, falling back to SQLite ClaimNext for // requeued tasks (waiting_human approval, retry-parked) that didn't come // through a NATS publish. func (d *Daemon) drainNATS(ctx context.Context) { - for { - if ctx.Err() != nil { - return - } + dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency) + for ctx.Err() == nil { msg, err := d.Nats.Fetch(ctx) if err != nil { d.Log.Error("nats fetch failed", "err", err) - return + break } if msg != nil { - d.processNATSTask(ctx, msg) + tm, err := arnats.DecodeTask(msg) + if err != nil { + d.Log.Error("nats decode failed", "err", err) + _ = msg.Ack() // bad message, don't retry + continue + } + task := &store.Task{Owner: tm.Owner, Repo: tm.Repo} + dispatcher.Submit(ctx, task, func(ctx context.Context, _ *store.Task) { + d.processNATSTask(ctx, msg) + }) continue } // Fall back to SQLite for requeued tasks. task, err := d.Store.ClaimNext(ctx) if err != nil { d.Log.Error("sqlite claim failed", "err", err) - return + break } if task == nil { - return + break } - d.process(ctx, task) + dispatcher.Submit(ctx, task, d.process) } + dispatcher.Wait() +} + +// taskDispatcher bounds task execution globally while preserving the default +// one-task-per-repository safety rule. Submit order is retained within a repo; +// tasks for different repos may run concurrently. +type taskDispatcher struct { + slots chan struct{} + + mu sync.Mutex + repoTail map[string]chan struct{} + wg sync.WaitGroup +} + +func newTaskDispatcher(maxConcurrency int) *taskDispatcher { + var slots chan struct{} + if maxConcurrency > 0 { + slots = make(chan struct{}, maxConcurrency) + } + return &taskDispatcher{ + slots: slots, + repoTail: make(map[string]chan struct{}), + } +} + +func (d *taskDispatcher) Submit( + ctx context.Context, + task *store.Task, + process func(context.Context, *store.Task), +) { + repo := task.Owner + "/" + task.Repo + done := make(chan struct{}) + + d.mu.Lock() + previous := d.repoTail[repo] + d.repoTail[repo] = done + d.mu.Unlock() + + d.wg.Go(func() { + if previous != nil { + <-previous + } + if d.slots != nil { + d.slots <- struct{}{} + defer func() { <-d.slots }() + } + defer func() { + close(done) + d.mu.Lock() + if d.repoTail[repo] == done { + delete(d.repoTail, repo) + } + d.mu.Unlock() + }() + process(ctx, task) + }) +} + +func (d *taskDispatcher) Wait() { + d.wg.Wait() } func (d *Daemon) poll(ctx context.Context) { @@ -569,7 +635,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { if err := container.WriteTaskJSON(workDir, container.TaskPayload{ ID: task.ID, Owner: task.Owner, Repo: task.Repo, Number: task.IssueNumber, Title: task.Title, Body: task.Body, - Labels: strings.Split(task.Labels, ","), + Labels: strings.Split(task.Labels, ","), Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan, }); err != nil { d.Log.Error("task.json write failed", "err", err) diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 3649e88dd..d0d28e6b9 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -5,13 +5,141 @@ import ( "log/slog" "os" "strings" + "sync/atomic" "testing" + "time" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/store" ) +func TestTaskDispatcherEnforcesMaxConcurrency(t *testing.T) { + t.Parallel() + + const maxConcurrency = 2 + dispatcher := newTaskDispatcher(maxConcurrency) + release := make(chan struct{}) + started := make(chan int, 3) + var active atomic.Int32 + var peak atomic.Int32 + + for i := 1; i <= 3; i++ { + task := &store.Task{Owner: "sam", Repo: "repo-" + string(rune('0'+i))} + dispatcher.Submit(context.Background(), task, func(context.Context, *store.Task) { + n := active.Add(1) + for { + old := peak.Load() + if n <= old || peak.CompareAndSwap(old, n) { + break + } + } + started <- i + <-release + active.Add(-1) + }) + } + + for range maxConcurrency { + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("tasks did not start up to max_concurrency") + } + } + select { + case task := <-started: + t.Fatalf("task %d started before a concurrency slot was available", task) + case <-time.After(50 * time.Millisecond): + } + + close(release) + dispatcher.Wait() + + if got := peak.Load(); got != maxConcurrency { + t.Fatalf("peak concurrency = %d, want %d", got, maxConcurrency) + } + select { + case <-started: + default: + t.Fatal("queued task never started after a concurrency slot became available") + } +} + +func TestTaskDispatcherSerializesTasksForSameRepo(t *testing.T) { + t.Parallel() + + dispatcher := newTaskDispatcher(3) + releaseFirst := make(chan struct{}) + firstStarted := make(chan struct{}) + secondStarted := make(chan struct{}) + otherRepoStarted := make(chan struct{}) + + dispatcher.Submit(context.Background(), &store.Task{Owner: "sam", Repo: "archie"}, func(context.Context, *store.Task) { + close(firstStarted) + <-releaseFirst + }) + dispatcher.Submit(context.Background(), &store.Task{Owner: "sam", Repo: "archie"}, func(context.Context, *store.Task) { + close(secondStarted) + }) + dispatcher.Submit(context.Background(), &store.Task{Owner: "sam", Repo: "tau"}, func(context.Context, *store.Task) { + close(otherRepoStarted) + }) + + for name, started := range map[string]<-chan struct{}{ + "first same-repo task": firstStarted, + "other-repo task": otherRepoStarted, + } { + select { + case <-started: + case <-time.After(time.Second): + t.Fatalf("%s did not start", name) + } + } + select { + case <-secondStarted: + t.Fatal("second task for the same repo ran concurrently") + case <-time.After(50 * time.Millisecond): + } + + close(releaseFirst) + dispatcher.Wait() + + select { + case <-secondStarted: + default: + t.Fatal("second same-repo task did not start after the first completed") + } +} + +func TestTaskDispatcherWaitsForRunningTasks(t *testing.T) { + t.Parallel() + + dispatcher := newTaskDispatcher(1) + release := make(chan struct{}) + dispatcher.Submit(context.Background(), &store.Task{Owner: "sam", Repo: "archie"}, func(context.Context, *store.Task) { + <-release + }) + + waited := make(chan struct{}) + go func() { + dispatcher.Wait() + close(waited) + }() + + select { + case <-waited: + t.Fatal("Wait returned while a task was still running") + case <-time.After(50 * time.Millisecond): + } + close(release) + select { + case <-waited: + case <-time.After(time.Second): + t.Fatal("Wait did not return after the running task completed") + } +} + func TestHasLabelUsesExactNames(t *testing.T) { labels := []string{"bug", "archie:parked-old", "feature", "custom,label"} if hasLabel(labels, "archie:parked") { @@ -54,24 +182,36 @@ func (f *testForge) SetStateLabel(_ context.Context, owner, repo string, number f.stateLabels = append(f.stateLabels, stateLabelCall{owner, repo, number, label, knownLabels}) } -func (f *testForge) AcceptInvitations(context.Context) error { return nil } +func (f *testForge) AcceptInvitations(context.Context) error { return nil } func (f *testForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) { panic("unexpected call") } + func (f *testForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) { panic("unexpected call") } + func (f *testForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) { panic("unexpected call") } + func (f *testForge) CreatePR(context.Context, string, string, string, string, string, string) (int, error) { panic("unexpected call") } -func (f *testForge) PRState(context.Context, string, string, int) (string, error) { panic("unexpected call") } -func (f *testForge) CloseIssue(context.Context, string, string, int, string) error { panic("unexpected call") } -func (f *testForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) { return 0, nil } -func (f *testForge) React(context.Context, string, string, int, string) error { return nil } -func (f *testForge) VerifyPush(context.Context, string, string) error { return nil } + +func (f *testForge) PRState(context.Context, string, string, int) (string, error) { + panic("unexpected call") +} + +func (f *testForge) CloseIssue(context.Context, string, string, int, string) error { + panic("unexpected call") +} + +func (f *testForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) { + return 0, nil +} +func (f *testForge) React(context.Context, string, string, int, string) error { return nil } +func (f *testForge) VerifyPush(context.Context, string, string) error { return nil } func testDaemon(t *testing.T, maxRetries int, _ int) (*Daemon, *store.Store, *testForge) { t.Helper() diff --git a/internal/forge/github.go b/internal/forge/github.go index 51703c4f6..9298d555b 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -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.String("closed")}) + &github.IssueRequest{State: new("closed")}) return err } diff --git a/internal/nats/client.go b/internal/nats/client.go index 63e2937bb..b848e34d5 100644 --- a/internal/nats/client.go +++ b/internal/nats/client.go @@ -53,10 +53,10 @@ func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error) } stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{ - Name: streamName, - Subjects: []string{"archie.task.>", "archie.agent.>"}, - Storage: jetstream.FileStorage, - Retention: jetstream.WorkQueuePolicy, + Name: streamName, + Subjects: []string{"archie.task.>", "archie.agent.>"}, + Storage: jetstream.FileStorage, + Retention: jetstream.WorkQueuePolicy, Duplicates: dedupWindow, }) if err != nil { @@ -65,12 +65,12 @@ func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error) } consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{ - Name: consumerName, - Durable: consumerName, - FilterSubject: "archie.task.>", - AckPolicy: jetstream.AckExplicitPolicy, - MaxDeliver: 3, - AckWait: 5 * time.Minute, + Name: consumerName, + Durable: consumerName, + FilterSubject: "archie.task.>", + AckPolicy: jetstream.AckExplicitPolicy, + MaxDeliver: 3, + AckWait: 5 * time.Minute, InactiveThreshold: 24 * time.Hour, }) if err != nil { diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 465303c9c..2bd4de8e9 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -42,11 +42,11 @@ import ( // TaskRef identifies a task for storage setup. type TaskRef struct { - Owner, Repo string - IssueNumber int - Ecosystem string // "go", "node", "python", "rust", "custom" - WorktreeDir string // host path to the git worktree - PersistentStorage bool // if true, attach a per-repo Docker volume at /data/repo + Owner, Repo string + IssueNumber int + Ecosystem string // "go", "node", "python", "rust", "custom" + WorktreeDir string // host path to the git worktree + PersistentStorage bool // if true, attach a per-repo Docker volume at /data/repo } // Mount describes a container mount point. diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index b0fcaf2a4..8e660ffa1 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -3,6 +3,7 @@ package storage import ( "context" "os" + "slices" "sort" "testing" ) @@ -435,10 +436,5 @@ func mountDestinations(mounts []Mount) []string { } func contains(slice []string, s string) bool { - for _, v := range slice { - if v == s { - return true - } - } - return false + return slices.Contains(slice, s) } diff --git a/internal/webui/webui_test.go b/internal/webui/webui_test.go index 8d9f527bc..bedd78c69 100644 --- a/internal/webui/webui_test.go +++ b/internal/webui/webui_test.go @@ -151,16 +151,16 @@ func TestIndexHasResponsiveFeatures(t *testing.T) { t.Fatalf("status = %d", w.Code) } body := w.Body.String() - reqs := []struct{ - name string - want string + reqs := []struct { + name string + want string }{ - {"section-table", ".section-table { overflow-x: auto; }"}, - {"feed-wraps", "white-space: normal"}, - {"feed-break-word", "overflow-wrap: break-word"}, - {"700px-breakpoint", "@media (max-width: 700px)"}, - {"950px-breakpoint", "@media (max-width: 950px)"}, - {"viewport-meta", ``}, + {"section-table", ".section-table { overflow-x: auto; }"}, + {"feed-wraps", "white-space: normal"}, + {"feed-break-word", "overflow-wrap: break-word"}, + {"700px-breakpoint", "@media (max-width: 700px)"}, + {"950px-breakpoint", "@media (max-width: 950px)"}, + {"viewport-meta", ``}, } for _, r := range reqs { if !strings.Contains(body, r.want) { diff --git a/internal/webui/webui_test_missing_features.go b/internal/webui/webui_test_missing_features.go index b4ae736e2..6c7e7ab6c 100644 --- a/internal/webui/webui_test_missing_features.go +++ b/internal/webui/webui_test_missing_features.go @@ -1,4 +1,4 @@ -// +build ignore +//go:build ignore package webui @@ -16,14 +16,14 @@ func TestIndexHasResponsiveFeatures(t *testing.T) { t.Fatalf("status = %d", w.Code) } body := w.Body.String() - reqs := []struct{ - name string - want string + reqs := []struct { + name string + want string }{ - {"mobile-font-padding", "section { min-height: 1.25rem; }"}, - {"table-wrap", "section .table-wrap { position: relative; overflow-x: auto;"}, - {"feed-wraps", "white-space: normal"}, - {"700px-breakpoint", "@media (max-width: 700px)"}, + {"mobile-font-padding", "section { min-height: 1.25rem; }"}, + {"table-wrap", "section .table-wrap { position: relative; overflow-x: auto;"}, + {"feed-wraps", "white-space: normal"}, + {"700px-breakpoint", "@media (max-width: 700px)"}, } for _, r := range reqs { if !strings.Contains(body, r.want) { diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index a03724389..245d4f49f 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -120,8 +120,8 @@ func (a AgentStage) Stage() Stage { Protection: protection, Notes: tc.Task.Notes, CaptureTools: captureTools, - Plugins: pluginSpecs(tc.SkillPlugins), - } + Plugins: pluginSpecs(tc.SkillPlugins), + } res, err := tc.Agent.Run(ctx, tc.Dir, req) if err != nil && res.Version == 0 { return fmt.Errorf("agent run: %w", err) @@ -218,4 +218,3 @@ func loadSkillBody(tc *TaskContext) string { } return body } - diff --git a/internal/workflow/agent_test.go b/internal/workflow/agent_test.go index facd357cf..d57970f9a 100644 --- a/internal/workflow/agent_test.go +++ b/internal/workflow/agent_test.go @@ -204,9 +204,9 @@ func TestReviewResultBlocksOnResultWhenRejected(t *testing.T) { }, }.Stage() tc := &TaskContext{ - Task: &store.Task{ID: 1, Attempt: 1}, + Task: &store.Task{ID: 1, Attempt: 1}, Agent: runner, Log: slog.New(slog.DiscardHandler), - Cfg: config.Config{Models: map[string]string{"planner": "provider/model"}}, + Cfg: config.Config{Models: map[string]string{"planner": "provider/model"}}, } err := rejectStage.Run(context.Background(), tc) if err == nil { diff --git a/internal/workflow/implement_test.go b/internal/workflow/implement_test.go index 7ae128fb6..9b2067eb6 100644 --- a/internal/workflow/implement_test.go +++ b/internal/workflow/implement_test.go @@ -15,22 +15,48 @@ type fakeForge struct { commented []string } -func (f *fakeForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { f.closed++; return nil } +func (f *fakeForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { + f.closed++ + return nil +} + func (f *fakeForge) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { f.commented = append(f.commented, body) return 0, nil } + // Remaining forge.Forge stubs — only CloseIssue and Comment are used by StageCommitPush. -func (f *fakeForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) { return 0, nil } -func (f *fakeForge) Name() string { return "fake" } +func (f *fakeForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) { + return 0, nil +} +func (f *fakeForge) Name() string { return "fake" } func (f *fakeForge) AcceptInvitations(ctx context.Context) error { return nil } -func (f *fakeForge) AssignedIssues(ctx context.Context, owner, repo, user string) ([]forge.Issue, error) { return nil, nil } -func (f *fakeForge) IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]forge.Issue, error) { return nil, nil } -func (f *fakeForge) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) { return 0, nil } -func (f *fakeForge) PRState(ctx context.Context, owner, repo string, number int) (string, error) { return "", nil } -func (f *fakeForge) React(ctx context.Context, owner, repo string, number int, reaction string) error { return nil } -func (f *fakeForge) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]forge.Reply, error) { return nil, nil } -func (f *fakeForge) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, known []string) {} +func (f *fakeForge) AssignedIssues(ctx context.Context, owner, repo, user string) ([]forge.Issue, error) { + return nil, nil +} + +func (f *fakeForge) IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]forge.Issue, error) { + return nil, nil +} + +func (f *fakeForge) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) { + return 0, nil +} + +func (f *fakeForge) PRState(ctx context.Context, owner, repo string, number int) (string, error) { + return "", nil +} + +func (f *fakeForge) React(ctx context.Context, owner, repo string, number int, reaction string) error { + return nil +} + +func (f *fakeForge) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]forge.Reply, error) { + return nil, nil +} + +func (f *fakeForge) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, known []string) { +} func (f *fakeForge) VerifyPush(ctx context.Context, owner, repo string) error { return nil } // TestStageCommitPushClosesIssueWhenBuildNoChanges verifies that @@ -47,9 +73,9 @@ func TestStageCommitPushClosesIssueWhenBuildNoChanges(t *testing.T) { Forge: f, BuildSummary: "already fixed", BuildNoChanges: true, - Dir: "/tmp/test", - Branch: "archie/issue-1", - Task: &store.Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, + Dir: "/tmp/test", + Branch: "archie/issue-1", + Task: &store.Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, } err := stage.Run(context.Background(), tc) diff --git a/internal/workflow/skillbuild/skillbuild.go b/internal/workflow/skillbuild/skillbuild.go index 7e2cd074e..ff5aac1b0 100644 --- a/internal/workflow/skillbuild/skillbuild.go +++ b/internal/workflow/skillbuild/skillbuild.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "log/slog" + "maps" "os" "path/filepath" "sort" @@ -101,9 +102,7 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry // Copy base — never mutate the caller's registry. reg := make(workflow.Registry, len(base)+len(catalog)) - for k, v := range base { - reg[k] = v - } + maps.Copy(reg, base) for _, entry := range catalog { if entry.Workflow == "" { diff --git a/internal/workflow/skillbuild/skillbuild_test.go b/internal/workflow/skillbuild/skillbuild_test.go index 2d8dffb96..70a193578 100644 --- a/internal/workflow/skillbuild/skillbuild_test.go +++ b/internal/workflow/skillbuild/skillbuild_test.go @@ -622,7 +622,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { // Run 10 concurrent augmentations — none should panic or corrupt state. errs := make(chan error, 10) - for i := 0; i < 10; i++ { + for range 10 { go func() { aug, err := AugmentRegistry(worktree, base) if err != nil { @@ -636,7 +636,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { errs <- nil }() } - for i := 0; i < 10; i++ { + for range 10 { if err := <-errs; err != nil { t.Error("concurrent AugmentRegistry failed:", err) } diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index 96f9253a9..a99fb8390 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -131,7 +131,7 @@ func archieBranch(issue int, title, body, labels string) string { // labels, then falls back to "feat". Maps: bug→fix, feature→feat, // enhancement→feat, docs→docs, chore→chore, test→test. func branchPrefix(title, body, labels string) string { - for _, l := range strings.Split(labels, ",") { + for l := range strings.SplitSeq(labels, ",") { switch strings.TrimSpace(strings.ToLower(l)) { case "bug": return "fix"