From 75f237d1adb48b55e7ae66006a333257746da3cb Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 24 Jul 2026 09:14:56 +1000 Subject: [PATCH] feat: daemon hands off tasks to archie-agent in sandboxed mode (archie-core-5zh.8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit daemon.process() branches on ContainerPool != nil: sandboxed tasks publish a taskrun.Request to archie.taskrun. and await the response via the new runViaAgent method, instead of running workflow.Route/workflow.Run locally. Non-container mode is unchanged. Every durable side effect (Store, Forge, git push) already landed via the storerpc/forgerpc/ worktreerpc proxies during archie-agent's run by the time runViaAgent returns — it only parks the task itself on transport/setup failure, never duplicating a terminal state archie-agent's own workflow.Run already recorded. Also fixes a real correctness gap: with concurrent multi-task dispatch (archie-core-u64/g1l) plus containerized archie-agent, a shared queue-group subscription could let one container answer a sibling's taskrun message while having a *different* task's worktree mounted. archie-agent now reads its boot-time task.json and subscribes to its own exact per-task subject when present, falling back to the shared queue group only in dev/pool mode (no task.json). Adds agentexec.ProvidersFromConfig, deduped from cmd/archied's former executionProviders. Closes the archie-core-5zh epic: archie-agent runs an entire task's workflow per invocation instead of one stage per round trip, with all credentials staying daemon-side throughout. --- .beads/interactions.jsonl | 1 + .beads/issues.jsonl | 2 +- cmd/archie-agent/main.go | 44 +++++++- cmd/archie-agent/main_test.go | 59 ++++++++++- cmd/archied/main.go | 6 +- internal/agentexec/providers.go | 14 +++ internal/agentexec/providers_test.go | 26 +++++ internal/daemon/daemon.go | 80 +++++++++++--- internal/daemon/daemon_test.go | 153 +++++++++++++++++++++++++++ 9 files changed, 363 insertions(+), 22 deletions(-) create mode 100644 internal/agentexec/providers.go create mode 100644 internal/agentexec/providers_test.go diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 9a8199465..86cec6d74 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -10,3 +10,4 @@ {"id":"int-5834a8b380a56b2badadcf9575e40716","kind":"field_change","created_at":"2026-07-23T22:56:17.803871719Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.6","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Trimmed workflow.TaskContext.Forge/Store/Trees to new interfaces (Forger, TaskStore, Trees) in internal/workflow/workflow.go, scoped to exactly the methods stages call mid-run (4 Forge methods, 2 Store methods, 6 Trees methods). Go's structural typing meant zero changes were needed anywhere else — forge.Forge (already an interface), *store.Store, and *worktree.Manager all satisfy the new interfaces automatically, and storerpc.Client/forgerpc.Client/worktreerpc.Client already match by construction from 5zh.1-3. Full build, race suite, vet, and staticcheck all clean with no behavior change. archie-core-5zh.7 (archie-agent full-task handler) and 5zh.9 (register RPC servers in archied) are now unblocked."}} {"id":"int-e854b54f66c451e2fe7bba43a2debaf0","kind":"field_change","created_at":"2026-07-23T22:58:57.94105369Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added registerTaskRPCServers() in cmd/archied/main.go, wiring storerpc.Server/forgerpc.Server/worktreerpc.Server onto the daemon's NATS connection whenever [nats] is configured, alongside the existing worktree.Manager and forge/store instances the daemon already owns. Test spins an embedded NATS server, registers via the composed function, then round-trips real storerpc/forgerpc/worktreerpc clients against it to prove all three are reachable. archie-core-5zh.7 (archie-agent full-task handler) can now be built and tested end-to-end against a real archied."}} {"id":"int-d3c2080053c72c054c32f4d5befd2be0","kind":"field_change","created_at":"2026-07-23T23:08:11.15292258Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.7","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Added internal/taskrun (Request/Response wire types + SubjectForTask) and cmd/archie-agent/taskrun.go: runTask builds a workflow.Registry from the container's own bind-mounted worktree (skillbuild.BuildRegistry, same call the daemon already makes), routes and runs the task's entire workflow via workflow.Route/workflow.Run, using storerpc.Client/forgerpc.Client for Store/Forge and a new hybridTrees (worktreerpc.Client for Prepare/Push, local *worktree.Manager for CommitAll/Diff/ChangedFiles/ChangedLines against the mount). Added config.TaskConfig.ToConfig() to rebuild a usable config.Config from the curated payload. Added storage.WorktreeMountDir constant (/data/worktree) — critical fix: hybridTrees.Prepare discards the RPC response's host-side directory and returns the container's fixed local mount path instead, since archied and archie-agent see the same files at different paths. Wired a queue-grouped core-NATS subscription on archie.taskrun.> in cmd/archie-agent/main.go so this is reachable in the running binary, not just testable in isolation. End-to-end test drives the real 'bootstrap' workflow (no LLM) through real storerpc/forgerpc/worktreerpc servers and a real local git remote, proving the full chain: registry build, route, prepare, commit, push, PR creation, and that the authoritative task state lands in archied's store via RPC. archie-core-5zh.8 (daemon.go handoff) is now unblocked — it owns deciding exactly how/when archied publishes to archie.taskrun.."}} +{"id":"int-029f2aa8429c3fd67bdc1541fd78f9c3","kind":"field_change","created_at":"2026-07-23T23:14:48.198047941Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.8","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"daemon.process() now branches on d.ContainerPool != nil: sandboxed tasks get handed to archie-agent via a new runViaAgent method (publishes taskrun.Request to archie.taskrun., awaits taskrun.Response) instead of calling workflow.Route/workflow.Run locally; non-container mode is unchanged. runViaAgent only parks the task itself on transport/setup failure (encode error, no responder, decode error, or an error returned before archie-agent's workflow.Run got to run) — on success, every durable side effect already landed via the storerpc/forgerpc/worktreerpc proxies during archie-agent's run, so runViaAgent just logs. Added agentexec.ProvidersFromConfig (deduped from cmd/archied's former executionProviders). Also fixed a real correctness gap this surfaced: with concurrent multi-task dispatch (u64/g1l) plus containerized archie-agent, the 5zh.7 wildcard queue-group subscription could let one container answer a sibling's taskrun message despite having a different task's worktree mounted. archie-agent now reads its boot-time task.json (container.TaskPayload, already written by daemon.process() before container acquire) and subscribes to its own exact archie.taskrun. subject when present, falling back to the shared queue group only when no task.json exists (dev/pool mode). Full container-mode integration (real Docker) isn't covered by an automated test, consistent with the rest of the container-dependent code — runViaAgent itself is unit-tested directly against embedded NATS, bypassing the Docker-dependent Acquire path. This closes the archie-core-5zh epic: archie-agent now runs an entire task's workflow per invocation instead of one stage per round trip, with Store/Forge/git-push credentials staying daemon-side throughout."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 68525a1d7..66c2d89d9 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,6 +1,6 @@ {"_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-5zh.7","title":"archie-agent: run full task (workflow.Route + workflow.Run) via RPC-backed TaskContext","description":"The actual stage-loop move for archie-core-5zh, depending on the TaskConfig payload and TaskContext interface refactor. cmd/archie-agent gains a handler for a new 'run whole task' NATS message (task summary + TaskConfig + repo config, no secrets). On receipt it: builds its own workflow.Registry via skillbuild.BuildRegistry against its mounted worktree (/data/worktree — same pattern the daemon already uses, no registry needs to cross the wire); calls workflow.Route itself; builds a TaskContext using storerpc.Client (Store), forgerpc.Client (Forge), and a hybrid Trees (worktreerpc.Client for Prepare/Push, a local *worktree.Manager with no token for CommitAll/Diff/ChangedFiles/ChangedLines against the bind-mounted dir); calls workflow.Run; reports completion once instead of round-tripping per stage.","acceptance_criteria":"When agent.mode=nats and containers are enabled, archie-agent runs an entire task's workflow (all stages) per invocation, not one stage per round trip; inprocess/subprocess modes are unaffected.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T22:28:00Z","created_by":"Sam Catlow","updated_at":"2026-07-23T23:08:11Z","closed_at":"2026-07-23T23:08:11Z","close_reason":"Added internal/taskrun (Request/Response wire types + SubjectForTask) and cmd/archie-agent/taskrun.go: runTask builds a workflow.Registry from the container's own bind-mounted worktree (skillbuild.BuildRegistry, same call the daemon already makes), routes and runs the task's entire workflow via workflow.Route/workflow.Run, using storerpc.Client/forgerpc.Client for Store/Forge and a new hybridTrees (worktreerpc.Client for Prepare/Push, local *worktree.Manager for CommitAll/Diff/ChangedFiles/ChangedLines against the mount). Added config.TaskConfig.ToConfig() to rebuild a usable config.Config from the curated payload. Added storage.WorktreeMountDir constant (/data/worktree) — critical fix: hybridTrees.Prepare discards the RPC response's host-side directory and returns the container's fixed local mount path instead, since archied and archie-agent see the same files at different paths. Wired a queue-grouped core-NATS subscription on archie.taskrun.\u003e in cmd/archie-agent/main.go so this is reachable in the running binary, not just testable in isolation. End-to-end test drives the real 'bootstrap' workflow (no LLM) through real storerpc/forgerpc/worktreerpc servers and a real local git remote, proving the full chain: registry build, route, prepare, commit, push, PR creation, and that the authoritative task state lands in archied's store via RPC. archie-core-5zh.8 (daemon.go handoff) is now unblocked — it owns deciding exactly how/when archied publishes to archie.taskrun.\u003cid\u003e.","dependencies":[{"issue_id":"archie-core-5zh.7","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:27:59Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.7","depends_on_id":"archie-core-5zh.5","type":"blocks","created_at":"2026-07-24T08:28:07Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.7","depends_on_id":"archie-core-5zh.6","type":"blocks","created_at":"2026-07-24T08:28:07Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-5zh.8","title":"daemon.go: hand off whole task to archie-agent in sandboxed NATS+container mode","description":"Depends on the archie-agent full-task handler existing. internal/daemon/daemon.go's process() currently always calls workflow.Route/workflow.Run itself, dispatching per-stage LLM calls to d.Agent (NATSRunner does this over NATS today). When d.Nats != nil \u0026\u0026 d.ContainerPool != nil (the sandboxed path this whole PRD phase targets), process() should instead publish one 'run whole task' message to archie-agent and await its completion report, skipping local workflow.Route/workflow.Run entirely. inprocess/subprocess modes (no container pool) keep calling workflow.Run in the daemon exactly as today — this only changes behavior for the fully-sandboxed path.","acceptance_criteria":"With containers enabled, daemon.process() delegates the entire task to archie-agent in one round trip; without containers, behavior is unchanged (verified by existing daemon tests continuing to pass).","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T22:28:00Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:28:00Z","dependencies":[{"issue_id":"archie-core-5zh.8","depends_on_id":"archie-core-5zh.7","type":"blocks","created_at":"2026-07-24T08:28:07Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.8","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:28:00Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-5zh.8","title":"daemon.go: hand off whole task to archie-agent in sandboxed NATS+container mode","description":"Depends on the archie-agent full-task handler existing. internal/daemon/daemon.go's process() currently always calls workflow.Route/workflow.Run itself, dispatching per-stage LLM calls to d.Agent (NATSRunner does this over NATS today). When d.Nats != nil \u0026\u0026 d.ContainerPool != nil (the sandboxed path this whole PRD phase targets), process() should instead publish one 'run whole task' message to archie-agent and await its completion report, skipping local workflow.Route/workflow.Run entirely. inprocess/subprocess modes (no container pool) keep calling workflow.Run in the daemon exactly as today — this only changes behavior for the fully-sandboxed path.","acceptance_criteria":"With containers enabled, daemon.process() delegates the entire task to archie-agent in one round trip; without containers, behavior is unchanged (verified by existing daemon tests continuing to pass).","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T22:28:00Z","created_by":"Sam Catlow","updated_at":"2026-07-23T23:14:48Z","closed_at":"2026-07-23T23:14:48Z","close_reason":"daemon.process() now branches on d.ContainerPool != nil: sandboxed tasks get handed to archie-agent via a new runViaAgent method (publishes taskrun.Request to archie.taskrun.\u003cid\u003e, awaits taskrun.Response) instead of calling workflow.Route/workflow.Run locally; non-container mode is unchanged. runViaAgent only parks the task itself on transport/setup failure (encode error, no responder, decode error, or an error returned before archie-agent's workflow.Run got to run) — on success, every durable side effect already landed via the storerpc/forgerpc/worktreerpc proxies during archie-agent's run, so runViaAgent just logs. Added agentexec.ProvidersFromConfig (deduped from cmd/archied's former executionProviders). Also fixed a real correctness gap this surfaced: with concurrent multi-task dispatch (u64/g1l) plus containerized archie-agent, the 5zh.7 wildcard queue-group subscription could let one container answer a sibling's taskrun message despite having a different task's worktree mounted. archie-agent now reads its boot-time task.json (container.TaskPayload, already written by daemon.process() before container acquire) and subscribes to its own exact archie.taskrun.\u003cid\u003e subject when present, falling back to the shared queue group only when no task.json exists (dev/pool mode). Full container-mode integration (real Docker) isn't covered by an automated test, consistent with the rest of the container-dependent code — runViaAgent itself is unit-tested directly against embedded NATS, bypassing the Docker-dependent Acquire path. This closes the archie-core-5zh epic: archie-agent now runs an entire task's workflow per invocation instead of one stage per round trip, with Store/Forge/git-push credentials staying daemon-side throughout.","dependencies":[{"issue_id":"archie-core-5zh.8","depends_on_id":"archie-core-5zh.7","type":"blocks","created_at":"2026-07-24T08:28:07Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.8","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:28:00Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-5zh.9","title":"Register storerpc/forgerpc/worktreerpc servers in archied startup","description":"Depends on the TaskContext interface refactor. cmd/archied/main.go builds the Daemon with Store/Forge/Trees but never registers the storerpc.Server/forgerpc.Server/worktreerpc.Server handlers, so archie-agent's RPC calls currently have no responder in production. Wire all three Register(nc) calls into archied's startup when cfg.NATS is configured, alongside the existing NATS client connect.","acceptance_criteria":"When [nats] is configured, archied subscribes to all storerpc/forgerpc/worktreerpc subjects at startup; an archie-agent container can successfully call Store/Forge/worktree operations against a running archied.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T22:28:00Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:58:58Z","started_at":"2026-07-23T22:56:35Z","closed_at":"2026-07-23T22:58:58Z","close_reason":"Added registerTaskRPCServers() in cmd/archied/main.go, wiring storerpc.Server/forgerpc.Server/worktreerpc.Server onto the daemon's NATS connection whenever [nats] is configured, alongside the existing worktree.Manager and forge/store instances the daemon already owns. Test spins an embedded NATS server, registers via the composed function, then round-trips real storerpc/forgerpc/worktreerpc clients against it to prove all three are reachable. archie-core-5zh.7 (archie-agent full-task handler) can now be built and tested end-to-end against a real archied.","dependencies":[{"issue_id":"archie-core-5zh.9","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:28:00Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.9","depends_on_id":"archie-core-5zh.6","type":"blocks","created_at":"2026-07-24T08:28:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-5zh.5","title":"Curated TaskConfig payload for archie-agent (no secrets)","description":"Groundwork for archie-core-5zh.4. workflow.TaskContext.Cfg (config.Config) is read throughout stages (Models, Budgets, Dispatch incl. label mapping, DiffCapLines, Notify.Webhook, Forge.Host) but the full Config also carries forge/NATS credentials that must never enter the agent container. Add a config.TaskConfig struct — same field names/shapes as the subset config.Config exposes (Models, Budgets, Dispatch, DiffCapLines, Notify, Forge) — with json tags, plus a constructor (e.g. config.Config.ForTask()) that builds it from the daemon's live config. Add json tags to config.Repo's remaining fields (only AllowConcurrent has them today) since tc.Repo also needs to cross the wire.","acceptance_criteria":"config.TaskConfig marshals/unmarshals via JSON and carries exactly the fields workflow stages read; no token/credential field is reachable from it; config.Repo fully round-trips through JSON.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T22:27:59Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:51:48Z","started_at":"2026-07-23T22:43:06Z","closed_at":"2026-07-23T22:51:48Z","close_reason":"Implemented curated non-secret TaskConfig/TaskForge payload with detached map snapshots, stable JSON Duration encoding, full Repo JSON tags, and regression coverage. Focused config tests, go vet, go fix -diff, and full race suite pass; repository-wide lint remains blocked only by 36 unrelated pre-existing findings.","dependencies":[{"issue_id":"archie-core-5zh.5","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:27:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-5zh.6","title":"TaskContext interface refactor: Forge/Store/Trees as trimmed interfaces","description":"Groundwork for archie-core-5zh.4. workflow.TaskContext currently types Forge/Store/Trees as concrete daemon types (forge.Forge interface already, *store.Store, *worktree.Manager). Define trimmed interfaces in internal/workflow scoped to exactly the methods stages call (Forge: Comment/CloseIssue/CreatePR/SetStateLabel; Store: Update/Transition; Trees: Prepare/CommitAll/Push/Diff/ChangedFiles/ChangedLines) so storerpc.Client, forgerpc.Client, and a worktreerpc-backed implementation can satisfy them from inside archie-agent, while *store.Store/*worktree.Manager and the real forge.Forge implementations keep satisfying them unchanged for the daemon's existing inprocess/subprocess paths.","acceptance_criteria":"TaskContext.Forge/Store/Trees are interface-typed; daemon.go compiles and all existing tests pass unchanged (concrete types satisfy the new interfaces structurally); no behavior change for inprocess/subprocess modes.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T22:27:59Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:56:18Z","started_at":"2026-07-23T22:54:26Z","closed_at":"2026-07-23T22:56:18Z","close_reason":"Trimmed workflow.TaskContext.Forge/Store/Trees to new interfaces (Forger, TaskStore, Trees) in internal/workflow/workflow.go, scoped to exactly the methods stages call mid-run (4 Forge methods, 2 Store methods, 6 Trees methods). Go's structural typing meant zero changes were needed anywhere else — forge.Forge (already an interface), *store.Store, and *worktree.Manager all satisfy the new interfaces automatically, and storerpc.Client/forgerpc.Client/worktreerpc.Client already match by construction from 5zh.1-3. Full build, race suite, vet, and staticcheck all clean with no behavior change. archie-core-5zh.7 (archie-agent full-task handler) and 5zh.9 (register RPC servers in archied) are now unblocked.","dependencies":[{"issue_id":"archie-core-5zh.6","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T08:27:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0} diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index 114280369..1657f13a3 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -15,6 +15,7 @@ import ( "log/slog" "os" "os/signal" + "path/filepath" "syscall" "time" @@ -22,7 +23,10 @@ import ( "github.com/nats-io/nats.go/jetstream" "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/container" arnats "github.com/samcharles93/archie-core/internal/nats" + "github.com/samcharles93/archie-core/internal/storage" + "github.com/samcharles93/archie-core/internal/taskrun" ) const ( @@ -107,9 +111,23 @@ func run() int { return 1 } - taskRunSub, err := nc.QueueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, func(msg *nats.Msg) { - handleTaskRun(ctx, msg, nc, log) - }) + // Prefer a dedicated per-task subscription over the shared queue group + // whenever this container was spawned for a specific task (task.json + // present at the worktree mount): with concurrent multi-task dispatch, + // a queue-group member could otherwise pick up a message meant for a + // sibling container that has a *different* task's worktree mounted. + var taskRunSub *nats.Subscription + if taskID, ok := bootTaskID(storage.WorktreeMountDir, log); ok { + taskRunSub, err = nc.Subscribe(taskrun.SubjectForTask(taskID), func(msg *nats.Msg) { + handleTaskRun(ctx, msg, nc, log) + }) + log.Info("taskrun: dedicated per-task subscription", "task", taskID) + } else { + taskRunSub, err = nc.QueueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, func(msg *nats.Msg) { + handleTaskRun(ctx, msg, nc, log) + }) + log.Info("taskrun: shared queue-group subscription (no task.json found)") + } if err != nil { log.Error("taskrun subscribe failed", "err", err) return 1 @@ -160,6 +178,26 @@ func run() int { } } +// bootTaskID reads the boot-time task.json brief the daemon writes into +// the worktree before container acquire (container.WriteTaskJSON) and +// returns its ID. Returns (0, false) when the file is absent, unparseable, +// or has no ID — any of which mean "shared pool mode, no dedicated task." +func bootTaskID(mountDir string, log *slog.Logger) (int64, bool) { + data, err := os.ReadFile(filepath.Join(mountDir, "task.json")) + if err != nil { + return 0, false + } + var payload container.TaskPayload + if err := json.Unmarshal(data, &payload); err != nil { + log.Warn("task.json present but unparseable — falling back to shared queue subscription", "err", err) + return 0, false + } + if payload.ID <= 0 { + return 0, false + } + return payload.ID, true +} + func natsConnectionSettings(flagURL string, getenv func(string) string) (url, token string) { url = flagURL if url == "" { diff --git a/cmd/archie-agent/main_test.go b/cmd/archie-agent/main_test.go index a4bae0c12..4b6b6ce81 100644 --- a/cmd/archie-agent/main_test.go +++ b/cmd/archie-agent/main_test.go @@ -1,6 +1,63 @@ package main -import "testing" +import ( + "encoding/json" + "log/slog" + "os" + "path/filepath" + "testing" + + "github.com/samcharles93/archie-core/internal/container" +) + +func TestBootTaskID(t *testing.T) { + log := slog.New(slog.DiscardHandler) + + t.Run("no task.json — shared pool mode", func(t *testing.T) { + id, ok := bootTaskID(t.TempDir(), log) + if ok || id != 0 { + t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok) + } + }) + + t.Run("valid task.json — dedicated per-task mode", func(t *testing.T) { + dir := t.TempDir() + data, err := json.Marshal(container.TaskPayload{ID: 42, Owner: "sam", Repo: "archie"}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "task.json"), data, 0o644); err != nil { + t.Fatal(err) + } + id, ok := bootTaskID(dir, log) + if !ok || id != 42 { + t.Fatalf("bootTaskID() = (%d, %v), want (42, true)", id, ok) + } + }) + + t.Run("malformed task.json falls back to shared pool mode", func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "task.json"), []byte("not json"), 0o644); err != nil { + t.Fatal(err) + } + id, ok := bootTaskID(dir, log) + if ok || id != 0 { + t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok) + } + }) + + t.Run("zero ID falls back to shared pool mode", func(t *testing.T) { + dir := t.TempDir() + data, _ := json.Marshal(container.TaskPayload{Owner: "sam", Repo: "archie"}) + if err := os.WriteFile(filepath.Join(dir, "task.json"), data, 0o644); err != nil { + t.Fatal(err) + } + id, ok := bootTaskID(dir, log) + if ok || id != 0 { + t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok) + } + }) +} func TestNATSConnectionSettings(t *testing.T) { getenv := func(name string) string { diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 5a43dba85..510c6c8b5 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -275,11 +275,7 @@ func run() int { } func executionProviders(cfg config.Config) map[string]agentexec.Provider { - providers := make(map[string]agentexec.Provider, len(cfg.Providers)) - for name, p := range cfg.Providers { - providers[name] = agentexec.Provider{Class: p.Class, APIKeyEnv: p.APIKeyEnv, BaseURL: p.BaseURL} - } - return providers + return agentexec.ProvidersFromConfig(cfg.Providers) } // registerTaskRPCServers subscribes the storerpc/forgerpc/worktreerpc diff --git a/internal/agentexec/providers.go b/internal/agentexec/providers.go new file mode 100644 index 000000000..b8b80707a --- /dev/null +++ b/internal/agentexec/providers.go @@ -0,0 +1,14 @@ +package agentexec + +import "github.com/samcharles93/archie-core/internal/config" + +// ProvidersFromConfig converts the daemon's configured LLM providers into +// the wire-safe Provider map sent to an agent runner. It carries only +// class/env-var-name/base-URL — never the resolved API key. +func ProvidersFromConfig(providers map[string]config.Provider) map[string]Provider { + out := make(map[string]Provider, len(providers)) + for name, p := range providers { + out[name] = Provider{Class: p.Class, APIKeyEnv: p.APIKeyEnv, BaseURL: p.BaseURL} + } + return out +} diff --git a/internal/agentexec/providers_test.go b/internal/agentexec/providers_test.go new file mode 100644 index 000000000..037de5c4e --- /dev/null +++ b/internal/agentexec/providers_test.go @@ -0,0 +1,26 @@ +package agentexec + +import ( + "reflect" + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +func TestProvidersFromConfig(t *testing.T) { + in := map[string]config.Provider{ + "anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.anthropic.com"}, + } + want := map[string]Provider{ + "anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.anthropic.com"}, + } + if got := ProvidersFromConfig(in); !reflect.DeepEqual(got, want) { + t.Fatalf("ProvidersFromConfig() = %#v, want %#v", got, want) + } +} + +func TestProvidersFromConfigEmpty(t *testing.T) { + if got := ProvidersFromConfig(nil); len(got) != 0 { + t.Fatalf("ProvidersFromConfig(nil) = %#v, want empty", got) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f6255fb9e..0d23c32cd 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -5,6 +5,7 @@ package daemon import ( "context" + "encoding/json" "fmt" "log/slog" "os" @@ -27,6 +28,7 @@ import ( "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/workflow" "github.com/samcharles93/archie-core/internal/workflow/skillbuild" "github.com/samcharles93/archie-core/internal/worktree" @@ -688,18 +690,27 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { // container is needed). This prevents label/database divergence on failure. d.Forge.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues()) - workflow.Run(ctx, wf, &workflow.TaskContext{ - Task: task, - Repo: repo, - Cfg: d.Cfg, - Forge: d.Forge, - Store: d.Store, - Trees: d.Trees, - Agent: d.Agent, - Bus: d.Bus, - Log: d.Log, - CustomStages: d.CustomStages, - }) + // Sandboxed path: hand the whole task to archie-agent in one NATS round + // trip instead of running the stage loop here. archie-agent proxies + // Store/Forge/worktree-push calls back to archied over storerpc/ + // forgerpc/worktreerpc — by the time runViaAgent returns, the task's + // terminal state already landed via those calls. + if d.ContainerPool != nil { + d.runViaAgent(ctx, task, repo) + } else { + workflow.Run(ctx, wf, &workflow.TaskContext{ + 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, + CustomStages: d.CustomStages, + }) + } // Teardown storage after workflow completes. The Docker backend is a // no-op; future backends (temp volumes, NFS leases) use this hook. @@ -715,6 +726,51 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { } // containerEnv returns the environment variables passed to agent containers. +// runViaAgent publishes a full-task handoff to archie-agent over +// archie.taskrun. and waits for its completion report. Every durable +// side effect (Store transitions, Forge calls, git push) happens inside +// archie-agent's workflow.Run, proxied back to this daemon over +// storerpc/forgerpc/worktreerpc — those RPC servers are the sole place a +// terminal state gets written on success. runViaAgent only parks the task +// itself when nothing else could have: the request never reached (or was +// never answered by) an archie-agent, or archie-agent failed before its +// own workflow.Run got a chance to record an outcome. +func (d *Daemon) runViaAgent(ctx context.Context, task *store.Task, repo config.Repo) { + req := taskrun.Request{ + Task: task, + Repo: repo, + Cfg: d.Cfg.ForTask(), + Providers: agentexec.ProvidersFromConfig(d.Cfg.Providers), + } + data, err := json.Marshal(req) + if err != nil { + d.Log.Error("taskrun encode failed", "task", task.ID, "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "taskrun encode failed: "+err.Error()) + return + } + + reply, err := d.Nats.Conn().RequestWithContext(ctx, taskrun.SubjectForTask(task.ID), data) + if err != nil { + d.Log.Error("taskrun request failed", "task", task.ID, "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "taskrun request failed: "+err.Error()) + return + } + + var resp taskrun.Response + if err := json.Unmarshal(reply.Data, &resp); err != nil { + d.Log.Error("taskrun decode response failed", "task", task.ID, "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "taskrun decode response failed: "+err.Error()) + return + } + if resp.Error != "" { + d.Log.Error("taskrun run failed", "task", task.ID, "err", resp.Error) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "taskrun run failed: "+resp.Error) + return + } + + d.Log.Info("taskrun complete", "task", task.ID, "status", resp.Status) +} + func (d *Daemon) containerEnv() []string { var env []string env = append(env, "NATS_URL="+d.Cfg.NATS.URL) diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 2c16f99f9..faaa4fcfa 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -2,6 +2,7 @@ package daemon import ( "context" + "encoding/json" "log/slog" "os" "slices" @@ -10,9 +11,15 @@ import ( "testing" "time" + "github.com/nats-io/nats-server/v2/server" + natssrv "github.com/nats-io/nats-server/v2/test" + natsio "github.com/nats-io/nats.go" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/forge" + arnats "github.com/samcharles93/archie-core/internal/nats" "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/taskrun" ) func TestTaskDispatcherEnforcesMaxConcurrency(t *testing.T) { @@ -216,6 +223,152 @@ func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) { } } +func startEmbeddedNATSForDaemon(t *testing.T) *server.Server { + t.Helper() + srv := natssrv.RunRandClientPortServer() + t.Cleanup(srv.Shutdown) + if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil { + t.Fatalf("enable jetstream: %v", err) + } + return srv +} + +func daemonWithNATS(t *testing.T) (*Daemon, *store.Store) { + t.Helper() + srv := startEmbeddedNATSForDaemon(t) + client, err := arnats.Connect(context.Background(), srv.ClientURL(), "", slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("nats connect: %v", err) + } + t.Cleanup(client.Close) + + s := store.OpenTest(t) + d := &Daemon{ + Cfg: config.Config{ + Dispatch: config.Dispatch{Labels: map[string]string{ + "parked": "archie:parked", "queued": "archie:queued", "dead": "archie:dead", + }}, + }, + Store: s, + Nats: client, + Log: slog.New(slog.DiscardHandler), + } + return d, s +} + +func TestRunViaAgentParksOnRequestFailure(t *testing.T) { + d, s := daemonWithNATS(t) + ctx := context.Background() + + if _, err := s.EnqueueIssue(ctx, "sam", "archie", 1, "t", "b", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + + // No responder registered on the taskrun subject — the request must + // fail, and runViaAgent must park rather than leave the task stuck + // running. + d.runViaAgent(ctx, task, config.Repo{Owner: "sam", Name: "archie"}) + + got, err := s.TaskByIssue(ctx, "sam", "archie", 1) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Status != store.StatusParked { + t.Fatalf("status = %q, want %q", got.Status, store.StatusParked) + } +} + +func TestRunViaAgentParksOnRunError(t *testing.T) { + d, s := daemonWithNATS(t) + ctx := context.Background() + + if _, err := s.EnqueueIssue(ctx, "sam", "archie", 2, "t", "b", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + + sub, err := d.Nats.Conn().Subscribe(taskrun.SubjectForTask(task.ID), func(msg *natsio.Msg) { + data, _ := json.Marshal(taskrun.Response{Error: "registry build failed"}) + _ = msg.Respond(data) + }) + if err != nil { + t.Fatalf("subscribe: %v", err) + } + t.Cleanup(func() { sub.Unsubscribe() }) + + d.runViaAgent(ctx, task, config.Repo{Owner: "sam", Name: "archie"}) + + got, err := s.TaskByIssue(ctx, "sam", "archie", 2) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Status != store.StatusParked { + t.Fatalf("status = %q, want %q", got.Status, store.StatusParked) + } +} + +func TestRunViaAgentSendsExpectedRequest(t *testing.T) { + d, s := daemonWithNATS(t) + d.Cfg.DiffCapLines = 999 + ctx := context.Background() + + if _, err := s.EnqueueIssue(ctx, "sam", "archie", 3, "t", "b", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + + received := make(chan taskrun.Request, 1) + sub, err := d.Nats.Conn().Subscribe(taskrun.SubjectForTask(task.ID), func(msg *natsio.Msg) { + var req taskrun.Request + _ = json.Unmarshal(msg.Data, &req) + received <- req + data, _ := json.Marshal(taskrun.Response{Status: store.StatusPROpen}) + _ = msg.Respond(data) + }) + if err != nil { + t.Fatalf("subscribe: %v", err) + } + t.Cleanup(func() { sub.Unsubscribe() }) + + repo := config.Repo{Owner: "sam", Name: "archie", Base: "main"} + d.runViaAgent(ctx, task, repo) + + select { + case req := <-received: + if req.Task == nil || req.Task.ID != task.ID { + t.Fatalf("request Task = %+v, want ID %d", req.Task, task.ID) + } + if req.Repo.FullName() != "sam/archie" { + t.Fatalf("request Repo = %+v", req.Repo) + } + if req.Cfg.DiffCapLines != 999 { + t.Fatalf("request Cfg.DiffCapLines = %d, want 999", req.Cfg.DiffCapLines) + } + case <-time.After(time.Second): + t.Fatal("archied did not publish a taskrun request") + } + + // Success path: runViaAgent must not park a task that archie-agent + // already reported as complete — the daemon just logs it. + got, err := s.TaskByIssue(ctx, "sam", "archie", 3) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Status == store.StatusParked { + t.Fatal("runViaAgent parked a task that succeeded") + } +} + func TestHasLabelUsesExactNames(t *testing.T) { labels := []string{"bug", "archie:parked-old", "feature", "custom,label"} if hasLabel(labels, "archie:parked") {