| new file mode 100644 |
| index 000000000..117acc28b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md |
| @@ -0,0 +1,817 @@ |
| +# Managed fleets 2a: provider-neutral core Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** 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. |
| + |
| +**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. |
| + |
| +## Global Constraints |
| + |
| +- Commit subjects under 80 characters; body after a blank line. |
| +- 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. |
| +- 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). |
| +- Go: GOFLAGS=-buildvcs=false; leave GOCACHE default. |
| +- Census: changes to authority/record-write inventories need make census-card / census-propose with an independent |
| + reviewer approval recorded on discussion #280 (see AGENTS.md); name which tasks touch census in each task. |
| +- These are execution instructions. Drafting this plan runs no tests and makes no implementation changes. |
| +- The short `/tmp/k.XXXX` exception is only for socket fixtures, tiny and removed by their owner. Everything else uses `$TMPDIR` or an owned disk cache directory. |
| +- Existing fleets decode as BYO. Preserve wire compatibility, secrets-key fields, drain marks, ownership and revision semantics. |
| +- Any account member may use managed create/add/show. Membership in another account grants no inspection or mutation authority. |
| +- No live resources, AWS adapter, IAM edits, cloud-init script, key distribution or billing are implemented here. |
| +- `enabled` defaults false. Missing providers also refuse new reservations. Production never substitutes a fake when a provider is missing. |
| +- Disabling admission does not abandon already reserved work or its cleanup. Frozen reservations survive config removal and ceiling reductions. |
| +- One branch (`managed-fleets-2a`), tasks committed in order, one squash merge at the end on Paul's go. Task 1 (BYO `show`) is first because it is useful on its own; it is not merged separately. |
| +- The controller explicitly assigns switch-on to 2b's approved dev drill. Keep the fake launch feature off through 2a; do not claim the draft supplies a calendar date or authorization for that drill. |
| +- 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. |
| + |
| +## 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`. |
| +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`. |
| + |
| +## File map and execution boundaries |
| + |
| +| Area | Files | Responsibility | |
| +|---|---|---| |
| +| Read-only fleet view | `internal/console/managedview.go`, `fleets_managed.go` | Shared BYO/managed show contract; no provider calls | |
| +| Compute | `internal/compute/provisioner.go`, `fake.go` | Identity, idempotent launch, discovery and checked termination | |
| +| Fleet storage | `internal/fleetstore/provisioner.go`, `fake.go` | Fleet bucket and opaque credentials | |
| +| Operator settings | `internal/console/managedconfig.go`, `system_managedfleets.go` | Validation, generation cache, system-only doors | |
| +| Durable state | `internal/console/managedstore.go`, `internal/registry/fleets.go` | Operations, reservations, quota, managed discriminator | |
| +| Preparation/history | `internal/console/managedhistory.go` | Storage preparation, examined targets, registry publication | |
| +| Worker | `internal/console/managedworker.go` | Launch recovery, deadlines, cleanup, persisted progress | |
| +| Enrolment | `internal/console/managedenrol.go` | One-time token, empty-directory evidence, ordinary token trade | |
| +| Readiness | `internal/console/managedready.go` | Existing-signal observations, six checks, no added polling | |
| +| Public operations | `internal/console/managedapi.go`, `apimode_managedfleets.go` | Create/add/show and CLI follow | |
| +| Integration | `internal/console/managed_e2e_test.go`, `managedbudget_test.go` | Failure matrix and call counts | |
| + |
| +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 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. |
| + |
| +### Task 1: Ship a useful BYO fleet show command |
| + |
| +**Files:** |
| +- Create: `internal/console/managedview.go`, `internal/console/managedview_test.go`. |
| +- Create: `fleets_managed.go`, `fleets_managed_test.go`, `apimode_managedfleets.go`. |
| +- Modify: `fleets.go`, `internal/console/authcli.go`, `docs/site/cli.md`. |
| +- Existing seams: `internal/console/fleets.go:89,105,322`; `apimode.go:5064`; `fleets.go:120`. |
| + |
| +**Interfaces:** |
| +- Consumes existing `func (s *Server) apiFleet(w http.ResponseWriter, r *http.Request) (addr string, acct *Account, fleet *registry.Fleet, reg consoleRegistry, ok bool)`. |
| +- Consumes existing `func fleetPath(a apiAcct, tail string) string`. |
| +- New `func (s *Server) handleAPIFleetShow(w http.ResponseWriter, r *http.Request)`. |
| +- New `type managedCheck struct { State, Reason string }`; state is `pending`, `pass` or `fail`. |
| +- New `type fleetShowBox struct { Label, State, Version, LastError string; Checks map[string]managedCheck }`. |
| +- New `type fleetShowOperation struct { ID, Kind, State, Outcome, Error string; Requested int }`. |
| +- New `type fleetShowReply struct { Name string; Managed bool; Boxes []fleetShowBox; Operation *fleetShowOperation }`. |
| +- New CLI mirror `apiFleetShowReply`, with matching JSON fields; CLI-local check/box/op types mirror the console contract without importing console. |
| +- New `func (s *apiSession) showFleet(ctx context.Context, a apiAcct, name string) (apiFleetShowReply, error)`. |
| +- New `func runFleetsShow(args []string)` and `func printFleetShow(w io.Writer, out apiFleetShowReply)`. |
| + |
| +JSON keys are lower snake case, arrays are empty rather than null, and optional operation is omitted for BYO. |
| +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. |
| + |
| +**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. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestFleetShowBYO: GET owned production => 200; managed=false; operation absent; |
| + active and detached labels preserved; no token_hash in serialized JSON. |
| +TestFleetShowMembership: owner and ordinary member => 200; |
| + another account and absent fleet => identical 404 body. |
| +TestFleetShowNoProviderCalls: render/show => launch=0, find=0, terminate=0. |
| +TestFleetsShowCLI: account selectors retained; output contains labels and versions; |
| + malformed response => error; no local registry or bucket fallback. |
| +``` |
| + |
| +- [ ] **Step 2: Run the failing tests.** |
| + |
| +Run `GOFLAGS=-buildvcs=false go test ./internal/console . -run 'TestFleetShow|TestFleetsShowCLI' -count=1`. |
| +Expected: missing route/command/type fails these tests. |
| +Use the CLI test environment helper and scratch working directory for subprocess cases. |
| + |
| +- [ ] **Step 3: Implement the view and CLI renderer.** |
| + |
| +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. |
| +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. |
| + |
| +- [ ] **Step 4: Run the same targeted command; expect PASS.** |
| + |
| +Retain the cross-account response comparison, not merely status-code assertions. |
| +Check CLI documentation coverage through the existing docsite gate when this task is integrated. |
| + |
| +- [ ] **Step 5: Commit with subject `feat: show fleet boxes through the console API`.** |
| + |
| +### Task 2: Establish compute/storage fakes and enforce the provider boundary |
| + |
| +**Files:** |
| +- Create: `internal/compute/provisioner.go`, `fake.go`, `fake_test.go`, `imports_test.go`. |
| +- Create: `internal/fleetstore/provisioner.go`, `fake.go`, `fake_test.go`. |
| +- No existing console file moves. The console package already imports the AWS SDK for unrelated features (Cost Explorer, CloudWatch, perf); extracting those is out of scope (controller ruling). |
| + |
| +**Interfaces (new, exact controller contract):** |
| + |
| +```go |
| +type Identity struct{ Deployment, Fleet, Label, Operation string } |
| +type LaunchSpec struct { |
| + Identity |
| + Region, InstanceType, Image, Subnet string |
| + SecurityGroups []string |
| + RootGB int |
| + UserData string |
| + ClientToken string |
| +} |
| +type State string |
| +type Instance struct { |
| + CloudID, Region string |
| + Identity Identity |
| + State State |
| + Reason string |
| + LaunchedAt time.Time |
| +} |
| +type Provisioner interface { |
| + Launch(ctx context.Context, s LaunchSpec) (Instance, error) |
| + Find(ctx context.Context, region string, id Identity) ([]Instance, error) |
| + Terminate(ctx context.Context, region, cloudID string, want Identity) error |
| + ListDeployment(ctx context.Context, region, deployment string) ([]Instance, error) |
| + ConsoleOutput(ctx context.Context, region, cloudID string) (string, error) |
| +} |
| +``` |
| + |
| +`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) }`. |
| +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. |
| +Expose `SetState(cloudID string, state State)` and `Calls() map[string]int` on the compute fake. |
| +Fault fields: `LoseLaunchResponse bool`, `FailLaunch error`, `FailLaunchNumber int`, `InitialState State`, `TerminateIdentityMismatch bool`. |
| +Use `ErrLaunchRejected` for a definite no-side-effect launch refusal; every unclassified error is ambiguous. |
| +Use `ErrIdentityMismatch` for termination refusal; no matching effect is performed. |
| + |
| +**Census/review:** New packages only; no authority change. No census delta expected unless a root envelope imports them. |
| + |
| +- [ ] **Step 1: Write failing contract and boundary tests.** |
| + |
| +```text |
| +TestFakeClientToken: same token + identical spec => same CloudID; |
| + same fleet/label + different token => TWO instances; changed spec + same token => error. |
| +TestFakeLostLaunchResponse: first call creates one instance and errors; |
| + Find with exact identity returns it, including after it becomes terminated. |
| +TestFakeIdentityTerminate: change any Identity field => ErrIdentityMismatch, state unchanged. |
| +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. |
| +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. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/compute ./internal/fleetstore ./internal/console -run 'TestFake|TestFleetStorageFake|TestManagedCoreImports' -count=1`; expect FAIL.** |
| +- [ ] **Step 3: Implement contracts, fakes and the narrow adapter extraction.** |
| + |
| +Keep identity matching exact; a different deployment never matches discovery. |
| +The test parses files (go/parser) for direct imports; existing release/registry dependencies transitively use AWS and are not being rewritten here. |
| +Port only small helpers from #183 after adapting them; never copy its fleet/label deduplication. |
| + |
| +- [ ] **Step 4: Repeat the targeted command; expect PASS.** |
| +- [ ] **Step 5: Commit with subject `feat: compute and fleet storage interfaces with fakes`.** |
| + |
| +### Task 3: Operator-only managed settings, refreshed by generation |
| + |
| +**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`. |
| +- 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`. |
| + |
| +**Interfaces:** |
| +- New `type managedConfig struct { Enabled bool; Ceiling, AccountLimit int; Regions map[string]managedRegion }` with the controller's snake-case JSON keys. |
| +- New `type managedRegion struct { Image string; Subnets, SecurityGroups []string; RootGB int; Sizes map[string]string }`. |
| +- 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 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. |
| + |
| +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`. |
| +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. |
| +`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. |
| + |
| +**Census/review:** Configuration is an authority gate and cache. Change-index and root CLI envelopes need census; console's config cache needs security review even where outside root scope. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +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. |
| +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; |
| + last good enabled value cannot authorize after a failed invalidation refresh. |
| +TestManagedConfigWriteVisibility: successful PUT updates held config immediately; |
| + attempted stale If-Match cannot replace a newer operator setting. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./internal/release . -run 'TestManagedConfig|TestSystemManaged' -count=1`; expect FAIL.** |
| +- [ ] **Step 3: Implement validation, CAS write, generation observation and CLI.** |
| + |
| +Integrate with the existing observed ChangeWatch stream; do not introduce a managed worker polling the config object or its own change-index timer. |
| +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. |
| +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. |
| + |
| +- [ ] **Step 4: Repeat the targeted command; expect PASS, including exact GET counts.** |
| +- [ ] **Step 5: Commit with subject `feat: configure managed fleets through the system API`.** |
| + |
| +### Task 4: Reserve durable operations and enforce quotas atomically |
| + |
| +**Files:** |
| +- Create: `internal/console/managedstore.go`, `managedstore_test.go`. |
| +- Modify: `internal/console/store.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, 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. |
| +- `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. |
| +`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. |
| + |
| +Reserve under one pinned SQL connection using `BEGIN IMMEDIATE`, count and insert, then commit. |
| +Count every row except `terminated`, including ready, failed and terminating, across the deployment and per account. |
| +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. |
| +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. |
| + |
| +**Census/review:** Registry schema, fleet writers, remote envelopes and authority inventories require census approval. Global quota concurrency and preserved ownership need independent review. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestManagedMigration: reopen old DB twice; old fleets managed=false; secrets/drain fields unchanged. |
| +TestManagedQuotaAcrossAccounts: two DB handles, ceiling=3, concurrent requests of 2; |
| + exactly one op and two reservations committed; other refused; provider calls=0. |
| +TestManagedAccountQuota: global=10, account_limit=2; account cannot reserve third; |
| + another account can reserve; terminating/failed/ready rows still count. |
| +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. |
| +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 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`. |
| +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.** |
| +- [ ] **Step 5: Commit with subject `feat: reserve managed boxes under deployment and account quotas`.** |
| + |
| +### Task 5: Prepare fleet storage and admit managed history before publication |
| + |
| +**Files:** |
| +- Create: `internal/console/managedhistory.go`, `managedhistory_test.go`. |
| +- Modify: `internal/console/{hostsused.go,fleets.go,managedstore.go,server.go}`. |
| +- Checked seams: `hostsused.go:104,132,227,307`; `provision/hostsused.go:152,172`; `fleetowner.go:44,93`; `fleetfloor.go:240`. |
| + |
| +**Interfaces:** |
| +- Existing `provision.ReadHostsState(ctx context.Context, s release.Store) (provision.HostsState, string, error)`. |
| +- Existing `provision.WriteHostsState(ctx context.Context, s release.Store, st provision.HostsState, ifMatch string) (string, error)`. |
| +- Existing `func (s *Server) lockFleet(fleet string) (unlock func())` (`fleetbox.go:189`). |
| +- Existing `func (s *Server) writeFleetOwner(ctx context.Context, f registry.Fleet) error`. |
| +- New `func (s *Server) prepareManagedFleet(ctx context.Context, op managedOp, boxes []managedBox) error`. |
| +- 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. |
| + |
| +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. |
| +Read fresh state on each CAS retry; preserve RegionTargets, unrelated fleets, Closed, reason and timestamps except the updated admission time. |
| +A closed fleet is refused, never silently reopened. |
| +Mode off skips admission with no error; incomplete/invalidated/unreadable history preserves the existing refusal behavior. |
| +Do not set the cached `verified` flag true merely because this write succeeded; keep existing startup verification/latch semantics. |
| +After successful CAS refresh the held history under its mutex; a concurrent invalidation must still win. |
| +Lock order: fleet lock, then history mutex; never acquire a fleet lock while holding the history mutex. |
| + |
| +**Census/review:** New history/owner-record writers are authority and record-write inventory changes. Include their production call sites and witness tests in the census review; console exclusion from root scope does not exempt the writer inventories. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```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. |
| +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. |
| +TestManagedPrepareNameRace: BYO and managed race same name => one owner; |
| + no provider bucket prepared for a known foreign name; no owner overwrite. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare)' -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`. |
| +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. |
| + |
| +- [ ] **Step 4: Repeat the targeted command; expect PASS.** |
| +- [ ] **Step 5: Commit with subject `feat: admit fresh managed fleets into hostname history`.** |
| + |
| +### Task 6: Drive launch recovery and failure cleanup from durable state |
| + |
| +**Files:** |
| +- Create: `internal/console/managedworker.go`, `managedworker_test.go`. |
| +- Modify: `internal/console/{server.go,managedstore.go,jobs.go,jobs_test.go}` and the existing claim-worker registration table. |
| +- Modify: `cmd/console/main.go` beside the FleetRelabel startup at line 788. |
| +- Checked pattern: `fleetrelabel.go:70,91` and `lifetimes_cutover.go:430`. |
| + |
| +**Interfaces (new):** |
| +- `func (s *Server) StartManagedFleets(ctx context.Context)`. |
| +- `func (s *Server) RunManagedFleetsPass(ctx context.Context, now time.Time) error`. |
| +- `func (s *Server) stepManagedBox(ctx context.Context, b managedBox, now time.Time) error`. |
| +- `func (s *Server) wakeManagedFleets()`; coalesced in-memory notification after durable work commits. |
| +- `func (s *Server) failManagedBox(ctx context.Context, b managedBox, reason string, now time.Time) error`. |
| +- 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. |
| +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. |
| +Honor lifetime/claim mode admission as FleetRelabel does; do not bypass cutover by starting a bare unregistered goroutine. |
| +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. |
| +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. |
| +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. |
| + |
| +**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. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestManagedRestartAfterLaunchBeforeCloudID: persist launching, fake Launch succeeds, |
| + discard Server, reopen DB => Find adopts original CloudID; physical instances=1. |
| +TestManagedAmbiguousLaunch: lost response => Find before any second Launch; |
| + every Launch uses byte-identical ClientToken and frozen parameters. |
| +TestManagedFrozenLaunchAcrossConfigChange: change image/subnet/type/SG/root/ceiling; |
| + 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. |
| +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. |
| +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 3: Implement the state machine and safe error projection.** |
| + |
| +Use bounded per-call contexts and a fake clock; never sleep twenty minutes in tests. |
| +Provider raw errors/UserData/ConsoleOutput must not enter logs or API text; persist a safe code and bounded redacted detail. |
| +Routine 2a diagnostics are state/check/error evidence; raw bootstrap diagnostics are deferred to 2b/2c. |
| +Do not call ListDeployment on this timer; the orphan sweep is 2d. |
| +COPY: states, deadline and recovery messages; all logs remain secret-free. |
| + |
| +- [ ] **Step 4: Repeat the targeted command; expect PASS.** |
| +- [ ] **Step 5: Commit with subject `feat: reconcile managed launches and identity-checked cleanup`.** |
| + |
| +### Task 7: Trade a one-time enrolment token for a fleet identity |
| + |
| +**Files:** |
| +- Create: `internal/console/managedenrol.go`, `managedenrol_test.go`. |
| +- Modify: `internal/console/{server.go,authcli.go,managedstore.go,managedhistory.go}`. |
| +- Checked seams: `fleets.go:154,133`; `registry/fleets.go:441,574`; `authcli.go:216,229,1177`. |
| + |
| +**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. |
| +- `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. |
| +- 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. |
| + |
| +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. |
| +Bound JSON to 4 KiB, require both attestation fields to be present, reject negative counts and extra fields. |
| +Use `newRateLimiter` with 60 requests/minute per trusted `clientIP`, plus one deployment-wide 600/minute bucket; bound limiter key growth using the existing limiter behavior. |
| +Unknown, expired and consumed tokens share one generic 403 COPY response; rate-limit denial is 429 with Retry-After. |
| +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. |
| +`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. |
| +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. |
| +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. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestManagedEnrolReplayAndRace: 20 parallel trades => exactly one 200; |
| + one tunnel hash installed; all other results generic 403; replay after restart => 403. |
| +TestManagedEnrolInvalidTokens: unknown/expired/used have identical 403 body; |
| + exact expiry fails; neither SQL nor registry gains active authority. |
| +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; |
| + 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. |
| +TestManagedEnrolLimiter: 61st same-IP request => 429; spoofed forwarding header cannot evade. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedEnrol' -count=1`; expect FAIL.** |
| +- [ ] **Step 3: Implement the door and crash completion.** |
| + |
| +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. |
| +Do not grant the ordinary fleet token system-operator rights or secrets-key replacement rights. |
| +2b supplies box-side attestation and bootstrap; this slice tests the exact provider-neutral first-contact contract. |
| +COPY: the generic refusal, invalid report and retry/cleanup explanations; preserve the controller's recorded nonempty-data reason. |
| + |
| +- [ ] **Step 4: Repeat the targeted command; expect PASS.** |
| +- [ ] **Step 5: Commit with subject `feat: enrol managed boxes with single-use tokens`.** |
| + |
| +### Task 8: Persist six readiness checks using existing observations |
| + |
| +**Files:** |
| +- Create: `internal/console/managedready.go`, `managedready_test.go`. |
| +- Modify: `internal/console/{managedworker.go,managedview.go}`. |
| +- Modify the existing system-pointer observation path in `internal/console/apisystemupdate.go`. |
| +- Checked source: `rootfs.go:281`, `fleetowner.go:93`, `reqmemo.go:197`, `remoteinstances.go:60`, `release/systempointer.go:259`. |
| + |
| +**Interfaces:** |
| +- New `func (s *Server) managedHeartbeat(ctx context.Context, fleet, label string) (*status.Box, error)`: one GET of `fleets/<fleet>/status/boxes/<label>.json` through the console's store (controller ruling: read directly while the box is enrolled-not-ready). |
| +- New `func (s *Server) managedReadiness(ctx context.Context, b managedBox, now time.Time) (map[string]managedCheck, error)`. |
| +- New test-injectable `type managedExtraChecks interface { Checks(context.Context, managedBox) (storage, router managedCheck, err error) }`. |
| +- Existing `func boxRootfsReady(b status.Box) bool` checks the heartbeat metric. |
| +- Existing `func fleetOwnerRecorded(ctx context.Context, st release.Store, key string, f registry.Fleet) (bool, error)` verifies owner identity. |
| +- Existing `release.GetSystemPointer(ctx context.Context, s release.Store, pub ed25519.PublicKey, component, channel string) (*release.SystemPointer, string, error)` verifies the expected release pointer. |
| + |
| +Persist exactly `registered`, `version`, `rootfs_ready`, `owner_record`, `storage`, `router_probe` in checks JSON. |
| +Registered means active registry row for this reservation's label; heartbeat presence alone is insufficient. |
| +Version compares Metrics.Release exactly with the deployment's current verified `router/stable` pointer's Current.Version. |
| +Require a fresh matching fleet/label heartbeat and a complete observation; a missing/stale report or unreadable pointer yields pending. |
| +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. |
| +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. |
| + |
| +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 |
| +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. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestManagedReadinessSixChecks: five passes plus one pending => enrolled; |
| + all six pass => ready; persisted JSON contains all six keys. |
| +TestManagedReadinessTracksStableRoll: heartbeat=v0.33.0, stable=v0.34.0 => pending; |
| + fresh heartbeat=v0.34.0 => pass; bad signature/missing stable => pending. |
| +TestManagedReadinessStaleOrPartial: stale/missing/partial/wrong-fleet report => not ready; |
| + Metrics=nil => pending; future/untrusted report cannot bypass existing freshness rules. |
| +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. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadiness' -count=1`; expect FAIL.** |
| +- [ ] **Step 3: Implement snapshot publication and readiness evaluation.** |
| + |
| +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. |
| + |
| +- [ ] **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`.** |
| + |
| +### Task 9: Expose managed create/add and follow durable progress from the CLI |
| + |
| +**Files:** |
| +- Create: `internal/console/managedapi.go`, `managedapi_test.go`. |
| +- Modify: `internal/console/{authcli.go,fleets.go,managedview.go}`. |
| +- Modify: `fleets.go`, `fleets_managed.go`, `fleets_managed_test.go`, `apimode_managedfleets.go`, `docs/site/cli.md`. |
| +- Existing CLI seams: `runFleetsCreate(args []string)` at `fleets.go:187`; `createFleet` at `apimode.go:5152`; existing BYO add at `apimode.go:5195` remains distinct. |
| + |
| +**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) 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. |
| +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}`. |
| +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. |
| + |
| +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. |
| +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>`. |
| +`show` follows an open op by default, printing changes; a settled fleet prints once. |
| +A failed outcome returns nonzero while still reporting ready siblings and failed labels. |
| + |
| +**Census/review:** Root CLI envelopes need census; account authorization and operation creation need independent security review. No direct AWS or box-local fallback is permitted. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestManagedAPIAnyMember: ordinary member create/add/show works; cross-account and absent => same 404. |
| +TestManagedAPIIsolation: injected image/subnet/bucket/client token rejected; |
| + disabled/missing-provider => no op/reservations; BYO/managed wrong doors refused. |
| +TestManagedAPIPreview: rendered region/size/type/N precedes POST; preview never reserves; |
| + 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. |
| +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; |
| + subprocess uses carlosTestEnv and scratch cwd, never real credentials/config. |
| +``` |
| + |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console . -run 'TestManagedAPI|TestManagedCLI' -count=1`; expect FAIL.** |
| +- [ ] **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. |
| +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. |
| + |
| +- [ ] **Step 4: Repeat the targeted command and the touched CLI documentation check; expect PASS.** |
| +- [ ] **Step 5: Commit with subject `feat: create and follow managed fleet operations from the CLI`.** |
| + |
| +### Task 10: Prove the failure matrix, request budget and merge gates |
| + |
| +**Files:** |
| +- Create: `internal/console/managed_e2e_test.go`, `managedbudget_test.go`. |
| +- Modify only the task-owned tests/helpers needed to inject clocks, DB-close crash points and fake observations. |
| +- 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. |
| +- Reconstruct Server from a reopened on-disk SQLite database for restart tests; do not reuse its in-memory op or token maps. |
| +- 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. |
| + |
| +**Census/review:** Whole-branch review includes each changed root envelope, authority writer, cache and termination path. Apply P2 fixes without restarting review; review newly changed authority behavior within the same budget. |
| + |
| +- [ ] **Step 1: Write failing end-to-end and budget tests.** |
| + |
| +```text |
| +TestManagedFleetFakeEndToEnd: member previews/creates three; worker prepares and launches; |
| + three one-time enrolments; publish fresh version/rootfs signals, pass fake storage/router; |
| + 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. |
| +TestManagedFailureMatrix/restart: crash after launch before cloud ID save; |
| + reopen, Find original, enrol, ready; one cloud resource for each ClientToken. |
| +TestManagedFailureMatrix/ambiguous: provider accepts and loses response; |
| + discovery precedes retry, no duplicate, original identity maintained. |
| +TestManagedFailureMatrix/retry: concurrent identical API requests => one operation/batch. |
| +TestManagedFailureMatrix/partial_capacity: Nth failure, others ready; |
| + failed instance cleaned if it exists, successful ones retained, outcome lists failure. |
| +TestManagedFailureMatrix/quota: separate accounts and SQL handles race at ceiling; |
| + committed reservations never exceed global/account limits, including cleanup rows. |
| +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. |
| +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 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. |
| + |
| +- [ ] **Step 4: Run the targeted integration command once to PASS, then one touched-package race run.** |
| + |
| +Run `GOFLAGS=-buildvcs=false go test -race ./internal/compute ./internal/fleetstore ./internal/console ./internal/registry -run 'TestManaged|TestFake|TestFleetStorageFake' -count=1` once after the final implementation changes. |
| +Run touched CLI/adapter checks and build/vet/gofmt checks appropriate to their changes; full repository tests and cross-builds run in CI. |
| +Run `make census-card`; write per-unit CLAIMS, then `make census-propose NAME=<branch> CLAIMS=<owned-file>` and obtain independent approval recorded on #280. |
| +The reviewer must inspect every changed registry field/writer, not just newly named managed files. |
| +Use the opposite-family reviewer required by AGENTS at implementation time; this draft does not spawn reviewers or consume a review round. |
| +Carry the review history and fault-family names; stop at the first round with no P1, apply P2, list P3 follow-ups. |
| +Finish copy review for every introduced member string and docs paragraph before the merge. |
| + |
| +- [ ] **Step 5: Commit, describe, push and land the completed 2a branch through amadan.** |
| + |
| +Subject: `test: prove managed fleet recovery and request budgets`. |
| +Use `amadan branch describe carlos/platform <branch> -body -` with exact multiline context. |
| +Check `amadan ci status carlos/platform -branch <branch>` on the full tip SHA. |
| +Merge with `amadan branch merge carlos/platform <branch> -squash -expect <full-tip> -message <short-subject-and-body>` only after green CI and required review. |
| +Read main CI, update the GitHub mirror only from amadan main if needed, and remove owned scratch/processes. |
| +Finish line: reviewed 2a core merged, fake acceptance green, production switch false, 2b readiness/adapter gaps explicitly recorded. |
| + |
| +## Self-review |
| + |
| +| Phase 2 requirement / acceptance item | Coverage | |
| +|---|---| |
| +| 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 | |
| +| 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 | |
| +| 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 | |
| +| 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 | |
| +| 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 | |
| +| Boxes add and retry missing capacity | Tasks 4, 9–10 fake proof; key-bearing real multi-box use 2c | |
| +| Box removal stops placements, drains/waits then terminates | 2d: bounded 15-minute running-instance wait | |
| +| Fleet removal refuses placed apps | 2d | |
| +| Identity-checked removal, observed terminal then detach | Task 6 failed-provisioning cleanup; user removal 2d | |
| +| Bucket kept while used, 30-day retention and revival by add | 2d | |
| +| Lost box keeps instances on survivors, no auto replacement | Existing merged 1b; real multi-box proof 2c/2d | |
| +| Self-hosted immediate removal after drain | 2d | |
| +| Paid-month removal and monthly charges | Phase 3, outside 2a–2d billing implementation | |
| +| No AWS deployment retains BYO, managed off | Tasks 1–3, 9 | |
| +| No added steady-state per-box polling; idle zero calls | Tasks 3, 6, 8, 10 | |
| +| Three requested boxes all six checks pass (§8.1) | Task 10 fake proof; real proof 2b/2c | |
| +| Rails/native/custom-domain public serving (§8.2) | 2b/2c approved dev drill | |
| +| Six fake failure cases (§8.3) | Task 10 matrix, with Task 6 crash boundaries | |
| +| Cross-account refusal and bucket credential isolation (§8.4) | Tasks 1, 7, 9; real credential policy proof 2b | |
| +| No secret leakage (§8.5) | Tasks 7, 10; cloud-init copies 2b | |
| +| Reboot, active removal, survivors, retained bucket (§8.6) | Existing 1c; 2c/2d drills | |
| +| Phase 3 charging acceptance (§8.7) | Phase 3 | |
| +| CLI documentation and copy review (§8.8) | Tasks 1, 3, 9–10 | |
| + |
| +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. |
| +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. |
| + |
| +## 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:** 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. |
| +- **2d:** Member box removal: drain, wait for no running instances up to 15 minutes, identity-check terminate, observe terminated, detach; no revival of rejected 1b drain-evidence fields. |
| +- **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. |