fix(factory): converge factory agent registration instead of looping on 409 (#316)

Merged
KH
3mo ago
+559-7

Fixes #316.

What broke

#registerFactoryAgent picked agents.registerOrRotate when present:

const register = agents.registerOrRotate?.bind(agents) ?? agents.register.bind(agents)

In @relaycast/sdk 8.0.x that method genuinely recovered from a name conflict — register(strict), and on conflict agents.get + agents.rotateToken. In 8.2.0 it became a deprecated alias for plain register, and the engine simultaneously closed POST /v1/agents/:name/rotate-token to workspace keys (requireWorkspaceKey → requireAgentToken). Because the method still exists, the ?? fallback never fires.

Why it looped silently

The loop is ours. #bootstrapMessaging held the minted token in a local variable, and #ensureMessaging clears its memo on any failure so a later call retries. So a bootstrap step that failed after a successful registration re-registered the same name on the next attempt — colliding with the record we had just created seconds earlier. The engine answers that with 409 agent_already_exists, indefinitely, and nothing surfaced it.

The fix

  • Call agents.register directly; never registerOrRotate/registerOrGet.
  • Cache the minted token on the instance so a post-registration bootstrap failure reuses it instead of re-registering. This is the actual convergence fix.
  • Treat a name conflict as terminal: throw a named FactoryAgentRegistrationError carrying the agent name and the conflict, with a bounded backstop on consecutive transient failures.

Reclaiming a name that is already taken

Registration alone cannot converge when the workspace holds the name and we have no token for it. That case is now handled by audited takeover — and, to be explicit about what this PR actually does: takeOver is not on the SDK surface we consume, so this calls POST /v1/agents/:name/takeover over raw HTTP with the workspace key, deliberately going around the @agent-relay/sdk wrapper. That is not a workaround for a missing endpoint; the endpoint exists and admits our credential. It is a workaround for a missing method, and it is the same thing the Rust broker does in relay#1596.

register -> 409 agent_already_exists
         -> read the id back
         -> refuse if the agent is live
         -> POST /v1/agents/:name/takeover  (workspace key)
         -> proceed with the returned identity

409 agent_identity_conflict means the record moved between the read and the seizure — re-read and retry exactly once. Anything else fails as a named FactoryAgentRegistrationError.

The liveness guard is coded, not assumed, and it fails closed. Only a presence row we actually read, for this agent, carrying a status we recognise as not-live, authorises a seizure. A failed request, an unparseable body, a missing row, or a row without a status all abort the reclaim with the named error — absence of evidence is not evidence of death. (Thanks to codex for catching that the original catch(() => undefined) made an unreadable presence indistinguishable from "nobody is live".)

The asymmetry is deliberate: refusing to boot costs us a recoverable outage of our own, whereas seizing a live agent's credential strands another running process and takes the very token it would need to recover. Our case is a collision with our own dead record, but "the record happens to be offline" is a situation, not a safety property; seizing a live name would strand another factory's credential.

Every takeover field is an audit row, so every field carries meaning — actor, reason, session_ref and node_id are all populated and asserted in tests.

Why not recover, and why not pin to relaycast 7.0.0

recover is not usable:

  1. Its handler admits three authorities — work_unit_proof (needs a pre-image we never enrolled), current_agent_token (the thing we've lost), origin_node (needs a node token and a matching originNodeId). A workspace key satisfies none; the handler says so in a comment. Production confirms the last one independently: the factory record's origin_node_id is null.
  2. It is absent from our SDK surface (below) — as is takeOver, which is why the takeover above is a direct HTTP call.

Pinning to relaycast 7.0.0 — as the Rust broker does in relay#1596 — would be wrong here. 7.0.0's registerOrRotate does still rotate, but it rotates via POST /agents/:name/rotate-token with the workspace key, and production rejects exactly that:

POST /v1/agents/<nonexistent>/rotate-token  + workspace key -> 401 "Agent token required (at_live_...)"
GET  /v1/agents/<nonexistent>               + same key      -> 404   (control)

The 404 control proves the key is valid and the workspace resolves, so the 401 is the rotate-token guard itself. 7.0.0 also has no takeOver and no recover on its namespace at all. The pin would swap a silent 409 loop for a silent 401 loop. The broker's pin is not what gives it takeover — it calls /takeover over raw HTTP.

Why the takeover is raw HTTP and not agents.takeOver

recover is not usable, for two independent reasons:

  1. The engine's /recover handler admits three authorities — work_unit_proof (needs a pre-image we never enrolled), current_agent_token (the thing we've lost), origin_node (needs a node token). A workspace key satisfies none; the handler says so in a comment.
  2. More decisively: recover, takeOver, rotateToken and enrollRecoveryCredential are absent from the @agent-relay/sdk messaging.agents surface — a hand-written subset (list, get, register, registerOrRotate, me, update, delete, release, presence). Verified at runtime and in source, in both the pinned 11.6.9 and latest 11.8.1.

So agents.takeOver and agents.recover are a TypeError for us, not a 401. The endpoint being open is necessary but not sufficient — which is why the takeover above calls the endpoint directly rather than through the wrapper, exactly as the Rust broker does. Verified non-mutatingly that the guard admits our credential:

POST /v1/agents/<nonexistent>/takeover + workspace key -> 404 agent_not_found   (not 401)

Exposing takeOver on @agent-relay/sdk remains worth doing upstream; this PR does not block on it.

Hazard for the next person: the wrapper surface is narrower than the client

@agent-relay/sdk's messaging.agents is a hand-written subset, not a passthrough to @relaycast/sdk. Reading the relaycast SDK or the engine routes proves an endpoint exists; it does not prove factory can call it. recover, takeOver, rotateToken and enrollRecoveryCredential are all documented on the raw relaycast namespace and all absent here — agents.takeOver is a TypeError, not a 401.

Before designing against any relay agent primitive, probe the wrapper surface (Object.keys / typeof on relay.messaging.agents), not the relaycast source.

If registration fails loudly: operator recovery

A conflict is not terminal in the normal case — it is reclaimed by takeover. FactoryAgentRegistrationError is thrown only when the reclaim itself cannot proceed, and the message says which:

messagemeaningwhat to do
refusing to take over agent in status "…"another agent is live on this nameconfirm with GET /v1/agents/<name> and /v1/agents/presence. Stop the other instance, or wait for it to go offline; the next boot reclaims automatically.
could not reclaim the existing identity: …takeover was rejectedcheck the workspace key is valid (GET /v1/agents/<name> should 200) and read the engine's error code in the message.
name is taken but the record could not be read backregister said 409 but the read-back failedtransient; the next boot retries. If it persists, the name and the read are disagreeing — inspect the record directly.
gave up after N registration attempts10 consecutive transient failuresthe relay is unreachable or degraded, not an identity problem.

Manual escape hatch, workspace key only — take over the record by hand, then restart the container:

ID=$(curl -s -H "Authorization: Bearer $RELAY_WORKSPACE_KEY" \
  https://cast.agentrelay.com/v1/agents/factory | jq -r .data.id)
curl -X POST -H "Authorization: Bearer $RELAY_WORKSPACE_KEY" -H 'content-type: application/json' \
  -d "{\"expected_agent_id\":\"$ID\",\"actor\":\"operator\",\"reason\":\"manual reclaim\",\"session_ref\":\"manual\",\"node_id\":\"manual\"}" \
  https://cast.agentrelay.com/v1/agents/factory/takeover

Fail-closed with no documented recovery is how the original outage lasted as long as it did; this table is the documentation.

Tests

Stub the real 8.2.0 semantics at the SDK boundary — aliases present and delegating to register, which 409s on a name it already holds — rather than unit-testing a helper in isolation, which is what let the last regression through.

Against the pre-fix client all four fail, each for the production reason:

testfailure on main
converges when a bootstrap step fails after registrationAgent "factory" already exists — rawCode: agent_already_exists, statusCode: 409
never calls the deprecated aliasesexpected [ 'registerOrRotate' ] to deeply equal []
fails loudly with a named errorno FactoryAgentRegistrationError export
bounded attempt budgetsix plain Errors, never a named one
fails closed when presence cannot be read (4 cases)the takeover proceeds and seizes the name
reclaims by audited takeoverno takeover path exists
refuses to take over a live agentno guard exists
re-reads and retries once on identity conflictno retry exists

Verification

  • src/fleet/ — all pass. Every new/changed test fails against the prior head, each for the production reason.
  • CI on this head: all five jobs green, read per job (verification-stack-e2e, verification-gate-e2e, load-e2e, kubernetes-provider-e2e, package). Note package had been failing on main in its three most recent runs.
  • npm run build clean.

On the local full suite: it is noisy on a loaded machine and I am not going to overstate it. Most failures are the known ≥5s load-timeout class plus dist-entrypoints needing a build, and those pass in isolation. But src/cli/fleet.test.ts > keeps relay dispatch ownership until the remote PR is published and the issue is parked also failed in isolation locally, with the documented expected 3 to be +0 signature (the 3 is an exit code, not a count) — a pre-existing intermittent that is unrelated to this diff and green in CI on this head.

CI must be read per job — gh run view <id> --json jobs, not statusCheckRollup.

🤖 Generated with Claude Code