From 3a0dfa924d7e8f106b9f5be0ad898973c440820f Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 7 Sep 2026 05:06:12 +1000 Subject: [PATCH] refactor(state-store): cut daemon/Gateway over to the remote State Store (archie-core-8cda.4.6) (#774) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(state-store): delete NATS storerpc; agent store is gRPC-only (archie-core-8cda.4.6) The agent is fully on the gRPC State Store contract, so the legacy NATS storerpc path is dead (docs/prds/state-store-contract.md §12 step 4): - delete internal/storerpc (Server, Client, subjects) and its tests - drop the storerpc registration from registerTaskRPCServers and the now-unused store param - make the agent transport's State Store URL required and Store() return only the gRPC staterpc.Client (no NATS fallback) - rework agentworker/agent transport tests to back the store with a real gRPC State Store server instead of the deleted NATS storerpc server The agent binary now fails fast when STATE_STORE_URL is absent. Agent store calls (workflow.Store) go over gRPC to the archie-state-store service. * refactor(state-store): delete daemon/gateway in-process store ownership (archie-core-8cda.4.6) The daemon and gateway no longer open archie.db in-process: the single SQLite file is owned by the standalone archie-state-store process, and both consumers dial its gRPC State StateStore contract (docs/prds/state-store-contract.md §12 step 7, no dual-store ownership). - openStores no longer opens the production task store or seeds b.st; it only wires secrets/forge and the gateway conversation store - openStateStoreAdapter now requires [services.state].target (the old local default is deleted) and resolves b.stateStore as the remote *staterpc.Client - delete the in-process startStateStoreServer (the multiplexed gRPC server and its per-task bearer-token registry) from the daemon composition - RunGateway now resolves the same remote State Store adapter; its session SQLite stays Gateway-owned and untouched - daemon.ConnectedStateStore carries the configured target plus the resolved bearer token, which containerEnv injects as STATE_STORE_URL / STATE_STORE_TOKEN so archie-agent authenticates to the same remote service - readiness store probe reads b.stateStore PRD-consistent choice (noted): with the in-process server gone, per-task token generation is removed; the daemon/gateway/agent all present the single [services.state].target_token (or STATE_STORE_TOKEN secret) that the standalone store validates. * docs(webui): require [services.state].target in config and deployment templates (archie-core-8cda.4.6) After the in-process store path is deleted, archied and archie-gateway dial the standalone archie-state-store gRPC service via [services.state].target and never open archie.db themselves (docs/prds/state-store-contract.md §12 step 7). - config.example.toml documents [services.state].target as required, with the loopback vs Docker-bridge gateway + target_token rule - deployment templates set [services.state] per topology: bridge gateway + token for container-mode agents, loopback for host-only - deployments/README.md and systemd-user-service.md describe start commands for both topologies and drop the stale "not yet consumed by the daemon" note * style: gofumpt alignment for State Store daemon literal; appease noctx/staticcheck (archie-core-8cda.4.6) * docs(state-store): refresh stale in-process references post-cutover (archie-core-8cda.4.6) --- cmd/archie-agent/main.go | 7 +- cmd/archie-agent/main_test.go | 5 +- config.example.toml | 29 ++- deployments/README.md | 23 ++- deployments/docker-nats-stack.toml | 10 + deployments/local-ollama-standalone.toml | 8 + deployments/multi-forge-github-gitea.toml | 10 + deployments/single-forge-github.toml | 13 ++ deployments/systemd-user-service.md | 20 +- .../app/agentworker/task_execution_test.go | 39 ++-- internal/app/agentworker/worker.go | 8 +- internal/app/archied/bootstrap.go | 174 +++++------------- .../archied/chat_store_composition_test.go | 8 +- internal/app/archied/gateway.go | 14 +- internal/app/archied/main.go | 57 +++--- internal/app/archied/main_test.go | 19 +- internal/app/archied/readiness.go | 2 +- internal/app/archied/state_store.go | 4 +- internal/app/archied/state_store_client.go | 18 +- .../app/archied/state_store_client_test.go | 23 +-- .../app/archied/state_store_consumers_test.go | 16 +- internal/daemon/daemon.go | 113 +++--------- internal/daemon/terminal_cleanup_test.go | 2 +- internal/domain/workflow/task.go | 4 +- .../agenttransport/nats/transport.go | 64 ++++--- .../agenttransport/nats/transport_test.go | 12 +- .../infrastructure/eventbus/nats/client.go | 4 +- internal/natsrpc/natsrpc.go | 6 +- internal/storerpc/storerpc.go | 137 -------------- internal/storerpc/storerpc_test.go | 153 --------------- internal/taskrun/taskrun.go | 7 +- 31 files changed, 328 insertions(+), 681 deletions(-) delete mode 100644 internal/storerpc/storerpc.go delete mode 100644 internal/storerpc/storerpc_test.go diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index 2c7a45c2b..86248b3a8 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -29,7 +29,7 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run flags := flag.NewFlagSet("archie-agent", flag.ContinueOnError) flags.SetOutput(stderr) natsURLFlag := flags.String("nats-url", "", "NATS server URL (defaults to NATS_URL)") - stateStoreURLFlag := flags.String("state-store-url", "", "State Store gRPC target (defaults to STATE_STORE_URL; empty uses the legacy NATS storerpc path)") + stateStoreURLFlag := flags.String("state-store-url", "", "State Store gRPC target (defaults to STATE_STORE_URL; required -- the legacy NATS storerpc path is deleted)") stateStoreTokenFlag := flags.String("state-store-token", "", "State Store bearer token (defaults to STATE_STORE_TOKEN)") if err := flags.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { @@ -53,6 +53,11 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run if stateStoreURL == "" { stateStoreURL = getenv("STATE_STORE_URL") } + if stateStoreURL == "" { + fmt.Fprintln(stderr, "error: -state-store-url or STATE_STORE_URL is required (the legacy NATS storerpc path is deleted)") + flags.Usage() + return 1 + } stateStoreToken := *stateStoreTokenFlag if stateStoreToken == "" { stateStoreToken = getenv("STATE_STORE_TOKEN") diff --git a/cmd/archie-agent/main_test.go b/cmd/archie-agent/main_test.go index 8282f189f..de8a28933 100644 --- a/cmd/archie-agent/main_test.go +++ b/cmd/archie-agent/main_test.go @@ -23,9 +23,10 @@ func TestRunCommandPreservesCLIExitSemantics(t *testing.T) { {name: "flag parse error", args: []string{"-unknown"}, wantCode: 2}, {name: "removed consumer flag", args: []string{"-consumer", "legacy"}, wantCode: 2}, {name: "missing NATS URL", wantCode: 1}, + {name: "missing state store URL", args: []string{"-nats-url", "nats://test"}, wantCode: 1}, { name: "worker failure", - args: []string{"-nats-url", "nats://test"}, + args: []string{"-nats-url", "nats://test", "-state-store-url", "127.0.0.1:9090"}, worker: func(context.Context, agentworker.Settings, *slog.Logger) error { return errors.New("worker failed") }, @@ -33,7 +34,7 @@ func TestRunCommandPreservesCLIExitSemantics(t *testing.T) { }, { name: "success", - args: []string{"-nats-url", "nats://test"}, + args: []string{"-nats-url", "nats://test", "-state-store-url", "127.0.0.1:9090"}, worker: func(context.Context, agentworker.Settings, *slog.Logger) error { return nil }, diff --git a/config.example.toml b/config.example.toml index eda28799a..402c3f698 100644 --- a/config.example.toml +++ b/config.example.toml @@ -261,25 +261,24 @@ max_steps = 60 wall_clock = "30m" gate_max_failures = 5 -# Services selects contract adapters at composition time. Leave the section -# absent to use every adapter's default (see docs/prds/state-store-contract.md). +# Services selects contract adapters at composition time (see +# docs/prds/state-store-contract.md). # [services.gateway] # target = "127.0.0.1:8585" # archie-gateway's gRPC address (always remote once set) # [services.state] -# target = "" # empty (default) = local *store.Store adapter. -# target_token = "..." # bearer token for a NON-loopback listener. The standalone -# # archie-state-store server validates this; a loopback -# # bind (127.0.0.1/::1/localhost) needs no token. Non-loopback -# # without a token fails closed (docs/prds/state-store-contract.md §9). -# # The standalone archie-state-store binary (.4.3) consumes -# # this surface; the daemon reads [services.state].target to -# # route its own capture/mapping/binding AND task-lifecycle / -# # workflow / intake consumers to the remote store -# # (docs/prds/state-store-contract.md §10/§12 step 6). The -# # daemon still serves the State Store gRPC service in-process -# # until that path is deleted (.4.6); staying empty (the -# # default) keeps every consumer on the in-process local store. +# target = "127.0.0.1:9090" # REQUIRED. The State Store gRPC address archied and +# # archie-gateway dial. They no longer own archie.db +# # in-process: the standalone archie-state-store process +# # owns the single SQLite file (docs/prds/state-store-contract.md +# # §10/§12 step 7). An empty target is a startup error. +# target_token = "..." # bearer token for a NON-loopback target. A loopback target +# # (127.0.0.1/::1/localhost) needs no token. A non-loopback +# # target without a token fails closed (docs/prds/state-store-contract.md +# # §9). The same token is injected as STATE_STORE_TOKEN into +# # archie-agent containers so the agent authenticates to the +# # same remote store. See deployments/README.md for how to +# # start archie-state-store. # NATS is the sole autonomous workflow handoff. mode changes only where the # broker runs; every workflow still runs in a managed task container: diff --git a/deployments/README.md b/deployments/README.md index 5ab81eb30..a1eace034 100644 --- a/deployments/README.md +++ b/deployments/README.md @@ -44,9 +44,20 @@ The templates use the extracted Gateway Service by default. Start `archie-gateway` before `archied`; it owns the conversation SQLite file and serves the `ChatContract` gRPC API on the configured target. -The State Store service (`archie-state-store`) is `.4.3`: it owns the single -`archie.db` task SQLite file and serves the `StateStore` gRPC contract. It is -not yet consumed by the daemon (which still serves the store in-process), so -running it now is only needed once the daemon points at it — the loopback -bind above is the safe default, and a non-loopback bind requires a bearer -token (`--token` / `STATE_STORE_TOKEN` / `[services.state].target_token`). +The State Store service (`archie-state-store`) owns the single `archie.db` task +SQLite file and serves the `StateStore` gRPC contract. After the in-process +store path was deleted, BOTH `archied` and `archie-gateway` dial it via +`[services.state].target` and never open `archie.db` themselves +(`docs/prds/state-store-contract.md` §12 step 7). The templates set +`[services.state]` accordingly: a host-only agent reaches a loopback bind +(`127.0.0.1:9090`) with no token, while a container-mode agent needs the +Docker bridge gateway address plus a matching bearer token (`target_token` / +`--token` / `STATE_STORE_TOKEN`), because a container cannot reach the host's +loopback. + +```bash +# loopback (host-only agent) +archie-state-store -config ~/.config/archie/config.toml -listen 127.0.0.1:9090 +# or container-mode: bind the bridge gateway with a token +archie-state-store -config ~/.config/archie/config.toml -listen 172.17.0.1:9090 -token +``` diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index a523c611a..d640086ed 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -20,6 +20,16 @@ db_path = "~/.local/share/archie/archie.db" [services.gateway] target = "127.0.0.1:8585" +# The State Store gRPC service owns the single archie.db SQLite file; archied +# and archie-gateway dial it and never open archie.db themselves (§12 step 7). +# This deployment runs the agent in containers, so target is the Docker bridge +# gateway (172.17.0.1) the container can reach, with a matching target_token +# that archie-state-store validates. Host-only agent: use 127.0.0.1:9090 with +# no token. +[services.state] +target = "172.17.0.1:9090" +target_token = "change-me-state-store-token" + [forge] type = "gitea" host = "https://git.example.com" diff --git a/deployments/local-ollama-standalone.toml b/deployments/local-ollama-standalone.toml index 185fcf878..2c5bba6df 100644 --- a/deployments/local-ollama-standalone.toml +++ b/deployments/local-ollama-standalone.toml @@ -12,6 +12,14 @@ db_path = "~/.local/share/archie/archie.db" target = "127.0.0.1:8585" poll_interval = "60s" +# The State Store gRPC service owns the single archie.db SQLite file; archied +# and archie-gateway dial it and never open archie.db themselves (§12 step 7). +# Host-only deployment: the agent runs on the host, so the loopback target +# 127.0.0.1:9090 needs no token. Start archie-state-store with the matching +# `-listen 127.0.0.1:9090`. +[services.state] +target = "127.0.0.1:9090" + # Standalone execution: Forge polling is disabled [forge] type = "none" diff --git a/deployments/multi-forge-github-gitea.toml b/deployments/multi-forge-github-gitea.toml index fa011c839..8a75a29db 100644 --- a/deployments/multi-forge-github-gitea.toml +++ b/deployments/multi-forge-github-gitea.toml @@ -13,6 +13,16 @@ db_path = "~/.local/share/archie/archie.db" target = "127.0.0.1:8585" poll_interval = "60s" +# The State Store gRPC service owns the single archie.db SQLite file; archied +# and archie-gateway dial it and never open archie.db themselves (§12 step 7). +# This deployment runs the agent in containers, so target is the Docker bridge +# gateway (172.17.0.1) the container can reach, with a matching target_token +# that archie-state-store validates. Host-only agent: use 127.0.0.1:9090 with +# no token. +[services.state] +target = "172.17.0.1:9090" +target_token = "change-me-state-store-token" + [models] triage = "openai/gpt-4o" planner = "openai/gpt-4o" diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index 9dc240df2..a2fadf06a 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -18,6 +18,19 @@ diff_cap_lines = 400 [services.gateway] target = "127.0.0.1:8585" +# The State Store gRPC service owns the single archie.db SQLite file. archied +# and archie-gateway dial it here and never open archie.db themselves +# (docs/prds/state-store-contract.md §12 step 7). This deployment runs the +# agent in containers, so the target must be the Docker bridge gateway address +# (172.17.0.1) that the container can reach, and a non-loopback target requires +# a matching target_token that archie-state-store validates -- start it with the +# same token (e.g. `archie-state-store ... -listen 172.17.0.1:9090 -token +# change-me-state-store-token`). For a host-only agent (no [containers]) use the +# loopback target 127.0.0.1:9090 with no token. +[services.state] +target = "172.17.0.1:9090" +target_token = "change-me-state-store-token" + [forge] type = "github" host = "https://github.com" diff --git a/deployments/systemd-user-service.md b/deployments/systemd-user-service.md index e73f9764a..d90b66887 100644 --- a/deployments/systemd-user-service.md +++ b/deployments/systemd-user-service.md @@ -44,11 +44,14 @@ WantedBy=default.target ``` Create the State Store unit beside it. It owns the single `archie.db` SQLite -file and serves the `StateStore` gRPC contract. It is not yet consumed by the -daemon during the `.4.2`/`.4.3` split (the daemon still serves in-process), so -the loopback bind with no token is the correct default; a non-loopback bind -requires a bearer token via `--token`/`STATE_STORE_TOKEN` or -`[services.state].target_token` and fails closed without one: +file and serves the `StateStore` gRPC contract. After the in-process store path +was deleted, BOTH `archied` and `archie-gateway` dial it via +`[services.state].target` (see the `archied` config below) and never open +`archie.db` themselves (`docs/prds/state-store-contract.md` §12 step 7). A +host-only agent uses the loopback bind with no token below; a container-mode +agent needs the Docker bridge gateway address plus a bearer token via +`--token`/`STATE_STORE_TOKEN` or `[services.state].target_token`, and a +non-loopback bind fails closed without one: ```ini [Unit] @@ -142,6 +145,13 @@ binds the authenticated embedded broker only to that bridge's host gateway, and passes the resulting endpoint to each worker. There is no port to publish and no broker URL to maintain. +The State Store is a separate process and, with a container-mode agent, must +be reachable from the container, so bind it to the same bridge gateway with a +token and point `[services.state].target` at it (start +`archie-state-store` with `-listen :9090 -token `); without a +token a non-loopback bind fails closed. For a host-only agent, `127.0.0.1:9090` +with no token is correct. + If Docker or the image is unavailable, `archied` still serves chat and the dashboard. Autonomous tasks park with an explicit capability error; they never fall back to a host model loop. diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 614f3804e..8da17d3fc 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "log/slog" + "net" "os" "os/exec" "path/filepath" @@ -16,6 +17,7 @@ import ( "github.com/nats-io/nats-server/v2/server" natssrv "github.com/nats-io/nats-server/v2/test" natsio "github.com/nats-io/nats.go" + "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" @@ -24,9 +26,9 @@ import ( "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/forgerpc" agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats" + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/installtype" "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" @@ -318,6 +320,27 @@ func connectTaskRPC(t *testing.T, url string) *natsio.Conn { return connection } +// startStateStoreGRPC serves the State Store gRPC contract over a loopback +// TCP listener fronting local, returning the dial address. The agent is fully +// on gRPC for its store calls (docs/prds/state-store-contract.md §12 step 4), +// so an agentworker test that drives executeTaskRequest needs a real State +// Store server rather than the deleted NATS storerpc path. +func startStateStoreGRPC(t *testing.T, local *store.Store) string { + t.Helper() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + staterpc.RegisterServer(server, staterpc.Deps{ + Tasks: local, Captures: local, Mappings: local, Bindings: local, + BindingDispatcher: local, BindingTaskCreator: local, + }) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Stop(); _ = listener.Close() }) + return listener.Addr().String() +} + func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not installed") @@ -418,11 +441,6 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) { srv := startEmbeddedTaskRPCServer(t) serverConn := connectTaskRPC(t, srv.ClientURL()) - unsubStore, err := (&storerpc.Server{Store: st, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) - if err != nil { - t.Fatal(err) - } - t.Cleanup(unsubStore) unsubForge, err := (&forgerpc.Server{Forge: forge, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) if err != nil { t.Fatal(err) @@ -434,7 +452,7 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) { } t.Cleanup(unsubTrees) - transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL()}, slog.New(slog.DiscardHandler)) + transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL(), StateStoreURL: startStateStoreGRPC(t, st)}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatal(err) } @@ -515,11 +533,6 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) { srv := startEmbeddedTaskRPCServer(t) serverConn := connectTaskRPC(t, srv.ClientURL()) - unsubStore, err := (&storerpc.Server{Store: st, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) - if err != nil { - t.Fatal(err) - } - t.Cleanup(unsubStore) unsubForge, err := (&forgerpc.Server{Forge: forge, Log: slog.New(slog.DiscardHandler)}).Register(serverConn) if err != nil { t.Fatal(err) @@ -557,7 +570,7 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) { t.Fatal(err) } - transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL()}, slog.New(slog.DiscardHandler)) + transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL(), StateStoreURL: startStateStoreGRPC(t, st)}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatal(err) } diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index d0bbe158a..341651c01 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -34,10 +34,10 @@ type Settings struct { WorkDir string // StateStoreTarget and StateStoreToken are the daemon-injected State - // Store gRPC endpoint and per-task bearer token (docs/prds/ - // state-store-contract.md §6: STATE_STORE_URL/STATE_STORE_TOKEN, - // mirroring the NATS_URL/NATS_TOKEN handoff). Empty keeps the legacy - // NATS storerpc path for workflow.Store. + // Store gRPC endpoint and bearer token (docs/prds/state-store-contract.md + // §6: STATE_STORE_URL/STATE_STORE_TOKEN, mirroring the NATS_URL/NATS_TOKEN + // handoff). StateStoreTarget is required: the legacy NATS storerpc path + // is deleted (docs/prds/state-store-contract.md §12 step 4). StateStoreTarget string StateStoreToken string } diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index f1e866eda..77f380d85 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "log/slog" - "net" "net/http" "os" "os/signal" @@ -24,7 +23,6 @@ import ( "time" "github.com/samcharles93/ai-sdk/runtime" - "google.golang.org/grpc" channelruntime "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/email" @@ -52,7 +50,6 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" "github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator" "github.com/samcharles93/archie-core/internal/infrastructure/skillcurator" - "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/memory" @@ -102,21 +99,16 @@ type boot struct { playbooks *playbook.Store st store.TaskStore - // stateStore is the State Store contract adapter the daemon's own - // store consumers depend on. It is the in-process *store.Store (the - // same one b.st holds) unless [services.state].target is set, in which - // case it is a remote *staterpc.Client dialed to the standalone - // archie-state-store gRPC service. openStores seeds it from b.st so it - // is never nil in any composition (daemon or gateway); the daemon's - // openStateStoreAdapter upgrades it to the remote client when the seam - // is set (the gateway never calls openStateStoreAdapter, so it stays on - // the local adapter). During .4.5 the workflow/intake/task-lifecycle - // consumers (the TaskStore composite) resolve through this field, so a - // consumer mixes in-process and remote contracts per contract-code while - // the daemon's own local store stays in-process; the in-process State - // Store gRPC server keeps fronting b.st for the agent until .4.6 - // (docs/prds/state-store-contract.md §12 step 6). + // stateStore is the State Store contract adapter every daemon and gateway + // store consumer depends on. It is ALWAYS the remote *staterpc.Client + // dialed to the standalone archie-state-store gRPC service at + // [services.state].target (the daemon and gateway no longer own archie.db + // in-process, per docs/prds/state-store-contract.md §12 step 7). It is set + // by openStateStoreAdapter, which requires [services.state].target to be + // set. The b.st field remains solely for the standalone archie-state-store + // binary, which owns the single SQLite file. stateStore store.TaskStore + stateStoreToken string chatSessionStore gateway.SessionStore catalog modelcatalog.Snapshot @@ -283,49 +275,30 @@ func (b *boot) openStores(ctx context.Context) error { b.secrets = secrets b.forgeClient, b.token = resolveForge(cfg.Forge, secrets, log) - bindingCipher, err := bindingCipherFromConfig(cfg, secrets) - if err != nil { - log.Error("configure bindings cipher", "err", err) - return err - } - - st, err := openProductionTaskStore(ctx, taskDBPath(cfg.DBPath), store.WithBindingCipher(bindingCipher)) - if err != nil { - log.Error("open store", "err", err) - return err - } - b.st = st - // Seed the State Store contract adapter from the just-opened in-process - // store so it is never nil in any composition (Run and RunGateway both - // open b.st here). The daemon's openStateStoreAdapter upgrades it to a - // remote *staterpc.Client when [services.state].target is set; the - // gateway never calls openStateStoreAdapter, so it stays on this local - // adapter and never dials remote (docs/prds/state-store-contract.md §10). - b.stateStore = st - b.addCleanup(func() { - if err := st.Close(); err != nil { - log.Error("close store", "err", err) - } - }) + // The daemon and gateway no longer open archie.db directly: the single + // SQLite file is owned by the standalone archie-state-store process, and + // both consumers dial its gRPC State Store contract. openStateStoreAdapter + // (called by Run and RunGateway after openStores) resolves b.stateStore as + // the remote *staterpc.Client. There is no local store to open here + // (docs/prds/state-store-contract.md §12 step 7, no dual-store ownership). return b.openChatSessions(ctx) } -// openStateStoreAdapter upgrades the State Store contract adapter to the -// remote *staterpc.Client when [services.state].target is set; otherwise it -// leaves the in-process adapter seeded by openStores (the default -- the -// State Store service is not yet extracted into its own process), so this is -// additive and behaviour-neutral until an operator flips the seam -// (docs/prds/state-store-contract.md §10). openStores already seeds -// b.stateStore = b.st, so the empty-target branch is an idempotent no-op that -// keeps the default explicit. Called only from the daemon's composition (the -// gateway does not consume these surfaces via a remote adapter), so a gateway -// config that happens to carry [services.state].target can never dial (or fail -// closed against) a state store it does not use. It runs after openStores has -// opened b.st and resolved b.secrets. +// openStateStoreAdapter resolves the State Store contract adapter as the +// remote *staterpc.Client dialed to [services.state].target, so every daemon +// and gateway store consumer uses one endpoint -- the standalone +// archie-state-store service. It requires [services.state].target to be set: +// after .4.6 the daemon and gateway no longer own archie.db in-process, so the +// local default of earlier phases is removed (no dual-store ownership; +// docs/prds/state-store-contract.md §12 step 7). The token the daemon also +// injects into agent containers (STATE_STORE_TOKEN) is the same one this +// client authenticates with, resolved from [services.state].target_token or +// the STATE_STORE_TOKEN secret (§10). It runs after openStores has resolved +// b.secrets, and before setupObservability / buildDaemon wire consumers. func (b *boot) openStateStoreAdapter() error { - if strings.TrimSpace(b.cfg.Services.State.Target) == "" { - b.stateStore = b.st - return nil + target := strings.TrimSpace(b.cfg.Services.State.Target) + if target == "" { + return fmt.Errorf("services.state.target is required: archied/archie-gateway no longer own archie.db; the standalone archie-state-store process owns it (docs/prds/state-store-contract.md §12 step 7)") } client, cleanup, err := composeStateStoreClient(b.cfg.Services.State, b.secrets) if err != nil { @@ -333,6 +306,7 @@ func (b *boot) openStateStoreAdapter() error { return err } b.stateStore = client + b.stateStoreToken = stateStoreResolvedToken(b.cfg.Services.State, b.secrets) b.addCleanup(cleanup) return nil } @@ -913,7 +887,7 @@ func (b *boot) registerNATSRPC() error { return err } b.worktreeGrants = worktreerpc.NewGrants() - unsubscribe, err := registerTaskRPCServers(coreConn, b.st, b.forgeClient, b.trees, b.identityRunners, b.worktreeGrants, log) + unsubscribe, err := registerTaskRPCServers(coreConn, b.forgeClient, b.trees, b.identityRunners, b.worktreeGrants, log) if err != nil { log.Error("task RPC server registration failed", "err", err) return err @@ -1283,24 +1257,25 @@ func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) { func (b *boot) buildDaemon() { cfg, log := b.cfg, b.log b.d = &daemon.Daemon{ - Cfg: config.NewHolder(cfg), - ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken}, - Store: b.stateStore, - Bus: b.bus, - Forge: b.forgeClient, - Trees: b.trees, - CapabilityHost: b.capabilityHost, - Storage: b.storeBackend, - Log: log, - Tasks: b.natsClient, - WorktreeGrants: b.worktreeGrants, - ContainerPool: b.containerPool, - Guardrails: b.guardrails, - ToolRegistry: b.toolReg, - Curators: b.curatorRegistry, - Identities: b.identityRunners, - TaskLogs: b.taskLogs, - AgentStatus: b.agentStatus, + Cfg: config.NewHolder(cfg), + ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken}, + ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.State.Target), Token: b.stateStoreToken}, + Store: b.stateStore, + Bus: b.bus, + Forge: b.forgeClient, + Trees: b.trees, + CapabilityHost: b.capabilityHost, + Storage: b.storeBackend, + Log: log, + Tasks: b.natsClient, + WorktreeGrants: b.worktreeGrants, + ContainerPool: b.containerPool, + Guardrails: b.guardrails, + ToolRegistry: b.toolReg, + Curators: b.curatorRegistry, + Identities: b.identityRunners, + TaskLogs: b.taskLogs, + AgentStatus: b.agentStatus, } b.web.TaskStopper = b.d // Curator observability (archie-core-1786637489932-6): GET @@ -1331,55 +1306,6 @@ func (b *boot) buildDaemon() { b.setupForgeWebhook() } -// startStateStoreServer serves the State Store gRPC service in-process -// (multiplexed inside archied), so archie-agent has a gRPC target before the -// standalone archie-state-store binary exists (docs/prds/ -// state-store-contract.md §12 step 3). Listener topology follows §9's single -// rule: bind the host-gateway bridge address with mandatory per-task bearer -// tokens when agent containers can reach this daemon, or loopback-only with -// no token when there is no container pool to serve. Failure degrades -// (archie-agent falls back to the legacy NATS storerpc path) rather than -// aborting boot -- the State Store's in-process server is additive during -// .4.2, not yet load-bearing. -func (b *boot) startStateStoreServer(ctx context.Context) { - log := b.log - // The in-process server fronts the daemon's LOCAL store surfaces, not the - // consumer-facing b.d.* adapters: during .4.4 the daemon may route its own - // capture/mapping/binding consumers to a remote *staterpc.Client via - // [services.state].target, but the daemon still OWNS archie.db in-process - // and the agent's gRPC target must keep answering from that same local - // file (no dual-store ownership, docs/prds/state-store-contract.md §9/§12 - // step 6). Deletion of the in-process serving path is .4.6. - deps := b.stateStoreDeps() - - host := "127.0.0.1" - var opts []grpc.ServerOption - if b.containerPool != nil { - if bridge := b.containerPool.HostGateway(); bridge != "" { - host = bridge - tokens := daemon.NewStateStoreTokens() - b.d.StateStoreTokens = tokens - opts = append(opts, grpc.ChainUnaryInterceptor(staterpc.UnaryTokenInterceptor(tokens.Validate))) - } - } - - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", net.JoinHostPort(host, "0")) - if err != nil { - log.Error("state store gRPC listen failed; archie-agent will use the legacy NATS storerpc path", "err", err) - return - } - server := grpc.NewServer(opts...) - staterpc.RegisterServer(server, deps) - go func() { - if err := server.Serve(listener); err != nil { - log.Error("state store gRPC server stopped", "err", err) - } - }() - b.addCleanup(server.GracefulStop) - b.d.ConnectedStateStore = daemon.StateStoreEndpoint{URL: listener.Addr().String()} - log.Info("state store gRPC server running", "addr", listener.Addr().String(), "token_required", host != "127.0.0.1") -} - // setupForgeWebhook starts the forge webhook receiver when intake is "webhook" // or "both". It decodes GitHub issue events into task envelopes and publishes // them through the same path the poller uses, so a labelled or assigned issue diff --git a/internal/app/archied/chat_store_composition_test.go b/internal/app/archied/chat_store_composition_test.go index 40bf19547..9f7cdf452 100644 --- a/internal/app/archied/chat_store_composition_test.go +++ b/internal/app/archied/chat_store_composition_test.go @@ -7,13 +7,19 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webui" ) func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) { cfg := config.Config{DBPath: filepath.Join(t.TempDir(), "tasks.db")} cfg.Services.Gateway.Target = "127.0.0.1:1" - b := &boot{cfg: cfg, log: slog.Default(), web: &webui.Server{Cfg: config.NewHolder(cfg)}} + st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state-store.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + b := &boot{cfg: cfg, log: slog.Default(), web: &webui.Server{Cfg: config.NewHolder(cfg)}, stateStore: st} t.Cleanup(b.cleanup) if err := b.openStores(t.Context()); err != nil { t.Fatal(err) diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index 8d15cb75b..c373aaac6 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -26,8 +26,11 @@ type GatewayOptions struct { } // RunGateway owns conversation persistence, model runtime and tool-provider -// lifecycles. Task-store adapters continue to access the existing task database -// until the State Store Service extraction; no task data is relocated. +// lifecycles. Task-store adapters access the State Store contract (remote +// *staterpc.Client via [services.state].target), not archie.db directly: the +// single SQLite file is owned by archie-state-store, and the Gateway keeps its +// own already-separate session SQLite (docs/prds/state-store-contract.md §12 +// step 8), which is out of state-store scope. func RunGateway(ctx context.Context, options GatewayOptions) error { b := newBootstrap() defer b.cleanup() @@ -38,6 +41,13 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { if err := b.openStores(ctx); err != nil { return err } + // The Gateway also no longer opens archie.db directly: it consumes the + // same remote State Store contract the daemon does via + // [services.state].target (docs/prds/state-store-contract.md §12 step 7). + // Its own session SQLite is untouched and stays Gateway-owned. + if err := b.openStateStoreAdapter(); err != nil { + return err + } b.loadCatalog(ctx, options.Config) url, token := b.cfg.NATS.URL, "" var nc *natsio.Conn diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 311a6fc10..3b12ccd29 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -44,7 +44,6 @@ import ( "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/store" - "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools/mcp" @@ -378,13 +377,12 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del if err := b.openStores(ctx); err != nil { return 1 } - // Upgrade the State Store contract adapter to a remote *staterpc.Client - // when [services.state].target is set; openStores already seeded it from - // b.st (the local default), so an empty target is a no-op. This is - // daemon-only (the gateway never dials a remote store), so it runs after - // openStores has opened b.st and resolved b.secrets and before - // setupObservability wires the dashboard's storage surfaces - // (docs/prds/state-store-contract.md §10). + // Resolve the State Store contract adapter as the remote *staterpc.Client + // dialed to [services.state].target; the daemon no longer owns archie.db + // in-process, so an empty target is a composition error + // (docs/prds/state-store-contract.md §12 step 7). This runs after + // openStores has resolved b.secrets and before setupObservability wires the + // dashboard's storage surfaces (§10). if err := b.openStateStoreAdapter(); err != nil { return 1 } @@ -431,7 +429,6 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del } b.registerStandaloneTools() b.buildDaemon() - b.startStateStoreServer(ctx) b.wireConfigPublishing(ctx, args.cfgPath, args.overlayPath) b.installUpdateConfigHandler() b.installUpdateRepoFieldHandler() @@ -826,33 +823,26 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u }, nil } -// registerTaskRPCServers subscribes the storerpc/forgerpc/worktreerpc -// handlers on nc so an archie-agent container (which holds no DB -// connection, forge token, or push credential) can proxy those operations -// back to archied. The returned func unsubscribes all of them. +// registerTaskRPCServers subscribes the forgerpc/worktreerpc handlers on nc +// so an archie-agent container (which holds no forge token, or push +// credential) can proxy those operations back to archied. The returned func +// unsubscribes all of them. The agent's store calls are NOT proxied here: they +// go over gRPC to the State Store (docs/prds/state-store-contract.md §12 step +// 4), so the legacy NATS storerpc registration is deleted. // -// The store is shared across identities, so storerpc registers once on its -// root subjects. Forge and worktree are identity-scoped: the root servers -// answer the root (identity-less) subjects for single-identity deployments -// and root-owned tasks, and one server pair per identity answers that -// identity's scoped subjects so a container-mode task owned by a non-root -// identity has its RPC calls served by its own forge client and worktree -// manager. -func registerTaskRPCServers(nc *natsio.Conn, st store.TaskStore, forgeClient forge.Forge, trees *worktree.Manager, identities []*daemon.IdentityRunner, grants *worktreerpc.Grants, log *slog.Logger) (unsubscribe func(), err error) { - unsubs := make([]func(), 0, 3+2*len(identities)) +// Forge and worktree are identity-scoped: the root servers answer the root +// (identity-less) subjects for single-identity deployments and root-owned +// tasks, and one server pair per identity answers that identity's scoped +// subjects so a container-mode task owned by a non-root identity has its RPC +// calls served by its own forge client and worktree manager. +func registerTaskRPCServers(nc *natsio.Conn, forgeClient forge.Forge, trees *worktree.Manager, identities []*daemon.IdentityRunner, grants *worktreerpc.Grants, log *slog.Logger) (unsubscribe func(), err error) { + unsubs := make([]func(), 0, 2+2*len(identities)) unsubAll := func() { for _, u := range unsubs { u() } } - storeServer := &storerpc.Server{Store: st, Log: log} - u, err := storeServer.Register(nc) - if err != nil { - return nil, fmt.Errorf("register storerpc: %w", err) - } - unsubs = append(unsubs, u) - registerForge := func(fg forge.Forge, identity string) error { srv := &forgerpc.Server{Forge: fg, Log: log.With("rpc_identity", identity)} u, err := srv.RegisterFor(nc, identity) @@ -1076,10 +1066,11 @@ func startContainers( Network: cfg.Containers.Network, DockerClient: dockerCli, // Always resolve the bridge gateway: agent containers need it to - // reach embedded NATS (when configured) and, as of Phase 2, the - // daemon's in-process State Store gRPC server (docs/prds/ - // state-store-contract.md §9's single listener-topology rule) -- - // a container can never reach the host's 127.0.0.1. + // reach embedded NATS (when configured) and the State Store gRPC + // service, whose [services.state].target must be the bridge gateway + // for a container-mode agent (docs/prds/state-store-contract.md §9's + // single listener-topology rule) -- a container can never reach the + // host's 127.0.0.1. RequireHostGateway: true, }, log) if err != nil { diff --git a/internal/app/archied/main_test.go b/internal/app/archied/main_test.go index f8e26463d..261af4c8a 100644 --- a/internal/app/archied/main_test.go +++ b/internal/app/archied/main_test.go @@ -30,7 +30,6 @@ import ( "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/store" - "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/worktree" "github.com/samcharles93/archie-core/internal/worktreerpc" @@ -942,11 +941,10 @@ func TestRegisterTaskRPCServersReachableFromClient(t *testing.T) { } t.Cleanup(serverConn.Close) - st := store.OpenTest(t) trees := &worktree.Manager{WorkDir: t.TempDir()} log := slog.New(slog.DiscardHandler) - unsubscribe, err := registerTaskRPCServers(serverConn, st, stubForge{}, trees, nil, worktreerpc.NewGrants(), log) + unsubscribe, err := registerTaskRPCServers(serverConn, stubForge{}, trees, nil, worktreerpc.NewGrants(), log) if err != nil { t.Fatalf("registerTaskRPCServers: %v", err) } @@ -960,18 +958,6 @@ func TestRegisterTaskRPCServersReachableFromClient(t *testing.T) { ctx := context.Background() - storeClient := &storerpc.Client{Conn: clientConn, Timeout: 2 * time.Second} - if _, err := st.EnqueueIssue(ctx, "acme", "widget", 1, "t", "b", "", ""); err != nil { - t.Fatalf("enqueue: %v", err) - } - task, err := st.ClaimNext(ctx) - if err != nil || task == nil { - t.Fatalf("claim: (%v, %v)", task, err) - } - if err := storeClient.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, "opened"); err != nil { - t.Fatalf("storerpc Transition unreachable: %v", err) - } - forgeClient := &forgerpc.Client{Conn: clientConn, Timeout: 2 * time.Second} if _, err := forgeClient.Comment(ctx, "acme", "widget", 1, "hi"); err != nil { t.Fatalf("forgerpc Comment unreachable: %v", err) @@ -1045,7 +1031,6 @@ func TestRegisterTaskRPCServersRoutesIdentityScopedCalls(t *testing.T) { } t.Cleanup(serverConn.Close) - st := store.OpenTest(t) rootForge := &identityForge{} archieForge := &identityForge{} rootTrees := &worktree.Manager{WorkDir: t.TempDir()} @@ -1054,7 +1039,7 @@ func TestRegisterTaskRPCServersRoutesIdentityScopedCalls(t *testing.T) { identities := []*daemon.IdentityRunner{ {Name: "archie", Forge: archieForge, Trees: archieTrees}, } - unsubscribe, err := registerTaskRPCServers(serverConn, st, rootForge, rootTrees, identities, worktreerpc.NewGrants(), slog.New(slog.DiscardHandler)) + unsubscribe, err := registerTaskRPCServers(serverConn, rootForge, rootTrees, identities, worktreerpc.NewGrants(), slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("registerTaskRPCServers: %v", err) } diff --git a/internal/app/archied/readiness.go b/internal/app/archied/readiness.go index 8def9b0b5..9dce30475 100644 --- a/internal/app/archied/readiness.go +++ b/internal/app/archied/readiness.go @@ -27,7 +27,7 @@ import ( func (b *boot) setupReadinessProbes() { cfg := b.cfg probes := []health.Probe{ - readiness.NewStoreProbe(b.st), + readiness.NewStoreProbe(b.stateStore), readiness.NewConfigProbe(func() config.Config { return b.web.Cfg.Get() }, configuration.Validate), readiness.NewDiskProbe(diskProbePath(cfg)), readiness.NewModelProbe(b.chatModels.ActiveModel, b.chatModels.Models, modelReachProbe(cfg, b.chatModels.ActiveModel)), diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index dba8540fb..8615773fc 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -248,8 +248,8 @@ func stateStoreListenIsLoopback(listen string) (bool, error) { // constantTimeTokenValidator returns a staterpc.TokenValidator that accepts // exactly the configured token, compared in constant time so a timing side -// channel cannot leak how many bytes matched (mirrors the daemon's -// StateStoreTokens.Validate). +// channel cannot leak how many bytes matched (the standalone server's +// equivalent of the earlier in-process interceptor's token check). func constantTimeTokenValidator(token string) staterpc.TokenValidator { return func(candidate string) bool { return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1 diff --git a/internal/app/archied/state_store_client.go b/internal/app/archied/state_store_client.go index 0b35f3452..c3c2f0bbe 100644 --- a/internal/app/archied/state_store_client.go +++ b/internal/app/archied/state_store_client.go @@ -22,15 +22,25 @@ import ( // secret/env. The returned cleanup closes the connection; Close() on the // adapter itself is a no-op, because the store service owns its own DB // lifecycle (§11). +// stateStoreResolvedToken returns the bearer token a State Store client +// presents, matching composeStateStoreClient's resolution order: the explicit +// [services.state].target_token key, then the STATE_STORE_TOKEN secret/env. The +// daemon injects the same token into agent containers as STATE_STORE_TOKEN so +// the agent authenticates to the same remote store the daemon dials. +func stateStoreResolvedToken(settings config.ServiceConnection, secrets *secret.Registry) string { + token := settings.TargetToken + if token == "" { + token = secrets.Getenv("STATE_STORE_TOKEN") + } + return token +} + func composeStateStoreClient(settings config.ServiceConnection, secrets *secret.Registry) (store.TaskStore, func(), error) { target := strings.TrimSpace(settings.Target) if target == "" { return nil, nil, fmt.Errorf("services.state.target is required") } - token := settings.TargetToken - if token == "" { - token = secrets.Getenv("STATE_STORE_TOKEN") - } + token := stateStoreResolvedToken(settings, secrets) loopback, err := stateStoreListenIsLoopback(target) if err != nil { return nil, nil, fmt.Errorf("services.state.target must be host:port: %w", err) diff --git a/internal/app/archied/state_store_client_test.go b/internal/app/archied/state_store_client_test.go index bdb99ffaa..50efa53a6 100644 --- a/internal/app/archied/state_store_client_test.go +++ b/internal/app/archied/state_store_client_test.go @@ -1,13 +1,11 @@ package archied import ( - "path/filepath" "strings" "testing" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/secret" - "github.com/samcharles93/archie-core/internal/store" ) func TestComposeStateStoreClientRequiresTarget(t *testing.T) { @@ -63,23 +61,14 @@ func TestComposeStateStoreClientTokenFromTargetToken(t *testing.T) { } } -func TestOpenStateStoreAdapterLocalUsesOpenedStore(t *testing.T) { - dir := t.TempDir() - st, err := store.Open(t.Context(), filepath.Join(dir, "tasks.sqlite")) - if err != nil { - t.Fatalf("open temp store: %v", err) - } - defer st.Close() - +func TestOpenStateStoreAdapterRequiresTarget(t *testing.T) { b := newBootstrap() - b.st = st b.secrets = &secret.Registry{} - // Empty [services.state].target → the base path: the local *store.Store. - if err := b.openStateStoreAdapter(); err != nil { - t.Fatalf("openStateStoreAdapter(local): %v", err) - } - if b.stateStore != st { - t.Fatal("local adapter should be the opened *store.Store") + // After .4.6 the daemon and gateway no longer own archie.db in-process, so + // an empty [services.state].target is a composition error, not the old + // local *store.Store default (docs/prds/state-store-contract.md §12 step 7). + if err := b.openStateStoreAdapter(); err == nil { + t.Fatal("empty services.state.target should error: the in-process store path is deleted") } } diff --git a/internal/app/archied/state_store_consumers_test.go b/internal/app/archied/state_store_consumers_test.go index 2b67a121e..e2967dcb0 100644 --- a/internal/app/archied/state_store_consumers_test.go +++ b/internal/app/archied/state_store_consumers_test.go @@ -31,11 +31,10 @@ func openSecondStore(t *testing.T) *store.Store { // TestBuildDaemonRoutesTaskStoreThroughStateStore proves the daemon's task // lifecycle consumer resolves its store surfaces from b.stateStore (the State -// Store contract adapter) -- local by default, remote *staterpc.Client when -// [services.state].target is set -- and not from b.st directly. This is the -// .4.5 TaskStore-composite swap (docs/prds/state-store-contract.md §12 step -// 6): the daemon's Store field and its mapping/binding dispatch surfaces all -// come from the adapter. +// Store contract adapter -- always the remote *staterpc.Client after .4.6) +// and not from b.st directly. This is the .4.5 TaskStore-composite swap +// (docs/prds/state-store-contract.md §12 step 6): the daemon's Store field and +// its mapping/binding dispatch surfaces all come from the adapter. func TestBuildDaemonRoutesTaskStoreThroughStateStore(t *testing.T) { storeA, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "store-a.db")) if err != nil { @@ -71,8 +70,9 @@ func TestBuildDaemonRoutesTaskStoreThroughStateStore(t *testing.T) { } // TestSetupObservabilityRoutesTaskStoreThroughStateStore proves the dashboard's -// task store (web.Store) is wired from b.stateStore, not b.st, so the webui -// reaches the same contract adapter the daemon uses. +// task store (web.Store) is wired from b.stateStore (the State Store contract +// adapter), not b.st, so the webui reaches the same contract adapter the +// daemon uses. func TestSetupObservabilityRoutesTaskStoreThroughStateStore(t *testing.T) { storeA, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "store-a.db")) if err != nil { @@ -110,7 +110,7 @@ func TestSetupObservabilityRoutesTaskStoreThroughStateStore(t *testing.T) { // TestTaskActionsRoutesThroughStateStore proves the daemon's operator task // action service wraps b.stateStore (the contract adapter), so an operator // approve/cancel/archive action mutates the same store the daemon lifecycle -// uses -- local by default, remote when [services.state].target is set. +// uses. func TestTaskActionsRoutesThroughStateStore(t *testing.T) { storeB := openSecondStore(t) diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 4bec2e380..0fd30f7bc 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -5,9 +5,6 @@ package daemon import ( "context" - "crypto/rand" - "crypto/subtle" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -65,76 +62,17 @@ type NATSEndpoint struct { Token string } -// StateStoreEndpoint is the address the daemon's in-process State Store gRPC -// server is bound to (docs/prds/state-store-contract.md §6, §12 step 3). The -// zero value (empty URL) means the server is not serving -- containerEnv -// omits STATE_STORE_URL/STATE_STORE_TOKEN and archie-agent falls back to the -// legacy NATS storerpc path. +// StateStoreEndpoint is the State Store gRPC target (and the bearer token the +// daemon presents, when one is configured) that containerEnv injects as +// STATE_STORE_URL / STATE_STORE_TOKEN so archie-agent authenticates to the +// same remote archie-state-store service the daemon dials +// (docs/prds/state-store-contract.md §6, §9, §10). After the in-process +// serving path is deleted (docs/prds/state-store-contract.md §12 step 7) this +// is always the configured [services.state].target, never a daemon-owned +// listener. type StateStoreEndpoint struct { - URL string -} - -// StateStoreTokens issues and validates the per-task bearer tokens the State -// Store's bridge-address (agent-consumed) listener topology requires (§9's -// token lifecycle). A token is per-incumbence: Generate overwrites any -// earlier token for the same task, so a new container acquisition -// invalidates the previous one, and Revoke drops a released task's token -// entirely. The zero value is ready to use. -type StateStoreTokens struct { - mu sync.Mutex - byTask map[int64]string -} - -// NewStateStoreTokens returns a ready-to-use token registry. -func NewStateStoreTokens() *StateStoreTokens { - return &StateStoreTokens{byTask: make(map[int64]string)} -} - -// Generate issues a fresh bearer token for taskID, replacing (and thereby -// invalidating) any token previously issued for that task. -func (t *StateStoreTokens) Generate(taskID int64) string { - token := randomToken() - t.mu.Lock() - defer t.mu.Unlock() - t.byTask[taskID] = token - return token -} - -// Revoke invalidates taskID's current token, if any. Called when the -// container holding it is released, so a stale token cannot outlive its -// container. -func (t *StateStoreTokens) Revoke(taskID int64) { - t.mu.Lock() - defer t.mu.Unlock() - delete(t.byTask, taskID) -} - -// Validate reports whether token is any task's currently issued token. -// The comparison is constant-time (crypto/subtle) so a timing side channel -// cannot tell how many token bytes matched. -func (t *StateStoreTokens) Validate(token string) bool { - if token == "" { - return false - } - t.mu.Lock() - defer t.mu.Unlock() - for _, v := range t.byTask { - if subtle.ConstantTimeCompare([]byte(v), []byte(token)) == 1 { - return true - } - } - return false -} - -func randomToken() string { - b := make([]byte, 32) - if _, err := rand.Read(b); err != nil { - // crypto/rand.Read on the standard reader does not fail in practice; - // a zero-value token would fail every Validate call, which is a safe - // (fail-closed) degradation rather than a panic. - return "" - } - return hex.EncodeToString(b) + URL string + Token string } type Daemon struct { @@ -147,16 +85,13 @@ type Daemon struct { // broker the daemon is not publishing on. The zero value is invalid in // production composition and remains useful only to fail closed in tests. ConnectedNATS NATSEndpoint - // ConnectedStateStore is the address the daemon's in-process State - // Store gRPC server bound to at startup, if any. Empty means the - // server is not serving (StateStoreTokens is then unused) and - // containerEnv omits STATE_STORE_URL/STATE_STORE_TOKEN. + // ConnectedStateStore is the State Store gRPC target (and token) the + // daemon's own client dialed at startup. containerEnv injects these as + // STATE_STORE_URL / STATE_STORE_TOKEN so archie-agent reaches the same + // remote archie-state-store service; it is always the configured + // [services.state].target after the in-process serving path is deleted. ConnectedStateStore StateStoreEndpoint - // StateStoreTokens issues and validates the per-task bearer tokens the - // State Store's gRPC interceptor checks. Nil when ConnectedStateStore - // is empty. - StateStoreTokens *StateStoreTokens - Store store.TaskStore + Store store.TaskStore // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). // Used by the binding dispatch loop to resolve capture bodies against // the mapping a binding names. Optional: nil disables the binding @@ -1171,9 +1106,6 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) { return } defer d.ContainerPool.Release(ctx, ctr) - if d.StateStoreTokens != nil { - defer d.StateStoreTokens.Revoke(task.ID) - } // Hand the whole task to archie-agent in one NATS round trip. archie-agent // proxies Store/Forge/worktree-push calls back to archied over storerpc/ @@ -1472,12 +1404,15 @@ func (d *Daemon) containerEnv(task *workflow.Task) []string { env = append(env, "NATS_TOKEN="+token) } // The State Store gRPC target follows the same seam as NATS_URL/ - // NATS_TOKEN above (docs/prds/state-store-contract.md §6). Omitted - // when the daemon is not serving the State Store in-process, so - // archie-agent falls back to the legacy NATS storerpc path. - if d.ConnectedStateStore.URL != "" && d.StateStoreTokens != nil { + // NATS_TOKEN above (docs/prds/state-store-contract.md §6). It is always + // the configured [services.state].target after the in-process serving + // path is deleted; the token is the same one the daemon client presents, + // so archie-agent authenticates to the same archie-state-store service. + if d.ConnectedStateStore.URL != "" { env = append(env, "STATE_STORE_URL="+d.ConnectedStateStore.URL) - env = append(env, "STATE_STORE_TOKEN="+d.StateStoreTokens.Generate(task.ID)) + if d.ConnectedStateStore.Token != "" { + env = append(env, "STATE_STORE_TOKEN="+d.ConnectedStateStore.Token) + } } // The agent process runs as root inside the container (no USER in the // Dockerfile, no userns-remap), so a commit it writes to the bind-mounted diff --git a/internal/daemon/terminal_cleanup_test.go b/internal/daemon/terminal_cleanup_test.go index 263774824..f23435933 100644 --- a/internal/daemon/terminal_cleanup_test.go +++ b/internal/daemon/terminal_cleanup_test.go @@ -319,7 +319,7 @@ func TestProcessCleansWorktreeOnTerminalNoChange(t *testing.T) { workDir := targetTrees.Dir(task.Owner, task.Repo, task.IssueNumber) sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) { - // Transition task in store as archie-agent would do over storerpc + // Transition task in store as archie-agent would do over the gRPC State Store _ = s.Transition(ctx, task.ID, workflow.StatusRunning, tt.workerStatus, "worker completion") resp, _ := json.Marshal(taskrun.Response{ Status: tt.workerStatus, diff --git a/internal/domain/workflow/task.go b/internal/domain/workflow/task.go index 5aa52c616..5f43b1b2f 100644 --- a/internal/domain/workflow/task.go +++ b/internal/domain/workflow/task.go @@ -94,8 +94,8 @@ func (t Task) IsForgeBacked() bool { // Store is the narrow, consumer-owned subset of the State Store contract // that workflow stages call mid-run. *store.Store and staterpc.Client -// satisfy it; this is the interface archie-agent uses via the storerpc -// proxy. It supersedes store.WorkflowStore. +// satisfy it; this is the interface archie-agent uses over the gRPC State +// Store contract. It supersedes store.WorkflowStore. type Store interface { Update(ctx context.Context, t *Task) error Transition(ctx context.Context, taskID int64, from, to, detail string) error diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 507f13c9c..497526c32 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -21,17 +21,15 @@ import ( "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forgerpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" - "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/worktreerpc" ) // Config contains the broker endpoint and credential for the worker -// transport, plus the optional State Store gRPC target (docs/prds/ -// state-store-contract.md §6). An empty StateStoreURL keeps the legacy NATS -// storerpc path for workflow.Store; a non-empty one dials the gRPC -// StateStoreService instead -- a single agent process is either NATS-backed -// or gRPC-backed for its store calls, never both. +// transport, plus the State Store gRPC target (docs/prds/ +// state-store-contract.md §6). StateStoreURL is required: the agent is fully +// on gRPC for its store calls, and the legacy NATS storerpc path is deleted +// (docs/prds/state-store-contract.md §12 step 4). type Config struct { URL string Token string @@ -53,10 +51,11 @@ type sdkSubscription interface { // worker has no JetStream consumer. type Transport struct { conn *natsio.Conn - // stateConn is the long-lived gRPC connection to the State Store, - // non-nil only when Config.StateStoreURL was set. Store() dials no - // per-call connection; it wraps this one connection with the - // per-call timeout each caller supplies. + // stateConn is the long-lived gRPC connection to the State Store. Store() + // dials no per-call connection; it wraps this one connection with the + // per-call timeout each caller supplies. Connect refuses to construct a + // Transport without one (the legacy NATS storerpc path is deleted), so it + // is never nil in a real worker. stateConn *grpc.ClientConn subscribe func(string, natsio.MsgHandler) (sdkSubscription, error) @@ -89,15 +88,20 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, } log.Info("worker transport connected", "url", conn.ConnectedUrl()) - var stateConn *grpc.ClientConn - if config.StateStoreURL != "" { - stateConn, err = dialStateStore(config.StateStoreURL, config.StateStoreToken) - if err != nil { - conn.Close() - return nil, fmt.Errorf("connect state store: %w", err) - } - log.Info("worker state store transport connected", "url", config.StateStoreURL) + // The agent is fully on gRPC for its store calls; the legacy NATS + // storerpc path is deleted (docs/prds/state-store-contract.md §12 step + // 4). A missing StateStoreURL fails fast rather than letting Store() + // hand back a client over a nil connection. + if config.StateStoreURL == "" { + conn.Close() + return nil, fmt.Errorf("state store target is required: archie-agent no longer supports the legacy NATS storerpc path (docs/prds/state-store-contract.md §12 step 4)") } + stateConn, err := dialStateStore(config.StateStoreURL, config.StateStoreToken) + if err != nil { + conn.Close() + return nil, fmt.Errorf("connect state store: %w", err) + } + log.Info("worker state store transport connected", "url", config.StateStoreURL) return &Transport{ conn: conn, @@ -149,25 +153,25 @@ type RemoteTrees interface { Push(ctx context.Context) error } -// The top-level forgerpc, storerpc, and worktreerpc packages remain legacy -// infrastructure with an open final destination. This adapter is their single -// worker composition point until that broader migration is approved. +// The top-level forgerpc and worktreerpc packages remain legacy infrastructure +// with an open final destination. This adapter is their single worker +// composition point until that broader migration is approved. The State Store +// is the exception: it is a gRPC contract (staterpc), and this adapter's +// Store() returns that client directly. // Forger constructs the identity-scoped forge RPC client. func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forger { return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity} } -// Store constructs the workflow store RPC client: a long-lived gRPC -// staterpc.Client over the State Store connection when one was configured, -// or the legacy NATS storerpc.Client otherwise (docs/prds/ -// state-store-contract.md §6). Either way each call is bounded by timeout -// when the caller's context carries no deadline of its own. +// Store constructs the workflow store RPC client over the long-lived gRPC +// State Store connection (docs/prds/state-store-contract.md §6). Each call +// is bounded by timeout when the caller's context carries no deadline of its +// own. The legacy NATS storerpc path is deleted (§12 step 4); a transport +// without a stateConn cannot reach Store() because Connect refused to build +// one. func (t *Transport) Store(timeout time.Duration) workflow.Store { - if t.stateConn != nil { - return deadlineStore{Store: staterpc.NewClient(t.stateConn), timeout: timeout} - } - return &storerpc.Client{Conn: t.conn, Timeout: timeout} + return deadlineStore{Store: staterpc.NewClient(t.stateConn), timeout: timeout} } // deadlineStore applies a default per-call timeout to workflow.Store calls diff --git a/internal/infrastructure/agenttransport/nats/transport_test.go b/internal/infrastructure/agenttransport/nats/transport_test.go index 06ad53c3d..5893e4b2f 100644 --- a/internal/infrastructure/agenttransport/nats/transport_test.go +++ b/internal/infrastructure/agenttransport/nats/transport_test.go @@ -17,7 +17,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/forgerpc" - "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/worktreerpc" ) @@ -83,12 +82,14 @@ func TestTaskRunSubjectOwnsCanonicalNATSTopology(t *testing.T) { // Full-task handoff and all worker RPC use core NATS. The worker must connect // to a broker with JetStream disabled; requiring a durable consumer would mean -// the deleted per-stage transport still owns startup. +// the deleted per-stage transport still owns startup. The State Store target +// is a separate gRPC connection, not a NATS feature, so it is supplied here +// too (it does not need to be reachable -- grpc.NewClient is lazy). func TestConnectRequiresOnlyCoreNATS(t *testing.T) { srv := natstest.RunServer(&server.Options{Port: -1, Authorization: "worker-secret"}) t.Cleanup(srv.Shutdown) - transport, err := Connect(t.Context(), Config{URL: srv.ClientURL(), Token: "worker-secret"}, slog.New(slog.DiscardHandler)) + transport, err := Connect(t.Context(), Config{URL: srv.ClientURL(), Token: "worker-secret", StateStoreURL: "127.0.0.1:9999"}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("Connect to core-only NATS: %v", err) } @@ -300,9 +301,8 @@ func TestRPCFactoriesPreserveIdentityAndTimeout(t *testing.T) { if !ok || forgeClient.Identity != "identity-a" || forgeClient.Timeout != timeout { t.Fatalf("forge client = %#v", forgeClient) } - storeClient, ok := transport.Store(timeout).(*storerpc.Client) - if !ok || storeClient.Timeout != timeout { - t.Fatalf("store client = %#v", storeClient) + if store := transport.Store(timeout); store == nil { + t.Fatal("store client = nil, want a non-nil workflow.Store") } treeClient, ok := transport.Trees("identity-a", "grant-a", timeout).(*worktreerpc.Client) if !ok || treeClient.Identity != "identity-a" || treeClient.Grant != "grant-a" || treeClient.Timeout != timeout { diff --git a/internal/infrastructure/eventbus/nats/client.go b/internal/infrastructure/eventbus/nats/client.go index ee27f568c..2966b4ba6 100644 --- a/internal/infrastructure/eventbus/nats/client.go +++ b/internal/infrastructure/eventbus/nats/client.go @@ -123,8 +123,8 @@ func (c *Client) Close() { } // CoreConn exposes the raw connection for the NATS-specific RPC layers -// (forgerpc, storerpc, worktreerpc, natsrpc) that register their own core-NATS -// subscriptions. +// (forgerpc, worktreerpc, natsrpc) that register their own core-NATS +// subscriptions. The State Store is a gRPC contract, not a core-NATS RPC. // // This is the single sanctioned escape hatch and exists only because those // packages are themselves NATS infrastructure, not domain code. Domain and diff --git a/internal/natsrpc/natsrpc.go b/internal/natsrpc/natsrpc.go index b7983bcc4..f286d4904 100644 --- a/internal/natsrpc/natsrpc.go +++ b/internal/natsrpc/natsrpc.go @@ -1,6 +1,6 @@ // Package natsrpc holds the request/reply plumbing shared by -// archie-core's three core-NATS RPC surfaces (storerpc, worktreerpc, -// forgerpc): a timeout-bounded client call, multi-subject server +// archie-core's core-NATS RPC surfaces (worktreerpc, forgerpc, +// taskactions): a timeout-bounded client call, multi-subject server // registration with rollback on partial failure, and a JSON error // envelope so handlers don't each reimplement "marshal error, log // encode/respond failures." @@ -126,7 +126,7 @@ func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err er // Respond marshals v and replies to msg, logging (rather than // returning) any encode or transport failure -- a handler has no // meaningful way to retry or propagate a respond failure to its caller. -// pkg prefixes the log message (e.g. "storerpc") to identify the +// pkg prefixes the log message (e.g. "forgerpc") to identify the // surface a failure came from. func Respond(msg *nats.Msg, log *slog.Logger, pkg string, v any) { data, err := json.Marshal(v) diff --git a/internal/storerpc/storerpc.go b/internal/storerpc/storerpc.go deleted file mode 100644 index cf1578283..000000000 --- a/internal/storerpc/storerpc.go +++ /dev/null @@ -1,137 +0,0 @@ -// 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.TaskStore. -package storerpc - -import ( - "context" - "encoding/json" - "log/slog" - "time" - - "github.com/nats-io/nats.go" - - "github.com/samcharles93/archie-core/internal/domain/workflow" - "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/natsrpc" - "github.com/samcharles93/archie-core/internal/store" -) - -// Subjects for the two store.TaskStore methods workflow stages call mid-run. -const ( - SubjectUpdate = "archie.store.update" - SubjectTransition = "archie.store.transition" - SubjectInsertEvent = "archie.store.insert_event" -) - -// UpdateRequest mirrors store.TaskStore.Update's argument. -type UpdateRequest struct { - Task *workflow.Task `json:"task"` -} - -// TransitionRequest mirrors store.TaskStore.Transition's arguments. -type TransitionRequest struct { - TaskID int64 `json:"task_id"` - From string `json:"from"` - To string `json:"to"` - Detail string `json:"detail"` -} - -type InsertEventRequest struct { - Event events.Event `json:"event"` -} - -// Response carries the result of an RPC. Error is empty on success. -type Response struct { - natsrpc.Envelope - ID int64 `json:"id,omitempty"` -} - -// Server handles storerpc requests against the daemon's TaskStore. -type Server struct { - Store store.TaskStore - 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) { - return natsrpc.RegisterAll(nc, []natsrpc.Registration{ - {Subject: SubjectUpdate, Handler: s.handleUpdate}, - {Subject: SubjectTransition, Handler: s.handleTransition}, - {Subject: SubjectInsertEvent, Handler: s.handleInsertEvent}, - }) -} - -func (s *Server) handleInsertEvent(msg *nats.Msg) { - var req InsertEventRequest - if err := json.Unmarshal(msg.Data, &req); err != nil { - s.reply(msg, err) - return - } - id, err := s.Store.InsertEvent(context.Background(), req.Event) - natsrpc.Respond(msg, s.Log, "storerpc", Response{Envelope: natsrpc.NewEnvelope(err), ID: id}) -} - -func (s *Server) handleUpdate(msg *nats.Msg) { - var req UpdateRequest - if err := json.Unmarshal(msg.Data, &req); err != nil { - s.reply(msg, 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, 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) { - natsrpc.Respond(msg, s.Log, "storerpc", Response{Envelope: natsrpc.NewEnvelope(err)}) -} - -// Client calls the storerpc Server from archie-agent's process. -// It implements workflow.Store (the narrow interface workflow stages -// need -- just Update + Transition), not the full store.TaskStore. -type Client struct { - Conn *nats.Conn - Timeout time.Duration // bounds each call when ctx has no deadline -} - -func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} } - -// Update calls store.TaskStore.Update on the daemon over NATS request/reply. -func (c *Client) Update(ctx context.Context, task *workflow.Task) error { - resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectUpdate, UpdateRequest{Task: task}) - if err != nil { - return err - } - return resp.Err() -} - -// Transition calls store.TaskStore.Transition on the daemon over NATS request/reply. -func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail string) error { - req := TransitionRequest{TaskID: taskID, From: from, To: to, Detail: detail} - resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectTransition, req) - if err != nil { - return err - } - return resp.Err() -} - -func (c *Client) InsertEvent(ctx context.Context, event events.Event) (int64, error) { - resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectInsertEvent, InsertEventRequest{Event: event}) - if err != nil { - return 0, err - } - return resp.ID, resp.Err() -} - -// Compile-time check: Client satisfies workflow.Store. -var _ workflow.Store = (*Client)(nil) diff --git a/internal/storerpc/storerpc_test.go b/internal/storerpc/storerpc_test.go deleted file mode 100644 index d4d206973..000000000 --- a/internal/storerpc/storerpc_test.go +++ /dev/null @@ -1,153 +0,0 @@ -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/domain/workflow" - "github.com/samcharles93/archie-core/internal/events" - "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) *workflow.Task { - t.Helper() - ctx := context.Background() - if _, err := s.EnqueueIssue(ctx, "acme", "widget", 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(), "acme", "widget", 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, workflow.StatusRunning, workflow.StatusPROpen, "opened PR"); err != nil { - t.Fatalf("Transition: %v", err) - } - - got, err := s.TaskByIssue(context.Background(), "acme", "widget", 1) - if err != nil || got == nil { - t.Fatalf("TaskByIssue: (%+v, %v)", got, err) - } - if got.Status != workflow.StatusPROpen { - t.Fatalf("expected status %s, got %s", workflow.StatusPROpen, got.Status) - } -} - -func TestClientInsertEventPersistsViaServer(t *testing.T) { - s, _, client := newTestServer(t) - task := enqueueTask(t, s) - event := events.Event{Kind: events.KindAgentFinish, TaskID: task.ID, Data: map[string]any{"tokens": 42}} - - id, err := client.InsertEvent(context.Background(), event) - if err != nil { - t.Fatalf("InsertEvent: %v", err) - } - got, err := s.TaskEvents(context.Background(), task.ID) - if err != nil || len(got) != 1 || got[0].ID != id || got[0].Kind != events.KindAgentFinish { - t.Fatalf("TaskEvents = (%+v, %v), want persisted agent_finish id %d", got, err, id) - } -} - -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(), &workflow.Task{ID: 1}) - if err == nil { - t.Fatal("expected Update to time out with no server registered") - } -} diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go index ec4be26a6..86a9812fd 100644 --- a/internal/taskrun/taskrun.go +++ b/internal/taskrun/taskrun.go @@ -2,7 +2,8 @@ // from archied to archie-agent in one NATS round trip. // 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. +// the forgerpc/worktreerpc calls archie-agent proxies back. Agent store +// calls go over gRPC to the State Store, not through this NATS handoff. package taskrun import ( @@ -51,8 +52,8 @@ func (r Request) Validate() error { // 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. +// authoritative state already landed in the State Store via the agent's +// gRPC store calls made during the run. type Response struct { Task *workflow.Task `json:"task"` Status string `json:"status"`