fleet spawn: unconfirmed-spawn message hides a live agent, and agent remove is async so the retry fails with AlreadyExists

Merged
AG
2mo ago
+1318-80

Fix pending fleet spawns and asynchronous name reuse

An accepted fleet spawn could time out while its worker was already running, and an immediate retry after removal could collide with the old registration. Targeted spawn now retries the invocation read, checks fresh target-node heartbeat evidence, and reports unresolved outcomes as spawn_pending with exit 8 and safe inspection/reclaim guidance. Fresh worker presence returns confirmed:false without claiming harness readiness; pending outcomes preserve provisioned sandboxes.

  • Add opt-in agent remove --wait and fleet release --delete-agent --wait, with timeout controls. Clearance requires not-found or a single deadline membership check; a released status never proves name reuse is safe. Remaining registrations exit 8; wholly unavailable verification reads retain the asynchronous acknowledgement.
  • Replace Rust registration debug text with the existing formatter and classify create-only collisions as spawn_name_taken, covering cleanup after both removals and unsuccessful spawns.
  • Mirror pending/liveness evidence and optional removal waits in MCP, preserving nested persona invocation correlation and terminal readiness requirements.
  • Add node heartbeat timestamps/ages to fleet roster JSON, stale-snapshot warnings, regression tests, documentation, and a Minor unreleased changelog entry.

Validation

  • npm run typecheck: passed; final CLI tsc --noEmit also passed.
  • env -u RELAY_BASE_URL npm run test --ignore-scripts -- packages/cli: 2,021 passed, 17 skipped, across 100 passing files and one skipped file. The normal test command's build completed first. Unsetting the inherited URL prevents it overriding two existing transport-test fixtures.
  • Latest MCP regression run: 72 passed.
  • git diff --check: passed.
  • cargo test -p agent-relay-broker relaycast_events: unavailable because Cargo is not installed. The Rust regression test was added but not executed.

Scope and limitations

Removal waits stay opt-in under reviewed-plan section 3.7: no live workspace credentials were available to verify whether deletion produces not-found or a persistent tombstone. Both shapes are covered by regression tests. Polling defaults to 30 seconds plus one bounded membership read. Invocation/liveness recovery reads are also bounded.

This fixes outcome reporting and retry/cleanup handling; it does not explain missing spawn results or short-lived workers tracked in #1448 and #1603. Existing broker identity cleanup remains in place. SDK behavior and workflow files are unchanged. Work is committed on the supplied branch; nothing was pushed or merged.

Checks

Relayflow ran this repository's checks (.relayflow/check.sh) and they passed.

What ran (.relayflow/check.sh)
#!/bin/sh
#
# CI-equivalent check for a fresh machine.
#
# Mirrors the pull-request gates for the TypeScript monorepo:
#   .github/workflows/test.yml      -> `test` job (install, guard tests, npm test)
#                                      and `lint` job (eslint, prettier)
#   .github/workflows/codegen-models.yml -> model codegen drift check
#   .github/workflows/node-compat.yml    -> `npm run build` + `npm test`
#
# Deliberately omitted (needs secrets, services or another platform):
#   - Coverage upload (test.yml `coverage`): needs a Codecov token. The
#     underlying `npm run test:coverage` is just `npm test` plus thresholds.
#   - e2e-tests.yml, fleet-e2e.yml, prod-smoke.yml, relay-evals.yml and the
#     relay-cleanroom-qualification-* / relay-package-qualification-*
#     workflows: need a live broker fleet, cloud credentials and real agent
#     CLIs (claude/codex/gemini) that are not installed here.
#   - publish.yml, verify-publish*.yml, deploy-relayflows.yml,
#     update-cli-versions.yml, github-*-posthog.yml: registry/deploy tokens.
#   - security.yml CodeQL, gitleaks and dependency-review: hosted GitHub
#     services. `npm audit` there is non-blocking, so it is skipped too.
#   - test-build.yml / package-validation.yml standalone binaries: need Bun
#     plus macOS codesigning; package-validation also boots a broker daemon.
#   - macOS/Windows-only jobs: Swift SDK tests (packages/sdk-swift) and the
#     Windows credential ACL job.
#   - rust-ci.yml cargo jobs run below only when a cargo toolchain exists;
#     this machine has none and `npm run build:rust` no-ops without it
#     (installs use the prebuilt broker optional dependencies).
set -e

