carlos / platform Public

docs: plan 2a review round 2 fixes and Paul's joining-box ruling

A managed box runs nothing until the console writes its ready.json
(Paul, stopping rule 2). HKDF enrolment key off the seal key file,
seal-key loss recovery, conditional drain clear, request_id rules,
failed boxes lose tunnel auth.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 036844dbf0db5782d127dfd68569a9cc0a42ee9c parent 4e37a15
1 file changed, +107 −61
  • docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md +107 −61
diff --git a/docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md b/docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md
index bd588864a..8752b2650 100644
--- a/docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md
+++ b/docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md
@@ -8,7 +8,7 @@
**Tech Stack:** Go, SQLite through the existing console store, registry migrations, conditional release-store writes, console API, `carlos` CLI, deterministic compute/storage fakes.
-**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 2, §§5–6 and §§8–9. Controller decisions: `/home/paulca/.cache/managed-fleets-2-notes/decisions.md`; recon: `/home/paulca/.cache/managed-fleets-2-notes/recon.md`. Source checked at `b7802fd840cb3485e104d00a9a3e614b62bd15a2`. The controller's split, Phase 2 addendum and fix1-brief.md round-1 rulings govern this plan; the fix brief supersedes conflicting earlier decisions. The 1b ledger governs inherited placement and drain behavior.
+**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 2, §§5–6 and §§8–9. Controller decisions: `/home/paulca/.cache/managed-fleets-2-notes/decisions.md`; recon: `/home/paulca/.cache/managed-fleets-2-notes/recon.md`. Source checked at `b7802fd840cb3485e104d00a9a3e614b62bd15a2`. The controller’s split, Phase 2 addendum, fix1-brief.md round-1 rulings, fix2-brief.md round-2 rulings and fix3-brief.md (Paul’s joining invariant) govern this plan; the later brief supersedes conflicting earlier decisions. The 1b ledger governs inherited placement and drain behavior.
## Global Constraints
@@ -16,7 +16,8 @@
- No tenant names; neutral examples (shop, example.com, production).
- Member-facing strings go through copy review before merge; placeholder copy is marked COPY in the plan.
- Provider-neutral core: no AWS SDK import outside adapters; an import test enforces it.
-- Request budget (spec §6): no new per-box store polling; worker idle = zero calls.
+- Request budget (spec §6): no new steady-state per-box store polling; worker idle = zero calls.
+- A managed box runs no workloads until the console writes its ready.json after all six checks pass; 2a supplies the signal and fake proof, 2b must enforce the box-side joining marker before switch-on.
- Verification budget: mutation checks only on refusal, security, termination and lifecycle paths, at most ~10 per
task, targeted -run; local runs once with -count=1 plus one -race; touched packages only (CI runs the full suite);
activator/socket tests need TMPDIR=/tmp/k.XXXX (short path).
@@ -35,7 +36,7 @@
- Copy review applies during implementation to CLI help, errors, progress and docs. This implementation plan contains contracts and COPY markers, not approved member copy.
- Each task's failing run and passing run are the TDD pair. Run the touched-package race check once after integration; do not repeat full suites locally between tasks.
- Review only security, cache, termination, storage and authority tasks individually; other tasks receive the whole-branch review. Follow the existing three-round budget and stop at the first round without P1.
-- Round 1 findings and controller dispositions are recorded below. Carry that round history into subsequent review briefs; a filename change or a later task does not reset it.
+- Rounds 1–2 findings and controller dispositions are recorded below. Carry that round history into subsequent review briefs; a filename change or a later task does not reset it.
## Review Focus
@@ -45,7 +46,7 @@
4. An operator changes image, subnet, size mapping or ceiling during an operation; retries keep the original launch parameters and new reservations use the new config; existing request IDs always return their original op. Tasks 3–4 and 6: `TestManagedFrozenLaunchAcrossConfigChange`.
5. A fresh heartbeat still names the old release during a stable rollout; version stays pending until it equals the current verified stable pointer. Task 8: `TestManagedReadinessTracksStableRoll`.
-6. An enrolled box cannot take placements until ready; cleanup requires LabelledAt==0. Tasks 7–8: `TestManagedJoiningPlacement`, `TestManagedFailedEnrolledCleanup`.
+6. A joining box owns no records and starts no instances until console-written ready.json; the drain blocks labelled placements only. Tasks 6–8 and 10: `TestManagedJoiningPlacement`, `TestManagedFailedEnrolledCleanup`.
7. Restart before dispatch reconstructs identical UserData; request retries after completion return the original batch. Tasks 4, 6, 9: `TestManagedRequestID`, `TestManagedRestartBeforeDispatch`.
8. Preparation deadlines, identity-mismatch hourly cleanup and closed-op add admission are durable. Tasks 5–6: `TestManagedPreparationDeadline`, `TestManagedIdentityCleanup`, `TestManagedPartialFailure`.
9. Atomic name claim precedes reservation; show stays SQL-only during open work. Tasks 5, 9–10: `TestManagedPrepareNameRace`, `TestManagedFollowStoreBudget`.
@@ -101,7 +102,7 @@ BYO reports the actual active/detached status and observed version; checks are e
During an open managed op, render persisted SQL states/checks only; never load heartbeat snapshots for show/follow.
BYO and settled fleets retain today's request-local heartbeat reads. Task 9 adds following an open operation.
The early registry name claim makes preparation visible: show the owned op's preparation failure; foreign accounts still get identical 404.
-Render enrolled-not-ready as joining, even though its registry row carries a placement-blocking drain mark.
+Render enrolled-not-ready as joining, even though its registry row carries a labelled-placement-blocking drain mark.
**Census/review:** Root CLI source changes require a root-read census card and independent envelope review. Console-only view changes do not create a root package; account access still belongs in security review.
@@ -178,8 +179,9 @@ type Provisioner interface {
`State` values: `pending`, `running`, `stopping`, `stopped`, `shutting-down`, `terminated`.
In `fleetstore`: `type Credentials []byte`, `type FleetStorage struct { Bucket, Region string }`.
`type Provisioner interface { EnsureFleetStorage(ctx context.Context, fleet, region string) (FleetStorage, error); FleetCredentials(ctx context.Context, fleet string) (Credentials, error); RotateFleetCredentials(ctx context.Context, fleet string) (Credentials, error) }`.
-FleetCredentials returns the current fleet credential, creating it once if absent; retries return the same bytes.
-RotateFleetCredentials mints a new credential and reaps all but the newest two.
+FleetCredentials does not promise recoverable secret bytes; console delivery uses its sealed copy.
+RotateFleetCredentials mints a new key (secret revealed once) and reaps all but the newest two.
+If no sealed copy exists, the console mints through RotateFleetCredentials, seals, persists, then uses it.
Empty credentials are valid for a future profile adapter; no profile or IAM type enters either interface.
Both fake constructors are `NewFake() *Fake`; methods implement the respective interface.
Compute fake faults are configured before a test starts; all runtime state/counters use its mutex.
@@ -201,8 +203,9 @@ TestFakeIdentityTerminate: change any Identity field => ErrIdentityMismatch, sta
TestFakeNthCapacityFailure: third launch rejected, first two retained, no third instance.
TestFleetStorageFake: same fleet/region => same bucket; distinct fleets isolated;
opaque credentials not present in storage metadata; empty credentials supported.
-TestFleetStorageFakeRotation: repeated FleetCredentials and many enrolments use one current key;
- rotations return new keys, retain at most the newest two live keys per fleet, and never affect another fleet.
+TestFleetStorageFakeRotation: each minted secret is revealed once; FleetCredentials cannot recover it;
+ rotations retain at most the newest two live keys per fleet and never affect another fleet;
+ many enrolments reuse the console-sealed current key without provider minting.
TestManagedCoreImports: direct imports in compute and fleetstore (all files, tests included) and in
internal/console/managed*.go contain no AWS SDK (github.com/aws/...); a new managed*.go file is covered automatically.
```
@@ -284,13 +287,13 @@ Document both system subcommands in this task's merge.
**Files:**
- Create: `internal/console/managedstore.go`, `managedstore_test.go`.
-- Modify: `internal/console/store.go`, `internal/registry/fleets.go`, `internal/registry/fleets_test.go`.
+- Modify: `internal/console/{store.go,alertseal.go}`, `internal/registry/fleets.go`, `internal/registry/fleets_test.go`.
- Inspect/update registry remote serialization consumers and schema census rows for the added field.
- Checked patterns: `billingstore.go:218`, `billingops.go:201`; console store connection setup at `store.go:99`.
**Interfaces (new):**
- `type managedOp struct { ID, RequestID, Account, Fleet, Kind, State, CreatedBy, Error string; Requested int; CreatedAt, UpdatedAt time.Time }`.
-- `type managedBox struct { Fleet, Label, OpID, Account, Region, Size, ClientToken, CloudID, State, LastError, EnrolHash string; Launch compute.LaunchSpec; Checks map[string]managedCheck; EnrolExpires, CreatedAt, UpdatedAt time.Time; ReadyDrainPending bool; LaunchStartedAt, TerminateSentAt, NextCleanupAt, LastHeartbeatAt time.Time; ConfigGeneration uint64; Storage fleetstore.FleetStorage }`.
+- `type managedBox struct { Fleet, Label, OpID, Account, Region, Size, ClientToken, CloudID, State, LastError, EnrolHash string; Launch compute.LaunchSpec; Checks map[string]managedCheck; EnrolExpires, CreatedAt, UpdatedAt time.Time; ReadyDrainPending bool; LaunchStartedAt, TerminateAttemptedAt, TerminateSentAt, NextCleanupAt, LastHeartbeatAt time.Time; EnrolDrainStart int64; ConfigGeneration uint64; Storage fleetstore.FleetStorage }`.
- `type managedRequest struct { RequestID, Account, Fleet, Kind, Region, Size, CreatedBy string; Boxes int }`.
- `func (s *Store) ReserveManaged(ctx context.Context, req managedRequest, cfg managedConfig, now time.Time, enrolHash func(clientToken string) (string, error)) (managedOp, []managedBox, bool, error)`; bool means returned existing op. Check request ID and open op before validating/resolving cfg; resolve per allocated label inside this transaction.
- `func (s *Store) ManagedWork(ctx context.Context) ([]managedOp, []managedBox, error)`.
@@ -299,9 +302,9 @@ Document both system subcommands in this task's merge.
- `func (s *Store) FinishManagedOp(ctx context.Context, id string, now time.Time) error`.
- Add `Managed bool` to `registry.Fleet`; existing `CreateFleet(f Fleet) (created bool, err error)`, `GetFleet(name string) (*Fleet, error)` and `ListFleets() ([]Fleet, error)` keep their signatures.
-Create the controller's tables plus `managed_ops.request_id TEXT` with UNIQUE(account, request_id), persisted requested region/size and `preparation_started_at`; include the partial unique index on `managed_ops(fleet) WHERE state='open'`.
+Create the controller's tables plus `managed_ops.request_id TEXT NOT NULL` with UNIQUE(account, request_id), persisted requested region/size and `preparation_started_at`; include the partial unique index on `managed_ops(fleet) WHERE state='open'`.
`launch` contains the frozen LaunchSpec with `UserData` empty; no enrolment plaintext or unsealed credentials enter SQL. Store the current fleet credential in a fleet-scoped sealed BLOB (Task 5), never in launch metadata.
-Persist additional immutable launch timing metadata in that JSON envelope: `launch_started_at` and `config_generation`; persist `ready_drain_pending` for crash recovery, `terminate_sent_at` bound to the exact cloud ID, `next_cleanup_at` and `last_heartbeat_at` as well; leave the public compute type unchanged.
+Persist additional immutable launch timing metadata in that JSON envelope: `launch_started_at` and `config_generation`; persist `ready_drain_pending` for recovery of ready-object publication and drain clear, plus immutable `ready_at` and `ready_object_written`, `enrol_drain_start` (Unix nanoseconds), `terminate_attempted_at` and `terminate_sent_at` bound to the exact cloud ID, `next_cleanup_at` and `last_heartbeat_at` as well; leave the public compute type unchanged.
`managed_ops.state` stays `open|done|failed`; `done-with-failures` is the response's derived outcome, not a fourth SQL state.
`managed_boxes` states are exactly `reserved|launching|booting|enrolled|ready|failed|terminating|terminated`.
Keep first error separately from subsequent cleanup detail in the structured checks/error rendering so cleanup does not erase cause.
@@ -311,7 +314,8 @@ Count every row except `terminated`, including ready, failed and terminating, ac
A count overflow or invalid request rolls back the entire batch; never reserve a prefix of N.
Select new `box-N` labels monotonically from all retained reservations and existing registry labels; never recycle a terminated label in 2a.
Client token is `hex(sha256(op_id+"/"+label))[:32]`, persisted with identity before Launch.
-First look up (account, request_id): identical parameters return that original op in any state; changed parameters conflict. Then compare an open operation's account/kind/count/region/size before resolving new config: identical request joins its frozen rows; different parameters return 409 and the owned open op ID.
+Require non-empty request_id matching `^[A-Za-z0-9_-]{22,64}$` on managed create/add; otherwise return 400 before any claim or reservation.
+After authentication and request validation, first look up (account, request_id), before name claim or name-taken checks: identical parameters return that original op in any state; changed parameters conflict. Then compare an open operation's account/kind/count/region/size before resolving new config: identical request joins its frozen rows; different parameters return 409 and the owned open op ID.
Never return another account's operation ID on a global fleet-name collision.
A new invocation uses a new request ID: after completion create refuses an existing nonempty fleet; add starts a new batch.
Resolve each newly allocated box-N with subnet = subnets[N % len(subnets)]; freeze the result in its row. Joins work with a removed size or disabled feature.
@@ -330,7 +334,8 @@ TestManagedJoin: concurrent identical requests => same op, same N rows;
different count/size/kind => 409; foreign account gets no op details.
TestManagedFrozenLaunchAcrossConfigChange: mutate original config slices/maps;
persisted launch bytes unchanged; ClientToken stable across DB reopen.
-TestManagedRequestID: create and add repeat after done/failed => original op, no new reservation;
+TestManagedRequestID: empty, malformed, short or overlong ID => 400, no claim/reservation;
+ create and add repeat after done/failed => original op, no new reservation;
changed payload with the same account/request ID conflicts; another account cannot read it.
TestManagedJoinRemovedConfig: open op joins after size removal/disable; new request is refused.
TestManagedSubnetAllocation: allocated box numbers choose subnets[N % len(subnets)]; retries preserve bytes.
@@ -343,9 +348,10 @@ TestManagedTransitionCAS: stale prior state cannot overwrite ready/cloud identit
Use the billing migration style, not its subscription lock as the quota lock.
Validate `Boxes > 0` before arithmetic; compare against remaining capacity without overflowing an int.
Within the transaction, generate random op IDs and stable client tokens, then persist only SHA-256 of the derived enrolment token.
-Derive token = hex(HMAC-SHA256(consoleSecret, "managed-enrol/"+client_token)).
-Obtain consoleSecret from the stable console signing key as `dbHandleSecret` does (`apidbclaim.go:56`, wired in `server.go:1875`); use a separate managed-enrol key domain.
-Do not keep a pending-delivery map or remint on restart. The stable secret and frozen client token reconstruct identical UserData.
+Derive a 32-byte enrolment HMAC key with HKDF-SHA256, input keying material = the external 0600 connector seal key, nil salt, info/label = "managed-enrol".
+Reuse the key file loaded by `openConnectorSeal` (`internal/console/alertseal.go:39,76` at b7802fd8); factor its validated load/create path to supply the same bytes to HKDF and AES-GCM without storing them in SQL. Do not use dbHandleSecret or keymail-sign.
+Derive token = hex(HMAC-SHA256(enrolKey, "managed-enrol/"+client_token)). Before every launch/relaunch, require sha256(derived token) == enrol_hash; mismatch fails the box with reason "enrolment key changed" and makes no Launch call.
+Do not keep a pending-delivery map or remint on restart. With the same external key and frozen client token, reconstruct identical UserData; key loss/replacement instead fails safely.
Make `UpsertFleet` preserve the managed discriminator on conflict; ordinary BYO writes cannot convert ownership or managed status.
- [ ] **Step 4: Repeat the targeted command; expect PASS.**
@@ -367,18 +373,20 @@ Make `UpsertFleet` preserve the managed discriminator on conflict; ordinary BYO
- New `func (s *Server) admitManagedHistory(ctx context.Context, f registry.Fleet, label string) error`; caller holds fleet lock; empty label means fleet/bucket admission only.
- New server config fields `ManagedCompute compute.Provisioner`, `ManagedStorage fleetstore.Provisioner`, `ManagedDeployment string`.
-For create, atomically claim the name first with `CreateFleet(registry.Fleet{Name: name, Managed: true, Account: account})`, then ReserveManaged.
+For create, authenticate/validate and look up request_id first (Task 4), returning the original op even when closed; only a new request may atomically claim the name with `CreateFleet(registry.Fleet{Name: name, Managed: true, Account: account})`, then ReserveManaged.
BYO create uses the atomic insert (`registry/fleets.go:253`), not lockFleet; do not claim a shared BYO mutex.
An existing empty managed row owned by the same account with no boxes/ops permits an identical create to resume after a crash. A foreign or BYO row gets normal name-taken refusal.
Serialize managed admission/empty-row cleanup under lockFleet. If quota/disabled admission refuses, delete only the just-created empty managed row after checking no ops and no boxes.
Add a conditional registry deletion method `DeleteEmptyManagedFleet(name, account string) (bool, error)`; preserve account/managed identity and refuse nonempty rows. Keep the console no-ops check under the same managed admission lock.
Prepare storage idempotently, persist its bucket/region, admit history, update the owned registry bucket and write/verify owner. No launch precedes successful preparation.
`hostsTargetRefusal` (`hostsused.go:197`) keeps an unexamined fleet from taking data while history is active.
-Add uses the existing bucket. Recheck provider output against the persisted bucket/region; refuse drift, never overwrite another owner.
+Add on a fleet whose preparation failed re-runs preparation before reserving new boxes, with a durably recorded start for that new attempt and the same 30-minute deadline; retries/restarts never reset that start. No reservation or launch precedes its success.
+Add uses the existing bucket when one was persisted; otherwise recover preparation to establish it. Recheck provider output against the persisted bucket/region; refuse drift, never overwrite another owner.
Persist preparation_started_at before the first provider call; at 30 minutes fail the op and its unlaunched reservations without launching. Proven never-dispatched reservations become terminated and release quota.
-Create the fleet credential once during preparation with FleetCredentials, seal and persist it before any enrolment.
-Reuse `openConnectorSeal`, `connectorSeal.Seal/Open` (`internal/console/alertseal.go:39,104,114`): AES-GCM, external 0600 key, ciphertext only in SQL. Missing/unreadable seal keys fail preparation or delivery safely.
-Retry storage/credential preparation idempotently after restart; do not mint per enrolment. No bucket deletion is attempted in 2a.
+If no sealed credential exists, call RotateFleetCredentials, seal and persist the one-time secret before use. Reuse the persisted copy on ordinary retries and enrolments.
+Reuse `openConnectorSeal`, `connectorSeal.Seal/Open` (`internal/console/alertseal.go:39,104,114`): AES-GCM, external 0600 key, ciphertext only in SQL. If created=true or Open fails for a fleet credential, call RotateFleetCredentials and reseal/persist before use; unreadable/invalid key files still refuse safely.
+A lost seal key also changes Task 4’s HKDF enrolment key: outstanding launches fail its hash comparison, never relaunch with changed UserData.
+A crash before sealing may require another rotation; the provider retains at most two live keys. No per-enrolment mint or bucket deletion in 2a.
On active history, CAS-union `fleet:<name>` into Examined and `bucket:<bucket>` into its FleetTargets.
For a nonempty label, also union `box:fleet/<fleet>/<label>` before its registry row becomes active.
@@ -403,7 +411,7 @@ TestManagedHistoryCASRace: another fleet/region admission wins first;
TestManagedHistoryModes: off => no write; closed/invalidated/unreadable => refusal;
local latched invalidation cannot be cleared by admission.
TestManagedBYOBoundary: BYO still hits fleetGrowthRefusal;
- BYO add/rotate/detach API and page doors refuse a managed fleet; drain/tag remain allowed.
+ BYO add/rotate/detach API and page doors refuse a managed fleet; tag remains allowed; member drain of a joining box returns 409 (COPY), ready-box drain remains allowed.
TestManagedPrepareNameRace: BYO and managed race same name => one owner;
no provider bucket prepared for a known foreign name; no owner overwrite;
crash after claim before reservation resumes for same owner; foreign owner refused;
@@ -411,15 +419,19 @@ TestManagedPrepareNameRace: BYO and managed race same name => one owner;
TestManagedPreparationDeadline: persisted start +30m => failed op, zero launches, visible owned show;
restart does not reset deadline; cross-account show still identical 404.
TestManagedFleetCredentials: preparation retries mint once; SQL contains only sealed bytes;
- restart opens same credential; missing/wrong seal key refuses; many boxes receive same current key.
+ restart opens same credential; many boxes receive same current key without minting.
+TestManagedSealKeyLost: created=true or fleet credential Open failure => rotate, reseal, persist before use;
+ at most two live keys; replacement seal key changes HKDF output, outstanding launch hash mismatch => no Launch.
+TestManagedAddAfterPreparationFailure: add re-runs preparation before reservation; persisted deadline survives restart;
+ timeout => no new boxes/launches; success => reserve against recovered bucket/owner.
```
-- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare|Preparation|FleetCredentials)' -count=1`; expect FAIL.**
+- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare|Preparation|FleetCredentials|SealKeyLost|AddAfterPreparationFailure)' -count=1`; expect FAIL.**
- [ ] **Step 3: Implement preparation and history admission.**
Keep existing fleet floor checks on managed creation; being born examined is not a release-floor bypass.
Use the provider only through `fleetstore.Provisioner`, and reapply history before a retry publishes missing registry state.
-Guard BYO add-box, rotate-token and detach-box at API and HTML actions with `Fleet.Managed`; keep drain/tag allowed until 2d supplies managed removal.
+Guard BYO add-box, rotate-token and detach-box at API and HTML actions with `Fleet.Managed`; keep tags and ready-box drains allowed; under lockFleet refuse member drain of joining boxes with 409 (COPY), before any registry mutation. Apply the same guard at API and HTML doors.
The managed path does not call `fleetGrowthRefusal`; it supplies the stronger first-contact admission in Task 7.
COPY: preparation/refusal errors, with safe machine codes and no raw provider response.
@@ -455,21 +467,22 @@ Set `enrol_expires=launch_started_at+30m`; use the same anchor for the 20-minute
Call Launch with the frozen spec and deterministically reconstructed enrolment token in transient UserData.
Any ambiguous error or restart in launching first calls Find with all four identity fields and frozen region.
One matching instance is adopted; multiple matches are an invariant failure with no extra Launch and no arbitrary termination choice.
-Retry Launch when Find returned a complete empty result; reconstruct the original complete request from durable state and the console secret; keep ClientToken and bytes unchanged.
+Retry Launch when Find returned a complete empty result; reconstruct the original complete request from durable state and the external HKDF key, checking the persisted enrol_hash before each launch/relaunch; keep ClientToken and bytes unchanged.
A definitively rejected launch records failed/terminated without a cloud instance; unclassified network errors do not establish absence.
Pending stays launching; running becomes booting; stopped/stopping/shutting-down are not successful or terminal observations.
A found cloud instance with mismatched identity/region is never adopted or terminated.
A restart before dispatch rebuilds byte-identical UserData, including the derived token, and retries with the same ClientToken; no remint or lost-transient uncertainty state.
Every provisioning state has a persisted deadline: reserved preparation uses 30 minutes; launching/booting/enrolled use 20 minutes from launch_started_at. Retries never reset either anchor.
-On failure persist cause before Terminate. An enrolled box must still have LabelledAt==0 under lockFleet; otherwise refuse automatic termination, record the invariant failure and retain quota.
-Transition to terminating and call `Terminate(..., want Identity)`. Persist terminate_sent_at for that exact cloud ID only after acceptance.
-Confirm termination by Find reporting terminated, or by later complete Find absence after persisted acceptance for that same ID. A successful Terminate response alone never frees quota.
+On failure persist cause before Terminate. Under lockFleet, revoke any enrolled box’s tunnel token with SetFleetBoxToken using a valid 64-lowercase-hex hash of a fresh discarded random token; keep its registry row for cleanup. Retry revocation after a crash/error before cleanup proceeds. Checked seam: `internal/registry/fleets.go:509,524` at b7802fd8 validates the hash and bumps rev. Automatic termination of a not-ready box rests on the joining invariant: without console-written ready.json it owns no records and runs no instances. LabelledAt is not a termination proof. Ready rows, including pending ready publication/drain recovery, never enter failed-provisioning cleanup.
+Transition to terminating and persist terminate_attempted_at bound to the exact cloud ID before calling `Terminate(..., want Identity)`. Persist terminate_sent_at only after acceptance.
+Confirm termination by Find reporting terminated, or NotFound/complete Find absence for that exact cloud ID after its persisted attempt, including a lost Terminate response. A successful Terminate response alone never frees quota.
Identity mismatch records a safe error, stops fast retries and schedules hourly retry with persisted next_cleanup_at; quota stays held and show reports the reason.
Failed/terminating cleanup uses hourly back-off after the op closes; each attempt is bounded and retains quota until termination is established. Cleanup has no forced quota-release deadline.
Ready boxes are never cleanup targets merely because a sibling failed.
-One finishing rule: close an op when every box is ready, terminated, or in cleanup (failed/terminating). All ready => done; some ready => done with failures; none ready => failed.
+One finishing rule: close an op when every box is ready with ready_drain_pending cleared, terminated, or in cleanup (failed/terminating). All ready => done; some ready => done with failures; none ready => failed.
A closed op no longer blocks add; unresolved cleanup still counts against quota and is discovered on restart. Detach only after established termination.
+Failure and cleanup never write ready.json. Delete any ready object idempotently after established termination and before detach (also required of 2d removal); retry deletion failures before detach. This avoids leaving an obsolete authorization object; deleting it does not stop an already-ready box.
**Census/review:** Launch and termination authority, worker registration, registry detach and timing need independent review. Include newly changed root command envelopes and record-write witnesses in the census proposal.
@@ -486,19 +499,23 @@ TestManagedDeadline: 19m59s pending, 20m failed cleanup; token expiry not extend
stopped and shutting-down never free quota; terminated observation does.
TestManagedIdentityCleanup: mismatched tags => no termination/detach, quota retained, visible error;
no fast retry; retry at one hour, including after restart.
-TestManagedAcceptedTerminateAbsent: persisted acceptance for exact ID then Find absent => terminated;
- absence without acceptance or for a different ID never releases quota.
-TestManagedFailedEnrolledCleanup: failed joining box has LabelledAt==0 and never held a placement;
- unexpected labelled mark refuses Terminate and retains quota.
+TestManagedAcceptedTerminateAbsent: persisted attempt for exact ID, lost Terminate response, then NotFound => terminated;
+ crash before dispatch resumes cleanup; absence without an attempt or for a different ID never releases quota.
+TestManagedFailedEnrolledCleanup: failed joining box never gets ready.json and runs no instances;
+ old tunnel token fails authentication after failure/restart; registry row retained with unusable hash;
+ cleanup uses the joining invariant, not LabelledAt; ready/pending-ready siblings never terminate;
+ termination precedes idempotent ready-object deletion and detach; deletion failure retries without detach.
TestManagedPartialFailure: ready siblings untouched; failed Nth launch reported;
op closes with ready/cleanup siblings; new add allowed subject to held quota; cleanup continues hourly.
+TestManagedEnrolKeyChanged: replace external key before first launch or relaunch => failed,
+ reason="enrolment key changed", no Launch call; unchanged key preserves UserData.
TestManagedRestartBeforeDispatch: crash after launching commit, before dispatch; reopen and relaunch
with identical UserData/ClientToken; exactly one physical instance, no lost token state.
TestManagedWorkerWakeAndStop: commit racing idle wakes; canceled worker exits;
registered worker covered by startup wiring test.
```
-- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./cmd/console -run 'TestManaged(Restart|Ambiguous|Frozen|Deadline|Identity|Partial|AcceptedTerminate|FailedEnrolled|Worker)' -count=1`; expect FAIL.**
+- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./cmd/console -run 'TestManaged(Restart|Ambiguous|Frozen|Deadline|Identity|Partial|AcceptedTerminate|FailedEnrolled|EnrolKeyChanged|Worker)' -count=1`; expect FAIL.**
- [ ] **Step 3: Implement the state machine and safe error projection.**
Use bounded per-call contexts and a fake clock; never sleep twenty minutes in tests.
@@ -519,16 +536,16 @@ COPY: states, deadline and recovery messages; all logs remain secret-free.
**Interfaces (new unless marked existing):**
- `type managedEnrolRequest struct { Token string; DataDirEmpty bool; DataDirEntries int }` with `token`, `data_dir_empty`, `data_dir_entries` JSON keys.
-- `type managedEnrolReply struct { Fleet, Label, TunnelURL, TunnelToken string; Credentials fleetstore.Credentials }` with snake-case JSON keys.
+- `type managedEnrolReply struct { Fleet, Label, TunnelURL, TunnelToken string; Credentials fleetstore.Credentials; Joining bool }` with snake-case JSON keys; `joining` is always true for managed enrolment in 2a.
- `func (s *Server) handleManagedEnrol(w http.ResponseWriter, r *http.Request)` at `POST /api/fleet/enrol`.
- `func (s *Server) enrolManagedBox(ctx context.Context, in managedEnrolRequest, now time.Time) (managedEnrolReply, error)`.
-- `func deriveManagedEnrolToken(consoleSecret []byte, clientToken string) (plaintext, hash string)`; Task 4 HMAC derivation, lowercase hex, SHA-256 of plaintext string.
+- `func deriveManagedEnrolToken(enrolKey []byte, clientToken string) (plaintext, hash string)`; Task 4 HMAC derivation, lowercase hex, SHA-256 of plaintext string.
- Existing `func mintFleetToken() (plaintext, hash string, err error)` is the ordinary tunnel-token issuer.
- Add durable `enrol_used_at INTEGER NOT NULL DEFAULT 0` to managed_boxes for single-use claim/recovery; no plaintext response column.
- Extend `managedBox` with `EnrolUsedAt time.Time`; include it in scan/CAS predicates, exclude from public views.
- Existing `SetFleetBoxDraining(fleet, label string, since int64) (int64, error)` (`registry/fleets.go:609`); no equivalent clear method exists.
- New `AddManagedFleetBox(b FleetBox, drainingSince int64) error`: registry transaction inserts the active row already drained, sharing SetFleetBoxDraining validation/revision semantics; add remote dispatch.
-- New `ClearFleetBoxDraining(fleet, label string) error`, including remote dispatch and console registry interface; clear only for the ready transition, preserving LabelledAt and bumping rev when changed.
+- New `ClearFleetBoxDraining(fleet, label string, expectedStart int64) (bool, error)`, including remote dispatch and console registry interface; require positive expectedStart and clear only where draining_since equals that persisted enrolment start, preserving LabelledAt and bumping rev only when changed. Existing SetFleetBoxDraining retains the first start (`registry/fleets.go:609–641`, checked at b7802fd8).
Register outside CLI-user auth, inside the normal request-size, recovery and lifetime-admission protections.
Authenticate solely by the presented one-time token, never by requested fleet/label/account fields.
@@ -538,7 +555,7 @@ Unknown, expired and consumed tokens share one generic 403 COPY response; rate-l
Unknown tokens cannot select a reservation; compare only a hash, without logging body/token.
Expired means `now >= enrol_expires`; only launching/booting rows with an authorized Launch timestamp are eligible.
-Within fleet lock: recheck token and box state, verify the empty-directory assertion, admit history, prepare the ordinary token hash, claim token durably, open sealed fleet credentials, insert active registry row and set its drain mark before releasing lockFleet, then persist enrolled before writing the response. Placement takes the same lock, so it cannot observe the insertion without the mark.
+Within fleet lock: recheck token and box state, verify the empty-directory assertion, admit history, prepare the ordinary token hash, claim token durably, open sealed fleet credentials, insert active registry row and set its drain mark before releasing lockFleet, then persist enrolled before writing the response. Labelled placement takes the same lock, so it cannot observe the insertion without the mark. The drain does not prevent unlabelled work; the 2b joining marker does.
`data_dir_empty` must be true AND `data_dir_entries` zero. Otherwise persist failed with reason `data directory not empty`, invalidate the token and wake cleanup.
Do not admit a bucket/box history target for rejected nonempty data.
The SQL token claim is conditional on unused/hash/state and ensures only one process can win; a process mutex alone is not the replay guard.
@@ -548,7 +565,7 @@ The fleet history write precedes any active registry insertion.
Because console DB and registry are separate stores, this is a recoverable sequence, not a fictional cross-DB transaction.
On restart, claimed-but-not-enrolled fails into cleanup; never complete a trade or replay its response. A crash after enrolled but before response eventually hits the readiness deadline.
Never rotate or overwrite an existing unrelated registry row; no tunnel hash is saved in managed_boxes for crash completion.
-Use AddManagedFleetBox for atomic insertion plus drain, so no partially inserted undrained row can survive a crash; ordinary SetFleetBoxDraining remains the drain-mark contract.
+Persist enrol_drain_start before AddManagedFleetBox and pass that exact start to insertion and every readiness clear, including after restart. Use AddManagedFleetBox for atomic insertion plus drain, so no partially inserted undrained row can survive a crash; ordinary SetFleetBoxDraining remains the drain-mark contract.
A failed response write does not unconsume the enrolment token.
**Census/review:** Public authentication, one-use CAS, history admission and active fleet-token writes are security/authority changes; require independent review and applicable writer/census records before merge.
@@ -563,7 +580,7 @@ TestManagedEnrolInvalidTokens: unknown/expired/used have identical 403 body;
TestManagedEnrolAttestation: missing flag/count, negative count => refused;
false or positive count => failed, reason=data directory not empty, termination queued.
TestManagedEnrolHistoryOrdering: CAS conflict/error => no active row;
- successful trade records bucket and box coverage before active insertion.
+ successful trade records bucket and box coverage before active insertion; reply includes joining:true.
TestManagedEnrolCrash: crash after claim/before registry, after drained registry insert/before enrolled, and after enrolled/before response;
restart never returns secret twice, never replaces another row, eventually cleans lost trade.
TestManagedEnrolSecrets: captured logs/progress/pages/SQL lack both plaintext tokens
@@ -608,18 +625,22 @@ Rootfs uses `boxRootfsReady` on that same fresh report.
Owner check uses FleetOwnerKey and `fleetOwnerRecorded`; it proves the owner record, not that the box consumed it.
Make one owner GET per box at the moment the other five checks would permit readiness; never memoize owner evidence.
Storage/router default to pending in production. Test fakes may pass them independently; a connected heartbeat is not a router probe or bucket proof.
-Only all six current passes transition enrolled to ready. Under lockFleet persist ready with ready_drain_pending, then ClearFleetBoxDraining and clear the pending flag before releasing the lock; recover pending clears after a crash. Never clear first and leave an enrolled row placeable.
-ManagedWork includes ready_drain_pending rows; recover only these, never clear arbitrary ready-row drains. Before accepting a member drain under lockFleet, finish any pending ready clear so crash recovery cannot undo that member drain.
+Only all six current passes transition enrolled to ready. Under lockFleet persist ready with ready_drain_pending, immutable ready_at and ready_object_written=false. Write `fleets/<fleet>/boxes/<label>/ready.json` to the deployment store with exactly `{"fleet","label","ready_at","op"}` (reservation identity, persisted ready timestamp and operation ID), then persist ready_object_written=true BEFORE ClearFleetBoxDraining with the persisted enrol_drain_start. Clear the pending flag only after the conditional drain attempt completes. A failed publication leaves the drain and pending state intact; it never enters failure cleanup.
+Use release.Store.Put with create-only semantics; after conflict or an ambiguous write, GET and require the exact persisted object before proceeding. A mismatch retains pending state and reports an invariant error, never overwrites or clears the drain. Restart retries this sequence, including a crash after the PUT but before its SQL acknowledgement. Never regenerate ready_at on retry.
+Announce successful publication through s.bumpSerial; recovery may repeat the announcement. A lost bump is covered by 2b's joining-only 60-second backstop. The ready object is the authorization; the serial is only a wakeup.
+Checked at b7802fd8: `internal/release/store.go:44–55` defines create-only Put and idempotent Delete; `internal/console/serialbump.go:32` announces writes. `internal/edge/storedoor.go:530–543` already grants aclRead for the authenticated box's own fleet prefix, including this key; no read-ACL expansion is needed.
+A mismatched drain start is preserved, never cleared; a zero/already-cleared mark is an idempotent completion. Record completion of the conditional attempt so recovery cannot clear a later member drain.
+ManagedWork includes ready_drain_pending rows; recover only these, never clear arbitrary ready-row drains. Before accepting a member drain under lockFleet, finish any pending ready-object publication and drain clear so crash recovery cannot undo that member drain.
Include the registry clear method in Tasks 7–8 file changes, remote dispatch/interface and census review.
Controller ruling: while an operation is open, the worker reads each enrolled-not-ready box's own heartbeat object directly
(one GET per such box every 60 seconds, using persisted last_heartbeat_at) and the verified stable pointer at most once per due readiness pass. This is bounded by open
-operations, not steady state, so §6 holds: once a box is ready or terminal the worker never reads it again, and an idle
+operations, not steady state, so §6 holds: once a box is ready or terminal the worker stops heartbeat reads; pending ready-object recovery may still verify its object. An idle
worker reads nothing. No observation cache, no publication from page views or the relabel worker.
Labels are fleet-scoped by the key path, so identical labels in different fleets cannot match.
After a box reaches ready and its op settles, the worker stops describing it; ordinary existing health paths continue.
-**Census/review:** Readiness and drain-clear authority require security review. If no root package changes, record no root-read delta; check authority/write inventories for transition writers.
+**Census/review:** Readiness-object publication and drain-clear authority require security review. If no root package changes, record no root-read delta; check authority/write inventories for transition writers.
- [ ] **Step 1: Write failing tests.**
@@ -635,11 +656,15 @@ TestManagedReadinessDefaults: production extras absent => storage/router_probe p
EC2 running plus Tunnel=connected cannot pass those checks.
TestManagedReadinessBudget: at most one heartbeat GET per enrolled box per 60s, including restart;
at most one stable pointer GET per due pass; zero LISTs; one owner GET per box about to turn ready;
- ready/terminal boxes => zero reads; no owner memo.
-TestManagedJoiningPlacement: one-box fleet with fresh joining heartbeat places nothing;
- all checks pass => ready plus drain cleared, placement succeeds; crash boundaries never expose enrolled as placeable.
-TestManagedReadinessDrainRecovery: crash after ready before clear => restart clears mark safely;
- no cleanup of ready box and no repeated clearing of a later member drain.
+ ready/terminal boxes => zero heartbeat/owner reads; count pending ready-object recovery GETs separately; no owner memo.
+TestManagedJoiningPlacement: no ready.json until all six checks pass, even with a fresh heartbeat;
+ joining drain excludes labelled placements only; failed boxes never receive ready.json;
+ all six pass => exact ready.json written before drain clear, then labelled placement succeeds.
+TestManagedReadinessDrainRecovery: crash after ready before PUT, after PUT before SQL acknowledgement,
+ and after acknowledgement before drain clear => restart publishes/verifies the same object before clearing;
+ PUT failure or mismatched object leaves drain/pending state; ready_at/op stay stable across retries;
+ a different draining_since survives conditional clear; no cleanup of ready box;
+ joining member drain => 409 without mutation; later member drain survives recovery and repeated readiness passes.
```
- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadiness|TestManagedJoiningPlacement' -count=1`; expect FAIL.**
@@ -676,7 +701,7 @@ An identical already-open request joins its frozen op even if config has since c
Add is POST `/api/cli/fleets/{account}/{fleet}/managed-boxes` with `{boxes,request_id}`. CLI generates a random request ID per invocation and reuses it on every POST retry, even after the op closes.
For 2a add inherits the fleet's creation region and named size from retained reservations, then resolves that size in current config; no implicit new region/size flag.
If the old size/region is removed, refuse new capacity while existing operations keep their snapshots.
-Managed doors refuse BYO fleets; add-box/rotate-token/detach-box refuse managed fleets at API and page surfaces; drain/tag stay allowed.
+Managed doors refuse BYO fleets; add-box/rotate-token/detach-box refuse managed fleets at API and page surfaces; tags and ready-box drains stay allowed; joining-box member drains return 409 (COPY) at API/page doors.
Authorization precedes existence details; preserve write/create budgets, fleet plan entitlement and normal account access rules.
No monthly charge or hourly compute billing is introduced in 2a; self-hosted without plan catalog is the acceptance environment.
@@ -700,8 +725,10 @@ TestManagedAPIPreview: rendered region/size/type/N precedes POST; preview never
a config change between preview and create => reply shows the reserved plan and the CLI prints the difference.
TestManagedAPIJoin: rerun open create/add => same op; changed N => 409 naming owned op;
add after completion => fresh op and fresh labels, no recycled tokens.
-TestManagedAPIRetryClosed: lost create/add response then completion before retry => same request ID returns original op, no second batch.
-TestManagedAPIGuards: managed detach/add-box/rotate-token refused at API/page; drain/tag permitted.
+TestManagedAPIRetryClosed: lost create/add response then completion before retry => same request ID returns original op, no second batch;
+ create bypasses name-taken/claim and add bypasses fresh preparation/config checks on this lookup.
+TestManagedAPIGuards: managed detach/add-box/rotate-token refused at API/page; tags and ready drains permitted;
+ joining-box member drain => 409 (COPY), no mutation; invalid request_id => 400 before claim/reservation.
TestManagedCLIFollow: polls every 2s; interrupted CLI => operation continues;
show reattaches after client restart; done-with-failures preserves successful boxes.
TestManagedCLISelectors: account/console selectors and exact sqid survive every poll;
@@ -712,7 +739,7 @@ TestManagedCLISelectors: account/console selectors and exact sqid survive every
- [ ] **Step 3: Implement API and CLI orchestration.**
Do not expose compute.Find/ConsoleOutput through show; the worker persists the evidence the view needs.
-On interrupted POST response, retry with the same request_id; return the original op even if it has already completed. A retry must reach this lookup before preview/config failure can block it.
+On interrupted POST response, retry with the same request_id; return the original op even if it has already completed. A retry must reach this lookup before name claim/name-taken checks or preview/config/preparation failure can block it.
Include documentation headings for managed create, show and boxes add, with COPY-reviewed examples and partial-failure behavior.
Explain that the real adapter and complete readiness ship in 2b; do not publish commands for removal before 2d.
2a code stays neutral on credentials (opaque bytes); docs do not describe P1/P2 until 2b/2c ship them.
@@ -728,8 +755,9 @@ Explain that the real adapter and complete readiness ship in 2b; do not publish
- Implementation-time artifacts: census claims/card/overlay and review brief following `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`; no such artifact is created by this draft.
**Interfaces:**
-- Consume Tasks 1–9's real HTTP handlers, SQL persistence, registry and worker; fake only compute/storage, time, extra checks and published heartbeat observations.
+- Consume Tasks 1–9's real HTTP handlers, SQL persistence, registry and worker; fake only compute/storage, time, extra checks, published heartbeat observations and the deferred box joining behavior.
- Reconstruct Server from a reopened on-disk SQLite database for restart tests; do not reuse its in-memory work state.
+- The fake box consumes joining:true into a persistent local marker; while marked, it owns neither labelled nor unlabelled records (statics included) and starts no instances. It removes the marker only after reading valid ready.json for its own fleet/label, then reconciles normally; console handlers and readiness persistence remain real.
- Preserve the fake provider's cloud resources across that reconstruction, as real cloud resources survive a console restart.
- Count all release.Store operations plus SQL entry calls and all five compute methods; reset only after explicit startup discovery/warming.
- Use the existing `countStore` pattern in `internal/console/fleetbox_test.go:325`, extending coverage to every method used by these tasks.
@@ -740,7 +768,9 @@ Explain that the real adapter and complete readiness ship in 2b; do not publish
```text
TestManagedFleetFakeEndToEnd: member previews/creates three; worker prepares and launches;
- three one-time enrolments; publish fresh version/rootfs signals, pass fake storage/router;
+ three one-time enrolments with joining:true; offer labelled, unlabelled and static records;
+ fake boxes run nothing while marked, including across restart and missing/malformed/wrong-identity ready objects;
+ publish fresh version/rootfs signals, pass fake storage/router; read console-written ready.json, remove markers, reconcile;
all six checks persisted per box; GET and CLI agree; op done; no untracked resources.
TestManagedFailureMatrix/interrupted_create: disconnect after reservation commit;
server worker finishes independently; retry joins; physical launches=requested count.
@@ -815,11 +845,11 @@ Finish line: reviewed 2a core merged, fake acceptance green, production switch f
| Born-examined fleet and first-report empty-data requirement | Tasks 5, 7; real box attestation 2b |
| BYO history/growth remains unchanged | Tasks 1, 5, 7, 9 |
| Registered, exact current stable, rootfs, per-box owner GET | Task 8 |
-| Joining placement exclusion and LabelledAt cleanup gate | Tasks 6–8 |
+| Joining box runs nothing before console-written ready.json; drain excludes labelled placement | Tasks 6–8, 10 fake contract; box enforcement required in 2b |
| Preparation deadline, hourly cleanup, add after op closure | Tasks 5–6, 9 |
| Atomic name claim and same-owner empty-row resume | Tasks 4–5 |
| SQL-only open follow; 60-second enrolled heartbeat reads | Tasks 1, 8–10 |
-| Managed detach refused; drain/tag allowed | Tasks 5, 9 |
+| Managed detach refused; tags/ready drains allowed; joining drain refused | Tasks 5, 9 |
| Bucket read/write and router tunnel probe | Task 8 pending contract/fakes; real checks 2b |
| Each check and safe failure visible via API/CLI | Tasks 1, 6, 8–9 |
| Bootstrap breadcrumbs/provider console diagnostics | 2b/2c; no raw provider-output exposure in 2a |
@@ -855,6 +885,9 @@ Real storage/router readiness remains pending without 2b. The core follows Paul'
- **2b:** AWS compute adapter with ClientToken/tags, identity-checked termination, regional discovery and safe console output; fleet bucket/credentials adapter through rootaws; scoped IAM module changes.
- **2b:** Bucket credentials: per-fleet IAM user with a permissions boundary (objstore.EnsureUser/MintKey pattern), access key delivered once in the enrolment response as `fleetstore.Credentials` (Paul, 2026-11-01, P1).
- **2b hard requirement:** Install the verified binary named by the current stable pointer, never stale bootstrap/carlos; exact version equality remains mandatory in 2a.
+- **2b hard requirement:** Consume enrolment joining:true and durably write a local joining marker before any workload reconcile/start; retain it across reboot. While present, ownsRecord returns false for labelled AND unlabelled records, statics included, and every instance-start path refuses work. Bootstrap, heartbeats and readiness probes must still run. Current `internal/provision/reconcile.go:525–539` at b7802fd8 admits unlabelled records; the drain alone is insufficient.
+- **2b hard requirement:** Read ready.json only while joining, piggybacked on the existing control/serial change pass (`internal/host/agent.go:2875–2933`, b7802fd8): at most one GET per serial change or per 60 seconds while joining, no new steady polling. Missing, unreadable, malformed or wrong-fleet/label objects retain the marker. A valid object for this fleet/label removes it durably and triggers normal reconcile. Test restart and lost serial announcements; after marker removal, zero ready-object reads.
+- **2b hard requirement before switch-on:** Keep ready.json console-written. At b7802fd8 `internal/edge/storedoor.go:644–651` grants boxes writes/deletes across their own fleet prefix; exclude ready-object keys from both operations and prove box credentials cannot forge/delete them, including sibling labels. Preserve the existing read grant and check any direct-store credential route too. The 2a fake proof does not establish this production boundary.
- **2b:** Cloud-init allowlists, pinned binary digest verification before exec, IMDS gate before work, secret scrubbing, enrolment client and real empty-data attestation.
- **2b:** Fleet bucket read/write and router-to-specific-box probes; first-box secrets-key mint and public registration; first real box and approved self-hosted dev drill/switch-on.
- **2c:** Later-box key delivery: the first box writes the fleet private key into the fleet's own bucket; later boxes read it with their fleet credentials (Paul, 2026-11-01, P2), many real boxes, add/rejoin, partial failure drill and complete bootstrap diagnostics. The fake core already reserves N and preserves ready siblings.
@@ -866,7 +899,7 @@ Real storage/router readiness remains pending without 2b. The core follows Paul'
## Review history
Round 1: independent review supplied by the controller; this edit applies its rulings without opening another round.
-- P1-a — Placement-before-readiness: enrol drained, clear at ready, refuse cleanup if LabelledAt != 0; placement tests added.
+- P1-a — Placement-before-readiness: originally enrol drained and require LabelledAt==0 for cleanup; superseded by Paul’s round-2 ruling below. Retain the drain for labelled placements, replace the cleanup proof with the joining invariant.
- P1-b — Pre-dispatch recovery: deterministic HMAC token replaces transient map/remint; identical-restart test added.
- P2-a — Unbounded lifecycle: persisted preparation/launch deadlines, accepted-ID absence proof, hourly quota-held cleanup and one op finishing rule.
- P2-b — Pre-registry show: superseded by P2-d; owned preparation failure remains visible, foreign 404 unchanged.
@@ -882,3 +915,16 @@ Round 1: independent review supplied by the controller; this edit applies its ru
- P3 trade — No saved tunnel hash/crash completion; persist enrolled before response, claimed incomplete trade cleans up.
- P3 heartbeat — Enrolled checks every 60 seconds; launch tick stays 10 seconds.
- P3 sizes — Explicit ARM family allowlist covers g/gd/gn/gen families.
+
+Round 2: controller-supplied review; apply Paul’s P1 ruling and the P2/P3 dispositions without opening another review round.
+- P1 (joining box runs unlabelled records) — Paul: refuse up front; box runs nothing until console-written ready.json (2a console side, 2b box side). Same placement-before-readiness fault family as round 1; stopping rule 2 resolved by this gate, not another drain/LabelledAt fix.
+- P2-1 — Enrolment secret storage: external seal key feeds HKDF with label "managed-enrol"; every launch/relaunch checks enrol_hash, failing safely on key change.
+- P2-2 — Lost seal key: created=true or credential Open failure rotates and reseals; TestManagedSealKeyLost covers credential recovery and outstanding-token failure.
+- P2-3 — Credential disclosure: RotateFleetCredentials reveals each minted secret once and retains at most two keys; console persists sealed bytes before use.
+- P2-4 — Drain ownership: persist enrolment drain start, condition readiness clear on equality, refuse joining-box member drains with 409 (COPY).
+- P2-5 — Request identity: require 22–64 characters from [A-Za-z0-9_-]; invalid/empty IDs return 400.
+- P2-6 — Retry ordering: account/request_id lookup precedes name claim/name-taken checks; closed create/add retries return their original operation.
+- P2-7 — Failed-box authority: revoke tunnel hash under lockFleet while retaining the row for cleanup; test old-token refusal after restart.
+- P3-1 — Termination evidence: persist exact-ID attempt before dispatch; subsequent exact-ID NotFound establishes termination.
+- P3-2 — Preparation recovery: add re-runs failed preparation before reserving, with the same persisted deadline rules.
+Newly cited ready-object store, store-door read/write ACL, serial announcement/pass and ownsRecord seams rechecked at main b7802fd8. This edit applies fix3-brief.md; no tests run or review round reopened.