docs: plan 2a pre-flight rulings C01-C14
Apply the controller rulings to task contracts, publication recovery, verification and execution ownership; record C01-C14 in the ledger.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+150
−73
docs/superpowers/notes/managed-fleets-2a-ledger.md+29 −0docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md+121 −73
CI passed — run details
diff --git a/docs/superpowers/notes/managed-fleets-2a-ledger.md b/docs/superpowers/notes/managed-fleets-2a-ledger.md| new file mode 100644 |
| index 000000000..ddb66de42 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/managed-fleets-2a-ledger.md |
| @@ -0,0 +1,29 @@ |
| +# SDD ledger — plan: docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md |
| + |
| +Managed fleets 2a build ledger: tasks, commits, review results, rulings and deferred minors. |
| +Branch managed-fleets-2a, base main b7802fd8, plan tip 8c4ed4ff. Implementers: Astra (codex). Reviews: Opus |
| +subagents for Tasks 4-7 and the whole branch. Later rulings supersede earlier ones on the same point. |
| + |
| +Ruling: SDD workspace (briefs, reports, review packages) lives in /home/paulca/.cache/managed-fleets-2-notes/sdd, not |
| +.superpowers/sdd in the worktree — the sandbox mounts the worktree read-only — cost if wrong: none. |
| + |
| +## Pre-flight scan |
| + |
| +Conflict table: /home/paulca/.cache/managed-fleets-2-notes/sdd/preflight.md, “Conflicts and proposed rulings”. Binding decisions: /home/paulca/.cache/managed-fleets-2-notes/sdd/preflight-rulings.md. No new review round; rounds 1–3 remain closed. |
| + |
| +Ruling: C01 Keep Task 1 BYO-only; move managed views to Task 9 and provider integration to Task 10; define token derivation in Task 4 — sequential tasks must compile without forward dependencies — blocked tasks or empty placeholder tests |
| +Ruling: C02 Resolve immutable config/generation snapshots with a pure function after label allocation; pass deployment explicitly — Store cannot call a Server resolver or infer missing frozen inputs — launch identity or config drifts on retry |
| +Ruling: C03 Persist op region/size/preparation start and box ready time/observed version with scan/write contracts — open show and restart recovery need durable observations — lost deadlines or misleading progress |
| +Ruling: C04 Persist every joined request ID and validated payload in account-scoped aliases — joined invocations must replay after closure — duplicate batches after a lost response |
| +Ruling: C05 Return 202 for a durable zero-box add op; worker prepares then atomically quota-checks/allocates; exclude preparing ops from completion — preparation must precede new reservations without blocking admission — unrecoverable preparation or premature closure |
| +Ruling: C06 Assign conditional deletion, owned bucket updates, consoleRegistry, remote tests and census to Task 5 — the preparation task must compile and preserve registry ownership — missing interfaces or overwritten owner/secrets fields |
| +Ruling: C07 Name the Task 6 case TestManagedFrozenLaunchRetryAcrossConfigChange — Task 4 already declares the original name — duplicate test declaration breaks compilation |
| +Ruling: C08 Create-only PUT then GET; absent is proven unpublished, matching present is published and becomes ready without termination; only proven unpublished at 20 minutes fails into cleanup; uncertainty/mismatch stays publishing with durable uncertain reason in show, quota held, no revoke/terminate, hourly verification after deadline and op closure allowed; test both publication windows — ready.json may authorize work before console verification; operator resolves mismatch and 2d removal drains first — termination of a box already running workloads |
| +Ruling: C09 Add a safe frozen region/size/type/count projection to operation replies and CLI; compare actual reply with preview — members must see what was reserved — misreported capacity after config changes |
| +Ruling: C10 Preview looks up request aliases and matching owned open ops before config; ambiguous POST retries directly with the same ID — disabled or removed config must not block frozen joins/replays — CLI cannot recover an accepted operation |
| +Ruling: C11 GeneratedAt zero or more than two minutes ahead is pending; retain BoxStale for age and test boundaries — BoxStale alone accepts future timestamps — untrusted timestamps bypass readiness |
| +Ruling: C12 Expand the one final race run to all touched packages and explicit rotation/system/show/change-index/startup patterns — the prior command omitted changed code and a risky test — races survive the local gate |
| +Ruling: C13 Implementers mark/list COPY strings without running copy review; controller reviews before merge — the execution contract assigns copy review to the controller — implementation blocks or unreviewed copy ships |
| +Ruling: C14 Implementers end at local checks, commit, census proposal and report; controller owns review/#280/push/CI/landing on Paul's go — implementation must stay within the dispatch boundary — unauthorized publication or landing |
| + |
| +## Tasks |
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 78b1b7fa9..3da2ff0b4 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 |
| @@ -1,10 +1,10 @@ |
| # 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. |
| +> **For agentic workers:** Follow the controller's execution contract task-by-task; implementers do not spawn subagents. 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 reads enrolled-box heartbeats every 60 seconds and persists six named checks; production storage and router checks remain pending until 2b. |
| +**Architecture:** The console persists each operation before provider calls and reserves each box before launch; an add retry after failed preparation first persists a zero-box op, then prepares storage before reservation. 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. |
| @@ -14,7 +14,7 @@ |
| - 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. |
| +- Implementers mark/list draft member-facing strings as COPY and do not run copy review; the controller completes copy review before merge. |
| - Provider-neutral core: no AWS SDK import outside adapters; an import test enforces it. |
| - Request budget (spec §6): no new steady-state per-box store polling; worker idle = zero calls. |
| - A managed box runs no workloads until the console writes its ready.json after all six checks pass; 2a supplies the signal and fake proof, 2b must enforce the box-side joining marker before switch-on. |
| @@ -33,24 +33,25 @@ |
| - 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. |
| +- Mark CLI help, errors, progress and docs strings COPY during implementation. This implementation plan contains contracts and COPY markers, not approved member copy. Implementers do not spawn subagents, post to #280, push, run CI or merge; the controller owns review, #280, push, CI and landing, with landing only on Paul's go. |
| - 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. |
| -- Rounds 1–2 findings and controller dispositions are recorded below. Carry that round history into subsequent review briefs; a filename change or a later task does not reset it. |
| +- Rounds 1–3 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 reservations use the new config; existing request IDs always return their original op. 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`, `TestManagedFrozenLaunchRetryAcrossConfigChange`. |
| 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. A joining box owns no records and starts no instances until console-written ready.json; the drain blocks labelled placements only. Tasks 6–8 and 10: `TestManagedJoiningPlacement`, `TestManagedFailedEnrolledCleanup`. |
| 7. Restart before dispatch reconstructs identical UserData; request retries after completion return the original batch. Tasks 4, 6, 9: `TestManagedRequestID`, `TestManagedRestartBeforeDispatch`. |
| 8. Preparation deadlines, identity-mismatch hourly cleanup and closed-op add admission are durable. Tasks 5–6: `TestManagedPreparationDeadline`, `TestManagedIdentityCleanup`, `TestManagedPartialFailure`. |
| 9. Atomic name claim precedes reservation; show stays SQL-only during open work. Tasks 5, 9–10: `TestManagedPrepareNameRace`, `TestManagedFollowStoreBudget`. |
| -10. Fleet credentials are sealed, shared across enrolments and limited to two live keys. Tasks 2, 5, 7: `TestFleetStorageFakeRotation`, `TestManagedFleetCredentials`. |
| +10. Publication may authorize work before console verification. Task 8: `TestManagedPublishDeadline` covers consumed publication with failed GET past the deadline and proven absence at the deadline; uncertain publication never revokes or terminates. |
| +11. Fleet credentials are sealed, shared across enrolments and limited to two live keys. Tasks 2, 5, 7: `TestFleetStorageFakeRotation`, `TestManagedFleetCredentials`. |
| ## File map and execution boundaries |
| @@ -99,10 +100,7 @@ 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. |
| -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 labelled-placement-blocking drain mark. |
| +Task 1 implements BYO only, with today's request-local heartbeat reads and Managed=false; it does not depend on Task 4's registry discriminator or SQL schema. Task 9 adds managed progress, preparation failures and joining projection. |
| **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. |
| @@ -113,7 +111,6 @@ 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. |
| ``` |
| @@ -128,10 +125,10 @@ 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 identity and use request-local heartbeat data only for BYO/settled views; open managed progress comes from SQL. |
| +Read registry identity and use request-local heartbeat data for BYO views. |
| 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. |
| +Mark and list newly written member copy as COPY for the controller; do not run copy review. |
| - [ ] **Step 4: Run the same targeted command; expect PASS.** |
| @@ -204,8 +201,8 @@ TestFakeNthCapacityFailure: third launch rejected, first two retained, no third |
| TestFleetStorageFake: same fleet/region => same bucket; distinct fleets isolated; |
| opaque credentials not present in storage metadata; empty credentials supported. |
| TestFleetStorageFakeRotation: each minted secret is revealed once; FleetCredentials cannot recover it; |
| - rotations retain at most two live keys per fleet, always preserve keep, reap an unsealed orphan first, and never affect another fleet; |
| - many enrolments reuse the console-sealed current key without provider minting. |
| + rotations retain at most two live keys per fleet, always preserve keep, reap an unsealed orphan first, and never affect another fleet. |
| + Console-sealed multi-enrolment behavior is tested in Tasks 5/7 and integrated in Task 10. |
| TestFleetCredentialsDoubleLostRotation: deliver one key, then lose two consecutive rotations before sealing; |
| pass delivered_key_id as keep both times; the delivered key remains live and at most two keys are live. |
| TestManagedCoreImports: direct imports in compute and fleetstore (all files, tests included) and in |
| @@ -237,7 +234,8 @@ 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(cfg managedConfig, region, size string, boxNumber int) (managedResolved, error)`; resolves a held config snapshot inside the reservation transaction after label allocation. |
| +- New `type managedConfigSnapshot struct { Config managedConfig; Generation uint64 }`; immutable deep copy. |
| +- New pure package function `func resolveManagedConfig(snapshot managedConfigSnapshot, region, size string, boxNumber int) (managedResolved, error)`; resolves inside the reservation transaction after label allocation and carries the snapshot generation into the result. |
| - 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. |
| @@ -294,19 +292,22 @@ 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, 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; DrainClearCompleted bool; LaunchStartedAt, TerminateAttemptedAt, TerminateSentAt, NextCleanupAt, LastHeartbeatAt time.Time; EnrolDrainStart int64; ConfigGeneration uint64; Storage fleetstore.FleetStorage }`. |
| +- `type managedOp struct { ID, RequestID, Account, Fleet, Kind, State, CreatedBy, Error, Region, Size string; Requested int; PreparationStartedAt, CreatedAt, UpdatedAt time.Time }`. |
| +- `type managedBox struct { Fleet, Label, OpID, Account, Region, Size, ClientToken, CloudID, State, LastError, EnrolHash, ObservedVersion string; Launch compute.LaunchSpec; Checks map[string]managedCheck; EnrolExpires, ReadyAt, CreatedAt, UpdatedAt time.Time; DrainClearCompleted bool; LaunchStartedAt, TerminateAttemptedAt, TerminateSentAt, NextCleanupAt, LastHeartbeatAt time.Time; EnrolDrainStart int64; ConfigGeneration uint64; Storage fleetstore.FleetStorage }`. |
| - `type managedRequest struct { RequestID, Account, Fleet, Kind, Region, Size, CreatedBy string; Boxes int }`. |
| -- `func (s *Store) ReserveManaged(ctx context.Context, req managedRequest, cfg managedConfig, now time.Time, enrolHash func(clientToken string) (string, error)) (managedOp, []managedBox, bool, error)`; bool means returned existing op. Check request ID and open op before validating/resolving cfg; resolve per allocated label inside this transaction. |
| +- `func (s *Store) ReserveManaged(ctx context.Context, req managedRequest, snapshot managedConfigSnapshot, deployment string, 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 the snapshot; resolve per allocated label inside this transaction, freezing snapshot.Generation and the explicit stable deployment in ConfigGeneration and Identity.Deployment. |
| +- `func deriveManagedEnrolToken(enrolKey []byte, clientToken string) (plaintext, hash string)`; HMAC derivation defined here and consumed in Task 7. |
| - `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 tables plus `managed_ops.request_id TEXT NOT NULL` with UNIQUE(account, request_id), persisted requested region/size and `preparation_started_at`; include the partial unique index on `managed_ops(fleet) WHERE state='open'`. |
| +Create the controller's tables plus `managed_ops.request_id TEXT NOT NULL` with UNIQUE(account, request_id), persisted requested region/size and `preparation_started_at`; add `managed_request_aliases` with UNIQUE(account, request_id), op ID and validated payload for every original or joined invocation, written in the same reservation transaction. Consult aliases before config/name/preparation checks, including after closure; 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 the `publishing` state for ready-object recovery, immutable `ready_at`, and `drain_clear_completed` for conditional drain-clear recovery, plus `enrol_drain_start` (Unix nanoseconds), `terminate_attempted_at` and `terminate_sent_at` bound to the exact cloud ID, `next_cleanup_at` and `last_heartbeat_at` as well; leave the public compute type unchanged. |
| +Scan/write Region, Size and PreparationStartedAt on operations, and ReadyAt and ObservedVersion on boxes through every load/CAS path. ReadyAt is immutable once publishing starts; persist ObservedVersion with readiness observations for SQL-only show. |
| +For an add after failed preparation, persist an open op with zero boxes, payload/alias and PreparationStartedAt. The worker prepares it, then quota-checks and allocates its complete batch in one SQL transaction; persist preparation/allocation failure on the op. Preparing zero-box ops are excluded from the all-boxes-finished rule. |
| `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|publishing|ready|failed|terminating|terminated`. |
| Keep first error separately from subsequent cleanup detail in the structured checks/error rendering so cleanup does not erase cause. |
| @@ -317,7 +318,7 @@ A count overflow or invalid request rolls back the entire batch; never reserve a |
| 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. |
| Require non-empty request_id matching `^[A-Za-z0-9_-]{22,64}$` on managed create/add; otherwise return 400 before any claim or reservation. |
| -After authentication and request validation, first look up (account, request_id), before name claim or name-taken checks: identical parameters return that original op in any state; changed parameters conflict. Then compare an open operation's account/kind/count/region/size before resolving new config: identical request joins its frozen rows; different parameters return 409 and the owned open op ID. |
| +After authentication and request validation, first look up the (account, request_id) alias, before name claim or name-taken checks: identical parameters return that original op in any state; changed parameters conflict. Then compare an open operation's account/kind/count/region/size before resolving new config: identical request joins its frozen rows and atomically adds its request-ID/payload alias; different parameters return 409 and the owned open op ID. |
| Never return another account's operation ID on a global fleet-name collision. |
| A new invocation uses a new request ID: after completion create refuses an existing nonempty fleet; add starts a new batch. |
| Resolve each newly allocated box-N with subnet = subnets[N % len(subnets)]; freeze the result in its row. Joins work with a removed size or disabled feature. |
| @@ -335,13 +336,15 @@ TestManagedAccountQuota: global=10, account_limit=2; account cannot reserve thir |
| 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. |
| + persisted launch bytes, deployment identity and config generation unchanged; ClientToken stable across DB reopen. |
| TestManagedRequestID: empty, malformed, short or overlong ID => 400, no claim/reservation; |
| create and add repeat after done/failed => original op, no new reservation; |
| - changed payload with the same account/request ID conflicts; another account cannot read it. |
| + two different request IDs joining one op both replay it after closure/reopen; |
| + changed payload with either alias 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. |
| +TestManagedTransitionCAS: stale prior state cannot overwrite ready/cloud identity; |
| + op region/size/preparation start and box ready_at/observed version survive scan/write and reopen. |
| ``` |
| - [ ] **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.** |
| @@ -363,7 +366,8 @@ Make `UpsertFleet` preserve the managed discriminator on conflict; ordinary BYO |
| **Files:** |
| - Create: `internal/console/managedhistory.go`, `managedhistory_test.go`. |
| -- Modify: `internal/console/{hostsused.go,fleets.go,managedstore.go,server.go}`. |
| +- Modify: `internal/console/{hostsused.go,fleets.go,managedstore.go,server.go,view.go}`. |
| +- Modify: `internal/registry/{fleets.go,remote_dispatch.go}` and registry/interface/remote tests for conditional deletion and owned bucket updates. |
| - Checked seams: `hostsused.go:104,132,227,307`; `provision/hostsused.go:152,172`; `fleetowner.go:44,93`; `fleetfloor.go:240`. |
| **Interfaces:** |
| @@ -380,9 +384,10 @@ BYO create uses the atomic insert (`registry/fleets.go:253`), not lockFleet; do |
| 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. |
| +Expose conditional deletion and an owned bucket-update method through consoleRegistry and remote dispatch in this task; preserve owner, Managed and secrets-key fields, and test local/remote parity and foreign/nonempty refusal. |
| 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 on a fleet whose preparation failed re-runs preparation before reserving new boxes, with a durably recorded start for that new attempt and the same 30-minute deadline; retries/restarts never reset that start. No reservation or launch precedes its success. |
| +Add on a fleet whose preparation failed persists an open zero-box op with request payload/alias and PreparationStartedAt, then returns 202 without cloud calls. The worker discovers it and re-runs preparation with the same 30-minute deadline; retries/restarts never reset that start. After success, quota-check and allocate the op's boxes in one SQL transaction. No reservation or launch precedes preparation success; preparing zero-box ops cannot close as all-boxes-finished, and failure stays visible. |
| Add uses the existing bucket when one was persisted; otherwise recover preparation to establish it. Recheck provider output against the persisted bucket/region; refuse drift, never overwrite another owner. |
| Persist preparation_started_at before the first provider call; at 30 minutes fail the op and its unlaunched reservations without launching. Proven never-dispatched reservations become terminated and release quota. |
| Persist fleet-scoped non-secret `delivered_key_id` independently of the sealed credential, so losing the seal key cannot lose the key ID boxes use. Persist it before sending any enrolment response; never advance it for a rotation lost before sealing or delivery. If no sealed credential exists, call RotateFleetCredentials(ctx, fleet, delivered_key_id), seal Secret and persist ID before use. Reuse the persisted copy on ordinary retries and enrolments. |
| @@ -399,7 +404,7 @@ Do not set the cached `verified` flag true merely because this write succeeded; |
| 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. |
| +**Census/review:** Registry deletion/bucket-update methods, remote envelopes and preserved fields need census changes and independent 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.** |
| @@ -418,17 +423,20 @@ TestManagedPrepareNameRace: BYO and managed race same name => one owner; |
| no provider bucket prepared for a known foreign name; no owner overwrite; |
| crash after claim before reservation resumes for same owner; foreign owner refused; |
| 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. |
| +TestManagedPreparationDeadline: persisted start +30m => failed op, zero launches, failure retained in SQL; |
| + restart does not reset deadline; owned/foreign show assertions are in Task 9. |
| TestManagedFleetCredentials: preparation retries mint once; SQL contains only sealed secret bytes and non-secret key IDs; |
| - restart opens same credential; many boxes receive same current key without minting. |
| + restart opens same credential; repeated credential reads reuse it without minting; real enrolment assertions follow in Tasks 7/10. |
| TestManagedSealKeyLost: created=true or fleet credential Open failure => rotate, reseal, persist before use; |
| at most two live keys; replacement seal key changes HKDF output, outstanding launch hash mismatch => no Launch. |
| -TestManagedAddAfterPreparationFailure: add re-runs preparation before reservation; persisted deadline survives restart; |
| - timeout => no new boxes/launches; success => reserve against recovered bucket/owner. |
| +TestManagedAddAfterPreparationFailure: persist open zero-box add op and alias before cloud calls (HTTP 202 tested in Task 9); |
| + restart discovers preparation with unchanged deadline; zero boxes do not finish the preparing op; |
| + timeout => visible failure, no new boxes/launches; success => atomic quota check and complete allocation against recovered bucket/owner. |
| +TestManagedRegistryPreparationMethods: local/remote conditional deletion refuses foreign/nonempty rows; |
| + owned bucket update preserves owner, Managed and secrets-key fields through consoleRegistry. |
| ``` |
| -- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare|Preparation|FleetCredentials|SealKeyLost|AddAfterPreparationFailure)' -count=1`; expect FAIL.** |
| +- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(Born|History|BYO|Prepare|Preparation|FleetCredentials|SealKeyLost|AddAfterPreparationFailure|RegistryPreparationMethods)' -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. |
| @@ -456,8 +464,8 @@ COPY: preparation/refusal errors, with safe machine codes and no raw provider re |
| - `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. |
| -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. |
| +Discover durable work once on startup, including zero-box preparing ops, failed ops with cleanup rows and closed ops with uncertain publishing rows. Prepare zero-box adds before atomically quota-checking and allocating their boxes (Tasks 4–5). |
| +Use a 10-second tick for open launch work; when only cleanup or post-deadline uncertain publication 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. |
| @@ -475,16 +483,16 @@ Pending stays launching; running becomes booting; stopped/stopping/shutting-down |
| A found cloud instance with mismatched identity/region is never adopted or terminated. |
| A restart before dispatch rebuilds byte-identical UserData, including the derived token, and retries with the same ClientToken; no remint or lost-transient uncertainty state. |
| -Every provisioning state has a persisted deadline: reserved preparation uses 30 minutes; launching/booting/enrolled/publishing use 20 minutes from launch_started_at. Retries never reset either anchor. |
| -On failure persist cause before Terminate. Under lockFleet, revoke any enrolled box’s tunnel token with SetFleetBoxToken using a valid 64-lowercase-hex hash of a fresh discarded random token; keep its registry row for cleanup. Retry revocation after a crash/error before cleanup proceeds. Checked seam: `internal/registry/fleets.go:509,524` at b7802fd8 validates the hash and bumps rev. Automatic termination of a not-ready box rests on the joining invariant: without console-written ready.json it owns no records and runs no instances. LabelledAt is not a termination proof. Publishing reaches failed at that deadline or on a mismatched existing ready object, then follows normal token revocation, idempotent object deletion and termination cleanup while the box is still joining. Ready rows, including drain-clear recovery, never enter failed-provisioning cleanup. |
| +Every provisioning state has a persisted deadline: reserved/zero-box preparation uses 30 minutes; launching/booting/enrolled use 20 minutes from launch_started_at. Publishing verifies at that 20-minute deadline; only proven unpublished fails into cleanup, while uncertain publication continues hourly. Retries never reset either anchor. |
| +On failure persist cause before Terminate. Under lockFleet, revoke any enrolled box’s tunnel token with SetFleetBoxToken using a valid 64-lowercase-hex hash of a fresh discarded random token; keep its registry row for cleanup. Retry revocation after a crash/error before cleanup proceeds. Checked seam: `internal/registry/fleets.go:509,524` at b7802fd8 validates the hash and bumps rev. Automatic termination requires proof that the box was never authorized: without console-written ready.json it owns no records and runs no instances. LabelledAt is not a termination proof. Publishing uses create-only PUT then GET: absent means proven unpublished; present and matching means published, even if found late, so persist ready and clear the conditional drain, never terminate. Proven unpublished at the 20-minute deadline fails into normal cleanup. Failed GET or a mismatched object keeps publishing with durable `uncertain` reason visible in show, quota held, no revoke and no terminate; verify hourly after the deadline. An operator resolves a mismatched object (2d removal drains first). Ready rows, including drain-clear recovery, never enter failed-provisioning cleanup. |
| Transition to terminating and persist terminate_attempted_at bound to the exact cloud ID before calling `Terminate(..., want Identity)`. Persist terminate_sent_at only after acceptance. |
| Confirm termination by Find reporting terminated, or NotFound/complete Find absence for that exact cloud ID after its persisted attempt, including a lost Terminate response. A successful Terminate response alone never frees quota. |
| Identity mismatch records a safe error, stops fast retries and schedules hourly retry with persisted next_cleanup_at; quota stays held and show reports the reason. |
| Failed/terminating cleanup uses hourly back-off after the op closes; each attempt is bounded and retains quota until termination is established. Cleanup has no forced quota-release deadline. |
| Ready boxes are never cleanup targets merely because a sibling failed. |
| -One finishing rule: close an op when every box is ready with drain_clear_completed recorded, terminated, or in cleanup (failed/terminating). All ready => done; some ready => done with failures; none ready => failed. |
| -A closed op no longer blocks add; unresolved cleanup still counts against quota and is discovered on restart. Detach only after established termination. |
| -Failure and cleanup never write ready.json. For failed publishing, revoke the token, delete the ready object idempotently, then terminate; retry deletion failures before proceeding. For other cleanup, delete any ready object idempotently after established termination and before detach (also required of 2d removal); retry deletion failures before detach. This avoids leaving an obsolete authorization object; deleting it does not stop an already-ready box. |
| +One finishing rule: exclude preparing zero-box ops; otherwise close an op when every box is ready with drain_clear_completed recorded, terminated, in cleanup (failed/terminating), or publishing with post-deadline uncertain verification scheduled hourly. All ready => done; some ready => done with failures; none ready => failed. |
| +A closed op no longer blocks add; unresolved cleanup and uncertain publication still count against quota and are discovered on restart. Detach only after established termination. |
| +Failure and cleanup never write ready.json. Only proven-unpublished publishing can fail into normal cleanup; uncertain or mismatched publication is never revoked, deleted or terminated automatically. For other cleanup, delete any ready object idempotently after established termination and before detach (also required of 2d removal); retry deletion failures before detach. This avoids leaving an obsolete authorization object; deleting it does not stop an already-ready box. |
| **Census/review:** Launch and termination authority, worker registration, registry detach and timing need independent review. Include newly changed root command envelopes and record-write witnesses in the census proposal. |
| @@ -495,9 +503,9 @@ TestManagedRestartAfterLaunchBeforeCloudID: persist launching, fake Launch succe |
| 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; |
| +TestManagedFrozenLaunchRetryAcrossConfigChange: 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; |
| +TestManagedDeadline: unpublished launching/booting/enrolled at 19m59s pending, 20m failed cleanup; token expiry not extended; |
| stopped and shutting-down never free quota; terminated observation does. |
| TestManagedIdentityCleanup: mismatched tags => no termination/detach, quota retained, visible error; |
| no fast retry; retry at one hour, including after restart. |
| @@ -509,7 +517,8 @@ TestManagedFailedEnrolledCleanup: failed joining box never gets ready.json and r |
| cleanup uses the joining invariant, not LabelledAt; ready siblings, including drain-clear recovery, never terminate; |
| termination precedes idempotent ready-object deletion and detach; deletion failure retries without detach. |
| TestManagedPartialFailure: ready siblings untouched; failed Nth launch reported; |
| - op closes with ready/cleanup siblings; new add allowed subject to held quota; cleanup continues hourly. |
| + op closes with ready/cleanup or post-deadline uncertain-publishing siblings; new add allowed subject to held quota; |
| + cleanup/verification continues hourly after closure and restart; preparing zero-box op stays open. |
| TestManagedEnrolKeyChanged: replace external key before first launch or relaunch => failed, |
| reason="enrolment key changed", no Launch call; unchanged key preserves UserData. |
| TestManagedRestartBeforeDispatch: crash after launching commit, before dispatch; reopen and relaunch |
| @@ -542,7 +551,7 @@ COPY: states, deadline and recovery messages; all logs remain secret-free. |
| - `type managedEnrolReply struct { Fleet, Label, TunnelURL, TunnelToken string; Credentials fleetstore.Credentials; Joining bool }` with snake-case JSON keys; `joining` is always true for managed enrolment in 2a. |
| - `func (s *Server) handleManagedEnrol(w http.ResponseWriter, r *http.Request)` at `POST /api/fleet/enrol`. |
| - `func (s *Server) enrolManagedBox(ctx context.Context, in managedEnrolRequest, now time.Time) (managedEnrolReply, error)`. |
| -- `func deriveManagedEnrolToken(enrolKey []byte, clientToken string) (plaintext, hash string)`; Task 4 HMAC derivation, lowercase hex, SHA-256 of plaintext string. |
| +- Existing from Task 4: `func deriveManagedEnrolToken(enrolKey []byte, clientToken string) (plaintext, hash string)`; HMAC derivation, lowercase hex, SHA-256 of plaintext string. |
| - Existing `func mintFleetToken() (plaintext, hash string, err error)` is the ordinary tunnel-token issuer. |
| - Add durable `enrol_used_at INTEGER NOT NULL DEFAULT 0` to managed_boxes for single-use claim/recovery; no plaintext response column. |
| - Extend `managedBox` with `EnrolUsedAt time.Time`; include it in scan/CAS predicates, exclude from public views. |
| @@ -607,7 +616,7 @@ COPY: the generic refusal, invalid report and retry/cleanup explanations; preser |
| **Files:** |
| - Create: `internal/console/managedready.go`, `managedready_test.go`. |
| -- Modify: `internal/console/{managedworker.go,managedview.go}`. |
| +- Modify: `internal/console/{managedworker.go,managedstore.go,managedview.go}`; store scans/CAS persist observed version, immutable ReadyAt and uncertain publication reason/schedule. |
| - 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`. |
| @@ -621,24 +630,26 @@ COPY: the generic refusal, invalid report and retry/cleanup explanations; preser |
| 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. |
| +Persist Metrics.Release as ObservedVersion with the checks for SQL-only show; 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. |
| +Use `status.BoxStale` with the configured SnapshotPeriod for age; separately require GeneratedAt nonzero and no more than 2 minutes in the future, otherwise pending. The existing helper does not enforce that clock-skew guard; 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. |
| 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 publishing. Under lockFleet persist publishing and immutable ready_at. Write `fleets/<fleet>/boxes/<label>/ready.json` to the deployment store with exactly `{"fleet","label","ready_at","op"}` (reservation identity, persisted ready timestamp and operation ID). Write and verify the exact object before persisting ready; only then call ClearFleetBoxDraining with the persisted enrol_drain_start and record drain_clear_completed after the conditional attempt completes. |
| -Use release.Store.Put with create-only semantics and GET to verify the exact persisted object, including after conflict or an ambiguous write. Restart in publishing re-verifies the object; never regenerate ready_at. Publishing remains under the 20-minute launch deadline: persistent publication failure at the deadline or a mismatched existing object transitions to failed and normal cleanup (revoke token, delete object idempotently, terminate), safe because the box is still joining. Restart in ready with its enrolment drain still set re-clears it conditionally; ready never returns to failed provisioning. |
| +Use release.Store.Put with create-only semantics, then GET to verify the exact persisted object, including after conflict or an ambiguous write. Restart in publishing re-verifies; never regenerate ready_at. At any verification: absent = proven unpublished; present and matching this box/op and persisted ready_at = published. Published, even if found late, means persist ready and clear the conditional drain; never terminate. |
| +At the 20-minute launch deadline, proven unpublished becomes failed into normal cleanup (token revoked, terminate). Uncertain verification (GET keeps failing) or a mismatched object stays publishing with a durable `uncertain` reason visible in show, quota held, no revoke and no terminate. After the deadline, persist hourly verification scheduling; the op may close around it as for hourly cleanup. An operator resolves a mismatched object; 2d removal drains first. Never overwrite or delete that object automatically. |
| +Restart in ready with its enrolment drain still set re-clears it conditionally; ready never returns to failed provisioning. |
| Announce successful publication through s.bumpSerial; recovery may repeat the announcement. A lost bump is covered by 2b's joining-only 60-second backstop. The ready object is the authorization; the serial is only a wakeup. |
| Checked at b7802fd8: `internal/release/store.go:44–55` defines create-only Put and idempotent Delete; `internal/console/serialbump.go:32` announces writes. `internal/edge/storedoor.go:530–543` already grants aclRead for the authenticated box's own fleet prefix, including this key; no read-ACL expansion is needed. |
| A mismatched drain start is preserved, never cleared; a zero/already-cleared mark is an idempotent completion. Record completion of the conditional attempt so recovery cannot clear a later member drain. |
| -ManagedWork includes publishing rows and ready rows whose drain_clear_completed is false; recover only these, never clear arbitrary ready-row drains. Before accepting a member drain under lockFleet, finish and record the ready row’s conditional drain clear so crash recovery cannot undo that member drain. Publishing boxes remain joining and refuse member drains. |
| +ManagedWork includes publishing rows and ready rows whose drain_clear_completed is false; recover only these, never clear arbitrary ready-row drains. Before accepting a member drain under lockFleet, finish and record the ready row’s conditional drain clear so crash recovery cannot undo that member drain. Publishing rows retain the console joining projection and refuse member drains; that projection is not proof that the box has not consumed ready.json. |
| Include the registry clear method in Tasks 7–8 file changes, remote dispatch/interface and census review. |
| Controller ruling: while an operation is open, the worker reads each enrolled-not-ready box's own heartbeat object directly |
| (one GET per such box every 60 seconds, using persisted last_heartbeat_at) and the verified stable pointer at most once per due readiness pass. This is bounded by open |
| -operations, not steady state, so §6 holds: once a box is ready or terminal the worker stops heartbeat reads; publishing recovery verifies its object until ready or failed. An idle |
| +operations, not steady state, so §6 holds: once a box is ready or terminal the worker stops heartbeat reads; publishing recovery verifies until ready or proven-unpublished failure, hourly after the deadline while uncertain, including after op closure. 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. |
| @@ -653,7 +664,8 @@ TestManagedReadinessSixChecks: five passes plus one pending => enrolled; |
| 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. |
| + Metrics=nil or GeneratedAt=zero => pending; GeneratedAt=now+2m accepted if otherwise fresh; |
| + GeneratedAt>now+2m => pending, including the first instant past the boundary; test the separate age guard too. |
| 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. |
| @@ -668,15 +680,20 @@ TestManagedReadinessDrainRecovery: crash in publishing before PUT, after PUT bef |
| PUT failure stays publishing until the deadline; ready_at/op stay stable across retries; |
| a different draining_since survives conditional clear; no cleanup of ready box; |
| joining member drain => 409 without mutation; later member drain survives recovery and repeated readiness passes. |
| -TestManagedPublishDeadline: persistent PUT failure => publishing until the 20-minute launch deadline, then failed; |
| - op closes; token revoked, object deleted idempotently, termination attempted; quota held until terminated; |
| - restart preserves deadline; mismatched existing object => failed with the same cleanup, never overwritten or ready. |
| +TestManagedPublishDeadline/published_window: PUT succeeds; fake box consumes ready.json and starts work; |
| + console GET fails through the 20-minute deadline => publishing, durable uncertain reason visible in show; |
| + no revoke/terminate/delete, quota held, op may close; restart retains hourly verification; |
| + next successful matching GET => ready and conditional drain clear, never terminate. |
| +TestManagedPublishDeadline/unpublished_window: PUT fails; GET proves absent at the deadline => |
| + failed normal cleanup, token revoked and termination attempted; quota held until terminated. |
| +TestManagedPublishDeadline/mismatch: present mismatched object => publishing with uncertain reason; |
| + never overwrite, revoke or terminate; hourly verification after deadline survives closure/restart. |
| ``` |
| - [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadiness|TestManagedJoiningPlacement|TestManagedPublishDeadline' -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. |
| +Persist ObservedVersion alongside checks when either changes; persist publication reason/schedule through the store CAS. Otherwise persist changes only when the check result changes, avoiding repeated SQLite progress writes with identical content. |
| 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.** |
| @@ -696,11 +713,13 @@ COPY: check descriptions and stale/version/owner explanations, including "waitin |
| - `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. |
| +- Extend fleetShowOperation and its CLI mirror with `Plan *fleetShowPlan`, JSON `plan`; `type fleetShowPlan struct { Region, Size, InstanceType string; Boxes int }`, lower snake case. Derive the frozen region/size/type/count from retained reservations and requested metadata, never current config; no network/image/credential fields. A preparing zero-box op retains region/size/count and omits instance_type until allocation freezes it. |
| +- New preview handler `handleAPIManagedFleetPlan(w http.ResponseWriter, r *http.Request)`; request has name/kind/region/size/boxes and request_id where available, 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,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. |
| +Before current-config resolution, preview checks the authenticated account/request-ID alias where supplied, then a matching owned open op, and returns its frozen summary. Payload conflicts are refused; disabled config or removed size cannot block a matching join/replay. |
| 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. |
| @@ -711,9 +730,9 @@ Managed doors refuse BYO fleets; add-box/rotate-token/detach-box refuse managed |
| 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. |
| -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. |
| +Create/add persist synchronously and return 202 with a durable operation; neither waits for cloud calls. Add after failed preparation returns the zero-box open op (Tasks 4–5); its worker prepares, then quota-checks/allocates atomically. |
| +Add the managed view deferred from Task 1 using Fleet.Managed and ManagedFleet: render ObservedVersion from SQL and enrolled-not-ready as joining despite its drain mark. 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. |
| +Uncertain publishing remains visible in SQL-only show even after op closure; it retains quota and hourly verification. 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. |
| @@ -732,11 +751,18 @@ TestManagedAPIPreview: rendered region/size/type/N precedes POST; preview never |
| 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; |
| - create bypasses name-taken/claim and add bypasses fresh preparation/config checks on this lookup. |
| + create bypasses name-taken/claim and add bypasses fresh preparation/config checks on this lookup; |
| + a second invocation joined with a new ID also replays the same op after closure. |
| TestManagedAPIGuards: managed detach/add-box/rotate-token refused at API/page; tags and ready drains permitted; |
| joining-box member drain => 409 (COPY), no mutation; invalid request_id => 400 before claim/reservation. |
| TestManagedCLIFollow: polls every 2s; interrupted CLI => operation continues; |
| show reattaches after client restart; done-with-failures preserves successful boxes. |
| +TestManagedCLIJoinRemovedConfig: preview joins owned open create/add after disable or size removal; |
| + lost POST retries directly with the same ID, without preview, even after completion. |
| +TestManagedAPIAddPreparation: failed fleet preparation => 202 with durable zero-box op and no cloud calls; |
| + worker prepares then atomically allocates; failure remains visible to the owner. |
| +TestManagedAPIShow: SQL-only managed states/checks/ObservedVersion, joining drain projection and preparation failure; |
| + foreign and absent responses identical; uncertain publishing visible after closure. |
| TestManagedCLISelectors: account/console selectors and exact sqid survive every poll; |
| subprocess uses carlosTestEnv and scratch cwd, never real credentials/config. |
| ``` |
| @@ -745,8 +771,8 @@ TestManagedCLISelectors: account/console selectors and exact sqid survive every |
| - [ ] **Step 3: Implement API and CLI orchestration.** |
| Do not expose compute.Find/ConsoleOutput through show; the worker persists the evidence the view needs. |
| -On interrupted POST response, retry with the same request_id; return the original op even if it has already completed. A retry must reach this lookup before name claim/name-taken checks or preview/config/preparation failure can block it. |
| -Include documentation headings for managed create, show and boxes add, with COPY-reviewed examples and partial-failure behavior. |
| +On interrupted POST response, retry POST directly with the same request_id without repeating preview; return the original op even if it has already completed. A retry must reach this lookup before name claim/name-taken checks or preview/config/preparation failure can block it. |
| +Include documentation headings for managed create, show and boxes add, with COPY-marked examples for controller review 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. |
| @@ -795,37 +821,40 @@ TestManagedOpenBudget: calls concern only active reservations; ready/terminated |
| 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. |
| +TestFleetShowNoProviderCalls: real show/render => all five compute method counts zero. |
| +TestManagedFleetCredentialsIntegration: multiple real one-time enrolments reuse the sealed current key with no provider minting. |
| 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|TestManagedFollowStoreBudget|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|TestFleetShowNoProviderCalls|TestManagedFleetCredentialsIntegration' -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. |
| -Assert hourly cleanup remains visible and counted after op closure; no pre-dispatch crash uncertainty remains with deterministic enrolment tokens. |
| +Assert hourly cleanup and uncertain publication remain 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.** |
| -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 `GOFLAGS=-buildvcs=false go test -race . ./cmd/console ./internal/compute ./internal/fleetstore ./internal/console ./internal/registry ./internal/release -run 'TestManaged|TestFake|TestFleetStorageFake|TestFleetCredentialsDoubleLostRotation|TestSystem|TestFleetShow|TestFleetsShowCLI|TestChange|TestBumpChangeIndex|TestReadChangeIndex|Test.*Startup|Test.*Worker|Test.*Fleet|Test.*Jobs' -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. |
| +Run `make census-card`; write per-unit CLAIMS, then `make census-propose NAME=<branch> CLAIMS=<owned-file>` and report the proposal to the controller for independent approval and recording on #280; implementers do not post there. |
| 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. |
| +The controller obtains 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. |
| +Implementers list all introduced COPY strings and docs paragraphs; the controller finishes copy review before merge. Implementers do not run copy review. |
| -- [ ] **Step 5: Commit, describe, push and land the completed 2a branch through amadan.** |
| +- [ ] **Step 5: Commit and report the completed local work to the controller.** |
| Subject: `test: prove managed fleet recovery and request budgets`. |
| +Implementers stop at green local checks, commit, census proposal and report; no subagents, #280 posts, push, CI or merge. The controller owns the following landing steps. |
| 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. |
| +Merge with `amadan branch merge carlos/platform <branch> -squash -expect <full-tip> -message <short-subject-and-body>` only after green CI, required review and Paul's go. |
| 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. |
| +Controller finish line: reviewed 2a core merged, fake acceptance green, production switch false, 2b readiness/adapter gaps explicitly recorded. |
| ## Self-review |
| @@ -937,7 +966,26 @@ Newly cited ready-object store, store-door read/write ACL, serial announcement/p |
| Round 3: controller-supplied findings and fix4-brief.md rulings applied locally; no further review round. |
| - P2-1 — Delivered-key preservation: persist non-secret delivered_key_id, carry ID and Secret in Credentials, and pass keep to every rotation; reap unsealed orphans without reaping the delivered key. TestFleetCredentialsDoubleLostRotation covers two consecutive losses before sealing. |
| -- P2-2 — Bounded publication: enrolled → publishing → ready; write and verify before ready and conditional drain clear. Publishing retains the 20-minute launch deadline; deadline or object mismatch fails into normal cleanup with quota held until termination. TestManagedPublishDeadline covers both failures and restart recovery. |
| +- P2-2 — Bounded publication: enrolled → publishing → ready; write and verify before ready and conditional drain clear. The deadline/mismatch cleanup ruling is superseded by pre-flight C08 below; TestManagedPublishDeadline covers authorization uncertainty and proven-unpublished cleanup. |
| - P3 — Token revocation refuses new connections; an existing tunnel lasts until termination. |
| Review closed after round 3 (three-round limit); remaining P3s none open. |
| + |
| +### Pre-flight (build) rulings |
| + |
| +Controller rulings applied without a new review round; rounds 1–3 remain closed. |
| + |
| +- C01 — Keep Task 1 BYO-only; move managed views to Task 9 and provider integration to Task 10; define token derivation in Task 4. |
| +- C02 — Resolve immutable config/generation snapshots with a pure function after label allocation; pass deployment explicitly. |
| +- C03 — Persist op region/size/preparation start and box ready time/observed version with scan/write contracts. |
| +- C04 — Persist every joined request ID and validated payload in account-scoped aliases. |
| +- C05 — Return 202 for a durable zero-box add op; worker prepares then atomically quota-checks/allocates; exclude preparing ops from completion. |
| +- C06 — Assign conditional deletion, owned bucket updates, consoleRegistry, remote tests and census to Task 5. |
| +- C07 — Name the Task 6 case TestManagedFrozenLaunchRetryAcrossConfigChange. |
| +- C08 — Create-only PUT then GET; absent is proven unpublished, matching present is published and becomes ready without termination; only proven unpublished at 20 minutes fails into cleanup; uncertainty/mismatch stays publishing with durable uncertain reason in show, quota held, no revoke/terminate, hourly verification after deadline and op closure allowed; test both publication windows. |
| +- C09 — Add a safe frozen region/size/type/count projection to operation replies and CLI; compare actual reply with preview. |
| +- C10 — Preview looks up request aliases and matching owned open ops before config; ambiguous POST retries directly with the same ID. |
| +- C11 — GeneratedAt zero or more than two minutes ahead is pending; retain BoxStale for age and test boundaries. |
| +- C12 — Expand the one final race run to all touched packages and explicit rotation/system/show/change-index/startup patterns. |
| +- C13 — Implementers mark/list COPY strings without running copy review; controller reviews before merge. |
| +- C14 — Implementers end at local checks, commit, census proposal and report; controller owns review/#280/push/CI/landing on Paul's go. |