cd "$(dirname "$0")/.."

# Every CI workflow sets this; keep local runs off the telemetry pipeline.
export AGENT_RELAY_TELEMETRY_DISABLED=1
export TURBO_TELEMETRY_DISABLED=1

echo "=== Install dependencies ==="
npm ci

# test.yml installs rollup's platform optional dependency best-effort before
# building, because some install trees resolve it incorrectly.
npm install --no-save rollup || true

echo "=== Code generation drift (codegen-models.yml) ==="
# Generated from packages/utils/cli-registry.yaml; CI fails the PR when the
# committed output no longer matches.
npm run codegen:models
git diff --exit-code \
  packages/config/src/cli-registry.generated.ts \
  packages/sdk-py/src/agent_relay/models.py

echo "=== Build (Rust broker if available + all workspace packages) ==="
npm run build

echo "=== Rust checks (rust-ci.yml) ==="
if command -v cargo >/dev/null 2>&1; then
  cargo fmt -- --check
  cargo clippy -- -D warnings
  cargo test
else
  echo "skipped: no cargo toolchain on this machine"
fi

echo "=== PR proof transfer guards ==="
node --test \
  scripts/pr-proof/broker-transfer.test.mjs \
  scripts/pr-proof/run-cloud.test.mjs \
  scripts/flows/deploy-listeners.test.mjs \
  scripts/pr-proof/event-from-input.test.mjs

echo "=== Subscription proof guards ==="
npm run test:subscriptions:proof

echo "=== Unit/integration tests (vitest) ==="
# `npm test` is `vitest run` behind a `pretest` hook that re-runs the full
# build; call vitest directly since the build already ran above.
npx vitest run

echo "=== Lint (test.yml lint job) ==="
npm run lint

echo "=== Formatting (test.yml lint job) ==="
# Non-blocking here only because main already carries two unformatted root
# scratch files (plan.md, reviewed-plan.md), which would abort this script
# before anything else ran. Check the output for files you actually touched —
# in CI this gate is blocking.
npm run format:check || echo "WARNING: prettier reported unformatted files (see above)"

echo "=== All checks completed ==="

Fixes #1899


[!NOTE]
Medium Risk
Changes fleet spawn error semantics, script exit codes (8), and async removal verification across CLI and MCP; behavior is heavily tested but operators must handle new pending/collision flows.

Overview
Improves fleet/MCP spawn and name-reuse when outcomes are uncertain or registrations lag behind async removal.

Pending spawns (spawn_unconfirmed, exit 8, state: "pending") now carry invocation/dispatch diagnostics and liveness evidence from a bounded final invocation read plus target-node heartbeats—without treating same-named heartbeat presence as success or auto-deleting provisioned sandboxes. Registration collisions map to readable spawn_name_taken (CLI/MCP) and the broker uses format_worker_preregistration_error instead of Rust debug text.

Opt-in removal waits (agent remove --wait, fleet release --delete-agent --wait, MCP remove_agent with wait) poll until 404 or a deadline list absence; released never counts as cleared—still-present names exit 8; failed verification keeps the async acknowledgement.

fleet agent list JSON adds per-node heartbeat timestamps/ages and stale-snapshot warnings. Shared helpers live in new spawn-liveness and agent-removal modules wired through runSdk exit-code handling.

Reviewed by Cursor Bugbot for commit d5f616ee756892715caf78f1721989535d516a2e. Bugbot is set up for automated code reviews on this repo. Configure here.