From c9d0f015cafb6c59ec94fd7d40709af140be1205 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 24 Jul 2026 07:58:56 +1000 Subject: [PATCH] feat: Store RPC proxy for archie-agent (archie-core-5zh.1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add internal/storerpc: core NATS request/reply so archie-agent can call Store.Update/Transition without a direct SQLite connection. archied stays the sole DB owner and responds to update/transition subjects; store.Task gains json tags to cross the wire. Groundwork for archie-core-5zh — not yet wired into daemon.go or workflow.TaskContext. Splitting 5zh into sub-issues (.1 Store RPC, .2 Forge RPC, .3 worktree push RPC, .4 the actual stage-loop move) since the full move needs all three proxies to keep secrets/DB ownership on the daemon. --- .beads/interactions.jsonl | 1 + .beads/issues.jsonl | 6 +- internal/store/store.go | 40 ++++---- internal/storerpc/storerpc.go | 146 +++++++++++++++++++++++++++++ internal/storerpc/storerpc_test.go | 136 +++++++++++++++++++++++++++ 5 files changed, 308 insertions(+), 21 deletions(-) create mode 100644 internal/storerpc/storerpc.go create mode 100644 internal/storerpc/storerpc_test.go diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 67af0c41d..b92e0d9d6 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -2,3 +2,4 @@ {"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."}} {"id":"int-dd2e5e0351a12ea84b50ad3e3c3c42e3","kind":"field_change","created_at":"2026-07-23T21:46:52.85072403Z","actor":"Sam Catlow","issue_id":"archie-core-g1l","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added config.Repo.AllowConcurrent (allow_concurrent toml key) and threaded it through taskDispatcher so opted-in repos skip the default FIFO same-repo serialization while still respecting containers.max_concurrency. Worktrees are already keyed per issue number, so no on-disk collision. Race-tested dispatcher coverage added."}} {"id":"int-a6f23a24a14200e58047cb705b026703","kind":"field_change","created_at":"2026-07-23T21:49:40.094050867Z","actor":"Sam Catlow","issue_id":"archie-core-l1q","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Completed JetStream task dispatch and NATS agent request/reply, including token_env authentication for archied and canonical NATS_URL/NATS_TOKEN propagation to container workers; anonymous local mode remains supported and race-tested."}} +{"id":"int-4b10e52acc74cd691919159a77b36f6d","kind":"field_change","created_at":"2026-07-23T21:58:50.804043554Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added internal/storerpc: core-NATS request/reply RPC so archie-agent can call Store.Update/Transition without direct DB access. archied's Store stays the sole owner; store.Task gained json tags to cross the wire. Not yet wired into daemon.go or workflow.TaskContext — that's archie-core-5zh.4's job once all three RPC proxies exist."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 1e81070e4..5812d48f4 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,6 +1,10 @@ {"_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.2","title":"Forge RPC proxy: archie-agent → archied for forge API calls","description":"Phase 1 groundwork for archie-core-5zh. Stages call Forge.SetStateLabel/Comment/CreatePR/CloseIssue/CreateIssue/React/RepliesAfter mid-workflow. Forge holds live API tokens (Gitea/GitHub) that must stay daemon-side per the PRD's 'daemon never runs untrusted code, owns all secrets' boundary. Once workflow.Run moves into archie-agent, these calls need to become NATS request/reply RPCs to the daemon rather than shipping forge credentials into the agent container.","acceptance_criteria":"archie-agent can invoke the forge.Forge interface methods used by workflow stages over NATS; archied executes them against the real forge client and replies; no forge API tokens are present in the agent container.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.2","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-5zh.3","title":"Worktree push RPC proxy: archie-agent → archied for git push","description":"Phase 1 groundwork for archie-core-5zh. worktree.Manager.Push needs the forge HTTPS push token (held daemon-side, used via an askpass helper). Trees.Prepare/CommitAll/Diff/ChangedFiles/ChangedLines are local git operations against the already-mounted worktree and can run agent-side unchanged (containers already bind-mount /data/worktree) — only Push needs to be proxied back to the daemon, which holds the credential.","acceptance_criteria":"archie-agent can request a git push over NATS; archied performs the authenticated push using its held token and replies with success/failure; the push token is never sent to or stored in the agent container.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.3","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-5zh.4","title":"Move workflow.Route/workflow.Run stage loop into archie-agent","description":"Final step of archie-core-5zh, depends on the Store/Forge/push RPC proxies existing. Move workflow.Route + workflow.Run's stage-loop execution from internal/daemon/daemon.go's process() into cmd/archie-agent, using the RPC proxies for Store/Forge/push and reimplementing CustomStages discovery (wfeval.Discover) agent-side against the already-mounted worktree. daemon.process() keeps worktree prepare + container acquire/release, then hands off the whole task to archie-agent in one NATS round trip instead of one round trip per stage.","acceptance_criteria":"workflow.Route and workflow.Run execute inside archie-agent, not archied, when agent.mode=nats; archie-agent handles a full task (not a single stage) per invocation; inprocess/subprocess modes keep working unchanged.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.1","type":"blocks","created_at":"2026-07-24T07:55:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:44Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.3","type":"blocks","created_at":"2026-07-24T07:55:49Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.2","type":"blocks","created_at":"2026-07-24T07:55:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":3,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-5zh.1","title":"Store RPC proxy: archie-agent → archied for task state mutations","description":"Phase 1 groundwork for archie-core-5zh. workflow.Run calls tc.Store.Update every stage and tc.Store.Transition on terminal outcomes — Store wraps a direct SQLite *sql.DB handle that only the daemon owns. Once workflow.Run moves into archie-agent, these calls need to become NATS request/reply RPCs to the daemon (the sole DB owner), reusing the existing AgentRequestMessage/reply-inbox plumbing pattern (internal/agentexec/nats.go) rather than giving the agent container direct DB access.","acceptance_criteria":"archie-agent can call Store.Update and Store.Transition equivalents over NATS; archied executes them against SQLite and replies; no direct DB access from the agent container.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:43Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:58:51Z","started_at":"2026-07-23T21:55:58Z","closed_at":"2026-07-23T21:58:51Z","close_reason":"Added internal/storerpc: core-NATS request/reply RPC so archie-agent can call Store.Update/Transition without direct DB access. archied's Store stays the sole owner; store.Task gained json tags to cross the wire. Not yet wired into daemon.go or workflow.TaskContext — that's archie-core-5zh.4's job once all three RPC proxies exist.","dependencies":[{"issue_id":"archie-core-5zh.1","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"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-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":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:32Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:51:46Z","started_at":"2026-07-23T21:51:46Z","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":"closed","priority":2,"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:49:40Z","started_at":"2026-07-23T21:43:05Z","closed_at":"2026-07-23T21:49:40Z","close_reason":"Completed JetStream task dispatch and NATS agent request/reply, including token_env authentication for archied and canonical NATS_URL/NATS_TOKEN propagation to container workers; anonymous local mode remains supported and race-tested.","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} {"_type":"issue","id":"archie-core-rig","title":"Audit archie-core repo for bugs/improvements, file as Gitea issues","description":"Fan out exploration subagents across internal/ subsystems to find bugs, tech debt, and enhancement opportunities. Each confirmed finding gets filed as a Gitea issue on git.catlow.cloud/sam/archie-core.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-22T16:24:07Z","created_by":"Sam Catlow","updated_at":"2026-07-22T16:37:16Z","started_at":"2026-07-22T16:24:09Z","closed_at":"2026-07-22T16:37:16Z","close_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).","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-g1l","title":"Per-repo allow_concurrent override for same-repo multi-agent work","description":"Concurrent agents on the same repo are blocked by default (worktree conflict). PRD sec.9 open question 5 proposes a per-repo config override (allow_concurrent = true) for repos where parallel work is safe (different base branches, different packages). Deferred to Phase 2 in the PRD; depends on the daemon supporting concurrent task dispatch at all.","acceptance_criteria":"Repos with allow_concurrent = true in [[repos]] config can have multiple agents working simultaneously without worktree collisions; repos without it keep current serialized behavior.","status":"closed","priority":3,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:32Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:46:53Z","started_at":"2026-07-23T21:43:14Z","closed_at":"2026-07-23T21:46:53Z","close_reason":"Added config.Repo.AllowConcurrent (allow_concurrent toml key) and threaded it through taskDispatcher so opted-in repos skip the default FIFO same-repo serialization while still respecting containers.max_concurrency. Worktrees are already keyed per issue number, so no on-disk collision. Race-tested dispatcher coverage added.","dependencies":[{"issue_id":"archie-core-g1l","depends_on_id":"archie-core-u64","type":"blocks","created_at":"2026-07-24T05:36:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} diff --git a/internal/store/store.go b/internal/store/store.go index 9fadd493c..98f147b12 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -29,31 +29,31 @@ const ( ) type Task struct { - ID int64 - Owner string - Repo string - IssueNumber int - Title string - Body string - Labels string // comma-separated, as seen at enqueue time - Status string - Workflow string - Stage string - Branch string - Plan string - Notes string - PRNumber int - TokensUsed int - Iterations int - Attempt int - ParkReason string + ID int64 `json:"id"` + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + Title string `json:"title"` + Body string `json:"body"` + Labels string `json:"labels"` // comma-separated, as seen at enqueue time + Status string `json:"status"` + Workflow string `json:"workflow"` + Stage string `json:"stage"` + Branch string `json:"branch"` + Plan string `json:"plan"` + Notes string `json:"notes"` + PRNumber int `json:"pr_number"` + TokensUsed int `json:"tokens_used"` + Iterations int `json:"iterations"` + Attempt int `json:"attempt"` + ParkReason string `json:"park_reason"` // RetryCount tracks how many times a parked task has been retried // (parking-to-queued transitions). When it reaches the configured // max_retries the daemon moves the task to StatusDead. - RetryCount int + RetryCount int `json:"retry_count"` // WatchCommentID: replies to the issue after this comment are the // human input a waiting_human task is blocked on. - WatchCommentID int64 + WatchCommentID int64 `json:"watch_comment_id"` } type Store struct{ db *sql.DB } diff --git a/internal/storerpc/storerpc.go b/internal/storerpc/storerpc.go new file mode 100644 index 000000000..577e73964 --- /dev/null +++ b/internal/storerpc/storerpc.go @@ -0,0 +1,146 @@ +// Package storerpc lets archie-agent (which does not hold a database +// connection) mutate task state by calling back to archied over core NATS +// request/reply, instead of the agent process needing direct SQLite access. +// archied remains the sole owner of the store.Store. +package storerpc + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/nats-io/nats.go" + + "github.com/samcharles93/archie-core/internal/store" +) + +// Subjects for the two store.Store methods workflow stages call mid-run. +const ( + SubjectUpdate = "archie.store.update" + SubjectTransition = "archie.store.transition" +) + +// UpdateRequest mirrors store.Store.Update's argument. +type UpdateRequest struct { + Task *store.Task `json:"task"` +} + +// TransitionRequest mirrors store.Store.Transition's arguments. +type TransitionRequest struct { + TaskID int64 `json:"task_id"` + From string `json:"from"` + To string `json:"to"` + Detail string `json:"detail"` +} + +// Response carries the result of an RPC. Error is empty on success. +type Response struct { + Error string `json:"error,omitempty"` +} + +// Server handles storerpc requests against the daemon's Store. +type Server struct { + Store *store.Store + Log *slog.Logger +} + +// Register subscribes the update and transition handlers on nc. The +// returned func unsubscribes both. +func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) { + updateSub, err := nc.Subscribe(SubjectUpdate, s.handleUpdate) + if err != nil { + return nil, fmt.Errorf("subscribe %s: %w", SubjectUpdate, err) + } + transitionSub, err := nc.Subscribe(SubjectTransition, s.handleTransition) + if err != nil { + updateSub.Unsubscribe() + return nil, fmt.Errorf("subscribe %s: %w", SubjectTransition, err) + } + return func() { + updateSub.Unsubscribe() + transitionSub.Unsubscribe() + }, nil +} + +func (s *Server) handleUpdate(msg *nats.Msg) { + var req UpdateRequest + if err := json.Unmarshal(msg.Data, &req); err != nil { + s.reply(msg, fmt.Errorf("decode update request: %w", err)) + return + } + s.reply(msg, s.Store.Update(context.Background(), req.Task)) +} + +func (s *Server) handleTransition(msg *nats.Msg) { + var req TransitionRequest + if err := json.Unmarshal(msg.Data, &req); err != nil { + s.reply(msg, fmt.Errorf("decode transition request: %w", err)) + return + } + s.reply(msg, s.Store.Transition(context.Background(), req.TaskID, req.From, req.To, req.Detail)) +} + +func (s *Server) reply(msg *nats.Msg, err error) { + resp := Response{} + if err != nil { + resp.Error = err.Error() + } + data, encErr := json.Marshal(resp) + if encErr != nil { + if s.Log != nil { + s.Log.Error("storerpc: encode response failed", "err", encErr) + } + return + } + if err := msg.Respond(data); err != nil && s.Log != nil { + s.Log.Error("storerpc: respond failed", "err", err) + } +} + +// Client calls the storerpc Server from archie-agent's process. +type Client struct { + Conn *nats.Conn + // Timeout bounds each call when ctx has no deadline of its own. + Timeout time.Duration +} + +// Update calls store.Store.Update on the daemon over NATS request/reply. +func (c *Client) Update(ctx context.Context, task *store.Task) error { + data, err := json.Marshal(UpdateRequest{Task: task}) + if err != nil { + return fmt.Errorf("encode update request: %w", err) + } + return c.call(ctx, SubjectUpdate, data) +} + +// Transition calls store.Store.Transition on the daemon over NATS request/reply. +func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail string) error { + data, err := json.Marshal(TransitionRequest{TaskID: taskID, From: from, To: to, Detail: detail}) + if err != nil { + return fmt.Errorf("encode transition request: %w", err) + } + return c.call(ctx, SubjectTransition, data) +} + +func (c *Client) call(ctx context.Context, subject string, data []byte) error { + if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, c.Timeout) + defer cancel() + } + reply, err := c.Conn.RequestWithContext(ctx, subject, data) + if err != nil { + return fmt.Errorf("storerpc %s: %w", subject, err) + } + var resp Response + if err := json.Unmarshal(reply.Data, &resp); err != nil { + return fmt.Errorf("storerpc %s: decode response: %w", subject, err) + } + if resp.Error != "" { + return errors.New(resp.Error) + } + return nil +} diff --git a/internal/storerpc/storerpc_test.go b/internal/storerpc/storerpc_test.go new file mode 100644 index 000000000..549c575f0 --- /dev/null +++ b/internal/storerpc/storerpc_test.go @@ -0,0 +1,136 @@ +package storerpc + +import ( + "context" + "log/slog" + "testing" + "time" + + "github.com/nats-io/nats-server/v2/server" + natssrv "github.com/nats-io/nats-server/v2/test" + "github.com/nats-io/nats.go" + + "github.com/samcharles93/archie-core/internal/store" +) + +func startEmbedded(t *testing.T) *server.Server { + t.Helper() + srv := natssrv.RunRandClientPortServer() + t.Cleanup(srv.Shutdown) + return srv +} + +func connect(t *testing.T, url string) *nats.Conn { + t.Helper() + nc, err := nats.Connect(url) + if err != nil { + t.Fatalf("nats connect: %v", err) + } + t.Cleanup(nc.Close) + return nc +} + +func newTestServer(t *testing.T) (*store.Store, *nats.Conn, *Client) { + t.Helper() + s := store.OpenTest(t) + srv := startEmbedded(t) + url := srv.ClientURL() + + serverConn := connect(t, url) + rpcServer := &Server{Store: s, Log: slog.New(slog.DiscardHandler)} + unsub, err := rpcServer.Register(serverConn) + if err != nil { + t.Fatalf("register: %v", err) + } + t.Cleanup(unsub) + + clientConn := connect(t, url) + client := &Client{Conn: clientConn, Timeout: 2 * time.Second} + + return s, serverConn, client +} + +func enqueueTask(t *testing.T, s *store.Store) *store.Task { + t.Helper() + ctx := context.Background() + if _, err := s.EnqueueIssue(ctx, "sam", "archie", 1, "title", "body", ""); err != nil { + t.Fatalf("enqueue: %v", err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + return task +} + +func TestClientUpdatePersistsViaServer(t *testing.T) { + s, _, client := newTestServer(t) + task := enqueueTask(t, s) + + task.Workflow = "implement" + task.Stage = "plan" + task.Branch = "archie/1-test" + task.Plan = "do the thing" + task.Notes = "some notes" + task.PRNumber = 42 + task.TokensUsed = 1000 + task.Iterations = 3 + + if err := client.Update(context.Background(), task); err != nil { + t.Fatalf("Update: %v", err) + } + + got, err := s.TaskByIssue(context.Background(), "sam", "archie", 1) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Workflow != "implement" || got.Stage != "plan" || got.Branch != "archie/1-test" || + got.Plan != "do the thing" || got.Notes != "some notes" || got.PRNumber != 42 || + got.TokensUsed != 1000 || got.Iterations != 3 { + t.Fatalf("update did not persist over RPC, got %+v", got) + } +} + +func TestClientTransitionPersistsViaServer(t *testing.T) { + s, _, client := newTestServer(t) + task := enqueueTask(t, s) + + if err := client.Transition(context.Background(), task.ID, store.StatusRunning, store.StatusPROpen, "opened PR"); err != nil { + t.Fatalf("Transition: %v", err) + } + + got, err := s.TaskByIssue(context.Background(), "sam", "archie", 1) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Status != store.StatusPROpen { + t.Fatalf("expected status %s, got %s", store.StatusPROpen, got.Status) + } +} + +func TestClientPropagatesServerError(t *testing.T) { + s, _, client := newTestServer(t) + task := enqueueTask(t, s) + + // Close the store's underlying DB so the server-side call fails, + // and confirm that failure round-trips back to the client as an error. + if err := s.Close(); err != nil { + t.Fatalf("close store: %v", err) + } + + err := client.Update(context.Background(), task) + if err == nil { + t.Fatal("expected Update to return an error when the server-side store is closed") + } +} + +func TestClientUpdateTimesOutWithNoResponder(t *testing.T) { + srv := startEmbedded(t) + clientConn := connect(t, srv.ClientURL()) + client := &Client{Conn: clientConn, Timeout: 100 * time.Millisecond} + + err := client.Update(context.Background(), &store.Task{ID: 1}) + if err == nil { + t.Fatal("expected Update to time out with no server registered") + } +}