carlos / platform Public

Managed fleets 1b: plan rev 2 after Astra R1 (7 P1, 4 P2); spec rules 5, 6, 8 (Paul: gate and alert), 10; R2 brief

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e5a1f614e3b402b3f6e20cfafc6d0909ef91404a parent 1ea7e81
4 files changed, +265 −215
  • docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md +113 −200
  • docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md +115 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1B-PLAN.md +6 −2
  • docs/superpowers/specs/2026-10-28-managed-fleets-design.md +31 −13

CI passed — run details

diff --git a/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md b/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md
index f5ed6c1a9..0837c6a0d 100644
--- a/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md
+++ b/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md
@@ -1,252 +1,165 @@
-# Managed fleets 1b: each instance runs on one named box Implementation Plan
+# Managed fleets 1b: each instance runs on one named box Implementation Plan (rev 2)
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-**Goal:** On a fleet with two or more boxes, each instance runs on exactly one box the console chose, traffic goes straight to it, a lost or detached box's instances move to the survivors, and no box ever boots a stale local copy (#470).
+**Goal:** On a fleet with two or more boxes, each instance runs on exactly one box the console chose, traffic goes straight to it, a lost or drained box's instances move to the survivors, and no box boots a stale local copy or loses unreplicated writes (#470).
-**Architecture:** The console stamps the chosen box's label and an assignment time on the instance record. A fleet box mints only records labelled for it (or unlabelled ones, today's behaviour). The hub's forward row carries the label as `FleetBox` from the first write. A console worker labels existing records once a fleet is ready for it and relabels records off detached or silent boxes. A box notes the assignment time beside each local database and discards the copy when the record's assignment changed.
+**Architecture:** The console stamps the chosen box's label and an assignment time on the instance record, conditional on the record's placement and label at the time. A fleet box mints only records labelled for it (or unlabelled ones, as today). The hub's forward row carries the label as its authoritative box; the edge never falls back to another box for a labelled row. A console worker labels existing records to the box already serving them, moves records off silent boxes, and drives two-step drains. A box sets a stale local copy aside (never deletes it) and restores, or refuses to start when there is nothing to restore.
-**Tech Stack:** Go. `internal/provision` (record, reconcile, forward phase), `internal/registry` (route columns), `internal/console` (create doors, worker, detach door, rootfs admission), `internal/activator` (restore), `internal/host` (wiring).
+**Tech Stack:** Go. `internal/provision`, `internal/registry`, `internal/edge`, `internal/console`, `internal/activator`, `internal/host`, `cmd/console`.
-**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, "1b addendum", rules 1-10 (approved by Paul 2026-10-30; rule 6 is his option 1). Code map: main 65fd8060 (1a merged). 1a's spec: `docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md`.
+**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, "1b addendum", rules 1-10 (approved by Paul 2026-10-30; rule 6 his option 1; rule 8 his "gate and alert"; rules 5 and 10 revised after plan review R1). Code: main 65fd8060 (1a merged). Review history: round 1 `docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md` (7 P1, 4 P2), dispositions at the end of this plan.
## Global Constraints
-- Unlabelled records behave exactly as on main: every box of the fleet mints them. Single-box fleets never get labels.
-- The console labels a fleet's records only when the fleet has two or more active boxes and every active box's heartbeat reports a version at or above `release.FleetBoxLabelFloor` (`"v0.33.0"`; the release that ships this must be v0.33.0 or later). Below that, nothing is labelled and nothing changes.
-- A label is always written with its assignment time, together; a relabel is conditional on the label it replaces.
-- The lease stays the one-writer guarantee. Nothing here takes or releases a lease differently.
-- Lost-box threshold: no fresh heartbeat for `lease.LeaseTTL + 5*time.Minute` (20 minutes today).
-- No new per-box bucket polling (memory "S3 requests cost money"). The console worker runs every 5 minutes and reads only fleets with two or more active boxes.
-- Member-facing strings (the detach refusal) go through a Luna copy pass before merge; diagnostics and log lines do not.
-- Local tests: touched packages with `-run`; activator tests with `TMPDIR=/tmp/k`; Go builds in a worktree with `GOFLAGS=-buildvcs=false`; CI runs the full suite. Darwin and windows must cross-compile.
-- Neutral names in code, tests and copy (`shop`, `example.com`, fleet `pi`, boxes `pi-1`, `pi-2`).
+- Unlabelled records behave exactly as on main. Single-box fleets and fleets with sidecars are never labelled.
+- **Activation gate** (`release.FleetBoxLabelFloor = "v0.33.0"`; the release that ships this must be v0.33.0 or later): the console labels a fleet only when (a) the fleet has two or more active boxes, (b) the fleet has no sidecar records, (c) every box in the deployment, platform and fleet, reports a version at or above the floor in its heartbeat (the same complete box listing `carlos system status` reads; an incomplete listing counts as not met), and (d) the console's own version is at or above it.
+- **Alert:** once a fleet has labels, a box in it reporting a version below the floor pauses all relabelling for that fleet and raises an alert (an ERROR log line naming fleet, box and version, plus `LABELS PAUSED` in `carlos fleets ls`), until every box is back at or above the floor.
+- Every label write is a conditional update: the record's region, current label and `CreatedAt` must equal what the decision read, rechecked inside every retry of the update.
+- A stale local copy is set aside, never deleted. A box that set a copy aside and finds no replica refuses to start that instance.
+- The lease stays the one-writer guarantee. Lease take and release are unchanged.
+- Lost box: no fresh heartbeat for `lease.LeaseTTL + 5*time.Minute` (20 minutes).
+- **Request budget** (asserted by store-call counting tests in Tasks 2 and 6): an idle worker pass costs, per labelled fleet, one heartbeat LIST plus one GET per box, then one LIST per placed app; zero record GETs and zero PUTs when nothing is unlabelled, lost or draining. A create on a labelled fleet adds one heartbeat read (memoised per request) and one inventory per fleet (one LIST per placed app). First labelling of a fleet reads each record once and each binding object once, then one PUT per record. A move or drain reads one inventory per pass and writes one PUT per moved record; load counts update in memory after each write.
+- Member-facing strings (drain and detach refusals, the sidecar refusal, the paused state) get a Luna copy pass before merge; log lines do not.
+- Local tests: touched packages with `-run`; activator and host e2e tests with `TMPDIR=/tmp/k` (Unix socket path length, memory "Gate tmp exec wrapper"); Go builds in a worktree with `GOFLAGS=-buildvcs=false`; CI runs the full suite. Darwin and windows must cross-compile.
+- Neutral names (`shop`, `example.com`, fleet `pi`, boxes `pi-1`, `pi-2`).
## Review Focus
-1. **Two creates at once on the same fleet** both counting the same load and picking the same box. Expect: they serialise on the fleet and land on different boxes when loads tie. Test in Task 2.
-2. **A box comes back after its records were relabelled away** (it was partitioned, not dead). Expect: it drops those rows and never serves them; the new box waits out the lease if the old one still renews. Test in Tasks 3 and 7.
-3. **A, then B, then A** for one instance. Expect: A restores on its second turn and serves B's writes. Test in Tasks 4 and 7.
-4. **A mixed-version fleet** (one box below the floor). Expect: no labels are written, every record keeps today's behaviour. Test in Task 2 and Task 6.
-5. **Detaching the only ready box** while it runs instances. Expect: refused, naming the apps; nothing relabelled. Test in Task 6.
+1. **A box partitioned from the console but still renewing its lease** while its records move. Expect: the destination waits out the lease; the source drops the rows when it next reads the record; no writes are lost (the source's copy is set aside on any later return). Task 7.
+2. **First labelling of a running fleet.** Expect: every record is labelled to the box already serving it; nothing moves; each box sets its copy aside once and restores the same data. Tasks 4, 6, 7.
+3. **A rollback of one box below the floor after labelling.** Expect: relabelling pauses with an alert; nothing else changes. Task 6.
+4. **Drain with one record that has nowhere to go.** Expect: the drain refuses up front, naming the app, and relabels nothing. Task 6.
+5. **A placement change racing a relabel.** Expect: the relabel loses (`ErrFleetBoxMoved`) and the record stays unlabelled in its new fleet. Tasks 1 and 6.
---
### Task 1: The record carries a box and an assignment time
-**Files:**
-- Modify: `internal/provision/provision.go` (Record, `SetRecordRegion` at :1023)
-- Create: `internal/provision/fleetbox.go`
-- Test: `internal/provision/fleetbox_test.go`; census overlay beside `internal/provision/fleet_public_routes_census_test.go`
+**Files:** Modify `internal/provision/provision.go` (Record; `SetRecordRegion` :1023); create `internal/provision/fleetbox.go`; test `internal/provision/fleetbox_test.go`; census `internal/provision/plan9_b8_census_test.go` (name table :52-76, the inventory the test selects :369) and a new overlay layered on `fleetPublicRoutesWriteCensusInventory`.
-**Interfaces:**
-- Produces: `Record.FleetBox string` (`json:"fleet_box,omitempty"`), `Record.FleetBoxAt string` (`json:"fleet_box_at,omitempty"`, RFC 3339 nanoseconds, UTC); `func SetRecordFleetBox(ctx context.Context, s release.Store, acct, app, host, wantLabel, label string, at time.Time) error` (writes both fields only if the record's current label equals `wantLabel`; `ErrFleetBoxMoved` otherwise); `var ErrFleetBoxMoved = errors.New(...)`.
+**Interfaces (produces):**
+- `Record.FleetBox string` (`json:"fleet_box,omitempty"`), `Record.FleetBoxAt string` (`json:"fleet_box_at,omitempty"`, RFC 3339 nanoseconds, UTC).
+- `type FleetBoxExpect struct { Region, Label string; CreatedAt time.Time }`.
+- `func SetRecordFleetBox(ctx context.Context, s release.Store, acct, app, host string, want FleetBoxExpect, label string, at time.Time) error` writes both fields when the current record's Region, FleetBox and CreatedAt equal `want`, rechecked inside each retry of the update; else `ErrFleetBoxMoved`.
+- `SetRecordRegion` clears both fields when the region changes.
-- [ ] **Step 1: Write the failing tests**
+- [ ] **Step 1: Write the failing tests.** `TestRecordFleetBoxRoundTrip`; `TestSetRecordFleetBoxIsConditional` (label, then a stale `want` loses); `TestSetRecordFleetBoxLosesToAPlacementChange` (region changed between read and write: `ErrFleetBoxMoved`, record unlabelled); `TestSetRecordFleetBoxLosesToARecreate` (same host recreated with a new `CreatedAt`); `TestSetRecordRegionClearsTheBox`.
+- [ ] **Step 2: Run them to see them fail.** `go test ./internal/provision/ -run 'RecordFleetBox|SetRecordFleetBox|SetRecordRegionClears'` → FAIL.
+- [ ] **Step 3: Implement** through the record's update scaffold (the path `SetRecordRegion` uses, `provision.go:1093-1139`), the expectation checked inside the mutation.
+- [ ] **Step 4: Census.** Add `SetRecordFleetBox` to the typed-writer name table, extend the rejection witnesses, add the overlay and switch the test's selected inventory to it. `go test ./internal/provision/ -run 'RecordFleetBox|SetRecordFleetBox|SetRecordRegion|TestPlan9B8RecordWriteCensus'` → PASS.
+- [ ] **Step 5: Commit.**
-`TestRecordFleetBoxRoundTrip`: a record with `FleetBox:"pi-2", FleetBoxAt:"2026-10-30T18:00:00Z"` survives `CreateRecord` then a read; a record without them marshals with neither key.
-`TestSetRecordFleetBoxIsConditional`: from label `""` to `pi-1` succeeds; a second call wanting `""` returns `ErrFleetBoxMoved` and leaves `pi-1`; wanting `pi-1` to `pi-2` succeeds and updates `FleetBoxAt`.
-`TestSetRecordRegionClearsTheBox`: `SetRecordRegion` to another region clears both fields; to the same region keeps them.
+### Task 2: The console labels at create, behind the activation gate (rules 1, 7, 8, 10)
-- [ ] **Step 2: Run them to see them fail**
+**Files:** create `internal/console/fleetbox.go`; modify `internal/console/apiinstances.go` (before the record create, ~:2264), `internal/console/apisidecars.go` (the create door), `internal/console/rootfs.go:189-244`, `internal/release/layoutintent.go` (the floor), the store (`AppsPlacedOn`); tests `internal/console/fleetbox_test.go`, `rootfs_test.go`, `apisidecars_test.go`.
-Run: `go test ./internal/provision/ -run 'TestRecordFleetBox|TestSetRecordFleetBox|TestSetRecordRegionClearsTheBox'`
-Expected: FAIL (unknown fields, undefined function).
+**Interfaces (produces):**
+- `const release.FleetBoxLabelFloor = "v0.33.0"`.
+- `type fleetView struct { Boxes []fleetBoxView; Active, HasSidecars, DeploymentCurrent bool; Load map[string]int }`; `type fleetBoxView struct { Label string; Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor bool; LastSeen time.Time }`.
+- `func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, error)`: one heartbeat listing, one deployment-wide box listing for (c), one inventory (`AppsPlacedOn` plus `provision.ListRecordsCompleteJudged` per app) for `Load` and `HasSidecars`. An incomplete or truncated listing leaves `Active` false.
+- `func (v fleetView) labelActive() bool`: the Global Constraints gate.
+- `func (v fleetView) chooseDestination(rootfs bool, exclude string) string`: among boxes that are fresh, not draining, at the label floor (and rootfs-ready at the rootfs floor for a rootfs record), the lowest load, ties by label; "" when none. Independent of whether other boxes are fresh.
+- `func (s *Server) lockFleet(fleet string) (unlock func())`: one mutex per fleet, held from `loadFleetView` through the record create.
+- Store `AppsPlacedOn(ctx context.Context, placement string) ([]AppRef, error)`.
+- Copy: `msgSidecarNeedsSingleBoxFleet(fleet string) string`.
-- [ ] **Step 3: Implement**
+- [ ] **Step 1: Write the failing tests.** `TestCreateOnASingleBoxFleetLeavesNoLabel`; `TestCreateLabelsTheLeastLoadedReadyBox`; `TestCreateSkipsStaleDrainingAndDetachedBoxes`; `TestGateNeedsEveryDeploymentBoxCurrent` (a platform box below the floor: no label); `TestGateClosedForAFleetWithSidecars`; `TestGateClosedOnAnIncompleteListing`; `TestConcurrentCreatesSpreadAcrossBoxes`; `TestSidecarCreateRefusedOnAMultiBoxFleet` (and allowed on a single-box fleet); `TestRootfsAdmissionFollowsTheChosenBox`; `TestCreateOnALabelledFleetCostsOneInventory` (store-call counter: one LIST per placed app, zero record PUTs beyond the create). Existing `rootfs_test.go` and `TestAPIInstanceCreateInheritsFleetPlacement` still pass.
+- [ ] **Step 2: Run them to see them fail.** `go test ./internal/console/ -run 'FleetBox|LeastLoaded|SkipsStale|Gate|ConcurrentCreatesSpread|SidecarCreateRefused|RootfsAdmissionFollows|CostsOneInventory'` → FAIL.
+- [ ] **Step 3: Implement.** Freshness and readiness reuse `status.BoxStale`, `boxRootfsReady`, `boxAtRootfsFloor` and the join at `rootfs.go:212-238`. The create door stamps the label only when `labelActive()`; a rootfs create on an active fleet with no rootfs-ready destination is refused with today's rootfs refusal.
+- [ ] **Step 4: Run them to see them pass,** plus `-run 'Rootfs|FleetPlacement|Sidecar'` → PASS.
+- [ ] **Step 5: Commit.**
-Fields beside `Runtime` with a comment naming 1b rules 1 and 6. `SetRecordFleetBox` goes through the record's existing update path (the one `SetRecordRegion` uses), so `RecordSeq` advances. Every record writer decodes and re-marshals the whole record, so the fields survive writers built with this change; older console or platform-box binaries would drop them, which is why Task 2's floor gates labelling on every box being current.
+### Task 3: A fleet box mints only its own records (rules 2, 9)
-- [ ] **Step 4: Run them to see them pass, then the record-write census**
+**Files:** modify `internal/provision/reconcile.go` (`ReconcileConfig`; `inScope` callers :1253, :2182, :2263), `internal/provision/seedreconcile.go:177`, `internal/registry` (Route `Assigned`, column `fleet_assigned`, migration), `internal/host/agent.go:3504` (`provisionTickConfig`); tests in `internal/provision/reconcile_test.go`, `reconcile_lifetime_test.go`, `internal/registry`, `internal/host/host_test.go`.
-Run: `go test ./internal/provision/ -run 'TestRecordFleetBox|TestSetRecordFleetBox|TestSetRecordRegion|TestPlan9B8RecordWriteCensus'`
-Expected: the three new tests PASS; the census FAILs naming `SetRecordFleetBox` and `SetRecordRegion`. Add an overlay inventory layered on `fleetPublicRoutesWriteCensusInventory` re-pinning them, then PASS.
+**Interfaces (produces):** `ReconcileConfig.FleetBox string` (from `resolveFleetIdentity`); `func (cfg ReconcileConfig) ownsRecord(rec Record) bool` (true off a fleet, for an unlabelled record, or when the label is `cfg.FleetBox`); `registry.Route.Assigned string`, minted from `rec.FleetBoxAt` on the box's own row and rewritten when it changes.
-- [ ] **Step 5: Commit**
+- [ ] **Step 1: Write the failing tests.** `TestFleetBoxMintsOnlyItsOwnRecords`; `TestRelabelledRowIsRemovedNotKept` (lifetimes on and off; copy `TestOutOfScopeValidRecordFollowsTodaysRemoval`); `TestRelabelledSeedIsNotAdopted`; `TestMintedRowCarriesTheAssignment`; `TestProvisionTickConfigCarriesTheFleetBox`.
+- [ ] **Step 2: Run them to see them fail.** `go test ./internal/provision/ ./internal/registry/ ./internal/host/ -run 'FleetBoxMints|RelabelledRow|RelabelledSeed|MintedRowCarries|ProvisionTickConfigCarries'` → FAIL.
+- [ ] **Step 3: Implement.** `ownsRecord` is checked at every place `inScope` admits a record or keeps a row on a fleet box. A removed row retires its instance through `RetireExcept`; workers are stopped by `StopRetired`'s worker path (`activator.go:5642-5657`): add `TestRetiredRowStopsItsWorkers` if no existing test covers a rootfs entry with workers.
+- [ ] **Step 4: Run them to see them pass,** plus `-run 'Reconcile|Seed|Retire'` → PASS.
+- [ ] **Step 5: Commit.**
-### Task 2: The console picks the box at create (rules 1, 7, 8, 10)
+### Task 4: Set a stale copy aside, restore, or refuse (rule 6, #470)
-**Files:**
-- Create: `internal/console/fleetbox.go`
-- Modify: `internal/console/apiinstances.go` (before the record is created, ~:2264), the sidecar create door (`apisidecars.go`), `internal/console/rootfs.go:189-244`, `internal/release/layoutintent.go` (the floor), the store (an apps-on-fleet query)
-- Test: `internal/console/fleetbox_test.go`, `internal/console/rootfs_test.go`
+**Files:** modify `internal/activator/backend_exec.go` (`restorePlain`, beside `reconcileSeedMarker` at :879); test `internal/activator/activator_test.go` beside `TestExecBackendRestoreWarmCacheIsNotFresh` (:5774).
-**Interfaces:**
-- Consumes: Task 1's fields.
-- Produces: `const release.FleetBoxLabelFloor = "v0.33.0"`; `func (s *Server) fleetLabelReady(ctx context.Context, fleet string) (boxes []fleetBoxView, ready bool, err error)` (two or more active boxes, every one fresh and at or above the floor); `type fleetBoxView struct { Label string; Fresh, RootfsReady, AtRootfsFloor bool }`; `func (s *Server) chooseFleetBox(ctx context.Context, fleet string, rootfs bool, exclude string) (label string, err error)` ("" = leave unlabelled); `func (s *Server) fleetBoxLoad(ctx context.Context, fleet string) (map[string]int, error)` (labelled records per box); `func (s *Server) lockFleet(fleet string) func()` (per-fleet mutex, held from the choice through the record create); store `AppsPlacedOn(ctx context.Context, placement string) ([]AppRef, error)`.
+**Interfaces (produces):** `func (b *ExecBackend) reconcileAssignment(rt registry.Route, dbPath string) (setAside string, err error)`; marker `dbPath + ".assigned"` holding `rt.Assigned`, written atomically (temp file and rename); set-aside directory `<data dir>/.superseded/<host>/<unix nanos>/` holding the database and its litestream sidecar state (the files `reconcileSeedMarker` would remove); `var ErrNothingToRestore` whose message names the set-aside path.
-- [ ] **Step 1: Write the failing tests**
+- [ ] **Step 1: Write the failing tests.** `TestAssignmentChangeSetsTheCopyAside` (marker `T1`, route `T2`: the files move to `.superseded`, nothing is deleted, the restore runs, the marker reads `T2`); `TestSameAssignmentKeepsTheWarmCopy`; `TestUnassignedRouteIgnoresTheMarker`; `TestMissingMarkerSetsAside`; `TestNothingToRestoreRefuses` (a copy set aside and no replica: the wake fails with `ErrNothingToRestore`, no fresh boot); `TestNewInstanceBootsFresh` (assigned route, no local copy, nothing set aside, no replica: fresh boot, marker written); `TestFailedRestoreLeavesNoMarker` (the next wake tries again; the set-aside copy is still there); `TestUnreplicatedTailSurvives` (bytes written after the last replication are present in the set-aside copy).
+- [ ] **Step 2: Run them to see them fail.** `TMPDIR=/tmp/k go test ./internal/activator/ -run 'AssignmentChange|SameAssignment|UnassignedRoute|MissingMarker|NothingToRestore|NewInstanceBootsFresh|FailedRestoreLeaves|UnreplicatedTail'` → FAIL.
+- [ ] **Step 3: Implement.** Called before the warm-cache check. HA routes keep `restoreHA`, unchanged. The marker is written only after a successful restore, a kept matching copy, or a fresh boot of a new instance.
+- [ ] **Step 4: Run them to see them pass,** plus `-run 'Assignment|Marker|WarmCache|Seed|Restore'` → PASS.
+- [ ] **Step 5: Commit.**
-`TestCreateOnASingleBoxFleetLeavesNoLabel`, `TestCreateLabelsTheLeastLoadedReadyBox` (boxes `pi-1` with two labelled records, `pi-2` with none: the new record names `pi-2` with a non-zero `FleetBoxAt`; ties go to the lower label), `TestCreateSkipsStaleAndDetachedBoxes`, `TestMixedVersionFleetLeavesNoLabel` (one box below the floor: no label), `TestConcurrentCreatesSpreadAcrossBoxes` (two creates in parallel on a fleet of two empty boxes end on different boxes), `TestSidecarCreateLabelsToo`. Rootfs: `TestRootfsAdmissionFollowsTheChosenBox` (labelled: admitted when the chosen box is rootfs-ready even if another box is not; refused when the chosen box is not), and the existing `rootfs_test.go` cases still pass for an unlabelled fleet. Copy `TestAPIInstanceCreateInheritsFleetPlacement`'s setup.
+### Task 5: The forward row's box is authoritative when labelled (rule 3)
-- [ ] **Step 2: Run them to see them fail**
+**Files:** modify `internal/provision/forward.go` (`forwardRowFor` :25, `forwardCurrent` :43), `internal/registry/forward.go` (`putForwardSQL` :260-285, `PutForward` :297, `SetFleetBoxIf` :29, `forwardShape` :93), `internal/edge/edge.go` (`fleetChannelFor` :3223, `fleetProxy`); tests in `internal/provision/forward_test.go`, `internal/registry/forward_test.go`, `fleetbox_if_test.go`, `internal/edge/fleet_route_test.go`.
-Run: `go test ./internal/console/ -run 'FleetBox|LeastLoaded|MixedVersion|ConcurrentCreatesSpread|SidecarCreateLabels|RootfsAdmissionFollows'`
-Expected: FAIL (undefined).
+**Interfaces (produces):** `registry.Route.FleetLabel string` (column `fleet_label`, forward rows only); `PutForward` writes `fleet_label`, and `fleet_box = fleet_label` when the label is set; `SetFleetBoxIf` changes nothing on a row with a label; `func fleetChannelFor(fleet, boxLabel string, authoritative bool, hub *TunnelHub) string` (no fallback when `authoritative`).
-- [ ] **Step 3: Implement**
+- [ ] **Step 1: Write the failing tests.** `TestForwardRowCarriesTheLabel`; `TestQuietPassWritesNothingForABoundUnlabelledRow` (write counter over three passes: zero writes after the first); `TestPutForwardWritesTheLabelAsFleetBox`; `TestBindingDoesNotOverrideALabel`; `TestBindingStillBindsUnlabelledRows`; `TestLabelledForwardDoesNotFallBack` (row labelled `pi-2`, only `pi-1` connected: 503 with `Retry-After`); `TestUnlabelledForwardStillFallsBack`. Update `TestForwardShapeClassesEveryField`.
+- [ ] **Step 2: Run them to see them fail.** `go test ./internal/provision/ ./internal/registry/ ./internal/edge/ -run 'ForwardRowCarries|QuietPass|PutForwardWritesTheLabel|BindingDoesNotOverride|BindingStillBinds|LabelledForward|UnlabelledForward|ForwardShape'` → FAIL.
+- [ ] **Step 3: Implement.** `forwardCurrent` compares `FleetLabel`, and compares `FleetBox` only when the wanted row has a label.
+- [ ] **Step 4: Run them to see them pass,** plus `-run 'Forward|FleetRoute|FleetBox'` → PASS.
+- [ ] **Step 5: Commit.**
-Freshness and readiness reuse `status.BoxStale`, `boxRootfsReady` and `boxAtRootfsFloor` and the active-box join at `rootfs.go:212-238`. Load counts labelled records per box over `AppsPlacedOn` plus `provision.ListRecordsCompleteJudged`. A rootfs create chooses among rootfs-ready boxes at the rootfs floor. The admission check in `rootfsReadyRefusal` uses the chosen box when a label was chosen and keeps today's fleet-wide rule otherwise.
+### Task 6: The relabel worker, two-step drain, pause and alert (rules 2, 4, 5, 8)
-- [ ] **Step 4: Run them to see them pass**
+**Files:** create `internal/console/fleetrelabel.go`; modify `internal/console/claim_workers.go`, `cmd/console/main.go`, `internal/console/testdata/claim-routes.txt`, `internal/console/fleets.go` (new drain door; detach doors :544, :1455), `internal/registry/fleets.go` (`draining` column on `fleet_boxes`; `FleetChannelAuth` still admits a draining active box), `fleets.go` at the repo root (the CLI: `carlos fleets drain`, `LABELS PAUSED` in `fleets ls`); tests `internal/console/fleetrelabel_test.go`, `cmd/console/claimworkers_started_test.go`, `internal/registry` fleet tests, `cli_test.go` patterns for the CLI.
-Run: the Step 2 command plus `-run 'Rootfs|FleetPlacement'`. Expected: PASS.
+**Interfaces (produces):** worker `FleetRelabel` every 5 minutes, started like `StartRunSweep`; `func (s *Server) fleetRelabelPass(ctx context.Context) error`; `func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (moved int, err error)`; `func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []string, err error)`; `func (s *Server) boxEmpty(ctx context.Context, fleet, label string) (bool, error)` (its heartbeat reports no instance of the fleet and no record names it); `const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute`; copy `msgDrainStrandsApps(fleet, label string, apps []string) string`, `msgDetachNotDrained(fleet, label string) string`.
-- [ ] **Step 5: Commit**
+Per fleet, per pass: if a labelled fleet has a box below the floor, log the alert and skip it (paused). Else if `labelActive()`: label each unlabelled record to the box its binding names (`fleets/<f>/bindings/<host>.json`) when that box is a valid destination, otherwise `chooseDestination`; move each record whose box is lost to `chooseDestination(rootfs, lost)`; move each record of a draining box likewise. All writes use `SetRecordFleetBox` with the expectation read in this pass; `ErrFleetBoxMoved` is skipped until the next pass. Truncated or skipped records make the pass write nothing for that fleet.
-### Task 3: A fleet box mints only its own records (rules 2, 9, 10)
-
-**Files:**
-- Modify: `internal/provision/reconcile.go` (`ReconcileConfig`, :1253, :2182, :2263), `internal/provision/seedreconcile.go:177`, `internal/provision/sidecar_reconcile.go`, `internal/registry` (Route `Assigned` column), `internal/host/agent.go:3504` (`provisionTickConfig`)
-- Test: `internal/provision/reconcile_test.go`, `reconcile_lifetime_test.go`, `internal/host/host_test.go`
-
-**Interfaces:**
-- Consumes: Task 1's fields.
-- Produces: `ReconcileConfig.FleetBox string` (this box's label, from `resolveFleetIdentity`); `func (cfg ReconcileConfig) ownsRecord(rec Record) bool` (true when the box is not on a fleet, the record has no label, or the label equals `cfg.FleetBox`); `registry.Route.Assigned string` (column `fleet_assigned`, migration), minted from `rec.FleetBoxAt` on the box's own row.
-
-- [ ] **Step 1: Write the failing tests**
-
-`TestFleetBoxMintsOnlyItsOwnRecords` (two records labelled `pi-1` and `pi-2` and one unlabelled: box `pi-1` mints the first and third), `TestRelabelledRowIsRemovedNotKept` (a minted row whose record now names `pi-2` is removed by the removal phase on `pi-1`, lifetimes on and off, copying `TestOutOfScopeValidRecordFollowsTodaysRemoval`), `TestSidecarFollowsItsLabel`, `TestMintedRowCarriesTheAssignment` (`Route.Assigned` equals the record's `FleetBoxAt`, and a changed `FleetBoxAt` rewrites the row), `TestProvisionTickConfigCarriesTheFleetBox` (beside `TestProvisionTickConfig`).
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `go test ./internal/provision/ ./internal/host/ -run 'FleetBoxMints|RelabelledRow|SidecarFollows|MintedRowCarries|ProvisionTickConfigCarries'`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**
-
-`ownsRecord` sits beside `inScope` and is checked wherever `inScope` admits a record or keeps a row on a fleet box (the scan, the row filter, the removal phase, seeds, sidecars). A row removed this way stops its instance through the existing `RetireExcept` path.
-
-- [ ] **Step 4: Run them to see them pass**
-
-Run: `go test ./internal/provision/ -run 'Reconcile|FleetBox|Sidecar|Seed'` and the host test. Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-### Task 4: No stale local copy (rule 6, #470)
-
-**Files:**
-- Modify: `internal/activator/backend_exec.go` (`restorePlain`, beside `reconcileSeedMarker` at :879)
-- Test: `internal/activator/activator_test.go` beside `TestExecBackendRestoreWarmCacheIsNotFresh` (:5774)
-
-**Interfaces:**
-- Consumes: `registry.Route.Assigned` (Task 3).
-- Produces: `func reconcileAssignmentMarker(rt registry.Route, dbPath string) error`; marker file `dbPath + ".assigned"` holding `rt.Assigned`.
-
-- [ ] **Step 1: Write the failing tests**
-
-`TestAssignmentChangePurgesTheWarmCopy` (a local db with marker `T1`, route `Assigned` `T2`: the db and its litestream sidecar state are removed before the warm-cache check, so `restorePlain` restores; the marker then reads `T2`), `TestSameAssignmentKeepsTheWarmCopy` (marker equals `Assigned`: warm cache kept, no restore), `TestUnassignedRouteIgnoresTheMarker` (`Assigned` empty: today's behaviour, marker untouched), `TestMissingMarkerWithAssignmentPurges` (a db with no marker under an assigned route counts as stale).
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `TMPDIR=/tmp/k go test ./internal/activator/ -run 'AssignmentChange|SameAssignment|UnassignedRoute|MissingMarker'`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**
-
-Mirror `reconcileSeedMarker`'s purge (the same files it removes). Write the marker only after a successful restore or when keeping a matching copy, so a failed restore leaves no marker and the next wake purges again. HA routes keep their own rules (`restoreHA`), unchanged.
-
-- [ ] **Step 4: Run them to see them pass**
-
-Run: `TMPDIR=/tmp/k go test ./internal/activator/ -run 'Assignment|Marker|WarmCache|Seed'`. Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-### Task 5: The forward row knows the box from the start (rule 3)
-
-**Files:**
-- Modify: `internal/provision/forward.go` (`forwardRowFor` :25, `forwardCurrent` :43), `internal/registry/forward.go` (`putForwardSQL` :260-285, `PutForward` :297, `SetFleetBoxIf` :29), the forward shape table (`forwardShape`, :93)
-- Test: `internal/registry/forward_test.go`, `internal/registry/fleetbox_if_test.go`, `internal/provision/forward_test.go`
-
-**Interfaces:**
-- Produces: forward rows carry `FleetBox = rec.FleetBox`; registry column `fleet_label` (the record's label) on forward rows; `PutForward` writes `fleet_box` from a non-empty label; `SetFleetBoxIf` changes nothing on a row whose `fleet_label` is set.
-
-- [ ] **Step 1: Write the failing tests**
-
-`TestForwardRowCarriesTheLabel` (provision: a labelled record mints `FleetBox:"pi-2"`; a relabel to `pi-1` rewrites it; an unlabelled record leaves `FleetBox` to the bindings as today), `TestPutForwardWritesTheLabelAsFleetBox`, `TestBindingDoesNotOverrideALabel` (registry: `SetFleetBoxIf` on a labelled row returns false and leaves `fleet_box`), `TestBindingStillBindsUnlabelledRows` (today's behaviour). Update `TestForwardShapeClassesEveryField` for the new column.
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `go test ./internal/provision/ ./internal/registry/ -run 'ForwardRowCarries|PutForwardWritesTheLabel|BindingDoesNotOverride|BindingStillBinds|ForwardShape'`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**
-
-`forwardCurrent` compares `FleetBox` so a relabel rewrites the row and a quiet pass writes nothing. `fleetChannelFor`'s fallback (`internal/edge/edge.go:3223`) stays: it still serves unlabelled rows and a labelled box that is briefly disconnected answers 503 rather than reaching a box that does not hold the host. Add a test for that in `internal/edge` (`TestLabelledForwardDoesNotFallBack`): a labelled row whose box is disconnected answers 503 with `Retry-After`.
-
-- [ ] **Step 4: Run them to see them pass**
-
-Run: the Step 2 command plus `go test ./internal/edge/ -run 'LabelledForward|FleetRoute'`. Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-### Task 6: Label existing records, move a lost box's records, drain on detach (rules 2, 4, 5)
-
-**Files:**
-- Create: `internal/console/fleetrelabel.go`
-- Modify: `internal/console/claim_workers.go`, `cmd/console/main.go`, `internal/console/testdata/claim-routes.txt`, `internal/console/fleets.go` (`handleAPIFleetDetachBox` :544, `handleFleetDetachBoxPage` :1455)
-- Test: `internal/console/fleetrelabel_test.go`, `cmd/console/claimworkers_started_test.go`
-
-**Interfaces:**
-- Consumes: Tasks 1-2.
-- Produces: `func (s *Server) fleetRelabelPass(ctx context.Context) error`; worker name `FleetRelabel`, every 5 minutes, started like `StartRunSweep`; `func (s *Server) relabelOff(ctx context.Context, fleet, label string) (moved int, stuck []string, err error)`; `const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute`; refusal copy `msgDetachStrandsApps(fleet, label string, apps []string) string`.
-
-- [ ] **Step 1: Write the failing tests**
-
-`TestRelabelPassLabelsAReadyFleet` (two current boxes, three unlabelled records: all labelled, spread 2-1), `TestRelabelPassLeavesAMixedFleetAlone`, `TestRelabelPassMovesALostBoxsRecords` (box `pi-1` silent for 21 minutes: its records go to `pi-2` with a newer `FleetBoxAt`; silent for 19: nothing moves), `TestRelabelLosesToAConcurrentRelabel` (`ErrFleetBoxMoved` is skipped, not retried in the same pass), `TestDetachRelabelsFirst` (detach `pi-1`: its records move to `pi-2`, then the box is detached), `TestDetachRefusesWhenNothingCanTakeThem` (only box ready: 409 with `msgDetachStrandsApps`, nothing relabelled, box still active), `TestEveryRegisteredClaimWorkerIsStarted` passes with `FleetRelabel`.
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `go test ./internal/console/ ./cmd/console/ -run 'RelabelPass|RelabelLoses|DetachRelabels|DetachRefuses|ClaimWorker'`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**
-
-Each pass reads only fleets with two or more active boxes, under `lockFleet`. Relabelling uses `chooseFleetBox(..., exclude)` and `SetRecordFleetBox` wanting the old label. Log one line per moved record (host, from, to, reason). The detach doors call `relabelOff` before `SetFleetBoxStatus`. Run the refusal string through Luna with the plan's other copy before merge.
-
-- [ ] **Step 4: Run them to see them pass**
-
-Run: the Step 2 command. Expected: PASS.
-
-- [ ] **Step 5: Commit**
+- [ ] **Step 1: Write the failing tests.** `TestFirstLabellingFollowsBindings` (three running records, bindings on `pi-1`, `pi-1`, `pi-2`: labelled the same; nothing moves); `TestRelabelPassLeavesAnUngatedFleetAlone`; `TestLostBoxMovesToTheSurvivor` (two-box fleet, `pi-1` silent 21 minutes: all its records to `pi-2`; 19 minutes: nothing); `TestRelabelLosesToAPlacementChange`; `TestBelowFloorBoxPausesAndAlerts`; `TestDrainMovesEverythingOrNothing` (one record with no destination: refused naming the app, nothing written); `TestDrainingBoxKeepsFleetAccess` (`FleetChannelAuth` still lists it); `TestDetachRefusedUntilDrainedAndEmpty`; `TestIdlePassCostsTheBudget` (store-call counter for an idle labelled fleet: per the Global Constraints); `TestEveryRegisteredClaimWorkerIsStarted` with `FleetRelabel`; CLI tests for `carlos fleets drain` and the `LABELS PAUSED` column.
+- [ ] **Step 2: Run them to see them fail.** `go test ./internal/console/ ./internal/registry/ ./cmd/console/ . -run 'FirstLabelling|RelabelPass|LostBox|RelabelLoses|BelowFloor|Drain|Detach|IdlePass|ClaimWorker|FleetsDrain|LabelsPaused'` → FAIL.
+- [ ] **Step 3: Implement.** Log one line per moved record (host, from, to, reason).
+- [ ] **Step 4: Run them to see them pass.** Same command → PASS.
+- [ ] **Step 5: Commit.**
### Task 7: A real two-box fleet test
-**Files:**
-- Create: `internal/host/fleettwobox_e2e_test.go`
-- Test helpers: build on `newE2EWorld` (`internal/host/movesoffline_e2e_test.go:215`: `leasetest.NewS3Server`, `CARLOS_S3_ENDPOINT`, real `ExecBackend` lease take and restore)
-
-**Interfaces:**
-- Consumes: everything above.
+**Files:** create `internal/host/fleettwobox_e2e_test.go` with its own fixture (borrowing from `newE2EWorld`, `internal/host/movesoffline_e2e_test.go:215`), plus the smallest production seams it needs.
-- [ ] **Step 1: Write the test**
+**Fixture requirements:** one fake S3 (`leasetest.NewS3Server`) holding one shared fleet data bucket; two real `ExecBackend`s with their own data directories and their own lease identities (`pi-1`, `pi-2`). The lease's owner is process-global today (`internal/lease/self.go`), so add an injectable identity used when set, defaulting to `lease.CurrentSelf()` in production, and a test that production wiring still uses the default. A short lease TTL set by the fixture (seconds, not 15 minutes) for deterministic expiry. The console's `fleetRelabelPass` called directly with an injected clock. A "partitioned" box: its lease keeps renewing while its record reads fail.
-`TestTwoBoxFleetEndToEnd_Real` with two box agents `pi-1`, `pi-2` on one fake S3, the console in process, a tiny native app writing a counter to its database:
-1. Two instances created: one lands on each box (labels, rows, forward rows).
-2. Each box mints only its own; each instance's lock owner names its box.
-3. Instance `a` on `pi-1`: write `1`. Stop `pi-1`'s agent and advance the console clock 21 minutes: the relabel pass moves `a` to `pi-2`; after the lease lapses `pi-2` restores and reads `1`; write `2`.
-4. Bring `pi-1` back: it drops `a`'s row and does not serve it.
-5. Relabel `a` back to `pi-1` (detach `pi-2`): `pi-1` purges its stale copy, restores and reads `2`, not `1`.
+- [ ] **Step 1: Write the test** `TestTwoBoxFleetEndToEnd_Real`: (1) two instances land one per box, with forward rows naming them; (2) each box mints only its own and each lock names its box; (3) `a` on `pi-1` writes `1`; `pi-1` is partitioned: the relabel moves `a` to `pi-2`, which waits while `pi-1` renews; heal the partition: `pi-1` reads the relabel, drops the row, releases; `pi-2` restores, reads `1`, writes `2`; (4) drain `pi-2`: `a` moves to `pi-1`, which sets its old copy aside, restores and reads `2`; (5) a first-labelling run over a fleet started unlabelled moves nothing and loses nothing.
+- [ ] **Step 2: Run it.** `TMPDIR=/tmp/k go test ./internal/host/ -run TestTwoBoxFleetEndToEnd_Real -v` → PASS. A failure is fixed in the code, not the test.
+- [ ] **Step 3: Commit.**
-- [ ] **Step 2: Run it**
+### Task 8: Census, copy, review, merge
-Run: `TMPDIR=/tmp/k go test ./internal/host/ -run TestTwoBoxFleetEndToEnd_Real -v`
-Expected: PASS. If it fails, fix the code, not the test (systematic debugging).
-
-- [ ] **Step 3: Commit**
-
-### Task 8: Census, review, merge
-
-- [ ] **Step 1:** `go test ./internal/provision/ -run TestPlan14RootReadCensus`; on failure follow AGENTS.md "The census" (`make census-card`, CLAIMS, `make census-propose NAME=<branch>`). The reviewer decides; record it on #280.
-- [ ] **Step 2:** Luna copy pass on `msgDetachStrandsApps` and any CLI help text; apply verbatim.
-- [ ] **Step 3:** Whole-branch Astra review from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3, with this plan's Review Focus. Tasks 3, 4 and 6 touch production storage and the removal path, so the brief names them.
+- [ ] **Step 1:** `go test ./internal/provision/ -run TestPlan14RootReadCensus`; on failure, AGENTS.md "The census" (`make census-card`, CLAIMS, `make census-propose NAME=<branch>`); include the two new route columns and the `fleet_boxes.draining` column. The reviewer decides; record on #280.
+- [ ] **Step 2:** Luna copy pass on the drain, detach and sidecar refusals, the `LABELS PAUSED` state and the drain help text; apply verbatim.
+- [ ] **Step 3:** Whole-branch Astra review from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3, with this plan's Review Focus; name Tasks 3, 4 and 6 as production storage and removal.
- [ ] **Step 4:** CI green on the tip; merge with `amadan branch merge carlos/platform <branch> -squash` on Paul's go.
### Task 9: Prove it on dev
-Live action, needs Paul's go with the scoped plan: account dev (kass), eu-west-1, one extra t4g.small fleet box `box-2` added to r10r with `carlos fleets add-box` and bootstrapped like box-1, for about two hours, then detached and terminated. Cost: about $0.05.
+Live action, needs Paul's go with the scoped plan: account dev (kass), eu-west-1, one extra t4g.small fleet box `box-2` added to r10r and bootstrapped like box-1, for about two hours, then drained, detached and terminated. Cost about $0.05.
+
+- [ ] **Step 1:** After v0.33.0 or later is on every dev box and the dev console, add `box-2`; within one pass, `shop` and `railsdemo` are labelled to `box-1` (their binding) and nothing moves.
+- [ ] **Step 2:** Create a throwaway app on r10r: it lands on `box-2`; its public URL serves from it.
+- [ ] **Step 3:** `carlos fleets drain r10r box-2`: the app moves to `box-1` and serves; detach then succeeds; terminate `box-2`.
+- [ ] **Step 4:** Post results on #457; close #470.
+
+---
-- [ ] **Step 1:** After the release carrying this (v0.33.0 or later) is on dev, add `box-2`; wait for both boxes current; within one relabel pass, `shop` and `railsdemo` carry labels, spread one per box.
-- [ ] **Step 2:** Create a throwaway app on r10r: it lands on the less loaded box; its public URL serves from that box (edge log on the hub names the box).
-- [ ] **Step 3:** Detach `box-2`: its instances move to `box-1` and serve within the lease window; then terminate `box-2`.
-- [ ] **Step 4:** Post results on #457 and close #470.
+## Round 1 dispositions (`CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md`)
+
+| # | Sev | Finding | Disposition |
+|---|---|---|---|
+| 1 | P1 | Purge can destroy the only surviving writes | Accepted. Task 4 sets aside, never deletes; refuses on no replica; fresh boot only for a new instance; marker written atomically after success; tests for tail, absent replica, failed restore. First labelling follows bindings (Task 6) so it moves nothing. |
+| 2 | P1 | Floor misses hub, writers and later boxes | Accepted with Paul's ruling "gate and alert" (spec rule 8): the gate covers every deployment box and the console; a below-floor box in a labelled fleet pauses relabelling and alerts. Fail-closed region encoding was offered and declined. |
+| 3 | P1 | Detach revokes before drain | Accepted: two-step drain (spec rule 5); draining boxes keep fleet access; detach refused until drained and empty (Task 6). |
+| 4 | P1 | Freshness gate blocks lost-box failover | Accepted: activation (`labelActive`) separated from destination choice (`chooseDestination`), which needs only one eligible survivor (Tasks 2, 6). |
+| 5 | P1 | `fleetChannelFor` falls back past the label | Accepted: `authoritative` parameter; labelled rows never fall back (Task 5). |
+| 6 | P1 | Sidecars unimplemented; worker shutdown unproven | Sidecars: cut (spec rule 10); fleets with sidecars are not labelled and new sidecars are refused on multi-box fleets (Task 2). Workers: Task 3 names `StopRetired`'s worker path and adds a test if none covers it. |
+| 7 | P1 | Old-label-only CAS can label across fleets | Accepted: `FleetBoxExpect{Region, Label, CreatedAt}` checked inside every retry (Task 1); race tests in Tasks 1 and 6. |
+| 8 | P2 | Unconditional `FleetBox` compare rewrites forever | Accepted: compare `FleetLabel`, and `FleetBox` only when labelled; write-counter test (Task 5). |
+| 9 | P2 | Task 7 harness needs extensions | Accepted: shared bucket, per-box lease identity seam, short TTL, injected clock, partition (Task 7). Declined: disk-backed test roots for activator/host e2e; they need `/tmp/k` for the Unix socket path limit (memory "Gate tmp exec wrapper"). |
+| 10 | P2 | Request budgets and counting tests | Accepted: budgets in Global Constraints; counting tests in Tasks 2 and 6; one inventory per pass; incomplete listings write nothing. |
+| 11 | P2 | Census name table and selected inventory | Accepted: Task 1 Step 4; Task 8 Step 1 adds the new columns. |
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md
new file mode 100644
index 000000000..3596549be
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md
@@ -0,0 +1,115 @@
+Reviewed round 1 of 3 at `1ea7e8194e208da19c7b53eba34deafcd1457d4b`. No files changed, subagents spawned, or tests run.
+
+1. **P1 — Task 4: Purging on a missing or changed marker can destroy the only surviving writes.**
+
+ **Evidence:** The plan requires deletion before restore, including when no marker exists (`docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md:138`, `:147`). `reconcileSeedMarker` instead preserves an unmarked database (`internal/activator/seedplace.go:231–244`). A failed final replication can still release the lease (`internal/lease/lease.go:549–574`), and an absent replica becomes a fresh boot (`internal/activator/backend_exec.go:916–969`).
+
+ **Failure scenario:** An existing instance has a local database containing an unreplicated tail. The initial labelling pass assigns it to that same box. Its next wake finds no `.assigned` marker, deletes the database and WAL, and restores an older replica—or boots empty if none exists. An assignment mismatch establishes that the copy must not serve; it does not establish that its bytes are disposable.
+
+ **Fix:** Preserve the displaced database and replication artifacts in quarantine before restoring into a separate target. Define recovery/refusal when the replica is absent or unreadable. Specify marker establishment for a genuinely fresh first boot as well as a successful restore. Test an unreplicated tail, absent replica, failed restore, and interrupted marker publication.
+
+ **Fault family:** Assignment changes must prevent stale serving without destroying unrecovered data.
+
+2. **P1 — Tasks 1, 2 and 6: The version floor does not cover all readers and writers, or remain enforced after activation.**
+
+ **Evidence:** The gate checks active fleet boxes only (plan `:16`, `:76`), although the plan acknowledges that older console and platform-box writers drop the fields (`:58`). Record mutations decode and marshal the typed record (`internal/provision/provision.go:1093–1139`). The existing hub binding writer has no label guard (`internal/registry/forward.go:35–42`). Fleet authentication admits every active registration without a version condition (`internal/registry/fleets.go:625–636`).
+
+ **Failure scenario:** Both fleet boxes upgrade, so the new console begins labelling, while the hub still runs its older binary. The hub ignores the assignment and continues applying bindings. An older record writer can also erase the assignment. Separately, adding or downgrading a box after labelling leaves existing labelled records visible to a binary that mints every fleet record and can reuse its stale local database after acquiring the lease.
+
+ **Fix:** Specify an activation barrier covering the console, hub and every record-writing binary. Preserve that barrier through subsequent box admission and downgrade paths. Add mixed-version tests for an older hub, an older record writer, and an older box introduced after labels already exist.
+
+ **Fault family:** Mixed-version preservation and enforcement of assignment authority.
+
+3. **P1 — Task 6: Detach revokes access before the old box has drained.**
+
+ **Evidence:** The plan calls `relabelOff` immediately before `SetFleetBoxStatus` (plan `:205`). Both detach doors currently perform that status write (`internal/console/fleets.go:569`, `:1479`). Detached boxes disappear from the authentication map (`internal/registry/fleets.go:636`); reload closes their channels (`internal/edge/tunnel.go:314–322`), and the store API refuses their subsequent reads (`internal/edge/storedoor.go:111–126`). Fleet boxes can obtain deployment records through this API (`internal/host/agent.go:75–85`).
+
+ **Failure scenario:** The hub reloads the detach before the old box reads its relabelled records. That box can no longer observe the change that should retire its rows. If its data-bucket access still works, it can keep renewing the lease and block the destination indefinitely. Relabelling alone does not satisfy the spec’s drain requirement.
+
+ **Fix:** Preflight destinations for all affected records, prevent new assignments to the draining box, and retain its control access until stopping, final replication and lease release are confirmed. Define the unavailable-box completion path separately. Test both detach doors with a live writer whose next record read is delayed until after the detach request.
+
+ **Fault family:** Drain completion must precede credential revocation.
+
+4. **P1 — Tasks 2 and 6: The chooser’s freshness requirement prevents the specified lost-box failover.**
+
+ **Evidence:** `fleetLabelReady` requires two or more active boxes, “every one fresh” (plan `:76`). Lost-box migration uses `chooseFleetBox(..., exclude)` (`:205`), while its required test leaves `pi-1` active but silent for 21 minutes (`:196`). Freshness is explicitly determined from heartbeat age (`internal/status/fleet.go:138–139`).
+
+ **Failure scenario:** In a two-box labelled fleet, `pi-1` becomes lost. The fleet fails the chooser’s readiness gate precisely when the worker needs to move its records to `pi-2`. Excluding `pi-1` before applying the same two-box requirement also fails: only one candidate remains.
+
+ **Fix:** Separate initial activation eligibility from destination eligibility for an already-labelled fleet. A lost or draining source must not prevent selection of a compatible, fresh survivor. Keep the lease acquisition as the final writer exclusion. Test this distinction directly, including one surviving destination.
+
+ **Fault family:** Failover eligibility must remain satisfiable when the source is unavailable.
+
+5. **P1 — Task 5: Keeping `fleetChannelFor` unchanged contradicts the required labelled-route behavior.**
+
+ **Evidence:** The plan says the fallback stays and a disconnected assigned box produces 503 (`:175`). The actual function falls through from an unavailable named box to the first connected fleet box (`internal/edge/edge.go:3223–3232`). Its signature receives no indication that the label is authoritative rather than a binding.
+
+ **Failure scenario:** A forward row names `pi-2`; only `pi-1` is connected. The hub sends the request to `pi-1`, which no longer mints that host. The planned `TestLabelledForwardDoesNotFallBack` cannot pass with the prescribed implementation.
+
+ **Fix:** Carry the authoritative-label distinction into proxy selection. For labelled rows, an unavailable assigned channel must return `errFleetDark`; retain fallback for unlabelled rows. Exercise the test with another box connected.
+
+ **Fault family:** Traffic must follow the authoritative assignment.
+
+6. **P1 — Tasks 1–3 and 6: The proposed record interfaces do not implement sidecar placement, and row deletion does not establish worker shutdown.**
+
+ **Evidence:** Task 1 adds fields and a setter only for `provision.Record` (plan `:43`), while sidecars use a separate `SidecarRecord` (`internal/provision/sidecar.go:71–87`) and `sidecars/<name>.json` keys (`:125–129`). The sidecar create door constructs that separate type (`internal/console/apisidecars.go:305–318`). Task 2’s listing reads instance records (`internal/provision/lifetime_judge.go:165–177`). Task 3 claims removal stops the instance through `RetireExcept` (plan `:118`), but that method explicitly skips workers (`internal/activator/activator.go:5642–5652`).
+
+ **Failure scenario:** Implementing the stated interfaces leaves sidecars unlabelled and absent from load counting and evacuation. Passing their records to `ownsRecord(Record)` does not compile. Even after adding their fields, deleting a sidecar row does not prove that its running worker released the lease.
+
+ **Fix:** Specify sidecar fields, conditional mutation, complete listing, assignment convergence and inclusion in every placement/drain calculation. Name and verify the worker shutdown path. Add an always-on sidecar migration test that proves the old process stops and the destination acquires its lease.
+
+ **Fault family:** Sidecar execution and lifetime must follow the same assignment authority as instances.
+
+7. **P1 — Tasks 1 and 6: Comparing only the old label permits a stale decision to assign a record in another fleet.**
+
+ **Evidence:** `SetRecordFleetBox` conditions only on `wantLabel` (plan `:43`). `SetRecordRegion` clears labels on a placement change (`:49`). Placement uses account/app locks (`internal/console/fleets.go:760–761`) and updates records through `SetRecordRegion` (`:859`); the new worker uses a separate fleet lock (plan `:205`). The update scaffold rereads the latest record and applies its mutation (`internal/provision/provision.go:1093–1139`).
+
+ **Failure scenario:** The worker reads an unlabelled instance in `fleet/pi`. A concurrent placement moves it to `fleet/rho`, still with an empty label. The worker’s `wantLabel == ""` succeeds and assigns `pi-1` inside `fleet/rho`. If rho has no such box, no box mints the instance.
+
+ **Fix:** Guard the mutation with the expected fleet/region and record lifetime, plus the expected assignment pair where present. Revalidate these conditions on every CAS retry. Add a race test that changes placement between listing and assignment.
+
+ **Fault family:** A placement decision must apply only to the record state it examined.
+
+8. **P2 — Task 5: Comparing `FleetBox` unconditionally prevents quiet reconciliation of unlabelled rows.**
+
+ **Evidence:** The plan requires `forwardCurrent` to compare `FleetBox` while preserving binding-owned values for unlabelled records (`:166`, `:175`). Existing `PutForward` preserves the stored binding when the region is unchanged (`internal/registry/forward.go:269`).
+
+ **Failure scenario:** An unlabelled record produces an empty desired `FleetBox`, while its stored row has a binding. Every pass detects a difference; `PutForward` preserves that difference, so every subsequent pass writes again.
+
+ **Fix:** Compare the declared label separately, and compare `FleetBox` against it only when an authoritative label exists. Test repeated reconciliation of an unlabelled, bound row with a write counter.
+
+ **Fault family:** Reconciliation must converge to a stable no-write state.
+
+9. **P2 — Task 7: The proposed end-to-end recipe needs explicit harness extensions.**
+
+ **Evidence:** `newE2EWorld` constructs two regions and two data buckets, not two boxes sharing one fleet bucket (`internal/host/movesoffline_e2e_test.go:225–229`, `:327–349`). Its clock setter changes only `offWorld.now` (`:437–440`). Lease acquisition and expiry use wall time (`internal/lease/lease.go:191–206`; `internal/lease/legacytake.go:65`), and lease identity is process-global (`internal/lease/self.go:11–24`). The fixture documents a fake activator wake backend (`internal/host/movesoffline_e2e_test.go:59–62`).
+
+ **Failure scenario:** Advancing the fixture clock does not expire the real lease. Two in-process backends do not automatically acquire distinct box identities, and reusing the fixture does not itself exercise two real writers.
+
+ **Fix:** Specify a fleet-specific fixture with a shared data bucket, real wake backends, controlled per-box identity, an accessible relabel-pass/clock seam, and deterministic lease expiry. Include a partitioned source that continues renewing, not only a stopped agent. Replace the plan’s `/tmp/k` test directories with disk-backed scratch paths.
+
+ **Fault family:** Test evidence must exercise the production ownership and restore mechanisms.
+
+10. **P2 — Tasks 2 and 6: The request budget and counting tests are missing.**
+
+ **Evidence:** The spec requires numerical request budgets and store-call tests (`docs/superpowers/specs/2026-10-28-managed-fleets-design.md:437–446`). The plan specifies only a five-minute interval (`:20`). Load calculation walks records (`:89`); `ListRecordsCompleteJudged` lists each app’s prefix and observes each record (`internal/provision/lifetime_judge.go:172–194`).
+
+ **Failure scenario:** Recomputing fleet load for every assignment repeats the full walk, making initial labelling or evacuation quadratic in record count. Steady-state scans also have an unspecified cost.
+
+ **Fix:** State LIST/GET/PUT budgets for idle passes, creates, initial labelling and evacuation. Read one complete inventory per fleet pass, update its load counts after successful writes, and assert call counts. Treat truncated or skipped records as incomplete evidence for detach.
+
+ **Fault family:** Placement work must have bounded store traffic and complete drain evidence.
+
+11. **P2 — Tasks 1 and 8: The record-write census does not recognize the proposed setter automatically.**
+
+ **Evidence:** The plan expects the census to name `SetRecordFleetBox` and proposes an overlay (plan `:63`). Typed writers are recognized through an explicit name table that lacks this setter (`internal/provision/plan9_b8_census_test.go:52–76`). The test explicitly selects `fleetPublicRoutesWriteCensusInventory()` (`:369`).
+
+ **Failure scenario:** A setter implemented only through `updateRecord` is not automatically classified as the new typed API. Its callers can escape that recognition, and an overlay function added beside the existing inventory is unused unless the test selects it.
+
+ **Fix:** Register the new instance and sidecar setter names, extend the census rejection witnesses, select the new overlay, and inventory subsequent callers. Include both route columns in the root census schema review; retain the required independent reviewer approval.
+
+ **Fault family:** Census coverage must include every assignment-writing authority.
+
+P3: None.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1B-PLAN.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1B-PLAN.md
index 79c8458f7..d624e2332 100644
--- a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1B-PLAN.md
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1B-PLAN.md
@@ -1,4 +1,4 @@
-# Review brief: managed fleets 1b plan, round 1 of 3
+# Review brief: managed fleets 1b plan, round 2 of 3
Repo carlos/platform, branch `design-managed-fleets-457`, tip: the commit that adds this brief.
Under review: `docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md`.
@@ -8,7 +8,7 @@ You are an independent reviewer. Read the plan, the spec section and the code it
## Fixed: do not re-argue
-- Paul's rulings: rules 1-7 and rule 6's mechanism (assignment time on the record, a marker beside the local copy; not the lock's last holder). Rules 8-10 are the author's calls; challenge them only with a failure scenario.
+- Paul's rulings: rules 1-7, rule 6's mechanism (assignment time on the record, a marker beside the local copy; not the lock's last holder) and rule 8 "gate and alert" (the risk that a below-floor box added after labelling can serve its own stale copy until an operator acts is ACCEPTED; do not re-raise it, only report a mechanism that fails to gate or alert). Rules 5 (two-step drain) and 10 (sidecars cut to single-box fleets) are the author's calls; challenge them only with a failure scenario.
- Region HA, claims and managed provisioning (phase 2) are out of scope.
## What to check
@@ -22,6 +22,10 @@ You are an independent reviewer. Read the plan, the spec section and the code it
7. Are the tasks' tests sufficient to catch the failures above, and is Task 7 buildable on `newE2EWorld`?
8. Request budget and census implications the plan misses.
+## Round 2
+
+Earlier round: `docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md`. The plan's "Round 1 dispositions" table maps each finding. First give one line per round-1 P1 and P2: resolved, partly, or not. Carry every unresolved or partly resolved finding forward at its current severity, then add new findings. The verdict covers everything outstanding.
+
## Severity
- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks the plan.
diff --git a/docs/superpowers/specs/2026-10-28-managed-fleets-design.md b/docs/superpowers/specs/2026-10-28-managed-fleets-design.md
index 6a6321d48..abb7401ab 100644
--- a/docs/superpowers/specs/2026-10-28-managed-fleets-design.md
+++ b/docs/superpowers/specs/2026-10-28-managed-fleets-design.md
@@ -183,16 +183,26 @@ The rule (my calls, approved by Paul 2026-10-30):
writer: a box that was only partitioned keeps its lease until it
lapses, and the new box waits for it. When the old box returns, its
reconcile no longer admits those records and it drops them.
-5. **Removal drains.** Removing a box relabels its records to the other
- ready boxes first; the old box hibernates them, releasing their
- leases, and the new box wakes them from the fleet bucket. Removal is
- still refused when no other box can take them (Phase 2 §Removal).
+5. **Removal drains, in two steps (my call, after plan review R1).**
+ `carlos fleets drain <fleet> <box>` marks the box draining (no new
+ assignments; it keeps its fleet access) and relabels all its records
+ to other ready boxes, or refuses, naming the apps, when any record has
+ nowhere to go. The old box drops the rows, stops the instances and
+ releases their leases; the new box wakes them from the fleet bucket.
+ Detaching a box is refused while it still reports instances or any
+ record names it. Detaching first would revoke the box's access before
+ it had seen the relabel and released its leases.
6. **No stale local copy (#470), by assignment time (Paul, 2026-10-30,
option 1).** The record carries the time it was assigned to its box,
beside the label. A box notes that time next to its local copy. When
- it mints a labelled record whose assignment time differs from its
- note, it discards the local copy before any wake and records the new
- time, so the first wake restores from the fleet bucket. After A, then
+ it wakes a labelled record whose assignment time differs from its
+ note (or has no note), it sets the local copy aside, never deleting
+ it, and restores from the fleet bucket, then records the new time. If
+ there is nothing to restore from, it refuses to start the instance
+ and says where the set-aside copy is, rather than booting empty. When
+ existing records are first labelled, each is labelled to the box
+ already serving it, so nothing moves; that box's copy is set aside
+ once and the same data restored. After A, then
B, then A, box A sees a newer assignment and restores. The check is
local: no lock change, no extra bucket request, and ordinary wakes on
an unchanged assignment keep their warm copy. (This replaces the
@@ -203,15 +213,23 @@ The rule (my calls, approved by Paul 2026-10-30):
7. **Rootfs admission follows the box.** A rootfs placement is admitted
when the chosen box is rootfs-ready, replacing "one fresh box ready
and every box on the floor" (`internal/console/rootfs.go:160-212`).
-8. **Mixed versions (my call).** A box binary that predates the label
- ignores it and mints every fleet record. So the console labels a
- fleet's records only when every active box in the fleet reports the
- release that carries this rule or later; until then the fleet keeps
- today's behaviour, unlabelled.
+8. **Mixed versions: gate and alert (Paul, 2026-10-30).** A box binary
+ that predates the label ignores it and mints every fleet record. So
+ the console starts labelling a fleet only when every box in the
+ deployment (platform and fleet, the hub included) and the console run
+ the release that carries this rule or later; until then the fleet
+ keeps today's behaviour, unlabelled. If a box below that release later
+ appears in a labelled fleet (a rollback, a hand-built box), the
+ console stops relabelling that fleet and raises an alert. The lease
+ still prevents two writers; the risk accepted is that the old box can
+ serve its own stale copy until an operator acts.
9. **The removal phase checks the label too (my call).** A row whose
record now names another box is removed, not kept on region alone
(`internal/provision/reconcile.go` scan and removal phase).
-10. **Sidecars (my call)** follow the same rules as instances.
+10. **Sidecars stay on single-box fleets for now (my call, after plan
+ review R1).** Sidecar records are a separate type with their own
+ lifecycle. A fleet with sidecars is not labelled, and creating a
+ sidecar on a fleet with two or more active boxes is refused.
Tests that prove it: a real two-box fleet test (activator, lease and
restore, not the modelled lease of `TestTwoBoxFleetEndToEnd`) covering