diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index d623987cd..9a8199465 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -9,3 +9,4 @@ {"id":"int-52ef9df12424463a13205bb9f244a308","kind":"field_change","created_at":"2026-07-23T22:51:47.945822737Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress","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."}} {"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.."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index e1222ecf0..68525a1d7 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,5 +1,5 @@ {"_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":"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.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.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.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} diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index e06fc7156..114280369 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -1,7 +1,10 @@ -// Command archie-agent is a long-running NATS-connected worker that executes -// autonomous agent stages. It subscribes to archie.agent.> on the ARCHIE_TASKS -// JetStream stream, runs the agent loop for each received request, and publishes -// the result back to the daemon's reply inbox. +// Command archie-agent is a long-running NATS-connected worker. It answers +// two request shapes: single-stage archie.agent.> requests over the +// ARCHIE_TASKS JetStream stream (the legacy per-stage protocol), and full +// task handoffs on archie.taskrun.> (core NATS, queue-grouped) — where it +// runs workflow.Route/workflow.Run itself, proxying Store/Forge/worktree +// operations back to archied over NATS instead of holding those +// credentials directly. package main import ( @@ -28,6 +31,13 @@ const ( dedupWindow = 2 * time.Minute pollTimeout = 5 * time.Second ackWait = 30 * time.Minute + + // taskRunSubjectWildcard matches full-task handoffs (archie.taskrun.). + // A queue group means only one archie-agent instance answers each + // message, whether deployed as a shared worker pool (today) or spawned + // one-per-task (the sandboxed container target). + taskRunSubjectWildcard = "archie.taskrun.>" + taskRunQueueGroup = "archie-taskrun-workers" ) func main() { @@ -97,6 +107,15 @@ func run() int { return 1 } + taskRunSub, err := nc.QueueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, func(msg *nats.Msg) { + handleTaskRun(ctx, msg, nc, log) + }) + if err != nil { + log.Error("taskrun subscribe failed", "err", err) + return 1 + } + defer taskRunSub.Unsubscribe() + log.Info("archie-agent ready", "nats", natsURL, "consumer", *consumer) // Main loop: fetch, run, reply, ack. diff --git a/cmd/archie-agent/taskrun.go b/cmd/archie-agent/taskrun.go new file mode 100644 index 000000000..136992bd9 --- /dev/null +++ b/cmd/archie-agent/taskrun.go @@ -0,0 +1,159 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "time" + + natsio "github.com/nats-io/nats.go" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/forgerpc" + "github.com/samcharles93/archie-core/internal/storage" + "github.com/samcharles93/archie-core/internal/storerpc" + "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/workflow/wfeval" + "github.com/samcharles93/archie-core/internal/worktree" + "github.com/samcharles93/archie-core/internal/worktreerpc" +) + +const rpcTimeout = 60 * time.Second + +// hybridTrees implements workflow.Trees by splitting operations: Prepare +// and Push (network ops needing the daemon's forge credential) proxy over +// worktreerpc; CommitAll/Diff/ChangedFiles/ChangedLines are local git +// operations run directly against the container's bind-mounted worktree. +// +// Prepare deliberately discards the RPC response's directory (the +// daemon's host-side path) and returns localDir instead — archied and +// archie-agent see the same files at different paths. +type hybridTrees struct { + push *worktreerpc.Client + local *worktree.Manager + owner, repo string + issue int + localDir string +} + +func (h *hybridTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) { + _, branch, err = h.push.Prepare(ctx, owner, repo, base, issue, title, body, labels) + if err != nil { + return "", "", err + } + return h.localDir, branch, nil +} + +func (h *hybridTrees) CommitAll(ctx context.Context, dir, message string) (bool, error) { + return h.local.CommitAll(ctx, dir, message) +} + +func (h *hybridTrees) Push(ctx context.Context, dir, branch string) error { + return h.push.Push(ctx, h.owner, h.repo, h.issue, branch) +} + +func (h *hybridTrees) Diff(ctx context.Context, dir, base string) (string, error) { + return h.local.Diff(ctx, dir, base) +} + +func (h *hybridTrees) ChangedFiles(ctx context.Context, dir, base string) ([]string, error) { + return h.local.ChangedFiles(ctx, dir, base) +} + +func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, error) { + return h.local.ChangedLines(ctx, dir, base) +} + +var _ workflow.Trees = (*hybridTrees)(nil) + +// runTask builds a workflow.Registry from the container's own mounted +// worktree, routes and runs req.Task's entire workflow, and reports the +// terminal outcome. Store/Forge/worktree-push calls proxy back to archied +// over nc; Store is archied's sole authority for task state — the +// returned Response.Task is a best-effort snapshot for logging only. +func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunner agentexec.RunnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) { + registry, err := skillbuild.BuildRegistry(workDir) + if err != nil { + return nil, fmt.Errorf("build registry: %w", err) + } + + wf := workflow.Route(req.Task, registry) + + trees := &hybridTrees{ + push: &worktreerpc.Client{Conn: nc, Timeout: rpcTimeout}, + local: &worktree.Manager{WorkDir: workDir}, + owner: req.Task.Owner, + repo: req.Task.Repo, + issue: req.Task.IssueNumber, + localDir: workDir, + } + + agent := newRunner(req.Providers, log) + if agent == nil { + return nil, fmt.Errorf("no agent runner configured for task %d", req.Task.ID) + } + + tc := &workflow.TaskContext{ + Task: req.Task, + Repo: req.Repo, + Cfg: req.Cfg.ToConfig(), + Forge: &forgerpc.Client{Conn: nc, Timeout: rpcTimeout}, + Store: &storerpc.Client{Conn: nc, Timeout: rpcTimeout}, + Trees: trees, + Agent: agent, + Log: log, + CustomStages: wfeval.Discover, + } + + workflow.Run(ctx, wf, tc) + + return &taskrun.Response{ + Task: tc.Task, + Status: tc.Outcome.Status, + }, nil +} + +// handleTaskRun decodes a taskrun.Request from msg, runs it via runTask +// against the container's fixed worktree mount, and replies with the +// outcome. Errors are reported in the reply, not returned — there's no +// caller to return them to; this is a NATS subscription callback. +func handleTaskRun(ctx context.Context, msg *natsio.Msg, nc *natsio.Conn, log *slog.Logger) { + var req taskrun.Request + if err := json.Unmarshal(msg.Data, &req); err != nil { + log.Error("taskrun decode failed", "err", err) + respondTaskRun(msg, nil, fmt.Errorf("decode taskrun request: %w", err), log) + return + } + + log.Info("running task", "task", req.Task.ID, "repo", req.Repo.FullName(), "issue", req.Task.IssueNumber) + + resp, err := runTask(ctx, req, nc, agentexec.DefaultRunnerFactory, storage.WorktreeMountDir, log) + if err != nil { + log.Error("task run failed", "task", req.Task.ID, "err", err) + respondTaskRun(msg, nil, err, log) + return + } + + log.Info("task run complete", "task", req.Task.ID, "status", resp.Status) + respondTaskRun(msg, resp, nil, log) +} + +func respondTaskRun(msg *natsio.Msg, resp *taskrun.Response, runErr error, log *slog.Logger) { + if resp == nil { + resp = &taskrun.Response{} + } + if runErr != nil { + resp.Error = runErr.Error() + } + data, err := json.Marshal(resp) + if err != nil { + log.Error("taskrun encode response failed", "err", err) + return + } + if err := msg.Respond(data); err != nil { + log.Error("taskrun respond failed", "err", err) + } +} diff --git a/cmd/archie-agent/taskrun_test.go b/cmd/archie-agent/taskrun_test.go new file mode 100644 index 000000000..e8437f82f --- /dev/null +++ b/cmd/archie-agent/taskrun_test.go @@ -0,0 +1,227 @@ +package main + +import ( + "context" + "log/slog" + "os" + "os/exec" + "path/filepath" + "testing" + + "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/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/forge" + "github.com/samcharles93/archie-core/internal/forgerpc" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/storerpc" + "github.com/samcharles93/archie-core/internal/taskrun" + "github.com/samcharles93/archie-core/internal/worktree" + "github.com/samcharles93/archie-core/internal/worktreerpc" +) + +func startEmbeddedForTaskRun(t *testing.T) *server.Server { + t.Helper() + srv := natssrv.RunRandClientPortServer() + t.Cleanup(srv.Shutdown) + return srv +} + +func connectForTaskRun(t *testing.T, url string) *natsio.Conn { + t.Helper() + nc, err := natsio.Connect(url) + if err != nil { + t.Fatalf("nats connect: %v", err) + } + t.Cleanup(nc.Close) + return nc +} + +// panicRunner fails the test if the bootstrap workflow (deterministic, +// no LLM stages) ever invokes it. +type panicRunner struct{ t *testing.T } + +func (r panicRunner) Run(context.Context, string, agentexec.Request) (agentexec.Result, error) { + r.t.Fatal("bootstrap workflow must not invoke an LLM runner") + return agentexec.Result{}, nil +} + +// prCapturingForge records CreatePR calls and answers the four Forger +// methods the bootstrap workflow needs; everything else panics. +type prCapturingForge struct { + prs []struct{ owner, repo, title, head, base, body string } +} + +func (f *prCapturingForge) Comment(context.Context, string, string, int, string) (int64, error) { + return 1, nil +} +func (f *prCapturingForge) CloseIssue(context.Context, string, string, int, string) error { return nil } +func (f *prCapturingForge) CreatePR(_ context.Context, owner, repo, title, head, base, body string) (int, error) { + f.prs = append(f.prs, struct{ owner, repo, title, head, base, body string }{owner, repo, title, head, base, body}) + return 5, nil +} +func (f *prCapturingForge) SetStateLabel(context.Context, string, string, int, string, []string) {} +func (f *prCapturingForge) AcceptInvitations(context.Context) error { panic("unexpected call") } +func (f *prCapturingForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) { + panic("unexpected call") +} +func (f *prCapturingForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) { + panic("unexpected call") +} +func (f *prCapturingForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) { + panic("unexpected call") +} +func (f *prCapturingForge) PRState(context.Context, string, string, int) (string, error) { + panic("unexpected call") +} +func (f *prCapturingForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) { + panic("unexpected call") +} +func (f *prCapturingForge) React(context.Context, string, string, int, string) error { + panic("unexpected call") +} +func (f *prCapturingForge) VerifyPush(context.Context, string, string) error { + panic("unexpected call") +} + +// newLocalRemote mirrors worktree_test.go's helper: a bare repo with one +// commit on main, reachable via file:////.git. +func newLocalRemote(t *testing.T, owner, repo string) string { + t.Helper() + host := t.TempDir() + bare := filepath.Join(host, owner, repo+".git") + seed := filepath.Join(t.TempDir(), "seed") + + run := func(dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + + if err := os.MkdirAll(bare, 0o755); err != nil { + t.Fatal(err) + } + run(host, "init", "--bare", "-b", "main", bare) + if err := os.MkdirAll(seed, 0o755); err != nil { + t.Fatal(err) + } + run(seed, "init", "-b", "main") + run(seed, "config", "user.name", "seeder") + run(seed, "config", "user.email", "seed@example.com") + if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil { + t.Fatal(err) + } + run(seed, "add", "-A") + run(seed, "commit", "-m", "seed") + run(seed, "push", "file://"+bare, "main") + return host +} + +// TestRunTaskExecutesBootstrapWorkflowEndToEnd drives runTask through the +// deterministic "bootstrap" workflow (no LLM calls) with real storerpc/ +// forgerpc/worktreerpc servers backing an RPC-constructed TaskContext, +// proving the full archie-agent-side wiring: registry build, Route, Run, +// and the hybrid Trees split between proxied Prepare/Push and local git. +func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + ctx := context.Background() + host := newLocalRemote(t, "sam", "archie") + + // archied side: real Store, a capturing Forge, and the Manager that + // actually holds the (unused-for-file-remotes) push token. + st := store.OpenTest(t) + if _, err := st.EnqueueIssue(ctx, "sam", "archie", 1, "feat: bootstrap test", "", "bootstrap"); err != nil { + t.Fatalf("enqueue: %v", err) + } + task, err := st.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + + fg := &prCapturingForge{} + daemonTrees := &worktree.Manager{ + WorkDir: t.TempDir(), + Token: "unused-for-file-remotes", + BotUser: "archie-bot", + BotEmail: "archie-bot@example.com", + BaseURL: "file://" + host, + } + + // The daemon always prepares the worktree before container acquire — + // reproduce that here so the container's bind mount has real content. + hostDir, _, err := daemonTrees.Prepare(ctx, "sam", "archie", "main", 1, task.Title, "", "bootstrap") + if err != nil { + t.Fatalf("daemon-side prepare: %v", err) + } + + srv := startEmbeddedForTaskRun(t) + url := srv.ClientURL() + serverConn := connectForTaskRun(t, url) + + unsubStore, err := (&storerpc.Server{Store: st, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) + if err != nil { + t.Fatalf("register storerpc: %v", err) + } + t.Cleanup(unsubStore) + unsubForge, err := (&forgerpc.Server{Forge: fg, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) + if err != nil { + t.Fatalf("register forgerpc: %v", err) + } + t.Cleanup(unsubForge) + unsubTrees, err := (&worktreerpc.Server{Trees: daemonTrees, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) + if err != nil { + t.Fatalf("register worktreerpc: %v", err) + } + t.Cleanup(unsubTrees) + + // archie-agent side: its own NATS connection, "bind mount" is just + // hostDir since this test runs in a single process/filesystem. + agentConn := connectForTaskRun(t, url) + + req := taskrun.Request{ + Task: task, + Repo: config.Repo{Owner: "sam", Name: "archie", Base: "main"}, + Cfg: config.Config{}.ForTask(), + } + + fakeRunner := agentexec.RunnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { + return panicRunner{t} + }) + + resp, err := runTask(ctx, req, agentConn, fakeRunner, hostDir, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("runTask: %v", err) + } + if resp.Status != store.StatusPROpen { + t.Fatalf("resp.Status = %q, want %q (task: %+v)", resp.Status, store.StatusPROpen, resp.Task) + } + if len(fg.prs) != 1 { + t.Fatalf("expected 1 CreatePR call, got %d: %+v", len(fg.prs), fg.prs) + } + + // The authoritative state landed in archied's store via storerpc, not + // just in the in-memory tc.Task. + stored, err := st.TaskByIssue(ctx, "sam", "archie", 1) + if err != nil || stored == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", stored, err) + } + if stored.Status != store.StatusPROpen { + t.Fatalf("stored task status = %q, want %q", stored.Status, store.StatusPROpen) + } + if stored.PRNumber != 5 { + t.Fatalf("stored task PR number = %d, want 5", stored.PRNumber) + } + + if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil { + t.Fatalf("expected bootstrap marker file: %v", err) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index e9fd8443a..e59153b02 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -317,6 +317,21 @@ func (c Config) ForTask() TaskConfig { } } +// ToConfig expands a TaskConfig back into a Config with only the carried +// fields populated — everything else (Repos, NATS, Containers, Providers, +// secrets) is zero. Used by archie-agent to reconstruct the Config value +// workflow stages read via TaskContext.Cfg. +func (tc TaskConfig) ToConfig() Config { + return Config{ + Models: cloneStringMap(tc.Models), + Budgets: tc.Budgets, + Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction, Labels: cloneStringMap(tc.Dispatch.Labels)}, + DiffCapLines: tc.DiffCapLines, + Notify: tc.Notify, + Forge: Forge{Host: tc.Forge.Host}, + } +} + func cloneStringMap(src map[string]string) map[string]string { if src == nil { return nil diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a841e5534..1e8f22b9b 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -10,6 +10,40 @@ import ( "time" ) +func TestTaskConfigToConfigRoundTrip(t *testing.T) { + cfg := Config{ + DiffCapLines: 321, + Models: map[string]string{"builder": "anthropic/claude"}, + Budgets: Budgets{MaxSteps: 12, MaxTokens: 34_000, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, + Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}}, + Notify: Notify{Webhook: "https://notify.example.test/hook"}, + Forge: Forge{Type: "github", Host: "https://forge.example.test", TokenEnv: "TOP_SECRET"}, + } + + got := cfg.ForTask().ToConfig() + if !reflect.DeepEqual(got.Models, cfg.Models) { + t.Fatalf("Models = %#v, want %#v", got.Models, cfg.Models) + } + if got.Budgets != cfg.Budgets { + t.Fatalf("Budgets = %#v, want %#v", got.Budgets, cfg.Budgets) + } + if !reflect.DeepEqual(got.Dispatch, cfg.Dispatch) { + t.Fatalf("Dispatch = %#v, want %#v", got.Dispatch, cfg.Dispatch) + } + if got.DiffCapLines != cfg.DiffCapLines { + t.Fatalf("DiffCapLines = %d, want %d", got.DiffCapLines, cfg.DiffCapLines) + } + if got.Notify != cfg.Notify { + t.Fatalf("Notify = %#v, want %#v", got.Notify, cfg.Notify) + } + if got.Forge.Host != cfg.Forge.Host { + t.Fatalf("Forge.Host = %q, want %q", got.Forge.Host, cfg.Forge.Host) + } + if got.Forge.TokenEnv != "" { + t.Fatalf("Forge.TokenEnv = %q, want empty (never carried by TaskConfig)", got.Forge.TokenEnv) + } +} + func TestConfigForTaskJSONRoundTrip(t *testing.T) { cfg := Config{ DiffCapLines: 321, diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 2bd4de8e9..704e723d4 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -62,6 +62,12 @@ const ( MountTypeVolume = "volume" ) +// WorktreeMountDir is the fixed container path where a task's worktree is +// bind-mounted. archie-agent uses this path directly rather than the host +// path archied's worktree.Manager reports — the two processes see the same +// files at different paths. +const WorktreeMountDir = "/data/worktree" + // Backend prepares container storage. Each container runtime backend // (Docker, future containerd, etc.) implements this interface. type Backend interface { @@ -204,7 +210,7 @@ func (d *DockerBackend) Setup(ctx context.Context, task TaskRef) ([]Mount, error { Type: MountTypeBind, Source: task.WorktreeDir, - Destination: "/data/worktree", + Destination: WorktreeMountDir, }, } diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go new file mode 100644 index 000000000..16b08bbee --- /dev/null +++ b/internal/taskrun/taskrun.go @@ -0,0 +1,42 @@ +// Package taskrun defines the wire format for handing an entire task off +// from archied to archie-agent in one NATS round trip, replacing the +// per-stage AgentRequestMessage protocol for the sandboxed container path. +// archie-agent runs workflow.Route and workflow.Run itself; archied's role +// shrinks to worktree prepare, container acquire/release, and answering +// the storerpc/forgerpc/worktreerpc calls archie-agent proxies back. +package taskrun + +import ( + "fmt" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/store" +) + +// SubjectForTask returns the per-task NATS subject for a full-task handoff. +func SubjectForTask(taskID int64) string { + return fmt.Sprintf("archie.taskrun.%d", taskID) +} + +// Request carries everything archie-agent needs to run a task's entire +// workflow itself: the task row (already claimed by archied), the repo's +// gate/ecosystem config, a non-secret config snapshot, and LLM provider +// config (API keys are injected into the container's environment +// separately — Providers only carries class/env-var-name/base-URL). +type Request struct { + Task *store.Task `json:"task"` + Repo config.Repo `json:"repo"` + Cfg config.TaskConfig `json:"cfg"` + Providers map[string]agentexec.Provider `json:"providers"` +} + +// Response reports the task's final state after archie-agent runs its +// workflow. Task carries the last-known field values for logging; the +// authoritative state already landed in archied's store via storerpc +// calls made during the run. +type Response struct { + Task *store.Task `json:"task"` + Status string `json:"status"` + Error string `json:"error,omitempty"` +} diff --git a/internal/taskrun/taskrun_test.go b/internal/taskrun/taskrun_test.go new file mode 100644 index 000000000..4d3e28cdd --- /dev/null +++ b/internal/taskrun/taskrun_test.go @@ -0,0 +1,75 @@ +package taskrun + +import ( + "encoding/json" + "testing" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/store" +) + +func TestRequestJSONRoundTrip(t *testing.T) { + req := Request{ + Task: &store.Task{ + ID: 1, + Owner: "sam", + Repo: "archie", + IssueNumber: 42, + Title: "feat: thing", + Status: store.StatusRunning, + }, + Repo: config.Repo{Owner: "sam", Name: "archie", Base: "main"}, + Cfg: config.Config{DiffCapLines: 500}.ForTask(), + Providers: map[string]agentexec.Provider{ + "anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY"}, + }, + } + + data, err := json.Marshal(req) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + var got Request + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("unmarshal: %v", err) + } + + if got.Task == nil || got.Task.ID != 1 || got.Task.Owner != "sam" || got.Task.IssueNumber != 42 { + t.Fatalf("Task did not round-trip: %+v", got.Task) + } + if got.Repo.FullName() != "sam/archie" || got.Repo.BaseBranch() != "main" { + t.Fatalf("Repo did not round-trip: %+v", got.Repo) + } + if got.Cfg.DiffCapLines != 500 { + t.Fatalf("Cfg did not round-trip: %+v", got.Cfg) + } + if got.Providers["anthropic"].APIKeyEnv != "ANTHROPIC_API_KEY" { + t.Fatalf("Providers did not round-trip: %+v", got.Providers) + } +} + +func TestResponseJSONRoundTrip(t *testing.T) { + resp := Response{ + Task: &store.Task{ID: 1, Status: store.StatusPROpen}, + Status: "passed", + } + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var got Response + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if got.Task == nil || got.Task.Status != store.StatusPROpen || got.Status != "passed" { + t.Fatalf("Response did not round-trip: %+v", got) + } +} + +func TestSubjectForTask(t *testing.T) { + if got := SubjectForTask(42); got != "archie.taskrun.42" { + t.Fatalf("SubjectForTask(42) = %q", got) + } +}