feat: worktree push RPC proxy for archie-agent (archie-core-5zh.3)

Add internal/worktreerpc: core NATS request/reply so archie-agent can
request a git push without holding the forge push token. The server
resolves the worktree directory itself from owner/repo/issue rather than
trusting a path from the sandboxed agent, then calls the daemon's own
worktree.Manager.Push (which already holds the token). Prepare, CommitAll,
Diff, ChangedFiles, and ChangedLines stay local git ops the agent can run
directly against its bind-mounted worktree — only Push needed proxying.

All three RPC proxies for archie-core-5zh now exist (Store, Forge,
worktree push); archie-core-5zh.4 (the actual stage-loop move) is
unblocked.
This commit is contained in:
sam committed 2026-07-24 08:05:15 +10:00
1 parent 65eda765ab
commit afa8c05ca7
4 files changed
+275 -1

No files matched your search

+1
View File
@@ -4,3 +4,4 @@
{"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."}}
{"id":"int-b4c080744419b9e5838f016f0f7e3d2f","kind":"field_change","created_at":"2026-07-23T22:02:41.482197412Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added internal/forgerpc: core-NATS request/reply RPC for the four forge.Forge methods workflow stages actually call mid-run (Comment, CloseIssue, CreatePR, SetStateLabel). Confirmed via grep that all other Forge methods (AssignedIssues, IssuesWithLabel, React, RepliesAfter, PRState, CreateIssue, AcceptInvitations, VerifyPush) are daemon-only poll/reconcile-loop calls, never invoked from a workflow stage, so nothing else needs proxying. archied stays the sole holder of forge API tokens. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4."}}
{"id":"int-94134ef6491261db5696279899fe6e9b","kind":"field_change","created_at":"2026-07-23T22:05:09.970642059Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added internal/worktreerpc: core-NATS request/reply RPC so archie-agent can request a git push without holding the forge push token. Server resolves the worktree directory itself from owner/repo/issue (never trusts a path from the sandboxed agent) and calls the daemon's own worktree.Manager.Push, which already holds the token via its askpass helper. Prepare/CommitAll/Diff/ChangedFiles/ChangedLines stay local git ops the agent can run directly against its bind-mounted worktree — only Push needed proxying. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4, which now has all three RPC proxies (Store, Forge, worktree push) it depends on."}}
+1 -1
View File
@@ -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.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":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:02:41Z","started_at":"2026-07-23T22:00:46Z","closed_at":"2026-07-23T22:02:41Z","close_reason":"Added internal/forgerpc: core-NATS request/reply RPC for the four forge.Forge methods workflow stages actually call mid-run (Comment, CloseIssue, CreatePR, SetStateLabel). Confirmed via grep that all other Forge methods (AssignedIssues, IssuesWithLabel, React, RepliesAfter, PRState, CreateIssue, AcceptInvitations, VerifyPush) are daemon-only poll/reconcile-loop calls, never invoked from a workflow stage, so nothing else needs proxying. archied stays the sole holder of forge API tokens. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4.","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.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":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:05:10Z","started_at":"2026-07-23T22:02:54Z","closed_at":"2026-07-23T22:05:10Z","close_reason":"Added internal/worktreerpc: core-NATS request/reply RPC so archie-agent can request a git push without holding the forge push token. Server resolves the worktree directory itself from owner/repo/issue (never trusts a path from the sandboxed agent) and calls the daemon's own worktree.Manager.Push, which already holds the token via its askpass helper. Prepare/CommitAll/Diff/ChangedFiles/ChangedLines stay local git ops the agent can run directly against its bind-mounted worktree — only Push needed proxying. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4, which now has all three RPC proxies (Store, Forge, worktree push) it depends on.","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}
+115
View File
@@ -0,0 +1,115 @@
// Package worktreerpc lets archie-agent request a git push over core NATS
// request/reply instead of holding the forge push token itself. archied
// remains the sole holder of worktree.Manager.Token and performs the push
// against the host worktree directory (the same files the agent container
// has bind-mounted at /data/worktree).
//
// Only Push is proxied. Prepare/CommitAll/Diff/ChangedFiles/ChangedLines
// are local git operations against the already-mounted worktree and don't
// need the push credential, so they can run directly inside archie-agent.
package worktreerpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/worktree"
)
const SubjectPush = "archie.worktree.push"
// PushRequest identifies the task's worktree by owner/repo/issue rather
// than trusting a path from the (sandboxed) agent — the server resolves
// the directory itself via worktree.Manager.Dir.
type PushRequest struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Issue int `json:"issue"`
Branch string `json:"branch"`
}
type Response struct {
Error string `json:"error,omitempty"`
}
// Server proxies push requests to a real worktree.Manager holding the
// forge push token.
type Server struct {
Trees *worktree.Manager
Log *slog.Logger
}
// Register subscribes the push handler on nc. The returned func unsubscribes it.
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
sub, err := nc.Subscribe(SubjectPush, s.handlePush)
if err != nil {
return nil, fmt.Errorf("subscribe %s: %w", SubjectPush, err)
}
return func() { sub.Unsubscribe() }, nil
}
func (s *Server) handlePush(msg *nats.Msg) {
var req PushRequest
if err := json.Unmarshal(msg.Data, &req); err != nil {
s.respond(msg, fmt.Errorf("decode push request: %w", err))
return
}
dir := s.Trees.Dir(req.Owner, req.Repo, req.Issue)
s.respond(msg, s.Trees.Push(context.Background(), dir, req.Branch))
}
func (s *Server) respond(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("worktreerpc: encode response failed", "err", encErr)
}
return
}
if err := msg.Respond(data); err != nil && s.Log != nil {
s.Log.Error("worktreerpc: respond failed", "err", err)
}
}
// Client calls the worktreerpc 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
}
// Push requests that archied push branch for owner/repo/issue's worktree
// using its held forge credential.
func (c *Client) Push(ctx context.Context, owner, repo string, issue int, branch string) error {
data, err := json.Marshal(PushRequest{Owner: owner, Repo: repo, Issue: issue, Branch: branch})
if err != nil {
return fmt.Errorf("encode push request: %w", err)
}
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, SubjectPush, data)
if err != nil {
return fmt.Errorf("worktreerpc %s: %w", SubjectPush, err)
}
var resp Response
if err := json.Unmarshal(reply.Data, &resp); err != nil {
return fmt.Errorf("worktreerpc %s: decode response: %w", SubjectPush, err)
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
+158
View File
@@ -0,0 +1,158 @@
package worktreerpc
import (
"context"
"log/slog"
"os"
"os/exec"
"path/filepath"
"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/worktree"
)
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
}
// newLocalRemote creates a bare repo with one commit on main, reachable
// via file://<host>/<owner>/<repo>.git — mirrors worktree_test.go's helper.
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
}
func remoteHasBranch(t *testing.T, host, owner, repo, branch string) bool {
t.Helper()
bare := filepath.Join(host, owner, repo+".git")
cmd := exec.Command("git", "ls-remote", "--heads", bare, branch)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("ls-remote: %v\n%s", err, out)
}
return len(out) > 0
}
func TestClientPushPublishesViaServer(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
ctx := context.Background()
host := newLocalRemote(t, "sam", "archie")
m := &worktree.Manager{
WorkDir: t.TempDir(),
Token: "unused-for-file-remotes",
BotUser: "archie-bot",
BotEmail: "archie-bot@example.com",
BaseURL: "file://" + host,
}
dir, branch, err := m.Prepare(ctx, "sam", "archie", "main", 1, "feat: test", "", "")
if err != nil {
t.Fatalf("prepare: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("hi\n"), 0o644); err != nil {
t.Fatal(err)
}
if changed, err := m.CommitAll(ctx, dir, "add hello"); err != nil || !changed {
t.Fatalf("CommitAll = (%v, %v)", changed, err)
}
srv := startEmbedded(t)
url := srv.ClientURL()
rpcServer := &Server{Trees: m, Log: slog.New(slog.DiscardHandler)}
unsub, err := rpcServer.Register(connect(t, url))
if err != nil {
t.Fatalf("register: %v", err)
}
t.Cleanup(unsub)
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
if err := client.Push(ctx, "sam", "archie", 1, branch); err != nil {
t.Fatalf("Push: %v", err)
}
if !remoteHasBranch(t, host, "sam", "archie", branch) {
t.Fatalf("branch %q was not pushed to the remote", branch)
}
}
func TestClientPropagatesServerError(t *testing.T) {
m := &worktree.Manager{WorkDir: t.TempDir()}
srv := startEmbedded(t)
url := srv.ClientURL()
rpcServer := &Server{Trees: m, Log: slog.New(slog.DiscardHandler)}
unsub, err := rpcServer.Register(connect(t, url))
if err != nil {
t.Fatalf("register: %v", err)
}
t.Cleanup(unsub)
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
// No worktree ever prepared at this dir — push must fail.
err = client.Push(context.Background(), "sam", "nonexistent", 999, "some-branch")
if err == nil {
t.Fatal("expected Push to propagate the server-side git error")
}
}
func TestClientPushTimesOutWithNoResponder(t *testing.T) {
srv := startEmbedded(t)
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 100 * time.Millisecond}
err := client.Push(context.Background(), "sam", "archie", 1, "branch")
if err == nil {
t.Fatal("expected Push to time out with no server registered")
}
}