docs: plan 2a review round 1 fixes
Placement waits for readiness (enrol drained), HMAC-derived enrolment tokens, bounded states, request IDs, fleet-scoped sealed credentials, SQL-only follow view, managed detach guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+168
−101
docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md+168 −101
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 117acc28b..bd588864a 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 |
| @@ -4,11 +4,11 @@ |
| **Goal:** Let an account member create, inspect and add managed fleet capacity through durable console operations, proven against fakes, with the production launch switch off until 2b. |
| -**Architecture:** The console reserves every requested box in SQLite before any provider call, then a restartable worker advances each reservation using its frozen launch identity. Compute and fleet storage have separate provider-neutral interfaces; enrolment admits a fresh box into hostname history before activating its ordinary fleet token. Readiness consumes existing heartbeat observations and persists six named checks; production storage and router checks remain pending until 2b. |
| +**Architecture:** The console reserves every requested box in SQLite before any provider call, then a restartable worker advances each reservation using its frozen launch identity. Compute and fleet storage have separate provider-neutral interfaces; enrolment admits a fresh box into hostname history before activating its ordinary fleet token. Readiness reads enrolled-box heartbeats every 60 seconds and persists six named checks; production storage and router checks remain pending until 2b. |
| **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 and numbered decisions govern this plan. 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 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. |
| ## Global Constraints |
| @@ -35,16 +35,22 @@ |
| - 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. |
| -- This drafting session conducted no independent review. Carry any controller-held review history into the review brief; a filename change or a later task does not reset that history. |
| +- 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. |
| ## Review Focus |
| 1. Enrolment replay and two simultaneous trades must yield at most one successful response and one active token; a lost response never authorizes a second trade. Task 7: `TestManagedEnrolReplayAndRace`. |
| 2. Two accounts creating at the deployment ceiling must share one reservation transaction; neither a fleet mutex nor an account mutex is sufficient. Task 4: `TestManagedQuotaAcrossAccounts`. |
| 3. A console crash after Launch succeeds but before `cloud_id` is persisted must recover by the frozen identity, without purchasing another box. Task 6: `TestManagedRestartAfterLaunchBeforeCloudID`. |
| -4. An operator changes image, subnet, size mapping or ceiling during an operation; retries keep the original launch parameters and new requests use the new config. Tasks 3–4 and 6: `TestManagedFrozenLaunchAcrossConfigChange`. |
| +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`. |
| +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`. |
| +10. Fleet credentials are sealed, shared across enrolments and limited to two live keys. Tasks 2, 5, 7: `TestFleetStorageFakeRotation`, `TestManagedFleetCredentials`. |
| + |
| ## File map and execution boundaries |
| | Area | Files | Responsibility | |
| @@ -64,7 +70,7 @@ |
| Names below marked **new** are proposed interfaces, not claims that symbols already exist. |
| Existing signatures were rechecked in the checkout; source citations identify the baseline. |
| Storage belongs in `internal/fleetstore` (planner's choice): it keeps bucket credentials out of the reusable compute contract. |
| -Use deterministic subnet choice from the configured list, frozen per reservation (planner's choice): a retry cannot drift to another subnet. |
| +Use subnet choice by allocated box number from the configured list, frozen per reservation (round-1 ruling): a retry cannot drift to another subnet. |
| Use one serial worker per serving console (planner's choice), retaining conditional SQL transitions and the existing worker/lifetime admission gate. |
| There is no multi-console cloud lease protocol in this slice; deployment wiring must not start a second active managed worker against a different console DB. |
| @@ -92,7 +98,10 @@ JSON keys are lower snake case, arrays are empty rather than null, and optional |
| The route is `GET /api/cli/fleets/{account}/{fleet}`. |
| The view must not disclose buckets, tokens, credential bytes, launch blobs or provider output. |
| BYO reports the actual active/detached status and observed version; checks are empty, not six invented passes. |
| -Task 8 adds cached readiness observations; Task 9 adds following an open operation. |
| +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. |
| **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. |
| @@ -118,7 +127,7 @@ Use the CLI test environment helper and scratch working directory for subprocess |
| Use the established account-membership and exact-account selector path. |
| Add `show` to `RunFleets`; add the API route through `cliRoute` with the existing user-only fleet role set. |
| -Read registry state and the already available heartbeat view; do not add a timer. |
| +Read registry identity and use request-local heartbeat data only for BYO/settled views; open managed progress comes from SQL. |
| Keep machine codes separate from COPY display labels. |
| Add a `fleets show` documentation heading and neutral BYO example. |
| Send all newly written user copy through copy review before it enters the implementation files. |
| @@ -168,7 +177,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); BoxCredentials(ctx context.Context, fleet, label string) (Credentials, error) }`. |
| +`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. |
| 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. |
| @@ -190,6 +201,8 @@ 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. |
| 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. |
| ``` |
| @@ -209,7 +222,7 @@ Port only small helpers from #183 after adapting them; never copy its fleet/labe |
| **Files:** |
| - Create: `internal/console/managedconfig.go`, `managedconfig_test.go`, `system_managedfleets.go`, `system_managedfleets_test.go`. |
| - Modify: `internal/release/changeindex.go`, `changeindex_test.go`. |
| -- Modify: `internal/console/{authcli.go,server.go}`, `internal/provision/recordview.go`, `internal/release/changewatch.go`, `cmd/console/main.go`, `system.go`, `docs/site/cli.md`. |
| +- Modify: `internal/console/{authcli.go,server.go}`, `cmd/console/main.go`, `system.go`, `docs/site/cli.md`. |
| - Create root `system_managedfleets.go`, `system_managedfleets_test.go`. |
| - Checked seams: `apisystemupdate.go:144,168`; `changeindex.go:54`; `changewatch.go:150`; `system.go:42,61`. |
| @@ -219,12 +232,11 @@ Port only small helpers from #183 after adapting them; never copy its fleet/labe |
| - New `type managedResolved struct { Generation uint64; Region, Size string; Launch compute.LaunchSpec }`. |
| - New `func validateManagedConfig(c managedConfig) error`. |
| - New `func (s *Server) refreshManagedConfig(ctx context.Context, generation uint64) error`. |
| -- New `func (s *Server) resolveManagedConfig(region, size, label string) (managedResolved, error)`; reads held state only. |
| +- New `func (s *Server) resolveManagedConfig(cfg managedConfig, region, size string, boxNumber int) (managedResolved, error)`; resolves a held config snapshot inside the reservation transaction after label allocation. |
| - New handlers `handleAPISystemManagedGet` and `handleAPISystemManagedSet`, both `(w http.ResponseWriter, r *http.Request)`. |
| - Existing `func (s *Server) systemOperator(addr string) bool` is the exact normalized-address matcher. |
| - Existing `func (w *ChangeWatch) Gen(scope string) (gen uint64, ok bool)` supplies observed generations. |
| -- New `func (w *ChangeWatch) OnObserved(fn func(ChangeIndex, bool))` registers an observer; invoke outside the watch mutex after successful adoption or loss of usability. |
| -- Wire that observer once at console startup; it queues config refresh outside the polling call and coalesces duplicate generations. Invalidity closes admission immediately. |
| +- Compare `watch.Gen(scope)` with the held generation on admission and each active worker pass; refresh once per generation. No callback or additional watch Poll. An unusable watch refuses new admission. |
| Document key and scope are both `system/managed-fleets.json`; scope equality applies only to that exact key. |
| GET/PUT `/api/cli/system/managed-fleets`; CLI `carlos system managed-fleets show` / `set --file f.json`. |
| @@ -232,7 +244,7 @@ Use a user principal plus `systemOperator`, not an account operator flag. |
| Do not accidentally inherit `apiSystemRoller`'s additional ops-owner exception: this door follows the controller's configured-system-operator requirement. |
| Missing object means disabled and zero capacity; malformed/unreadable config refuses admission. |
| Reject negative limits, nonpositive root size, empty region/image/subnet/SG/size entries and non-ARM size mappings. |
| -For this operator schema require a full instance-type grammar with family suffix `g`, `gd` or `gn` before the dot, e.g. `m7g.large`; no substring-only test. |
| +Validate the complete instance type against an explicit ARM family allowlist, with letters + generation + g/gd/gn/gen suffix and a valid size after the dot. Include m7g, c7gd, c7gn, is4gen and r8g; reject unlisted families even if their spelling matches. |
| `account_limit=0` resolves to ceiling; otherwise both limits apply independently. |
| The cache stores a deep copy, generation and validity; never hand mutable maps/slices to a reservation. |
| @@ -244,7 +256,7 @@ The cache stores a deep copy, generation and validity; never hand mutable maps/s |
| TestManagedConfigOperatorsOnly: listed system operator => GET/PUT allowed; |
| ordinary member, account owner and unlisted ops owner => identical 404. |
| TestManagedConfigValidation: negative ceiling/account limit and x86 size => refusal; |
| - valid g/gd/gn examples accepted; unknown JSON fields refused; no write on failure. |
| + allowlisted m7g/c7gd/c7gn/is4gen/r8g examples accepted; unlisted lookalikes refused; unknown JSON fields refused; no write on failure. |
| TestManagedConfigGeneration: 1 or 100 boxes with same generation => one config GET; |
| changed generation => one additional GET; same-generation calls => zero GETs. |
| TestManagedConfigUnavailable: absent => disabled; corrupt/unreadable => no admission; |
| @@ -260,7 +272,7 @@ Integrate with the existing observed ChangeWatch stream; do not introduce a mana |
| If the existing watch is unavailable, refuse managed admission until initialized; never silently authorize from stale config. |
| At startup load once; after a local write refresh immediately even if the release store's best-effort generation bump fails. |
| For remotely observed generations, collapse concurrent refreshes into one read, and discard completion from an older generation. |
| -Publish generation observation from the existing record-view/watch path, adding a neutral callback if needed; no extra Poll from the managed worker. |
| +Admission and active passes compare Gen to the held generation; no new callback, Poll or timer. |
| Require change-index support before enabling this feature through the operator door. |
| COPY: help, validation errors, enabled/disabled display and config conflict explanation. |
| Document both system subcommands in this task's merge. |
| @@ -277,19 +289,19 @@ Document both system subcommands in this task's merge. |
| - Checked patterns: `billingstore.go:218`, `billingops.go:201`; console store connection setup at `store.go:99`. |
| **Interfaces (new):** |
| -- `type managedOp struct { ID, 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; LaunchStartedAt time.Time; ConfigGeneration uint64; Storage fleetstore.FleetStorage }`. |
| -- `type managedRequest struct { Account, Fleet, Kind, Region, Size, CreatedBy string; Boxes int }`. |
| -- `func (s *Store) ReserveManaged(ctx context.Context, req managedRequest, cfg managedConfig, resolved managedResolved, now time.Time, mint func(fleet, label string) (hash string, err error)) (managedOp, []managedBox, bool, error)`; bool means joined existing op. |
| +- `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 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)`. |
| - `func (s *Store) ManagedFleet(ctx context.Context, account, fleet string) ([]managedOp, []managedBox, error)`. |
| - `func (s *Store) AdvanceManagedBox(ctx context.Context, before, after managedBox) (bool, error)`; conditional old state/op/token/cloud ID, never blind last-writer-wins. |
| - `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 `managed_ops` and `managed_boxes` columns verbatim, including the partial unique index on `managed_ops(fleet) WHERE state='open'`. |
| -`launch` contains the frozen LaunchSpec with `UserData` empty; no enrolment plaintext or credentials enter SQL. |
| -Persist additional immutable launch timing metadata in that JSON envelope: `launch_started_at` and `config_generation`; leave the public compute type unchanged. |
| +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'`. |
| +`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. |
| `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. |
| @@ -299,9 +311,10 @@ 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. |
| -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. |
| +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. |
| Never return another account's operation ID on a global fleet-name collision. |
| -The same command after completion is not a join: create refuses an existing fleet; add starts a new batch. |
| +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. |
| **Census/review:** Registry schema, fleet writers, remote envelopes and authority inventories require census approval. Global quota concurrency and preserved ownership need independent review. |
| @@ -317,18 +330,22 @@ 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; |
| + 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. |
| TestManagedTransitionCAS: stale prior state cannot overwrite ready/cloud identity. |
| ``` |
| -- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./internal/registry -run 'TestManaged(Migration|Quota|AccountQuota|Join|Frozen|Transition)' -count=1`; expect FAIL.** |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./internal/registry -run 'TestManaged(Migration|Quota|AccountQuota|Join|RequestID|Subnet|Frozen|Transition)' -count=1`; expect FAIL.** |
| - [ ] **Step 3: Implement migration and repository methods.** |
| 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, token hashes and label reservations; retain enrolment plaintext only in an in-memory pending-delivery map owned by the server. |
| -The `mint` callback captures plaintext in a request-local map keyed by fleet/label, returning only its hash to the store. Plaintext never appears in returned persisted row structs. |
| -On DB rollback discard those pending secrets; on commit transfer them to the worker before waking it. |
| -A restart in `reserved` may replace a token hash because Launch has never been authorized; see Task 6's separate rule for `launching`. |
| +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. |
| 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.** |
| @@ -350,13 +367,18 @@ 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, reserve first, ensure storage idempotently, record fleet/bucket in history, create the managed registry row, then write/verify the owner record. |
| -No cloud launch precedes successful preparation; add uses the existing managed fleet's bucket. |
| -Before any external preparation, recheck fleet-name ownership under the same fleet lock used by BYO create. |
| -If a BYO create races an outstanding managed name reservation, it refuses; it cannot steal the name while storage preparation is in flight. |
| -Persist the storage result in the operation's reservation launch envelope as `fleet_storage` before registry publication; no bucket deletion is attempted in 2a. |
| -Recheck on retry that provider output matches the persisted bucket and region; refuse drift. |
| -Create does not overwrite an existing fleet from another account or a BYO fleet. |
| +For create, atomically claim the name first 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. |
| +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. |
| 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. |
| @@ -374,24 +396,30 @@ Lock order: fleet lock, then history mutex; never acquire a fleet lock while hol |
| ```text |
| TestManagedBornExamined: active history + prepared fleet => examined fleet and bucket; |
| data-kind target/coverage gates pass once owner/storage preparation succeeds. |
| -TestManagedHistoryBeforeRegistry: crash after CAS, before registry => retry idempotent; |
| - crash before CAS => no active box/fleet publication. |
| +TestManagedHistoryBeforeRegistry: name claim survives crash before CAS but data admission refuses; |
| + CAS before bucket update/box insertion => retry idempotent, no active unexamined box. |
| TestManagedHistoryCASRace: another fleet/region admission wins first; |
| retry preserves both admissions and Closed; no lost targets. |
| TestManagedHistoryModes: off => no write; closed/invalidated/unreadable => refusal; |
| local latched invalidation cannot be cleared by admission. |
| TestManagedBYOBoundary: BYO still hits fleetGrowthRefusal; |
| - BYO add/rotate API and page doors refuse a managed fleet. |
| + BYO add/rotate/detach API and page doors refuse a managed fleet; drain/tag remain allowed. |
| TestManagedPrepareNameRace: BYO and managed race same name => one owner; |
| - no provider bucket prepared for a known foreign name; no owner overwrite. |
| + no provider bucket prepared for a known foreign name; no owner overwrite; |
| + crash after claim before reservation resumes for same owner; foreign owner refused; |
| + rejected reservation deletes only its just-created empty row, never a row with boxes/ops. |
| +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. |
| ``` |
| -- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare)' -count=1`; expect FAIL.** |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare|Preparation|FleetCredentials)' -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 all BYO token issuance/rotation surfaces, including HTML actions, with `Fleet.Managed`. |
| +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. |
| 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. |
| @@ -415,7 +443,7 @@ COPY: preparation/refusal errors, with safe machine codes and no raw provider re |
| - Temporary readiness is pending; Task 8 supplies the concrete checker. No task may mark ready from `running` alone. |
| Discover durable work once on startup, including failed ops with cleanup rows. |
| -Arm a 10-second timer only while an op is open or a box is neither ready nor terminated. |
| +Use a 10-second tick for open launch work; when only cleanup remains, wake at its persisted hourly next_cleanup_at. Enrolled heartbeat checks run at most every 60 seconds. |
| When idle, a pass returns before SQL, release-store, registry, job bookkeeping or provider access. |
| Track work in memory after startup, with wake synchronization that cannot lose a commit racing the transition to sleep. |
| Read the DB again on an explicit wake; the list of work survives restart, not the timer. |
| @@ -424,29 +452,24 @@ Cancel the worker and outstanding calls with its parent context. |
| Before Launch, commit `launching`, the frozen identity/ClientToken and first-attempt time. |
| Set `enrol_expires=launch_started_at+30m`; use the same anchor for the 20-minute readiness deadline, never `updated_at`. |
| -Call Launch with the frozen spec plus only the in-memory one-time token in transient UserData. |
| +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 only when the original complete transient request is still available and Find returned a complete empty result; keep ClientToken and bytes unchanged. |
| +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. |
| 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. |
| -**Hash-only recovery boundary:** no persisted plaintext means a restart cannot reconstruct a pre-enrolment token. |
| -For `reserved`, remint before the first authorized Launch and replace only that reservation's hash. |
| -For `launching`, never remint or send different UserData with the same ClientToken. |
| -Find and adopt an already launched box; its user data still holds the original token. |
| -If no box can yet be found and the transient request was lost, record a safe failure and retain the quota reservation while discovery continues; never claim a missing lookup proves termination. |
| -This conservative outcome is visible in show; 2a does not invent a durable secret vault to make that narrow crash window succeed. |
| -After the deadline, any discovered instance goes through identity-checked cleanup, even if the operation already reports failure. |
| -The fake acceptance test must cover both successful recovery after Launch and this pre-dispatch uncertainty case. |
| - |
| -On failure persist cause before Terminate, transition to terminating, call `Terminate(..., want Identity)`, and confirm `terminated` through Find. |
| -Only confirmed termination releases quota and permits registry token detachment; a successful Terminate response alone does neither. |
| -A wrong-identity error retains the row and quota, records the error, and performs no detach. |
| -Ready boxes are never cleanup targets merely because another requested box failed. |
| -Finish an open op when all its boxes are ready or terminated-after-failure; derive `done-with-failures` for a mixed result. |
| -Terminal operations with unresolved failed/terminating boxes still keep the worker active. |
| +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. |
| +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. |
| +A closed op no longer blocks add; unresolved cleanup still counts against quota and is discovered on restart. Detach only after established termination. |
| **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. |
| @@ -461,16 +484,21 @@ TestManagedFrozenLaunchAcrossConfigChange: change image/subnet/type/SG/root/ceil |
| old retry unchanged; new reservations use new config or refuse its limit. |
| TestManagedDeadline: 19m59s pending, 20m failed cleanup; token expiry not extended; |
| stopped and shutting-down never free quota; terminated observation does. |
| -TestManagedIdentityCleanup: mismatched tags => no termination, no detach, quota retained. |
| +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. |
| TestManagedPartialFailure: ready siblings untouched; failed Nth launch reported; |
| - op done-with-failures only after failed cloud work is safely terminal. |
| -TestManagedLostTransientLaunch: restart before/after dispatch cannot remint launching token; |
| - later discovered box is adopted or cleaned up; absent evidence keeps reservation counted. |
| + op closes with ready/cleanup siblings; new add allowed subject to held quota; cleanup continues hourly. |
| +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|LostTransient|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|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. |
| @@ -486,7 +514,7 @@ COPY: states, deadline and recovery messages; all logs remain secret-free. |
| **Files:** |
| - Create: `internal/console/managedenrol.go`, `managedenrol_test.go`. |
| -- Modify: `internal/console/{server.go,authcli.go,managedstore.go,managedhistory.go}`. |
| +- Modify: `internal/console/{server.go,authcli.go,managedstore.go,managedhistory.go}`, `internal/registry/{fleets.go,remote_dispatch.go}`, their interface/remote tests and `consoleRegistry`. |
| - Checked seams: `fleets.go:154,133`; `registry/fleets.go:441,574`; `authcli.go:216,229,1177`. |
| **Interfaces (new unless marked existing):** |
| @@ -494,11 +522,13 @@ COPY: states, deadline and recovery messages; all logs remain secret-free. |
| - `type managedEnrolReply struct { Fleet, Label, TunnelURL, TunnelToken string; Credentials fleetstore.Credentials }` with snake-case JSON keys. |
| - `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 mintManagedEnrolToken() (plaintext, hash string, err error)`; 32 random bytes, lowercase hex, SHA-256 of the plaintext string. |
| +- `func deriveManagedEnrolToken(consoleSecret []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. |
| -- Add durable `enrol_tunnel_hash TEXT NOT NULL DEFAULT ''` for completing a claimed trade after a crash; never retain the plaintext tunnel token. |
| -- Extend `managedBox` with `EnrolUsedAt time.Time` and `EnrolTunnelHash string`; include both in scan/CAS predicates and internal recovery, exclude from public views. |
| +- 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. |
| 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. |
| @@ -508,16 +538,17 @@ 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, obtain credentials, insert active registry row, then mark enrolled. |
| +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. |
| `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. |
| A credential-fetch failure after the claim keeps the token consumed and fails the box into cleanup. |
| -Credentials are fetched through `BoxCredentials` only after the durable claim wins and returned once; they never enter managed rows, logs or views. |
| +Credentials come from the current sealed fleet record after the claim wins; each successful response delivers the same current fleet credential. No per-enrolment mint; plaintext never enters SQL, logs or views. |
| 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. |
| -If a crash follows the durable claim, recovery may finish registration from the saved tunnel hash, but cannot replay the secret response; the box times out and is cleaned up if it cannot connect. |
| -An existing active row is accepted only if its hash equals the saved hash for this exact reservation; never rotate or overwrite an unrelated row. |
| +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. |
| 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. |
| @@ -533,7 +564,7 @@ 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. |
| -TestManagedEnrolCrash: crash after claim/before registry and after registry/before response; |
| +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 |
| and credential bytes; only winning response contains ordinary token/credentials. |
| @@ -541,7 +572,7 @@ TestManagedEnrolLimiter: 61st same-IP request => 429; spoofed forwarding header |
| ``` |
| - [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedEnrol' -count=1`; expect FAIL.** |
| -- [ ] **Step 3: Implement the door and crash completion.** |
| +- [ ] **Step 3: Implement the door and claimed-trade cleanup.** |
| Use a unique index for nonempty enrolment hashes and conditional updates for claims. |
| Return `Cache-Control: no-store`; never put tokens in redirects or query strings. |
| @@ -575,18 +606,20 @@ Require a fresh matching fleet/label heartbeat and a complete observation; a mis |
| Use `status.BoxStale` with the configured SnapshotPeriod; never substitute a rootfs version floor for equality. |
| 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. |
| -Memoize owner evidence once per fleet/operation after preparation, invalidate on observed owner changes; no per-box owner GET loop. |
| +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. |
| +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. |
| +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 per 10 s pass) and the verified stable pointer at most once per pass. This is bounded by open |
| +(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 |
| 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:** New readiness cache and success gate require cache/security review. If no root package changes, record no root-read delta; check authority/write inventories for transition writers. |
| +**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. |
| - [ ] **Step 1: Write failing tests.** |
| @@ -600,15 +633,20 @@ TestManagedReadinessStaleOrPartial: stale/missing/partial/wrong-fleet report => |
| TestManagedReadinessOwner: wrong account or fleet => fail; no replacement of owner record. |
| TestManagedReadinessDefaults: production extras absent => storage/router_probe pending; |
| EC2 running plus Tunnel=connected cannot pass those checks. |
| -TestManagedReadinessBudget: per open pass, GETs = enrolled-not-ready boxes + at most 1 stable pointer; zero LISTs; |
| - ready/terminal boxes => zero reads; one owner verification per fleet preparation, not per box/pass. |
| +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. |
| ``` |
| -- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadiness' -count=1`; expect FAIL.** |
| -- [ ] **Step 3: Implement snapshot publication and readiness evaluation.** |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadiness|TestManagedJoiningPlacement' -count=1`; expect FAIL.** |
| +- [ ] **Step 3: Implement readiness evaluation and the ready/drain transition.** |
| Persist changes only when the check result changes, avoiding repeated SQLite progress writes with identical content. |
| -COPY: check descriptions and stale/version/owner explanations; include observed and expected versions without secrets. |
| +COPY: check descriptions and stale/version/owner explanations, including "waiting for version X (running Y)"; keep exact current-stable equality and the 20-minute launch deadline. |
| - [ ] **Step 4: Repeat the targeted command; expect PASS with exact call counts.** |
| - [ ] **Step 5: Commit with subject `feat: gate managed readiness on six persisted checks`.** |
| @@ -624,26 +662,26 @@ COPY: check descriptions and stale/version/owner explanations; include observed |
| **Interfaces (new):** |
| - `func (s *Server) handleAPIManagedFleetCreate(w http.ResponseWriter, r *http.Request)`. |
| - `func (s *Server) handleAPIManagedFleetAdd(w http.ResponseWriter, r *http.Request)`. |
| -- `func (s *apiSession) createManagedFleet(ctx context.Context, a apiAcct, name, region, size string, boxes int) (apiFleetShowReply, error)`. |
| -- `func (s *apiSession) addManagedFleetBoxes(ctx context.Context, a apiAcct, name string, boxes int) (apiFleetShowReply, error)`. |
| +- `func (s *apiSession) createManagedFleet(ctx context.Context, a apiAcct, name, region, size, requestID string, boxes int) (apiFleetShowReply, error)`. |
| +- `func (s *apiSession) addManagedFleetBoxes(ctx context.Context, a apiAcct, name, requestID string, boxes int) (apiFleetShowReply, error)`. |
| - `func (s *apiSession) followManagedFleet(ctx context.Context, a apiAcct, name string, w io.Writer) error`. |
| - New preview handler `handleAPIManagedFleetPlan(w http.ResponseWriter, r *http.Request)`; request has name/region/size/boxes, reply has region/size/instance_type/boxes. |
| Keep POST `/api/cli/fleets/{account}/new`: discriminate `managed:true` and dispatch to the managed handler; BYO request shape remains valid. |
| -Managed request is `{name,managed:true,region,size,boxes}`; reject a bucket field or member-selected image/network/type. |
| +Managed request is `{name,managed:true,region,size,boxes,request_id}`; reject a bucket field or member-selected image/network/type. |
| Preview is POST `/api/cli/fleets/{account}/managed-plan`, read-only after member authentication. |
| It exposes only member plan details, not image IDs/subnets/SGs or full operator config. |
| CLI prints the preview before the mutating POST, and the create reply carries the frozen plan actually reserved; the CLI prints it if it differs from the preview. No generation handshake (controller ruling). |
| An identical already-open request joins its frozen op even if config has since changed; CLI prints that existing operation's plan. |
| -Add is POST `/api/cli/fleets/{account}/{fleet}/managed-boxes` with `{boxes}`. |
| +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; existing add-box/rotate doors refuse managed fleets at API and page surfaces. |
| +Managed doors refuse BYO fleets; add-box/rotate-token/detach-box refuse managed fleets at API and page surfaces; drain/tag stay allowed. |
| 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. |
| Create/add reserve synchronously and return 202 with durable operation; neither waits for cloud calls. |
| -Show merges reservation state with registry labels, includes failed/terminating rows, six checks and safe errors. |
| +Open-op show renders SQL reservations/checks only, including joining, failed/terminating rows and preparation failures; it performs no heartbeat/store reads. Authorization uses the early registry claim. Settled/BYO heartbeat columns retain request-local reads. |
| Show returns latest op with open op preferred; never infer operation completion from missing heartbeat data. |
| Follow polls GET every two seconds while the op is open; its context is not the worker's context. |
| Ctrl-C stops only following and prints COPY guidance naming `carlos fleets show <name>`. |
| @@ -662,6 +700,8 @@ 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. |
| 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; |
| @@ -672,7 +712,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 the same open request instead of buying another batch. |
| +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. |
| 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. |
| @@ -689,7 +729,7 @@ Explain that the real adapter and complete readiness ship in 2b; do not publish |
| **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. |
| -- Reconstruct Server from a reopened on-disk SQLite database for restart tests; do not reuse its in-memory op or token maps. |
| +- Reconstruct Server from a reopened on-disk SQLite database for restart tests; do not reuse its in-memory work state. |
| - 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. |
| @@ -716,19 +756,21 @@ TestManagedFailureMatrix/quota: separate accounts and SQL handles race at ceilin |
| TestManagedIdleBudget: after startup with no work, 100 passes => SQL=0, store=0, compute=0. |
| TestManagedOpenBudget: calls concern only active reservations; ready/terminated => no Find and no heartbeat GET; |
| no ListDeployment, no ConsoleOutput; config GET once/generation. |
| +TestManagedFollowStoreBudget: 100 show/follow polls during an open op => zero store calls, |
| + even with enrolled boxes; preparation failure visible to owner, foreign account gets identical 404. |
| TestManagedSteadyBudget: 1, 10 and 100 ready managed boxes, no open op => worker adds zero store and compute calls. |
| TestManagedSecretSurfaces: unique sentinel secrets absent from API progress, logs, pages, |
| DB files and serialized launch metadata; winning enrolment response is the only trade output. |
| ``` |
| -- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedFleetFakeEndToEnd|TestManagedFailureMatrix|TestManagedIdleBudget|TestManagedOpenBudget|TestManagedSteadyBudget|TestManagedSecretSurfaces' -count=1`; expect FAIL for uncovered integration gaps.** |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedFleetFakeEndToEnd|TestManagedFailureMatrix|TestManagedIdleBudget|TestManagedOpenBudget|TestManagedSteadyBudget|TestManagedFollowStoreBudget|TestManagedSecretSurfaces' -count=1`; expect FAIL for uncovered integration gaps.** |
| - [ ] **Step 3: Close integration gaps within the owning interfaces.** |
| Add at most about ten mutation checks per risky task, targeting only its refusal/security/termination/lifecycle assertions. |
| Examples: remove one identity check, omit a quota state, consume token after response, or accept five readiness passes; the corresponding targeted test must fail. |
| Do not mutation-test renderers or struct mirrors. |
| Keep real bootstrap, credential isolation and live serving claims out of this fake-only acceptance report. |
| -Document any unresolved conservative cleanup reservation from the hash-only crash window; it must remain visible, counted and discoverable, never silently successful. |
| +Assert hourly cleanup remains visible and counted after op closure; no pre-dispatch crash uncertainty remains with deterministic enrolment tokens. |
| - [ ] **Step 4: Run the targeted integration command once to PASS, then one touched-package race run.** |
| @@ -755,24 +797,29 @@ Finish line: reviewed 2a core merged, fake acceptance green, production switch f |
| |---|---| |
| | Managed create prints region, size, instance type and count | Task 9 preview and CLI | |
| | Durable operation, CLI disconnect and show reattachment | Tasks 4, 6, 9–10 | |
| -| Identical open command joins; changed parameters conflict | Tasks 4, 9–10 | |
| +| Identical open command joins; changed parameters conflict; closed retry deduplicates by request ID | Tasks 4, 9–10 | |
| | Operator-approved ARM sizes, images, subnet/SG and ceiling | Task 3; frozen in Task 4 | |
| | Any account member; deployment and account quota under one lock | Tasks 4, 9–10 | |
| | Identity and ClientToken persisted before launch | Tasks 2, 4, 6 | |
| -| Restart, interrupted and ambiguous launch recovery | Tasks 6, 10; hash-only pre-dispatch uncertainty explicitly retained | |
| +| Restart, interrupted and ambiguous launch recovery | Tasks 4, 6, 10; deterministic token and byte-identical restart before dispatch | |
| | Autonomous console worker | Task 6 with startup discovery and wake/idle rules | |
| | Tagged-resource orphan sweep | 2d: hourly by region, 24-hour grace | |
| | Identity-checked termination of failed provisioning | Tasks 2, 6–7; real provider enforcement 2b | |
| | Keep ready siblings after partial failure | Tasks 6, 10 core proof; real many-box operation 2c | |
| | Provider interface and fake, AWS loaded through rootaws | Task 2 boundary/fakes; AWS compute/storage implementation 2b | |
| -| Fleet data bucket and scoped credentials | Tasks 2, 5, 7 contract; real access policy and isolation drill 2b | |
| +| Fleet data bucket and sealed fleet-scoped credentials, two-key rotation cap | Tasks 2, 5, 7 contract; real access policy and isolation drill 2b | |
| | One-time enrolment and no long-lived secret in user data/logs | Task 7; real user-data production/scrub 2b | |
| | Binary verification, allowlists and IMDS gate before work | 2b | |
| | First-box secrets key, same public registration door | 2b; no substitute console-minted key | |
| | Later-box private key delivery without console plaintext | 2c: via the fleet bucket (Paul P2) | |
| | 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, expected version, rootfs, owner checks | Task 8 | |
| +| Registered, exact current stable, rootfs, per-box owner GET | Task 8 | |
| +| Joining placement exclusion and LabelledAt cleanup gate | Tasks 6–8 | |
| +| 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 | |
| | 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 | |
| @@ -798,16 +845,16 @@ Finish line: reviewed 2a core merged, fake acceptance green, production switch f |
| Checked dependency order: Task 1 stands alone; Tasks 2–5 define the provider, config, persistence and preparation seams before Task 6 uses them. |
| Task 6 can launch and clean up with readiness pending; Task 7 adds the trade; Task 8 adds concrete readiness; Task 9 exposes mutations only after those paths exist. |
| Task 10 uses real handlers and persisted state rather than a parallel test-only state machine. |
| -All five Review Focus cases have named owning tests. |
| +All Review Focus cases have named owning tests. |
| The exact compute/storage signatures follow the controller decisions; existing source signatures cited above were checked at the stated base. |
| No implementation bodies are prescribed; test blocks specify observable assertions and commands. |
| -Two explicit limits remain: real readiness stays pending without 2b, and a lost in-memory enrolment request in an uncertain pre-dispatch crash retains a visible cleanup reservation instead of risking a duplicate launch. |
| -Neither limit chooses the pending credential/key decisions or claims a fake proves real cloud isolation. |
| +Real storage/router readiness remains pending without 2b. The core follows Paul's credential/key decisions; fake acceptance does not prove real cloud isolation. |
| ## Deferred to 2b-2d |
| - **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:** 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. |
| @@ -815,3 +862,23 @@ Neither limit chooses the pending credential/key decisions or claims a fake prov |
| - **2d:** Fleet removal refusal while apps remain placed; bucket retention for 30 days, add-box revival on the same bucket and cancellation of deletion. |
| - **2d:** Hourly regional orphan discovery with 24-hour grace and identity checks, including resources whose fleet record no longer exists. |
| - Monthly billing, carloku VPC/peering and platform-box self-provisioning remain outside this phase's core. |
| + |
| +## 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-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. |
| +- P2-c — Follow request budget: SQL-only open-op views and 100-poll zero-store test. |
| +- P2-d — Name ownership: atomic registry claim before reservation; conditional empty cleanup and same-owner resume. |
| +- P2-e — Lost POST: unique account/request ID returns original create/add op in any state. |
| +- P2-f — Join/config ordering: lookup before resolution; resolve allocated box numbers inside reservation transaction. |
| +- P2-g — Version readiness: keep exact current stable and 20-minute deadline; stable-binary installation required in 2b. |
| +- P2-h — Fleet credentials: shared current credential sealed at rest; rotation retains newest two; no enrolment mint. |
| +- P2-i — Managed guards: detach/add-box/rotate-token refused in API/page; drain/tag allowed. |
| +- P3 watch — Compare Gen on admission/worker passes; no observer callback. |
| +- P3 owner — One owner GET per box at readiness, no memo. |
| +- 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. |